[lld] 3b7c3a6 - Revert "Don't use Optional::hasValue (NFC)"

Kazu Hirata via llvm-commits llvm-commits at lists.llvm.org
Sat Jun 25 11:57:04 PDT 2022


Author: Kazu Hirata
Date: 2022-06-25T11:56:50-07:00
New Revision: 3b7c3a654c9175f41ac871a937cbcae73dfb3c5d

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

LOG: Revert "Don't use Optional::hasValue (NFC)"

This reverts commit aa8feeefd3ac6c78ee8f67bf033976fc7d68bc6d.

Added: 
    

Modified: 
    clang-tools-extra/clang-doc/HTMLGenerator.cpp
    clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
    clang-tools-extra/clangd/ClangdLSPServer.cpp
    clang-tools-extra/clangd/ClangdServer.cpp
    clang-tools-extra/clangd/CodeComplete.cpp
    clang-tools-extra/clangd/ConfigCompile.cpp
    clang-tools-extra/clangd/FeatureModule.cpp
    clang-tools-extra/clangd/index/YAMLSerialization.cpp
    clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
    clang-tools-extra/clangd/unittests/FSTests.cpp
    clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
    clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
    clang-tools-extra/clangd/unittests/LSPBinderTests.cpp
    clang-tools-extra/clangd/unittests/TidyProviderTests.cpp
    clang-tools-extra/pseudo/lib/GLR.cpp
    clang-tools-extra/unittests/clang-doc/ClangDocTest.cpp
    clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
    clang-tools-extra/unittests/clang-tidy/NamespaceAliaserTest.cpp
    clang-tools-extra/unittests/clang-tidy/OptionsProviderTest.cpp
    clang-tools-extra/unittests/clang-tidy/UsingInserterTest.cpp
    clang/include/clang/APINotes/Types.h
    clang/include/clang/AST/PropertiesBase.td
    clang/include/clang/Analysis/PathDiagnostic.h
    clang/include/clang/Sema/Sema.h
    clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
    clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
    clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
    clang/include/clang/Support/RISCVVIntrinsicUtils.h
    clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
    clang/lib/AST/AttrImpl.cpp
    clang/lib/ASTMatchers/Dynamic/Parser.cpp
    clang/lib/ASTMatchers/Dynamic/Registry.cpp
    clang/lib/Analysis/BodyFarm.cpp
    clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
    clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
    clang/lib/Analysis/PathDiagnostic.cpp
    clang/lib/Analysis/UninitializedValues.cpp
    clang/lib/Basic/Targets/RISCV.cpp
    clang/lib/CodeGen/CGClass.cpp
    clang/lib/CodeGen/CodeGenModule.cpp
    clang/lib/Driver/Driver.cpp
    clang/lib/Driver/ToolChains/AVR.cpp
    clang/lib/Driver/ToolChains/Clang.cpp
    clang/lib/Driver/ToolChains/Gnu.cpp
    clang/lib/Driver/ToolChains/Hexagon.cpp
    clang/lib/Edit/RewriteObjCFoundationAPI.cpp
    clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
    clang/lib/Frontend/CompilerInstance.cpp
    clang/lib/Frontend/CompilerInvocation.cpp
    clang/lib/Frontend/InitPreprocessor.cpp
    clang/lib/Lex/DependencyDirectivesScanner.cpp
    clang/lib/Lex/MacroInfo.cpp
    clang/lib/Lex/ModuleMap.cpp
    clang/lib/Lex/PPMacroExpansion.cpp
    clang/lib/Lex/PreprocessingRecord.cpp
    clang/lib/Parse/ParseOpenMP.cpp
    clang/lib/Sema/SemaCUDA.cpp
    clang/lib/Sema/SemaChecking.cpp
    clang/lib/Sema/SemaCodeComplete.cpp
    clang/lib/Sema/SemaDecl.cpp
    clang/lib/Sema/SemaDeclAttr.cpp
    clang/lib/Sema/SemaExprCXX.cpp
    clang/lib/Sema/SemaOpenMP.cpp
    clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
    clang/lib/Serialization/ASTWriter.cpp
    clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
    clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp
    clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
    clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
    clang/lib/StaticAnalyzer/Core/BugReporter.cpp
    clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
    clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
    clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
    clang/lib/Support/RISCVVIntrinsicUtils.cpp
    clang/lib/Tooling/Core/Replacement.cpp
    clang/tools/driver/driver.cpp
    clang/tools/libclang/CIndex.cpp
    clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
    clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
    clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
    clang/unittests/Analysis/MacroExpansionContextTest.cpp
    clang/unittests/Basic/DarwinSDKInfoTest.cpp
    clang/unittests/DirectoryWatcher/DirectoryWatcherTest.cpp
    clang/unittests/Lex/HeaderSearchTest.cpp
    clang/unittests/StaticAnalyzer/SValTest.cpp
    clang/unittests/Tooling/RefactoringTest.cpp
    clang/utils/TableGen/RISCVVEmitter.cpp
    flang/include/flang/Lower/IterationSpace.h
    flang/lib/Lower/Bridge.cpp
    flang/lib/Lower/ConvertExpr.cpp
    flang/lib/Lower/CustomIntrinsicCall.cpp
    flang/lib/Lower/IterationSpace.cpp
    flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp
    flang/lib/Optimizer/CodeGen/CodeGen.cpp
    flang/lib/Optimizer/CodeGen/TargetRewrite.cpp
    flang/lib/Optimizer/Dialect/FIROps.cpp
    flang/lib/Optimizer/Dialect/FIRType.cpp
    flang/lib/Optimizer/Support/InternalNames.cpp
    flang/lib/Optimizer/Transforms/AbstractResult.cpp
    flang/lib/Optimizer/Transforms/AffinePromotion.cpp
    flang/lib/Optimizer/Transforms/ExternalNameConversion.cpp
    flang/unittests/Optimizer/Builder/FIRBuilderTest.cpp
    flang/unittests/Optimizer/Builder/Runtime/RuntimeCallTestBase.h
    lld/ELF/InputFiles.cpp
    lld/MachO/SectionPriorities.cpp
    lld/wasm/InputChunks.h
    lld/wasm/InputElement.h
    lld/wasm/Writer.cpp
    lldb/include/lldb/Target/MemoryRegionInfo.h
    lldb/source/API/SBMemoryRegionInfo.cpp
    lldb/source/Breakpoint/BreakpointIDList.cpp
    lldb/source/Commands/CommandObjectFrame.cpp
    lldb/source/Commands/CommandObjectMemory.cpp
    lldb/source/Core/DataFileCache.cpp
    lldb/source/Core/DumpDataExtractor.cpp
    lldb/source/Core/ValueObjectChild.cpp
    lldb/source/Host/common/File.cpp
    lldb/source/Host/common/Terminal.cpp
    lldb/source/Plugins/ABI/X86/ABIX86.cpp
    lldb/source/Plugins/Disassembler/LLVMC/DisassemblerLLVMC.cpp
    lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
    lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.cpp
    lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp
    lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp
    lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.cpp
    lldb/source/Target/Thread.cpp
    lldb/source/Target/UnixSignals.cpp
    lldb/source/Utility/SelectHelper.cpp
    lldb/unittests/Host/ConnectionFileDescriptorTest.cpp
    lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp
    lldb/unittests/Process/minidump/MinidumpParserTest.cpp
    lldb/unittests/Target/FindFileTest.cpp
    lldb/unittests/Utility/StringExtractorGDBRemoteTest.cpp
    lldb/unittests/tools/lldb-server/tests/TestClient.cpp
    llvm/include/llvm/ADT/Optional.h
    llvm/include/llvm/Analysis/BlockFrequencyInfoImpl.h
    llvm/include/llvm/Analysis/VectorUtils.h
    llvm/include/llvm/Bitstream/BitstreamWriter.h
    llvm/include/llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h
    llvm/include/llvm/DebugInfo/GSYM/FunctionInfo.h
    llvm/include/llvm/IR/IRBuilder.h
    llvm/include/llvm/MC/MCDwarf.h
    llvm/include/llvm/MC/MCSectionXCOFF.h
    llvm/include/llvm/MC/MCSymbolWasm.h
    llvm/include/llvm/MC/MCSymbolXCOFF.h
    llvm/include/llvm/ObjectYAML/ELFYAML.h
    llvm/include/llvm/Support/Casting.h
    llvm/include/llvm/Support/Error.h
    llvm/include/llvm/Support/YAMLTraits.h
    llvm/include/llvm/Transforms/IPO/Attributor.h
    llvm/lib/Analysis/BranchProbabilityInfo.cpp
    llvm/lib/Analysis/CFLAndersAliasAnalysis.cpp
    llvm/lib/Analysis/CFLSteensAliasAnalysis.cpp
    llvm/lib/Analysis/IRSimilarityIdentifier.cpp
    llvm/lib/Analysis/InlineCost.cpp
    llvm/lib/Analysis/InstructionSimplify.cpp
    llvm/lib/Analysis/LazyValueInfo.cpp
    llvm/lib/Analysis/LoopCacheAnalysis.cpp
    llvm/lib/Analysis/MemoryBuiltins.cpp
    llvm/lib/Analysis/MemorySSA.cpp
    llvm/lib/Analysis/MustExecute.cpp
    llvm/lib/Analysis/ProfileSummaryInfo.cpp
    llvm/lib/Analysis/ScalarEvolution.cpp
    llvm/lib/Analysis/StratifiedSets.h
    llvm/lib/Analysis/VectorUtils.cpp
    llvm/lib/CodeGen/BasicBlockSections.cpp
    llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp
    llvm/lib/CodeGen/MIRParser/MIParser.cpp
    llvm/lib/CodeGen/MachineBasicBlock.cpp
    llvm/lib/CodeGen/MachineFunctionSplitter.cpp
    llvm/lib/CodeGen/ModuloSchedule.cpp
    llvm/lib/CodeGen/SelectOptimize.cpp
    llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
    llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
    llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp
    llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
    llvm/lib/DebugInfo/CodeView/CodeViewRecordIO.cpp
    llvm/lib/DebugInfo/CodeView/TypeRecordMapping.cpp
    llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
    llvm/lib/DebugInfo/DWARF/DWARFDebugLine.cpp
    llvm/lib/DebugInfo/PDB/Native/DbiStreamBuilder.cpp
    llvm/lib/Frontend/OpenMP/OMPContext.cpp
    llvm/lib/IR/Instructions.cpp
    llvm/lib/IR/IntrinsicInst.cpp
    llvm/lib/IR/LLVMContextImpl.cpp
    llvm/lib/IR/VectorBuilder.cpp
    llvm/lib/IR/Verifier.cpp
    llvm/lib/InterfaceStub/IFSHandler.cpp
    llvm/lib/MC/MCContext.cpp
    llvm/lib/MC/MCDisassembler/MCDisassembler.cpp
    llvm/lib/MC/MCParser/MasmParser.cpp
    llvm/lib/MC/MCSchedule.cpp
    llvm/lib/MC/MCSectionXCOFF.cpp
    llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp
    llvm/lib/Object/ELFObjectFile.cpp
    llvm/lib/ObjectYAML/DXContainerEmitter.cpp
    llvm/lib/Support/Process.cpp
    llvm/lib/Support/VirtualFileSystem.cpp
    llvm/lib/Support/raw_ostream.cpp
    llvm/lib/TableGen/Record.cpp
    llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp
    llvm/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.h
    llvm/lib/Target/AMDGPU/SIMemoryLegalizer.cpp
    llvm/lib/Target/ARM/MVEGatherScatterLowering.cpp
    llvm/lib/Target/Hexagon/HexagonFrameLowering.cpp
    llvm/lib/Target/Lanai/AsmParser/LanaiAsmParser.cpp
    llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp
    llvm/lib/Target/PowerPC/PPCMacroFusion.cpp
    llvm/lib/Target/PowerPC/PPCTargetMachine.cpp
    llvm/lib/Target/VE/VVPISelLowering.cpp
    llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.cpp
    llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp
    llvm/lib/Transforms/IPO/Attributor.cpp
    llvm/lib/Transforms/IPO/AttributorAttributes.cpp
    llvm/lib/Transforms/IPO/IROutliner.cpp
    llvm/lib/Transforms/IPO/OpenMPOpt.cpp
    llvm/lib/Transforms/IPO/SampleContextTracker.cpp
    llvm/lib/Transforms/IPO/SampleProfile.cpp
    llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
    llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
    llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp
    llvm/lib/Transforms/Scalar/ConstantHoisting.cpp
    llvm/lib/Transforms/Scalar/GVN.cpp
    llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp
    llvm/lib/Transforms/Scalar/LoopDistribute.cpp
    llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp
    llvm/lib/Transforms/Scalar/LoopRotation.cpp
    llvm/lib/Transforms/Scalar/LoopSimplifyCFG.cpp
    llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp
    llvm/lib/Transforms/Scalar/LoopUnrollAndJamPass.cpp
    llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp
    llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp
    llvm/lib/Transforms/Utils/CodeExtractor.cpp
    llvm/lib/Transforms/Utils/LoopPeel.cpp
    llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp
    llvm/lib/Transforms/Utils/LoopUtils.cpp
    llvm/lib/Transforms/Utils/MisExpect.cpp
    llvm/lib/Transforms/Utils/ModuleUtils.cpp
    llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
    llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
    llvm/lib/WindowsDriver/MSVCPaths.cpp
    llvm/tools/lli/lli.cpp
    llvm/tools/llvm-cov/CoverageExporterJson.cpp
    llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp
    llvm/tools/llvm-exegesis/lib/MCInstrDescView.cpp
    llvm/tools/llvm-ifs/llvm-ifs.cpp
    llvm/tools/llvm-mca/Views/InstructionInfoView.cpp
    llvm/tools/llvm-objdump/XCOFFDump.cpp
    llvm/tools/llvm-objdump/llvm-objdump.cpp
    llvm/tools/llvm-profdata/llvm-profdata.cpp
    llvm/tools/llvm-profgen/ProfiledBinary.cpp
    llvm/tools/llvm-sim/llvm-sim.cpp
    llvm/tools/obj2yaml/dwarf2yaml.cpp
    llvm/tools/obj2yaml/dxcontainer2yaml.cpp
    llvm/unittests/ADT/OptionalTest.cpp
    llvm/unittests/ADT/StatisticTest.cpp
    llvm/unittests/Analysis/BlockFrequencyInfoTest.cpp
    llvm/unittests/Analysis/IRSimilarityIdentifierTest.cpp
    llvm/unittests/Analysis/MemorySSATest.cpp
    llvm/unittests/Analysis/VectorFunctionABITest.cpp
    llvm/unittests/BinaryFormat/DwarfTest.cpp
    llvm/unittests/CodeGen/GlobalISel/ConstantFoldingTest.cpp
    llvm/unittests/DebugInfo/DWARF/DWARFDebugFrameTest.cpp
    llvm/unittests/DebugInfo/DWARF/DWARFDebugInfoTest.cpp
    llvm/unittests/DebugInfo/DWARF/DWARFFormValueTest.cpp
    llvm/unittests/DebugInfo/GSYM/GSYMTest.cpp
    llvm/unittests/FileCheck/FileCheckTest.cpp
    llvm/unittests/IR/MetadataTest.cpp
    llvm/unittests/IR/VPIntrinsicTest.cpp
    llvm/unittests/InterfaceStub/ELFYAMLTest.cpp
    llvm/unittests/Object/XCOFFObjectFileTest.cpp
    llvm/unittests/ObjectYAML/DWARFYAMLTest.cpp
    llvm/unittests/ProfileData/MemProfTest.cpp
    llvm/unittests/Support/AlignmentTest.cpp
    llvm/unittests/Support/Casting.cpp
    llvm/unittests/Support/KnownBitsTest.cpp
    llvm/unittests/Support/YAMLParserTest.cpp
    llvm/unittests/TableGen/ParserEntryPointTest.cpp
    llvm/utils/TableGen/GlobalISel/GIMatchTree.h
    llvm/utils/TableGen/GlobalISelEmitter.cpp
    mlir/include/mlir/Dialect/Affine/Analysis/AffineStructures.h
    mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
    mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td
    mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h
    mlir/include/mlir/IR/OpDefinition.h
    mlir/include/mlir/IR/OpImplementation.h
    mlir/include/mlir/Support/LogicalResult.h
    mlir/include/mlir/TableGen/Operator.h
    mlir/include/mlir/Transforms/DialectConversion.h
    mlir/lib/Analysis/Presburger/IntegerRelation.cpp
    mlir/lib/Conversion/SPIRVToLLVM/SPIRVToLLVM.cpp
    mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp
    mlir/lib/Conversion/TosaToLinalg/TosaToLinalgNamed.cpp
    mlir/lib/Conversion/VectorToSCF/VectorToSCF.cpp
    mlir/lib/Dialect/Affine/Analysis/AffineStructures.cpp
    mlir/lib/Dialect/Affine/Analysis/LoopAnalysis.cpp
    mlir/lib/Dialect/Affine/Analysis/Utils.cpp
    mlir/lib/Dialect/Affine/IR/AffineOps.cpp
    mlir/lib/Dialect/Affine/Transforms/AffineDataCopyGeneration.cpp
    mlir/lib/Dialect/Affine/Transforms/LoopFusion.cpp
    mlir/lib/Dialect/Affine/Utils/LoopUtils.cpp
    mlir/lib/Dialect/Affine/Utils/Utils.cpp
    mlir/lib/Dialect/Arithmetic/Transforms/UnsignedWhenEquivalent.cpp
    mlir/lib/Dialect/Bufferization/IR/BufferizationOps.cpp
    mlir/lib/Dialect/Bufferization/Transforms/BufferUtils.cpp
    mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp
    mlir/lib/Dialect/DLTI/DLTI.cpp
    mlir/lib/Dialect/EmitC/IR/EmitC.cpp
    mlir/lib/Dialect/GPU/Transforms/SerializeToBlob.cpp
    mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
    mlir/lib/Dialect/LLVMIR/IR/LLVMTypeSyntax.cpp
    mlir/lib/Dialect/LLVMIR/IR/NVVMDialect.cpp
    mlir/lib/Dialect/Linalg/Transforms/Fusion.cpp
    mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp
    mlir/lib/Dialect/Linalg/Transforms/Transforms.cpp
    mlir/lib/Dialect/MemRef/IR/MemRefOps.cpp
    mlir/lib/Dialect/OpenACC/IR/OpenACC.cpp
    mlir/lib/Dialect/PDL/IR/PDLTypes.cpp
    mlir/lib/Dialect/Quant/IR/TypeParser.cpp
    mlir/lib/Dialect/SCF/IR/SCF.cpp
    mlir/lib/Dialect/SCF/Transforms/TileUsingInterface.cpp
    mlir/lib/Dialect/SCF/Utils/AffineCanonicalizationUtils.cpp
    mlir/lib/Dialect/SPIRV/IR/SPIRVAttributes.cpp
    mlir/lib/Dialect/SPIRV/IR/SPIRVCanonicalization.cpp
    mlir/lib/Dialect/SPIRV/IR/SPIRVDialect.cpp
    mlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp
    mlir/lib/Dialect/SPIRV/Transforms/LowerABIAttributesPass.cpp
    mlir/lib/Dialect/Shape/IR/Shape.cpp
    mlir/lib/Dialect/SparseTensor/Transforms/Sparsification.cpp
    mlir/lib/Dialect/SparseTensor/Utils/Merger.cpp
    mlir/lib/Dialect/Tensor/Transforms/SwapExtractSliceWithProducer.cpp
    mlir/lib/Dialect/Tosa/Transforms/TosaDecomposeTransposeConv.cpp
    mlir/lib/Dialect/Transform/IR/TransformOps.cpp
    mlir/lib/Dialect/Utils/ReshapeOpsUtils.cpp
    mlir/lib/Dialect/Vector/IR/VectorOps.cpp
    mlir/lib/Dialect/Vector/Transforms/VectorTransferPermutationMapRewritePatterns.cpp
    mlir/lib/Dialect/Vector/Transforms/VectorTransforms.cpp
    mlir/lib/IR/FunctionImplementation.cpp
    mlir/lib/Interfaces/ControlFlowInterfaces.cpp
    mlir/lib/Interfaces/ViewLikeInterface.cpp
    mlir/lib/Parser/AffineParser.cpp
    mlir/lib/Parser/AttributeParser.cpp
    mlir/lib/Parser/LocationParser.cpp
    mlir/lib/Parser/Parser.cpp
    mlir/lib/Parser/TypeParser.cpp
    mlir/lib/Target/LLVMIR/ConvertFromLLVMIR.cpp
    mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
    mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
    mlir/lib/Target/SPIRV/Deserialization/Deserializer.cpp
    mlir/test/lib/Analysis/TestMemRefDependenceCheck.cpp
    mlir/test/lib/Dialect/Test/TestDialect.cpp
    mlir/test/lib/Dialect/Test/TestTypeDefs.td
    mlir/test/lib/Dialect/Test/TestTypes.cpp
    mlir/test/lib/Dialect/Test/TestTypes.h
    mlir/test/lib/Dialect/Transform/TestTransformDialectExtension.cpp
    mlir/test/lib/Transforms/TestIntRangeInference.cpp
    mlir/test/mlir-tblgen/default-type-attr-print-parser.td
    mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-yaml-gen.cpp
    mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
    mlir/tools/mlir-tblgen/OpFormatGen.cpp
    mlir/unittests/Analysis/Presburger/IntegerPolyhedronTest.cpp
    mlir/unittests/Analysis/Presburger/PWMAFunctionTest.cpp
    mlir/unittests/Analysis/Presburger/PresburgerSetTest.cpp
    mlir/unittests/Analysis/Presburger/SimplexTest.cpp
    mlir/unittests/IR/OperationSupportTest.cpp
    mlir/unittests/Interfaces/ControlFlowInterfacesTest.cpp
    mlir/unittests/Pass/AnalysisManagerTest.cpp
    polly/lib/Exchange/JSONExporter.cpp
    polly/lib/Transform/ManualOptimizer.cpp
    polly/lib/Transform/MatmulOptimizer.cpp

Removed: 
    


################################################################################
diff  --git a/clang-tools-extra/clang-doc/HTMLGenerator.cpp b/clang-tools-extra/clang-doc/HTMLGenerator.cpp
index 12c07ac1c1334..3e5a5331b7906 100644
--- a/clang-tools-extra/clang-doc/HTMLGenerator.cpp
+++ b/clang-tools-extra/clang-doc/HTMLGenerator.cpp
@@ -653,10 +653,10 @@ genHTML(const EnumInfo &I, const ClangDocContext &CDCtx) {
 
   if (I.DefLoc) {
     if (!CDCtx.RepositoryUrl)
-      Out.emplace_back(writeFileDefinition(*I.DefLoc));
+      Out.emplace_back(writeFileDefinition(I.DefLoc.getValue()));
     else
-      Out.emplace_back(
-          writeFileDefinition(*I.DefLoc, StringRef{*CDCtx.RepositoryUrl}));
+      Out.emplace_back(writeFileDefinition(
+          I.DefLoc.getValue(), StringRef{CDCtx.RepositoryUrl.getValue()}));
   }
 
   std::string Description;
@@ -702,10 +702,10 @@ genHTML(const FunctionInfo &I, const ClangDocContext &CDCtx,
 
   if (I.DefLoc) {
     if (!CDCtx.RepositoryUrl)
-      Out.emplace_back(writeFileDefinition(*I.DefLoc));
+      Out.emplace_back(writeFileDefinition(I.DefLoc.getValue()));
     else
-      Out.emplace_back(
-          writeFileDefinition(*I.DefLoc, StringRef{*CDCtx.RepositoryUrl}));
+      Out.emplace_back(writeFileDefinition(
+          I.DefLoc.getValue(), StringRef{CDCtx.RepositoryUrl.getValue()}));
   }
 
   std::string Description;
@@ -768,10 +768,10 @@ genHTML(const RecordInfo &I, Index &InfoIndex, const ClangDocContext &CDCtx,
 
   if (I.DefLoc) {
     if (!CDCtx.RepositoryUrl)
-      Out.emplace_back(writeFileDefinition(*I.DefLoc));
+      Out.emplace_back(writeFileDefinition(I.DefLoc.getValue()));
     else
-      Out.emplace_back(
-          writeFileDefinition(*I.DefLoc, StringRef{*CDCtx.RepositoryUrl}));
+      Out.emplace_back(writeFileDefinition(
+          I.DefLoc.getValue(), StringRef{CDCtx.RepositoryUrl.getValue()}));
   }
 
   std::string Description;

diff  --git a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
index 418b749720686..1efd88d7cbb95 100644
--- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
@@ -817,8 +817,8 @@ void NotNullTerminatedResultCheck::check(
       ++It;
     }
 
-    if (AreSafeFunctionsWanted)
-      UseSafeFunctions = *AreSafeFunctionsWanted;
+    if (AreSafeFunctionsWanted.hasValue())
+      UseSafeFunctions = AreSafeFunctionsWanted.getValue();
   }
 
   StringRef Name = FunctionExpr->getDirectCallee()->getName();

diff  --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index 4a26b5ae804d4..3bade14f86b91 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -663,9 +663,9 @@ void ClangdLSPServer::onDocumentDidOpen(
 void ClangdLSPServer::onDocumentDidChange(
     const DidChangeTextDocumentParams &Params) {
   auto WantDiags = WantDiagnostics::Auto;
-  if (Params.wantDiagnostics)
-    WantDiags =
-        *Params.wantDiagnostics ? WantDiagnostics::Yes : WantDiagnostics::No;
+  if (Params.wantDiagnostics.hasValue())
+    WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
+                                                  : WantDiagnostics::No;
 
   PathRef File = Params.textDocument.uri.file();
   auto Code = Server->getDraft(File);

diff  --git a/clang-tools-extra/clangd/ClangdServer.cpp b/clang-tools-extra/clangd/ClangdServer.cpp
index 1fe63c1f0b25f..fa6c70b4acbc4 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -411,9 +411,10 @@ void ClangdServer::codeComplete(PathRef File, Position Pos,
       clang::clangd::trace::Span Tracer("Completion results callback");
       CB(std::move(Result));
     }
-    if (SpecFuzzyFind && SpecFuzzyFind->NewReq) {
+    if (SpecFuzzyFind && SpecFuzzyFind->NewReq.hasValue()) {
       std::lock_guard<std::mutex> Lock(CachedCompletionFuzzyFindRequestMutex);
-      CachedCompletionFuzzyFindRequestByFile[File] = *SpecFuzzyFind->NewReq;
+      CachedCompletionFuzzyFindRequestByFile[File] =
+          SpecFuzzyFind->NewReq.getValue();
     }
     // SpecFuzzyFind is only destroyed after speculative fuzzy find finishes.
     // We don't want `codeComplete` to wait for the async call if it doesn't use

diff  --git a/clang-tools-extra/clangd/CodeComplete.cpp b/clang-tools-extra/clangd/CodeComplete.cpp
index d17a14bfaf2e7..fbd7488c07d21 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -391,9 +391,11 @@ struct CodeCompletionBuilder {
             ToInclude.takeError());
     }
     // Prefer includes that do not need edits (i.e. already exist).
-    std::stable_partition(
-        Completion.Includes.begin(), Completion.Includes.end(),
-        [](const CodeCompletion::IncludeCandidate &I) { return !I.Insertion; });
+    std::stable_partition(Completion.Includes.begin(),
+                          Completion.Includes.end(),
+                          [](const CodeCompletion::IncludeCandidate &I) {
+                            return !I.Insertion.hasValue();
+                          });
   }
 
   void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) {

diff  --git a/clang-tools-extra/clangd/ConfigCompile.cpp b/clang-tools-extra/clangd/ConfigCompile.cpp
index 8f207aba29bf4..2de8816f9f084 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -358,8 +358,8 @@ struct FragmentCompiler {
     }
 #endif
     // Make sure exactly one of the Sources is set.
-    unsigned SourceCount = External.File.has_value() +
-                           External.Server.has_value() + *External.IsNone;
+    unsigned SourceCount = External.File.hasValue() +
+                           External.Server.hasValue() + *External.IsNone;
     if (SourceCount != 1) {
       diag(Error, "Exactly one of File, Server or None must be set.",
            BlockRange);

diff  --git a/clang-tools-extra/clangd/FeatureModule.cpp b/clang-tools-extra/clangd/FeatureModule.cpp
index 872cea1443789..85977aadd6e32 100644
--- a/clang-tools-extra/clangd/FeatureModule.cpp
+++ b/clang-tools-extra/clangd/FeatureModule.cpp
@@ -13,12 +13,12 @@ namespace clang {
 namespace clangd {
 
 void FeatureModule::initialize(const Facilities &F) {
-  assert(!Fac && "Initialized twice");
+  assert(!Fac.hasValue() && "Initialized twice");
   Fac.emplace(F);
 }
 
 FeatureModule::Facilities &FeatureModule::facilities() {
-  assert(Fac && "Not initialized yet");
+  assert(Fac.hasValue() && "Not initialized yet");
   return *Fac;
 }
 

diff  --git a/clang-tools-extra/clangd/index/YAMLSerialization.cpp b/clang-tools-extra/clangd/index/YAMLSerialization.cpp
index 1ac74338298a8..79c9e1dfd9918 100644
--- a/clang-tools-extra/clangd/index/YAMLSerialization.cpp
+++ b/clang-tools-extra/clangd/index/YAMLSerialization.cpp
@@ -354,23 +354,23 @@ template <> struct MappingTraits<CompileCommandYAML> {
 
 template <> struct MappingTraits<VariantEntry> {
   static void mapping(IO &IO, VariantEntry &Variant) {
-    if (IO.mapTag("!Symbol", Variant.Symbol.has_value())) {
+    if (IO.mapTag("!Symbol", Variant.Symbol.hasValue())) {
       if (!IO.outputting())
         Variant.Symbol.emplace();
       MappingTraits<Symbol>::mapping(IO, *Variant.Symbol);
-    } else if (IO.mapTag("!Refs", Variant.Refs.has_value())) {
+    } else if (IO.mapTag("!Refs", Variant.Refs.hasValue())) {
       if (!IO.outputting())
         Variant.Refs.emplace();
       MappingTraits<RefBundle>::mapping(IO, *Variant.Refs);
-    } else if (IO.mapTag("!Relations", Variant.Relation.has_value())) {
+    } else if (IO.mapTag("!Relations", Variant.Relation.hasValue())) {
       if (!IO.outputting())
         Variant.Relation.emplace();
       MappingTraits<Relation>::mapping(IO, *Variant.Relation);
-    } else if (IO.mapTag("!Source", Variant.Source.has_value())) {
+    } else if (IO.mapTag("!Source", Variant.Source.hasValue())) {
       if (!IO.outputting())
         Variant.Source.emplace();
       MappingTraits<IncludeGraphNode>::mapping(IO, *Variant.Source);
-    } else if (IO.mapTag("!Cmd", Variant.Cmd.has_value())) {
+    } else if (IO.mapTag("!Cmd", Variant.Cmd.hasValue())) {
       if (!IO.outputting())
         Variant.Cmd.emplace();
       MappingTraits<CompileCommandYAML>::mapping(

diff  --git a/clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp b/clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
index 6af1e3bb74111..ddf6f4f5fb1f6 100644
--- a/clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
@@ -82,12 +82,12 @@ CompileFlags: { Add: [foo, bar] }
   EXPECT_THAT(Results[1].CompileFlags.Add, ElementsAre(val("b\naz\n")));
 
   ASSERT_TRUE(Results[2].Index.Background);
-  EXPECT_EQ("Skip", *Results[2].Index.Background.value());
+  EXPECT_EQ("Skip", *Results[2].Index.Background.getValue());
   EXPECT_THAT(Results[3].Diagnostics.ClangTidy.CheckOptions,
               ElementsAre(PairVal("IgnoreMacros", "true"),
                           PairVal("example-check.ExampleOption", "0")));
   EXPECT_TRUE(Results[3].Diagnostics.UnusedIncludes);
-  EXPECT_EQ("Strict", *Results[3].Diagnostics.UnusedIncludes.value());
+  EXPECT_EQ("Strict", *Results[3].Diagnostics.UnusedIncludes.getValue());
 }
 
 TEST(ParseYAML, Locations) {
@@ -163,10 +163,10 @@ TEST(ParseYAML, ExternalBlockNone) {
   ASSERT_THAT(Diags.Diagnostics, IsEmpty());
   ASSERT_EQ(Results.size(), 1u);
   ASSERT_TRUE(Results[0].Index.External);
-  EXPECT_FALSE(Results[0].Index.External.value()->File.has_value());
-  EXPECT_FALSE(Results[0].Index.External.value()->MountPoint.has_value());
-  EXPECT_FALSE(Results[0].Index.External.value()->Server.has_value());
-  EXPECT_THAT(*Results[0].Index.External.value()->IsNone, testing::Eq(true));
+  EXPECT_FALSE(Results[0].Index.External.getValue()->File.hasValue());
+  EXPECT_FALSE(Results[0].Index.External.getValue()->MountPoint.hasValue());
+  EXPECT_FALSE(Results[0].Index.External.getValue()->Server.hasValue());
+  EXPECT_THAT(*Results[0].Index.External.getValue()->IsNone, testing::Eq(true));
 }
 
 TEST(ParseYAML, ExternalBlock) {
@@ -182,10 +182,10 @@ TEST(ParseYAML, ExternalBlock) {
       Fragment::parseYAML(YAML.code(), "config.yaml", Diags.callback());
   ASSERT_EQ(Results.size(), 1u);
   ASSERT_TRUE(Results[0].Index.External);
-  EXPECT_THAT(*Results[0].Index.External.value()->File, val("foo"));
-  EXPECT_THAT(*Results[0].Index.External.value()->MountPoint, val("baz"));
+  EXPECT_THAT(*Results[0].Index.External.getValue()->File, val("foo"));
+  EXPECT_THAT(*Results[0].Index.External.getValue()->MountPoint, val("baz"));
   ASSERT_THAT(Diags.Diagnostics, IsEmpty());
-  EXPECT_THAT(*Results[0].Index.External.value()->Server, val("bar"));
+  EXPECT_THAT(*Results[0].Index.External.getValue()->Server, val("bar"));
 }
 
 TEST(ParseYAML, AllScopes) {

diff  --git a/clang-tools-extra/clangd/unittests/FSTests.cpp b/clang-tools-extra/clangd/unittests/FSTests.cpp
index 81129fec98c2d..575111e841dc5 100644
--- a/clang-tools-extra/clangd/unittests/FSTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FSTests.cpp
@@ -28,10 +28,10 @@ TEST(FSTests, PreambleStatusCache) {
   EXPECT_TRUE(ProduceFS->status("y"));
   EXPECT_TRUE(ProduceFS->status("main"));
 
-  EXPECT_TRUE(StatCache.lookup(testPath("x")).has_value());
-  EXPECT_TRUE(StatCache.lookup(testPath("y")).has_value());
+  EXPECT_TRUE(StatCache.lookup(testPath("x")).hasValue());
+  EXPECT_TRUE(StatCache.lookup(testPath("y")).hasValue());
   // Main file is not cached.
-  EXPECT_FALSE(StatCache.lookup(testPath("main")).has_value());
+  EXPECT_FALSE(StatCache.lookup(testPath("main")).hasValue());
 
   llvm::vfs::Status S("fake", llvm::sys::fs::UniqueID(123, 456),
                       std::chrono::system_clock::now(), 0, 0, 1024,

diff  --git a/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp b/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
index 3959c3eabc45c..fbf07aad4cd1f 100644
--- a/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
+++ b/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
@@ -331,14 +331,14 @@ TEST(GlobalCompilationDatabaseTest, CompileFlagsDirectory) {
   FS.Files[testPath("x/compile_flags.txt")] = "-DFOO";
   DirectoryBasedGlobalCompilationDatabase CDB(FS);
   auto Commands = CDB.getCompileCommand(testPath("x/y.cpp"));
-  ASSERT_TRUE(Commands.has_value());
-  EXPECT_THAT(Commands->CommandLine, Contains("-DFOO"));
+  ASSERT_TRUE(Commands.hasValue());
+  EXPECT_THAT(Commands.getValue().CommandLine, Contains("-DFOO"));
   // Make sure we pick the right working directory.
-  EXPECT_EQ(testPath("x"), Commands->Directory);
+  EXPECT_EQ(testPath("x"), Commands.getValue().Directory);
 }
 
 MATCHER_P(hasArg, Flag, "") {
-  if (!arg) {
+  if (!arg.hasValue()) {
     *result_listener << "command is null";
     return false;
   }

diff  --git a/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp b/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
index 5b9467f5c52f6..b2d7a7ee77240 100644
--- a/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
@@ -33,12 +33,12 @@ TEST(HeaderSourceSwitchTest, FileHeuristic) {
   FS.Files[Invalid];
   Optional<Path> PathResult =
       getCorrespondingHeaderOrSource(FooCpp, FS.view(llvm::None));
-  EXPECT_TRUE(PathResult.has_value());
-  ASSERT_EQ(*PathResult, FooH);
+  EXPECT_TRUE(PathResult.hasValue());
+  ASSERT_EQ(PathResult.getValue(), FooH);
 
   PathResult = getCorrespondingHeaderOrSource(FooH, FS.view(llvm::None));
-  EXPECT_TRUE(PathResult.has_value());
-  ASSERT_EQ(*PathResult, FooCpp);
+  EXPECT_TRUE(PathResult.hasValue());
+  ASSERT_EQ(PathResult.getValue(), FooCpp);
 
   // Test with header file in capital letters and 
diff erent extension, source
   // file with 
diff erent extension
@@ -48,8 +48,8 @@ TEST(HeaderSourceSwitchTest, FileHeuristic) {
   FS.Files[FooC];
   FS.Files[FooHH];
   PathResult = getCorrespondingHeaderOrSource(FooC, FS.view(llvm::None));
-  EXPECT_TRUE(PathResult.has_value());
-  ASSERT_EQ(*PathResult, FooHH);
+  EXPECT_TRUE(PathResult.hasValue());
+  ASSERT_EQ(PathResult.getValue(), FooHH);
 
   // Test with both capital letters
   auto Foo2C = testPath("foo2.C");
@@ -57,8 +57,8 @@ TEST(HeaderSourceSwitchTest, FileHeuristic) {
   FS.Files[Foo2C];
   FS.Files[Foo2HH];
   PathResult = getCorrespondingHeaderOrSource(Foo2C, FS.view(llvm::None));
-  EXPECT_TRUE(PathResult.has_value());
-  ASSERT_EQ(*PathResult, Foo2HH);
+  EXPECT_TRUE(PathResult.hasValue());
+  ASSERT_EQ(PathResult.getValue(), Foo2HH);
 
   // Test with source file as capital letter and .hxx header file
   auto Foo3C = testPath("foo3.C");
@@ -67,13 +67,13 @@ TEST(HeaderSourceSwitchTest, FileHeuristic) {
   FS.Files[Foo3C];
   FS.Files[Foo3HXX];
   PathResult = getCorrespondingHeaderOrSource(Foo3C, FS.view(llvm::None));
-  EXPECT_TRUE(PathResult.has_value());
-  ASSERT_EQ(*PathResult, Foo3HXX);
+  EXPECT_TRUE(PathResult.hasValue());
+  ASSERT_EQ(PathResult.getValue(), Foo3HXX);
 
   // Test if asking for a corresponding file that doesn't exist returns an empty
   // string.
   PathResult = getCorrespondingHeaderOrSource(Invalid, FS.view(llvm::None));
-  EXPECT_FALSE(PathResult.has_value());
+  EXPECT_FALSE(PathResult.hasValue());
 }
 
 MATCHER_P(declNamed, Name, "") {

diff  --git a/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp b/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp
index 97a4316928a8c..8b9363ba08655 100644
--- a/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp
+++ b/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp
@@ -93,18 +93,19 @@ TEST(LSPBinderTest, IncomingCalls) {
 
   auto &RawPlusOne = RawHandlers.MethodHandlers["plusOne"];
   RawPlusOne(1, capture(Reply));
-  ASSERT_TRUE(Reply.has_value());
-  EXPECT_THAT_EXPECTED(*Reply, llvm::HasValue(2));
+  ASSERT_TRUE(Reply.hasValue());
+  EXPECT_THAT_EXPECTED(Reply.getValue(), llvm::HasValue(2));
   RawPlusOne("foo", capture(Reply));
-  ASSERT_TRUE(Reply.has_value());
+  ASSERT_TRUE(Reply.hasValue());
   EXPECT_THAT_EXPECTED(
-      *Reply, llvm::FailedWithMessage(HasSubstr(
-                  "failed to decode plusOne request: expected integer")));
+      Reply.getValue(),
+      llvm::FailedWithMessage(
+          HasSubstr("failed to decode plusOne request: expected integer")));
 
   auto &RawFail = RawHandlers.MethodHandlers["fail"];
   RawFail(2, capture(Reply));
-  ASSERT_TRUE(Reply.has_value());
-  EXPECT_THAT_EXPECTED(*Reply, llvm::FailedWithMessage("X=2"));
+  ASSERT_TRUE(Reply.hasValue());
+  EXPECT_THAT_EXPECTED(Reply.getValue(), llvm::FailedWithMessage("X=2"));
 
   auto &RawNotify = RawHandlers.NotificationHandlers["notify"];
   RawNotify(42);
@@ -116,8 +117,8 @@ TEST(LSPBinderTest, IncomingCalls) {
 
   auto &RawCmdPlusOne = RawHandlers.CommandHandlers["cmdPlusOne"];
   RawCmdPlusOne(1, capture(Reply));
-  ASSERT_TRUE(Reply.has_value());
-  EXPECT_THAT_EXPECTED(*Reply, llvm::HasValue(2));
+  ASSERT_TRUE(Reply.hasValue());
+  EXPECT_THAT_EXPECTED(Reply.getValue(), llvm::HasValue(2));
 
   // None of this generated any outgoing traffic.
   EXPECT_THAT(RawOutgoing.Received, IsEmpty());
@@ -138,23 +139,23 @@ TEST(LSPBinderTest, OutgoingCalls) {
   llvm::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}));
+  ASSERT_TRUE(Reply.hasValue());
+  EXPECT_THAT_EXPECTED(Reply.getValue(), llvm::HasValue(Foo{2}));
 
   // JSON response is integer, can't be parsed as string.
   llvm::Optional<llvm::Expected<std::string>> WrongTypeReply;
   WrongSignature(Foo{2}, capture(WrongTypeReply));
   EXPECT_THAT(RawOutgoing.take("wrongSignature"),
               ElementsAre(llvm::json::Value(2)));
-  ASSERT_TRUE(Reply.has_value());
-  EXPECT_THAT_EXPECTED(*WrongTypeReply,
+  ASSERT_TRUE(Reply.hasValue());
+  EXPECT_THAT_EXPECTED(WrongTypeReply.getValue(),
                        llvm::FailedWithMessage(
                            HasSubstr("failed to decode wrongSignature reply")));
 
   Fail(Foo{2}, capture(Reply));
   EXPECT_THAT(RawOutgoing.take("fail"), ElementsAre(llvm::json::Value(2)));
-  ASSERT_TRUE(Reply.has_value());
-  EXPECT_THAT_EXPECTED(*Reply, llvm::FailedWithMessage("Params=2"));
+  ASSERT_TRUE(Reply.hasValue());
+  EXPECT_THAT_EXPECTED(Reply.getValue(), llvm::FailedWithMessage("Params=2"));
 }
 
 } // namespace

diff  --git a/clang-tools-extra/clangd/unittests/TidyProviderTests.cpp b/clang-tools-extra/clangd/unittests/TidyProviderTests.cpp
index ece7f52d04d45..df3dcac0aa51a 100644
--- a/clang-tools-extra/clangd/unittests/TidyProviderTests.cpp
+++ b/clang-tools-extra/clangd/unittests/TidyProviderTests.cpp
@@ -37,18 +37,18 @@ TEST(TidyProvider, NestedDirectories) {
   TidyProvider Provider = provideClangTidyFiles(FS);
 
   auto BaseOptions = getTidyOptionsForFile(Provider, testPath("File.cpp"));
-  ASSERT_TRUE(BaseOptions.Checks.has_value());
+  ASSERT_TRUE(BaseOptions.Checks.hasValue());
   EXPECT_EQ(*BaseOptions.Checks, "llvm-*");
   EXPECT_EQ(BaseOptions.CheckOptions.lookup("TestKey").Value, "1");
 
   auto Sub1Options = getTidyOptionsForFile(Provider, testPath("sub1/File.cpp"));
-  ASSERT_TRUE(Sub1Options.Checks.has_value());
+  ASSERT_TRUE(Sub1Options.Checks.hasValue());
   EXPECT_EQ(*Sub1Options.Checks, "misc-*");
   EXPECT_EQ(Sub1Options.CheckOptions.lookup("TestKey").Value, "2");
 
   auto Sub2Options =
       getTidyOptionsForFile(Provider, testPath("sub1/sub2/File.cpp"));
-  ASSERT_TRUE(Sub2Options.Checks.has_value());
+  ASSERT_TRUE(Sub2Options.Checks.hasValue());
   EXPECT_EQ(*Sub2Options.Checks, "misc-*,bugprone-*");
   EXPECT_EQ(Sub2Options.CheckOptions.lookup("TestKey").Value, "3");
 }

diff  --git a/clang-tools-extra/pseudo/lib/GLR.cpp b/clang-tools-extra/pseudo/lib/GLR.cpp
index d93f682afac6c..1cee8f86e599d 100644
--- a/clang-tools-extra/pseudo/lib/GLR.cpp
+++ b/clang-tools-extra/pseudo/lib/GLR.cpp
@@ -375,11 +375,11 @@ class GLRReduce {
     for (auto &A : Params.Table.getActions(Head->State, Lookahead)) {
       if (A.kind() != LRTable::Action::Reduce)
         continue;
-      if (RID)
+      if (RID.hasValue())
         return false;
       RID = A.getReduceRule();
     }
-    if (!RID)
+    if (!RID.hasValue())
       return true; // no reductions available, but we've processed the head!
     const auto &Rule = Params.G.lookupRule(*RID);
     const GSS::Node *Base = Head;

diff  --git a/clang-tools-extra/unittests/clang-doc/ClangDocTest.cpp b/clang-tools-extra/unittests/clang-doc/ClangDocTest.cpp
index ea1ef734593cd..970ffcebd717b 100644
--- a/clang-tools-extra/unittests/clang-doc/ClangDocTest.cpp
+++ b/clang-tools-extra/unittests/clang-doc/ClangDocTest.cpp
@@ -95,8 +95,8 @@ void CheckBaseInfo(Info *Expected, Info *Actual) {
 
 void CheckSymbolInfo(SymbolInfo *Expected, SymbolInfo *Actual) {
   CheckBaseInfo(Expected, Actual);
-  EXPECT_EQ(Expected->DefLoc.has_value(), Actual->DefLoc.has_value());
-  if (Expected->DefLoc && Actual->DefLoc) {
+  EXPECT_EQ(Expected->DefLoc.hasValue(), Actual->DefLoc.hasValue());
+  if (Expected->DefLoc.hasValue() && Actual->DefLoc.hasValue()) {
     EXPECT_EQ(Expected->DefLoc->LineNumber, Actual->DefLoc->LineNumber);
     EXPECT_EQ(Expected->DefLoc->Filename, Actual->DefLoc->Filename);
   }

diff  --git a/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp b/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
index 5dcec035c476a..3558b5f346a23 100644
--- a/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
@@ -129,14 +129,14 @@ TEST(ParseConfiguration, MergeConfigurations) {
   EXPECT_EQ("check1,check2,check3,check4", *Options.Checks);
   EXPECT_EQ("filter2", *Options.HeaderFilterRegex);
   EXPECT_EQ("user2", *Options.User);
-  ASSERT_TRUE(Options.ExtraArgs.has_value());
+  ASSERT_TRUE(Options.ExtraArgs.hasValue());
   EXPECT_EQ("arg1,arg2,arg3,arg4", llvm::join(Options.ExtraArgs->begin(),
                                               Options.ExtraArgs->end(), ","));
-  ASSERT_TRUE(Options.ExtraArgsBefore.has_value());
+  ASSERT_TRUE(Options.ExtraArgsBefore.hasValue());
   EXPECT_EQ("arg-before1,arg-before2,arg-before3,arg-before4",
             llvm::join(Options.ExtraArgsBefore->begin(),
                        Options.ExtraArgsBefore->end(), ","));
-  ASSERT_TRUE(Options.UseColor.has_value());
+  ASSERT_TRUE(Options.UseColor.hasValue());
   EXPECT_TRUE(*Options.UseColor);
 }
 
@@ -325,9 +325,9 @@ TEST(CheckOptionsValidation, ValidIntOptions) {
 
   CHECK_VAL(TestCheck.getIntLocal("IntExpected"), 1);
   CHECK_VAL(TestCheck.getIntGlobal("GlobalIntExpected"), 1);
-  EXPECT_FALSE(TestCheck.getIntLocal("IntInvalid1").has_value());
-  EXPECT_FALSE(TestCheck.getIntLocal("IntInvalid2").has_value());
-  EXPECT_FALSE(TestCheck.getIntGlobal("GlobalIntInvalid").has_value());
+  EXPECT_FALSE(TestCheck.getIntLocal("IntInvalid1").hasValue());
+  EXPECT_FALSE(TestCheck.getIntLocal("IntInvalid2").hasValue());
+  EXPECT_FALSE(TestCheck.getIntGlobal("GlobalIntInvalid").hasValue());
   ASSERT_EQ(TestCheck.getIntLocal("DefaultedIntInvalid", 1), 1);
 
   CHECK_VAL(TestCheck.getIntLocal<bool>("BoolITrueValue"), true);
@@ -395,14 +395,14 @@ TEST(ValidConfiguration, ValidEnumOptions) {
                                             /*IgnoreCase*/ true),
             Colours::Violet);
 
-  EXPECT_FALSE(TestCheck.getIntLocal<Colours>("ValidWrongCase").has_value());
-  EXPECT_FALSE(TestCheck.getIntLocal<Colours>("NearMiss").has_value());
-  EXPECT_FALSE(TestCheck.getIntGlobal<Colours>("GlobalInvalid").has_value());
+  EXPECT_FALSE(TestCheck.getIntLocal<Colours>("ValidWrongCase").hasValue());
+  EXPECT_FALSE(TestCheck.getIntLocal<Colours>("NearMiss").hasValue());
+  EXPECT_FALSE(TestCheck.getIntGlobal<Colours>("GlobalInvalid").hasValue());
   EXPECT_FALSE(
-      TestCheck.getIntGlobal<Colours>("GlobalValidWrongCase").has_value());
-  EXPECT_FALSE(TestCheck.getIntGlobal<Colours>("GlobalNearMiss").has_value());
+      TestCheck.getIntGlobal<Colours>("GlobalValidWrongCase").hasValue());
+  EXPECT_FALSE(TestCheck.getIntGlobal<Colours>("GlobalNearMiss").hasValue());
 
-  EXPECT_FALSE(TestCheck.getIntLocal<Colours>("Invalid").has_value());
+  EXPECT_FALSE(TestCheck.getIntLocal<Colours>("Invalid").hasValue());
   EXPECT_THAT(
       DiagConsumer.take(),
       UnorderedElementsAre(

diff  --git a/clang-tools-extra/unittests/clang-tidy/NamespaceAliaserTest.cpp b/clang-tools-extra/unittests/clang-tidy/NamespaceAliaserTest.cpp
index c7ebd5e9339ef..e4cd74ede7e4a 100644
--- a/clang-tools-extra/unittests/clang-tidy/NamespaceAliaserTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/NamespaceAliaserTest.cpp
@@ -34,8 +34,8 @@ class InsertAliasCheck : public ClangTidyCheck {
     assert(Call != nullptr && "Did not find node \"foo\"");
     auto Hint = Aliaser->createAlias(*Result.Context, *Call, "::foo::bar",
                                      {"b", "some_alias"});
-    if (Hint)
-      diag(Call->getBeginLoc(), "Fix for testing") << *Hint;
+    if (Hint.hasValue())
+      diag(Call->getBeginLoc(), "Fix for testing") << Hint.getValue();
 
     diag(Call->getBeginLoc(), "insert call") << FixItHint::CreateInsertion(
         Call->getBeginLoc(),

diff  --git a/clang-tools-extra/unittests/clang-tidy/OptionsProviderTest.cpp b/clang-tools-extra/unittests/clang-tidy/OptionsProviderTest.cpp
index 5aa3730ac5ccf..b99d0781e3f7d 100644
--- a/clang-tools-extra/unittests/clang-tidy/OptionsProviderTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/OptionsProviderTest.cpp
@@ -53,9 +53,9 @@ TEST(ClangTidyOptionsProvider, InMemoryFileSystems) {
   ClangTidyOptions File3Options =
       FileOpt.getOptions("ProjectRoot/SubDir1/SubDir2/SubDir3/File.cpp");
 
-  ASSERT_TRUE(File1Options.Checks.has_value());
+  ASSERT_TRUE(File1Options.Checks.hasValue());
   EXPECT_EQ(*File1Options.Checks, "-*,clang-diagnostic-*,readability-*");
-  ASSERT_TRUE(File2Options.Checks.has_value());
+  ASSERT_TRUE(File2Options.Checks.hasValue());
   EXPECT_EQ(*File2Options.Checks, "bugprone-*,misc-*,clang-diagnostic-*");
 
   // 2 and 3 should use the same config so these should also be the same.

diff  --git a/clang-tools-extra/unittests/clang-tidy/UsingInserterTest.cpp b/clang-tools-extra/unittests/clang-tidy/UsingInserterTest.cpp
index 43350cbff4e85..71c71596d0d90 100644
--- a/clang-tools-extra/unittests/clang-tidy/UsingInserterTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/UsingInserterTest.cpp
@@ -37,8 +37,8 @@ class InsertUsingCheck : public clang::tidy::ClangTidyCheck {
     auto Hint =
         Inserter->createUsingDeclaration(*Result.Context, *Call, "::foo::func");
 
-    if (Hint)
-      diag(Call->getBeginLoc(), "Fix for testing") << *Hint;
+    if (Hint.hasValue())
+      diag(Call->getBeginLoc(), "Fix for testing") << Hint.getValue();
 
     diag(Call->getBeginLoc(), "insert call")
         << clang::FixItHint::CreateReplacement(

diff  --git a/clang/include/clang/APINotes/Types.h b/clang/include/clang/APINotes/Types.h
index d98b3d979ccac..ed5250f3d5b4e 100644
--- a/clang/include/clang/APINotes/Types.h
+++ b/clang/include/clang/APINotes/Types.h
@@ -76,8 +76,8 @@ class CommonEntityInfo {
   }
 
   void setSwiftPrivate(llvm::Optional<bool> Private) {
-    SwiftPrivateSpecified = Private.has_value();
-    SwiftPrivate = Private.value_or(0);
+    SwiftPrivateSpecified = Private.hasValue();
+    SwiftPrivate = Private.hasValue() ? *Private : 0;
   }
 
   friend bool operator==(const CommonEntityInfo &, const CommonEntityInfo &);

diff  --git a/clang/include/clang/AST/PropertiesBase.td b/clang/include/clang/AST/PropertiesBase.td
index 0f7acf6006ddc..559f29edcf0fe 100644
--- a/clang/include/clang/AST/PropertiesBase.td
+++ b/clang/include/clang/AST/PropertiesBase.td
@@ -520,15 +520,15 @@ let Class = PropertyTypeCase<APValue, "LValue"> in {
     if (hasBase) {
       if (isTypeInfo) {
         base = APValue::LValueBase::getTypeInfo(
-            TypeInfoLValue(typeInfo->getTypePtr()), *type);
+            TypeInfoLValue(typeInfo.getValue().getTypePtr()), type.getValue());
         elemTy = base.getTypeInfoType();
       } else if (isExpr) {
-        base = APValue::LValueBase(cast<Expr>(*stmt),
-                                   *callIndex, *version);
+        base = APValue::LValueBase(cast<Expr>(stmt.getValue()),
+                                   callIndex.getValue(), version.getValue());
         elemTy = base.get<const Expr *>()->getType();
       } else {
-        base = APValue::LValueBase(cast<ValueDecl>(*decl),
-                                   *callIndex, *version);
+        base = APValue::LValueBase(cast<ValueDecl>(decl.getValue()),
+                                   callIndex.getValue(), version.getValue());
         elemTy = base.get<const ValueDecl *>()->getType();
       }
     }

diff  --git a/clang/include/clang/Analysis/PathDiagnostic.h b/clang/include/clang/Analysis/PathDiagnostic.h
index 9877f1e3d01fd..47cb549c8e669 100644
--- a/clang/include/clang/Analysis/PathDiagnostic.h
+++ b/clang/include/clang/Analysis/PathDiagnostic.h
@@ -544,8 +544,8 @@ class PathDiagnosticEventPiece : public PathDiagnosticSpotPiece {
   /// flag may have been previously set, at which point it will not
   /// be reset unless one specifies to do so.
   void setPrunable(bool isPrunable, bool override = false) {
-    if (IsPrunable && !override)
-      return;
+    if (IsPrunable.hasValue() && !override)
+     return;
     IsPrunable = isPrunable;
   }
 

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 8b8b1b2e2e864..ba4d0bb8f4354 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1766,9 +1766,9 @@ class Sema final {
     template <typename T>
     friend const SemaDiagnosticBuilder &
     operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
-      if (Diag.ImmediateDiag)
+      if (Diag.ImmediateDiag.hasValue())
         *Diag.ImmediateDiag << Value;
-      else if (Diag.PartialDiagId)
+      else if (Diag.PartialDiagId.hasValue())
         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
             << Value;
       return Diag;
@@ -1780,26 +1780,26 @@ class Sema final {
     template <typename T, typename = typename std::enable_if<
                               !std::is_lvalue_reference<T>::value>::type>
     const SemaDiagnosticBuilder &operator<<(T &&V) const {
-      if (ImmediateDiag)
+      if (ImmediateDiag.hasValue())
         *ImmediateDiag << std::move(V);
-      else if (PartialDiagId)
+      else if (PartialDiagId.hasValue())
         S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
       return *this;
     }
 
     friend const SemaDiagnosticBuilder &
     operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
-      if (Diag.ImmediateDiag)
+      if (Diag.ImmediateDiag.hasValue())
         PD.Emit(*Diag.ImmediateDiag);
-      else if (Diag.PartialDiagId)
+      else if (Diag.PartialDiagId.hasValue())
         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
       return Diag;
     }
 
     void AddFixItHint(const FixItHint &Hint) const {
-      if (ImmediateDiag)
+      if (ImmediateDiag.hasValue())
         ImmediateDiag->AddFixItHint(Hint);
-      else if (PartialDiagId)
+      else if (PartialDiagId.hasValue())
         S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
     }
 

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
index 59fe535e820bb..a01b32669ce3f 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -414,8 +414,7 @@ class CallEvent {
   bool isArgumentConstructedDirectly(unsigned Index) const {
     // This assumes that the object was not yet removed from the state.
     return ExprEngine::getObjectUnderConstruction(
-               getState(), {getOriginExpr(), Index}, getLocationContext())
-        .has_value();
+        getState(), {getOriginExpr(), Index}, getLocationContext()).hasValue();
   }
 
   /// Some calls have parameter numbering mismatched from argument numbering.
@@ -1017,8 +1016,9 @@ class CXXAllocatorCall : public AnyFunctionCall {
   }
 
   SVal getObjectUnderConstruction() const {
-    return *ExprEngine::getObjectUnderConstruction(getState(), getOriginExpr(),
-                                                   getLocationContext());
+    return ExprEngine::getObjectUnderConstruction(getState(), getOriginExpr(),
+                                                  getLocationContext())
+        .getValue();
   }
 
   /// Number of non-placement arguments to the call. It is equal to 2 for

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
index 92a37c6a9e608..11c60b6895627 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
@@ -53,17 +53,25 @@ class ConditionTruthVal {
   }
 
   /// Return true if the constraint is perfectly constrained to 'true'.
-  bool isConstrainedTrue() const { return Val && *Val; }
+  bool isConstrainedTrue() const {
+    return Val.hasValue() && Val.getValue();
+  }
 
   /// Return true if the constraint is perfectly constrained to 'false'.
-  bool isConstrainedFalse() const { return Val && !*Val; }
+  bool isConstrainedFalse() const {
+    return Val.hasValue() && !Val.getValue();
+  }
 
   /// Return true if the constrained is perfectly constrained.
-  bool isConstrained() const { return Val.has_value(); }
+  bool isConstrained() const {
+    return Val.hasValue();
+  }
 
   /// Return true if the constrained is underconstrained and we do not know
   /// if the constraint is true of value.
-  bool isUnderconstrained() const { return !Val.has_value(); }
+  bool isUnderconstrained() const {
+    return !Val.hasValue();
+  }
 };
 
 class ConstraintManager {

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
index 6c8ed07efbb29..250ba4f528968 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
@@ -341,10 +341,10 @@ class SMTConstraintManager : public clang::ento::SimpleConstraintManager {
     addStateConstraints(NewState);
 
     Optional<bool> res = Solver->check();
-    if (!res)
+    if (!res.hasValue())
       Cached[hash] = ConditionTruthVal();
     else
-      Cached[hash] = ConditionTruthVal(*res);
+      Cached[hash] = ConditionTruthVal(res.getValue());
 
     return Cached[hash];
   }

diff  --git a/clang/include/clang/Support/RISCVVIntrinsicUtils.h b/clang/include/clang/Support/RISCVVIntrinsicUtils.h
index 8d34cafb1d8a8..0e9fe97ab735e 100644
--- a/clang/include/clang/Support/RISCVVIntrinsicUtils.h
+++ b/clang/include/clang/Support/RISCVVIntrinsicUtils.h
@@ -209,8 +209,8 @@ class RVVType {
   }
 
   bool isValid() const { return Valid; }
-  bool isScalar() const { return Scale && *Scale == 0; }
-  bool isVector() const { return Scale && *Scale != 0; }
+  bool isScalar() const { return Scale.hasValue() && Scale.getValue() == 0; }
+  bool isVector() const { return Scale.hasValue() && Scale.getValue() != 0; }
   bool isVector(unsigned Width) const {
     return isVector() && ElementBitwidth == Width;
   }

diff  --git a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
index b3882c227eaff..e0d16df92e1a4 100644
--- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
+++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
@@ -94,9 +94,9 @@ class CachedFileSystemEntry {
     assert(!isDirectory() && "not a file");
     assert(Contents && "contents not initialized");
     if (auto *Directives = Contents->DepDirectives.load()) {
-      if (Directives->has_value())
+      if (Directives->hasValue())
         return ArrayRef<dependency_directives_scan::Directive>(
-            Directives->value());
+            Directives->getValue());
     }
     return None;
   }

diff  --git a/clang/lib/AST/AttrImpl.cpp b/clang/lib/AST/AttrImpl.cpp
index deb28bee5ed8c..7b8acfcd92bea 100644
--- a/clang/lib/AST/AttrImpl.cpp
+++ b/clang/lib/AST/AttrImpl.cpp
@@ -168,24 +168,24 @@ OMPDeclareTargetDeclAttr::getActiveAttr(const ValueDecl *VD) {
 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(const ValueDecl *VD) {
   llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = getActiveAttr(VD);
-  if (ActiveAttr)
-    return ActiveAttr.value()->getMapType();
+  if (ActiveAttr.hasValue())
+    return ActiveAttr.getValue()->getMapType();
   return llvm::None;
 }
 
 llvm::Optional<OMPDeclareTargetDeclAttr::DevTypeTy>
 OMPDeclareTargetDeclAttr::getDeviceType(const ValueDecl *VD) {
   llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = getActiveAttr(VD);
-  if (ActiveAttr)
-    return ActiveAttr.value()->getDevType();
+  if (ActiveAttr.hasValue())
+    return ActiveAttr.getValue()->getDevType();
   return llvm::None;
 }
 
 llvm::Optional<SourceLocation>
 OMPDeclareTargetDeclAttr::getLocation(const ValueDecl *VD) {
   llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = getActiveAttr(VD);
-  if (ActiveAttr)
-    return ActiveAttr.value()->getRange().getBegin();
+  if (ActiveAttr.hasValue())
+    return ActiveAttr.getValue()->getRange().getBegin();
   return llvm::None;
 }
 

diff  --git a/clang/lib/ASTMatchers/Dynamic/Parser.cpp b/clang/lib/ASTMatchers/Dynamic/Parser.cpp
index 6470df27e6e23..ec14f7abfdccf 100644
--- a/clang/lib/ASTMatchers/Dynamic/Parser.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Parser.cpp
@@ -397,9 +397,9 @@ bool Parser::parseIdentifierPrefixImpl(VariantValue *Value) {
       assert(NamedValue.isMatcher());
       llvm::Optional<DynTypedMatcher> Result =
           NamedValue.getMatcher().getSingleMatcher();
-      if (Result) {
+      if (Result.hasValue()) {
         llvm::Optional<DynTypedMatcher> Bound = Result->tryBind(BindID);
-        if (Bound) {
+        if (Bound.hasValue()) {
           *Value = VariantMatcher::SingleMatcher(*Bound);
           return true;
         }

diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 42193e65496dc..72629d0aa91e5 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -797,9 +797,9 @@ VariantMatcher Registry::constructBoundMatcher(MatcherCtor Ctor,
   if (Out.isNull()) return Out;
 
   llvm::Optional<DynTypedMatcher> Result = Out.getSingleMatcher();
-  if (Result) {
+  if (Result.hasValue()) {
     llvm::Optional<DynTypedMatcher> Bound = Result->tryBind(BindID);
-    if (Bound) {
+    if (Bound.hasValue()) {
       return VariantMatcher::SingleMatcher(*Bound);
     }
   }

diff  --git a/clang/lib/Analysis/BodyFarm.cpp b/clang/lib/Analysis/BodyFarm.cpp
index f182506a958a4..3587cf4678af8 100644
--- a/clang/lib/Analysis/BodyFarm.cpp
+++ b/clang/lib/Analysis/BodyFarm.cpp
@@ -697,8 +697,8 @@ static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
 
 Stmt *BodyFarm::getBody(const FunctionDecl *D) {
   Optional<Stmt *> &Val = Bodies[D];
-  if (Val)
-    return *Val;
+  if (Val.hasValue())
+    return Val.getValue();
 
   Val = nullptr;
 
@@ -872,8 +872,8 @@ Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) {
     return nullptr;
 
   Optional<Stmt *> &Val = Bodies[D];
-  if (Val)
-    return *Val;
+  if (Val.hasValue())
+    return Val.getValue();
   Val = nullptr;
 
   // For now, we only synthesize getters.

diff  --git a/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp b/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
index 3a362d49d21ab..c0b8119038f2d 100644
--- a/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
+++ b/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
@@ -31,10 +31,13 @@ buildStmtToBasicBlockMap(const CFG &Cfg) {
     if (Block == nullptr)
       continue;
 
-    for (const CFGElement &Element : *Block)
-      if (auto Stmt = Element.getAs<CFGStmt>())
-        StmtToBlock[Stmt->getStmt()] = Block;
+    for (const CFGElement &Element : *Block) {
+      auto Stmt = Element.getAs<CFGStmt>();
+      if (!Stmt.hasValue())
+        continue;
 
+      StmtToBlock[Stmt.getValue().getStmt()] = Block;
+    }
     if (const Stmt *TerminatorStmt = Block->getTerminatorStmt())
       StmtToBlock[TerminatorStmt] = Block;
   }

diff  --git a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
index 0de4bca3ffc16..68e897e035962 100644
--- a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -50,8 +50,8 @@ class StmtToEnvMapImpl : public StmtToEnvMap {
     auto BlockIT = CFCtx.getStmtToBlock().find(&ignoreCFGOmittedNodes(S));
     assert(BlockIT != CFCtx.getStmtToBlock().end());
     const auto &State = BlockToState[BlockIT->getSecond()->getBlockID()];
-    assert(State);
-    return &State->Env;
+    assert(State.hasValue());
+    return &State.getValue().Env;
   }
 
 private:
@@ -209,10 +209,10 @@ static TypeErasedDataflowAnalysisState computeBlockInputState(
     // loop back edge to `Block`.
     const llvm::Optional<TypeErasedDataflowAnalysisState> &MaybePredState =
         BlockStates[Pred->getBlockID()];
-    if (!MaybePredState)
+    if (!MaybePredState.hasValue())
       continue;
 
-    TypeErasedDataflowAnalysisState PredState = *MaybePredState;
+    TypeErasedDataflowAnalysisState PredState = MaybePredState.getValue();
     if (ApplyBuiltinTransfer) {
       if (const Stmt *PredTerminatorStmt = Pred->getTerminatorStmt()) {
         const StmtToEnvMapImpl StmtToEnv(CFCtx, BlockStates);
@@ -222,14 +222,14 @@ static TypeErasedDataflowAnalysisState computeBlockInputState(
       }
     }
 
-    if (MaybeState) {
+    if (MaybeState.hasValue()) {
       Analysis.joinTypeErased(MaybeState->Lattice, PredState.Lattice);
       MaybeState->Env.join(PredState.Env, Analysis);
     } else {
       MaybeState = std::move(PredState);
     }
   }
-  if (!MaybeState) {
+  if (!MaybeState.hasValue()) {
     // FIXME: Consider passing `Block` to `Analysis.typeErasedInitialElement()`
     // to enable building analyses like computation of dominators that
     // initialize the state of each basic block 
diff erently.
@@ -367,8 +367,8 @@ runTypeErasedDataflowAnalysis(const ControlFlowContext &CFCtx,
     TypeErasedDataflowAnalysisState NewBlockState =
         transferBlock(CFCtx, BlockStates, *Block, InitEnv, Analysis);
 
-    if (OldBlockState &&
-        Analysis.isEqualTypeErased(OldBlockState->Lattice,
+    if (OldBlockState.hasValue() &&
+        Analysis.isEqualTypeErased(OldBlockState.getValue().Lattice,
                                    NewBlockState.Lattice) &&
         OldBlockState->Env.equivalentTo(NewBlockState.Env, Analysis)) {
       // The state of `Block` didn't change after transfer so there's no need to

diff  --git a/clang/lib/Analysis/PathDiagnostic.cpp b/clang/lib/Analysis/PathDiagnostic.cpp
index b5be64552cfbb..90c4624018069 100644
--- a/clang/lib/Analysis/PathDiagnostic.cpp
+++ b/clang/lib/Analysis/PathDiagnostic.cpp
@@ -319,8 +319,8 @@ static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y) {
 
   for ( ; X_I != X_end && Y_I != Y_end; ++X_I, ++Y_I) {
     Optional<bool> b = comparePiece(**X_I, **Y_I);
-    if (b)
-      return *b;
+    if (b.hasValue())
+      return b.getValue();
   }
 
   return None;
@@ -396,8 +396,8 @@ static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y) {
       return (*XI) < (*YI);
   }
   Optional<bool> b = comparePath(X.path, Y.path);
-  assert(b);
-  return *b;
+  assert(b.hasValue());
+  return b.getValue();
 }
 
 void PathDiagnosticConsumer::FlushDiagnostics(

diff  --git a/clang/lib/Analysis/UninitializedValues.cpp b/clang/lib/Analysis/UninitializedValues.cpp
index f1be39298350d..811146e50b45a 100644
--- a/clang/lib/Analysis/UninitializedValues.cpp
+++ b/clang/lib/Analysis/UninitializedValues.cpp
@@ -148,8 +148,8 @@ class CFGBlockValues {
   Value getValue(const CFGBlock *block, const CFGBlock *dstBlock,
                  const VarDecl *vd) {
     const Optional<unsigned> &idx = declToIndex.getValueIndex(vd);
-    assert(idx);
-    return getValueVector(block)[*idx];
+    assert(idx.hasValue());
+    return getValueVector(block)[idx.getValue()];
   }
 };
 
@@ -209,8 +209,8 @@ void CFGBlockValues::resetScratch() {
 
 ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) {
   const Optional<unsigned> &idx = declToIndex.getValueIndex(vd);
-  assert(idx);
-  return scratch[*idx];
+  assert(idx.hasValue());
+  return scratch[idx.getValue()];
 }
 
 //------------------------------------------------------------------------====//

diff  --git a/clang/lib/Basic/Targets/RISCV.cpp b/clang/lib/Basic/Targets/RISCV.cpp
index 722a605d1c641..098bf21d6caa0 100644
--- a/clang/lib/Basic/Targets/RISCV.cpp
+++ b/clang/lib/Basic/Targets/RISCV.cpp
@@ -251,8 +251,8 @@ bool RISCVTargetInfo::hasFeature(StringRef Feature) const {
                     .Case("riscv64", Is64Bit)
                     .Case("64bit", Is64Bit)
                     .Default(None);
-  if (Result)
-    return *Result;
+  if (Result.hasValue())
+    return Result.getValue();
 
   if (ISAInfo->isSupportedExtensionFeature(Feature))
     return ISAInfo->hasExtension(Feature);

diff  --git a/clang/lib/CodeGen/CGClass.cpp b/clang/lib/CodeGen/CGClass.cpp
index ec9e325835c63..153f299a1c4b4 100644
--- a/clang/lib/CodeGen/CGClass.cpp
+++ b/clang/lib/CodeGen/CGClass.cpp
@@ -1782,15 +1782,15 @@ namespace {
        if (!StartIndex)
          StartIndex = FieldIndex;
      } else if (StartIndex) {
-       EHStack.pushCleanup<SanitizeDtorFieldRange>(NormalAndEHCleanup, DD,
-                                                   *StartIndex, FieldIndex);
+       EHStack.pushCleanup<SanitizeDtorFieldRange>(
+           NormalAndEHCleanup, DD, StartIndex.getValue(), FieldIndex);
        StartIndex = None;
      }
    }
    void End() {
      if (StartIndex)
        EHStack.pushCleanup<SanitizeDtorFieldRange>(NormalAndEHCleanup, DD,
-                                                   *StartIndex, -1);
+                                                   StartIndex.getValue(), -1);
    }
  };
 } // end anonymous namespace

diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index 34d8b3a7d3609..17b8e6bc1b470 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2826,12 +2826,12 @@ bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn,
   CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
   // First, check the function name.
   Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind);
-  if (V)
+  if (V.hasValue())
     return *V;
   // Next, check the source location.
   if (Loc.isValid()) {
     Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind);
-    if (V)
+    if (V.hasValue())
       return *V;
   }
   // If location is unknown, this may be a compiler-generated function. Assume

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 721c8f8ae9f23..d83142286e7d6 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -3325,8 +3325,8 @@ class OffloadingActionBuilder final {
         A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
                                                AssociatedOffloadKind);
 
-      if (CompileDeviceOnly && CurPhase == FinalPhase && BundleOutput &&
-          *BundleOutput) {
+      if (CompileDeviceOnly && CurPhase == FinalPhase &&
+          BundleOutput.hasValue() && BundleOutput.getValue()) {
         for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
           OffloadAction::DeviceDependences DDep;
           DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],

diff  --git a/clang/lib/Driver/ToolChains/AVR.cpp b/clang/lib/Driver/ToolChains/AVR.cpp
index 0b68a3241e12d..2547d1312322e 100644
--- a/clang/lib/Driver/ToolChains/AVR.cpp
+++ b/clang/lib/Driver/ToolChains/AVR.cpp
@@ -475,9 +475,9 @@ void AVR::Linker::ConstructJob(Compilation &C, const JobAction &JA,
       D.Diag(diag::warn_drv_avr_stdlib_not_linked);
   }
 
-  if (SectionAddressData) {
-    std::string DataSectionArg =
-        std::string("-Tdata=0x") + llvm::utohexstr(*SectionAddressData);
+  if (SectionAddressData.hasValue()) {
+    std::string DataSectionArg = std::string("-Tdata=0x") +
+                                 llvm::utohexstr(SectionAddressData.getValue());
     CmdArgs.push_back(Args.MakeArgString(DataSectionArg));
   } else {
     // We do not have an entry for this CPU in the address mapping table yet.

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp
index 286d414ddb372..5142b72a160fb 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -2340,8 +2340,8 @@ void Clang::AddHexagonTargetArgs(const ArgList &Args,
 
   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
     CmdArgs.push_back("-mllvm");
-    CmdArgs.push_back(
-        Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
+    CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
+                                         Twine(G.getValue())));
   }
 
   if (!Args.hasArg(options::OPT_fno_short_enums))

diff  --git a/clang/lib/Driver/ToolChains/Gnu.cpp b/clang/lib/Driver/ToolChains/Gnu.cpp
index d813def123b15..dc99010107376 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2086,8 +2086,8 @@ void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
 }
 
 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
-  if (BiarchSibling) {
-    M = *BiarchSibling;
+  if (BiarchSibling.hasValue()) {
+    M = BiarchSibling.getValue();
     return true;
   }
   return false;

diff  --git a/clang/lib/Driver/ToolChains/Hexagon.cpp b/clang/lib/Driver/ToolChains/Hexagon.cpp
index e129e3054dd86..9142dba81d54a 100644
--- a/clang/lib/Driver/ToolChains/Hexagon.cpp
+++ b/clang/lib/Driver/ToolChains/Hexagon.cpp
@@ -340,8 +340,8 @@ constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
     CmdArgs.push_back("-pie");
 
   if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
-    CmdArgs.push_back(Args.MakeArgString("-G" + Twine(*G)));
-    UseG0 = *G == 0;
+    CmdArgs.push_back(Args.MakeArgString("-G" + Twine(G.getValue())));
+    UseG0 = G.getValue() == 0;
   }
 
   CmdArgs.push_back("-o");

diff  --git a/clang/lib/Edit/RewriteObjCFoundationAPI.cpp b/clang/lib/Edit/RewriteObjCFoundationAPI.cpp
index 1ca041f3ed6da..589bf8d216ed3 100644
--- a/clang/lib/Edit/RewriteObjCFoundationAPI.cpp
+++ b/clang/lib/Edit/RewriteObjCFoundationAPI.cpp
@@ -725,11 +725,11 @@ static bool getLiteralInfo(SourceRange literalRange,
       break;
   }
 
-  if (!UpperU && !UpperL)
+  if (!UpperU.hasValue() && !UpperL.hasValue())
     UpperU = UpperL = true;
-  else if (UpperU && !UpperL)
+  else if (UpperU.hasValue() && !UpperL.hasValue())
     UpperL = UpperU;
-  else if (UpperL && !UpperU)
+  else if (UpperL.hasValue() && !UpperU.hasValue())
     UpperU = UpperL;
 
   Info.U = *UpperU ? "U" : "u";

diff  --git a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
index b1450b273ed4f..c4797cea333fe 100644
--- a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
+++ b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
@@ -31,14 +31,14 @@ namespace {
 /// at position \p Key.
 void serializeObject(Object &Paren, StringRef Key, Optional<Object> Obj) {
   if (Obj)
-    Paren[Key] = std::move(*Obj);
+    Paren[Key] = std::move(Obj.getValue());
 }
 
 /// Helper function to inject a JSON array \p Array into object \p Paren at
 /// position \p Key.
 void serializeArray(Object &Paren, StringRef Key, Optional<Array> Array) {
   if (Array)
-    Paren[Key] = std::move(*Array);
+    Paren[Key] = std::move(Array.getValue());
 }
 
 /// Serialize a \c VersionTuple \p V with the Symbol Graph semantic version

diff  --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp
index 95e5b04798b42..b982ca72c78ce 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -115,9 +115,9 @@ bool CompilerInstance::createTarget() {
     auto TO = std::make_shared<TargetOptions>();
     TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
     if (getFrontendOpts().AuxTargetCPU)
-      TO->CPU = *getFrontendOpts().AuxTargetCPU;
+      TO->CPU = getFrontendOpts().AuxTargetCPU.getValue();
     if (getFrontendOpts().AuxTargetFeatures)
-      TO->FeaturesAsWritten = *getFrontendOpts().AuxTargetFeatures;
+      TO->FeaturesAsWritten = getFrontendOpts().AuxTargetFeatures.getValue();
     TO->HostTriple = getTarget().getTriple().str();
     setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
   }

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp b/clang/lib/Frontend/CompilerInvocation.cpp
index 4b53d6d8b0458..c0eed3ad87485 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -1951,8 +1951,8 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
           << "-fdiagnostics-hotness-threshold=";
     } else {
       Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
-      if ((!Opts.DiagnosticsHotnessThreshold ||
-           *Opts.DiagnosticsHotnessThreshold > 0) &&
+      if ((!Opts.DiagnosticsHotnessThreshold.hasValue() ||
+           Opts.DiagnosticsHotnessThreshold.getValue() > 0) &&
           !UsingProfile)
         Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
             << "-fdiagnostics-hotness-threshold=";
@@ -1968,8 +1968,8 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
           << "-fdiagnostics-misexpect-tolerance=";
     } else {
       Opts.DiagnosticsMisExpectTolerance = *ResultOrErr;
-      if ((!Opts.DiagnosticsMisExpectTolerance ||
-           *Opts.DiagnosticsMisExpectTolerance > 0) &&
+      if ((!Opts.DiagnosticsMisExpectTolerance.hasValue() ||
+           Opts.DiagnosticsMisExpectTolerance.getValue() > 0) &&
           !UsingProfile)
         Diags.Report(diag::warn_drv_diagnostics_misexpect_requires_pgo)
             << "-fdiagnostics-misexpect-tolerance=";
@@ -2578,10 +2578,10 @@ static void GenerateFrontendArgs(const FrontendOptions &Opts,
   for (const auto &ModuleFile : Opts.ModuleFiles)
     GenerateArg(Args, OPT_fmodule_file, ModuleFile, SA);
 
-  if (Opts.AuxTargetCPU)
+  if (Opts.AuxTargetCPU.hasValue())
     GenerateArg(Args, OPT_aux_target_cpu, *Opts.AuxTargetCPU, SA);
 
-  if (Opts.AuxTargetFeatures)
+  if (Opts.AuxTargetFeatures.hasValue())
     for (const auto &Feature : *Opts.AuxTargetFeatures)
       GenerateArg(Args, OPT_aux_target_feature, Feature, SA);
 

diff  --git a/clang/lib/Frontend/InitPreprocessor.cpp b/clang/lib/Frontend/InitPreprocessor.cpp
index 033f332b24361..1032cb2e8e0ef 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -831,12 +831,12 @@ static void InitializePredefinedMacros(const TargetInfo &TI,
       VersionTuple tuple = LangOpts.ObjCRuntime.getVersion();
 
       unsigned minor = 0;
-      if (tuple.getMinor())
-        minor = *tuple.getMinor();
+      if (tuple.getMinor().hasValue())
+        minor = tuple.getMinor().getValue();
 
       unsigned subminor = 0;
-      if (tuple.getSubminor())
-        subminor = *tuple.getSubminor();
+      if (tuple.getSubminor().hasValue())
+        subminor = tuple.getSubminor().getValue();
 
       Builder.defineMacro("__OBJFW_RUNTIME_ABI__",
                           Twine(tuple.getMajor() * 10000 + minor * 100 +

diff  --git a/clang/lib/Lex/DependencyDirectivesScanner.cpp b/clang/lib/Lex/DependencyDirectivesScanner.cpp
index d7c40e2c29099..d8583841c607b 100644
--- a/clang/lib/Lex/DependencyDirectivesScanner.cpp
+++ b/clang/lib/Lex/DependencyDirectivesScanner.cpp
@@ -549,8 +549,8 @@ Scanner::tryLexIdentifierOrSkipLine(const char *&First, const char *const End) {
 
 StringRef Scanner::lexIdentifier(const char *&First, const char *const End) {
   Optional<StringRef> Id = tryLexIdentifierOrSkipLine(First, End);
-  assert(Id && "expected identifier token");
-  return *Id;
+  assert(Id.hasValue() && "expected identifier token");
+  return Id.getValue();
 }
 
 bool Scanner::isNextIdentifierOrSkipLine(StringRef Id, const char *&First,

diff  --git a/clang/lib/Lex/MacroInfo.cpp b/clang/lib/Lex/MacroInfo.cpp
index 54445d9754472..4a8127d29a459 100644
--- a/clang/lib/Lex/MacroInfo.cpp
+++ b/clang/lib/Lex/MacroInfo.cpp
@@ -209,11 +209,12 @@ MacroDirective::DefInfo MacroDirective::getDefinition() {
     }
 
     VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD);
-    if (!isPublic)
+    if (!isPublic.hasValue())
       isPublic = VisMD->isPublic();
   }
 
-  return DefInfo(nullptr, UndefLoc, !isPublic || *isPublic);
+  return DefInfo(nullptr, UndefLoc,
+                 !isPublic.hasValue() || isPublic.getValue());
 }
 
 const MacroDirective::DefInfo

diff  --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp
index 57e344622f25a..c791e3e4e5ca9 100644
--- a/clang/lib/Lex/ModuleMap.cpp
+++ b/clang/lib/Lex/ModuleMap.cpp
@@ -1219,8 +1219,8 @@ void ModuleMap::resolveHeaderDirectives(
     Module *Mod, llvm::Optional<const FileEntry *> File) const {
   bool NeedsFramework = false;
   SmallVector<Module::UnresolvedHeaderDirective, 1> NewHeaders;
-  const auto Size = File ? File.value()->getSize() : 0;
-  const auto ModTime = File ? File.value()->getModificationTime() : 0;
+  const auto Size = File ? File.getValue()->getSize() : 0;
+  const auto ModTime = File ? File.getValue()->getModificationTime() : 0;
 
   for (auto &Header : Mod->UnresolvedHeaders) {
     if (File && ((Header.ModTime && Header.ModTime != ModTime) ||

diff  --git a/clang/lib/Lex/PPMacroExpansion.cpp b/clang/lib/Lex/PPMacroExpansion.cpp
index fb0d67d0556b0..49e14732b3c23 100644
--- a/clang/lib/Lex/PPMacroExpansion.cpp
+++ b/clang/lib/Lex/PPMacroExpansion.cpp
@@ -1325,11 +1325,11 @@ static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
 
         // The last ')' has been reached; return the value if one found or
         // a diagnostic and a dummy value.
-        if (Result) {
-          OS << *Result;
+        if (Result.hasValue()) {
+          OS << Result.getValue();
           // For strict conformance to __has_cpp_attribute rules, use 'L'
           // suffix for dated literals.
-          if (*Result > 1)
+          if (Result.getValue() > 1)
             OS << 'L';
         } else {
           OS << 0;

diff  --git a/clang/lib/Lex/PreprocessingRecord.cpp b/clang/lib/Lex/PreprocessingRecord.cpp
index 66610c4892411..432068b35f19c 100644
--- a/clang/lib/Lex/PreprocessingRecord.cpp
+++ b/clang/lib/Lex/PreprocessingRecord.cpp
@@ -114,8 +114,8 @@ bool PreprocessingRecord::isEntityInFileID(iterator PPEI, FileID FID) {
     // deserializing it.
     Optional<bool> IsInFile =
         ExternalSource->isPreprocessedEntityInFileID(LoadedIndex, FID);
-    if (IsInFile)
-      return *IsInFile;
+    if (IsInFile.hasValue())
+      return IsInFile.getValue();
 
     // The external source did not provide a definite answer, go and deserialize
     // the entity to check it.

diff  --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp
index d508d2d1bfe38..1fa82a19d88d4 100644
--- a/clang/lib/Parse/ParseOpenMP.cpp
+++ b/clang/lib/Parse/ParseOpenMP.cpp
@@ -1873,13 +1873,14 @@ void Parser::ParseOMPDeclareTargetClauses(
       if (IsDeviceTypeClause) {
         Optional<SimpleClauseData> DevTypeData =
             parseOpenMPSimpleClause(*this, OMPC_device_type);
-        if (DevTypeData) {
+        if (DevTypeData.hasValue()) {
           if (DeviceTypeLoc.isValid()) {
             // We already saw another device_type clause, diagnose it.
-            Diag(DevTypeData->Loc, diag::warn_omp_more_one_device_type_clause);
+            Diag(DevTypeData.getValue().Loc,
+                 diag::warn_omp_more_one_device_type_clause);
             break;
           }
-          switch (static_cast<OpenMPDeviceType>(DevTypeData->Type)) {
+          switch (static_cast<OpenMPDeviceType>(DevTypeData.getValue().Type)) {
           case OMPC_DEVICE_TYPE_any:
             DTCI.DT = OMPDeclareTargetDeclAttr::DT_Any;
             break;
@@ -2312,9 +2313,9 @@ Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl(
     Sema::DeclareTargetContextInfo DTCI(DKind, DTLoc);
     if (HasClauses)
       ParseOMPDeclareTargetClauses(DTCI);
-    bool HasImplicitMappings = DKind == OMPD_begin_declare_target ||
-                               !HasClauses ||
-                               (DTCI.ExplicitlyMapped.empty() && DTCI.Indirect);
+    bool HasImplicitMappings =
+        DKind == OMPD_begin_declare_target || !HasClauses ||
+        (DTCI.ExplicitlyMapped.empty() && DTCI.Indirect.hasValue());
 
     // Skip the last annot_pragma_openmp_end.
     ConsumeAnyToken();
@@ -3619,18 +3620,20 @@ OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind,
   if (!Val || ParseOnly)
     return nullptr;
   if (getLangOpts().OpenMP < 51 && Kind == OMPC_default &&
-      (static_cast<DefaultKind>(Val->Type) == OMP_DEFAULT_private ||
-       static_cast<DefaultKind>(Val->Type) == OMP_DEFAULT_firstprivate)) {
-    Diag(Val->LOpen, diag::err_omp_invalid_dsa)
-        << getOpenMPClauseName(static_cast<DefaultKind>(Val->Type) ==
+      (static_cast<DefaultKind>(Val.getValue().Type) == OMP_DEFAULT_private ||
+       static_cast<DefaultKind>(Val.getValue().Type) ==
+           OMP_DEFAULT_firstprivate)) {
+    Diag(Val.getValue().LOpen, diag::err_omp_invalid_dsa)
+        << getOpenMPClauseName(static_cast<DefaultKind>(Val.getValue().Type) ==
                                        OMP_DEFAULT_private
                                    ? OMPC_private
                                    : OMPC_firstprivate)
         << getOpenMPClauseName(OMPC_default) << "5.1";
     return nullptr;
   }
-  return Actions.ActOnOpenMPSimpleClause(Kind, Val->Type, Val->TypeLoc,
-                                         Val->LOpen, Val->Loc, Val->RLoc);
+  return Actions.ActOnOpenMPSimpleClause(
+      Kind, Val.getValue().Type, Val.getValue().TypeLoc, Val.getValue().LOpen,
+      Val.getValue().Loc, Val.getValue().RLoc);
 }
 
 /// Parsing of OpenMP clauses like 'ordered'.

diff  --git a/clang/lib/Sema/SemaCUDA.cpp b/clang/lib/Sema/SemaCUDA.cpp
index a0bc1b5142692..a3b15fe7e90b6 100644
--- a/clang/lib/Sema/SemaCUDA.cpp
+++ b/clang/lib/Sema/SemaCUDA.cpp
@@ -381,12 +381,13 @@ bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
       InferredTarget = BaseMethodTarget;
     } else {
       bool ResolutionError = resolveCalleeCUDATargetConflict(
-          *InferredTarget, BaseMethodTarget, InferredTarget.getPointer());
+          InferredTarget.getValue(), BaseMethodTarget,
+          InferredTarget.getPointer());
       if (ResolutionError) {
         if (Diagnose) {
           Diag(ClassDecl->getLocation(),
                diag::note_implicit_member_target_infer_collision)
-              << (unsigned)CSM << *InferredTarget << BaseMethodTarget;
+              << (unsigned)CSM << InferredTarget.getValue() << BaseMethodTarget;
         }
         MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
         return true;
@@ -424,12 +425,14 @@ bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
       InferredTarget = FieldMethodTarget;
     } else {
       bool ResolutionError = resolveCalleeCUDATargetConflict(
-          *InferredTarget, FieldMethodTarget, InferredTarget.getPointer());
+          InferredTarget.getValue(), FieldMethodTarget,
+          InferredTarget.getPointer());
       if (ResolutionError) {
         if (Diagnose) {
           Diag(ClassDecl->getLocation(),
                diag::note_implicit_member_target_infer_collision)
-              << (unsigned)CSM << *InferredTarget << FieldMethodTarget;
+              << (unsigned)CSM << InferredTarget.getValue()
+              << FieldMethodTarget;
         }
         MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
         return true;
@@ -441,10 +444,10 @@ bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
   // If no target was inferred, mark this member as __host__ __device__;
   // it's the least restrictive option that can be invoked from any target.
   bool NeedsH = true, NeedsD = true;
-  if (InferredTarget) {
-    if (*InferredTarget == CFT_Device)
+  if (InferredTarget.hasValue()) {
+    if (InferredTarget.getValue() == CFT_Device)
       NeedsH = false;
-    else if (*InferredTarget == CFT_Host)
+    else if (InferredTarget.getValue() == CFT_Host)
       NeedsD = false;
   }
 

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index c83f648f39b00..28cfdfca4f3c7 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -1873,9 +1873,9 @@ static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
       return 2;
     return llvm::Optional<unsigned>{};
   }();
-  if (DiagSelect) {
+  if (DiagSelect.hasValue()) {
     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
-        << *DiagSelect << TheCall->getSourceRange();
+        << DiagSelect.getValue() << TheCall->getSourceRange();
     return ExprError();
   }
 

diff  --git a/clang/lib/Sema/SemaCodeComplete.cpp b/clang/lib/Sema/SemaCodeComplete.cpp
index 86bad736227d7..8c9ed53894882 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -5362,8 +5362,8 @@ class ConceptInfo {
       // Overwrite existing if the new member has more info.
       // The preference of . vs :: vs -> is fairly arbitrary.
       if (/*Inserted*/ R.second ||
-          std::make_tuple(M.ArgTypes.has_value(), M.ResultType != nullptr,
-                          M.Operator) > std::make_tuple(O.ArgTypes.has_value(),
+          std::make_tuple(M.ArgTypes.hasValue(), M.ResultType != nullptr,
+                          M.Operator) > std::make_tuple(O.ArgTypes.hasValue(),
                                                         O.ResultType != nullptr,
                                                         O.Operator))
         O = std::move(M);

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index c9c32f9440fba..2e0620785b551 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -15444,9 +15444,9 @@ void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
   //   (3.1) If the allocation function takes an argument of type
   //         std​::​align_­val_­t, the storage will have the alignment
   //         specified by the value of this argument.
-  if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
+  if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
     FD->addAttr(AllocAlignAttr::CreateImplicit(
-        Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
+        Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
   }
 
   // FIXME:
@@ -19102,12 +19102,12 @@ Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
     //  #pragma omp declare target to(*) device_type(*).
     // Therefore DevTy having no value does not imply host. The emission status
     // will be checked again at the end of compilation unit with Final = true.
-    if (DevTy)
+    if (DevTy.hasValue())
       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
         return FunctionEmissionStatus::OMPDiscarded;
     // If we have an explicit value for the device type, or we are in a target
     // declare context, we need to emit all extern and used symbols.
-    if (isInOpenMPDeclareTargetContext() || DevTy)
+    if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
       if (IsEmittedForExternalSymbol())
         return FunctionEmissionStatus::Emitted;
     // Device mode only emits what it must, if it wasn't tagged yet and needed,

diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 942e7f18ec40e..73a4be54861b6 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -2673,19 +2673,19 @@ static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
         if (IOSToWatchOSMapping) {
           if (auto MappedVersion = IOSToWatchOSMapping->map(
                   Version, MinimumWatchOSVersion, None)) {
-            return *MappedVersion;
+            return MappedVersion.getValue();
           }
         }
 
         auto Major = Version.getMajor();
         auto NewMajor = Major >= 9 ? Major - 7 : 0;
         if (NewMajor >= 2) {
-          if (Version.getMinor()) {
-            if (Version.getSubminor())
-              return VersionTuple(NewMajor, *Version.getMinor(),
-                                  *Version.getSubminor());
+          if (Version.getMinor().hasValue()) {
+            if (Version.getSubminor().hasValue())
+              return VersionTuple(NewMajor, Version.getMinor().getValue(),
+                                  Version.getSubminor().getValue());
             else
-              return VersionTuple(NewMajor, *Version.getMinor());
+              return VersionTuple(NewMajor, Version.getMinor().getValue());
           }
           return VersionTuple(NewMajor);
         }

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 1e7975ed513f1..bb1cf4b941b78 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -2274,10 +2274,10 @@ Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
 
     // How many bytes do we want to allocate here?
     llvm::Optional<llvm::APInt> AllocationSize;
-    if (!ArraySize && !AllocType->isDependentType()) {
+    if (!ArraySize.hasValue() && !AllocType->isDependentType()) {
       // For non-array operator new, we only want to allocate one element.
       AllocationSize = SingleEltSize;
-    } else if (KnownArraySize && !AllocType->isDependentType()) {
+    } else if (KnownArraySize.hasValue() && !AllocType->isDependentType()) {
       // For array operator new, only deal with static array size case.
       bool Overflow;
       AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)

diff  --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index fbea99daee598..7395e67505ff5 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -822,29 +822,29 @@ class DSAStackTy {
   /// false - otherwise.
   bool isOrderedRegion() const {
     if (const SharingMapTy *Top = getTopOfStackOrNull())
-      return Top->OrderedRegion.has_value();
+      return Top->OrderedRegion.hasValue();
     return false;
   }
   /// Returns optional parameter for the ordered region.
   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
     if (const SharingMapTy *Top = getTopOfStackOrNull())
-      if (Top->OrderedRegion)
-        return *Top->OrderedRegion;
+      if (Top->OrderedRegion.hasValue())
+        return Top->OrderedRegion.getValue();
     return std::make_pair(nullptr, nullptr);
   }
   /// Returns true, if parent region is ordered (has associated
   /// 'ordered' clause), false - otherwise.
   bool isParentOrderedRegion() const {
     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
-      return Parent->OrderedRegion.has_value();
+      return Parent->OrderedRegion.hasValue();
     return false;
   }
   /// Returns optional parameter for the ordered region.
   std::pair<const Expr *, OMPOrderedClause *>
   getParentOrderedRegionParam() const {
     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
-      if (Parent->OrderedRegion)
-        return *Parent->OrderedRegion;
+      if (Parent->OrderedRegion.hasValue())
+        return Parent->OrderedRegion.getValue();
     return std::make_pair(nullptr, nullptr);
   }
   /// Marks current region as nowait (it has a 'nowait' clause).
@@ -7653,9 +7653,9 @@ class OpenMPIterationSpaceChecker {
   /// Return true if any expression is dependent.
   bool dependent() const;
   /// Returns true if the initializer forms non-rectangular loop.
-  bool doesInitDependOnLC() const { return InitDependOnLC.has_value(); }
+  bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
   /// Returns true if the condition forms non-rectangular loop.
-  bool doesCondDependOnLC() const { return CondDependOnLC.has_value(); }
+  bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
   unsigned getLoopDependentIdx() const {
     return InitDependOnLC.value_or(CondDependOnLC.value_or(0));
@@ -7761,20 +7761,21 @@ bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
     bool IsConstZero = Result && !Result->getBoolValue();
 
     // != with increment is treated as <; != with decrement is treated as >
-    if (!TestIsLessOp)
+    if (!TestIsLessOp.hasValue())
       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
-    if (UB && (IsConstZero ||
-               (*TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
-                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
+    if (UB &&
+        (IsConstZero || (TestIsLessOp.getValue()
+                             ? (IsConstNeg || (IsUnsigned && Subtract))
+                             : (IsConstPos || (IsUnsigned && !Subtract))))) {
       SemaRef.Diag(NewStep->getExprLoc(),
                    diag::err_omp_loop_incr_not_compatible)
-          << LCDecl << *TestIsLessOp << NewStep->getSourceRange();
+          << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
       SemaRef.Diag(ConditionLoc,
                    diag::note_omp_loop_cond_requres_compatible_incr)
-          << *TestIsLessOp << ConditionSrcRange;
+          << TestIsLessOp.getValue() << ConditionSrcRange;
       return true;
     }
-    if (*TestIsLessOp == Subtract) {
+    if (TestIsLessOp.getValue() == Subtract) {
       NewStep =
           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
               .get();
@@ -8529,8 +8530,8 @@ Expr *OpenMPIterationSpaceChecker::buildNumIterations(
       UBVal = MinUB.get();
     }
   }
-  Expr *UBExpr = *TestIsLessOp ? UBVal : LBVal;
-  Expr *LBExpr = *TestIsLessOp ? LBVal : UBVal;
+  Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
+  Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
   if (!Upper || !Lower)
@@ -8593,12 +8594,12 @@ std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
   // init value.
   Expr *MinExpr = nullptr;
   Expr *MaxExpr = nullptr;
-  Expr *LBExpr = *TestIsLessOp ? LB : UB;
-  Expr *UBExpr = *TestIsLessOp ? UB : LB;
-  bool LBNonRect =
-      *TestIsLessOp ? InitDependOnLC.has_value() : CondDependOnLC.has_value();
-  bool UBNonRect =
-      *TestIsLessOp ? CondDependOnLC.has_value() : InitDependOnLC.has_value();
+  Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
+  Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
+  bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
+                                           : CondDependOnLC.hasValue();
+  bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
+                                           : InitDependOnLC.hasValue();
   Expr *Lower =
       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
   Expr *Upper =
@@ -8720,11 +8721,11 @@ Expr *OpenMPIterationSpaceChecker::buildPreCond(
   if (!NewLB.isUsable() || !NewUB.isUsable())
     return nullptr;
 
-  ExprResult CondExpr =
-      SemaRef.BuildBinOp(S, DefaultLoc,
-                         *TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
-                                       : (TestIsStrictOp ? BO_GT : BO_GE),
-                         NewLB.get(), NewUB.get());
+  ExprResult CondExpr = SemaRef.BuildBinOp(
+      S, DefaultLoc,
+      TestIsLessOp.getValue() ? (TestIsStrictOp ? BO_LT : BO_LE)
+                              : (TestIsStrictOp ? BO_GT : BO_GE),
+      NewLB.get(), NewUB.get());
   if (CondExpr.isUsable()) {
     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
                                                 SemaRef.Context.BoolTy))
@@ -8799,10 +8800,12 @@ Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
       !SemaRef.getLangOpts().CPlusPlus)
     return nullptr;
   // Upper - Lower
-  Expr *Upper =
-      *TestIsLessOp ? Cnt : tryBuildCapture(SemaRef, LB, Captures).get();
-  Expr *Lower =
-      *TestIsLessOp ? tryBuildCapture(SemaRef, LB, Captures).get() : Cnt;
+  Expr *Upper = TestIsLessOp.getValue()
+                    ? Cnt
+                    : tryBuildCapture(SemaRef, LB, Captures).get();
+  Expr *Lower = TestIsLessOp.getValue()
+                    ? tryBuildCapture(SemaRef, LB, Captures).get()
+                    : Cnt;
   if (!Upper || !Lower)
     return nullptr;
 
@@ -22177,27 +22180,27 @@ void Sema::ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
   auto *VD = cast<ValueDecl>(ND);
   llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
       OMPDeclareTargetDeclAttr::getActiveAttr(VD);
-  if (ActiveAttr && (*ActiveAttr)->getDevType() != DTCI.DT &&
-      (*ActiveAttr)->getLevel() == Level) {
+  if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DTCI.DT &&
+      ActiveAttr.getValue()->getLevel() == Level) {
     Diag(Loc, diag::err_omp_device_type_mismatch)
         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DTCI.DT)
         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(
-               ActiveAttr.value()->getDevType());
+               ActiveAttr.getValue()->getDevType());
     return;
   }
-  if (ActiveAttr && (*ActiveAttr)->getMapType() != MT &&
-      (*ActiveAttr)->getLevel() == Level) {
+  if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT &&
+      ActiveAttr.getValue()->getLevel() == Level) {
     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
     return;
   }
 
-  if (ActiveAttr && (*ActiveAttr)->getLevel() == Level)
+  if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level)
     return;
 
   Expr *IndirectE = nullptr;
   bool IsIndirect = false;
-  if (DTCI.Indirect) {
-    IndirectE = *DTCI.Indirect;
+  if (DTCI.Indirect.hasValue()) {
+    IndirectE = DTCI.Indirect.getValue();
     if (!IndirectE)
       IsIndirect = true;
   }
@@ -22291,13 +22294,13 @@ void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
         llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
             OMPDeclareTargetDeclAttr::getActiveAttr(VD);
         unsigned Level = DeclareTargetNesting.size();
-        if (ActiveAttr && (*ActiveAttr)->getLevel() >= Level)
+        if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level)
           return;
         DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back();
         Expr *IndirectE = nullptr;
         bool IsIndirect = false;
-        if (DTCI.Indirect) {
-          IndirectE = *DTCI.Indirect;
+        if (DTCI.Indirect.hasValue()) {
+          IndirectE = DTCI.Indirect.getValue();
           if (!IndirectE)
             IsIndirect = true;
         }

diff  --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 4352e7ec1c6d7..d7558017948a2 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -469,8 +469,8 @@ static void instantiateOMPDeclareVariantAttr(
   if (!DeclVarData)
     return;
 
-  E = DeclVarData->second;
-  FD = DeclVarData->first;
+  E = DeclVarData.getValue().second;
+  FD = DeclVarData.getValue().first;
 
   if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
     if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {

diff  --git a/clang/lib/Serialization/ASTWriter.cpp b/clang/lib/Serialization/ASTWriter.cpp
index f58f166db7af1..1787909bb6f77 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -1888,8 +1888,8 @@ void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
         // without this file existing on disk.
         if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
           PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
-              << WritingModule->getFullModuleName() << U.Size.has_value()
-              << U.FileName;
+            << WritingModule->getFullModuleName() << U.Size.hasValue()
+            << U.FileName;
           continue;
         }
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
index 16e0b8a3fe3d9..970bfd2d241cc 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
@@ -766,10 +766,10 @@ void VariadicMethodTypeChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
       continue;
 
     // Generate only one error node to use for all bug reports.
-    if (!errorNode)
+    if (!errorNode.hasValue())
       errorNode = C.generateNonFatalErrorNode();
 
-    if (!*errorNode)
+    if (!errorNode.getValue())
       continue;
 
     SmallString<128> sbuf;
@@ -786,8 +786,8 @@ void VariadicMethodTypeChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
     ArgTy.print(os, C.getLangOpts());
     os << "'";
 
-    auto R =
-        std::make_unique<PathSensitiveBugReport>(*BT, os.str(), *errorNode);
+    auto R = std::make_unique<PathSensitiveBugReport>(*BT, os.str(),
+                                                      errorNode.getValue());
     R->addRange(msg.getArgSourceRange(I));
     C.emitReport(std::move(R));
   }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp
index dbfdff4d2a3b1..0e273771498cc 100644
--- a/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp
@@ -272,12 +272,12 @@ ProgramStateRef GTestChecker::assumeValuesEqual(SVal Val1, SVal Val2,
                                                 CheckerContext &C) {
   auto DVal1 = Val1.getAs<DefinedOrUnknownSVal>();
   auto DVal2 = Val2.getAs<DefinedOrUnknownSVal>();
-  if (!DVal1 || !DVal2)
+  if (!DVal1.hasValue() || !DVal2.hasValue())
     return State;
 
   auto ValuesEqual =
       C.getSValBuilder().evalEQ(State, *DVal1, *DVal2).getAs<DefinedSVal>();
-  if (!ValuesEqual)
+  if (!ValuesEqual.hasValue())
     return State;
 
   State = C.getConstraintManager().assume(State, *ValuesEqual, true);

diff  --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
index 2aeb32d074906..552d042483393 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -1190,8 +1190,8 @@ MallocChecker::performKernelMalloc(const CallEvent &Call, CheckerContext &C,
 
   NonLoc Flags = V.castAs<NonLoc>();
   NonLoc ZeroFlag = C.getSValBuilder()
-                        .makeIntVal(*KernelZeroFlagVal, FlagsEx->getType())
-                        .castAs<NonLoc>();
+      .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
+      .castAs<NonLoc>();
   SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
                                                       Flags, ZeroFlag,
                                                       FlagsEx->getType());
@@ -1238,8 +1238,8 @@ void MallocChecker::checkKernelMalloc(const CallEvent &Call,
   ProgramStateRef State = C.getState();
   llvm::Optional<ProgramStateRef> MaybeState =
       performKernelMalloc(Call, C, State);
-  if (MaybeState)
-    State = *MaybeState;
+  if (MaybeState.hasValue())
+    State = MaybeState.getValue();
   else
     State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State,
                          AF_Malloc);
@@ -3571,13 +3571,13 @@ void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
       const RefState *RefS = State->get<RegionState>(I.getKey());
       AllocationFamily Family = RefS->getAllocationFamily();
       Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
-      if (!CheckKind)
-        CheckKind = getCheckIfTracked(Family, true);
+      if (!CheckKind.hasValue())
+         CheckKind = getCheckIfTracked(Family, true);
 
       I.getKey()->dumpToStream(Out);
       Out << " : ";
       I.getData().dump(Out);
-      if (CheckKind)
+      if (CheckKind.hasValue())
         Out << " (" << CheckNames[*CheckKind].getName() << ")";
       Out << NL;
     }

diff  --git a/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp
index fd47e19cb786c..3481936e572bf 100644
--- a/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp
@@ -136,10 +136,10 @@ void NonNullParamChecker::checkPreCall(const CallEvent &Call,
     if (!DV)
       continue;
 
-    assert(!HasRefTypeParam || isa<Loc>(*DV));
+    assert(!HasRefTypeParam || isa<Loc>(DV.getValue()));
 
     // Process the case when the argument is not a location.
-    if (ExpectedToBeNonNull && !isa<Loc>(*DV)) {
+    if (ExpectedToBeNonNull && !isa<Loc>(DV.getValue())) {
       // If the argument is a union type, we want to handle a potential
       // transparent_union GCC extension.
       if (!ArgE)

diff  --git a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
index 19b63a17191ca..9da44d5c0d394 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -234,8 +234,7 @@ void UnixAPIMisuseChecker::CheckOpenVariant(CheckerContext &C,
   }
   NonLoc oflags = V.castAs<NonLoc>();
   NonLoc ocreateFlag = C.getSValBuilder()
-                           .makeIntVal(*Val_O_CREAT, oflagsEx->getType())
-                           .castAs<NonLoc>();
+      .makeIntVal(Val_O_CREAT.getValue(), oflagsEx->getType()).castAs<NonLoc>();
   SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
                                                       oflags, ocreateFlag,
                                                       oflagsEx->getType());

diff  --git a/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp b/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
index 3b01ec6e24029..de94cb7c978da 100644
--- a/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
+++ b/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
@@ -77,8 +77,8 @@ AnalyzerOptions::getExplorationStrategy() const {
           .Case("bfs_block_dfs_contents",
                 ExplorationStrategyKind::BFSBlockDFSContents)
           .Default(None);
-  assert(K && "User mode is invalid.");
-  return *K;
+  assert(K.hasValue() && "User mode is invalid.");
+  return K.getValue();
 }
 
 CTUPhase1InliningKind AnalyzerOptions::getCTUPhase1Inlining() const {
@@ -88,8 +88,8 @@ CTUPhase1InliningKind AnalyzerOptions::getCTUPhase1Inlining() const {
                .Case("small", CTUPhase1InliningKind::Small)
                .Case("all", CTUPhase1InliningKind::All)
                .Default(None);
-  assert(K && "CTU inlining mode is invalid.");
-  return *K;
+  assert(K.hasValue() && "CTU inlining mode is invalid.");
+  return K.getValue();
 }
 
 IPAKind AnalyzerOptions::getIPAMode() const {
@@ -100,9 +100,9 @@ IPAKind AnalyzerOptions::getIPAMode() const {
           .Case("dynamic", IPAK_DynamicDispatch)
           .Case("dynamic-bifurcate", IPAK_DynamicDispatchBifurcate)
           .Default(None);
-  assert(K && "IPA Mode is invalid.");
+  assert(K.hasValue() && "IPA Mode is invalid.");
 
-  return *K;
+  return K.getValue();
 }
 
 bool

diff  --git a/clang/lib/StaticAnalyzer/Core/BugReporter.cpp b/clang/lib/StaticAnalyzer/Core/BugReporter.cpp
index 4d6b82e63f6a4..a2efe14f10453 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporter.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporter.cpp
@@ -2363,15 +2363,15 @@ PathSensitiveBugReport::getInterestingnessKind(const MemRegion *R) const {
 }
 
 bool PathSensitiveBugReport::isInteresting(SVal V) const {
-  return getInterestingnessKind(V).has_value();
+  return getInterestingnessKind(V).hasValue();
 }
 
 bool PathSensitiveBugReport::isInteresting(SymbolRef sym) const {
-  return getInterestingnessKind(sym).has_value();
+  return getInterestingnessKind(sym).hasValue();
 }
 
 bool PathSensitiveBugReport::isInteresting(const MemRegion *R) const {
-  return getInterestingnessKind(R).has_value();
+  return getInterestingnessKind(R).hasValue();
 }
 
 bool PathSensitiveBugReport::isInteresting(const LocationContext *LC)  const {

diff  --git a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
index 9d89069b239e4..339a675ed1baf 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -2949,8 +2949,8 @@ PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
 
   PathDiagnosticLocation Loc(Cond, SM, LCtx);
   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Message);
-  if (shouldPrune)
-    event->setPrunable(*shouldPrune);
+  if (shouldPrune.hasValue())
+    event->setPrunable(shouldPrune.getValue());
   return event;
 }
 
@@ -3084,9 +3084,9 @@ bool ConditionBRVisitor::printValue(const Expr *CondVarExpr, raw_ostream &Out,
       Out << (TookTrue ? "not equal to 0" : "0");
   } else {
     if (Ty->isBooleanType())
-      Out << (IntValue.value()->getBoolValue() ? "true" : "false");
+      Out << (IntValue.getValue()->getBoolValue() ? "true" : "false");
     else
-      Out << *IntValue.value();
+      Out << *IntValue.getValue();
   }
 
   return true;
@@ -3279,10 +3279,10 @@ void FalsePositiveRefutationBRVisitor::finalizeVisitor(
 
   // And check for satisfiability
   Optional<bool> IsSAT = RefutationSolver->check();
-  if (!IsSAT)
+  if (!IsSAT.hasValue())
     return;
 
-  if (!*IsSAT)
+  if (!IsSAT.getValue())
     BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext());
 }
 

diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
index b03af13622542..326a3b1fb665f 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
@@ -1015,8 +1015,8 @@ bool ExprEngine::shouldInlineCall(const CallEvent &Call, const Decl *D,
 
   // Check if this function has been marked as non-inlinable.
   Optional<bool> MayInline = Engine.FunctionSummaries->mayInline(D);
-  if (MayInline) {
-    if (!*MayInline)
+  if (MayInline.hasValue()) {
+    if (!MayInline.getValue())
       return false;
 
   } else {

diff  --git a/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp b/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
index 56f441ec2c8f2..93c19a688b9a8 100644
--- a/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
+++ b/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
@@ -407,11 +407,11 @@ void PlistPrinter::ReportMacroExpansions(raw_ostream &o, unsigned indent) {
 
     // Output the macro name.
     Indent(o, indent) << "<key>name</key>";
-    EmitString(o, *MacroName) << '\n';
+    EmitString(o, MacroName.getValue()) << '\n';
 
     // Output what it expands into.
     Indent(o, indent) << "<key>expansion</key>";
-    EmitString(o, *ExpansionText) << '\n';
+    EmitString(o, ExpansionText.getValue()) << '\n';
 
     // Finish up.
     --indent;

diff  --git a/clang/lib/Support/RISCVVIntrinsicUtils.cpp b/clang/lib/Support/RISCVVIntrinsicUtils.cpp
index 3f7c1315a4846..ebfe1a168936b 100644
--- a/clang/lib/Support/RISCVVIntrinsicUtils.cpp
+++ b/clang/lib/Support/RISCVVIntrinsicUtils.cpp
@@ -114,11 +114,11 @@ bool RVVType::verifyType() const {
     return false;
   if (isScalar())
     return true;
-  if (!Scale)
+  if (!Scale.hasValue())
     return false;
   if (isFloat() && ElementBitwidth == 8)
     return false;
-  unsigned V = *Scale;
+  unsigned V = Scale.getValue();
   switch (ElementBitwidth) {
   case 1:
   case 8:
@@ -799,10 +799,10 @@ RVVType::computeTypes(BasicType BT, int Log2LMUL, unsigned NF,
   RVVTypes Types;
   for (const PrototypeDescriptor &Proto : Prototype) {
     auto T = computeType(BT, Log2LMUL, Proto);
-    if (!T)
+    if (!T.hasValue())
       return llvm::None;
     // Record legal type index
-    Types.push_back(*T);
+    Types.push_back(T.getValue());
   }
   return Types;
 }

diff  --git a/clang/lib/Tooling/Core/Replacement.cpp b/clang/lib/Tooling/Core/Replacement.cpp
index aca2afceea446..30e1923bf1cb7 100644
--- a/clang/lib/Tooling/Core/Replacement.cpp
+++ b/clang/lib/Tooling/Core/Replacement.cpp
@@ -179,9 +179,9 @@ static std::string getReplacementErrString(replacement_error Err) {
 
 std::string ReplacementError::message() const {
   std::string Message = getReplacementErrString(Err);
-  if (NewReplacement)
+  if (NewReplacement.hasValue())
     Message += "\nNew replacement: " + NewReplacement->toString();
-  if (ExistingReplacement)
+  if (ExistingReplacement.hasValue())
     Message += "\nExisting replacement: " + ExistingReplacement->toString();
   return Message;
 }

diff  --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp
index 7231297f27575..fa1f09b44f4da 100644
--- a/clang/tools/driver/driver.cpp
+++ b/clang/tools/driver/driver.cpp
@@ -406,18 +406,18 @@ int clang_main(int Argc, char **Argv) {
   if (ClangCLMode) {
     // Arguments in "CL" are prepended.
     llvm::Optional<std::string> OptCL = llvm::sys::Process::GetEnv("CL");
-    if (OptCL) {
+    if (OptCL.hasValue()) {
       SmallVector<const char *, 8> PrependedOpts;
-      getCLEnvVarOptions(*OptCL, Saver, PrependedOpts);
+      getCLEnvVarOptions(OptCL.getValue(), Saver, PrependedOpts);
 
       // Insert right after the program name to prepend to the argument list.
       Args.insert(Args.begin() + 1, PrependedOpts.begin(), PrependedOpts.end());
     }
     // Arguments in "_CL_" are appended.
     llvm::Optional<std::string> Opt_CL_ = llvm::sys::Process::GetEnv("_CL_");
-    if (Opt_CL_) {
+    if (Opt_CL_.hasValue()) {
       SmallVector<const char *, 8> AppendedOpts;
-      getCLEnvVarOptions(*Opt_CL_, Saver, AppendedOpts);
+      getCLEnvVarOptions(Opt_CL_.getValue(), Saver, AppendedOpts);
 
       // Insert at the end of the argument list to append.
       Args.append(AppendedOpts.begin(), AppendedOpts.end());

diff  --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index 8d6c16efc3d0d..cba265b1d7d41 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -536,9 +536,9 @@ bool CursorVisitor::VisitChildren(CXCursor Cursor) {
                                            TLEnd = CXXUnit->top_level_end();
                TL != TLEnd; ++TL) {
             const Optional<bool> V = handleDeclForVisitation(*TL);
-            if (!V)
+            if (!V.hasValue())
               continue;
-            return *V;
+            return V.getValue();
           }
         } else if (VisitDeclContext(
                        CXXUnit->getASTContext().getTranslationUnitDecl()))
@@ -641,9 +641,9 @@ bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
         if (OMD->isSynthesizedAccessorStub())
           continue;
     const Optional<bool> V = handleDeclForVisitation(D);
-    if (!V)
+    if (!V.hasValue())
       continue;
-    return *V;
+    return V.getValue();
   }
   return false;
 }
@@ -675,9 +675,9 @@ Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
   }
 
   const Optional<bool> V = shouldVisitCursor(Cursor);
-  if (!V)
+  if (!V.hasValue())
     return None;
-  if (!*V)
+  if (!V.getValue())
     return false;
   if (Visit(Cursor, true))
     return true;
@@ -1074,9 +1074,9 @@ bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
        I != E; ++I) {
     CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
     const Optional<bool> &V = shouldVisitCursor(Cursor);
-    if (!V)
+    if (!V.hasValue())
       continue;
-    if (!*V)
+    if (!V.getValue())
       return false;
     if (Visit(Cursor, true))
       return true;
@@ -8178,13 +8178,13 @@ static CXVersion convertVersion(VersionTuple In) {
   Out.Major = In.getMajor();
 
   Optional<unsigned> Minor = In.getMinor();
-  if (Minor)
+  if (Minor.hasValue())
     Out.Minor = *Minor;
   else
     return Out;
 
   Optional<unsigned> Subminor = In.getSubminor();
-  if (Subminor)
+  if (Subminor.hasValue())
     Out.Subminor = *Subminor;
 
   return Out;

diff  --git a/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp b/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
index 312b9af989e3f..eaba6b762c026 100644
--- a/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
+++ b/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
@@ -449,27 +449,27 @@ TEST(ParserTest, ParseMultiline) {
   )
 )matcher";
     Diagnostics Error;
-    EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error));
+    EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue());
   }
 
   {
     Code = R"matcher(decl(decl()
 , decl()))matcher";
     Diagnostics Error;
-    EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).has_value());
+    EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue());
   }
 
   {
     Code = R"matcher(decl(decl(),
 decl()))matcher";
     Diagnostics Error;
-    EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).has_value());
+    EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue());
   }
 
   {
     Code = "namedDecl(hasName(\"n\"\n))";
     Diagnostics Error;
-    EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).has_value());
+    EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue());
   }
 
   {

diff  --git a/clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp b/clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
index 7c50453abe509..4c5efa7504048 100644
--- a/clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
@@ -40,8 +40,9 @@ isAnnotationDirectlyAfterStatement(const Stmt *Stmt, unsigned AnnotationBegin,
   auto NextToken =
       Lexer::findNextToken(Stmt->getEndLoc(), SourceManager, LangOptions);
 
-  while (NextToken && SourceManager.getFileOffset(NextToken->getLocation()) <
-                          AnnotationBegin) {
+  while (NextToken.hasValue() &&
+         SourceManager.getFileOffset(NextToken->getLocation()) <
+             AnnotationBegin) {
     if (NextToken->isNot(tok::semi))
       return false;
 

diff  --git a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
index 27b767101692e..594764b4e71bd 100644
--- a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -82,8 +82,8 @@ TEST(DataflowAnalysisTest, NoopAnalysis) {
         return NoopAnalysis(C, false);
       }));
   EXPECT_EQ(BlockStates.size(), 2u);
-  EXPECT_TRUE(BlockStates[0].has_value());
-  EXPECT_TRUE(BlockStates[1].has_value());
+  EXPECT_TRUE(BlockStates[0].hasValue());
+  EXPECT_TRUE(BlockStates[1].hasValue());
 }
 
 struct NonConvergingLattice {

diff  --git a/clang/unittests/Analysis/MacroExpansionContextTest.cpp b/clang/unittests/Analysis/MacroExpansionContextTest.cpp
index 88642303cf812..7cee64c1b9b0c 100644
--- a/clang/unittests/Analysis/MacroExpansionContextTest.cpp
+++ b/clang/unittests/Analysis/MacroExpansionContextTest.cpp
@@ -121,14 +121,14 @@ TEST_F(MacroExpansionContextTest, IgnoresPragmas) {
   EXPECT_EQ("\n=============== ExpansionRanges ===============\n",
             dumpExpansionRanges(*Ctx));
 
-  EXPECT_FALSE(Ctx->getExpandedText(at(2, 1)).has_value());
-  EXPECT_FALSE(Ctx->getOriginalText(at(2, 1)).has_value());
+  EXPECT_FALSE(Ctx->getExpandedText(at(2, 1)).hasValue());
+  EXPECT_FALSE(Ctx->getOriginalText(at(2, 1)).hasValue());
 
-  EXPECT_FALSE(Ctx->getExpandedText(at(2, 3)).has_value());
-  EXPECT_FALSE(Ctx->getOriginalText(at(2, 3)).has_value());
+  EXPECT_FALSE(Ctx->getExpandedText(at(2, 3)).hasValue());
+  EXPECT_FALSE(Ctx->getOriginalText(at(2, 3)).hasValue());
 
-  EXPECT_FALSE(Ctx->getExpandedText(at(3, 3)).has_value());
-  EXPECT_FALSE(Ctx->getOriginalText(at(3, 3)).has_value());
+  EXPECT_FALSE(Ctx->getExpandedText(at(3, 3)).hasValue());
+  EXPECT_FALSE(Ctx->getOriginalText(at(3, 3)).hasValue());
 }
 
 TEST_F(MacroExpansionContextTest, NoneForNonExpansionLocations) {
@@ -142,33 +142,33 @@ EMPTY zz
   //      zz
 
   // That's the beginning of the definition of EMPTY.
-  EXPECT_FALSE(Ctx->getExpandedText(at(2, 11)).has_value());
-  EXPECT_FALSE(Ctx->getOriginalText(at(2, 11)).has_value());
+  EXPECT_FALSE(Ctx->getExpandedText(at(2, 11)).hasValue());
+  EXPECT_FALSE(Ctx->getOriginalText(at(2, 11)).hasValue());
 
   // The space before the first expansion of EMPTY.
-  EXPECT_FALSE(Ctx->getExpandedText(at(3, 9)).has_value());
-  EXPECT_FALSE(Ctx->getOriginalText(at(3, 9)).has_value());
+  EXPECT_FALSE(Ctx->getExpandedText(at(3, 9)).hasValue());
+  EXPECT_FALSE(Ctx->getOriginalText(at(3, 9)).hasValue());
 
   // The beginning of the first expansion of EMPTY.
-  EXPECT_TRUE(Ctx->getExpandedText(at(3, 10)).has_value());
-  EXPECT_TRUE(Ctx->getOriginalText(at(3, 10)).has_value());
+  EXPECT_TRUE(Ctx->getExpandedText(at(3, 10)).hasValue());
+  EXPECT_TRUE(Ctx->getOriginalText(at(3, 10)).hasValue());
 
   // Pointing inside of the token EMPTY, but not at the beginning.
   // FIXME: We only deal with begin locations.
-  EXPECT_FALSE(Ctx->getExpandedText(at(3, 11)).has_value());
-  EXPECT_FALSE(Ctx->getOriginalText(at(3, 11)).has_value());
+  EXPECT_FALSE(Ctx->getExpandedText(at(3, 11)).hasValue());
+  EXPECT_FALSE(Ctx->getOriginalText(at(3, 11)).hasValue());
 
   // Same here.
-  EXPECT_FALSE(Ctx->getExpandedText(at(3, 12)).has_value());
-  EXPECT_FALSE(Ctx->getOriginalText(at(3, 12)).has_value());
+  EXPECT_FALSE(Ctx->getExpandedText(at(3, 12)).hasValue());
+  EXPECT_FALSE(Ctx->getOriginalText(at(3, 12)).hasValue());
 
   // The beginning of the last expansion of EMPTY.
-  EXPECT_TRUE(Ctx->getExpandedText(at(4, 1)).has_value());
-  EXPECT_TRUE(Ctx->getOriginalText(at(4, 1)).has_value());
+  EXPECT_TRUE(Ctx->getExpandedText(at(4, 1)).hasValue());
+  EXPECT_TRUE(Ctx->getOriginalText(at(4, 1)).hasValue());
 
   // Same as for the 3:11 case.
-  EXPECT_FALSE(Ctx->getExpandedText(at(4, 2)).has_value());
-  EXPECT_FALSE(Ctx->getOriginalText(at(4, 2)).has_value());
+  EXPECT_FALSE(Ctx->getExpandedText(at(4, 2)).hasValue());
+  EXPECT_FALSE(Ctx->getOriginalText(at(4, 2)).hasValue());
 }
 
 TEST_F(MacroExpansionContextTest, EmptyExpansions) {
@@ -181,14 +181,14 @@ EMPTY zz
   //  A b cd ef gh
   //      zz
 
-  EXPECT_EQ("", *Ctx->getExpandedText(at(3, 10)));
-  EXPECT_EQ("EMPTY", *Ctx->getOriginalText(at(3, 10)));
+  EXPECT_EQ("", Ctx->getExpandedText(at(3, 10)).getValue());
+  EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(3, 10)).getValue());
 
-  EXPECT_EQ("", *Ctx->getExpandedText(at(3, 19)));
-  EXPECT_EQ("EMPTY", *Ctx->getOriginalText(at(3, 19)));
+  EXPECT_EQ("", Ctx->getExpandedText(at(3, 19)).getValue());
+  EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(3, 19)).getValue());
 
-  EXPECT_EQ("", *Ctx->getExpandedText(at(4, 1)));
-  EXPECT_EQ("EMPTY", *Ctx->getOriginalText(at(4, 1)));
+  EXPECT_EQ("", Ctx->getExpandedText(at(4, 1)).getValue());
+  EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(4, 1)).getValue());
 }
 
 TEST_F(MacroExpansionContextTest, TransitiveExpansions) {
@@ -200,10 +200,10 @@ TEST_F(MacroExpansionContextTest, TransitiveExpansions) {
   // After preprocessing:
   //  A b cd ) 1 ef gh
 
-  EXPECT_EQ("WOOF", *Ctx->getOriginalText(at(4, 10)));
+  EXPECT_EQ("WOOF", Ctx->getOriginalText(at(4, 10)).getValue());
 
-  EXPECT_EQ("", *Ctx->getExpandedText(at(4, 18)));
-  EXPECT_EQ("EMPTY", *Ctx->getOriginalText(at(4, 18)));
+  EXPECT_EQ("", Ctx->getExpandedText(at(4, 18)).getValue());
+  EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(4, 18)).getValue());
 }
 
 TEST_F(MacroExpansionContextTest, MacroFunctions) {
@@ -219,17 +219,17 @@ TEST_F(MacroExpansionContextTest, MacroFunctions) {
   //  WOOF( ) ) ) 1
   //  bar barr( ) ) ) 1( ) ) ) 1),,),')
 
-  EXPECT_EQ("$$ ef ()))1", *Ctx->getExpandedText(at(4, 10)));
-  EXPECT_EQ("WOOF($$ ef)", *Ctx->getOriginalText(at(4, 10)));
+  EXPECT_EQ("$$ ef ()))1", Ctx->getExpandedText(at(4, 10)).getValue());
+  EXPECT_EQ("WOOF($$ ef)", Ctx->getOriginalText(at(4, 10)).getValue());
 
-  EXPECT_EQ("", Ctx->getExpandedText(at(4, 22)).value());
-  EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(4, 22)).value());
+  EXPECT_EQ("", Ctx->getExpandedText(at(4, 22)).getValue());
+  EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(4, 22)).getValue());
 
-  EXPECT_EQ("WOOF ()))1", Ctx->getExpandedText(at(5, 3)).value());
-  EXPECT_EQ("WOOF(WOOF)", Ctx->getOriginalText(at(5, 3)).value());
+  EXPECT_EQ("WOOF ()))1", Ctx->getExpandedText(at(5, 3)).getValue());
+  EXPECT_EQ("WOOF(WOOF)", Ctx->getOriginalText(at(5, 3)).getValue());
 
-  EXPECT_EQ("bar barr ()))1()))1", Ctx->getExpandedText(at(6, 3)).value());
-  EXPECT_EQ("WOOF(WOOF(bar barr))", Ctx->getOriginalText(at(6, 3)).value());
+  EXPECT_EQ("bar barr ()))1()))1", Ctx->getExpandedText(at(6, 3)).getValue());
+  EXPECT_EQ("WOOF(WOOF(bar barr))", Ctx->getOriginalText(at(6, 3)).getValue());
 }
 
 TEST_F(MacroExpansionContextTest, VariadicMacros) {
@@ -251,23 +251,24 @@ TEST_F(MacroExpansionContextTest, VariadicMacros) {
   //  fprintf (stderr, "success!\n" );
 
   EXPECT_EQ(R"(fprintf (stderr ,"success!\n",))",
-            Ctx->getExpandedText(at(3, 3)).value());
+            Ctx->getExpandedText(at(3, 3)).getValue());
   EXPECT_EQ(R"(eprintf("success!\n", ))",
-            Ctx->getOriginalText(at(3, 3)).value());
+            Ctx->getOriginalText(at(3, 3)).getValue());
 
   EXPECT_EQ(R"(fprintf (stderr ,"success!\n",))",
-            Ctx->getExpandedText(at(4, 3)).value());
-  EXPECT_EQ(R"(eprintf("success!\n"))", Ctx->getOriginalText(at(4, 3)).value());
+            Ctx->getExpandedText(at(4, 3)).getValue());
+  EXPECT_EQ(R"(eprintf("success!\n"))",
+            Ctx->getOriginalText(at(4, 3)).getValue());
 
   EXPECT_EQ(R"(fprintf (stderr ,"success!\n"))",
-            Ctx->getExpandedText(at(8, 3)).value());
+            Ctx->getExpandedText(at(8, 3)).getValue());
   EXPECT_EQ(R"(eprintf2("success!\n", ))",
-            Ctx->getOriginalText(at(8, 3)).value());
+            Ctx->getOriginalText(at(8, 3)).getValue());
 
   EXPECT_EQ(R"(fprintf (stderr ,"success!\n"))",
-            Ctx->getExpandedText(at(9, 3)).value());
+            Ctx->getExpandedText(at(9, 3)).getValue());
   EXPECT_EQ(R"(eprintf2("success!\n"))",
-            Ctx->getOriginalText(at(9, 3)).value());
+            Ctx->getOriginalText(at(9, 3)).getValue());
 }
 
 TEST_F(MacroExpansionContextTest, ConcatenationMacros) {
@@ -285,12 +286,12 @@ TEST_F(MacroExpansionContextTest, ConcatenationMacros) {
   //  };
 
   EXPECT_EQ(R"({"quit",quit_command })",
-            Ctx->getExpandedText(at(4, 5)).value());
-  EXPECT_EQ("COMMAND(quit)", Ctx->getOriginalText(at(4, 5)).value());
+            Ctx->getExpandedText(at(4, 5)).getValue());
+  EXPECT_EQ("COMMAND(quit)", Ctx->getOriginalText(at(4, 5)).getValue());
 
   EXPECT_EQ(R"({"help",help_command })",
-            Ctx->getExpandedText(at(5, 5)).value());
-  EXPECT_EQ("COMMAND(help)", Ctx->getOriginalText(at(5, 5)).value());
+            Ctx->getExpandedText(at(5, 5)).getValue());
+  EXPECT_EQ("COMMAND(help)", Ctx->getOriginalText(at(5, 5)).getValue());
 }
 
 TEST_F(MacroExpansionContextTest, StringizingMacros) {
@@ -315,14 +316,14 @@ TEST_F(MacroExpansionContextTest, StringizingMacros) {
 
   EXPECT_EQ(
       R"(do {if (x ==0)fprintf (stderr ,"Warning: ""x == 0""\n");}while (0))",
-      Ctx->getExpandedText(at(6, 3)).value());
-  EXPECT_EQ("WARN_IF (x == 0)", Ctx->getOriginalText(at(6, 3)).value());
+      Ctx->getExpandedText(at(6, 3)).getValue());
+  EXPECT_EQ("WARN_IF (x == 0)", Ctx->getOriginalText(at(6, 3)).getValue());
 
-  EXPECT_EQ(R"("foo")", Ctx->getExpandedText(at(11, 3)).value());
-  EXPECT_EQ("str (foo)", Ctx->getOriginalText(at(11, 3)).value());
+  EXPECT_EQ(R"("foo")", Ctx->getExpandedText(at(11, 3)).getValue());
+  EXPECT_EQ("str (foo)", Ctx->getOriginalText(at(11, 3)).getValue());
 
-  EXPECT_EQ(R"("4")", Ctx->getExpandedText(at(12, 3)).value());
-  EXPECT_EQ("xstr (foo)", Ctx->getOriginalText(at(12, 3)).value());
+  EXPECT_EQ(R"("4")", Ctx->getExpandedText(at(12, 3)).getValue());
+  EXPECT_EQ("xstr (foo)", Ctx->getOriginalText(at(12, 3)).getValue());
 }
 
 TEST_F(MacroExpansionContextTest, StringizingVariadicMacros) {
@@ -351,18 +352,18 @@ TEST_F(MacroExpansionContextTest, StringizingVariadicMacros) {
 
   EXPECT_EQ("zz !apple !x *apple !x !**y (apple )zz !apple !x *apple !x !**y "
             "(appleapple ))))",
-            Ctx->getExpandedText(at(11, 3)).value());
-  EXPECT_EQ("q(g)", Ctx->getOriginalText(at(11, 3)).value());
+            Ctx->getExpandedText(at(11, 3)).getValue());
+  EXPECT_EQ("q(g)", Ctx->getOriginalText(at(11, 3)).getValue());
 
   EXPECT_EQ(R"res("apple"(apple )"apple"(appleapple )))))res",
-            Ctx->getExpandedText(at(12, 3)).value());
-  EXPECT_EQ("q(xstr)", Ctx->getOriginalText(at(12, 3)).value());
+            Ctx->getExpandedText(at(12, 3)).getValue());
+  EXPECT_EQ("q(xstr)", Ctx->getOriginalText(at(12, 3)).getValue());
 
-  EXPECT_EQ("zz !*)!x )!**y ", Ctx->getExpandedText(at(13, 3)).value());
-  EXPECT_EQ("g(RParen2x)", Ctx->getOriginalText(at(13, 3)).value());
+  EXPECT_EQ("zz !*)!x )!**y ", Ctx->getExpandedText(at(13, 3)).getValue());
+  EXPECT_EQ("g(RParen2x)", Ctx->getOriginalText(at(13, 3)).getValue());
 
-  EXPECT_EQ("!))*))", Ctx->getExpandedText(at(14, 3)).value());
-  EXPECT_EQ("f( RParen2x )", Ctx->getOriginalText(at(14, 3)).value());
+  EXPECT_EQ("!))*))", Ctx->getExpandedText(at(14, 3)).getValue());
+  EXPECT_EQ("f( RParen2x )", Ctx->getOriginalText(at(14, 3)).getValue());
 }
 
 TEST_F(MacroExpansionContextTest, RedefUndef) {
@@ -380,15 +381,15 @@ TEST_F(MacroExpansionContextTest, RedefUndef) {
   //  Hi(Hi)
 
   // FIXME: Extra space follows every identifier.
-  EXPECT_EQ("Welcome Adam ", Ctx->getExpandedText(at(3, 3)).value());
-  EXPECT_EQ("Hi(Adam)", Ctx->getOriginalText(at(3, 3)).value());
+  EXPECT_EQ("Welcome Adam ", Ctx->getExpandedText(at(3, 3)).getValue());
+  EXPECT_EQ("Hi(Adam)", Ctx->getOriginalText(at(3, 3)).getValue());
 
-  EXPECT_EQ("Willkommen ", Ctx->getExpandedText(at(5, 3)).value());
-  EXPECT_EQ("Hi", Ctx->getOriginalText(at(5, 3)).value());
+  EXPECT_EQ("Willkommen ", Ctx->getExpandedText(at(5, 3)).getValue());
+  EXPECT_EQ("Hi", Ctx->getOriginalText(at(5, 3)).getValue());
 
   // There was no macro expansion at 7:3, we should expect None.
-  EXPECT_FALSE(Ctx->getExpandedText(at(7, 3)).has_value());
-  EXPECT_FALSE(Ctx->getOriginalText(at(7, 3)).has_value());
+  EXPECT_FALSE(Ctx->getExpandedText(at(7, 3)).hasValue());
+  EXPECT_FALSE(Ctx->getOriginalText(at(7, 3)).hasValue());
 }
 
 TEST_F(MacroExpansionContextTest, UnbalacedParenthesis) {
@@ -410,11 +411,12 @@ TEST_F(MacroExpansionContextTest, UnbalacedParenthesis) {
   //  fun();
   //  int x = ((1, fun(), 1, fun(), 1 ));
 
-  EXPECT_EQ("fun ()", Ctx->getExpandedText(at(8, 3)).value());
-  EXPECT_EQ("applyInt )", Ctx->getOriginalText(at(8, 3)).value());
+  EXPECT_EQ("fun ()", Ctx->getExpandedText(at(8, 3)).getValue());
+  EXPECT_EQ("applyInt )", Ctx->getOriginalText(at(8, 3)).getValue());
 
-  EXPECT_EQ("((1,fun (),1,fun (),1", Ctx->getExpandedText(at(13, 12)).value());
-  EXPECT_EQ("f(f(1))", Ctx->getOriginalText(at(13, 12)).value());
+  EXPECT_EQ("((1,fun (),1,fun (),1",
+            Ctx->getExpandedText(at(13, 12)).getValue());
+  EXPECT_EQ("f(f(1))", Ctx->getOriginalText(at(13, 12)).getValue());
 }
 
 } // namespace

diff  --git a/clang/unittests/Basic/DarwinSDKInfoTest.cpp b/clang/unittests/Basic/DarwinSDKInfoTest.cpp
index d56e13d839162..8d720c2e0a6f0 100644
--- a/clang/unittests/Basic/DarwinSDKInfoTest.cpp
+++ b/clang/unittests/Basic/DarwinSDKInfoTest.cpp
@@ -64,14 +64,14 @@ TEST(DarwinSDKInfo, VersionMappingParseEmpty) {
   llvm::json::Object Obj({});
   EXPECT_FALSE(
       DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON(Obj, VersionTuple())
-          .has_value());
+          .hasValue());
 }
 
 TEST(DarwinSDKInfo, VersionMappingParseError) {
   llvm::json::Object Obj({{"test", "1.2"}});
   EXPECT_FALSE(
       DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON(Obj, VersionTuple())
-          .has_value());
+          .hasValue());
 }
 
 TEST(DarwinSDKInfoTest, ParseAndTestMappingMacCatalyst) {

diff  --git a/clang/unittests/DirectoryWatcher/DirectoryWatcherTest.cpp b/clang/unittests/DirectoryWatcher/DirectoryWatcherTest.cpp
index d9c12450c6189..5b76480d3b869 100644
--- a/clang/unittests/DirectoryWatcher/DirectoryWatcherTest.cpp
+++ b/clang/unittests/DirectoryWatcher/DirectoryWatcherTest.cpp
@@ -258,12 +258,12 @@ void checkEventualResultWithTimeout(VerifyingConsumer &TestConsumer) {
               std::future_status::ready)
       << "The expected result state wasn't reached before the time-out.";
   std::unique_lock<std::mutex> L(TestConsumer.Mtx);
-  EXPECT_TRUE(TestConsumer.result().has_value());
-  if (TestConsumer.result()) {
+  EXPECT_TRUE(TestConsumer.result().hasValue());
+  if (TestConsumer.result().hasValue()) {
     EXPECT_TRUE(*TestConsumer.result());
   }
-  if ((TestConsumer.result() && !*TestConsumer.result()) ||
-      !TestConsumer.result())
+  if ((TestConsumer.result().hasValue() && !TestConsumer.result().getValue()) ||
+      !TestConsumer.result().hasValue())
     TestConsumer.printUnmetExpectations(llvm::outs());
 }
 } // namespace

diff  --git a/clang/unittests/Lex/HeaderSearchTest.cpp b/clang/unittests/Lex/HeaderSearchTest.cpp
index bd9d31da1cf7f..87d1c01650987 100644
--- a/clang/unittests/Lex/HeaderSearchTest.cpp
+++ b/clang/unittests/Lex/HeaderSearchTest.cpp
@@ -200,9 +200,9 @@ TEST_F(HeaderSearchTest, HeaderFrameworkLookup) {
       /*RelativePath=*/nullptr, /*RequestingModule=*/nullptr,
       /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr, &IsFrameworkFound);
 
-  EXPECT_TRUE(FoundFile.has_value());
+  EXPECT_TRUE(FoundFile.hasValue());
   EXPECT_TRUE(IsFrameworkFound);
-  auto &FE = *FoundFile;
+  auto &FE = FoundFile.getValue();
   auto FI = Search.getExistingFileInfo(FE);
   EXPECT_TRUE(FI);
   EXPECT_TRUE(FI->IsValid);
@@ -269,9 +269,9 @@ TEST_F(HeaderSearchTest, HeaderMapFrameworkLookup) {
       /*SuggestedModule=*/nullptr, &IsMapped,
       /*IsFrameworkFound=*/nullptr);
 
-  EXPECT_TRUE(FoundFile.has_value());
+  EXPECT_TRUE(FoundFile.hasValue());
   EXPECT_TRUE(IsMapped);
-  auto &FE = *FoundFile;
+  auto &FE = FoundFile.getValue();
   auto FI = Search.getExistingFileInfo(FE);
   EXPECT_TRUE(FI);
   EXPECT_TRUE(FI->IsValid);

diff  --git a/clang/unittests/StaticAnalyzer/SValTest.cpp b/clang/unittests/StaticAnalyzer/SValTest.cpp
index c41a501b07f8f..1a41faf098996 100644
--- a/clang/unittests/StaticAnalyzer/SValTest.cpp
+++ b/clang/unittests/StaticAnalyzer/SValTest.cpp
@@ -305,13 +305,13 @@ void foo(int x) {
   EXPECT_EQ("TestUnion", CRecordType->getDecl()->getName());
 
   auto D = getByName("d").getAs<nonloc::CompoundVal>();
-  ASSERT_TRUE(D.has_value());
+  ASSERT_TRUE(D.hasValue());
   auto Begin = D->begin();
   ASSERT_NE(D->end(), Begin);
   ++Begin;
   ASSERT_EQ(D->end(), Begin);
   auto LD = D->begin()->getAs<nonloc::LazyCompoundVal>();
-  ASSERT_TRUE(LD.has_value());
+  ASSERT_TRUE(LD.hasValue());
   auto LDT = LD->getType(Context);
   ASSERT_FALSE(LDT.isNull());
   const auto *DRecordType = dyn_cast<RecordType>(LDT);

diff  --git a/clang/unittests/Tooling/RefactoringTest.cpp b/clang/unittests/Tooling/RefactoringTest.cpp
index f0edff6052c9a..c71a7243396a1 100644
--- a/clang/unittests/Tooling/RefactoringTest.cpp
+++ b/clang/unittests/Tooling/RefactoringTest.cpp
@@ -118,18 +118,18 @@ static bool checkReplacementError(llvm::Error &&Error,
       OS << "Unexpected error code: " << int(RE.get()) << "\n";
     if (ExpectedExisting != RE.getExistingReplacement()) {
       OS << "Expected Existing != Actual Existing.\n";
-      if (ExpectedExisting)
+      if (ExpectedExisting.hasValue())
         OS << "Expected existing replacement: " << ExpectedExisting->toString()
            << "\n";
-      if (RE.getExistingReplacement())
+      if (RE.getExistingReplacement().hasValue())
         OS << "Actual existing replacement: "
            << RE.getExistingReplacement()->toString() << "\n";
     }
     if (ExpectedNew != RE.getNewReplacement()) {
       OS << "Expected New != Actual New.\n";
-      if (ExpectedNew)
+      if (ExpectedNew.hasValue())
         OS << "Expected new replacement: " << ExpectedNew->toString() << "\n";
-      if (RE.getNewReplacement())
+      if (RE.getNewReplacement().hasValue())
         OS << "Actual new replacement: " << RE.getNewReplacement()->toString()
            << "\n";
     }

diff  --git a/clang/utils/TableGen/RISCVVEmitter.cpp b/clang/utils/TableGen/RISCVVEmitter.cpp
index f6678cc611d34..7987d8954eb17 100644
--- a/clang/utils/TableGen/RISCVVEmitter.cpp
+++ b/clang/utils/TableGen/RISCVVEmitter.cpp
@@ -217,22 +217,22 @@ void RVVEmitter::createHeader(raw_ostream &OS) {
   for (int Log2LMUL : Log2LMULs) {
     auto T = RVVType::computeType(BasicType::Int8, Log2LMUL,
                                   PrototypeDescriptor::Mask);
-    if (T)
-      printType(*T);
+    if (T.hasValue())
+      printType(T.getValue());
   }
   // Print RVV int/float types.
   for (char I : StringRef("csil")) {
     BasicType BT = ParseBasicType(I);
     for (int Log2LMUL : Log2LMULs) {
       auto T = RVVType::computeType(BT, Log2LMUL, PrototypeDescriptor::Vector);
-      if (T) {
-        printType(*T);
+      if (T.hasValue()) {
+        printType(T.getValue());
         auto UT = RVVType::computeType(
             BT, Log2LMUL,
             PrototypeDescriptor(BaseTypeModifier::Vector,
                                 VectorTypeModifier::NoModifier,
                                 TypeModifier::UnsignedInteger));
-        printType(*UT);
+        printType(UT.getValue());
       }
     }
   }
@@ -240,8 +240,8 @@ void RVVEmitter::createHeader(raw_ostream &OS) {
   for (int Log2LMUL : Log2LMULs) {
     auto T = RVVType::computeType(BasicType::Float16, Log2LMUL,
                                   PrototypeDescriptor::Vector);
-    if (T)
-      printType(*T);
+    if (T.hasValue())
+      printType(T.getValue());
   }
   OS << "#endif\n";
 
@@ -249,8 +249,8 @@ void RVVEmitter::createHeader(raw_ostream &OS) {
   for (int Log2LMUL : Log2LMULs) {
     auto T = RVVType::computeType(BasicType::Float32, Log2LMUL,
                                   PrototypeDescriptor::Vector);
-    if (T)
-      printType(*T);
+    if (T.hasValue())
+      printType(T.getValue());
   }
   OS << "#endif\n";
 
@@ -258,8 +258,8 @@ void RVVEmitter::createHeader(raw_ostream &OS) {
   for (int Log2LMUL : Log2LMULs) {
     auto T = RVVType::computeType(BasicType::Float64, Log2LMUL,
                                   PrototypeDescriptor::Vector);
-    if (T)
-      printType(*T);
+    if (T.hasValue())
+      printType(T.getValue());
   }
   OS << "#endif\n\n";
 

diff  --git a/flang/include/flang/Lower/IterationSpace.h b/flang/include/flang/Lower/IterationSpace.h
index ed906e922b31b..055882c5770d1 100644
--- a/flang/include/flang/Lower/IterationSpace.h
+++ b/flang/include/flang/Lower/IterationSpace.h
@@ -446,9 +446,7 @@ class ExplicitIterSpace {
   /// `load` must be a LHS array_load. Returns `llvm::None` on error.
   llvm::Optional<size_t> findArgPosition(fir::ArrayLoadOp load);
 
-  bool isLHS(fir::ArrayLoadOp load) {
-    return findArgPosition(load).has_value();
-  }
+  bool isLHS(fir::ArrayLoadOp load) { return findArgPosition(load).hasValue(); }
 
   /// `load` must be a LHS array_load. Determine the threaded inner argument
   /// corresponding to this load.
@@ -467,15 +465,15 @@ class ExplicitIterSpace {
 
   llvm::Optional<fir::ArrayLoadOp> getLhsLoad(size_t i) {
     assert(i < lhsBases.size());
-    if (lhsBases[counter])
-      return findBinding(*lhsBases[counter]);
+    if (lhsBases[counter].hasValue())
+      return findBinding(lhsBases[counter].getValue());
     return llvm::None;
   }
 
   /// Return the outermost loop in this FORALL nest.
   fir::DoLoopOp getOuterLoop() {
-    assert(outerLoop);
-    return *outerLoop;
+    assert(outerLoop.hasValue());
+    return outerLoop.getValue();
   }
 
   /// Return the statement context for the entire, outermost FORALL construct.

diff  --git a/flang/lib/Lower/Bridge.cpp b/flang/lib/Lower/Bridge.cpp
index 745a7d497e263..b7d180ed73207 100644
--- a/flang/lib/Lower/Bridge.cpp
+++ b/flang/lib/Lower/Bridge.cpp
@@ -2227,10 +2227,10 @@ class FirConverter : public Fortran::lower::AbstractConverter {
                 llvm_unreachable("unknown category");
               }
               if (lhsIsWholeAllocatable)
-                fir::factory::finalizeRealloc(*builder, loc, *lhsMutableBox,
-                                              /*lbounds=*/llvm::None,
-                                              /*takeLboundsIfRealloc=*/false,
-                                              *lhsRealloc);
+                fir::factory::finalizeRealloc(
+                    *builder, loc, lhsMutableBox.getValue(),
+                    /*lbounds=*/llvm::None, /*takeLboundsIfRealloc=*/false,
+                    lhsRealloc.getValue());
             },
 
             // [2] User defined assignment. If the context is a scalar

diff  --git a/flang/lib/Lower/ConvertExpr.cpp b/flang/lib/Lower/ConvertExpr.cpp
index 0558a10c23fb6..07eceb74e400a 100644
--- a/flang/lib/Lower/ConvertExpr.cpp
+++ b/flang/lib/Lower/ConvertExpr.cpp
@@ -2607,9 +2607,9 @@ class ScalarExprLowering {
                                             funcSymbolAttr, operands);
 
     if (caller.mustSaveResult())
-      builder.create<fir::SaveResultOp>(loc, call.getResult(0),
-                                        fir::getBase(*allocatedResult),
-                                        arrayResultShape, resultLengths);
+      builder.create<fir::SaveResultOp>(
+          loc, call.getResult(0), fir::getBase(allocatedResult.getValue()),
+          arrayResultShape, resultLengths);
 
     if (allocatedResult) {
       allocatedResult->match(
@@ -4110,10 +4110,10 @@ class ArrayExprLowering {
                                            mlir::Value{});
       }
     } else if (isBoundsRemap()) {
-      auto lbs = *lbounds;
+      auto lbs = lbounds.getValue();
       if (lbs.size() > 0) {
         // Rebox the value with user-specified shift and shape.
-        auto shapeShiftArgs = flatZip(lbs, *ubounds);
+        auto shapeShiftArgs = flatZip(lbs, ubounds.getValue());
         auto shapeTy = fir::ShapeShiftType::get(eleTy.getContext(), lbs.size());
         mlir::Value shapeShift =
             builder.create<fir::ShapeShiftOp>(loc, shapeTy, shapeShiftArgs);
@@ -4185,8 +4185,8 @@ class ArrayExprLowering {
     auto [iterSpace, insPt] = genIterSpace(resultTy);
     auto exv = f(iterSpace);
     iterSpace.setElement(std::move(exv));
-    auto lambda = ccStoreToDest
-                      ? *ccStoreToDest
+    auto lambda = ccStoreToDest.hasValue()
+                      ? ccStoreToDest.getValue()
                       : defaultStoreToDestination(/*substring=*/nullptr);
     mlir::Value updVal = fir::getBase(lambda(iterSpace));
     finalizeElementCtx();
@@ -4522,8 +4522,8 @@ class ArrayExprLowering {
     }
 
     // Generate the lazy mask allocation, if one was given.
-    if (ccPrelude)
-      ccPrelude.value()(shape);
+    if (ccPrelude.hasValue())
+      ccPrelude.getValue()(shape);
 
     // Now handle the implicit loops.
     mlir::Value inner = explicitSpaceIsActive()
@@ -4582,8 +4582,8 @@ class ArrayExprLowering {
   fir::ArrayLoadOp
   createAndLoadSomeArrayTemp(mlir::Type type,
                              llvm::ArrayRef<mlir::Value> shape) {
-    if (ccLoadDest)
-      return ccLoadDest.value()(shape);
+    if (ccLoadDest.hasValue())
+      return ccLoadDest.getValue()(shape);
     auto seqTy = type.dyn_cast<fir::SequenceType>();
     assert(seqTy && "must be an array");
     mlir::Location loc = getLoc();
@@ -5810,8 +5810,8 @@ class ArrayExprLowering {
       // always loaded at the beginning of the statement and merged at the
       // end.
       destination = arrLoad;
-      auto lambda = ccStoreToDest
-                        ? ccStoreToDest.value()
+      auto lambda = ccStoreToDest.hasValue()
+                        ? ccStoreToDest.getValue()
                         : defaultStoreToDestination(components.substring);
       return [=](IterSpace iters) -> ExtValue { return lambda(iters); };
     }
@@ -6464,8 +6464,8 @@ class ArrayExprLowering {
 
     // Return the continuation.
     if (fir::isa_char(seqTy.getEleTy())) {
-      if (charLen) {
-        auto len = builder.create<fir::LoadOp>(loc, charLen.value());
+      if (charLen.hasValue()) {
+        auto len = builder.create<fir::LoadOp>(loc, charLen.getValue());
         return genarr(fir::CharArrayBoxValue{mem, len, extents});
       }
       return genarr(fir::CharArrayBoxValue{mem, zero, extents});
@@ -7181,14 +7181,14 @@ class ArrayExprLowering {
 
   void setUnordered(bool b) { unordered = b; }
 
-  inline bool isPointerAssignment() const { return lbounds.has_value(); }
+  inline bool isPointerAssignment() const { return lbounds.hasValue(); }
 
   inline bool isBoundsSpec() const {
-    return isPointerAssignment() && !ubounds.has_value();
+    return isPointerAssignment() && !ubounds.hasValue();
   }
 
   inline bool isBoundsRemap() const {
-    return isPointerAssignment() && ubounds.has_value();
+    return isPointerAssignment() && ubounds.hasValue();
   }
 
   void setPointerAssignmentBounds(
@@ -7515,8 +7515,8 @@ void Fortran::lower::createArrayLoads(
   auto genLoad = [&](const auto *x) -> fir::ArrayLoadOp {
     return genArrayLoad(loc, converter, builder, x, symMap, stmtCtx);
   };
-  if (esp.lhsBases[counter]) {
-    auto &base = *esp.lhsBases[counter];
+  if (esp.lhsBases[counter].hasValue()) {
+    auto &base = esp.lhsBases[counter].getValue();
     auto load = std::visit(genLoad, base);
     esp.initialArgs.push_back(load);
     esp.resetInnerArgs();
@@ -7535,13 +7535,13 @@ void Fortran::lower::createArrayMergeStores(
   // Gen the fir.array_merge_store ops for all LHS arrays.
   for (auto i : llvm::enumerate(esp.getOuterLoop().getResults()))
     if (llvm::Optional<fir::ArrayLoadOp> ldOpt = esp.getLhsLoad(i.index())) {
-      fir::ArrayLoadOp load = *ldOpt;
+      fir::ArrayLoadOp load = ldOpt.getValue();
       builder.create<fir::ArrayMergeStoreOp>(loc, load, i.value(),
                                              load.getMemref(), load.getSlice(),
                                              load.getTypeparams());
     }
-  if (esp.loopCleanup) {
-    esp.loopCleanup.value()(builder);
+  if (esp.loopCleanup.hasValue()) {
+    esp.loopCleanup.getValue()(builder);
     esp.loopCleanup = llvm::None;
   }
   esp.initialArgs.clear();

diff  --git a/flang/lib/Lower/CustomIntrinsicCall.cpp b/flang/lib/Lower/CustomIntrinsicCall.cpp
index 9548045a174b0..1127e2841b04f 100644
--- a/flang/lib/Lower/CustomIntrinsicCall.cpp
+++ b/flang/lib/Lower/CustomIntrinsicCall.cpp
@@ -195,12 +195,12 @@ lowerIshftc(fir::FirOpBuilder &builder, mlir::Location loc,
          isPresentCheck(2) &&
          "only ISHFTC SIZE arg is expected to be dynamically optional here");
   assert(retTy && "ISFHTC must have a return type");
-  mlir::Type resultType = *retTy;
+  mlir::Type resultType = retTy.getValue();
   llvm::SmallVector<fir::ExtendedValue> args;
   args.push_back(getOperand(0));
   args.push_back(getOperand(1));
   args.push_back(builder
-                     .genIfOp(loc, {resultType}, *isPresentCheck(2),
+                     .genIfOp(loc, {resultType}, isPresentCheck(2).getValue(),
                               /*withElseRegion=*/true)
                      .genThen([&]() {
                        fir::ExtendedValue sizeExv = getOperand(2);

diff  --git a/flang/lib/Lower/IterationSpace.cpp b/flang/lib/Lower/IterationSpace.cpp
index 4458086a50ec8..4d7a7f8cda0f8 100644
--- a/flang/lib/Lower/IterationSpace.cpp
+++ b/flang/lib/Lower/IterationSpace.cpp
@@ -862,12 +862,12 @@ void Fortran::lower::ExplicitIterSpace::conditionalCleanup() {
 
 llvm::Optional<size_t>
 Fortran::lower::ExplicitIterSpace::findArgPosition(fir::ArrayLoadOp load) {
-  if (lhsBases[counter]) {
-    auto ld = loadBindings.find(*lhsBases[counter]);
+  if (lhsBases[counter].hasValue()) {
+    auto ld = loadBindings.find(lhsBases[counter].getValue());
     llvm::Optional<size_t> optPos;
     if (ld != loadBindings.end() && ld->second == load)
       optPos = static_cast<size_t>(0u);
-    assert(optPos && "load does not correspond to lhs");
+    assert(optPos.hasValue() && "load does not correspond to lhs");
     return optPos;
   }
   return llvm::None;
@@ -919,8 +919,8 @@ Fortran::lower::operator<<(llvm::raw_ostream &s,
   s << "LHS bases:\n";
   for (const llvm::Optional<Fortran::lower::ExplicitIterSpace::ArrayBases> &u :
        e.lhsBases)
-    if (u)
-      dump(*u);
+    if (u.hasValue())
+      dump(u.getValue());
   s << "RHS bases:\n";
   for (const llvm::SmallVector<Fortran::lower::ExplicitIterSpace::ArrayBases>
            &bases : e.rhsBases) {

diff  --git a/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp b/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp
index 4cb1cf808fd4b..e652ca75f207f 100644
--- a/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp
+++ b/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp
@@ -252,11 +252,11 @@ class BoxedProcedurePass : public BoxedProcedurePassBase<BoxedProcedurePass> {
             auto toTy = typeConverter.convertType(unwrapRefType(ty));
             bool isPinned = mem.getPinned();
             llvm::StringRef uniqName;
-            if (mem.getUniqName())
-              uniqName = mem.getUniqName().value();
+            if (mem.getUniqName().hasValue())
+              uniqName = mem.getUniqName().getValue();
             llvm::StringRef bindcName;
-            if (mem.getBindcName())
-              bindcName = mem.getBindcName().value();
+            if (mem.getBindcName().hasValue())
+              bindcName = mem.getBindcName().getValue();
             rewriter.replaceOpWithNewOp<AllocaOp>(
                 mem, toTy, uniqName, bindcName, isPinned, mem.getTypeparams(),
                 mem.getShape());
@@ -267,11 +267,11 @@ class BoxedProcedurePass : public BoxedProcedurePassBase<BoxedProcedurePass> {
             rewriter.setInsertionPoint(mem);
             auto toTy = typeConverter.convertType(unwrapRefType(ty));
             llvm::StringRef uniqName;
-            if (mem.getUniqName())
-              uniqName = mem.getUniqName().value();
+            if (mem.getUniqName().hasValue())
+              uniqName = mem.getUniqName().getValue();
             llvm::StringRef bindcName;
-            if (mem.getBindcName())
-              bindcName = mem.getBindcName().value();
+            if (mem.getBindcName().hasValue())
+              bindcName = mem.getBindcName().getValue();
             rewriter.replaceOpWithNewOp<AllocMemOp>(
                 mem, toTy, uniqName, bindcName, mem.getTypeparams(),
                 mem.getShape());

diff  --git a/flang/lib/Optimizer/CodeGen/CodeGen.cpp b/flang/lib/Optimizer/CodeGen/CodeGen.cpp
index 5fc2e1760e511..ad59bd734fd05 100644
--- a/flang/lib/Optimizer/CodeGen/CodeGen.cpp
+++ b/flang/lib/Optimizer/CodeGen/CodeGen.cpp
@@ -2636,9 +2636,9 @@ struct GlobalOpConversion : public FIROpConversion<fir::GlobalOp> {
     auto loc = global.getLoc();
     mlir::Attribute initAttr;
     if (global.getInitVal())
-      initAttr = *global.getInitVal();
+      initAttr = global.getInitVal().getValue();
     auto linkage = convertLinkage(global.getLinkName());
-    auto isConst = global.getConstant().has_value();
+    auto isConst = global.getConstant().hasValue();
     auto g = rewriter.create<mlir::LLVM::GlobalOp>(
         loc, tyAttr, isConst, linkage, global.getSymName(), initAttr);
     auto &gr = g.getInitializerRegion();
@@ -2692,8 +2692,8 @@ struct GlobalOpConversion : public FIROpConversion<fir::GlobalOp> {
   // enumeration.
   mlir::LLVM::Linkage
   convertLinkage(llvm::Optional<llvm::StringRef> optLinkage) const {
-    if (optLinkage) {
-      auto name = *optLinkage;
+    if (optLinkage.hasValue()) {
+      auto name = optLinkage.getValue();
       if (name == "internal")
         return mlir::LLVM::Linkage::Internal;
       if (name == "linkonce")
@@ -2749,9 +2749,9 @@ static void genCondBrOp(mlir::Location loc, mlir::Value cmp, mlir::Block *dest,
                         llvm::Optional<mlir::ValueRange> destOps,
                         mlir::ConversionPatternRewriter &rewriter,
                         mlir::Block *newBlock) {
-  if (destOps)
-    rewriter.create<mlir::LLVM::CondBrOp>(loc, cmp, dest, *destOps, newBlock,
-                                          mlir::ValueRange());
+  if (destOps.hasValue())
+    rewriter.create<mlir::LLVM::CondBrOp>(loc, cmp, dest, destOps.getValue(),
+                                          newBlock, mlir::ValueRange());
   else
     rewriter.create<mlir::LLVM::CondBrOp>(loc, cmp, dest, newBlock);
 }
@@ -2759,8 +2759,9 @@ static void genCondBrOp(mlir::Location loc, mlir::Value cmp, mlir::Block *dest,
 template <typename A, typename B>
 static void genBrOp(A caseOp, mlir::Block *dest, llvm::Optional<B> destOps,
                     mlir::ConversionPatternRewriter &rewriter) {
-  if (destOps)
-    rewriter.replaceOpWithNewOp<mlir::LLVM::BrOp>(caseOp, *destOps, dest);
+  if (destOps.hasValue())
+    rewriter.replaceOpWithNewOp<mlir::LLVM::BrOp>(caseOp, destOps.getValue(),
+                                                  dest);
   else
     rewriter.replaceOpWithNewOp<mlir::LLVM::BrOp>(caseOp, llvm::None, dest);
 }
@@ -2883,14 +2884,15 @@ static void selectMatchAndRewrite(fir::LLVMTypeConverter &lowering, OP select,
     const mlir::Attribute &attr = cases[t];
     if (auto intAttr = attr.template dyn_cast<mlir::IntegerAttr>()) {
       destinations.push_back(dest);
-      destinationsOperands.push_back(destOps ? *destOps : mlir::ValueRange{});
+      destinationsOperands.push_back(destOps.hasValue() ? *destOps
+                                                        : mlir::ValueRange{});
       caseValues.push_back(intAttr.getInt());
       continue;
     }
     assert(attr.template dyn_cast_or_null<mlir::UnitAttr>());
     assert((t + 1 == conds) && "unit must be last");
     defaultDestination = dest;
-    defaultOperands = destOps ? *destOps : mlir::ValueRange{};
+    defaultOperands = destOps.hasValue() ? *destOps : mlir::ValueRange{};
   }
 
   // LLVM::SwitchOp takes a i32 type for the selector.

diff  --git a/flang/lib/Optimizer/CodeGen/TargetRewrite.cpp b/flang/lib/Optimizer/CodeGen/TargetRewrite.cpp
index 9b744fe6ec54c..f1e58d42779ea 100644
--- a/flang/lib/Optimizer/CodeGen/TargetRewrite.cpp
+++ b/flang/lib/Optimizer/CodeGen/TargetRewrite.cpp
@@ -316,9 +316,9 @@ class TargetRewrite : public fir::TargetRewriteBase<TargetRewrite> {
     newOpers.insert(newOpers.end(), trailingOpers.begin(), trailingOpers.end());
     if constexpr (std::is_same_v<std::decay_t<A>, fir::CallOp>) {
       fir::CallOp newCall;
-      if (callOp.getCallee()) {
-        newCall =
-            rewriter->create<A>(loc, *callOp.getCallee(), newResTys, newOpers);
+      if (callOp.getCallee().hasValue()) {
+        newCall = rewriter->create<A>(loc, callOp.getCallee().getValue(),
+                                      newResTys, newOpers);
       } else {
         // Force new type on the input operand.
         newOpers[0].setType(mlir::FunctionType::get(

diff  --git a/flang/lib/Optimizer/Dialect/FIROps.cpp b/flang/lib/Optimizer/Dialect/FIROps.cpp
index 7a6da508b535c..6443d5c6eca42 100644
--- a/flang/lib/Optimizer/Dialect/FIROps.cpp
+++ b/flang/lib/Optimizer/Dialect/FIROps.cpp
@@ -616,10 +616,10 @@ mlir::FunctionType fir::CallOp::getFunctionType() {
 }
 
 void fir::CallOp::print(mlir::OpAsmPrinter &p) {
-  bool isDirect = getCallee().has_value();
+  bool isDirect = getCallee().hasValue();
   p << ' ';
   if (isDirect)
-    p << *getCallee();
+    p << getCallee().getValue();
   else
     p << getOperand(0);
   p << '(' << (*this)->getOperands().drop_front(isDirect ? 0 : 1) << ')';
@@ -700,8 +700,9 @@ static void printCmpOp(mlir::OpAsmPrinter &p, OPTY op) {
       op->template getAttrOfType<mlir::IntegerAttr>(
             OPTY::getPredicateAttrName())
           .getInt());
-  assert(predSym && "invalid symbol value for predicate");
-  p << '"' << mlir::arith::stringifyCmpFPredicate(*predSym) << '"' << ", ";
+  assert(predSym.hasValue() && "invalid symbol value for predicate");
+  p << '"' << mlir::arith::stringifyCmpFPredicate(predSym.getValue()) << '"'
+    << ", ";
   p.printOperand(op.getLhs());
   p << ", ";
   p.printOperand(op.getRhs());
@@ -776,8 +777,8 @@ void fir::buildCmpCOp(mlir::OpBuilder &builder, mlir::OperationState &result,
 mlir::arith::CmpFPredicate
 fir::CmpcOp::getPredicateByName(llvm::StringRef name) {
   auto pred = mlir::arith::symbolizeCmpFPredicate(name);
-  assert(pred && "invalid predicate name");
-  return *pred;
+  assert(pred.hasValue() && "invalid predicate name");
+  return pred.getValue();
 }
 
 void fir::CmpcOp::print(mlir::OpAsmPrinter &p) { printCmpOp(p, *this); }
@@ -1073,7 +1074,7 @@ mlir::ParseResult fir::DispatchTableOp::parse(mlir::OpAsmParser &parser,
   // Parse the optional table body.
   mlir::Region *body = result.addRegion();
   mlir::OptionalParseResult parseResult = parser.parseOptionalRegion(*body);
-  if (parseResult.has_value() && failed(*parseResult))
+  if (parseResult.hasValue() && failed(*parseResult))
     return mlir::failure();
 
   fir::DispatchTableOp::ensureTerminator(*body, parser.getBuilder(),
@@ -1255,15 +1256,15 @@ mlir::ParseResult fir::GlobalOp::parse(mlir::OpAsmParser &parser,
     // Parse the optional initializer body.
     auto parseResult =
         parser.parseOptionalRegion(*result.addRegion(), /*arguments=*/{});
-    if (parseResult.has_value() && mlir::failed(*parseResult))
+    if (parseResult.hasValue() && mlir::failed(*parseResult))
       return mlir::failure();
   }
   return mlir::success();
 }
 
 void fir::GlobalOp::print(mlir::OpAsmPrinter &p) {
-  if (getLinkName())
-    p << ' ' << *getLinkName();
+  if (getLinkName().hasValue())
+    p << ' ' << getLinkName().getValue();
   p << ' ';
   p.printAttributeWithoutType(getSymrefAttr());
   if (auto val = getValueOrNull())

diff  --git a/flang/lib/Optimizer/Dialect/FIRType.cpp b/flang/lib/Optimizer/Dialect/FIRType.cpp
index 5347d8556facf..3293cad6177a2 100644
--- a/flang/lib/Optimizer/Dialect/FIRType.cpp
+++ b/flang/lib/Optimizer/Dialect/FIRType.cpp
@@ -120,7 +120,7 @@ mlir::Type fir::parseFirType(FIROpsDialect *dialect,
     return {};
   mlir::Type genType;
   auto parseResult = generatedTypeParser(parser, typeTag, genType);
-  if (parseResult.has_value())
+  if (parseResult.hasValue())
     return genType;
   parser.emitError(parser.getNameLoc(), "unknown fir type: ") << typeTag;
   return {};

diff  --git a/flang/lib/Optimizer/Support/InternalNames.cpp b/flang/lib/Optimizer/Support/InternalNames.cpp
index 19a2740a51a88..8e37df2f7df0c 100644
--- a/flang/lib/Optimizer/Support/InternalNames.cpp
+++ b/flang/lib/Optimizer/Support/InternalNames.cpp
@@ -51,8 +51,8 @@ convertToStringRef(llvm::ArrayRef<std::string> from) {
 inline llvm::Optional<llvm::StringRef>
 convertToStringRef(const llvm::Optional<std::string> &from) {
   llvm::Optional<llvm::StringRef> to;
-  if (from)
-    to = *from;
+  if (from.hasValue())
+    to = from.getValue();
   return to;
 }
 

diff  --git a/flang/lib/Optimizer/Transforms/AbstractResult.cpp b/flang/lib/Optimizer/Transforms/AbstractResult.cpp
index 68f3247401f01..7dd821474698f 100644
--- a/flang/lib/Optimizer/Transforms/AbstractResult.cpp
+++ b/flang/lib/Optimizer/Transforms/AbstractResult.cpp
@@ -101,7 +101,7 @@ class CallOpConversion : public mlir::OpRewritePattern<fir::CallOp> {
       llvm::SmallVector<mlir::Value> newOperands = {arg};
       newOperands.append(callOp.getOperands().begin(),
                          callOp.getOperands().end());
-      rewriter.create<fir::CallOp>(loc, callOp.getCallee().value(),
+      rewriter.create<fir::CallOp>(loc, callOp.getCallee().getValue(),
                                    newResultTypes, newOperands);
     } else {
       // Indirect calls.

diff  --git a/flang/lib/Optimizer/Transforms/AffinePromotion.cpp b/flang/lib/Optimizer/Transforms/AffinePromotion.cpp
index dd7b2591bf3fc..3890721cea25a 100644
--- a/flang/lib/Optimizer/Transforms/AffinePromotion.cpp
+++ b/flang/lib/Optimizer/Transforms/AffinePromotion.cpp
@@ -171,11 +171,11 @@ struct AffineIfCondition {
       fromCmpIOp(condDef);
   }
 
-  bool hasIntegerSet() const { return integerSet.has_value(); }
+  bool hasIntegerSet() const { return integerSet.hasValue(); }
 
   mlir::IntegerSet getIntegerSet() const {
     assert(hasIntegerSet() && "integer set is missing");
-    return *integerSet;
+    return integerSet.getValue();
   }
 
   mlir::ValueRange getAffineArgs() const { return affineArgs; }
@@ -188,8 +188,8 @@ struct AffineIfCondition {
 
   MaybeAffineExpr affineBinaryOp(mlir::AffineExprKind kind, MaybeAffineExpr lhs,
                                  MaybeAffineExpr rhs) {
-    if (lhs && rhs)
-      return mlir::getAffineBinaryOpExpr(kind, *lhs, *rhs);
+    if (lhs.hasValue() && rhs.hasValue())
+      return mlir::getAffineBinaryOpExpr(kind, lhs.getValue(), rhs.getValue());
     return {};
   }
 
@@ -233,14 +233,15 @@ struct AffineIfCondition {
   void fromCmpIOp(mlir::arith::CmpIOp cmpOp) {
     auto lhsAffine = toAffineExpr(cmpOp.getLhs());
     auto rhsAffine = toAffineExpr(cmpOp.getRhs());
-    if (!lhsAffine || !rhsAffine)
+    if (!lhsAffine.hasValue() || !rhsAffine.hasValue())
       return;
-    auto constraintPair =
-        constraint(cmpOp.getPredicate(), *rhsAffine - *lhsAffine);
+    auto constraintPair = constraint(
+        cmpOp.getPredicate(), rhsAffine.getValue() - lhsAffine.getValue());
     if (!constraintPair)
       return;
-    integerSet = mlir::IntegerSet::get(
-        dimCount, symCount, {constraintPair->first}, {constraintPair->second});
+    integerSet = mlir::IntegerSet::get(dimCount, symCount,
+                                       {constraintPair.getValue().first},
+                                       {constraintPair.getValue().second});
     return;
   }
 
@@ -483,8 +484,8 @@ class AffineLoopConversion : public mlir::OpRewritePattern<fir::DoLoopOp> {
   std::pair<mlir::AffineForOp, mlir::Value>
   createAffineFor(fir::DoLoopOp op, mlir::PatternRewriter &rewriter) const {
     if (auto constantStep = constantIntegerLike(op.getStep()))
-      if (*constantStep > 0)
-        return positiveConstantStep(op, *constantStep, rewriter);
+      if (constantStep.getValue() > 0)
+        return positiveConstantStep(op, constantStep.getValue(), rewriter);
     return genericBounds(op, rewriter);
   }
 

diff  --git a/flang/lib/Optimizer/Transforms/ExternalNameConversion.cpp b/flang/lib/Optimizer/Transforms/ExternalNameConversion.cpp
index 42260ad2826ac..6170556c24ac9 100644
--- a/flang/lib/Optimizer/Transforms/ExternalNameConversion.cpp
+++ b/flang/lib/Optimizer/Transforms/ExternalNameConversion.cpp
@@ -49,9 +49,9 @@ class MangleNameOnCallOp : public mlir::OpRewritePattern<fir::CallOp> {
                   mlir::PatternRewriter &rewriter) const override {
     rewriter.startRootUpdate(op);
     auto callee = op.getCallee();
-    if (callee) {
-      auto result =
-          fir::NameUniquer::deconstruct(callee->getRootReference().getValue());
+    if (callee.hasValue()) {
+      auto result = fir::NameUniquer::deconstruct(
+          callee.getValue().getRootReference().getValue());
       if (fir::NameUniquer::isExternalFacingUniquedName(result))
         op.setCalleeAttr(
             SymbolRefAttr::get(op.getContext(), mangleExternalName(result)));
@@ -137,9 +137,9 @@ void ExternalNameConversionPass::runOnOperation() {
                          acc::OpenACCDialect, omp::OpenMPDialect>();
 
   target.addDynamicallyLegalOp<fir::CallOp>([](fir::CallOp op) {
-    if (op.getCallee())
+    if (op.getCallee().hasValue())
       return !fir::NameUniquer::needExternalNameMangling(
-          op.getCallee()->getRootReference().getValue());
+          op.getCallee().getValue().getRootReference().getValue());
     return true;
   });
 

diff  --git a/flang/unittests/Optimizer/Builder/FIRBuilderTest.cpp b/flang/unittests/Optimizer/Builder/FIRBuilderTest.cpp
index 3172844cfe23b..3997d8fd50fe6 100644
--- a/flang/unittests/Optimizer/Builder/FIRBuilderTest.cpp
+++ b/flang/unittests/Optimizer/Builder/FIRBuilderTest.cpp
@@ -189,12 +189,12 @@ TEST_F(FIRBuilderTest, createGlobal1) {
       loc, i64Type, "global1", builder.createInternalLinkage(), {}, true);
   EXPECT_TRUE(mlir::isa<fir::GlobalOp>(global));
   EXPECT_EQ("global1", global.getSymName());
-  EXPECT_TRUE(global.getConstant().has_value());
+  EXPECT_TRUE(global.getConstant().hasValue());
   EXPECT_EQ(i64Type, global.getType());
-  EXPECT_TRUE(global.getLinkName().has_value());
-  EXPECT_EQ(
-      builder.createInternalLinkage().getValue(), global.getLinkName().value());
-  EXPECT_FALSE(global.getInitVal().has_value());
+  EXPECT_TRUE(global.getLinkName().hasValue());
+  EXPECT_EQ(builder.createInternalLinkage().getValue(),
+      global.getLinkName().getValue());
+  EXPECT_FALSE(global.getInitVal().hasValue());
 
   auto g1 = builder.getNamedGlobal("global1");
   EXPECT_EQ(global, g1);
@@ -213,14 +213,15 @@ TEST_F(FIRBuilderTest, createGlobal2) {
       loc, i32Type, "global2", builder.createLinkOnceLinkage(), attr, false);
   EXPECT_TRUE(mlir::isa<fir::GlobalOp>(global));
   EXPECT_EQ("global2", global.getSymName());
-  EXPECT_FALSE(global.getConstant().has_value());
+  EXPECT_FALSE(global.getConstant().hasValue());
   EXPECT_EQ(i32Type, global.getType());
-  EXPECT_TRUE(global.getInitVal().has_value());
-  EXPECT_TRUE(global.getInitVal()->isa<mlir::IntegerAttr>());
-  EXPECT_EQ(16, global.getInitVal()->cast<mlir::IntegerAttr>().getValue());
-  EXPECT_TRUE(global.getLinkName().has_value());
+  EXPECT_TRUE(global.getInitVal().hasValue());
+  EXPECT_TRUE(global.getInitVal().getValue().isa<mlir::IntegerAttr>());
   EXPECT_EQ(
-      builder.createLinkOnceLinkage().getValue(), global.getLinkName().value());
+      16, global.getInitVal().getValue().cast<mlir::IntegerAttr>().getValue());
+  EXPECT_TRUE(global.getLinkName().hasValue());
+  EXPECT_EQ(builder.createLinkOnceLinkage().getValue(),
+      global.getLinkName().getValue());
 }
 
 TEST_F(FIRBuilderTest, uniqueCFIdent) {
@@ -309,8 +310,8 @@ TEST_F(FIRBuilderTest, createStringLiteral) {
   auto addrOp = dyn_cast<fir::AddrOfOp>(addr.getDefiningOp());
   auto symbol = addrOp.getSymbol().getRootReference().getValue();
   auto global = builder.getNamedGlobal(symbol);
-  EXPECT_EQ(
-      builder.createLinkOnceLinkage().getValue(), global.getLinkName().value());
+  EXPECT_EQ(builder.createLinkOnceLinkage().getValue(),
+      global.getLinkName().getValue());
   EXPECT_EQ(fir::CharacterType::get(builder.getContext(), 1, strValue.size()),
       global.getType());
 
@@ -332,9 +333,9 @@ TEST_F(FIRBuilderTest, allocateLocal) {
   EXPECT_TRUE(mlir::isa<fir::AllocaOp>(var.getDefiningOp()));
   auto allocaOp = dyn_cast<fir::AllocaOp>(var.getDefiningOp());
   EXPECT_EQ(builder.getI64Type(), allocaOp.getInType());
-  EXPECT_TRUE(allocaOp.getBindcName().has_value());
-  EXPECT_EQ(varName, allocaOp.getBindcName().value());
-  EXPECT_FALSE(allocaOp.getUniqName().has_value());
+  EXPECT_TRUE(allocaOp.getBindcName().hasValue());
+  EXPECT_EQ(varName, allocaOp.getBindcName().getValue());
+  EXPECT_FALSE(allocaOp.getUniqName().hasValue());
   EXPECT_FALSE(allocaOp.getPinned());
   EXPECT_EQ(0u, allocaOp.getTypeparams().size());
   EXPECT_EQ(0u, allocaOp.getShape().size());

diff  --git a/flang/unittests/Optimizer/Builder/Runtime/RuntimeCallTestBase.h b/flang/unittests/Optimizer/Builder/Runtime/RuntimeCallTestBase.h
index 4b7c9f18543a8..8d549c54a0530 100644
--- a/flang/unittests/Optimizer/Builder/Runtime/RuntimeCallTestBase.h
+++ b/flang/unittests/Optimizer/Builder/Runtime/RuntimeCallTestBase.h
@@ -87,7 +87,7 @@ static inline void checkCallOp(mlir::Operation *op, llvm::StringRef fctName,
     unsigned nbArgs, bool addLocArgs = true) {
   EXPECT_TRUE(mlir::isa<fir::CallOp>(*op));
   auto callOp = mlir::dyn_cast<fir::CallOp>(*op);
-  EXPECT_TRUE(callOp.getCallee().has_value());
+  EXPECT_TRUE(callOp.getCallee().hasValue());
   mlir::SymbolRefAttr callee = *callOp.getCallee();
   EXPECT_EQ(fctName, callee.getRootReference().getValue());
   // sourceFile and sourceLine are added arguments.

diff  --git a/lld/ELF/InputFiles.cpp b/lld/ELF/InputFiles.cpp
index a9b00b73caf20..926400d047ece 100644
--- a/lld/ELF/InputFiles.cpp
+++ b/lld/ELF/InputFiles.cpp
@@ -744,9 +744,9 @@ static void updateARMVFPArgs(const ARMAttributeParser &attributes,
 static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) {
   Optional<unsigned> attr =
       attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
-  if (!attr)
+  if (!attr.hasValue())
     return;
-  auto arch = *attr;
+  auto arch = attr.getValue();
   switch (arch) {
   case ARMBuildAttrs::Pre_v4:
   case ARMBuildAttrs::v4:

diff  --git a/lld/MachO/SectionPriorities.cpp b/lld/MachO/SectionPriorities.cpp
index 0794217b66fd8..cdabd3e9ef465 100644
--- a/lld/MachO/SectionPriorities.cpp
+++ b/lld/MachO/SectionPriorities.cpp
@@ -367,10 +367,10 @@ macho::PriorityBuilder::buildInputSectionPriorities() {
 
   auto addSym = [&](const Defined *sym) {
     Optional<size_t> symbolPriority = getSymbolPriority(sym);
-    if (!symbolPriority)
+    if (!symbolPriority.hasValue())
       return;
     size_t &priority = sectionPriorities[sym->isec];
-    priority = std::max(priority, *symbolPriority);
+    priority = std::max(priority, symbolPriority.getValue());
   };
 
   // TODO: Make sure this handles weak symbols correctly.

diff  --git a/lld/wasm/InputChunks.h b/lld/wasm/InputChunks.h
index 066ca623866d1..f9626160976ce 100644
--- a/lld/wasm/InputChunks.h
+++ b/lld/wasm/InputChunks.h
@@ -249,9 +249,9 @@ class InputFunction : public InputChunk {
 public:
   InputFunction(const WasmSignature &s, const WasmFunction *func, ObjFile *f)
       : InputChunk(f, InputChunk::Function, func->SymbolName), signature(s),
-        function(func),
-        exportName(func && func->ExportName ? (*func->ExportName).str()
-                                            : llvm::Optional<std::string>()) {
+        function(func), exportName(func && func->ExportName.hasValue()
+                                       ? (*func->ExportName).str()
+                                       : llvm::Optional<std::string>()) {
     inputSectionOffset = function->CodeSectionOffset;
     rawData =
         file->codeSection->Content.slice(inputSectionOffset, function->Size);
@@ -268,17 +268,17 @@ class InputFunction : public InputChunk {
   }
 
   llvm::Optional<StringRef> getExportName() const {
-    return exportName ? llvm::Optional<StringRef>(*exportName)
-                      : llvm::Optional<StringRef>();
+    return exportName.hasValue() ? llvm::Optional<StringRef>(*exportName)
+                                 : llvm::Optional<StringRef>();
   }
   void setExportName(std::string exportName) { this->exportName = exportName; }
   uint32_t getFunctionInputOffset() const { return getInputSectionOffset(); }
   uint32_t getFunctionCodeOffset() const { return function->CodeOffset; }
-  uint32_t getFunctionIndex() const { return *functionIndex; }
-  bool hasFunctionIndex() const { return functionIndex.has_value(); }
+  uint32_t getFunctionIndex() const { return functionIndex.getValue(); }
+  bool hasFunctionIndex() const { return functionIndex.hasValue(); }
   void setFunctionIndex(uint32_t index);
-  uint32_t getTableIndex() const { return *tableIndex; }
-  bool hasTableIndex() const { return tableIndex.has_value(); }
+  uint32_t getTableIndex() const { return tableIndex.getValue(); }
+  bool hasTableIndex() const { return tableIndex.hasValue(); }
   void setTableIndex(uint32_t index);
   void writeCompressed(uint8_t *buf) const;
 

diff  --git a/lld/wasm/InputElement.h b/lld/wasm/InputElement.h
index 0d4e9b388b31d..9bea90b87640c 100644
--- a/lld/wasm/InputElement.h
+++ b/lld/wasm/InputElement.h
@@ -27,8 +27,8 @@ class InputElement {
 
 public:
   StringRef getName() const { return name; }
-  uint32_t getAssignedIndex() const { return *assignedIndex; }
-  bool hasAssignedIndex() const { return assignedIndex.has_value(); }
+  uint32_t getAssignedIndex() const { return assignedIndex.getValue(); }
+  bool hasAssignedIndex() const { return assignedIndex.hasValue(); }
   void assignIndex(uint32_t index) {
     assert(!hasAssignedIndex());
     assignedIndex = index;

diff  --git a/lld/wasm/Writer.cpp b/lld/wasm/Writer.cpp
index 2de43abb3faa4..fa9802d477d55 100644
--- a/lld/wasm/Writer.cpp
+++ b/lld/wasm/Writer.cpp
@@ -446,10 +446,10 @@ void Writer::populateTargetFeatures() {
   }
 
   // Only infer used features if user did not specify features
-  bool inferFeatures = !config->features.has_value();
+  bool inferFeatures = !config->features.hasValue();
 
   if (!inferFeatures) {
-    auto &explicitFeatures = config->features.value();
+    auto &explicitFeatures = config->features.getValue();
     allowed.insert(explicitFeatures.begin(), explicitFeatures.end());
     if (!config->checkFeatures)
       goto done;

diff  --git a/lldb/include/lldb/Target/MemoryRegionInfo.h b/lldb/include/lldb/Target/MemoryRegionInfo.h
index 8df790452506c..acca66e838337 100644
--- a/lldb/include/lldb/Target/MemoryRegionInfo.h
+++ b/lldb/include/lldb/Target/MemoryRegionInfo.h
@@ -124,8 +124,8 @@ class MemoryRegionInfo {
   void SetPageSize(int pagesize) { m_pagesize = pagesize; }
 
   void SetDirtyPageList(std::vector<lldb::addr_t> pagelist) {
-    if (m_dirty_pages)
-      m_dirty_pages->clear();
+    if (m_dirty_pages.hasValue())
+      m_dirty_pages.getValue().clear();
     m_dirty_pages = std::move(pagelist);
   }
 

diff  --git a/lldb/source/API/SBMemoryRegionInfo.cpp b/lldb/source/API/SBMemoryRegionInfo.cpp
index f4d78cf095468..d0f74374476e0 100644
--- a/lldb/source/API/SBMemoryRegionInfo.cpp
+++ b/lldb/source/API/SBMemoryRegionInfo.cpp
@@ -135,8 +135,8 @@ uint32_t SBMemoryRegionInfo::GetNumDirtyPages() {
   uint32_t num_dirty_pages = 0;
   const llvm::Optional<std::vector<addr_t>> &dirty_page_list =
       m_opaque_up->GetDirtyPageList();
-  if (dirty_page_list)
-    num_dirty_pages = dirty_page_list->size();
+  if (dirty_page_list.hasValue())
+    num_dirty_pages = dirty_page_list.getValue().size();
 
   return num_dirty_pages;
 }
@@ -147,8 +147,8 @@ addr_t SBMemoryRegionInfo::GetDirtyPageAddressAtIndex(uint32_t idx) {
   addr_t dirty_page_addr = LLDB_INVALID_ADDRESS;
   const llvm::Optional<std::vector<addr_t>> &dirty_page_list =
       m_opaque_up->GetDirtyPageList();
-  if (dirty_page_list && idx < dirty_page_list->size())
-    dirty_page_addr = dirty_page_list.value()[idx];
+  if (dirty_page_list.hasValue() && idx < dirty_page_list.getValue().size())
+    dirty_page_addr = dirty_page_list.getValue()[idx];
 
   return dirty_page_addr;
 }

diff  --git a/lldb/source/Breakpoint/BreakpointIDList.cpp b/lldb/source/Breakpoint/BreakpointIDList.cpp
index 20f75662ce5ae..b434056993640 100644
--- a/lldb/source/Breakpoint/BreakpointIDList.cpp
+++ b/lldb/source/Breakpoint/BreakpointIDList.cpp
@@ -192,14 +192,16 @@ void BreakpointIDList::FindAndReplaceIDRanges(Args &old_args, Target *target,
     auto start_bp = BreakpointID::ParseCanonicalReference(range_from);
     auto end_bp = BreakpointID::ParseCanonicalReference(range_to);
 
-    if (!start_bp || !target->GetBreakpointByID(start_bp->GetBreakpointID())) {
+    if (!start_bp.hasValue() ||
+        !target->GetBreakpointByID(start_bp->GetBreakpointID())) {
       new_args.Clear();
       result.AppendErrorWithFormat("'%s' is not a valid breakpoint ID.\n",
                                    range_from.str().c_str());
       return;
     }
 
-    if (!end_bp || !target->GetBreakpointByID(end_bp->GetBreakpointID())) {
+    if (!end_bp.hasValue() ||
+        !target->GetBreakpointByID(end_bp->GetBreakpointID())) {
       new_args.Clear();
       result.AppendErrorWithFormat("'%s' is not a valid breakpoint ID.\n",
                                    range_to.str().c_str());

diff  --git a/lldb/source/Commands/CommandObjectFrame.cpp b/lldb/source/Commands/CommandObjectFrame.cpp
index dfe1e14515fa7..4081e87f2ddb9 100644
--- a/lldb/source/Commands/CommandObjectFrame.cpp
+++ b/lldb/source/Commands/CommandObjectFrame.cpp
@@ -137,16 +137,16 @@ class CommandObjectFrameDiagnose : public CommandObjectParsed {
 
     ValueObjectSP valobj_sp;
 
-    if (m_options.address) {
-      if (m_options.reg || m_options.offset) {
+    if (m_options.address.hasValue()) {
+      if (m_options.reg.hasValue() || m_options.offset.hasValue()) {
         result.AppendError(
             "`frame diagnose --address` is incompatible with other arguments.");
         return false;
       }
-      valobj_sp = frame_sp->GuessValueForAddress(*m_options.address);
-    } else if (m_options.reg) {
+      valobj_sp = frame_sp->GuessValueForAddress(m_options.address.getValue());
+    } else if (m_options.reg.hasValue()) {
       valobj_sp = frame_sp->GuessValueForRegisterAndOffset(
-          m_options.reg.value(), m_options.offset.value_or(0));
+          m_options.reg.getValue(), m_options.offset.value_or(0));
     } else {
       StopInfoSP stop_info_sp = thread->GetStopInfo();
       if (!stop_info_sp) {

diff  --git a/lldb/source/Commands/CommandObjectMemory.cpp b/lldb/source/Commands/CommandObjectMemory.cpp
index be887f17e589a..117b5f468d4d7 100644
--- a/lldb/source/Commands/CommandObjectMemory.cpp
+++ b/lldb/source/Commands/CommandObjectMemory.cpp
@@ -1737,8 +1737,8 @@ class CommandObjectMemoryRegion : public CommandObjectParsed {
 
     const llvm::Optional<std::vector<addr_t>> &dirty_page_list =
         range_info.GetDirtyPageList();
-    if (dirty_page_list) {
-      const size_t page_count = dirty_page_list->size();
+    if (dirty_page_list.hasValue()) {
+      const size_t page_count = dirty_page_list.getValue().size();
       result.AppendMessageWithFormat(
           "Modified memory (dirty) page list provided, %zu entries.\n",
           page_count);

diff  --git a/lldb/source/Core/DataFileCache.cpp b/lldb/source/Core/DataFileCache.cpp
index b38adfda169aa..5f8568fdb54f2 100644
--- a/lldb/source/Core/DataFileCache.cpp
+++ b/lldb/source/Core/DataFileCache.cpp
@@ -203,17 +203,17 @@ bool CacheSignature::Encode(DataEncoder &encoder) const {
   if (!IsValid())
     return false; // Invalid signature, return false!
 
-  if (m_uuid) {
+  if (m_uuid.hasValue()) {
     llvm::ArrayRef<uint8_t> uuid_bytes = m_uuid->GetBytes();
     encoder.AppendU8(eSignatureUUID);
     encoder.AppendU8(uuid_bytes.size());
     encoder.AppendData(uuid_bytes);
   }
-  if (m_mod_time) {
+  if (m_mod_time.hasValue()) {
     encoder.AppendU8(eSignatureModTime);
     encoder.AppendU32(*m_mod_time);
   }
-  if (m_obj_mod_time) {
+  if (m_obj_mod_time.hasValue()) {
     encoder.AppendU8(eSignatureObjectModTime);
     encoder.AppendU32(*m_obj_mod_time);
   }

diff  --git a/lldb/source/Core/DumpDataExtractor.cpp b/lldb/source/Core/DumpDataExtractor.cpp
index f96c2328f1dcf..211e16a2e0337 100644
--- a/lldb/source/Core/DumpDataExtractor.cpp
+++ b/lldb/source/Core/DumpDataExtractor.cpp
@@ -118,8 +118,8 @@ static lldb::offset_t DumpAPInt(Stream *s, const DataExtractor &data,
                                 lldb::offset_t offset, lldb::offset_t byte_size,
                                 bool is_signed, unsigned radix) {
   llvm::Optional<llvm::APInt> apint = GetAPInt(data, &offset, byte_size);
-  if (apint) {
-    std::string apint_str = toString(*apint, radix, is_signed);
+  if (apint.hasValue()) {
+    std::string apint_str = toString(apint.getValue(), radix, is_signed);
     switch (radix) {
     case 2:
       s->Write("0b", 2);
@@ -670,8 +670,8 @@ lldb::offset_t lldb_private::DumpDataExtractor(
               (llvm::APFloat::getSizeInBits(semantics) + 7) / 8;
           llvm::Optional<llvm::APInt> apint =
               GetAPInt(DE, &offset, semantics_byte_size);
-          if (apint) {
-            llvm::APFloat apfloat(semantics, *apint);
+          if (apint.hasValue()) {
+            llvm::APFloat apfloat(semantics, apint.getValue());
             apfloat.toString(sv, format_precision, format_max_padding);
             if (!sv.empty()) {
               s->Printf("%*.*s", (int)sv.size(), (int)sv.size(), sv.data());

diff  --git a/lldb/source/Core/ValueObjectChild.cpp b/lldb/source/Core/ValueObjectChild.cpp
index f0c91e48ac564..a2beeb0bcdebe 100644
--- a/lldb/source/Core/ValueObjectChild.cpp
+++ b/lldb/source/Core/ValueObjectChild.cpp
@@ -82,8 +82,8 @@ ConstString ValueObjectChild::GetDisplayTypeName() {
 }
 
 LazyBool ValueObjectChild::CanUpdateWithInvalidExecutionContext() {
-  if (m_can_update_with_invalid_exe_ctx)
-    return *m_can_update_with_invalid_exe_ctx;
+  if (m_can_update_with_invalid_exe_ctx.hasValue())
+    return m_can_update_with_invalid_exe_ctx.getValue();
   if (m_parent) {
     ValueObject *opinionated_parent =
         m_parent->FollowParentChain([](ValueObject *valobj) -> bool {
@@ -93,11 +93,11 @@ LazyBool ValueObjectChild::CanUpdateWithInvalidExecutionContext() {
     if (opinionated_parent)
       return (m_can_update_with_invalid_exe_ctx =
                   opinionated_parent->CanUpdateWithInvalidExecutionContext())
-          .value();
+          .getValue();
   }
   return (m_can_update_with_invalid_exe_ctx =
               this->ValueObject::CanUpdateWithInvalidExecutionContext())
-      .value();
+      .getValue();
 }
 
 bool ValueObjectChild::UpdateValue() {

diff  --git a/lldb/source/Host/common/File.cpp b/lldb/source/Host/common/File.cpp
index 476ab23b45c34..760fb98fb496e 100644
--- a/lldb/source/Host/common/File.cpp
+++ b/lldb/source/Host/common/File.cpp
@@ -833,19 +833,22 @@ SerialPort::Create(int fd, OpenOptions options, Options serial_options,
   if (llvm::Error error = term.SetRaw())
     return std::move(error);
   if (serial_options.BaudRate) {
-    if (llvm::Error error = term.SetBaudRate(*serial_options.BaudRate))
+    if (llvm::Error error =
+            term.SetBaudRate(serial_options.BaudRate.getValue()))
       return std::move(error);
   }
   if (serial_options.Parity) {
-    if (llvm::Error error = term.SetParity(*serial_options.Parity))
+    if (llvm::Error error = term.SetParity(serial_options.Parity.getValue()))
       return std::move(error);
   }
   if (serial_options.ParityCheck) {
-    if (llvm::Error error = term.SetParityCheck(*serial_options.ParityCheck))
+    if (llvm::Error error =
+            term.SetParityCheck(serial_options.ParityCheck.getValue()))
       return std::move(error);
   }
   if (serial_options.StopBits) {
-    if (llvm::Error error = term.SetStopBits(*serial_options.StopBits))
+    if (llvm::Error error =
+            term.SetStopBits(serial_options.StopBits.getValue()))
       return std::move(error);
   }
 

diff  --git a/lldb/source/Host/common/Terminal.cpp b/lldb/source/Host/common/Terminal.cpp
index 6eb7332d336ad..831e9dff4eb18 100644
--- a/lldb/source/Host/common/Terminal.cpp
+++ b/lldb/source/Host/common/Terminal.cpp
@@ -281,11 +281,11 @@ llvm::Error Terminal::SetBaudRate(unsigned int baud_rate) {
     return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                    "baud rate %d unsupported by the platform",
                                    baud_rate);
-  if (::cfsetispeed(&fd_termios, *val) != 0)
+  if (::cfsetispeed(&fd_termios, val.getValue()) != 0)
     return llvm::createStringError(
         std::error_code(errno, std::generic_category()),
         "setting input baud rate failed");
-  if (::cfsetospeed(&fd_termios, *val) != 0)
+  if (::cfsetospeed(&fd_termios, val.getValue()) != 0)
     return llvm::createStringError(
         std::error_code(errno, std::generic_category()),
         "setting output baud rate failed");

diff  --git a/lldb/source/Plugins/ABI/X86/ABIX86.cpp b/lldb/source/Plugins/ABI/X86/ABIX86.cpp
index 64c5d5a1174f6..2cd653fe2c5e8 100644
--- a/lldb/source/Plugins/ABI/X86/ABIX86.cpp
+++ b/lldb/source/Plugins/ABI/X86/ABIX86.cpp
@@ -100,8 +100,8 @@ addCombinedRegisters(std::vector<DynamicRegisterInfo::Register> &regs,
     if (regdata1->subreg_name != regdata2->subreg_name)
       continue;
 
-    uint32_t base_index1 = *regdata1->base_index;
-    uint32_t base_index2 = *regdata2->base_index;
+    uint32_t base_index1 = regdata1->base_index.getValue();
+    uint32_t base_index2 = regdata2->base_index.getValue();
     if (regs[base_index1].byte_size != base_size ||
         regs[base_index2].byte_size != base_size)
       continue;

diff  --git a/lldb/source/Plugins/Disassembler/LLVMC/DisassemblerLLVMC.cpp b/lldb/source/Plugins/Disassembler/LLVMC/DisassemblerLLVMC.cpp
index 1f5addca9e704..e4c7e8fa3b83b 100644
--- a/lldb/source/Plugins/Disassembler/LLVMC/DisassemblerLLVMC.cpp
+++ b/lldb/source/Plugins/Disassembler/LLVMC/DisassemblerLLVMC.cpp
@@ -1382,14 +1382,14 @@ const char *DisassemblerLLVMC::SymbolLookup(uint64_t value, uint64_t *type_ptr,
         // the ADRP's register and this ADD's register are the same,
         // then this is a pc-relative address calculation.
         if (*type_ptr == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
-            m_adrp_insn && m_adrp_address == pc - 4 &&
-            (*m_adrp_insn & 0x1f) == ((value >> 5) & 0x1f)) {
+            m_adrp_insn.hasValue() && m_adrp_address == pc - 4 &&
+            (m_adrp_insn.getValue() & 0x1f) == ((value >> 5) & 0x1f)) {
           uint32_t addxri_inst;
           uint64_t adrp_imm, addxri_imm;
           // Get immlo and immhi bits, OR them together to get the ADRP imm
           // value.
-          adrp_imm =
-              ((*m_adrp_insn & 0x00ffffe0) >> 3) | ((*m_adrp_insn >> 29) & 0x3);
+          adrp_imm = ((m_adrp_insn.getValue() & 0x00ffffe0) >> 3) |
+                     ((m_adrp_insn.getValue() >> 29) & 0x3);
           // if high bit of immhi after right-shifting set, sign extend
           if (adrp_imm & (1ULL << 20))
             adrp_imm |= ~((1ULL << 21) - 1);

diff  --git a/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp b/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
index 4f23ff4437d9a..82f825871593d 100644
--- a/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
+++ b/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
@@ -218,10 +218,10 @@ void CPlusPlusLanguage::MethodName::Parse() {
     } else {
       CPlusPlusNameParser parser(m_full.GetStringRef());
       if (auto function = parser.ParseAsFunctionDefinition()) {
-        m_basename = function->name.basename;
-        m_context = function->name.context;
-        m_arguments = function->arguments;
-        m_qualifiers = function->qualifiers;
+        m_basename = function.getValue().name.basename;
+        m_context = function.getValue().name.context;
+        m_arguments = function.getValue().arguments;
+        m_qualifiers = function.getValue().qualifiers;
         m_parse_error = false;
       } else {
         m_parse_error = true;
@@ -329,8 +329,8 @@ bool CPlusPlusLanguage::ExtractContextAndIdentifier(
 
   CPlusPlusNameParser parser(name);
   if (auto full_name = parser.ParseAsFullName()) {
-    identifier = full_name->basename;
-    context = full_name->context;
+    identifier = full_name.getValue().basename;
+    context = full_name.getValue().context;
     return true;
   }
   return false;

diff  --git a/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.cpp b/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.cpp
index 3a1fde28c65cc..eca36fff18f83 100644
--- a/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.cpp
+++ b/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.cpp
@@ -55,8 +55,8 @@ Optional<ParsedName> CPlusPlusNameParser::ParseAsFullName() {
   if (HasMoreTokens())
     return None;
   ParsedName result;
-  result.basename = GetTextForRange(name_ranges->basename_range);
-  result.context = GetTextForRange(name_ranges->context_range);
+  result.basename = GetTextForRange(name_ranges.getValue().basename_range);
+  result.context = GetTextForRange(name_ranges.getValue().context_range);
   return result;
 }
 
@@ -125,8 +125,8 @@ CPlusPlusNameParser::ParseFunctionImpl(bool expect_return_type) {
   size_t end_position = GetCurrentPosition();
 
   ParsedFunction result;
-  result.name.basename = GetTextForRange(maybe_name->basename_range);
-  result.name.context = GetTextForRange(maybe_name->context_range);
+  result.name.basename = GetTextForRange(maybe_name.getValue().basename_range);
+  result.name.context = GetTextForRange(maybe_name.getValue().context_range);
   result.arguments = GetTextForRange(Range(argument_start, qualifiers_start));
   result.qualifiers = GetTextForRange(Range(qualifiers_start, end_position));
   start_position.Remove();
@@ -616,10 +616,10 @@ CPlusPlusNameParser::ParseFullNameImpl() {
       state == State::AfterTemplate) {
     ParsedNameRanges result;
     if (last_coloncolon_position) {
-      result.context_range =
-          Range(start_position.GetSavedPosition(), *last_coloncolon_position);
+      result.context_range = Range(start_position.GetSavedPosition(),
+                                   last_coloncolon_position.getValue());
       result.basename_range =
-          Range(*last_coloncolon_position + 1, GetCurrentPosition());
+          Range(last_coloncolon_position.getValue() + 1, GetCurrentPosition());
     } else {
       result.basename_range =
           Range(start_position.GetSavedPosition(), GetCurrentPosition());

diff  --git a/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp b/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp
index 045bdd4e2808f..fdebfcd388ff9 100644
--- a/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp
+++ b/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp
@@ -6516,8 +6516,8 @@ bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
             addr_t pagesize = range_info.GetPageSize();
             const llvm::Optional<std::vector<addr_t>> &dirty_page_list =
                 range_info.GetDirtyPageList();
-            if (dirty_pages_only && dirty_page_list) {
-              for (addr_t dirtypage : *dirty_page_list) {
+            if (dirty_pages_only && dirty_page_list.hasValue()) {
+              for (addr_t dirtypage : dirty_page_list.getValue()) {
                 page_object obj;
                 obj.addr = dirtypage;
                 obj.size = pagesize;

diff  --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp
index c44ace96dd55c..9f159f6188997 100644
--- a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp
+++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp
@@ -2722,12 +2722,12 @@ bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid,
     return true;
 
   llvm::Optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'g');
-  if (ret) {
+  if (ret.hasValue()) {
     if (ret->pid != LLDB_INVALID_PROCESS_ID)
       m_curr_pid = ret->pid;
     m_curr_tid = ret->tid;
   }
-  return ret.has_value();
+  return ret.hasValue();
 }
 
 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid,
@@ -2737,12 +2737,12 @@ bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid,
     return true;
 
   llvm::Optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'c');
-  if (ret) {
+  if (ret.hasValue()) {
     if (ret->pid != LLDB_INVALID_PROCESS_ID)
       m_curr_pid_run = ret->pid;
     m_curr_tid_run = ret->tid;
   }
-  return ret.has_value();
+  return ret.hasValue();
 }
 
 bool GDBRemoteCommunicationClient::GetStopReply(

diff  --git a/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.cpp b/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.cpp
index b5615c358b959..11175a410aa92 100644
--- a/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.cpp
+++ b/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.cpp
@@ -674,9 +674,9 @@ SymbolFileBreakpad::ParseCFIUnwindPlan(const Bookmark &bookmark,
   plan_sp->AppendRow(row_sp);
   for (++It; It != End; ++It) {
     llvm::Optional<StackCFIRecord> record = StackCFIRecord::parse(*It);
-    if (!record)
+    if (!record.hasValue())
       return nullptr;
-    if (record->Size)
+    if (record->Size.hasValue())
       break;
 
     row_sp = std::make_shared<UnwindPlan::Row>(*row_sp);

diff  --git a/lldb/source/Target/Thread.cpp b/lldb/source/Target/Thread.cpp
index 247913c5b615f..3803748be2971 100644
--- a/lldb/source/Target/Thread.cpp
+++ b/lldb/source/Target/Thread.cpp
@@ -2022,8 +2022,7 @@ lldb::ValueObjectSP Thread::GetSiginfoValue() {
 
   llvm::Optional<uint64_t> type_size = type.GetByteSize(nullptr);
   assert(type_size);
-  llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> data =
-      GetSiginfo(*type_size);
+  llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> data = GetSiginfo(type_size.getValue());
   if (!data)
     return ValueObjectConstResult::Create(&target, Status(data.takeError()));
 

diff  --git a/lldb/source/Target/UnixSignals.cpp b/lldb/source/Target/UnixSignals.cpp
index a92138ad2514f..de1fdb8cc4202 100644
--- a/lldb/source/Target/UnixSignals.cpp
+++ b/lldb/source/Target/UnixSignals.cpp
@@ -300,13 +300,14 @@ UnixSignals::GetFilteredSignals(llvm::Optional<bool> should_suppress,
 
     // If any of filtering conditions are not met, we move on to the next
     // signal.
-    if (should_suppress && signal_suppress != *should_suppress)
+    if (should_suppress.hasValue() &&
+        signal_suppress != should_suppress.getValue())
       continue;
 
-    if (should_stop && signal_stop != *should_stop)
+    if (should_stop.hasValue() && signal_stop != should_stop.getValue())
       continue;
 
-    if (should_notify && signal_notify != *should_notify)
+    if (should_notify.hasValue() && signal_notify != should_notify.getValue())
       continue;
 
     result.push_back(signo);

diff  --git a/lldb/source/Utility/SelectHelper.cpp b/lldb/source/Utility/SelectHelper.cpp
index 69b2abf1bc17c..eee6895296be6 100644
--- a/lldb/source/Utility/SelectHelper.cpp
+++ b/lldb/source/Utility/SelectHelper.cpp
@@ -161,15 +161,15 @@ lldb_private::Status SelectHelper::Select() {
   fd_set write_fdset;
   fd_set error_fdset;
 
-  if (max_read_fd) {
+  if (max_read_fd.hasValue()) {
     FD_ZERO(&read_fdset);
     read_fdset_ptr = &read_fdset;
   }
-  if (max_write_fd) {
+  if (max_write_fd.hasValue()) {
     FD_ZERO(&write_fdset);
     write_fdset_ptr = &write_fdset;
   }
-  if (max_error_fd) {
+  if (max_error_fd.hasValue()) {
     FD_ZERO(&error_fdset);
     error_fdset_ptr = &error_fdset;
   }
@@ -195,10 +195,10 @@ lldb_private::Status SelectHelper::Select() {
   while (true) {
     using namespace std::chrono;
     // Setup out relative timeout based on the end time if we have one
-    if (m_end_time) {
+    if (m_end_time.hasValue()) {
       tv_ptr = &tv;
-      const auto remaining_dur =
-          duration_cast<microseconds>(*m_end_time - steady_clock::now());
+      const auto remaining_dur = duration_cast<microseconds>(
+          m_end_time.getValue() - steady_clock::now());
       if (remaining_dur.count() > 0) {
         // Wait for a specific amount of time
         const auto dur_secs = duration_cast<seconds>(remaining_dur);

diff  --git a/lldb/unittests/Host/ConnectionFileDescriptorTest.cpp b/lldb/unittests/Host/ConnectionFileDescriptorTest.cpp
index 14a0d17255908..eb4b824c6c147 100644
--- a/lldb/unittests/Host/ConnectionFileDescriptorTest.cpp
+++ b/lldb/unittests/Host/ConnectionFileDescriptorTest.cpp
@@ -28,7 +28,7 @@ class ConnectionFileDescriptorTest : public testing::Test {
 
     std::string uri(connection_file_descriptor.GetURI());
     EXPECT_EQ((URI{"connect", ip, socket->GetRemotePortNumber(), "/"}),
-              *URI::Parse(uri));
+              URI::Parse(uri).getValue());
   }
 };
 

diff  --git a/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp b/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp
index b80c44dfae828..d15b85204b555 100644
--- a/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp
+++ b/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp
@@ -190,14 +190,14 @@ TEST_F(GDBRemoteCommunicationClientTest, GetModulesInfo) {
       R"("file_path":"/foo/bar.so","file_offset":0,"file_size":1234}]])");
 
   auto result = async_result.get();
-  ASSERT_TRUE(result.has_value());
+  ASSERT_TRUE(result.hasValue());
   ASSERT_EQ(1u, result->size());
-  EXPECT_EQ("/foo/bar.so", result.value()[0].GetFileSpec().GetPath());
-  EXPECT_EQ(triple, result.value()[0].GetArchitecture().GetTriple());
+  EXPECT_EQ("/foo/bar.so", result.getValue()[0].GetFileSpec().GetPath());
+  EXPECT_EQ(triple, result.getValue()[0].GetArchitecture().GetTriple());
   EXPECT_EQ(UUID::fromData("@ABCDEFGHIJKLMNO", 16),
-            result.value()[0].GetUUID());
-  EXPECT_EQ(0u, result.value()[0].GetObjectOffset());
-  EXPECT_EQ(1234u, result.value()[0].GetObjectSize());
+            result.getValue()[0].GetUUID());
+  EXPECT_EQ(0u, result.getValue()[0].GetObjectOffset());
+  EXPECT_EQ(1234u, result.getValue()[0].GetObjectSize());
 }
 
 TEST_F(GDBRemoteCommunicationClientTest, GetModulesInfo_UUID20) {
@@ -215,14 +215,14 @@ TEST_F(GDBRemoteCommunicationClientTest, GetModulesInfo_UUID20) {
       R"("file_path":"/foo/bar.so","file_offset":0,"file_size":1234}]])");
 
   auto result = async_result.get();
-  ASSERT_TRUE(result.has_value());
+  ASSERT_TRUE(result.hasValue());
   ASSERT_EQ(1u, result->size());
-  EXPECT_EQ("/foo/bar.so", result.value()[0].GetFileSpec().GetPath());
-  EXPECT_EQ(triple, result.value()[0].GetArchitecture().GetTriple());
+  EXPECT_EQ("/foo/bar.so", result.getValue()[0].GetFileSpec().GetPath());
+  EXPECT_EQ(triple, result.getValue()[0].GetArchitecture().GetTriple());
   EXPECT_EQ(UUID::fromData("@ABCDEFGHIJKLMNOPQRS", 20),
-            result.value()[0].GetUUID());
-  EXPECT_EQ(0u, result.value()[0].GetObjectOffset());
-  EXPECT_EQ(1234u, result.value()[0].GetObjectSize());
+            result.getValue()[0].GetUUID());
+  EXPECT_EQ(0u, result.getValue()[0].GetObjectOffset());
+  EXPECT_EQ(1234u, result.getValue()[0].GetObjectSize());
 }
 
 TEST_F(GDBRemoteCommunicationClientTest, GetModulesInfoInvalidResponse) {

diff  --git a/lldb/unittests/Process/minidump/MinidumpParserTest.cpp b/lldb/unittests/Process/minidump/MinidumpParserTest.cpp
index 85a15b84ecddb..95e2cf30b3dae 100644
--- a/lldb/unittests/Process/minidump/MinidumpParserTest.cpp
+++ b/lldb/unittests/Process/minidump/MinidumpParserTest.cpp
@@ -183,7 +183,7 @@ TEST_F(MinidumpParserTest, GetLinuxProcStatus) {
 )"),
                     llvm::Succeeded());
   llvm::Optional<LinuxProcStatus> proc_status = parser->GetLinuxProcStatus();
-  ASSERT_TRUE(proc_status.has_value());
+  ASSERT_TRUE(proc_status.hasValue());
   lldb::pid_t pid = proc_status->GetPid();
   ASSERT_EQ(16001UL, pid);
 }
@@ -218,8 +218,8 @@ TEST_F(MinidumpParserTest, GetPid) {
 )"),
                     llvm::Succeeded());
   llvm::Optional<lldb::pid_t> pid = parser->GetPid();
-  ASSERT_TRUE(pid.has_value());
-  ASSERT_EQ(16001UL, *pid);
+  ASSERT_TRUE(pid.hasValue());
+  ASSERT_EQ(16001UL, pid.getValue());
 }
 
 TEST_F(MinidumpParserTest, GetFilteredModuleList) {
@@ -260,7 +260,7 @@ TEST_F(MinidumpParserTest, GetExceptionStream) {
 void check_mem_range_exists(MinidumpParser &parser, const uint64_t range_start,
                             const uint64_t range_size) {
   llvm::Optional<minidump::Range> range = parser.FindMemoryRange(range_start);
-  ASSERT_TRUE(range.has_value()) << "There is no range containing this address";
+  ASSERT_TRUE(range.hasValue()) << "There is no range containing this address";
   EXPECT_EQ(range_start, range->start);
   EXPECT_EQ(range_start + range_size, range->start + range->range_ref.size());
 }
@@ -321,14 +321,14 @@ TEST_F(MinidumpParserTest, FindMemoryRangeWithFullMemoryMinidump) {
   SetUpData("fizzbuzz_wow64.dmp");
 
   // There are a lot of ranges in the file, just testing with some of them
-  EXPECT_FALSE(parser->FindMemoryRange(0x00).has_value());
-  EXPECT_FALSE(parser->FindMemoryRange(0x2a).has_value());
+  EXPECT_FALSE(parser->FindMemoryRange(0x00).hasValue());
+  EXPECT_FALSE(parser->FindMemoryRange(0x2a).hasValue());
   check_mem_range_exists(*parser, 0x10000, 65536); // first range
   check_mem_range_exists(*parser, 0x40000, 4096);
-  EXPECT_FALSE(parser->FindMemoryRange(0x40000 + 4096).has_value());
+  EXPECT_FALSE(parser->FindMemoryRange(0x40000 + 4096).hasValue());
   check_mem_range_exists(*parser, 0x77c12000, 8192);
   check_mem_range_exists(*parser, 0x7ffe0000, 4096); // last range
-  EXPECT_FALSE(parser->FindMemoryRange(0x7ffe0000 + 4096).has_value());
+  EXPECT_FALSE(parser->FindMemoryRange(0x7ffe0000 + 4096).hasValue());
 }
 
 constexpr auto yes = MemoryRegionInfo::eYes;
@@ -544,23 +544,23 @@ TEST_F(MinidumpParserTest, GetMiscInfoWindows) {
   const MinidumpMiscInfo *misc_info = parser->GetMiscInfo();
   ASSERT_NE(nullptr, misc_info);
   llvm::Optional<lldb::pid_t> pid = misc_info->GetPid();
-  ASSERT_TRUE(pid.has_value());
-  ASSERT_EQ(4440UL, *pid);
+  ASSERT_TRUE(pid.hasValue());
+  ASSERT_EQ(4440UL, pid.getValue());
 }
 
 TEST_F(MinidumpParserTest, GetPidWindows) {
   SetUpData("fizzbuzz_no_heap.dmp");
   llvm::Optional<lldb::pid_t> pid = parser->GetPid();
-  ASSERT_TRUE(pid.has_value());
-  ASSERT_EQ(4440UL, *pid);
+  ASSERT_TRUE(pid.hasValue());
+  ASSERT_EQ(4440UL, pid.getValue());
 }
 
 // wow64
 TEST_F(MinidumpParserTest, GetPidWow64) {
   SetUpData("fizzbuzz_wow64.dmp");
   llvm::Optional<lldb::pid_t> pid = parser->GetPid();
-  ASSERT_TRUE(pid.has_value());
-  ASSERT_EQ(7836UL, *pid);
+  ASSERT_TRUE(pid.hasValue());
+  ASSERT_EQ(7836UL, pid.getValue());
 }
 
 // Register tests

diff  --git a/lldb/unittests/Target/FindFileTest.cpp b/lldb/unittests/Target/FindFileTest.cpp
index 6715c347b77c6..77d374d1f498d 100644
--- a/lldb/unittests/Target/FindFileTest.cpp
+++ b/lldb/unittests/Target/FindFileTest.cpp
@@ -56,7 +56,7 @@ static void TestFileFindings(const PathMappingList &map,
     llvm::Optional<FileSpec> remapped;
 
     EXPECT_TRUE(bool(remapped = map.FindFile(match.original)));
-    EXPECT_TRUE(FileSpec(*remapped).GetPath() ==
+    EXPECT_TRUE(FileSpec(remapped.getValue()).GetPath() ==
                 ConstString(match.remapped).GetStringRef());
   }
 }

diff  --git a/lldb/unittests/Utility/StringExtractorGDBRemoteTest.cpp b/lldb/unittests/Utility/StringExtractorGDBRemoteTest.cpp
index 922167c342d90..88362c028a9db 100644
--- a/lldb/unittests/Utility/StringExtractorGDBRemoteTest.cpp
+++ b/lldb/unittests/Utility/StringExtractorGDBRemoteTest.cpp
@@ -109,77 +109,77 @@ TEST(StringExtractorGDBRemoteTest, GetPidTid) {
   // pure thread id
 
   ex.Reset("-1");
-  EXPECT_THAT(ex.GetPidTid(100).value(),
+  EXPECT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(100, StringExtractorGDBRemote::AllThreads));
 
   ex.Reset("1234");
-  EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(100, 0x1234ULL));
+  EXPECT_THAT(ex.GetPidTid(100).getValue(), ::testing::Pair(100, 0x1234ULL));
 
   ex.Reset("123456789ABCDEF0");
-  EXPECT_THAT(ex.GetPidTid(100).value(),
+  EXPECT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(100, 0x123456789ABCDEF0ULL));
 
   // pure process id
 
   ex.Reset("p-1");
-  EXPECT_THAT(ex.GetPidTid(100).value(),
+  EXPECT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(StringExtractorGDBRemote::AllProcesses,
                               StringExtractorGDBRemote::AllThreads));
 
   ex.Reset("p1234");
-  EXPECT_THAT(ex.GetPidTid(100).value(),
+  EXPECT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(0x1234ULL, StringExtractorGDBRemote::AllThreads));
 
   ex.Reset("p123456789ABCDEF0");
-  EXPECT_THAT(ex.GetPidTid(100).value(),
+  EXPECT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(0x123456789ABCDEF0ULL,
                               StringExtractorGDBRemote::AllThreads));
 
   ex.Reset("pFFFFFFFFFFFFFFFF");
-  EXPECT_THAT(ex.GetPidTid(100).value(),
+  EXPECT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(StringExtractorGDBRemote::AllProcesses,
                               StringExtractorGDBRemote::AllThreads));
 
   // combined thread id + process id
 
   ex.Reset("p-1.-1");
-  EXPECT_THAT(ex.GetPidTid(100).value(),
+  EXPECT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(StringExtractorGDBRemote::AllProcesses,
                               StringExtractorGDBRemote::AllThreads));
 
   ex.Reset("p1234.-1");
-  EXPECT_THAT(ex.GetPidTid(100).value(),
+  EXPECT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(0x1234ULL, StringExtractorGDBRemote::AllThreads));
 
   ex.Reset("p1234.123456789ABCDEF0");
-  EXPECT_THAT(ex.GetPidTid(100).value(),
+  EXPECT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(0x1234ULL, 0x123456789ABCDEF0ULL));
 
   ex.Reset("p123456789ABCDEF0.-1");
-  EXPECT_THAT(ex.GetPidTid(100).value(),
+  EXPECT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(0x123456789ABCDEF0ULL,
                               StringExtractorGDBRemote::AllThreads));
 
   ex.Reset("p123456789ABCDEF0.1234");
-  EXPECT_THAT(ex.GetPidTid(100).value(),
+  EXPECT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(0x123456789ABCDEF0ULL, 0x1234ULL));
 
   ex.Reset("p123456789ABCDEF0.123456789ABCDEF0");
-  EXPECT_THAT(ex.GetPidTid(100).value(),
+  EXPECT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(0x123456789ABCDEF0ULL, 0x123456789ABCDEF0ULL));
 
   ex.Reset("p123456789ABCDEF0.123456789ABCDEF0");
-  EXPECT_THAT(ex.GetPidTid(100).value(),
+  EXPECT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(0x123456789ABCDEF0ULL, 0x123456789ABCDEF0ULL));
 }
 
 TEST(StringExtractorGDBRemoteTest, GetPidTidMultipleValues) {
   StringExtractorGDBRemote ex("1234;p12;p1234.-1");
-  ASSERT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(100, 0x1234ULL));
+  ASSERT_THAT(ex.GetPidTid(100).getValue(), ::testing::Pair(100, 0x1234ULL));
   ASSERT_EQ(ex.GetChar(), ';');
-  ASSERT_THAT(ex.GetPidTid(100).value(),
+  ASSERT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(0x12ULL, StringExtractorGDBRemote::AllThreads));
   ASSERT_EQ(ex.GetChar(), ';');
-  ASSERT_THAT(ex.GetPidTid(100).value(),
+  ASSERT_THAT(ex.GetPidTid(100).getValue(),
               ::testing::Pair(0x1234ULL, StringExtractorGDBRemote::AllThreads));
 }

diff  --git a/lldb/unittests/tools/lldb-server/tests/TestClient.cpp b/lldb/unittests/tools/lldb-server/tests/TestClient.cpp
index f65c33e8c5c31..463dd226825eb 100644
--- a/lldb/unittests/tools/lldb-server/tests/TestClient.cpp
+++ b/lldb/unittests/tools/lldb-server/tests/TestClient.cpp
@@ -251,7 +251,7 @@ Error TestClient::queryProcess() {
 }
 
 Error TestClient::Continue(StringRef message) {
-  assert(m_process_info.has_value());
+  assert(m_process_info.hasValue());
 
   auto StopReplyOr = SendMessage<StopReply>(
       message, m_process_info->GetEndian(), m_register_infos);

diff  --git a/llvm/include/llvm/ADT/Optional.h b/llvm/include/llvm/ADT/Optional.h
index b2ebd17ce90fe..d1615d903e98d 100644
--- a/llvm/include/llvm/ADT/Optional.h
+++ b/llvm/include/llvm/ADT/Optional.h
@@ -92,40 +92,32 @@ class OptionalStorage {
   }
 
   constexpr bool has_value() const noexcept { return hasVal; }
-#if 0
   constexpr bool hasValue() const noexcept { return hasVal; }
-#endif
 
   T &value() &noexcept {
     assert(hasVal);
     return val;
   }
-#if 0
   T &getValue() &noexcept {
     assert(hasVal);
     return val;
   }
-#endif
   constexpr T const &value() const &noexcept {
     assert(hasVal);
     return val;
   }
-#if 0
   constexpr T const &getValue() const &noexcept {
     assert(hasVal);
     return val;
   }
-#endif
   T &&value() &&noexcept {
     assert(hasVal);
     return std::move(val);
   }
-#if 0
   T &&getValue() &&noexcept {
     assert(hasVal);
     return std::move(val);
   }
-#endif
 
   template <class... Args> void emplace(Args &&...args) {
     reset();
@@ -211,40 +203,32 @@ template <typename T> class OptionalStorage<T, true> {
   }
 
   constexpr bool has_value() const noexcept { return hasVal; }
-#if 0
   constexpr bool hasValue() const noexcept { return hasVal; }
-#endif
 
   T &value() &noexcept {
     assert(hasVal);
     return val;
   }
-#if 0
   T &getValue() &noexcept {
     assert(hasVal);
     return val;
   }
-#endif
   constexpr T const &value() const &noexcept {
     assert(hasVal);
     return val;
   }
-#if 0
   constexpr T const &getValue() const &noexcept {
     assert(hasVal);
     return val;
   }
-#endif
   T &&value() &&noexcept {
     assert(hasVal);
     return std::move(val);
   }
-#if 0
   T &&getValue() &&noexcept {
     assert(hasVal);
     return std::move(val);
   }
-#endif
 
   template <class... Args> void emplace(Args &&...args) {
     reset();
@@ -319,19 +303,13 @@ template <typename T> class Optional {
   constexpr const T *getPointer() const { return &Storage.value(); }
   T *getPointer() { return &Storage.value(); }
   constexpr const T &value() const & { return Storage.value(); }
-#if 0
   constexpr const T &getValue() const & { return Storage.value(); }
-#endif
   T &value() & { return Storage.value(); }
-#if 0
   T &getValue() & { return Storage.value(); }
-#endif
 
   constexpr explicit operator bool() const { return has_value(); }
   constexpr bool has_value() const { return Storage.has_value(); }
-#if 0
   constexpr bool hasValue() const { return Storage.has_value(); }
-#endif
   constexpr const T *operator->() const { return getPointer(); }
   T *operator->() { return getPointer(); }
   constexpr const T &operator*() const & { return value(); }
@@ -353,9 +331,7 @@ template <typename T> class Optional {
   }
 
   T &&value() && { return std::move(Storage.value()); }
-#if 0
   T &&getValue() && { return std::move(Storage.value()); }
-#endif
   T &&operator*() && { return std::move(Storage.value()); }
 
   template <typename U> T value_or(U &&alt) && {

diff  --git a/llvm/include/llvm/Analysis/BlockFrequencyInfoImpl.h b/llvm/include/llvm/Analysis/BlockFrequencyInfoImpl.h
index 7208f11f26a30..d8e524d7cb806 100644
--- a/llvm/include/llvm/Analysis/BlockFrequencyInfoImpl.h
+++ b/llvm/include/llvm/Analysis/BlockFrequencyInfoImpl.h
@@ -1277,10 +1277,10 @@ bool BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &Loop) {
         continue;
       }
       LLVM_DEBUG(dbgs() << getBlockName(HeaderNode)
-                        << " has irr loop header weight " << *HeaderWeight
-                        << "\n");
+                        << " has irr loop header weight "
+                        << HeaderWeight.getValue() << "\n");
       NumHeadersWithWeight++;
-      uint64_t HeaderWeightValue = *HeaderWeight;
+      uint64_t HeaderWeightValue = HeaderWeight.getValue();
       if (!MinHeaderWeight || HeaderWeightValue < MinHeaderWeight)
         MinHeaderWeight = HeaderWeightValue;
       if (HeaderWeightValue) {
@@ -1732,10 +1732,10 @@ raw_ostream &BlockFrequencyInfoImpl<BT>::print(raw_ostream &OS) const {
     if (Optional<uint64_t> ProfileCount =
         BlockFrequencyInfoImplBase::getBlockProfileCount(
             F->getFunction(), getNode(&BB)))
-      OS << ", count = " << *ProfileCount;
+      OS << ", count = " << ProfileCount.getValue();
     if (Optional<uint64_t> IrrLoopHeaderWeight =
         BB.getIrrLoopHeaderWeight())
-      OS << ", irr_loop_header_weight = " << *IrrLoopHeaderWeight;
+      OS << ", irr_loop_header_weight = " << IrrLoopHeaderWeight.getValue();
     OS << "\n";
   }
 

diff  --git a/llvm/include/llvm/Analysis/VectorUtils.h b/llvm/include/llvm/Analysis/VectorUtils.h
index 6e4c468ed64bc..df460cb49aeeb 100644
--- a/llvm/include/llvm/Analysis/VectorUtils.h
+++ b/llvm/include/llvm/Analysis/VectorUtils.h
@@ -236,10 +236,10 @@ class VFDatabase {
       // ensuring that the variant described in the attribute has a
       // corresponding definition or declaration of the vector
       // function in the Module M.
-      if (Shape && (Shape->ScalarName == ScalarName)) {
-        assert(CI.getModule()->getFunction(Shape->VectorName) &&
+      if (Shape.hasValue() && (Shape.getValue().ScalarName == ScalarName)) {
+        assert(CI.getModule()->getFunction(Shape.getValue().VectorName) &&
                "Vector function is missing.");
-        Mappings.push_back(*Shape);
+        Mappings.push_back(Shape.getValue());
       }
     }
   }

diff  --git a/llvm/include/llvm/Bitstream/BitstreamWriter.h b/llvm/include/llvm/Bitstream/BitstreamWriter.h
index 3660ce56ded82..be6bab5532bdf 100644
--- a/llvm/include/llvm/Bitstream/BitstreamWriter.h
+++ b/llvm/include/llvm/Bitstream/BitstreamWriter.h
@@ -386,12 +386,12 @@ class BitstreamWriter {
       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
 
       if (Op.isLiteral())
-        EmitAbbreviatedLiteral(Op, *Code);
+        EmitAbbreviatedLiteral(Op, Code.getValue());
       else {
         assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&
                Op.getEncoding() != BitCodeAbbrevOp::Blob &&
                "Expected literal or scalar");
-        EmitAbbreviatedField(Op, *Code);
+        EmitAbbreviatedField(Op, Code.getValue());
       }
     }
 

diff  --git a/llvm/include/llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h b/llvm/include/llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h
index 9e9fd654bfbcd..fa6f904e33a1c 100644
--- a/llvm/include/llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h
+++ b/llvm/include/llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h
@@ -674,8 +674,8 @@ bool InstructionSelector::executeMatchTable(
       ComplexRendererFns Renderer =
           (ISel.*ISelInfo.ComplexPredicates[ComplexPredicateID])(
               State.MIs[InsnID]->getOperand(OpIdx));
-      if (Renderer)
-        State.Renderers[RendererID] = *Renderer;
+      if (Renderer.hasValue())
+        State.Renderers[RendererID] = Renderer.getValue();
       else
         if (handleReject() == RejectAndGiveUp)
           return false;

diff  --git a/llvm/include/llvm/DebugInfo/GSYM/FunctionInfo.h b/llvm/include/llvm/DebugInfo/GSYM/FunctionInfo.h
index fb48f7f9a93c6..a41b2fe2a6e76 100644
--- a/llvm/include/llvm/DebugInfo/GSYM/FunctionInfo.h
+++ b/llvm/include/llvm/DebugInfo/GSYM/FunctionInfo.h
@@ -198,8 +198,8 @@ inline bool operator<(const FunctionInfo &LHS, const FunctionInfo &RHS) {
     return LHS.Range < RHS.Range;
 
   // Then sort by inline
-  if (LHS.Inline.has_value() != RHS.Inline.has_value())
-    return RHS.Inline.has_value();
+  if (LHS.Inline.hasValue() != RHS.Inline.hasValue())
+    return RHS.Inline.hasValue();
 
   return LHS.OptLineTable < RHS.OptLineTable;
 }

diff  --git a/llvm/include/llvm/IR/IRBuilder.h b/llvm/include/llvm/IR/IRBuilder.h
index 1747826ecacef..2b387db47ed25 100644
--- a/llvm/include/llvm/IR/IRBuilder.h
+++ b/llvm/include/llvm/IR/IRBuilder.h
@@ -1168,12 +1168,12 @@ class IRBuilderBase {
   Value *getConstrainedFPRounding(Optional<RoundingMode> Rounding) {
     RoundingMode UseRounding = DefaultConstrainedRounding;
 
-    if (Rounding)
-      UseRounding = *Rounding;
+    if (Rounding.hasValue())
+      UseRounding = Rounding.getValue();
 
     Optional<StringRef> RoundingStr = convertRoundingModeToStr(UseRounding);
-    assert(RoundingStr && "Garbage strict rounding mode!");
-    auto *RoundingMDS = MDString::get(Context, *RoundingStr);
+    assert(RoundingStr.hasValue() && "Garbage strict rounding mode!");
+    auto *RoundingMDS = MDString::get(Context, RoundingStr.getValue());
 
     return MetadataAsValue::get(Context, RoundingMDS);
   }
@@ -1181,12 +1181,12 @@ class IRBuilderBase {
   Value *getConstrainedFPExcept(Optional<fp::ExceptionBehavior> Except) {
     fp::ExceptionBehavior UseExcept = DefaultConstrainedExcept;
 
-    if (Except)
-      UseExcept = *Except;
+    if (Except.hasValue())
+      UseExcept = Except.getValue();
 
     Optional<StringRef> ExceptStr = convertExceptionBehaviorToStr(UseExcept);
-    assert(ExceptStr && "Garbage strict exception behavior!");
-    auto *ExceptMDS = MDString::get(Context, *ExceptStr);
+    assert(ExceptStr.hasValue() && "Garbage strict exception behavior!");
+    auto *ExceptMDS = MDString::get(Context, ExceptStr.getValue());
 
     return MetadataAsValue::get(Context, ExceptMDS);
   }

diff  --git a/llvm/include/llvm/MC/MCDwarf.h b/llvm/include/llvm/MC/MCDwarf.h
index 8b2ae84749b4f..d0eb06eb592bc 100644
--- a/llvm/include/llvm/MC/MCDwarf.h
+++ b/llvm/include/llvm/MC/MCDwarf.h
@@ -296,8 +296,8 @@ struct MCDwarfLineTableHeader {
     RootFile.DirIndex = 0;
     RootFile.Checksum = Checksum;
     RootFile.Source = Source;
-    trackMD5Usage(Checksum.has_value());
-    HasSource = Source.has_value();
+    trackMD5Usage(Checksum.hasValue());
+    HasSource = Source.hasValue();
   }
 
   void resetFileTable() {
@@ -374,8 +374,8 @@ class MCDwarfLineTable {
     Header.RootFile.DirIndex = 0;
     Header.RootFile.Checksum = Checksum;
     Header.RootFile.Source = Source;
-    Header.trackMD5Usage(Checksum.has_value());
-    Header.HasSource = Source.has_value();
+    Header.trackMD5Usage(Checksum.hasValue());
+    Header.HasSource = Source.hasValue();
   }
 
   void resetFileTable() { Header.resetFileTable(); }

diff  --git a/llvm/include/llvm/MC/MCSectionXCOFF.h b/llvm/include/llvm/MC/MCSectionXCOFF.h
index 1b68d2726c74f..77f0b28c1d0a3 100644
--- a/llvm/include/llvm/MC/MCSectionXCOFF.h
+++ b/llvm/include/llvm/MC/MCSectionXCOFF.h
@@ -111,8 +111,8 @@ class MCSectionXCOFF final : public MCSection {
   bool isVirtualSection() const override;
   StringRef getSymbolTableName() const { return SymbolTableName; }
   bool isMultiSymbolsAllowed() const { return MultiSymbolsAllowed; }
-  bool isCsect() const { return CsectProp.has_value(); }
-  bool isDwarfSect() const { return DwarfSubtypeFlags.has_value(); }
+  bool isCsect() const { return CsectProp.hasValue(); }
+  bool isDwarfSect() const { return DwarfSubtypeFlags.hasValue(); }
   Optional<XCOFF::DwarfSectionSubtypeFlags> getDwarfSubtypeFlags() const {
     return DwarfSubtypeFlags;
   }

diff  --git a/llvm/include/llvm/MC/MCSymbolWasm.h b/llvm/include/llvm/MC/MCSymbolWasm.h
index 6d086850e4c6f..5a4852e0e8955 100644
--- a/llvm/include/llvm/MC/MCSymbolWasm.h
+++ b/llvm/include/llvm/MC/MCSymbolWasm.h
@@ -86,10 +86,10 @@ class MCSymbolWasm : public MCSymbol {
   bool omitFromLinkingSection() const { return OmitFromLinkingSection; }
   void setOmitFromLinkingSection() { OmitFromLinkingSection = true; }
 
-  bool hasImportModule() const { return ImportModule.has_value(); }
+  bool hasImportModule() const { return ImportModule.hasValue(); }
   StringRef getImportModule() const {
-    if (ImportModule)
-      return *ImportModule;
+    if (ImportModule.hasValue())
+      return ImportModule.getValue();
     // Use a default module name of "env" for now, for compatibility with
     // existing tools.
     // TODO(sbc): Find a way to specify a default value in the object format
@@ -98,16 +98,16 @@ class MCSymbolWasm : public MCSymbol {
   }
   void setImportModule(StringRef Name) { ImportModule = Name; }
 
-  bool hasImportName() const { return ImportName.has_value(); }
+  bool hasImportName() const { return ImportName.hasValue(); }
   StringRef getImportName() const {
-    if (ImportName)
-      return *ImportName;
+    if (ImportName.hasValue())
+      return ImportName.getValue();
     return getName();
   }
   void setImportName(StringRef Name) { ImportName = Name; }
 
-  bool hasExportName() const { return ExportName.has_value(); }
-  StringRef getExportName() const { return *ExportName; }
+  bool hasExportName() const { return ExportName.hasValue(); }
+  StringRef getExportName() const { return ExportName.getValue(); }
   void setExportName(StringRef Name) { ExportName = Name; }
 
   bool isFunctionTable() const {
@@ -129,15 +129,15 @@ class MCSymbolWasm : public MCSymbol {
   void setSignature(wasm::WasmSignature *Sig) { Signature = Sig; }
 
   const wasm::WasmGlobalType &getGlobalType() const {
-    assert(GlobalType.has_value());
-    return *GlobalType;
+    assert(GlobalType.hasValue());
+    return GlobalType.getValue();
   }
   void setGlobalType(wasm::WasmGlobalType GT) { GlobalType = GT; }
 
-  bool hasTableType() const { return TableType.has_value(); }
+  bool hasTableType() const { return TableType.hasValue(); }
   const wasm::WasmTableType &getTableType() const {
     assert(hasTableType());
-    return *TableType;
+    return TableType.getValue();
   }
   void setTableType(wasm::WasmTableType TT) { TableType = TT; }
   void setTableType(wasm::ValType VT) {

diff  --git a/llvm/include/llvm/MC/MCSymbolXCOFF.h b/llvm/include/llvm/MC/MCSymbolXCOFF.h
index 4e21d397b9685..752e1e7bba0f2 100644
--- a/llvm/include/llvm/MC/MCSymbolXCOFF.h
+++ b/llvm/include/llvm/MC/MCSymbolXCOFF.h
@@ -39,8 +39,9 @@ class MCSymbolXCOFF : public MCSymbol {
   };
 
   XCOFF::StorageClass getStorageClass() const {
-    assert(StorageClass && "StorageClass not set on XCOFF MCSymbol.");
-    return *StorageClass;
+    assert(StorageClass.hasValue() &&
+           "StorageClass not set on XCOFF MCSymbol.");
+    return StorageClass.getValue();
   }
 
   StringRef getUnqualifiedName() const { return getUnqualifiedName(getName()); }

diff  --git a/llvm/include/llvm/ObjectYAML/ELFYAML.h b/llvm/include/llvm/ObjectYAML/ELFYAML.h
index 95bf5237869a7..faff482c9b29c 100644
--- a/llvm/include/llvm/ObjectYAML/ELFYAML.h
+++ b/llvm/include/llvm/ObjectYAML/ELFYAML.h
@@ -433,10 +433,10 @@ struct GnuHashSection : Section {
   GnuHashSection() : Section(ChunkKind::GnuHash) {}
 
   std::vector<std::pair<StringRef, bool>> getEntries() const override {
-    return {{"Header", Header.has_value()},
-            {"BloomFilter", BloomFilter.has_value()},
-            {"HashBuckets", HashBuckets.has_value()},
-            {"HashValues", HashValues.has_value()}};
+    return {{"Header", Header.hasValue()},
+            {"BloomFilter", BloomFilter.hasValue()},
+            {"HashBuckets", HashBuckets.hasValue()},
+            {"HashValues", HashValues.hasValue()}};
   };
 
   static bool classof(const Chunk *S) { return S->Kind == ChunkKind::GnuHash; }

diff  --git a/llvm/include/llvm/Support/Casting.h b/llvm/include/llvm/Support/Casting.h
index 7037cbf49fccf..21c981ad3255e 100644
--- a/llvm/include/llvm/Support/Casting.h
+++ b/llvm/include/llvm/Support/Casting.h
@@ -637,8 +637,10 @@ template <typename T, typename Enable = void> struct ValueIsPresent {
 // Optional provides its own way to check if something is present.
 template <typename T> struct ValueIsPresent<Optional<T>> {
   using UnwrappedType = T;
-  static inline bool isPresent(const Optional<T> &t) { return t.has_value(); }
-  static inline decltype(auto) unwrapValue(Optional<T> &t) { return *t; }
+  static inline bool isPresent(const Optional<T> &t) { return t.hasValue(); }
+  static inline decltype(auto) unwrapValue(Optional<T> &t) {
+    return t.getValue();
+  }
 };
 
 // If something is "nullable" then we just compare it to nullptr to see if it

diff  --git a/llvm/include/llvm/Support/Error.h b/llvm/include/llvm/Support/Error.h
index 316e5dcf14412..80a5212b8f076 100644
--- a/llvm/include/llvm/Support/Error.h
+++ b/llvm/include/llvm/Support/Error.h
@@ -1269,8 +1269,8 @@ class FileError final : public ErrorInfo<FileError> {
   void log(raw_ostream &OS) const override {
     assert(Err && "Trying to log after takeError().");
     OS << "'" << FileName << "': ";
-    if (Line)
-      OS << "line " << *Line << ": ";
+    if (Line.hasValue())
+      OS << "line " << Line.getValue() << ": ";
     Err->log(OS);
   }
 

diff  --git a/llvm/include/llvm/Support/YAMLTraits.h b/llvm/include/llvm/Support/YAMLTraits.h
index 8ade9b15642b5..dfe9b1b0d9397 100644
--- a/llvm/include/llvm/Support/YAMLTraits.h
+++ b/llvm/include/llvm/Support/YAMLTraits.h
@@ -1668,13 +1668,14 @@ template <typename T, typename Context>
 void IO::processKeyWithDefault(const char *Key, Optional<T> &Val,
                                const Optional<T> &DefaultValue, bool Required,
                                Context &Ctx) {
-  assert(!DefaultValue && "Optional<T> shouldn't have a value!");
+  assert(DefaultValue.hasValue() == false &&
+         "Optional<T> shouldn't have a value!");
   void *SaveInfo;
   bool UseDefault = true;
-  const bool sameAsDefault = outputting() && !Val;
-  if (!outputting() && !Val)
+  const bool sameAsDefault = outputting() && !Val.hasValue();
+  if (!outputting() && !Val.hasValue())
     Val = T();
-  if (Val &&
+  if (Val.hasValue() &&
       this->preflightKey(Key, Required, sameAsDefault, UseDefault, SaveInfo)) {
 
     // When reading an Optional<X> key from a YAML description, we allow the

diff  --git a/llvm/include/llvm/Transforms/IPO/Attributor.h b/llvm/include/llvm/Transforms/IPO/Attributor.h
index 17e29695ab739..6aa19b00e0f6b 100644
--- a/llvm/include/llvm/Transforms/IPO/Attributor.h
+++ b/llvm/include/llvm/Transforms/IPO/Attributor.h
@@ -4884,10 +4884,12 @@ struct AAPointerInfo : public AbstractAttribute {
     Instruction *getRemoteInst() const { return RemoteI; }
 
     /// Return true if the value written is not known yet.
-    bool isWrittenValueYetUndetermined() const { return !Content; }
+    bool isWrittenValueYetUndetermined() const { return !Content.hasValue(); }
 
     /// Return true if the value written cannot be determined at all.
-    bool isWrittenValueUnknown() const { return Content && !*Content; }
+    bool isWrittenValueUnknown() const {
+      return Content.hasValue() && !*Content;
+    }
 
     /// Return the type associated with the access, if known.
     Type *getType() const { return Ty; }

diff  --git a/llvm/lib/Analysis/BranchProbabilityInfo.cpp b/llvm/lib/Analysis/BranchProbabilityInfo.cpp
index 2bca424e3da3b..1d880424e55c9 100644
--- a/llvm/lib/Analysis/BranchProbabilityInfo.cpp
+++ b/llvm/lib/Analysis/BranchProbabilityInfo.cpp
@@ -826,8 +826,9 @@ void BranchProbabilityInfo::computeEestimateBlockWeight(
     if (auto BBWeight = getInitialEstimatedBlockWeight(BB))
       // If we were able to find estimated weight for the block set it to this
       // block and propagate up the IR.
-      propagateEstimatedBlockWeight(getLoopBlock(BB), DT, PDT, *BBWeight,
-                                    BlockWorkList, LoopWorkList);
+      propagateEstimatedBlockWeight(getLoopBlock(BB), DT, PDT,
+                                    BBWeight.getValue(), BlockWorkList,
+                                    LoopWorkList);
 
   // BlockWorklist/LoopWorkList contains blocks/loops with at least one
   // successor/exit having estimated weight. Try to propagate weight to such

diff  --git a/llvm/lib/Analysis/CFLAndersAliasAnalysis.cpp b/llvm/lib/Analysis/CFLAndersAliasAnalysis.cpp
index 602a01867f3b5..1216d03e448b1 100644
--- a/llvm/lib/Analysis/CFLAndersAliasAnalysis.cpp
+++ b/llvm/lib/Analysis/CFLAndersAliasAnalysis.cpp
@@ -831,14 +831,14 @@ CFLAndersAAResult::ensureCached(const Function &Fn) {
     scan(Fn);
     Iter = Cache.find(&Fn);
     assert(Iter != Cache.end());
-    assert(Iter->second);
+    assert(Iter->second.hasValue());
   }
   return Iter->second;
 }
 
 const AliasSummary *CFLAndersAAResult::getAliasSummary(const Function &Fn) {
   auto &FunInfo = ensureCached(Fn);
-  if (FunInfo)
+  if (FunInfo.hasValue())
     return &FunInfo->getAliasSummary();
   else
     return nullptr;

diff  --git a/llvm/lib/Analysis/CFLSteensAliasAnalysis.cpp b/llvm/lib/Analysis/CFLSteensAliasAnalysis.cpp
index f92869c2ec636..b831a599cc091 100644
--- a/llvm/lib/Analysis/CFLSteensAliasAnalysis.cpp
+++ b/llvm/lib/Analysis/CFLSteensAliasAnalysis.cpp
@@ -250,14 +250,14 @@ CFLSteensAAResult::ensureCached(Function *Fn) {
     scan(Fn);
     Iter = Cache.find(Fn);
     assert(Iter != Cache.end());
-    assert(Iter->second);
+    assert(Iter->second.hasValue());
   }
   return Iter->second;
 }
 
 const AliasSummary *CFLSteensAAResult::getAliasSummary(Function &Fn) {
   auto &FunInfo = ensureCached(&Fn);
-  if (FunInfo)
+  if (FunInfo.hasValue())
     return &FunInfo->getAliasSummary();
   else
     return nullptr;
@@ -293,15 +293,15 @@ AliasResult CFLSteensAAResult::query(const MemoryLocation &LocA,
 
   assert(Fn != nullptr);
   auto &MaybeInfo = ensureCached(Fn);
-  assert(MaybeInfo);
+  assert(MaybeInfo.hasValue());
 
   auto &Sets = MaybeInfo->getStratifiedSets();
   auto MaybeA = Sets.find(InstantiatedValue{ValA, 0});
-  if (!MaybeA)
+  if (!MaybeA.hasValue())
     return AliasResult::MayAlias;
 
   auto MaybeB = Sets.find(InstantiatedValue{ValB, 0});
-  if (!MaybeB)
+  if (!MaybeB.hasValue())
     return AliasResult::MayAlias;
 
   auto SetA = *MaybeA;

diff  --git a/llvm/lib/Analysis/IRSimilarityIdentifier.cpp b/llvm/lib/Analysis/IRSimilarityIdentifier.cpp
index 81aa85436a671..c9450506d46c2 100644
--- a/llvm/lib/Analysis/IRSimilarityIdentifier.cpp
+++ b/llvm/lib/Analysis/IRSimilarityIdentifier.cpp
@@ -183,9 +183,9 @@ CmpInst::Predicate IRInstructionData::getPredicate() const {
   assert(isa<CmpInst>(Inst) &&
          "Can only get a predicate from a compare instruction");
 
-  if (RevisedPredicate)
-    return *RevisedPredicate;
-
+  if (RevisedPredicate.hasValue())
+    return RevisedPredicate.getValue();
+  
   return cast<CmpInst>(Inst)->getPredicate();
 }
 

diff  --git a/llvm/lib/Analysis/InlineCost.cpp b/llvm/lib/Analysis/InlineCost.cpp
index f2dcaa84332be..63fe651bb5718 100644
--- a/llvm/lib/Analysis/InlineCost.cpp
+++ b/llvm/lib/Analysis/InlineCost.cpp
@@ -703,8 +703,8 @@ class InlineCostCallAnalyzer final : public CallAnalyzer {
       BlockFrequencyInfo *BFI = &(GetBFI(F));
       assert(BFI && "BFI must be available");
       auto ProfileCount = BFI->getBlockProfileCount(BB);
-      assert(ProfileCount);
-      if (*ProfileCount == 0)
+      assert(ProfileCount.hasValue());
+      if (ProfileCount.getValue() == 0)
         ColdSize += Cost - CostAtBBStart;
     }
 
@@ -828,14 +828,14 @@ class InlineCostCallAnalyzer final : public CallAnalyzer {
       }
 
       auto ProfileCount = CalleeBFI->getBlockProfileCount(&BB);
-      assert(ProfileCount);
-      CurrentSavings *= *ProfileCount;
+      assert(ProfileCount.hasValue());
+      CurrentSavings *= ProfileCount.getValue();
       CycleSavings += CurrentSavings;
     }
 
     // Compute the cycle savings per call.
     auto EntryProfileCount = F.getEntryCount();
-    assert(EntryProfileCount && EntryProfileCount->getCount());
+    assert(EntryProfileCount.hasValue() && EntryProfileCount->getCount());
     auto EntryCount = EntryProfileCount->getCount();
     CycleSavings += EntryCount / 2;
     CycleSavings = CycleSavings.udiv(EntryCount);
@@ -1800,12 +1800,12 @@ void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
 
   // return min(A, B) if B is valid.
   auto MinIfValid = [](int A, Optional<int> B) {
-    return B ? std::min(A, *B) : A;
+    return B ? std::min(A, B.getValue()) : A;
   };
 
   // return max(A, B) if B is valid.
   auto MaxIfValid = [](int A, Optional<int> B) {
-    return B ? std::max(A, *B) : A;
+    return B ? std::max(A, B.getValue()) : A;
   };
 
   // Various bonus percentages. These are multiplied by Threshold to get the

diff  --git a/llvm/lib/Analysis/InstructionSimplify.cpp b/llvm/lib/Analysis/InstructionSimplify.cpp
index a7aec39b65e02..07e3392c226e6 100644
--- a/llvm/lib/Analysis/InstructionSimplify.cpp
+++ b/llvm/lib/Analysis/InstructionSimplify.cpp
@@ -6123,9 +6123,9 @@ static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) {
     Value *Op1 = Call->getArgOperand(1);
     Value *Op2 = Call->getArgOperand(2);
     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
-    if (Value *V =
-            simplifyFPOp({Op0, Op1, Op2}, {}, Q, *FPI->getExceptionBehavior(),
-                         *FPI->getRoundingMode()))
+    if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q,
+                                FPI->getExceptionBehavior().getValue(),
+                                FPI->getRoundingMode().getValue()))
       return V;
     return nullptr;
   }
@@ -6189,33 +6189,38 @@ static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) {
   }
   case Intrinsic::experimental_constrained_fadd: {
     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
-    return simplifyFAddInst(
-        FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
-        Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
+    return simplifyFAddInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
+                            FPI->getFastMathFlags(), Q,
+                            FPI->getExceptionBehavior().getValue(),
+                            FPI->getRoundingMode().getValue());
   }
   case Intrinsic::experimental_constrained_fsub: {
     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
-    return simplifyFSubInst(
-        FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
-        Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
+    return simplifyFSubInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
+                            FPI->getFastMathFlags(), Q,
+                            FPI->getExceptionBehavior().getValue(),
+                            FPI->getRoundingMode().getValue());
   }
   case Intrinsic::experimental_constrained_fmul: {
     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
-    return simplifyFMulInst(
-        FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
-        Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
+    return simplifyFMulInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
+                            FPI->getFastMathFlags(), Q,
+                            FPI->getExceptionBehavior().getValue(),
+                            FPI->getRoundingMode().getValue());
   }
   case Intrinsic::experimental_constrained_fdiv: {
     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
-    return simplifyFDivInst(
-        FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
-        Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
+    return simplifyFDivInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
+                            FPI->getFastMathFlags(), Q,
+                            FPI->getExceptionBehavior().getValue(),
+                            FPI->getRoundingMode().getValue());
   }
   case Intrinsic::experimental_constrained_frem: {
     auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
-    return simplifyFRemInst(
-        FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
-        Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
+    return simplifyFRemInst(FPI->getArgOperand(0), FPI->getArgOperand(1),
+                            FPI->getFastMathFlags(), Q,
+                            FPI->getExceptionBehavior().getValue(),
+                            FPI->getRoundingMode().getValue());
   }
   default:
     return nullptr;

diff  --git a/llvm/lib/Analysis/LazyValueInfo.cpp b/llvm/lib/Analysis/LazyValueInfo.cpp
index e82c3aeed5776..5803c3d7f50d4 100644
--- a/llvm/lib/Analysis/LazyValueInfo.cpp
+++ b/llvm/lib/Analysis/LazyValueInfo.cpp
@@ -918,10 +918,10 @@ Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueCast(
   // transfer rule on the full set since we may be able to locally infer
   // interesting facts.
   Optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB);
-  if (!LHSRes)
+  if (!LHSRes.hasValue())
     // More work to do before applying this transfer rule.
     return None;
-  const ConstantRange &LHSRange = *LHSRes;
+  const ConstantRange &LHSRange = LHSRes.getValue();
 
   const unsigned ResultBitWidth = CI->getType()->getIntegerBitWidth();
 
@@ -946,8 +946,8 @@ Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
     // More work to do before applying this transfer rule.
     return None;
 
-  const ConstantRange &LHSRange = *LHSRes;
-  const ConstantRange &RHSRange = *RHSRes;
+  const ConstantRange &LHSRange = LHSRes.getValue();
+  const ConstantRange &RHSRange = RHSRes.getValue();
   return ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
 }
 

diff  --git a/llvm/lib/Analysis/LoopCacheAnalysis.cpp b/llvm/lib/Analysis/LoopCacheAnalysis.cpp
index 2cbf1f7f2d28e..002e993028034 100644
--- a/llvm/lib/Analysis/LoopCacheAnalysis.cpp
+++ b/llvm/lib/Analysis/LoopCacheAnalysis.cpp
@@ -645,8 +645,8 @@ bool CacheCost::populateReferenceGroups(ReferenceGroupsTy &RefGroups) const {
         Optional<bool> HasSpacialReuse =
             R->hasSpacialReuse(Representative, CLS, AA);
 
-        if ((HasTemporalReuse && *HasTemporalReuse) ||
-            (HasSpacialReuse && *HasSpacialReuse)) {
+        if ((HasTemporalReuse.hasValue() && *HasTemporalReuse) ||
+            (HasSpacialReuse.hasValue() && *HasSpacialReuse)) {
           RefGroup.push_back(std::move(R));
           Added = true;
           break;

diff  --git a/llvm/lib/Analysis/MemoryBuiltins.cpp b/llvm/lib/Analysis/MemoryBuiltins.cpp
index ff303ceab8d4e..3c0e494bf1da7 100644
--- a/llvm/lib/Analysis/MemoryBuiltins.cpp
+++ b/llvm/lib/Analysis/MemoryBuiltins.cpp
@@ -270,53 +270,54 @@ static Optional<AllocFnsTy> getAllocationSize(const Value *V,
 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
 /// like).
 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI) {
-  return getAllocationData(V, AnyAlloc, TLI).has_value();
+  return getAllocationData(V, AnyAlloc, TLI).hasValue();
 }
 bool llvm::isAllocationFn(
     const Value *V, function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
-  return getAllocationData(V, AnyAlloc, GetTLI).has_value();
+  return getAllocationData(V, AnyAlloc, GetTLI).hasValue();
 }
 
 /// Tests if a value is a call or invoke to a library function that
 /// allocates uninitialized memory (such as malloc).
 static bool isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
-  return getAllocationData(V, MallocOrOpNewLike, TLI).has_value();
+  return getAllocationData(V, MallocOrOpNewLike, TLI).hasValue();
 }
 
 /// Tests if a value is a call or invoke to a library function that
 /// allocates uninitialized memory with alignment (such as aligned_alloc).
 static bool isAlignedAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
-  return getAllocationData(V, AlignedAllocLike, TLI).has_value();
+  return getAllocationData(V, AlignedAllocLike, TLI)
+      .hasValue();
 }
 
 /// Tests if a value is a call or invoke to a library function that
 /// allocates zero-filled memory (such as calloc).
 static bool isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
-  return getAllocationData(V, CallocLike, TLI).has_value();
+  return getAllocationData(V, CallocLike, TLI).hasValue();
 }
 
 /// Tests if a value is a call or invoke to a library function that
 /// allocates memory similar to malloc or calloc.
 bool llvm::isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
-  return getAllocationData(V, MallocOrCallocLike, TLI).has_value();
+  return getAllocationData(V, MallocOrCallocLike, TLI).hasValue();
 }
 
 /// Tests if a value is a call or invoke to a library function that
 /// allocates memory (either malloc, calloc, or strdup like).
 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
-  return getAllocationData(V, AllocLike, TLI).has_value();
+  return getAllocationData(V, AllocLike, TLI).hasValue();
 }
 
 /// Tests if a value is a call or invoke to a library function that
 /// reallocates memory (e.g., realloc).
 bool llvm::isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
-  return getAllocationData(V, ReallocLike, TLI).has_value();
+  return getAllocationData(V, ReallocLike, TLI).hasValue();
 }
 
 /// Tests if a functions is a call or invoke to a library function that
 /// reallocates memory (e.g., realloc).
 bool llvm::isReallocLikeFn(const Function *F, const TargetLibraryInfo *TLI) {
-  return getAllocationDataForFunction(F, ReallocLike, TLI).has_value();
+  return getAllocationDataForFunction(F, ReallocLike, TLI).hasValue();
 }
 
 bool llvm::isAllocRemovable(const CallBase *CB, const TargetLibraryInfo *TLI) {
@@ -500,18 +501,18 @@ Optional<StringRef> llvm::getAllocationFamily(const Value *I,
   if (!TLI || !TLI->getLibFunc(*Callee, TLIFn) || !TLI->has(TLIFn))
     return None;
   const auto AllocData = getAllocationDataForFunction(Callee, AnyAlloc, TLI);
-  if (AllocData)
-    return mangledNameForMallocFamily(AllocData->Family);
+  if (AllocData.hasValue())
+    return mangledNameForMallocFamily(AllocData.getValue().Family);
   const auto FreeData = getFreeFunctionDataForFunction(Callee, TLIFn);
-  if (FreeData)
-    return mangledNameForMallocFamily(FreeData->Family);
+  if (FreeData.hasValue())
+    return mangledNameForMallocFamily(FreeData.getValue().Family);
   return None;
 }
 
 /// isLibFreeFunction - Returns true if the function is a builtin free()
 bool llvm::isLibFreeFunction(const Function *F, const LibFunc TLIFn) {
   Optional<FreeFnsTy> FnData = getFreeFunctionDataForFunction(F, TLIFn);
-  if (!FnData)
+  if (!FnData.hasValue())
     return false;
 
   // Check free prototype.

diff  --git a/llvm/lib/Analysis/MemorySSA.cpp b/llvm/lib/Analysis/MemorySSA.cpp
index 76371b88812e9..f63898be31735 100644
--- a/llvm/lib/Analysis/MemorySSA.cpp
+++ b/llvm/lib/Analysis/MemorySSA.cpp
@@ -749,9 +749,9 @@ template <class AliasAnalysisType> class ClobberWalker {
     }
 
     bool operator==(const generic_def_path_iterator &O) const {
-      if (N.has_value() != O.N.has_value())
+      if (N.hasValue() != O.N.hasValue())
         return false;
-      return !N || *N == *O.N;
+      return !N.hasValue() || *N == *O.N;
     }
 
   private:

diff  --git a/llvm/lib/Analysis/MustExecute.cpp b/llvm/lib/Analysis/MustExecute.cpp
index 8dbce2669f25d..c785b500e760c 100644
--- a/llvm/lib/Analysis/MustExecute.cpp
+++ b/llvm/lib/Analysis/MustExecute.cpp
@@ -491,9 +491,9 @@ template <typename K, typename V, typename FnTy, typename... ArgsTy>
 static V getOrCreateCachedOptional(K Key, DenseMap<K, Optional<V>> &Map,
                                    FnTy &&Fn, ArgsTy&&... args) {
   Optional<V> &OptVal = Map[Key];
-  if (!OptVal)
+  if (!OptVal.hasValue())
     OptVal = Fn(std::forward<ArgsTy>(args)...);
-  return *OptVal;
+  return OptVal.getValue();
 }
 
 const BasicBlock *

diff  --git a/llvm/lib/Analysis/ProfileSummaryInfo.cpp b/llvm/lib/Analysis/ProfileSummaryInfo.cpp
index b564dbea8924b..9d5fa6d0a41b1 100644
--- a/llvm/lib/Analysis/ProfileSummaryInfo.cpp
+++ b/llvm/lib/Analysis/ProfileSummaryInfo.cpp
@@ -279,19 +279,19 @@ ProfileSummaryInfo::computeThreshold(int PercentileCutoff) const {
 }
 
 bool ProfileSummaryInfo::hasHugeWorkingSetSize() const {
-  return HasHugeWorkingSetSize && *HasHugeWorkingSetSize;
+  return HasHugeWorkingSetSize && HasHugeWorkingSetSize.getValue();
 }
 
 bool ProfileSummaryInfo::hasLargeWorkingSetSize() const {
-  return HasLargeWorkingSetSize && *HasLargeWorkingSetSize;
+  return HasLargeWorkingSetSize && HasLargeWorkingSetSize.getValue();
 }
 
 bool ProfileSummaryInfo::isHotCount(uint64_t C) const {
-  return HotCountThreshold && C >= *HotCountThreshold;
+  return HotCountThreshold && C >= HotCountThreshold.getValue();
 }
 
 bool ProfileSummaryInfo::isColdCount(uint64_t C) const {
-  return ColdCountThreshold && C <= *ColdCountThreshold;
+  return ColdCountThreshold && C <= ColdCountThreshold.getValue();
 }
 
 template <bool isHot>
@@ -299,9 +299,9 @@ bool ProfileSummaryInfo::isHotOrColdCountNthPercentile(int PercentileCutoff,
                                                        uint64_t C) const {
   auto CountThreshold = computeThreshold(PercentileCutoff);
   if (isHot)
-    return CountThreshold && C >= *CountThreshold;
+    return CountThreshold && C >= CountThreshold.getValue();
   else
-    return CountThreshold && C <= *CountThreshold;
+    return CountThreshold && C <= CountThreshold.getValue();
 }
 
 bool ProfileSummaryInfo::isHotCountNthPercentile(int PercentileCutoff,

diff  --git a/llvm/lib/Analysis/ScalarEvolution.cpp b/llvm/lib/Analysis/ScalarEvolution.cpp
index 795118053d6b1..5eb5c6b7c594a 100644
--- a/llvm/lib/Analysis/ScalarEvolution.cpp
+++ b/llvm/lib/Analysis/ScalarEvolution.cpp
@@ -4847,16 +4847,16 @@ class SCEVBackedgeConditionFolder
         SelectInst *SI = cast<SelectInst>(I);
         Optional<const SCEV *> Res =
             compareWithBackedgeCondition(SI->getCondition());
-        if (Res) {
-          bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
+        if (Res.hasValue()) {
+          bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
         }
         break;
       }
       default: {
         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
-        if (Res)
-          Result = *Res;
+        if (Res.hasValue())
+          Result = Res.getValue();
         break;
       }
       }
@@ -6596,9 +6596,9 @@ ScalarEvolution::getRangeRef(const SCEV *S,
 
     // Check if the IR explicitly contains !range metadata.
     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
-    if (MDRange)
-      ConservativeResult =
-          ConservativeResult.intersectWith(*MDRange, RangeType);
+    if (MDRange.hasValue())
+      ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
+                                                            RangeType);
 
     // Use facts about recurrences in the underlying IR.  Note that add
     // recurrences are AddRecExprs and thus don't hit this path.  This
@@ -9710,15 +9710,15 @@ GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
 /// (b) if neither X nor Y exist, return None,
 /// (c) if exactly one of X and Y exists, return that value.
 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
-  if (X && Y) {
+  if (X.hasValue() && Y.hasValue()) {
     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
     APInt XW = X->sext(W);
     APInt YW = Y->sext(W);
     return XW.slt(YW) ? *X : *Y;
   }
-  if (!X && !Y)
+  if (!X.hasValue() && !Y.hasValue())
     return None;
-  return X ? *X : *Y;
+  return X.hasValue() ? *X : *Y;
 }
 
 /// Helper function to truncate an optional APInt to a given BitWidth.
@@ -9760,13 +9760,13 @@ SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
   APInt A, B, C, M;
   unsigned BitWidth;
   auto T = GetQuadraticEquation(AddRec);
-  if (!T)
+  if (!T.hasValue())
     return None;
 
   std::tie(A, B, C, M, BitWidth) = *T;
   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
-  if (!X)
+  if (!X.hasValue())
     return None;
 
   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
@@ -10471,8 +10471,8 @@ ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
     auto ResultSwapped =
         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
 
-    assert(ResultSwapped && "should be able to analyze both!");
-    assert(*ResultSwapped != *Result &&
+    assert(ResultSwapped.hasValue() && "should be able to analyze both!");
+    assert(ResultSwapped.getValue() != Result.getValue() &&
            "monotonicity should flip as we flip the predicate");
   }
 #endif

diff  --git a/llvm/lib/Analysis/StratifiedSets.h b/llvm/lib/Analysis/StratifiedSets.h
index 883ebd24efdcc..8468f2b0d1040 100644
--- a/llvm/lib/Analysis/StratifiedSets.h
+++ b/llvm/lib/Analysis/StratifiedSets.h
@@ -340,10 +340,10 @@ template <typename T> class StratifiedSetsBuilder {
     return StratifiedSets<T>(std::move(Values), std::move(StratLinks));
   }
 
-  bool has(const T &Elem) const { return get(Elem).has_value(); }
+  bool has(const T &Elem) const { return get(Elem).hasValue(); }
 
   bool add(const T &Main) {
-    if (get(Main))
+    if (get(Main).hasValue())
       return false;
 
     auto NewIndex = getNewUnlinkedIndex();

diff  --git a/llvm/lib/Analysis/VectorUtils.cpp b/llvm/lib/Analysis/VectorUtils.cpp
index 56a5983242b1c..beb14c456da8a 100644
--- a/llvm/lib/Analysis/VectorUtils.cpp
+++ b/llvm/lib/Analysis/VectorUtils.cpp
@@ -1501,8 +1501,8 @@ void VFABI::getVectorVariantNames(
 #ifndef NDEBUG
     LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << S << "'\n");
     Optional<VFInfo> Info = VFABI::tryDemangleForVFABI(S, *(CI.getModule()));
-    assert(Info && "Invalid name for a VFABI variant.");
-    assert(CI.getModule()->getFunction(Info->VectorName) &&
+    assert(Info.hasValue() && "Invalid name for a VFABI variant.");
+    assert(CI.getModule()->getFunction(Info.getValue().VectorName) &&
            "Vector function is missing.");
 #endif
     VariantMappings.push_back(std::string(S));

diff  --git a/llvm/lib/CodeGen/BasicBlockSections.cpp b/llvm/lib/CodeGen/BasicBlockSections.cpp
index b6b018cca8ae8..e6f4e396fa472 100644
--- a/llvm/lib/CodeGen/BasicBlockSections.cpp
+++ b/llvm/lib/CodeGen/BasicBlockSections.cpp
@@ -234,8 +234,9 @@ assignSections(MachineFunction &MF,
       // If we already have one cluster containing eh_pads, this must be updated
       // to ExceptionSectionID. Otherwise, we set it equal to the current
       // section ID.
-      EHPadsSectionID = EHPadsSectionID ? MBBSectionID::ExceptionSectionID
-                                        : MBB.getSectionID();
+      EHPadsSectionID = EHPadsSectionID.hasValue()
+                            ? MBBSectionID::ExceptionSectionID
+                            : MBB.getSectionID();
     }
   }
 

diff  --git a/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp b/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp
index 2c94f87804ac9..674649c5f386e 100644
--- a/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp
+++ b/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp
@@ -1291,12 +1291,12 @@ bool CombinerHelper::matchCombineConstantFoldFpUnary(MachineInstr &MI,
   Register SrcReg = MI.getOperand(1).getReg();
   LLT DstTy = MRI.getType(DstReg);
   Cst = constantFoldFpUnary(MI.getOpcode(), DstTy, SrcReg, MRI);
-  return Cst.has_value();
+  return Cst.hasValue();
 }
 
 void CombinerHelper::applyCombineConstantFoldFpUnary(MachineInstr &MI,
                                                      Optional<APFloat> &Cst) {
-  assert(Cst && "Optional is unexpectedly empty!");
+  assert(Cst.hasValue() && "Optional is unexpectedly empty!");
   Builder.setInstrAndDebugLoc(MI);
   MachineFunction &MF = Builder.getMF();
   auto *FPVal = ConstantFP::get(MF.getFunction().getContext(), *Cst);

diff  --git a/llvm/lib/CodeGen/MIRParser/MIParser.cpp b/llvm/lib/CodeGen/MIRParser/MIParser.cpp
index 5ddfc697b3997..879ec00b3d63c 100644
--- a/llvm/lib/CodeGen/MIRParser/MIParser.cpp
+++ b/llvm/lib/CodeGen/MIRParser/MIParser.cpp
@@ -741,8 +741,8 @@ bool MIParser::parseBasicBlockDefinition(
   MBB->setIsEHPad(IsLandingPad);
   MBB->setIsInlineAsmBrIndirectTarget(IsInlineAsmBrIndirectTarget);
   MBB->setIsEHFuncletEntry(IsEHFuncletEntry);
-  if (SectionID) {
-    MBB->setSectionID(*SectionID);
+  if (SectionID.hasValue()) {
+    MBB->setSectionID(SectionID.getValue());
     MF.setBBSectionsType(BasicBlockSection::List);
   }
   return false;

diff  --git a/llvm/lib/CodeGen/MachineBasicBlock.cpp b/llvm/lib/CodeGen/MachineBasicBlock.cpp
index a50e188afa240..c186d0ba99695 100644
--- a/llvm/lib/CodeGen/MachineBasicBlock.cpp
+++ b/llvm/lib/CodeGen/MachineBasicBlock.cpp
@@ -450,8 +450,8 @@ void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
 
   if (IrrLoopHeaderWeight && IsStandalone) {
     if (Indexes) OS << '\t';
-    OS.indent(2) << "; Irreducible loop header weight: " << *IrrLoopHeaderWeight
-                 << '\n';
+    OS.indent(2) << "; Irreducible loop header weight: "
+                 << IrrLoopHeaderWeight.getValue() << '\n';
   }
 }
 

diff  --git a/llvm/lib/CodeGen/MachineFunctionSplitter.cpp b/llvm/lib/CodeGen/MachineFunctionSplitter.cpp
index 3f55a82170c1c..7d0f294ca5523 100644
--- a/llvm/lib/CodeGen/MachineFunctionSplitter.cpp
+++ b/llvm/lib/CodeGen/MachineFunctionSplitter.cpp
@@ -106,8 +106,9 @@ bool MachineFunctionSplitter::runOnMachineFunction(MachineFunction &MF) {
   // We don't want to proceed further for cold functions
   // or functions of unknown hotness. Lukewarm functions have no prefix.
   Optional<StringRef> SectionPrefix = MF.getFunction().getSectionPrefix();
-  if (SectionPrefix &&
-      (SectionPrefix->equals("unlikely") || SectionPrefix->equals("unknown"))) {
+  if (SectionPrefix.hasValue() &&
+      (SectionPrefix.getValue().equals("unlikely") ||
+       SectionPrefix.getValue().equals("unknown"))) {
     return false;
   }
 

diff  --git a/llvm/lib/CodeGen/ModuloSchedule.cpp b/llvm/lib/CodeGen/ModuloSchedule.cpp
index 37b851f19ccf0..8e8cdb24452d9 100644
--- a/llvm/lib/CodeGen/ModuloSchedule.cpp
+++ b/llvm/lib/CodeGen/ModuloSchedule.cpp
@@ -1447,8 +1447,8 @@ Register KernelRewriter::remapUse(Register Reg, MachineInstr &MI) {
 Register KernelRewriter::phi(Register LoopReg, Optional<Register> InitReg,
                              const TargetRegisterClass *RC) {
   // If the init register is not undef, try and find an existing phi.
-  if (InitReg) {
-    auto I = Phis.find({LoopReg, *InitReg});
+  if (InitReg.hasValue()) {
+    auto I = Phis.find({LoopReg, InitReg.getValue()});
     if (I != Phis.end())
       return I->second;
   } else {
@@ -1469,10 +1469,10 @@ Register KernelRewriter::phi(Register LoopReg, Optional<Register> InitReg,
       return R;
     // Found a phi taking undef as input, so rewrite it to take InitReg.
     MachineInstr *MI = MRI.getVRegDef(R);
-    MI->getOperand(1).setReg(*InitReg);
-    Phis.insert({{LoopReg, *InitReg}, R});
+    MI->getOperand(1).setReg(InitReg.getValue());
+    Phis.insert({{LoopReg, InitReg.getValue()}, R});
     const TargetRegisterClass *ConstrainRegClass =
-        MRI.constrainRegClass(R, MRI.getRegClass(*InitReg));
+        MRI.constrainRegClass(R, MRI.getRegClass(InitReg.getValue()));
     assert(ConstrainRegClass && "Expected a valid constrained register class!");
     (void)ConstrainRegClass;
     UndefPhis.erase(I);
@@ -1483,18 +1483,18 @@ Register KernelRewriter::phi(Register LoopReg, Optional<Register> InitReg,
   if (!RC)
     RC = MRI.getRegClass(LoopReg);
   Register R = MRI.createVirtualRegister(RC);
-  if (InitReg) {
+  if (InitReg.hasValue()) {
     const TargetRegisterClass *ConstrainRegClass =
         MRI.constrainRegClass(R, MRI.getRegClass(*InitReg));
     assert(ConstrainRegClass && "Expected a valid constrained register class!");
     (void)ConstrainRegClass;
   }
   BuildMI(*BB, BB->getFirstNonPHI(), DebugLoc(), TII->get(TargetOpcode::PHI), R)
-      .addReg(InitReg ? *InitReg : undef(RC))
+      .addReg(InitReg.hasValue() ? *InitReg : undef(RC))
       .addMBB(PreheaderBB)
       .addReg(LoopReg)
       .addMBB(BB);
-  if (!InitReg)
+  if (!InitReg.hasValue())
     UndefPhis[LoopReg] = R;
   else
     Phis[{LoopReg, *InitReg}] = R;

diff  --git a/llvm/lib/CodeGen/SelectOptimize.cpp b/llvm/lib/CodeGen/SelectOptimize.cpp
index 403222794dfe7..c199b6a6cca85 100644
--- a/llvm/lib/CodeGen/SelectOptimize.cpp
+++ b/llvm/lib/CodeGen/SelectOptimize.cpp
@@ -870,8 +870,8 @@ bool SelectOptimize::computeLoopCosts(
           ORE->emit(ORmissL);
           return false;
         }
-        IPredCost += Scaled64::get(*ILatency);
-        INonPredCost += Scaled64::get(*ILatency);
+        IPredCost += Scaled64::get(ILatency.getValue());
+        INonPredCost += Scaled64::get(ILatency.getValue());
 
         // For a select that can be converted to branch,
         // compute its cost as a branch (non-predicated cost).

diff  --git a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
index aa688d9dda3c6..38f440acc1a66 100644
--- a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
@@ -24514,8 +24514,9 @@ bool DAGCombiner::mayAlias(SDNode *Op0, SDNode *Op1) const {
   auto &Size0 = MUC0.NumBytes;
   auto &Size1 = MUC1.NumBytes;
   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
-      Size0 && Size1 && *Size0 == *Size1 && OrigAlignment0 > *Size0 &&
-      SrcValOffset0 % *Size0 == 0 && SrcValOffset1 % *Size1 == 0) {
+      Size0.hasValue() && Size1.hasValue() && *Size0 == *Size1 &&
+      OrigAlignment0 > *Size0 && SrcValOffset0 % *Size0 == 0 &&
+      SrcValOffset1 % *Size1 == 0) {
     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0.value();
     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1.value();
 
@@ -24534,8 +24535,8 @@ bool DAGCombiner::mayAlias(SDNode *Op0, SDNode *Op1) const {
     UseAA = false;
 #endif
 
-  if (UseAA && AA && MUC0.MMO->getValue() && MUC1.MMO->getValue() && Size0 &&
-      Size1) {
+  if (UseAA && AA && MUC0.MMO->getValue() && MUC1.MMO->getValue() &&
+      Size0.hasValue() && Size1.hasValue()) {
     // Use alias analysis information.
     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
     int64_t Overlap0 = *Size0 + SrcValOffset0 - MinOffset;

diff  --git a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
index 103da92dc63dc..15455ebbfee89 100644
--- a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
@@ -703,8 +703,8 @@ static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
   unsigned NumRegs;
   if (IsABIRegCopy) {
     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
-        *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
-        RegisterVT);
+        *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
+        NumIntermediates, RegisterVT);
   } else {
     NumRegs =
         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
@@ -800,11 +800,11 @@ RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
   for (EVT ValueVT : ValueVTs) {
     unsigned NumRegs =
         isABIMangled()
-            ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
+            ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
             : TLI.getNumRegisters(Context, ValueVT);
     MVT RegisterVT =
         isABIMangled()
-            ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
+            ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
             : TLI.getRegisterType(Context, ValueVT);
     for (unsigned i = 0; i != NumRegs; ++i)
       Regs.push_back(Reg + i);
@@ -831,10 +831,10 @@ SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
     // Copy the legal parts from the registers.
     EVT ValueVT = ValueVTs[Value];
     unsigned NumRegs = RegCount[Value];
-    MVT RegisterVT = isABIMangled()
-                         ? TLI.getRegisterTypeForCallingConv(
-                               *DAG.getContext(), *CallConv, RegVTs[Value])
-                         : RegVTs[Value];
+    MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
+                                          *DAG.getContext(),
+                                          CallConv.getValue(), RegVTs[Value])
+                                    : RegVTs[Value];
 
     Parts.resize(NumRegs);
     for (unsigned i = 0; i != NumRegs; ++i) {
@@ -914,10 +914,10 @@ void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
     unsigned NumParts = RegCount[Value];
 
-    MVT RegisterVT = isABIMangled()
-                         ? TLI.getRegisterTypeForCallingConv(
-                               *DAG.getContext(), *CallConv, RegVTs[Value])
-                         : RegVTs[Value];
+    MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
+                                          *DAG.getContext(),
+                                          CallConv.getValue(), RegVTs[Value])
+                                    : RegVTs[Value];
 
     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
       ExtendKind = ISD::ZERO_EXTEND;
@@ -8867,10 +8867,10 @@ void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
             : OpInfo;
     const auto RegError =
         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
-    if (RegError) {
+    if (RegError.hasValue()) {
       const MachineFunction &MF = DAG.getMachineFunction();
       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
-      const char *RegName = TRI.getName(*RegError);
+      const char *RegName = TRI.getName(RegError.getValue());
       emitInlineAsmError(Call, "register '" + Twine(RegName) +
                                    "' allocated for constraint '" +
                                    Twine(OpInfo.ConstraintCode) +

diff  --git a/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp
index 68c53fd552945..b318c2ae76623 100644
--- a/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp
@@ -196,10 +196,10 @@ static Optional<int> findPreviousSpillSlot(const Value *Val,
     for (auto &IncomingValue : Phi->incoming_values()) {
       Optional<int> SpillSlot =
           findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
-      if (!SpillSlot)
+      if (!SpillSlot.hasValue())
         return None;
 
-      if (MergedResult && *MergedResult != *SpillSlot)
+      if (MergedResult.hasValue() && *MergedResult != *SpillSlot)
         return None;
 
       MergedResult = SpillSlot;
@@ -530,14 +530,16 @@ lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
     GCStrategy &S = GFI->getStrategy();
     for (const Value *V : SI.Bases) {
       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
-      if (Opt) {
-        assert(*Opt && "non gc managed base pointer found in statepoint");
+      if (Opt.hasValue()) {
+        assert(Opt.getValue() &&
+               "non gc managed base pointer found in statepoint");
       }
     }
     for (const Value *V : SI.Ptrs) {
       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
-      if (Opt) {
-        assert(*Opt && "non gc managed derived pointer found in statepoint");
+      if (Opt.hasValue()) {
+        assert(Opt.getValue() &&
+               "non gc managed derived pointer found in statepoint");
       }
     }
     assert(SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!");

diff  --git a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
index c286d211b6f5d..a6b471ea22b78 100644
--- a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
@@ -1972,9 +1972,9 @@ bool TargetLowering::SimplifyDemandedBits(
     KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
     Known = KnownBits::umin(Known0, Known1);
     if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1))
-      return TLO.CombineTo(Op, *IsULE ? Op0 : Op1);
+      return TLO.CombineTo(Op, IsULE.getValue() ? Op0 : Op1);
     if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1))
-      return TLO.CombineTo(Op, *IsULT ? Op0 : Op1);
+      return TLO.CombineTo(Op, IsULT.getValue() ? Op0 : Op1);
     break;
   }
   case ISD::UMAX: {
@@ -1985,9 +1985,9 @@ bool TargetLowering::SimplifyDemandedBits(
     KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
     Known = KnownBits::umax(Known0, Known1);
     if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
-      return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1);
+      return TLO.CombineTo(Op, IsUGE.getValue() ? Op0 : Op1);
     if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
-      return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1);
+      return TLO.CombineTo(Op, IsUGT.getValue() ? Op0 : Op1);
     break;
   }
   case ISD::BITREVERSE: {

diff  --git a/llvm/lib/DebugInfo/CodeView/CodeViewRecordIO.cpp b/llvm/lib/DebugInfo/CodeView/CodeViewRecordIO.cpp
index a66f9af988358..c49c2e5e1d32f 100644
--- a/llvm/lib/DebugInfo/CodeView/CodeViewRecordIO.cpp
+++ b/llvm/lib/DebugInfo/CodeView/CodeViewRecordIO.cpp
@@ -70,10 +70,10 @@ uint32_t CodeViewRecordIO::maxFieldLength() const {
   Optional<uint32_t> Min = Limits.front().bytesRemaining(Offset);
   for (auto X : makeArrayRef(Limits).drop_front()) {
     Optional<uint32_t> ThisMin = X.bytesRemaining(Offset);
-    if (ThisMin)
-      Min = Min ? std::min(*Min, *ThisMin) : *ThisMin;
+    if (ThisMin.hasValue())
+      Min = (Min.hasValue()) ? std::min(*Min, *ThisMin) : *ThisMin;
   }
-  assert(Min && "Every field must have a maximum length!");
+  assert(Min.hasValue() && "Every field must have a maximum length!");
 
   return *Min;
 }

diff  --git a/llvm/lib/DebugInfo/CodeView/TypeRecordMapping.cpp b/llvm/lib/DebugInfo/CodeView/TypeRecordMapping.cpp
index 27f63b9edcd03..9b35b23739650 100644
--- a/llvm/lib/DebugInfo/CodeView/TypeRecordMapping.cpp
+++ b/llvm/lib/DebugInfo/CodeView/TypeRecordMapping.cpp
@@ -228,8 +228,8 @@ static Error mapNameAndUniqueName(CodeViewRecordIO &IO, StringRef &Name,
 }
 
 Error TypeRecordMapping::visitTypeBegin(CVType &CVR) {
-  assert(!TypeKind && "Already in a type mapping!");
-  assert(!MemberKind && "Already in a member mapping!");
+  assert(!TypeKind.hasValue() && "Already in a type mapping!");
+  assert(!MemberKind.hasValue() && "Already in a member mapping!");
 
   // FieldList and MethodList records can be any length because they can be
   // split with continuation records.  All other record types cannot be
@@ -260,8 +260,8 @@ Error TypeRecordMapping::visitTypeBegin(CVType &CVR, TypeIndex Index) {
 }
 
 Error TypeRecordMapping::visitTypeEnd(CVType &Record) {
-  assert(TypeKind && "Not in a type mapping!");
-  assert(!MemberKind && "Still in a member mapping!");
+  assert(TypeKind.hasValue() && "Not in a type mapping!");
+  assert(!MemberKind.hasValue() && "Still in a member mapping!");
 
   error(IO.endRecord());
 
@@ -270,8 +270,8 @@ Error TypeRecordMapping::visitTypeEnd(CVType &Record) {
 }
 
 Error TypeRecordMapping::visitMemberBegin(CVMemberRecord &Record) {
-  assert(TypeKind && "Not in a type mapping!");
-  assert(!MemberKind && "Already in a member mapping!");
+  assert(TypeKind.hasValue() && "Not in a type mapping!");
+  assert(!MemberKind.hasValue() && "Already in a member mapping!");
 
   // The largest possible subrecord is one in which there is a record prefix,
   // followed by the subrecord, followed by a continuation, and that entire
@@ -296,8 +296,8 @@ Error TypeRecordMapping::visitMemberBegin(CVMemberRecord &Record) {
 }
 
 Error TypeRecordMapping::visitMemberEnd(CVMemberRecord &Record) {
-  assert(TypeKind && "Not in a type mapping!");
-  assert(MemberKind && "Not in a member mapping!");
+  assert(TypeKind.hasValue() && "Not in a type mapping!");
+  assert(MemberKind.hasValue() && "Not in a member mapping!");
 
   if (IO.isReading()) {
     if (auto EC = IO.skipPadding())

diff  --git a/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp b/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
index dd49ef8194304..c785026f8461b 100644
--- a/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
+++ b/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
@@ -1205,12 +1205,13 @@ void DWARFContext::addLocalsForDie(DWARFCompileUnit *CU, DWARFDie Subprogram,
     if (auto DeclFileAttr = Die.find(DW_AT_decl_file)) {
       if (const auto *LT = CU->getContext().getLineTableForUnit(CU))
         LT->getFileNameByIndex(
-            *DeclFileAttr->getAsUnsignedConstant(), CU->getCompilationDir(),
+            DeclFileAttr->getAsUnsignedConstant().getValue(),
+            CU->getCompilationDir(),
             DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
             Local.DeclFile);
     }
     if (auto DeclLineAttr = Die.find(DW_AT_decl_line))
-      Local.DeclLine = *DeclLineAttr->getAsUnsignedConstant();
+      Local.DeclLine = DeclLineAttr->getAsUnsignedConstant().getValue();
 
     Result.push_back(Local);
     return;

diff  --git a/llvm/lib/DebugInfo/DWARF/DWARFDebugLine.cpp b/llvm/lib/DebugInfo/DWARF/DWARFDebugLine.cpp
index 25d0b9f84005f..2e0780e249aa4 100644
--- a/llvm/lib/DebugInfo/DWARF/DWARFDebugLine.cpp
+++ b/llvm/lib/DebugInfo/DWARF/DWARFDebugLine.cpp
@@ -327,20 +327,20 @@ parseV5DirFileTables(const DWARFDataExtractor &DebugLineData,
         FileEntry.Source = Value;
         break;
       case DW_LNCT_directory_index:
-        FileEntry.DirIdx = *Value.getAsUnsignedConstant();
+        FileEntry.DirIdx = Value.getAsUnsignedConstant().getValue();
         break;
       case DW_LNCT_timestamp:
-        FileEntry.ModTime = *Value.getAsUnsignedConstant();
+        FileEntry.ModTime = Value.getAsUnsignedConstant().getValue();
         break;
       case DW_LNCT_size:
-        FileEntry.Length = *Value.getAsUnsignedConstant();
+        FileEntry.Length = Value.getAsUnsignedConstant().getValue();
         break;
       case DW_LNCT_MD5:
-        if (!Value.getAsBlock() || Value.getAsBlock()->size() != 16)
+        if (!Value.getAsBlock() || Value.getAsBlock().getValue().size() != 16)
           return createStringError(
               errc::invalid_argument,
               "failed to parse file entry because the MD5 hash is invalid");
-        std::uninitialized_copy_n(Value.getAsBlock()->begin(), 16,
+        std::uninitialized_copy_n(Value.getAsBlock().getValue().begin(), 16,
                                   FileEntry.Checksum.begin());
         break;
       default:

diff  --git a/llvm/lib/DebugInfo/PDB/Native/DbiStreamBuilder.cpp b/llvm/lib/DebugInfo/PDB/Native/DbiStreamBuilder.cpp
index 3a719bd07c8a3..1cb332c5fd00a 100644
--- a/llvm/lib/DebugInfo/PDB/Native/DbiStreamBuilder.cpp
+++ b/llvm/lib/DebugInfo/PDB/Native/DbiStreamBuilder.cpp
@@ -427,14 +427,14 @@ Error DbiStreamBuilder::commit(const msf::MSFLayout &Layout,
 
   for (auto &Stream : DbgStreams) {
     uint16_t StreamNumber = kInvalidStreamIndex;
-    if (Stream)
+    if (Stream.hasValue())
       StreamNumber = Stream->StreamNumber;
     if (auto EC = Writer.writeInteger(StreamNumber))
       return EC;
   }
 
   for (auto &Stream : DbgStreams) {
-    if (!Stream)
+    if (!Stream.hasValue())
       continue;
     assert(Stream->StreamNumber != kInvalidStreamIndex);
 

diff  --git a/llvm/lib/Frontend/OpenMP/OMPContext.cpp b/llvm/lib/Frontend/OpenMP/OMPContext.cpp
index 017548f83e372..eea08b23db9c1 100644
--- a/llvm/lib/Frontend/OpenMP/OMPContext.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPContext.cpp
@@ -212,8 +212,9 @@ static int isVariantApplicableInContextHelper(
         return Ctx.matchesISATrait(RawString);
       });
 
-    if (Optional<bool> Result = HandleTrait(Property, IsActiveTrait))
-      return *Result;
+    Optional<bool> Result = HandleTrait(Property, IsActiveTrait);
+    if (Result.hasValue())
+      return Result.getValue();
   }
 
   if (!DeviceSetOnly) {
@@ -232,8 +233,9 @@ static int isVariantApplicableInContextHelper(
       if (ConstructMatches)
         ConstructMatches->push_back(ConstructIdx - 1);
 
-      if (Optional<bool> Result = HandleTrait(Property, FoundInOrder))
-        return *Result;
+      Optional<bool> Result = HandleTrait(Property, FoundInOrder);
+      if (Result.hasValue())
+        return Result.getValue();
 
       if (!FoundInOrder) {
         LLVM_DEBUG(dbgs() << "[" << DEBUG_TYPE << "] Construct property "

diff  --git a/llvm/lib/IR/Instructions.cpp b/llvm/lib/IR/Instructions.cpp
index 7e718ac5300a4..22e8ca70c0a6a 100644
--- a/llvm/lib/IR/Instructions.cpp
+++ b/llvm/lib/IR/Instructions.cpp
@@ -4423,9 +4423,10 @@ MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() {
   assert(SI.getNumSuccessors() == Weights->size() &&
          "num of prof branch_weights must accord with num of successors");
 
-  bool AllZeroes = all_of(*Weights, [](uint32_t W) { return W == 0; });
+  bool AllZeroes =
+      all_of(Weights.getValue(), [](uint32_t W) { return W == 0; });
 
-  if (AllZeroes || Weights->size() < 2)
+  if (AllZeroes || Weights.getValue().size() < 2)
     return nullptr;
 
   return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights);
@@ -4459,8 +4460,8 @@ SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) {
     // Copy the last case to the place of the removed one and shrink.
     // This is tightly coupled with the way SwitchInst::removeCase() removes
     // the cases in SwitchInst::removeCase(CaseIt).
-    Weights.value()[I->getCaseIndex() + 1] = Weights->back();
-    Weights->pop_back();
+    Weights.getValue()[I->getCaseIndex() + 1] = Weights.getValue().back();
+    Weights.getValue().pop_back();
   }
   return SI.removeCase(I);
 }
@@ -4473,10 +4474,10 @@ void SwitchInstProfUpdateWrapper::addCase(
   if (!Weights && W && *W) {
     Changed = true;
     Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
-    Weights.value()[SI.getNumSuccessors() - 1] = *W;
+    Weights.getValue()[SI.getNumSuccessors() - 1] = *W;
   } else if (Weights) {
     Changed = true;
-    Weights->push_back(W.value_or(0));
+    Weights.getValue().push_back(W.value_or(0));
   }
   if (Weights)
     assert(SI.getNumSuccessors() == Weights->size() &&

diff  --git a/llvm/lib/IR/IntrinsicInst.cpp b/llvm/lib/IR/IntrinsicInst.cpp
index 953090fdb2ca4..ac03b1493dd7a 100644
--- a/llvm/lib/IR/IntrinsicInst.cpp
+++ b/llvm/lib/IR/IntrinsicInst.cpp
@@ -223,13 +223,13 @@ ConstrainedFPIntrinsic::getExceptionBehavior() const {
 bool ConstrainedFPIntrinsic::isDefaultFPEnvironment() const {
   Optional<fp::ExceptionBehavior> Except = getExceptionBehavior();
   if (Except) {
-    if (*Except != fp::ebIgnore)
+    if (Except.getValue() != fp::ebIgnore)
       return false;
   }
 
   Optional<RoundingMode> Rounding = getRoundingMode();
   if (Rounding) {
-    if (*Rounding != RoundingMode::NearestTiesToEven)
+    if (Rounding.getValue() != RoundingMode::NearestTiesToEven)
       return false;
   }
 
@@ -363,14 +363,14 @@ VPIntrinsic::getVectorLengthParamPos(Intrinsic::ID IntrinsicID) {
 /// scatter.
 MaybeAlign VPIntrinsic::getPointerAlignment() const {
   Optional<unsigned> PtrParamOpt = getMemoryPointerParamPos(getIntrinsicID());
-  assert(PtrParamOpt && "no pointer argument!");
-  return getParamAlign(*PtrParamOpt);
+  assert(PtrParamOpt.hasValue() && "no pointer argument!");
+  return getParamAlign(PtrParamOpt.getValue());
 }
 
 /// \return The pointer operand of this load,store, gather or scatter.
 Value *VPIntrinsic::getMemoryPointerParam() const {
   if (auto PtrParamOpt = getMemoryPointerParamPos(getIntrinsicID()))
-    return getArgOperand(*PtrParamOpt);
+    return getArgOperand(PtrParamOpt.getValue());
   return nullptr;
 }
 
@@ -388,9 +388,10 @@ Optional<unsigned> VPIntrinsic::getMemoryPointerParamPos(Intrinsic::ID VPID) {
 
 /// \return The data (payload) operand of this store or scatter.
 Value *VPIntrinsic::getMemoryDataParam() const {
-  if (auto DataParamOpt = getMemoryDataParamPos(getIntrinsicID()))
-    return getArgOperand(*DataParamOpt);
-  return nullptr;
+  auto DataParamOpt = getMemoryDataParamPos(getIntrinsicID());
+  if (!DataParamOpt.hasValue())
+    return nullptr;
+  return getArgOperand(DataParamOpt.getValue());
 }
 
 Optional<unsigned> VPIntrinsic::getMemoryDataParamPos(Intrinsic::ID VPID) {

diff  --git a/llvm/lib/IR/LLVMContextImpl.cpp b/llvm/lib/IR/LLVMContextImpl.cpp
index 7e005b39860f2..dc44a34ea9101 100644
--- a/llvm/lib/IR/LLVMContextImpl.cpp
+++ b/llvm/lib/IR/LLVMContextImpl.cpp
@@ -250,17 +250,17 @@ void LLVMContextImpl::setOptPassGate(OptPassGate& OPG) {
 }
 
 bool LLVMContextImpl::hasOpaquePointersValue() {
-  return OpaquePointers.has_value();
+  return OpaquePointers.hasValue();
 }
 
 bool LLVMContextImpl::getOpaquePointers() {
-  if (LLVM_UNLIKELY(!OpaquePointers))
+  if (LLVM_UNLIKELY(!(OpaquePointers.hasValue())))
     OpaquePointers = OpaquePointersCL;
   return *OpaquePointers;
 }
 
 void LLVMContextImpl::setOpaquePointers(bool OP) {
-  assert((!OpaquePointers || *OpaquePointers == OP) &&
+  assert((!OpaquePointers.hasValue() || OpaquePointers.getValue() == OP) &&
          "Cannot change opaque pointers mode once set");
   OpaquePointers = OP;
 }

diff  --git a/llvm/lib/IR/VectorBuilder.cpp b/llvm/lib/IR/VectorBuilder.cpp
index e7be7a98a593c..82995ce3d05c4 100644
--- a/llvm/lib/IR/VectorBuilder.cpp
+++ b/llvm/lib/IR/VectorBuilder.cpp
@@ -90,9 +90,9 @@ Value *VectorBuilder::createVectorInstruction(unsigned Opcode, Type *ReturnTy,
     }
   }
 
-  if (MaskPosOpt)
+  if (MaskPosOpt.hasValue())
     IntrinParams[*MaskPosOpt] = &requestMask();
-  if (VLenPosOpt)
+  if (VLenPosOpt.hasValue())
     IntrinParams[*VLenPosOpt] = &requestEVL();
 
   auto *VPDecl = VPIntrinsic::getDeclarationForParams(&getModule(), VPID,

diff  --git a/llvm/lib/IR/Verifier.cpp b/llvm/lib/IR/Verifier.cpp
index cbdf1d1899585..8f857933ada60 100644
--- a/llvm/lib/IR/Verifier.cpp
+++ b/llvm/lib/IR/Verifier.cpp
@@ -5844,10 +5844,10 @@ void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
   // match the specification in the intrinsic call table. Thus, no
   // argument type check is needed here.
 
-  Check(FPI.getExceptionBehavior().has_value(),
+  Check(FPI.getExceptionBehavior().hasValue(),
         "invalid exception behavior argument", &FPI);
   if (HasRoundingMD) {
-    Check(FPI.getRoundingMode().has_value(), "invalid rounding mode argument",
+    Check(FPI.getRoundingMode().hasValue(), "invalid rounding mode argument",
           &FPI);
   }
 }

diff  --git a/llvm/lib/InterfaceStub/IFSHandler.cpp b/llvm/lib/InterfaceStub/IFSHandler.cpp
index c9993874dfc6b..71189e79360e1 100644
--- a/llvm/lib/InterfaceStub/IFSHandler.cpp
+++ b/llvm/lib/InterfaceStub/IFSHandler.cpp
@@ -202,8 +202,8 @@ Error ifs::writeIFSToOutputStream(raw_ostream &OS, const IFSStub &Stub) {
   yaml::Output YamlOut(OS, nullptr, /*WrapColumn =*/0);
   std::unique_ptr<IFSStubTriple> CopyStub(new IFSStubTriple(Stub));
   if (Stub.Target.Arch) {
-    CopyStub->Target.ArchString =
-        std::string(ELF::convertEMachineToArchName(*Stub.Target.Arch));
+    CopyStub->Target.ArchString = std::string(
+        ELF::convertEMachineToArchName(Stub.Target.Arch.getValue()));
   }
   IFSTarget Target = Stub.Target;
 
@@ -222,33 +222,36 @@ Error ifs::overrideIFSTarget(IFSStub &Stub, Optional<IFSArch> OverrideArch,
                              Optional<std::string> OverrideTriple) {
   std::error_code OverrideEC(1, std::generic_category());
   if (OverrideArch) {
-    if (Stub.Target.Arch && *Stub.Target.Arch != *OverrideArch) {
+    if (Stub.Target.Arch &&
+        Stub.Target.Arch.getValue() != OverrideArch.getValue()) {
       return make_error<StringError>(
           "Supplied Arch conflicts with the text stub", OverrideEC);
     }
-    Stub.Target.Arch = *OverrideArch;
+    Stub.Target.Arch = OverrideArch.getValue();
   }
   if (OverrideEndianness) {
     if (Stub.Target.Endianness &&
-        *Stub.Target.Endianness != *OverrideEndianness) {
+        Stub.Target.Endianness.getValue() != OverrideEndianness.getValue()) {
       return make_error<StringError>(
           "Supplied Endianness conflicts with the text stub", OverrideEC);
     }
-    Stub.Target.Endianness = *OverrideEndianness;
+    Stub.Target.Endianness = OverrideEndianness.getValue();
   }
   if (OverrideBitWidth) {
-    if (Stub.Target.BitWidth && *Stub.Target.BitWidth != *OverrideBitWidth) {
+    if (Stub.Target.BitWidth &&
+        Stub.Target.BitWidth.getValue() != OverrideBitWidth.getValue()) {
       return make_error<StringError>(
           "Supplied BitWidth conflicts with the text stub", OverrideEC);
     }
-    Stub.Target.BitWidth = *OverrideBitWidth;
+    Stub.Target.BitWidth = OverrideBitWidth.getValue();
   }
   if (OverrideTriple) {
-    if (Stub.Target.Triple && *Stub.Target.Triple != *OverrideTriple) {
+    if (Stub.Target.Triple &&
+        Stub.Target.Triple.getValue() != OverrideTriple.getValue()) {
       return make_error<StringError>(
           "Supplied Triple conflicts with the text stub", OverrideEC);
     }
-    Stub.Target.Triple = *OverrideTriple;
+    Stub.Target.Triple = OverrideTriple.getValue();
   }
   return Error::success();
 }

diff  --git a/llvm/lib/MC/MCContext.cpp b/llvm/lib/MC/MCContext.cpp
index e8f0987e8e102..1c0c711a4e3a0 100644
--- a/llvm/lib/MC/MCContext.cpp
+++ b/llvm/lib/MC/MCContext.cpp
@@ -767,13 +767,14 @@ MCSectionXCOFF *MCContext::getXCOFFSection(
     Optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed,
     const char *BeginSymName,
     Optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) {
-  bool IsDwarfSec = DwarfSectionSubtypeFlags.has_value();
-  assert((IsDwarfSec != CsectProp.has_value()) && "Invalid XCOFF section!");
+  bool IsDwarfSec = DwarfSectionSubtypeFlags.hasValue();
+  assert((IsDwarfSec != CsectProp.hasValue()) && "Invalid XCOFF section!");
 
   // Do the lookup. If we have a hit, return it.
   auto IterBool = XCOFFUniquingMap.insert(std::make_pair(
-      IsDwarfSec ? XCOFFSectionKey(Section.str(), *DwarfSectionSubtypeFlags)
-                 : XCOFFSectionKey(Section.str(), CsectProp->MappingClass),
+      IsDwarfSec
+          ? XCOFFSectionKey(Section.str(), DwarfSectionSubtypeFlags.getValue())
+          : XCOFFSectionKey(Section.str(), CsectProp->MappingClass),
       nullptr));
   auto &Entry = *IterBool.first;
   if (!IterBool.second) {
@@ -803,9 +804,10 @@ MCSectionXCOFF *MCContext::getXCOFFSection(
   // CachedName contains invalid character(s) such as '$' for an XCOFF symbol.
   MCSectionXCOFF *Result = nullptr;
   if (IsDwarfSec)
-    Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF(
-        QualName->getUnqualifiedName(), Kind, QualName,
-        *DwarfSectionSubtypeFlags, Begin, CachedName, MultiSymbolsAllowed);
+    Result = new (XCOFFAllocator.Allocate())
+        MCSectionXCOFF(QualName->getUnqualifiedName(), Kind, QualName,
+                       DwarfSectionSubtypeFlags.getValue(), Begin, CachedName,
+                       MultiSymbolsAllowed);
   else
     Result = new (XCOFFAllocator.Allocate())
         MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass,

diff  --git a/llvm/lib/MC/MCDisassembler/MCDisassembler.cpp b/llvm/lib/MC/MCDisassembler/MCDisassembler.cpp
index af52c34b7c292..c6035dca4ce19 100644
--- a/llvm/lib/MC/MCDisassembler/MCDisassembler.cpp
+++ b/llvm/lib/MC/MCDisassembler/MCDisassembler.cpp
@@ -83,13 +83,12 @@ bool XCOFFSymbolInfo::operator<(const XCOFFSymbolInfo &SymInfo) const {
     return SymInfo.IsLabel;
 
   // Symbols with a StorageMappingClass have higher priority than those without.
-  if (StorageMappingClass.has_value() !=
-      SymInfo.StorageMappingClass.has_value())
-    return SymInfo.StorageMappingClass.has_value();
+  if (StorageMappingClass.hasValue() != SymInfo.StorageMappingClass.hasValue())
+    return SymInfo.StorageMappingClass.hasValue();
 
-  if (StorageMappingClass) {
-    return getSMCPriority(*StorageMappingClass) <
-           getSMCPriority(*SymInfo.StorageMappingClass);
+  if (StorageMappingClass.hasValue()) {
+    return getSMCPriority(StorageMappingClass.getValue()) <
+           getSMCPriority(SymInfo.StorageMappingClass.getValue());
   }
 
   return false;

diff  --git a/llvm/lib/MC/MCParser/MasmParser.cpp b/llvm/lib/MC/MCParser/MasmParser.cpp
index c4240cac6c00a..7ed37b02f460d 100644
--- a/llvm/lib/MC/MCParser/MasmParser.cpp
+++ b/llvm/lib/MC/MCParser/MasmParser.cpp
@@ -4239,9 +4239,10 @@ bool MasmParser::parseStructInitializer(const StructInfo &Structure,
 
   auto &FieldInitializers = Initializer.FieldInitializers;
   size_t FieldIndex = 0;
-  if (EndToken) {
+  if (EndToken.hasValue()) {
     // Initialize all fields with given initializers.
-    while (getTok().isNot(*EndToken) && FieldIndex < Structure.Fields.size()) {
+    while (getTok().isNot(EndToken.getValue()) &&
+           FieldIndex < Structure.Fields.size()) {
       const FieldInfo &Field = Structure.Fields[FieldIndex++];
       if (parseOptionalToken(AsmToken::Comma)) {
         // Empty initializer; use the default and continue. (Also, allow line
@@ -4271,11 +4272,11 @@ bool MasmParser::parseStructInitializer(const StructInfo &Structure,
     FieldInitializers.push_back(Field.Contents);
   }
 
-  if (EndToken) {
-    if (*EndToken == AsmToken::Greater)
+  if (EndToken.hasValue()) {
+    if (EndToken.getValue() == AsmToken::Greater)
       return parseAngleBracketClose();
 
-    return parseToken(*EndToken);
+    return parseToken(EndToken.getValue());
   }
 
   return false;

diff  --git a/llvm/lib/MC/MCSchedule.cpp b/llvm/lib/MC/MCSchedule.cpp
index dd1ecce365b61..db08e20441137 100644
--- a/llvm/lib/MC/MCSchedule.cpp
+++ b/llvm/lib/MC/MCSchedule.cpp
@@ -96,10 +96,10 @@ MCSchedModel::getReciprocalThroughput(const MCSubtargetInfo &STI,
       continue;
     unsigned NumUnits = SM.getProcResource(I->ProcResourceIdx)->NumUnits;
     double Temp = NumUnits * 1.0 / I->Cycles;
-    Throughput = Throughput ? std::min(*Throughput, Temp) : Temp;
+    Throughput = Throughput ? std::min(Throughput.getValue(), Temp) : Temp;
   }
-  if (Throughput)
-    return 1.0 / *Throughput;
+  if (Throughput.hasValue())
+    return 1.0 / Throughput.getValue();
 
   // If no throughput value was calculated, assume that we can execute at the
   // maximum issue width scaled by number of micro-ops for the schedule class.
@@ -140,10 +140,10 @@ MCSchedModel::getReciprocalThroughput(unsigned SchedClass,
     if (!I->getCycles())
       continue;
     double Temp = countPopulation(I->getUnits()) * 1.0 / I->getCycles();
-    Throughput = Throughput ? std::min(*Throughput, Temp) : Temp;
+    Throughput = Throughput ? std::min(Throughput.getValue(), Temp) : Temp;
   }
-  if (Throughput)
-    return 1.0 / *Throughput;
+  if (Throughput.hasValue())
+    return 1.0 / Throughput.getValue();
 
   // If there are no execution resources specified for this class, then assume
   // that it can execute at the maximum default issue width.

diff  --git a/llvm/lib/MC/MCSectionXCOFF.cpp b/llvm/lib/MC/MCSectionXCOFF.cpp
index 0f6d5d5ad0806..ee8fa04c421ff 100644
--- a/llvm/lib/MC/MCSectionXCOFF.cpp
+++ b/llvm/lib/MC/MCSectionXCOFF.cpp
@@ -110,8 +110,8 @@ void MCSectionXCOFF::printSwitchToSection(const MCAsmInfo &MAI, const Triple &T,
 
   // XCOFF debug sections.
   if (getKind().isMetadata() && isDwarfSect()) {
-    OS << "\n\t.dwsect " << format("0x%" PRIx32, *getDwarfSubtypeFlags())
-       << '\n';
+    OS << "\n\t.dwsect "
+       << format("0x%" PRIx32, getDwarfSubtypeFlags().getValue()) << '\n';
     OS << MAI.getPrivateLabelPrefix() << getName() << ':' << '\n';
     return;
   }

diff  --git a/llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp b/llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp
index 01c0ae7596bbd..a7b7a47e49ca4 100644
--- a/llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp
+++ b/llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp
@@ -601,8 +601,8 @@ handleUserSection(const NewSectionInfo &NewSection,
 static Error handleArgs(const CommonConfig &Config, const ELFConfig &ELFConfig,
                         Object &Obj) {
   if (Config.OutputArch) {
-    Obj.Machine = Config.OutputArch->EMachine;
-    Obj.OSABI = Config.OutputArch->OSABI;
+    Obj.Machine = Config.OutputArch.getValue().EMachine;
+    Obj.OSABI = Config.OutputArch.getValue().OSABI;
   }
 
   if (!Config.SplitDWO.empty() && Config.ExtractDWO) {
@@ -639,8 +639,8 @@ static Error handleArgs(const CommonConfig &Config, const ELFConfig &ELFConfig,
       if (Iter != Config.SectionsToRename.end()) {
         const SectionRename &SR = Iter->second;
         Sec.Name = std::string(SR.NewName);
-        if (SR.NewFlags)
-          setSectionFlagsAndType(Sec, *SR.NewFlags);
+        if (SR.NewFlags.hasValue())
+          setSectionFlagsAndType(Sec, SR.NewFlags.getValue());
         RenamedSections.insert(&Sec);
       } else if (RelocSec && !(Sec.Flags & SHF_ALLOC))
         // Postpone processing relocation sections which are not specified in
@@ -808,9 +808,9 @@ Error objcopy::elf::executeObjcopyOnBinary(const CommonConfig &Config,
   if (!Obj)
     return Obj.takeError();
   // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
-  const ElfType OutputElfType = Config.OutputArch
-                                    ? getOutputElfType(*Config.OutputArch)
-                                    : getOutputElfType(In);
+  const ElfType OutputElfType =
+      Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
+                        : getOutputElfType(In);
 
   if (Error E = handleArgs(Config, ELFConfig, **Obj))
     return createFileError(Config.InputFilename, std::move(E));

diff  --git a/llvm/lib/Object/ELFObjectFile.cpp b/llvm/lib/Object/ELFObjectFile.cpp
index 9ab03578914e6..9bac454602abb 100644
--- a/llvm/lib/Object/ELFObjectFile.cpp
+++ b/llvm/lib/Object/ELFObjectFile.cpp
@@ -167,12 +167,12 @@ SubtargetFeatures ELFObjectFileBase::getARMFeatures() const {
   bool isV7 = false;
   Optional<unsigned> Attr =
       Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
-  if (Attr)
-    isV7 = *Attr == ARMBuildAttrs::v7;
+  if (Attr.hasValue())
+    isV7 = Attr.getValue() == ARMBuildAttrs::v7;
 
   Attr = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch_profile);
-  if (Attr) {
-    switch (*Attr) {
+  if (Attr.hasValue()) {
+    switch (Attr.getValue()) {
     case ARMBuildAttrs::ApplicationProfile:
       Features.AddFeature("aclass");
       break;
@@ -190,8 +190,8 @@ SubtargetFeatures ELFObjectFileBase::getARMFeatures() const {
   }
 
   Attr = Attributes.getAttributeValue(ARMBuildAttrs::THUMB_ISA_use);
-  if (Attr) {
-    switch (*Attr) {
+  if (Attr.hasValue()) {
+    switch (Attr.getValue()) {
     default:
       break;
     case ARMBuildAttrs::Not_Allowed:
@@ -205,8 +205,8 @@ SubtargetFeatures ELFObjectFileBase::getARMFeatures() const {
   }
 
   Attr = Attributes.getAttributeValue(ARMBuildAttrs::FP_arch);
-  if (Attr) {
-    switch (*Attr) {
+  if (Attr.hasValue()) {
+    switch (Attr.getValue()) {
     default:
       break;
     case ARMBuildAttrs::Not_Allowed:
@@ -229,8 +229,8 @@ SubtargetFeatures ELFObjectFileBase::getARMFeatures() const {
   }
 
   Attr = Attributes.getAttributeValue(ARMBuildAttrs::Advanced_SIMD_arch);
-  if (Attr) {
-    switch (*Attr) {
+  if (Attr.hasValue()) {
+    switch (Attr.getValue()) {
     default:
       break;
     case ARMBuildAttrs::Not_Allowed:
@@ -248,8 +248,8 @@ SubtargetFeatures ELFObjectFileBase::getARMFeatures() const {
   }
 
   Attr = Attributes.getAttributeValue(ARMBuildAttrs::MVE_arch);
-  if (Attr) {
-    switch (*Attr) {
+  if (Attr.hasValue()) {
+    switch (Attr.getValue()) {
     default:
       break;
     case ARMBuildAttrs::Not_Allowed:
@@ -267,8 +267,8 @@ SubtargetFeatures ELFObjectFileBase::getARMFeatures() const {
   }
 
   Attr = Attributes.getAttributeValue(ARMBuildAttrs::DIV_use);
-  if (Attr) {
-    switch (*Attr) {
+  if (Attr.hasValue()) {
+    switch (Attr.getValue()) {
     default:
       break;
     case ARMBuildAttrs::DisallowDIV:
@@ -521,8 +521,8 @@ void ELFObjectFileBase::setARMSubArch(Triple &TheTriple) const {
 
   Optional<unsigned> Attr =
       Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
-  if (Attr) {
-    switch (*Attr) {
+  if (Attr.hasValue()) {
+    switch (Attr.getValue()) {
     case ARMBuildAttrs::v4:
       Triple += "v4";
       break;
@@ -553,8 +553,8 @@ void ELFObjectFileBase::setARMSubArch(Triple &TheTriple) const {
     case ARMBuildAttrs::v7: {
       Optional<unsigned> ArchProfileAttr =
           Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch_profile);
-      if (ArchProfileAttr &&
-          *ArchProfileAttr == ARMBuildAttrs::MicroControllerProfile)
+      if (ArchProfileAttr.hasValue() &&
+          ArchProfileAttr.getValue() == ARMBuildAttrs::MicroControllerProfile)
         Triple += "v7m";
       else
         Triple += "v7";

diff  --git a/llvm/lib/ObjectYAML/DXContainerEmitter.cpp b/llvm/lib/ObjectYAML/DXContainerEmitter.cpp
index d51120b3ab5a1..9834b036de903 100644
--- a/llvm/lib/ObjectYAML/DXContainerEmitter.cpp
+++ b/llvm/lib/ObjectYAML/DXContainerEmitter.cpp
@@ -133,17 +133,17 @@ void DXContainerWriter::writeParts(raw_ostream &OS) {
 
       // Compute the optional fields if needed...
       if (P.Program->DXILOffset)
-        Header.Bitcode.Offset = *P.Program->DXILOffset;
+        Header.Bitcode.Offset = P.Program->DXILOffset.getValue();
       else
         Header.Bitcode.Offset = sizeof(dxbc::BitcodeHeader);
 
       if (P.Program->DXILSize)
-        Header.Bitcode.Size = *P.Program->DXILSize;
+        Header.Bitcode.Size = P.Program->DXILSize.getValue();
       else
         Header.Bitcode.Size = P.Program->DXIL ? P.Program->DXIL->size() : 0;
 
       if (P.Program->Size)
-        Header.Size = *P.Program->Size;
+        Header.Size = P.Program->Size.getValue();
       else
         Header.Size = sizeof(dxbc::ProgramHeader) + Header.Bitcode.Size;
 

diff  --git a/llvm/lib/Support/Process.cpp b/llvm/lib/Support/Process.cpp
index d93b7de619cb6..547b3b73eec2d 100644
--- a/llvm/lib/Support/Process.cpp
+++ b/llvm/lib/Support/Process.cpp
@@ -42,12 +42,12 @@ Optional<std::string> Process::FindInEnvPath(StringRef EnvName,
   assert(!path::is_absolute(FileName));
   Optional<std::string> FoundPath;
   Optional<std::string> OptPath = Process::GetEnv(EnvName);
-  if (!OptPath)
+  if (!OptPath.hasValue())
     return FoundPath;
 
   const char EnvPathSeparatorStr[] = {Separator, '\0'};
   SmallVector<StringRef, 8> Dirs;
-  SplitString(*OptPath, Dirs, EnvPathSeparatorStr);
+  SplitString(OptPath.getValue(), Dirs, EnvPathSeparatorStr);
 
   for (StringRef Dir : Dirs) {
     if (Dir.empty())

diff  --git a/llvm/lib/Support/VirtualFileSystem.cpp b/llvm/lib/Support/VirtualFileSystem.cpp
index 9f6ad7e7ca097..9c6a0c071755d 100644
--- a/llvm/lib/Support/VirtualFileSystem.cpp
+++ b/llvm/lib/Support/VirtualFileSystem.cpp
@@ -2667,15 +2667,15 @@ void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
 
   OS << "{\n"
         "  'version': 0,\n";
-  if (IsCaseSensitive)
-    OS << "  'case-sensitive': '" << (*IsCaseSensitive ? "true" : "false")
-       << "',\n";
-  if (UseExternalNames)
-    OS << "  'use-external-names': '" << (*UseExternalNames ? "true" : "false")
-       << "',\n";
+  if (IsCaseSensitive.hasValue())
+    OS << "  'case-sensitive': '"
+       << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
+  if (UseExternalNames.hasValue())
+    OS << "  'use-external-names': '"
+       << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
   bool UseOverlayRelative = false;
-  if (IsOverlayRelative) {
-    UseOverlayRelative = *IsOverlayRelative;
+  if (IsOverlayRelative.hasValue()) {
+    UseOverlayRelative = IsOverlayRelative.getValue();
     OS << "  'overlay-relative': '" << (UseOverlayRelative ? "true" : "false")
        << "',\n";
   }

diff  --git a/llvm/lib/Support/raw_ostream.cpp b/llvm/lib/Support/raw_ostream.cpp
index 0c83259fbff33..7648dac005986 100644
--- a/llvm/lib/Support/raw_ostream.cpp
+++ b/llvm/lib/Support/raw_ostream.cpp
@@ -428,8 +428,8 @@ raw_ostream &raw_ostream::operator<<(const FormattedBytes &FB) {
   while (!Bytes.empty()) {
     indent(FB.IndentLevel);
 
-    if (FB.FirstByteOffset) {
-      uint64_t Offset = *FB.FirstByteOffset;
+    if (FB.FirstByteOffset.hasValue()) {
+      uint64_t Offset = FB.FirstByteOffset.getValue();
       llvm::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth);
       *this << ": ";
     }

diff  --git a/llvm/lib/TableGen/Record.cpp b/llvm/lib/TableGen/Record.cpp
index 64f0953324717..e100251fbfcd5 100644
--- a/llvm/lib/TableGen/Record.cpp
+++ b/llvm/lib/TableGen/Record.cpp
@@ -2598,10 +2598,10 @@ Init *Record::getValueInit(StringRef FieldName) const {
 
 StringRef Record::getValueAsString(StringRef FieldName) const {
   llvm::Optional<StringRef> S = getValueAsOptionalString(FieldName);
-  if (!S)
+  if (!S.hasValue())
     PrintFatalError(getLoc(), "Record `" + getName() +
       "' does not have a field named `" + FieldName + "'!\n");
-  return *S;
+  return S.getValue();
 }
 
 llvm::Optional<StringRef>

diff  --git a/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp b/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp
index 4e2dfc6407a55..76a39d011569b 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp
@@ -1171,8 +1171,8 @@ bool AMDGPUInstructionSelector::selectBallot(MachineInstr &I) const {
   Optional<ValueAndVReg> Arg =
       getIConstantVRegValWithLookThrough(I.getOperand(2).getReg(), *MRI);
 
-  if (Arg) {
-    const int64_t Value = Arg->Value.getSExtValue();
+  if (Arg.hasValue()) {
+    const int64_t Value = Arg.getValue().Value.getSExtValue();
     if (Value == 0) {
       unsigned Opcode = Is64 ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
       BuildMI(*BB, &I, DL, TII.get(Opcode), DstReg).addImm(0);
@@ -4201,8 +4201,8 @@ AMDGPUInstructionSelector::selectMUBUFScratchOffen(MachineOperand &Root) const {
              MIB.addReg(Info->getScratchRSrcReg());
            },
            [=](MachineInstrBuilder &MIB) { // vaddr
-             if (FI)
-               MIB.addFrameIndex(*FI);
+             if (FI.hasValue())
+               MIB.addFrameIndex(FI.getValue());
              else
                MIB.addReg(VAddr);
            },

diff  --git a/llvm/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.h b/llvm/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.h
index 2572b042b5d16..1b513c4563077 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.h
+++ b/llvm/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.h
@@ -131,8 +131,8 @@ class AMDGPUMachineModuleInfo final : public MachineModuleInfoELF {
     bool IsAOneAddressSpace = isOneAddressSpace(A);
     bool IsBOneAddressSpace = isOneAddressSpace(B);
 
-    return *AIO >= *BIO &&
-           (IsAOneAddressSpace == IsBOneAddressSpace || !IsAOneAddressSpace);
+    return AIO.getValue() >= BIO.getValue() &&
+        (IsAOneAddressSpace == IsBOneAddressSpace || !IsAOneAddressSpace);
   }
 };
 

diff  --git a/llvm/lib/Target/AMDGPU/SIMemoryLegalizer.cpp b/llvm/lib/Target/AMDGPU/SIMemoryLegalizer.cpp
index 19989a3b99dfc..8a66213931ffb 100644
--- a/llvm/lib/Target/AMDGPU/SIMemoryLegalizer.cpp
+++ b/llvm/lib/Target/AMDGPU/SIMemoryLegalizer.cpp
@@ -2329,13 +2329,13 @@ bool SIMemoryLegalizer::runOnMachineFunction(MachineFunction &MF) {
         continue;
 
       if (const auto &MOI = MOA.getLoadInfo(MI))
-        Changed |= expandLoad(*MOI, MI);
+        Changed |= expandLoad(MOI.getValue(), MI);
       else if (const auto &MOI = MOA.getStoreInfo(MI))
-        Changed |= expandStore(*MOI, MI);
+        Changed |= expandStore(MOI.getValue(), MI);
       else if (const auto &MOI = MOA.getAtomicFenceInfo(MI))
-        Changed |= expandAtomicFence(*MOI, MI);
+        Changed |= expandAtomicFence(MOI.getValue(), MI);
       else if (const auto &MOI = MOA.getAtomicCmpxchgOrRmwInfo(MI))
-        Changed |= expandAtomicCmpxchgOrRmw(*MOI, MI);
+        Changed |= expandAtomicCmpxchgOrRmw(MOI.getValue(), MI);
     }
   }
 

diff  --git a/llvm/lib/Target/ARM/MVEGatherScatterLowering.cpp b/llvm/lib/Target/ARM/MVEGatherScatterLowering.cpp
index 310d3ede3f7a1..30785340ef129 100644
--- a/llvm/lib/Target/ARM/MVEGatherScatterLowering.cpp
+++ b/llvm/lib/Target/ARM/MVEGatherScatterLowering.cpp
@@ -351,13 +351,13 @@ Optional<int64_t> MVEGatherScatterLowering::getIfConst(const Value *V) {
     if (!Op0 || !Op1)
       return Optional<int64_t>{};
     if (I->getOpcode() == Instruction::Add)
-      return Optional<int64_t>{*Op0 + *Op1};
+      return Optional<int64_t>{Op0.getValue() + Op1.getValue()};
     if (I->getOpcode() == Instruction::Mul)
-      return Optional<int64_t>{*Op0 * *Op1};
+      return Optional<int64_t>{Op0.getValue() * Op1.getValue()};
     if (I->getOpcode() == Instruction::Shl)
-      return Optional<int64_t>{*Op0 << *Op1};
+      return Optional<int64_t>{Op0.getValue() << Op1.getValue()};
     if (I->getOpcode() == Instruction::Or)
-      return Optional<int64_t>{*Op0 | *Op1};
+      return Optional<int64_t>{Op0.getValue() | Op1.getValue()};
   }
   return Optional<int64_t>{};
 }

diff  --git a/llvm/lib/Target/Hexagon/HexagonFrameLowering.cpp b/llvm/lib/Target/Hexagon/HexagonFrameLowering.cpp
index 9641791552f24..56d471af8e208 100644
--- a/llvm/lib/Target/Hexagon/HexagonFrameLowering.cpp
+++ b/llvm/lib/Target/Hexagon/HexagonFrameLowering.cpp
@@ -1021,9 +1021,11 @@ findCFILocation(MachineBasicBlock &B) {
 }
 
 void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
-  for (auto &B : MF)
-    if (auto At = findCFILocation(B))
-      insertCFIInstructionsAt(B, *At);
+  for (auto &B : MF) {
+    auto At = findCFILocation(B);
+    if (At.hasValue())
+      insertCFIInstructionsAt(B, At.getValue());
+  }
 }
 
 void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,

diff  --git a/llvm/lib/Target/Lanai/AsmParser/LanaiAsmParser.cpp b/llvm/lib/Target/Lanai/AsmParser/LanaiAsmParser.cpp
index 5ef28cc006e5d..660215ca74353 100644
--- a/llvm/lib/Target/Lanai/AsmParser/LanaiAsmParser.cpp
+++ b/llvm/lib/Target/Lanai/AsmParser/LanaiAsmParser.cpp
@@ -704,15 +704,15 @@ LanaiAsmParser::parseRegister(bool RestoreOnFailure) {
   if (Lexer.getKind() == AsmToken::Identifier) {
     RegNum = MatchRegisterName(Lexer.getTok().getIdentifier());
     if (RegNum == 0) {
-      if (PercentTok && RestoreOnFailure)
-        Lexer.UnLex(*PercentTok);
+      if (PercentTok.hasValue() && RestoreOnFailure)
+        Lexer.UnLex(PercentTok.getValue());
       return nullptr;
     }
     Parser.Lex(); // Eat identifier token
     return LanaiOperand::createReg(RegNum, Start, End);
   }
-  if (PercentTok && RestoreOnFailure)
-    Lexer.UnLex(*PercentTok);
+  if (PercentTok.hasValue() && RestoreOnFailure)
+    Lexer.UnLex(PercentTok.getValue());
   return nullptr;
 }
 

diff  --git a/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp b/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp
index 312ab0a37fb7b..e52b49e3e8322 100644
--- a/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp
+++ b/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp
@@ -1860,8 +1860,8 @@ SDValue NVPTXTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
     Chain = Ret.getValue(1);
     InFlag = Ret.getValue(2);
 
-    if (ProxyRegTruncates[i]) {
-      Ret = DAG.getNode(ISD::TRUNCATE, dl, *ProxyRegTruncates[i], Ret);
+    if (ProxyRegTruncates[i].hasValue()) {
+      Ret = DAG.getNode(ISD::TRUNCATE, dl, ProxyRegTruncates[i].getValue(), Ret);
     }
 
     InVals.push_back(Ret);

diff  --git a/llvm/lib/Target/PowerPC/PPCMacroFusion.cpp b/llvm/lib/Target/PowerPC/PPCMacroFusion.cpp
index 58b74c6b8c7ab..caf14576fd446 100644
--- a/llvm/lib/Target/PowerPC/PPCMacroFusion.cpp
+++ b/llvm/lib/Target/PowerPC/PPCMacroFusion.cpp
@@ -267,13 +267,13 @@ static bool shouldScheduleAdjacent(const TargetInstrInfo &TII,
         continue;
 
       auto DepOpIdx = Feature.depOpIdx();
-      if (DepOpIdx) {
+      if (DepOpIdx.hasValue()) {
         // Checking if the result of the FirstMI is the desired operand of the
         // SecondMI if the DepOpIdx is set. Otherwise, ignore it.
         if (!matchingRegOps(*FirstMI, 0, SecondMI, *DepOpIdx))
           return false;
       }
-
+  
       // Checking more on the instruction operands.
       if (checkOpConstraints(Feature.getKind(), *FirstMI, SecondMI))
         return true;

diff  --git a/llvm/lib/Target/PowerPC/PPCTargetMachine.cpp b/llvm/lib/Target/PowerPC/PPCTargetMachine.cpp
index fe396cbfc011d..dd7a9fe917c7b 100644
--- a/llvm/lib/Target/PowerPC/PPCTargetMachine.cpp
+++ b/llvm/lib/Target/PowerPC/PPCTargetMachine.cpp
@@ -246,10 +246,10 @@ static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
 
 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
                                            Optional<Reloc::Model> RM) {
-  assert((!TT.isOSAIX() || !RM || *RM == Reloc::PIC_) &&
+  assert((!TT.isOSAIX() || !RM.hasValue() || *RM == Reloc::PIC_) &&
          "Invalid relocation model for AIX.");
 
-  if (RM)
+  if (RM.hasValue())
     return *RM;
 
   // Big Endian PPC and AIX default to PIC.

diff  --git a/llvm/lib/Target/VE/VVPISelLowering.cpp b/llvm/lib/Target/VE/VVPISelLowering.cpp
index e4c35dafff565..cd67a0fb40f26 100644
--- a/llvm/lib/Target/VE/VVPISelLowering.cpp
+++ b/llvm/lib/Target/VE/VVPISelLowering.cpp
@@ -39,9 +39,9 @@ SDValue VETargetLowering::lowerToVVP(SDValue Op, SelectionDAG &DAG) const {
   // Can we represent this as a VVP node.
   const unsigned Opcode = Op->getOpcode();
   auto VVPOpcodeOpt = getVVPOpcode(Opcode);
-  if (!VVPOpcodeOpt)
+  if (!VVPOpcodeOpt.hasValue())
     return SDValue();
-  unsigned VVPOpcode = *VVPOpcodeOpt;
+  unsigned VVPOpcode = VVPOpcodeOpt.getValue();
   const bool FromVP = ISD::isVPOpcode(Opcode);
 
   // The representative and legalized vector type of this operation.

diff  --git a/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.cpp b/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.cpp
index abc6115c0453b..61097e115a1c4 100644
--- a/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.cpp
+++ b/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.cpp
@@ -86,15 +86,18 @@ bool WebAssemblyAsmTypeCheck::popType(SMLoc ErrorLoc,
                                       Optional<wasm::ValType> EVT) {
   if (Stack.empty()) {
     return typeError(ErrorLoc,
-                     EVT ? StringRef("empty stack while popping ") +
-                               WebAssembly::typeToString(*EVT)
-                         : StringRef("empty stack while popping value"));
+                      EVT.hasValue()
+                          ? StringRef("empty stack while popping ") +
+                                WebAssembly::typeToString(EVT.getValue())
+                          : StringRef(
+                                    "empty stack while popping value"));
   }
   auto PVT = Stack.pop_back_val();
-  if (EVT && *EVT != PVT) {
-    return typeError(ErrorLoc,
-                     StringRef("popped ") + WebAssembly::typeToString(PVT) +
-                         ", expected " + WebAssembly::typeToString(*EVT));
+  if (EVT.hasValue() && EVT.getValue() != PVT) {
+    return typeError(
+        ErrorLoc, StringRef("popped ") + WebAssembly::typeToString(PVT) +
+                                    ", expected " +
+                                    WebAssembly::typeToString(EVT.getValue()));
   }
   return false;
 }

diff  --git a/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp b/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp
index 65aa709bb349a..f09758a0d1033 100644
--- a/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp
+++ b/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp
@@ -552,8 +552,8 @@ Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallBase *CI) {
     Optional<unsigned> NEltArg;
     std::tie(SizeArg, NEltArg) = FnAttrs.getAllocSizeArgs();
     SizeArg += 1;
-    if (NEltArg)
-      NEltArg = *NEltArg + 1;
+    if (NEltArg.hasValue())
+      NEltArg = NEltArg.getValue() + 1;
     FnAttrs.addAllocSizeAttr(SizeArg, NEltArg);
   }
   // In case the callee has 'noreturn' attribute, We need to remove it, because

diff  --git a/llvm/lib/Transforms/IPO/Attributor.cpp b/llvm/lib/Transforms/IPO/Attributor.cpp
index 284b9b34d76cb..769d79b97517a 100644
--- a/llvm/lib/Transforms/IPO/Attributor.cpp
+++ b/llvm/lib/Transforms/IPO/Attributor.cpp
@@ -297,11 +297,11 @@ AA::combineOptionalValuesInAAValueLatice(const Optional<Value *> &A,
                                          const Optional<Value *> &B, Type *Ty) {
   if (A == B)
     return A;
-  if (!B)
+  if (!B.hasValue())
     return A;
   if (*B == nullptr)
     return nullptr;
-  if (!A)
+  if (!A.hasValue())
     return Ty ? getWithType(**B, *Ty) : nullptr;
   if (*A == nullptr)
     return nullptr;
@@ -718,8 +718,8 @@ Argument *IRPosition::getAssociatedArgument() const {
   }
 
   // If we found a unique callback candidate argument, return it.
-  if (CBCandidateArg && *CBCandidateArg)
-    return *CBCandidateArg;
+  if (CBCandidateArg.hasValue() && CBCandidateArg.getValue())
+    return CBCandidateArg.getValue();
 
   // If no callbacks were found, or none used the underlying call site operand
   // exclusively, use the direct callee argument if available.
@@ -1048,11 +1048,11 @@ Attributor::getAssumedConstant(const IRPosition &IRP,
     recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL);
     return llvm::None;
   }
-  if (isa_and_nonnull<UndefValue>(*SimplifiedV)) {
+  if (isa_and_nonnull<UndefValue>(SimplifiedV.getValue())) {
     recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL);
     return UndefValue::get(IRP.getAssociatedType());
   }
-  Constant *CI = dyn_cast_or_null<Constant>(*SimplifiedV);
+  Constant *CI = dyn_cast_or_null<Constant>(SimplifiedV.getValue());
   if (CI)
     CI = dyn_cast_or_null<Constant>(
         AA::getWithType(*CI, *IRP.getAssociatedType()));
@@ -2695,10 +2695,10 @@ void InformationCache::initializeInformationCache(const Function &CF,
     while (!Worklist.empty()) {
       const Instruction *I = Worklist.pop_back_val();
       Optional<short> &NumUses = AssumeUsesMap[I];
-      if (!NumUses)
+      if (!NumUses.hasValue())
         NumUses = I->getNumUses();
-      NumUses = *NumUses - /* this assume */ 1;
-      if (*NumUses != 0)
+      NumUses = NumUses.getValue() - /* this assume */ 1;
+      if (NumUses.getValue() != 0)
         continue;
       AssumeOnlyValues.insert(I);
       for (const Value *Op : I->operands())

diff  --git a/llvm/lib/Transforms/IPO/AttributorAttributes.cpp b/llvm/lib/Transforms/IPO/AttributorAttributes.cpp
index 5483e42b5fbc2..b36c712cdd6c8 100644
--- a/llvm/lib/Transforms/IPO/AttributorAttributes.cpp
+++ b/llvm/lib/Transforms/IPO/AttributorAttributes.cpp
@@ -395,9 +395,9 @@ static bool genericValueTraversal(
     if (UseValueSimplify && !isa<Constant>(V)) {
       Optional<Value *> SimpleV =
           A.getAssumedSimplified(*V, QueryingAA, UsedAssumedInformation);
-      if (!SimpleV)
+      if (!SimpleV.hasValue())
         continue;
-      Value *NewV = *SimpleV;
+      Value *NewV = SimpleV.getValue();
       if (NewV && NewV != V) {
         if ((VS & AA::Interprocedural) || !CtxI ||
             AA::isValidInScope(*NewV, CtxI->getFunction())) {
@@ -1851,14 +1851,14 @@ ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) {
   // Check if we have an assumed unique return value that we could manifest.
   Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A);
 
-  if (!UniqueRV || !*UniqueRV)
+  if (!UniqueRV.hasValue() || !UniqueRV.getValue())
     return Changed;
 
   // Bookkeeping.
   STATS_DECLTRACK(UniqueReturnValue, FunctionReturn,
                   "Number of function with unique return");
   // If the assumed unique return value is an argument, annotate it.
-  if (auto *UniqueRVArg = dyn_cast<Argument>(*UniqueRV)) {
+  if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) {
     if (UniqueRVArg->getType()->canLosslesslyBitCastTo(
             getAssociatedFunction()->getReturnType())) {
       getIRPosition() = IRPosition::argument(*UniqueRVArg);
@@ -2626,9 +2626,9 @@ struct AAUndefinedBehaviorImpl : public AAUndefinedBehavior {
       // Either we stopped and the appropriate action was taken,
       // or we got back a simplified value to continue.
       Optional<Value *> SimplifiedPtrOp = stopOnUndefOrAssumed(A, PtrOp, &I);
-      if (!SimplifiedPtrOp || !*SimplifiedPtrOp)
+      if (!SimplifiedPtrOp.hasValue() || !SimplifiedPtrOp.getValue())
         return true;
-      const Value *PtrOpVal = *SimplifiedPtrOp;
+      const Value *PtrOpVal = SimplifiedPtrOp.getValue();
 
       // A memory access through a pointer is considered UB
       // only if the pointer has constant null value.
@@ -2717,14 +2717,15 @@ struct AAUndefinedBehaviorImpl : public AAUndefinedBehavior {
             IRPosition::value(*ArgVal), *this, UsedAssumedInformation);
         if (UsedAssumedInformation)
           continue;
-        if (SimplifiedVal && !*SimplifiedVal)
+        if (SimplifiedVal.hasValue() && !SimplifiedVal.getValue())
           return true;
-        if (!SimplifiedVal || isa<UndefValue>(**SimplifiedVal)) {
+        if (!SimplifiedVal.hasValue() ||
+            isa<UndefValue>(*SimplifiedVal.getValue())) {
           KnownUBInsts.insert(&I);
           continue;
         }
         if (!ArgVal->getType()->isPointerTy() ||
-            !isa<ConstantPointerNull>(**SimplifiedVal))
+            !isa<ConstantPointerNull>(*SimplifiedVal.getValue()))
           continue;
         auto &NonNullAA =
             A.getAAFor<AANonNull>(*this, CalleeArgumentIRP, DepClassTy::NONE);
@@ -4061,11 +4062,11 @@ identifyAliveSuccessors(Attributor &A, const SwitchInst &SI,
   bool UsedAssumedInformation = false;
   Optional<Constant *> C =
       A.getAssumedConstant(*SI.getCondition(), AA, UsedAssumedInformation);
-  if (!C || isa_and_nonnull<UndefValue>(*C)) {
+  if (!C.hasValue() || isa_and_nonnull<UndefValue>(C.getValue())) {
     // No value yet, assume all edges are dead.
-  } else if (isa_and_nonnull<ConstantInt>(*C)) {
+  } else if (isa_and_nonnull<ConstantInt>(C.getValue())) {
     for (auto &CaseIt : SI.cases()) {
-      if (CaseIt.getCaseValue() == *C) {
+      if (CaseIt.getCaseValue() == C.getValue()) {
         AliveSuccessors.push_back(&CaseIt.getCaseSuccessor()->front());
         return UsedAssumedInformation;
       }
@@ -5480,11 +5481,11 @@ struct AAValueSimplifyImpl : AAValueSimplify {
     bool UsedAssumedInformation = false;
     Optional<Value *> SimpleV =
         A.getAssumedSimplified(V, QueryingAA, UsedAssumedInformation);
-    if (!SimpleV)
+    if (!SimpleV.hasValue())
       return PoisonValue::get(&Ty);
     Value *EffectiveV = &V;
-    if (*SimpleV)
-      EffectiveV = *SimpleV;
+    if (SimpleV.getValue())
+      EffectiveV = SimpleV.getValue();
     if (auto *C = dyn_cast<Constant>(EffectiveV))
       if (!C->canTrap())
         return C;
@@ -5500,8 +5501,8 @@ struct AAValueSimplifyImpl : AAValueSimplify {
   /// Return a value we can use as replacement for the associated one, or
   /// nullptr if we don't have one that makes sense.
   Value *manifestReplacementValue(Attributor &A, Instruction *CtxI) const {
-    Value *NewV = SimplifiedAssociatedValue
-                      ? *SimplifiedAssociatedValue
+    Value *NewV = SimplifiedAssociatedValue.hasValue()
+                      ? SimplifiedAssociatedValue.getValue()
                       : UndefValue::get(getAssociatedType());
     if (NewV && NewV != &getAssociatedValue()) {
       ValueToValueMapTy VMap;
@@ -5630,9 +5631,9 @@ struct AAValueSimplifyArgument final : AAValueSimplifyImpl {
       bool UsedAssumedInformation = false;
       Optional<Constant *> SimpleArgOp =
           A.getAssumedConstant(ACSArgPos, *this, UsedAssumedInformation);
-      if (!SimpleArgOp)
+      if (!SimpleArgOp.hasValue())
         return true;
-      if (!*SimpleArgOp)
+      if (!SimpleArgOp.getValue())
         return false;
       if (!AA::isDynamicallyUnique(A, *this, **SimpleArgOp))
         return false;
@@ -5745,18 +5746,18 @@ struct AAValueSimplifyFloating : AAValueSimplifyImpl {
     const auto &SimplifiedLHS =
         A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()),
                                *this, UsedAssumedInformation);
-    if (!SimplifiedLHS)
+    if (!SimplifiedLHS.hasValue())
       return true;
-    if (!*SimplifiedLHS)
+    if (!SimplifiedLHS.getValue())
       return false;
     LHS = *SimplifiedLHS;
 
     const auto &SimplifiedRHS =
         A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()),
                                *this, UsedAssumedInformation);
-    if (!SimplifiedRHS)
+    if (!SimplifiedRHS.hasValue())
       return true;
-    if (!*SimplifiedRHS)
+    if (!SimplifiedRHS.getValue())
       return false;
     RHS = *SimplifiedRHS;
 
@@ -5825,11 +5826,11 @@ struct AAValueSimplifyFloating : AAValueSimplifyImpl {
                                  *this, UsedAssumedInformation);
       // If we are not sure about any operand we are not sure about the entire
       // instruction, we'll wait.
-      if (!SimplifiedOp)
+      if (!SimplifiedOp.hasValue())
         return true;
 
-      if (*SimplifiedOp)
-        NewOps[Idx] = *SimplifiedOp;
+      if (SimplifiedOp.getValue())
+        NewOps[Idx] = SimplifiedOp.getValue();
       else
         NewOps[Idx] = Op;
 
@@ -6248,10 +6249,11 @@ struct AAHeapToStackFunction final : public AAHeapToStack {
         Alignment = std::max(Alignment, *RetAlign);
       if (Value *Align = getAllocAlignment(AI.CB, TLI)) {
         Optional<APInt> AlignmentAPI = getAPInt(A, *this, *Align);
-        assert(AlignmentAPI && AlignmentAPI->getZExtValue() > 0 &&
+        assert(AlignmentAPI.hasValue() &&
+               AlignmentAPI.getValue().getZExtValue() > 0 &&
                "Expected an alignment during manifest!");
-        Alignment =
-            std::max(Alignment, assumeAligned(AlignmentAPI->getZExtValue()));
+        Alignment = std::max(
+            Alignment, assumeAligned(AlignmentAPI.getValue().getZExtValue()));
       }
 
       // TODO: Hoist the alloca towards the function entry.
@@ -6297,9 +6299,9 @@ struct AAHeapToStackFunction final : public AAHeapToStack {
     bool UsedAssumedInformation = false;
     Optional<Constant *> SimpleV =
         A.getAssumedConstant(V, AA, UsedAssumedInformation);
-    if (!SimpleV)
+    if (!SimpleV.hasValue())
       return APInt(64, 0);
-    if (auto *CI = dyn_cast_or_null<ConstantInt>(*SimpleV))
+    if (auto *CI = dyn_cast_or_null<ConstantInt>(SimpleV.getValue()))
       return CI->getValue();
     return llvm::None;
   }
@@ -6576,9 +6578,9 @@ ChangeStatus AAHeapToStackFunction::updateImpl(Attributor &A) {
 
     if (MaxHeapToStackSize != -1) {
       Optional<APInt> Size = getSize(A, *this, AI);
-      if (!Size || Size->ugt(MaxHeapToStackSize)) {
+      if (!Size.hasValue() || Size.getValue().ugt(MaxHeapToStackSize)) {
         LLVM_DEBUG({
-          if (!Size)
+          if (!Size.hasValue())
             dbgs() << "[H2S] Unknown allocation size: " << *AI.CB << "\n";
           else
             dbgs() << "[H2S] Allocation size too large: " << *AI.CB << " vs. "
@@ -6631,9 +6633,9 @@ struct AAPrivatizablePtrImpl : public AAPrivatizablePtr {
   /// Return a privatizable type that encloses both T0 and T1.
   /// TODO: This is merely a stub for now as we should manage a mapping as well.
   Optional<Type *> combineTypes(Optional<Type *> T0, Optional<Type *> T1) {
-    if (!T0)
+    if (!T0.hasValue())
       return T1;
-    if (!T1)
+    if (!T1.hasValue())
       return T0;
     if (T0 == T1)
       return T0;
@@ -6693,9 +6695,9 @@ struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
 
       LLVM_DEBUG({
         dbgs() << "[AAPrivatizablePtr] ACSPos: " << ACSArgPos << ", CSTy: ";
-        if (CSTy && *CSTy)
-          CSTy.value()->print(dbgs());
-        else if (CSTy)
+        if (CSTy.hasValue() && CSTy.getValue())
+          CSTy.getValue()->print(dbgs());
+        else if (CSTy.hasValue())
           dbgs() << "<nullptr>";
         else
           dbgs() << "<none>";
@@ -6705,16 +6707,16 @@ struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
 
       LLVM_DEBUG({
         dbgs() << " : New Type: ";
-        if (Ty && *Ty)
-          (*Ty)->print(dbgs());
-        else if (Ty)
+        if (Ty.hasValue() && Ty.getValue())
+          Ty.getValue()->print(dbgs());
+        else if (Ty.hasValue())
           dbgs() << "<nullptr>";
         else
           dbgs() << "<none>";
         dbgs() << "\n";
       });
 
-      return !Ty || *Ty;
+      return !Ty.hasValue() || Ty.getValue();
     };
 
     if (!A.checkForAllCallSites(CallSiteCheck, *this, true,
@@ -6726,9 +6728,9 @@ struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
   /// See AbstractAttribute::updateImpl(...).
   ChangeStatus updateImpl(Attributor &A) override {
     PrivatizableType = identifyPrivatizableType(A);
-    if (!PrivatizableType)
+    if (!PrivatizableType.hasValue())
       return ChangeStatus::UNCHANGED;
-    if (!*PrivatizableType)
+    if (!PrivatizableType.getValue())
       return indicatePessimisticFixpoint();
 
     // The dependence is optional so we don't give up once we give up on the
@@ -6815,9 +6817,9 @@ struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
               *this, IRPosition::argument(CBArg), DepClassTy::REQUIRED);
           if (CBArgPrivAA.isValidState()) {
             auto CBArgPrivTy = CBArgPrivAA.getPrivatizableType();
-            if (!CBArgPrivTy)
+            if (!CBArgPrivTy.hasValue())
               continue;
-            if (*CBArgPrivTy == PrivatizableType)
+            if (CBArgPrivTy.getValue() == PrivatizableType)
               continue;
           }
 
@@ -6862,9 +6864,9 @@ struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
             DepClassTy::REQUIRED);
         if (DCArgPrivAA.isValidState()) {
           auto DCArgPrivTy = DCArgPrivAA.getPrivatizableType();
-          if (!DCArgPrivTy)
+          if (!DCArgPrivTy.hasValue())
             return true;
-          if (*DCArgPrivTy == PrivatizableType)
+          if (DCArgPrivTy.getValue() == PrivatizableType)
             return true;
         }
       }
@@ -7004,9 +7006,9 @@ struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
 
   /// See AbstractAttribute::manifest(...)
   ChangeStatus manifest(Attributor &A) override {
-    if (!PrivatizableType)
+    if (!PrivatizableType.hasValue())
       return ChangeStatus::UNCHANGED;
-    assert(*PrivatizableType && "Expected privatizable type!");
+    assert(PrivatizableType.getValue() && "Expected privatizable type!");
 
     // Collect all tail calls in the function as we cannot allow new allocas to
     // escape into tail recursion.
@@ -7039,9 +7041,9 @@ struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
           Instruction *IP = &*EntryBB.getFirstInsertionPt();
           const DataLayout &DL = IP->getModule()->getDataLayout();
           unsigned AS = DL.getAllocaAddrSpace();
-          Instruction *AI = new AllocaInst(*PrivatizableType, AS,
+          Instruction *AI = new AllocaInst(PrivatizableType.getValue(), AS,
                                            Arg->getName() + ".priv", IP);
-          createInitialization(*PrivatizableType, *AI, ReplacementFn,
+          createInitialization(PrivatizableType.getValue(), *AI, ReplacementFn,
                                ArgIt->getArgNo(), *IP);
 
           if (AI->getType() != Arg->getType())
@@ -7147,9 +7149,9 @@ struct AAPrivatizablePtrCallSiteArgument final
   /// See AbstractAttribute::updateImpl(...).
   ChangeStatus updateImpl(Attributor &A) override {
     PrivatizableType = identifyPrivatizableType(A);
-    if (!PrivatizableType)
+    if (!PrivatizableType.hasValue())
       return ChangeStatus::UNCHANGED;
-    if (!*PrivatizableType)
+    if (!PrivatizableType.getValue())
       return indicatePessimisticFixpoint();
 
     const IRPosition &IRP = getIRPosition();
@@ -8608,18 +8610,18 @@ struct AAValueConstantRangeFloating : AAValueConstantRangeImpl {
     const auto &SimplifiedLHS =
         A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()),
                                *this, UsedAssumedInformation);
-    if (!SimplifiedLHS)
+    if (!SimplifiedLHS.hasValue())
       return true;
-    if (!*SimplifiedLHS)
+    if (!SimplifiedLHS.getValue())
       return false;
     LHS = *SimplifiedLHS;
 
     const auto &SimplifiedRHS =
         A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()),
                                *this, UsedAssumedInformation);
-    if (!SimplifiedRHS)
+    if (!SimplifiedRHS.hasValue())
       return true;
-    if (!*SimplifiedRHS)
+    if (!SimplifiedRHS.getValue())
       return false;
     RHS = *SimplifiedRHS;
 
@@ -8661,9 +8663,9 @@ struct AAValueConstantRangeFloating : AAValueConstantRangeImpl {
     const auto &SimplifiedOpV =
         A.getAssumedSimplified(IRPosition::value(*OpV, getCallBaseContext()),
                                *this, UsedAssumedInformation);
-    if (!SimplifiedOpV)
+    if (!SimplifiedOpV.hasValue())
       return true;
-    if (!*SimplifiedOpV)
+    if (!SimplifiedOpV.getValue())
       return false;
     OpV = *SimplifiedOpV;
 
@@ -8691,18 +8693,18 @@ struct AAValueConstantRangeFloating : AAValueConstantRangeImpl {
     const auto &SimplifiedLHS =
         A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()),
                                *this, UsedAssumedInformation);
-    if (!SimplifiedLHS)
+    if (!SimplifiedLHS.hasValue())
       return true;
-    if (!*SimplifiedLHS)
+    if (!SimplifiedLHS.getValue())
       return false;
     LHS = *SimplifiedLHS;
 
     const auto &SimplifiedRHS =
         A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()),
                                *this, UsedAssumedInformation);
-    if (!SimplifiedRHS)
+    if (!SimplifiedRHS.hasValue())
       return true;
-    if (!*SimplifiedRHS)
+    if (!SimplifiedRHS.getValue())
       return false;
     RHS = *SimplifiedRHS;
 
@@ -8765,9 +8767,9 @@ struct AAValueConstantRangeFloating : AAValueConstantRangeImpl {
         const auto &SimplifiedOpV =
             A.getAssumedSimplified(IRPosition::value(V, getCallBaseContext()),
                                    *this, UsedAssumedInformation);
-        if (!SimplifiedOpV)
+        if (!SimplifiedOpV.hasValue())
           return true;
-        if (!*SimplifiedOpV)
+        if (!SimplifiedOpV.getValue())
           return false;
         Value *VPtr = *SimplifiedOpV;
 
@@ -9126,18 +9128,18 @@ struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl {
     const auto &SimplifiedLHS =
         A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()),
                                *this, UsedAssumedInformation);
-    if (!SimplifiedLHS)
+    if (!SimplifiedLHS.hasValue())
       return ChangeStatus::UNCHANGED;
-    if (!*SimplifiedLHS)
+    if (!SimplifiedLHS.getValue())
       return indicatePessimisticFixpoint();
     LHS = *SimplifiedLHS;
 
     const auto &SimplifiedRHS =
         A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()),
                                *this, UsedAssumedInformation);
-    if (!SimplifiedRHS)
+    if (!SimplifiedRHS.hasValue())
       return ChangeStatus::UNCHANGED;
-    if (!*SimplifiedRHS)
+    if (!SimplifiedRHS.getValue())
       return indicatePessimisticFixpoint();
     RHS = *SimplifiedRHS;
 
@@ -9209,18 +9211,18 @@ struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl {
     const auto &SimplifiedLHS =
         A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()),
                                *this, UsedAssumedInformation);
-    if (!SimplifiedLHS)
+    if (!SimplifiedLHS.hasValue())
       return ChangeStatus::UNCHANGED;
-    if (!*SimplifiedLHS)
+    if (!SimplifiedLHS.getValue())
       return indicatePessimisticFixpoint();
     LHS = *SimplifiedLHS;
 
     const auto &SimplifiedRHS =
         A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()),
                                *this, UsedAssumedInformation);
-    if (!SimplifiedRHS)
+    if (!SimplifiedRHS.hasValue())
       return ChangeStatus::UNCHANGED;
-    if (!*SimplifiedRHS)
+    if (!SimplifiedRHS.getValue())
       return indicatePessimisticFixpoint();
     RHS = *SimplifiedRHS;
 
@@ -9232,9 +9234,9 @@ struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl {
 
     // Check if we only need one operand.
     bool OnlyLeft = false, OnlyRight = false;
-    if (C && *C && (*C)->isOneValue())
+    if (C.hasValue() && *C && (*C)->isOneValue())
       OnlyLeft = true;
-    else if (C && *C && (*C)->isZeroValue())
+    else if (C.hasValue() && *C && (*C)->isZeroValue())
       OnlyRight = true;
 
     const AAPotentialConstantValues *LHSAA = nullptr, *RHSAA = nullptr;
@@ -9284,9 +9286,9 @@ struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl {
     const auto &SimplifiedSrc =
         A.getAssumedSimplified(IRPosition::value(*Src, getCallBaseContext()),
                                *this, UsedAssumedInformation);
-    if (!SimplifiedSrc)
+    if (!SimplifiedSrc.hasValue())
       return ChangeStatus::UNCHANGED;
-    if (!*SimplifiedSrc)
+    if (!SimplifiedSrc.getValue())
       return indicatePessimisticFixpoint();
     Src = *SimplifiedSrc;
 
@@ -9317,18 +9319,18 @@ struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl {
     const auto &SimplifiedLHS =
         A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()),
                                *this, UsedAssumedInformation);
-    if (!SimplifiedLHS)
+    if (!SimplifiedLHS.hasValue())
       return ChangeStatus::UNCHANGED;
-    if (!*SimplifiedLHS)
+    if (!SimplifiedLHS.getValue())
       return indicatePessimisticFixpoint();
     LHS = *SimplifiedLHS;
 
     const auto &SimplifiedRHS =
         A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()),
                                *this, UsedAssumedInformation);
-    if (!SimplifiedRHS)
+    if (!SimplifiedRHS.hasValue())
       return ChangeStatus::UNCHANGED;
-    if (!*SimplifiedRHS)
+    if (!SimplifiedRHS.getValue())
       return indicatePessimisticFixpoint();
     RHS = *SimplifiedRHS;
 
@@ -9385,9 +9387,9 @@ struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl {
       const auto &SimplifiedIncomingValue = A.getAssumedSimplified(
           IRPosition::value(*IncomingValue, getCallBaseContext()), *this,
           UsedAssumedInformation);
-      if (!SimplifiedIncomingValue)
+      if (!SimplifiedIncomingValue.hasValue())
         continue;
-      if (!*SimplifiedIncomingValue)
+      if (!SimplifiedIncomingValue.getValue())
         return indicatePessimisticFixpoint();
       IncomingValue = *SimplifiedIncomingValue;
 
@@ -9874,8 +9876,9 @@ struct AAFunctionReachabilityFunction : public AAFunctionReachability {
     bool isReachable(Attributor &A, AAFunctionReachability &AA,
                      ArrayRef<const AACallEdges *> AAEdgesList,
                      const Function &Fn) {
-      if (Optional<bool> Cached = isCachedReachable(Fn))
-        return *Cached;
+      Optional<bool> Cached = isCachedReachable(Fn);
+      if (Cached.hasValue())
+        return Cached.getValue();
 
       // The query was not cached, thus it is new. We need to request an update
       // explicitly to make sure this the information is properly run to a

diff  --git a/llvm/lib/Transforms/IPO/IROutliner.cpp b/llvm/lib/Transforms/IPO/IROutliner.cpp
index 9ed21deea6be5..89ae575603e56 100644
--- a/llvm/lib/Transforms/IPO/IROutliner.cpp
+++ b/llvm/lib/Transforms/IPO/IROutliner.cpp
@@ -554,8 +554,8 @@ collectRegionsConstants(OutlinableRegion &Region,
     // the the number has been found to be not the same value in each instance.
     for (Value *V : ID.OperVals) {
       Optional<unsigned> GVNOpt = C.getGVN(V);
-      assert(GVNOpt && "Expected a GVN for operand?");
-      unsigned GVN = *GVNOpt;
+      assert(GVNOpt.hasValue() && "Expected a GVN for operand?");
+      unsigned GVN = GVNOpt.getValue();
 
       // Check if this global value has been found to not be the same already.
       if (NotSame.contains(GVN)) {
@@ -569,8 +569,8 @@ collectRegionsConstants(OutlinableRegion &Region,
       // global value number.  If the global value does not map to a Constant,
       // it is considered to not be the same value.
       Optional<bool> ConstantMatches = constantMatches(V, GVN, GVNToConstant);
-      if (ConstantMatches) {
-        if (*ConstantMatches)
+      if (ConstantMatches.hasValue()) {
+        if (ConstantMatches.getValue())
           continue;
         else
           ConstantsTheSame = false;
@@ -650,8 +650,8 @@ Function *IROutliner::createFunction(Module &M, OutlinableGroup &Group,
       "outlined_ir_func_" + std::to_string(FunctionNameSuffix), M);
 
   // Transfer the swifterr attribute to the correct function parameter.
-  if (Group.SwiftErrorArgument)
-    Group.OutlinedFunction->addParamAttr(*Group.SwiftErrorArgument,
+  if (Group.SwiftErrorArgument.hasValue())
+    Group.OutlinedFunction->addParamAttr(Group.SwiftErrorArgument.getValue(),
                                          Attribute::SwiftError);
 
   Group.OutlinedFunction->addFnAttr(Attribute::OptimizeForSize);
@@ -808,8 +808,9 @@ static void mapInputsToGVNs(IRSimilarityCandidate &C,
     assert(Input && "Have a nullptr as an input");
     if (OutputMappings.find(Input) != OutputMappings.end())
       Input = OutputMappings.find(Input)->second;
-    assert(C.getGVN(Input) && "Could not find a numbering for the given input");
-    EndInputNumbers.push_back(*C.getGVN(Input));
+    assert(C.getGVN(Input).hasValue() &&
+           "Could not find a numbering for the given input");
+    EndInputNumbers.push_back(C.getGVN(Input).getValue());
   }
 }
 
@@ -947,12 +948,12 @@ findExtractedInputToOverallInputMapping(OutlinableRegion &Region,
   // numbering overrides any discovered location for the extracted code.
   for (unsigned InputVal : InputGVNs) {
     Optional<unsigned> CanonicalNumberOpt = C.getCanonicalNum(InputVal);
-    assert(CanonicalNumberOpt && "Canonical number not found?");
-    unsigned CanonicalNumber = *CanonicalNumberOpt;
+    assert(CanonicalNumberOpt.hasValue() && "Canonical number not found?");
+    unsigned CanonicalNumber = CanonicalNumberOpt.getValue();
 
     Optional<Value *> InputOpt = C.fromGVN(InputVal);
-    assert(InputOpt && "Global value number not found?");
-    Value *Input = *InputOpt;
+    assert(InputOpt.hasValue() && "Global value number not found?");
+    Value *Input = InputOpt.getValue();
 
     DenseMap<unsigned, unsigned>::iterator AggArgIt =
         Group.CanonicalNumberToAggArg.find(CanonicalNumber);
@@ -1234,15 +1235,16 @@ static Optional<unsigned> getGVNForPHINode(OutlinableRegion &Region,
   DenseMap<hash_code, unsigned>::iterator GVNToPHIIt;
   DenseMap<unsigned, PHINodeData>::iterator PHIToGVNIt;
   Optional<unsigned> BBGVN = Cand.getGVN(PHIBB);
-  assert(BBGVN && "Could not find GVN for the incoming block!");
+  assert(BBGVN.hasValue() && "Could not find GVN for the incoming block!");
 
-  BBGVN = Cand.getCanonicalNum(*BBGVN);
-  assert(BBGVN && "Could not find canonical number for the incoming block!");
+  BBGVN = Cand.getCanonicalNum(BBGVN.getValue());
+  assert(BBGVN.hasValue() &&
+         "Could not find canonical number for the incoming block!");
   // Create a pair of the exit block canonical value, and the aggregate
   // argument location, connected to the canonical numbers stored in the
   // PHINode.
   PHINodeData TemporaryPair =
-      std::make_pair(std::make_pair(*BBGVN, AggArgIdx), PHIGVNs);
+      std::make_pair(std::make_pair(BBGVN.getValue(), AggArgIdx), PHIGVNs);
   hash_code PHINodeDataHash = encodePHINodeData(TemporaryPair);
 
   // Look for and create a new entry in our connection between canonical
@@ -1515,8 +1517,9 @@ CallInst *replaceCalledFunction(Module &M, OutlinableRegion &Region) {
 
   // Make sure that the argument in the new function has the SwiftError
   // argument.
-  if (Group.SwiftErrorArgument)
-    Call->addParamAttr(*Group.SwiftErrorArgument, Attribute::SwiftError);
+  if (Group.SwiftErrorArgument.hasValue())
+    Call->addParamAttr(Group.SwiftErrorArgument.getValue(),
+                       Attribute::SwiftError);
 
   return Call;
 }
@@ -1647,9 +1650,9 @@ static void findCanonNumsForPHI(
 
     // Find and add the canonical number for the incoming value.
     Optional<unsigned> GVN = Region.Candidate->getGVN(IVal);
-    assert(GVN && "No GVN for incoming value");
+    assert(GVN.hasValue() && "No GVN for incoming value");
     Optional<unsigned> CanonNum = Region.Candidate->getCanonicalNum(*GVN);
-    assert(CanonNum && "No Canonical Number for GVN");
+    assert(CanonNum.hasValue() && "No Canonical Number for GVN");
     CanonNums.push_back(std::make_pair(*CanonNum, IBlock));
   }
 }
@@ -2078,11 +2081,12 @@ static void alignOutputBlockWithAggFunc(
 
   // If there is, we remove the new output blocks.  If it does not,
   // we add it to our list of sets of output blocks.
-  if (MatchingBB) {
+  if (MatchingBB.hasValue()) {
     LLVM_DEBUG(dbgs() << "Set output block for region in function"
-                      << Region.ExtractedFunction << " to " << *MatchingBB);
+                      << Region.ExtractedFunction << " to "
+                      << MatchingBB.getValue());
 
-    Region.OutputBlockNum = *MatchingBB;
+    Region.OutputBlockNum = MatchingBB.getValue();
     for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs)
       VtoBB.second->eraseFromParent();
     return;
@@ -2500,9 +2504,9 @@ static Value *findOutputValueInRegion(OutlinableRegion &Region,
     OutputCanon = *It->second.second.begin();
   }
   Optional<unsigned> OGVN = Region.Candidate->fromCanonicalNum(OutputCanon);
-  assert(OGVN && "Could not find GVN for Canonical Number?");
+  assert(OGVN.hasValue() && "Could not find GVN for Canonical Number?");
   Optional<Value *> OV = Region.Candidate->fromGVN(*OGVN);
-  assert(OV && "Could not find value for GVN?");
+  assert(OV.hasValue() && "Could not find value for GVN?");
   return *OV;
 }
 
@@ -2677,14 +2681,15 @@ void IROutliner::updateOutputMapping(OutlinableRegion &Region,
   if (!OutputIdx)
     return;
 
-  if (OutputMappings.find(Outputs[*OutputIdx]) == OutputMappings.end()) {
+  if (OutputMappings.find(Outputs[OutputIdx.getValue()]) ==
+      OutputMappings.end()) {
     LLVM_DEBUG(dbgs() << "Mapping extracted output " << *LI << " to "
-                      << *Outputs[*OutputIdx] << "\n");
-    OutputMappings.insert(std::make_pair(LI, Outputs[OutputIdx.value()]));
+                      << *Outputs[OutputIdx.getValue()] << "\n");
+    OutputMappings.insert(std::make_pair(LI, Outputs[OutputIdx.getValue()]));
   } else {
-    Value *Orig = OutputMappings.find(Outputs[OutputIdx.value()])->second;
+    Value *Orig = OutputMappings.find(Outputs[OutputIdx.getValue()])->second;
     LLVM_DEBUG(dbgs() << "Mapping extracted output " << *Orig << " to "
-                      << *Outputs[*OutputIdx] << "\n");
+                      << *Outputs[OutputIdx.getValue()] << "\n");
     OutputMappings.insert(std::make_pair(LI, Orig));
   }
 }

diff  --git a/llvm/lib/Transforms/IPO/OpenMPOpt.cpp b/llvm/lib/Transforms/IPO/OpenMPOpt.cpp
index 20555afd67c12..f458afafa6984 100644
--- a/llvm/lib/Transforms/IPO/OpenMPOpt.cpp
+++ b/llvm/lib/Transforms/IPO/OpenMPOpt.cpp
@@ -2514,13 +2514,13 @@ struct AAICVTrackerFunction : public AAICVTracker {
         if (ValuesMap.count(CurrInst)) {
           Optional<Value *> NewReplVal = ValuesMap.lookup(CurrInst);
           // Unknown value, track new.
-          if (!ReplVal) {
+          if (!ReplVal.hasValue()) {
             ReplVal = NewReplVal;
             break;
           }
 
           // If we found a new value, we can't know the icv value anymore.
-          if (NewReplVal)
+          if (NewReplVal.hasValue())
             if (ReplVal != NewReplVal)
               return nullptr;
 
@@ -2528,11 +2528,11 @@ struct AAICVTrackerFunction : public AAICVTracker {
         }
 
         Optional<Value *> NewReplVal = getValueForCall(A, *CurrInst, ICV);
-        if (!NewReplVal)
+        if (!NewReplVal.hasValue())
           continue;
 
         // Unknown value, track new.
-        if (!ReplVal) {
+        if (!ReplVal.hasValue()) {
           ReplVal = NewReplVal;
           break;
         }
@@ -4422,13 +4422,13 @@ struct AAFoldRuntimeCallCallSiteReturned : AAFoldRuntimeCall {
 
     std::string Str("simplified value: ");
 
-    if (!SimplifiedValue)
+    if (!SimplifiedValue.hasValue())
       return Str + std::string("none");
 
-    if (!SimplifiedValue.value())
+    if (!SimplifiedValue.getValue())
       return Str + std::string("nullptr");
 
-    if (ConstantInt *CI = dyn_cast<ConstantInt>(SimplifiedValue.value()))
+    if (ConstantInt *CI = dyn_cast<ConstantInt>(SimplifiedValue.getValue()))
       return Str + std::to_string(CI->getSExtValue());
 
     return Str + std::string("unknown");
@@ -4452,8 +4452,8 @@ struct AAFoldRuntimeCallCallSiteReturned : AAFoldRuntimeCall {
         IRPosition::callsite_returned(CB),
         [&](const IRPosition &IRP, const AbstractAttribute *AA,
             bool &UsedAssumedInformation) -> Optional<Value *> {
-          assert((isValidState() ||
-                  (SimplifiedValue && *SimplifiedValue == nullptr)) &&
+          assert((isValidState() || (SimplifiedValue.hasValue() &&
+                                     SimplifiedValue.getValue() == nullptr)) &&
                  "Unexpected invalid state!");
 
           if (!isAtFixpoint()) {

diff  --git a/llvm/lib/Transforms/IPO/SampleContextTracker.cpp b/llvm/lib/Transforms/IPO/SampleContextTracker.cpp
index caeddae5c2051..9cb558bd2b156 100644
--- a/llvm/lib/Transforms/IPO/SampleContextTracker.cpp
+++ b/llvm/lib/Transforms/IPO/SampleContextTracker.cpp
@@ -132,10 +132,10 @@ void ContextTrieNode::setFunctionSamples(FunctionSamples *FSamples) {
 Optional<uint32_t> ContextTrieNode::getFunctionSize() const { return FuncSize; }
 
 void ContextTrieNode::addFunctionSize(uint32_t FSize) {
-  if (!FuncSize)
+  if (!FuncSize.hasValue())
     FuncSize = 0;
 
-  FuncSize = *FuncSize + FSize;
+  FuncSize = FuncSize.getValue() + FSize;
 }
 
 LineLocation ContextTrieNode::getCallSiteLoc() const { return CallSiteLoc; }

diff  --git a/llvm/lib/Transforms/IPO/SampleProfile.cpp b/llvm/lib/Transforms/IPO/SampleProfile.cpp
index e5d6e2602179a..8e4534723517c 100644
--- a/llvm/lib/Transforms/IPO/SampleProfile.cpp
+++ b/llvm/lib/Transforms/IPO/SampleProfile.cpp
@@ -1351,14 +1351,14 @@ SampleProfileLoader::getExternalInlineAdvisorCost(CallBase &CB) {
 
 bool SampleProfileLoader::getExternalInlineAdvisorShouldInline(CallBase &CB) {
   Optional<InlineCost> Cost = getExternalInlineAdvisorCost(CB);
-  return Cost ? !!*Cost : false;
+  return Cost ? !!Cost.getValue() : false;
 }
 
 InlineCost
 SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
   if (Optional<InlineCost> ReplayCost =
           getExternalInlineAdvisorCost(*Candidate.CallInstr))
-    return *ReplayCost;
+    return ReplayCost.getValue();
   // Adjust threshold based on call site hotness, only do this for callsite
   // prioritized inliner because otherwise cost-benefit check is done earlier.
   int SampleThreshold = SampleColdCallSiteThreshold;

diff  --git a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
index 120f9918de7bd..449c0f178bf42 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
@@ -2677,8 +2677,9 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
   }
   default: {
     // Handle target specific intrinsics
-    if (Optional<Instruction *> V = targetInstCombineIntrinsic(*II))
-      return *V;
+    Optional<Instruction *> V = targetInstCombineIntrinsic(*II);
+    if (V.hasValue())
+      return V.getValue();
     break;
   }
   }

diff  --git a/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp b/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
index d8a2a960449ec..d801f4d509645 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
@@ -924,8 +924,8 @@ Value *InstCombinerImpl::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
         // Handle target specific intrinsics
         Optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic(
             *II, DemandedMask, Known, KnownBitsComputed);
-        if (V)
-          return *V;
+        if (V.hasValue())
+          return V.getValue();
         break;
       }
       }
@@ -1635,8 +1635,8 @@ Value *InstCombinerImpl::SimplifyDemandedVectorElts(Value *V,
       Optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic(
           *II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
           simplifyAndSetOp);
-      if (V)
-        return *V;
+      if (V.hasValue())
+        return V.getValue();
       break;
     }
     } // switch on IntrinsicID

diff  --git a/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp
index 284a4c2662ec2..5cc5804dcbc59 100644
--- a/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp
@@ -483,10 +483,10 @@ void ThreadSanitizer::chooseInstructionsToInstrument(
 static bool isTsanAtomic(const Instruction *I) {
   // TODO: Ask TTI whether synchronization scope is between threads.
   auto SSID = getAtomicSyncScopeID(I);
-  if (!SSID)
+  if (!SSID.hasValue())
     return false;
   if (isa<LoadInst>(I) || isa<StoreInst>(I))
-    return *SSID != SyncScope::SingleThread;
+    return SSID.getValue() != SyncScope::SingleThread;
   return true;
 }
 

diff  --git a/llvm/lib/Transforms/Scalar/ConstantHoisting.cpp b/llvm/lib/Transforms/Scalar/ConstantHoisting.cpp
index b698503d74300..8a1761505d590 100644
--- a/llvm/lib/Transforms/Scalar/ConstantHoisting.cpp
+++ b/llvm/lib/Transforms/Scalar/ConstantHoisting.cpp
@@ -611,9 +611,9 @@ ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
                                    ConstCand->ConstInt->getValue());
         if (Diff) {
           const InstructionCost ImmCosts =
-              TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, *Diff, Ty);
+              TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
           Cost -= ImmCosts;
-          LLVM_DEBUG(dbgs() << "Offset " << *Diff << " "
+          LLVM_DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
                             << "has penalty: " << ImmCosts << "\n"
                             << "Adjusted cost: " << Cost << "\n");
         }

diff  --git a/llvm/lib/Transforms/Scalar/GVN.cpp b/llvm/lib/Transforms/Scalar/GVN.cpp
index af2b48c953800..783301fe589ea 100644
--- a/llvm/lib/Transforms/Scalar/GVN.cpp
+++ b/llvm/lib/Transforms/Scalar/GVN.cpp
@@ -748,14 +748,14 @@ void GVNPass::printPipeline(
 
   OS << "<";
   if (Options.AllowPRE != None)
-    OS << (*Options.AllowPRE ? "" : "no-") << "pre;";
+    OS << (Options.AllowPRE.getValue() ? "" : "no-") << "pre;";
   if (Options.AllowLoadPRE != None)
-    OS << (*Options.AllowLoadPRE ? "" : "no-") << "load-pre;";
+    OS << (Options.AllowLoadPRE.getValue() ? "" : "no-") << "load-pre;";
   if (Options.AllowLoadPRESplitBackedge != None)
-    OS << (*Options.AllowLoadPRESplitBackedge ? "" : "no-")
+    OS << (Options.AllowLoadPRESplitBackedge.getValue() ? "" : "no-")
        << "split-backedge-load-pre;";
   if (Options.AllowMemDep != None)
-    OS << (*Options.AllowMemDep ? "" : "no-") << "memdep";
+    OS << (Options.AllowMemDep.getValue() ? "" : "no-") << "memdep";
   OS << ">";
 }
 

diff  --git a/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp b/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp
index 94ed288eb152d..0e27c856947ca 100644
--- a/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp
+++ b/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp
@@ -1427,9 +1427,9 @@ bool LoopConstrainer::run() {
   // constructor.
   ClonedLoop PreLoop, PostLoop;
   bool NeedsPreLoop =
-      Increasing ? SR.LowLimit.has_value() : SR.HighLimit.has_value();
+      Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
   bool NeedsPostLoop =
-      Increasing ? SR.HighLimit.has_value() : SR.LowLimit.has_value();
+      Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
 
   Value *ExitPreLoopAt = nullptr;
   Value *ExitMainLoopAt = nullptr;
@@ -1708,9 +1708,9 @@ IntersectSignedRange(ScalarEvolution &SE,
                      const InductiveRangeCheck::Range &R2) {
   if (R2.isEmpty(SE, /* IsSigned */ true))
     return None;
-  if (!R1)
+  if (!R1.hasValue())
     return R2;
-  auto &R1Value = *R1;
+  auto &R1Value = R1.getValue();
   // We never return empty ranges from this function, and R1 is supposed to be
   // a result of intersection. Thus, R1 is never empty.
   assert(!R1Value.isEmpty(SE, /* IsSigned */ true) &&
@@ -1737,9 +1737,9 @@ IntersectUnsignedRange(ScalarEvolution &SE,
                        const InductiveRangeCheck::Range &R2) {
   if (R2.isEmpty(SE, /* IsSigned */ false))
     return None;
-  if (!R1)
+  if (!R1.hasValue())
     return R2;
-  auto &R1Value = *R1;
+  auto &R1Value = R1.getValue();
   // We never return empty ranges from this function, and R1 is supposed to be
   // a result of intersection. Thus, R1 is never empty.
   assert(!R1Value.isEmpty(SE, /* IsSigned */ false) &&
@@ -1948,21 +1948,24 @@ bool InductiveRangeCheckElimination::run(
   for (InductiveRangeCheck &IRC : RangeChecks) {
     auto Result = IRC.computeSafeIterationSpace(SE, IndVar,
                                                 LS.IsSignedPredicate);
-    if (Result) {
-      auto MaybeSafeIterRange = IntersectRange(SE, SafeIterRange, *Result);
-      if (MaybeSafeIterRange) {
-        assert(!MaybeSafeIterRange->isEmpty(SE, LS.IsSignedPredicate) &&
-               "We should never return empty ranges!");
+    if (Result.hasValue()) {
+      auto MaybeSafeIterRange =
+          IntersectRange(SE, SafeIterRange, Result.getValue());
+      if (MaybeSafeIterRange.hasValue()) {
+        assert(
+            !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) &&
+            "We should never return empty ranges!");
         RangeChecksToEliminate.push_back(IRC);
-        SafeIterRange = *MaybeSafeIterRange;
+        SafeIterRange = MaybeSafeIterRange.getValue();
       }
     }
   }
 
-  if (!SafeIterRange)
+  if (!SafeIterRange.hasValue())
     return false;
 
-  LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT, *SafeIterRange);
+  LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT,
+                     SafeIterRange.getValue());
   bool Changed = LC.run();
 
   if (Changed) {

diff  --git a/llvm/lib/Transforms/Scalar/LoopDistribute.cpp b/llvm/lib/Transforms/Scalar/LoopDistribute.cpp
index f70ab0d50cfea..f606e9b7a4841 100644
--- a/llvm/lib/Transforms/Scalar/LoopDistribute.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopDistribute.cpp
@@ -600,9 +600,9 @@ class InstPartitionContainer {
         {LLVMLoopDistributeFollowupAll,
          Part->hasDepCycle() ? LLVMLoopDistributeFollowupSequential
                              : LLVMLoopDistributeFollowupCoincident});
-    if (PartitionID) {
+    if (PartitionID.hasValue()) {
       Loop *NewLoop = Part->getDistributedLoop();
-      NewLoop->setLoopID(*PartitionID);
+      NewLoop->setLoopID(PartitionID.getValue());
     }
   }
 };
@@ -821,10 +821,12 @@ class LoopDistributeForLoop {
       // The unversioned loop will not be changed, so we inherit all attributes
       // from the original loop, but remove the loop distribution metadata to
       // avoid to distribute it again.
-      MDNode *UnversionedLoopID = *makeFollowupLoopID(
-          OrigLoopID,
-          {LLVMLoopDistributeFollowupAll, LLVMLoopDistributeFollowupFallback},
-          "llvm.loop.distribute.", true);
+      MDNode *UnversionedLoopID =
+          makeFollowupLoopID(OrigLoopID,
+                             {LLVMLoopDistributeFollowupAll,
+                              LLVMLoopDistributeFollowupFallback},
+                             "llvm.loop.distribute.", true)
+              .getValue();
       LVer.getNonVersionedLoop()->setLoopID(UnversionedLoopID);
     }
 

diff  --git a/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp b/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp
index 4bcf102296619..6d4c6756f04de 100644
--- a/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp
@@ -1481,9 +1481,9 @@ bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
       return Changed;
     // We cannot allow unaligned ops for unordered load/store, so reject
     // anything where the alignment isn't at least the element size.
-    assert((StoreAlign && LoadAlign) &&
+    assert((StoreAlign.hasValue() && LoadAlign.hasValue()) &&
            "Expect unordered load/store to have align.");
-    if (*StoreAlign < StoreSize || *LoadAlign < StoreSize)
+    if (StoreAlign.getValue() < StoreSize || LoadAlign.getValue() < StoreSize)
       return Changed;
 
     // If the element.atomic memcpy is not lowered into explicit
@@ -1497,8 +1497,9 @@ bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
     // Note that unordered atomic loads/stores are *required* by the spec to
     // have an alignment but non-atomic loads/stores may not.
     NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
-        StoreBasePtr, *StoreAlign, LoadBasePtr, *LoadAlign, NumBytes, StoreSize,
-        AATags.TBAA, AATags.TBAAStruct, AATags.Scope, AATags.NoAlias);
+        StoreBasePtr, StoreAlign.getValue(), LoadBasePtr, LoadAlign.getValue(),
+        NumBytes, StoreSize, AATags.TBAA, AATags.TBAAStruct, AATags.Scope,
+        AATags.NoAlias);
   }
   NewCall->setDebugLoc(TheStore->getDebugLoc());
 

diff  --git a/llvm/lib/Transforms/Scalar/LoopRotation.cpp b/llvm/lib/Transforms/Scalar/LoopRotation.cpp
index d9c33b5f335aa..533c8536c4891 100644
--- a/llvm/lib/Transforms/Scalar/LoopRotation.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopRotation.cpp
@@ -60,8 +60,8 @@ PreservedAnalyses LoopRotatePass::run(Loop &L, LoopAnalysisManager &AM,
     MSSAU = MemorySSAUpdater(AR.MSSA);
   bool Changed =
       LoopRotation(&L, &AR.LI, &AR.TTI, &AR.AC, &AR.DT, &AR.SE,
-                   MSSAU ? MSSAU.getPointer() : nullptr, SQ, false, Threshold,
-                   false, PrepareForLTO || PrepareForLTOOption);
+                   MSSAU.hasValue() ? MSSAU.getPointer() : nullptr, SQ, false,
+                   Threshold, false, PrepareForLTO || PrepareForLTOOption);
 
   if (!Changed)
     return PreservedAnalyses::all();
@@ -131,8 +131,9 @@ class LoopRotateLegacyPass : public LoopPass {
                         : MaxHeaderSize;
 
     return LoopRotation(L, LI, TTI, AC, &DT, &SE,
-                        MSSAU ? MSSAU.getPointer() : nullptr, SQ, false,
-                        Threshold, false, PrepareForLTO || PrepareForLTOOption);
+                        MSSAU.hasValue() ? MSSAU.getPointer() : nullptr, SQ,
+                        false, Threshold, false,
+                        PrepareForLTO || PrepareForLTOOption);
   }
 };
 } // end namespace

diff  --git a/llvm/lib/Transforms/Scalar/LoopSimplifyCFG.cpp b/llvm/lib/Transforms/Scalar/LoopSimplifyCFG.cpp
index 51007b9006093..c2c29d9f0ff79 100644
--- a/llvm/lib/Transforms/Scalar/LoopSimplifyCFG.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopSimplifyCFG.cpp
@@ -735,9 +735,9 @@ class LoopSimplifyCFGLegacyPass : public LoopPass {
     if (MSSAA && VerifyMemorySSA)
       MSSAU->getMemorySSA()->verifyMemorySSA();
     bool DeleteCurrentLoop = false;
-    bool Changed =
-        simplifyLoopCFG(*L, DT, LI, SE, MSSAU ? MSSAU.getPointer() : nullptr,
-                        DeleteCurrentLoop);
+    bool Changed = simplifyLoopCFG(
+        *L, DT, LI, SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
+        DeleteCurrentLoop);
     if (DeleteCurrentLoop)
       LPM.markLoopAsDeleted(*L);
     return Changed;

diff  --git a/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp b/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp
index 49c3083bb19a9..9959e408e2e22 100644
--- a/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp
@@ -6406,8 +6406,9 @@ static bool SalvageDVI(llvm::Loop *L, ScalarEvolution &SE,
     // less DWARF ops than an iteration count-based expression.
     if (Optional<APInt> Offset =
             SE.computeConstantDifference(DVIRec.SCEVs[i], SCEVInductionVar)) {
-      if (Offset->getMinSignedBits() <= 64)
-        SalvageExpr->createOffsetExpr(Offset->getSExtValue(), LSRInductionVar);
+      if (Offset.getValue().getMinSignedBits() <= 64)
+        SalvageExpr->createOffsetExpr(Offset.getValue().getSExtValue(),
+                                      LSRInductionVar);
     } else if (!SalvageExpr->createIterCountExpr(DVIRec.SCEVs[i], IterCountExpr,
                                                  SE))
       return false;

diff  --git a/llvm/lib/Transforms/Scalar/LoopUnrollAndJamPass.cpp b/llvm/lib/Transforms/Scalar/LoopUnrollAndJamPass.cpp
index 8ea8f284c03aa..a33e5cca09b90 100644
--- a/llvm/lib/Transforms/Scalar/LoopUnrollAndJamPass.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopUnrollAndJamPass.cpp
@@ -372,8 +372,8 @@ tryToUnrollAndJamLoop(Loop *L, DominatorTree &DT, LoopInfo *LI,
   Optional<MDNode *> NewInnerEpilogueLoopID = makeFollowupLoopID(
       OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
                         LLVMLoopUnrollAndJamFollowupRemainderInner});
-  if (NewInnerEpilogueLoopID)
-    SubLoop->setLoopID(*NewInnerEpilogueLoopID);
+  if (NewInnerEpilogueLoopID.hasValue())
+    SubLoop->setLoopID(NewInnerEpilogueLoopID.getValue());
 
   // Find trip count and trip multiple
   BasicBlock *Latch = L->getLoopLatch();
@@ -402,15 +402,15 @@ tryToUnrollAndJamLoop(Loop *L, DominatorTree &DT, LoopInfo *LI,
     Optional<MDNode *> NewOuterEpilogueLoopID = makeFollowupLoopID(
         OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
                           LLVMLoopUnrollAndJamFollowupRemainderOuter});
-    if (NewOuterEpilogueLoopID)
-      EpilogueOuterLoop->setLoopID(*NewOuterEpilogueLoopID);
+    if (NewOuterEpilogueLoopID.hasValue())
+      EpilogueOuterLoop->setLoopID(NewOuterEpilogueLoopID.getValue());
   }
 
   Optional<MDNode *> NewInnerLoopID =
       makeFollowupLoopID(OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll,
                                            LLVMLoopUnrollAndJamFollowupInner});
-  if (NewInnerLoopID)
-    SubLoop->setLoopID(*NewInnerLoopID);
+  if (NewInnerLoopID.hasValue())
+    SubLoop->setLoopID(NewInnerLoopID.getValue());
   else
     SubLoop->setLoopID(OrigSubLoopID);
 
@@ -418,8 +418,8 @@ tryToUnrollAndJamLoop(Loop *L, DominatorTree &DT, LoopInfo *LI,
     Optional<MDNode *> NewOuterLoopID = makeFollowupLoopID(
         OrigOuterLoopID,
         {LLVMLoopUnrollAndJamFollowupAll, LLVMLoopUnrollAndJamFollowupOuter});
-    if (NewOuterLoopID) {
-      L->setLoopID(*NewOuterLoopID);
+    if (NewOuterLoopID.hasValue()) {
+      L->setLoopID(NewOuterLoopID.getValue());
 
       // Do not setLoopAlreadyUnrolled if a followup was given.
       return UnrollResult;

diff  --git a/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp b/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp
index 08f21bed48a38..1969513353008 100644
--- a/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp
@@ -253,19 +253,19 @@ TargetTransformInfo::UnrollingPreferences llvm::gatherUnrollingPreferences(
     UP.MaxIterationsCountToAnalyze = UnrollMaxIterationsCountToAnalyze;
 
   // Apply user values provided by argument
-  if (UserThreshold) {
+  if (UserThreshold.hasValue()) {
     UP.Threshold = *UserThreshold;
     UP.PartialThreshold = *UserThreshold;
   }
-  if (UserCount)
+  if (UserCount.hasValue())
     UP.Count = *UserCount;
-  if (UserAllowPartial)
+  if (UserAllowPartial.hasValue())
     UP.Partial = *UserAllowPartial;
-  if (UserRuntime)
+  if (UserRuntime.hasValue())
     UP.Runtime = *UserRuntime;
-  if (UserUpperBound)
+  if (UserUpperBound.hasValue())
     UP.UpperBound = *UserUpperBound;
-  if (UserFullUnrollMaxCount)
+  if (UserFullUnrollMaxCount.hasValue())
     UP.FullUnrollMaxCount = *UserFullUnrollMaxCount;
 
   return UP;
@@ -1323,16 +1323,16 @@ static LoopUnrollResult tryToUnrollLoop(
     Optional<MDNode *> RemainderLoopID =
         makeFollowupLoopID(OrigLoopID, {LLVMLoopUnrollFollowupAll,
                                         LLVMLoopUnrollFollowupRemainder});
-    if (RemainderLoopID)
-      RemainderLoop->setLoopID(*RemainderLoopID);
+    if (RemainderLoopID.hasValue())
+      RemainderLoop->setLoopID(RemainderLoopID.getValue());
   }
 
   if (UnrollResult != LoopUnrollResult::FullyUnrolled) {
     Optional<MDNode *> NewLoopID =
         makeFollowupLoopID(OrigLoopID, {LLVMLoopUnrollFollowupAll,
                                         LLVMLoopUnrollFollowupUnrolled});
-    if (NewLoopID) {
-      L->setLoopID(*NewLoopID);
+    if (NewLoopID.hasValue()) {
+      L->setLoopID(NewLoopID.getValue());
 
       // Do not setLoopAlreadyUnrolled if loop attributes have been specified
       // explicitly.
@@ -1645,15 +1645,15 @@ void LoopUnrollPass::printPipeline(
       OS, MapClassName2PassName);
   OS << "<";
   if (UnrollOpts.AllowPartial != None)
-    OS << (*UnrollOpts.AllowPartial ? "" : "no-") << "partial;";
+    OS << (UnrollOpts.AllowPartial.getValue() ? "" : "no-") << "partial;";
   if (UnrollOpts.AllowPeeling != None)
-    OS << (*UnrollOpts.AllowPeeling ? "" : "no-") << "peeling;";
+    OS << (UnrollOpts.AllowPeeling.getValue() ? "" : "no-") << "peeling;";
   if (UnrollOpts.AllowRuntime != None)
-    OS << (*UnrollOpts.AllowRuntime ? "" : "no-") << "runtime;";
+    OS << (UnrollOpts.AllowRuntime.getValue() ? "" : "no-") << "runtime;";
   if (UnrollOpts.AllowUpperBound != None)
-    OS << (*UnrollOpts.AllowUpperBound ? "" : "no-") << "upperbound;";
+    OS << (UnrollOpts.AllowUpperBound.getValue() ? "" : "no-") << "upperbound;";
   if (UnrollOpts.AllowProfileBasedPeeling != None)
-    OS << (*UnrollOpts.AllowProfileBasedPeeling ? "" : "no-")
+    OS << (UnrollOpts.AllowProfileBasedPeeling.getValue() ? "" : "no-")
        << "profile-peeling;";
   if (UnrollOpts.FullUnrollMaxCount != None)
     OS << "full-unroll-max=" << UnrollOpts.FullUnrollMaxCount << ";";

diff  --git a/llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp b/llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp
index 47493b54a5274..a886563a1c252 100644
--- a/llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp
+++ b/llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp
@@ -143,10 +143,10 @@ static bool lowerConstantIntrinsics(Function &F, const TargetLibraryInfo &TLI,
       break;
     }
     HasDeadBlocks |= replaceConditionalBranchesOnConstant(
-        II, NewValue, DTU ? DTU.getPointer() : nullptr);
+        II, NewValue, DTU.hasValue() ? DTU.getPointer() : nullptr);
   }
   if (HasDeadBlocks)
-    removeUnreachableBlocks(F, DTU ? DTU.getPointer() : nullptr);
+    removeUnreachableBlocks(F, DTU.hasValue() ? DTU.getPointer() : nullptr);
   return !Worklist.empty();
 }
 

diff  --git a/llvm/lib/Transforms/Utils/CodeExtractor.cpp b/llvm/lib/Transforms/Utils/CodeExtractor.cpp
index 82403864c1143..c4ef979790be3 100644
--- a/llvm/lib/Transforms/Utils/CodeExtractor.cpp
+++ b/llvm/lib/Transforms/Utils/CodeExtractor.cpp
@@ -1775,9 +1775,9 @@ CodeExtractor::extractCodeRegion(const CodeExtractorAnalysisCache &CEAC,
   // Update the entry count of the function.
   if (BFI) {
     auto Count = BFI->getProfileCountFromFreq(EntryFreq.getFrequency());
-    if (Count)
+    if (Count.hasValue())
       newFunction->setEntryCount(
-          ProfileCount(*Count, Function::PCT_Real)); // FIXME
+          ProfileCount(Count.getValue(), Function::PCT_Real)); // FIXME
     BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency());
   }
 

diff  --git a/llvm/lib/Transforms/Utils/LoopPeel.cpp b/llvm/lib/Transforms/Utils/LoopPeel.cpp
index f093fea19c4d4..7f0852cef8ec9 100644
--- a/llvm/lib/Transforms/Utils/LoopPeel.cpp
+++ b/llvm/lib/Transforms/Utils/LoopPeel.cpp
@@ -719,9 +719,9 @@ TargetTransformInfo::PeelingPreferences llvm::gatherPeelingPreferences(
   }
 
   // User specifed values provided by argument.
-  if (UserAllowPeeling)
+  if (UserAllowPeeling.hasValue())
     PP.AllowPeeling = *UserAllowPeeling;
-  if (UserAllowProfileBasedPeeling)
+  if (UserAllowProfileBasedPeeling.hasValue())
     PP.PeelProfiledIterations = *UserAllowProfileBasedPeeling;
 
   return PP;

diff  --git a/llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp b/llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp
index 295ae03eceae2..df24af5c6d609 100644
--- a/llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp
+++ b/llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp
@@ -397,8 +397,8 @@ CloneLoopBlocks(Loop *L, Value *NewIter, const bool UseEpilogRemainder,
 
   Optional<MDNode *> NewLoopID = makeFollowupLoopID(
       LoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder});
-  if (NewLoopID) {
-    NewLoop->setLoopID(*NewLoopID);
+  if (NewLoopID.hasValue()) {
+    NewLoop->setLoopID(NewLoopID.getValue());
 
     // Do not setLoopAlreadyUnrolled if loop attributes have been defined
     // explicitly.

diff  --git a/llvm/lib/Transforms/Utils/LoopUtils.cpp b/llvm/lib/Transforms/Utils/LoopUtils.cpp
index 7dc94d837896b..b7656f43490bd 100644
--- a/llvm/lib/Transforms/Utils/LoopUtils.cpp
+++ b/llvm/lib/Transforms/Utils/LoopUtils.cpp
@@ -358,8 +358,8 @@ TransformationMode llvm::hasUnrollTransformation(const Loop *L) {
 
   Optional<int> Count =
       getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
-  if (Count)
-    return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
+  if (Count.hasValue())
+    return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
 
   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
     return TM_ForcedByUser;
@@ -379,8 +379,8 @@ TransformationMode llvm::hasUnrollAndJamTransformation(const Loop *L) {
 
   Optional<int> Count =
       getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
-  if (Count)
-    return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
+  if (Count.hasValue())
+    return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
 
   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
     return TM_ForcedByUser;

diff  --git a/llvm/lib/Transforms/Utils/MisExpect.cpp b/llvm/lib/Transforms/Utils/MisExpect.cpp
index a7acd8dee2ac4..5ace0c63a7395 100644
--- a/llvm/lib/Transforms/Utils/MisExpect.cpp
+++ b/llvm/lib/Transforms/Utils/MisExpect.cpp
@@ -219,18 +219,18 @@ void verifyMisExpect(Instruction &I, ArrayRef<uint32_t> RealWeights,
 void checkBackendInstrumentation(Instruction &I,
                                  const ArrayRef<uint32_t> RealWeights) {
   auto ExpectedWeightsOpt = extractWeights(&I, I.getContext());
-  if (!ExpectedWeightsOpt)
+  if (!ExpectedWeightsOpt.hasValue())
     return;
-  auto ExpectedWeights = *ExpectedWeightsOpt;
+  auto ExpectedWeights = ExpectedWeightsOpt.getValue();
   verifyMisExpect(I, RealWeights, ExpectedWeights);
 }
 
 void checkFrontendInstrumentation(Instruction &I,
                                   const ArrayRef<uint32_t> ExpectedWeights) {
   auto RealWeightsOpt = extractWeights(&I, I.getContext());
-  if (!RealWeightsOpt)
+  if (!RealWeightsOpt.hasValue())
     return;
-  auto RealWeights = *RealWeightsOpt;
+  auto RealWeights = RealWeightsOpt.getValue();
   verifyMisExpect(I, RealWeights, ExpectedWeights);
 }
 

diff  --git a/llvm/lib/Transforms/Utils/ModuleUtils.cpp b/llvm/lib/Transforms/Utils/ModuleUtils.cpp
index 694837ae63b0e..7388a4bd42dbe 100644
--- a/llvm/lib/Transforms/Utils/ModuleUtils.cpp
+++ b/llvm/lib/Transforms/Utils/ModuleUtils.cpp
@@ -254,8 +254,8 @@ void VFABI::setVectorVariantNames(CallInst *CI,
   for (const std::string &VariantMapping : VariantMappings) {
     LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << VariantMapping << "'\n");
     Optional<VFInfo> VI = VFABI::tryDemangleForVFABI(VariantMapping, *M);
-    assert(VI && "Cannot add an invalid VFABI name.");
-    assert(M->getNamedValue(VI->VectorName) &&
+    assert(VI.hasValue() && "Cannot add an invalid VFABI name.");
+    assert(M->getNamedValue(VI.getValue().VectorName) &&
            "Cannot add variant to attribute: "
            "vector function declaration is missing.");
   }

diff  --git a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
index 8ab7fc0d6b973..5e7a762ffac97 100644
--- a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
+++ b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
@@ -4877,8 +4877,8 @@ LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
   if (!MaxVScale && TheFunction->hasFnAttribute(Attribute::VScaleRange))
     MaxVScale =
         TheFunction->getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
-  MaxScalableVF =
-      ElementCount::getScalable(MaxVScale ? (MaxSafeElements / *MaxVScale) : 0);
+  MaxScalableVF = ElementCount::getScalable(
+      MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
   if (!MaxScalableVF)
     reportVectorizationInfo(
         "Max legal vector width too small, scalable vectorization "
@@ -5273,9 +5273,9 @@ bool LoopVectorizationCostModel::isMoreProfitable(
   unsigned EstimatedWidthB = B.Width.getKnownMinValue();
   if (Optional<unsigned> VScale = getVScaleForTuning()) {
     if (A.Width.isScalable())
-      EstimatedWidthA *= *VScale;
+      EstimatedWidthA *= VScale.getValue();
     if (B.Width.isScalable())
-      EstimatedWidthB *= *VScale;
+      EstimatedWidthB *= VScale.getValue();
   }
 
   // Assume vscale may be larger than 1 (or the value being tuned for),
@@ -7612,8 +7612,8 @@ void LoopVectorizationPlanner::executePlan(ElementCount BestVF, unsigned BestUF,
   VPBasicBlock *HeaderVPBB =
       BestVPlan.getVectorLoopRegion()->getEntryBasicBlock();
   Loop *L = LI->getLoopFor(State.CFG.VPBB2IRBB[HeaderVPBB]);
-  if (VectorizedLoopID)
-    L->setLoopID(*VectorizedLoopID);
+  if (VectorizedLoopID.hasValue())
+    L->setLoopID(VectorizedLoopID.getValue());
   else {
     // Keep all loop hints from the original loop on the vector loop (we'll
     // replace the vectorizer-specific hints below).
@@ -10622,8 +10622,8 @@ bool LoopVectorizePass::processLoop(Loop *L) {
   Optional<MDNode *> RemainderLoopID =
       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
                                       LLVMLoopVectorizeFollowupEpilogue});
-  if (RemainderLoopID) {
-    L->setLoopID(*RemainderLoopID);
+  if (RemainderLoopID.hasValue()) {
+    L->setLoopID(RemainderLoopID.getValue());
   } else {
     if (DisableRuntimeUnroll)
       AddRuntimeUnrollDisableMetaData(L);

diff  --git a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
index a9bccbc290140..d7769efb0e464 100644
--- a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
+++ b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
@@ -2636,8 +2636,8 @@ class BoUpSLP {
     // First check if the result is already in the cache.
     AliasCacheKey key = std::make_pair(Inst1, Inst2);
     Optional<bool> &result = AliasCache[key];
-    if (result) {
-      return *result;
+    if (result.hasValue()) {
+      return result.getValue();
     }
     bool aliased = true;
     if (Loc1.Ptr && isSimple(Inst1))

diff  --git a/llvm/lib/WindowsDriver/MSVCPaths.cpp b/llvm/lib/WindowsDriver/MSVCPaths.cpp
index 0661ed7c6ae12..46a4426b38b4d 100644
--- a/llvm/lib/WindowsDriver/MSVCPaths.cpp
+++ b/llvm/lib/WindowsDriver/MSVCPaths.cpp
@@ -98,14 +98,14 @@ static bool getWindowsSDKDirViaCommandLine(
     llvm::Optional<llvm::StringRef> WinSdkVersion,
     llvm::Optional<llvm::StringRef> WinSysRoot, std::string &Path, int &Major,
     std::string &Version) {
-  if (WinSdkDir || WinSysRoot) {
+  if (WinSdkDir.hasValue() || WinSysRoot.hasValue()) {
     // Don't validate the input; trust the value supplied by the user.
     // The motivation is to prevent unnecessary file and registry access.
     llvm::VersionTuple SDKVersion;
-    if (WinSdkVersion)
+    if (WinSdkVersion.hasValue())
       SDKVersion.tryParse(*WinSdkVersion);
 
-    if (WinSysRoot) {
+    if (WinSysRoot.hasValue()) {
       llvm::SmallString<128> SDKPath(*WinSysRoot);
       llvm::sys::path::append(SDKPath, "Windows Kits");
       if (!SDKVersion.empty())
@@ -479,12 +479,12 @@ bool findVCToolChainViaCommandLine(vfs::FileSystem &VFS,
                                    std::string &Path, ToolsetLayout &VSLayout) {
   // Don't validate the input; trust the value supplied by the user.
   // The primary motivation is to prevent unnecessary file and registry access.
-  if (VCToolsDir || WinSysRoot) {
-    if (WinSysRoot) {
+  if (VCToolsDir.hasValue() || WinSysRoot.hasValue()) {
+    if (WinSysRoot.hasValue()) {
       SmallString<128> ToolsPath(*WinSysRoot);
       sys::path::append(ToolsPath, "VC", "Tools", "MSVC");
       std::string ToolsVersion;
-      if (VCToolsVersion)
+      if (VCToolsVersion.hasValue())
         ToolsVersion = VCToolsVersion->str();
       else
         ToolsVersion = getHighestNumericTupleInDirectory(VFS, ToolsPath);

diff  --git a/llvm/tools/lli/lli.cpp b/llvm/tools/lli/lli.cpp
index 2bc7391bcbcad..f2e3886bdf077 100644
--- a/llvm/tools/lli/lli.cpp
+++ b/llvm/tools/lli/lli.cpp
@@ -536,9 +536,9 @@ int main(int argc, char **argv, char * const *envp) {
   builder.setMCPU(codegen::getCPUStr());
   builder.setMAttrs(codegen::getFeatureList());
   if (auto RM = codegen::getExplicitRelocModel())
-    builder.setRelocationModel(RM.value());
+    builder.setRelocationModel(RM.getValue());
   if (auto CM = codegen::getExplicitCodeModel())
-    builder.setCodeModel(CM.value());
+    builder.setCodeModel(CM.getValue());
   builder.setErrorStr(&ErrorMsg);
   builder.setEngineKind(ForceInterpreter
                         ? EngineKind::Interpreter

diff  --git a/llvm/tools/llvm-cov/CoverageExporterJson.cpp b/llvm/tools/llvm-cov/CoverageExporterJson.cpp
index 2e161f53b10d5..d341abe8dfc8d 100644
--- a/llvm/tools/llvm-cov/CoverageExporterJson.cpp
+++ b/llvm/tools/llvm-cov/CoverageExporterJson.cpp
@@ -291,8 +291,8 @@ void CoverageExporterJson::renderRoot(ArrayRef<std::string> SourceFiles) {
     const json::Object *ObjB = B.getAsObject();
     assert(ObjA != nullptr && "Value A was not an Object");
     assert(ObjB != nullptr && "Value B was not an Object");
-    const StringRef FilenameA = ObjA->getString("filename").value();
-    const StringRef FilenameB = ObjB->getString("filename").value();
+    const StringRef FilenameA = ObjA->getString("filename").getValue();
+    const StringRef FilenameB = ObjB->getString("filename").getValue();
     return FilenameA.compare(FilenameB) < 0;
   });
   auto Export = json::Object(

diff  --git a/llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp b/llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp
index 46782c9b3c9a3..f38eb00dc50f5 100644
--- a/llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp
+++ b/llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp
@@ -561,12 +561,12 @@ void SourceCoverageViewHTML::renderLine(raw_ostream &OS, LineRef L,
     else
       Color = None;
 
-    if (Color)
+    if (Color.hasValue())
       Snippets[I + 1] = Highlight(Snippets[I + 1], CurSeg->Col,
                                   CurSeg->Col + Snippets[I + 1].size());
   }
 
-  if (Color && Segments.empty())
+  if (Color.hasValue() && Segments.empty())
     Snippets.back() = Highlight(Snippets.back(), 1, 1 + Snippets.back().size());
 
   if (getOptions().Debug) {

diff  --git a/llvm/tools/llvm-exegesis/lib/MCInstrDescView.cpp b/llvm/tools/llvm-exegesis/lib/MCInstrDescView.cpp
index 0ad664590957c..049cc68b4fb97 100644
--- a/llvm/tools/llvm-exegesis/lib/MCInstrDescView.cpp
+++ b/llvm/tools/llvm-exegesis/lib/MCInstrDescView.cpp
@@ -47,9 +47,9 @@ bool Operand::isUse() const { return !IsDef; }
 
 bool Operand::isReg() const { return Tracker; }
 
-bool Operand::isTied() const { return TiedToIndex.has_value(); }
+bool Operand::isTied() const { return TiedToIndex.hasValue(); }
 
-bool Operand::isVariable() const { return VariableIndex.has_value(); }
+bool Operand::isVariable() const { return VariableIndex.hasValue(); }
 
 bool Operand::isMemory() const {
   return isExplicit() &&

diff  --git a/llvm/tools/llvm-ifs/llvm-ifs.cpp b/llvm/tools/llvm-ifs/llvm-ifs.cpp
index 6909bd1c74d61..f9b6a8c012235 100644
--- a/llvm/tools/llvm-ifs/llvm-ifs.cpp
+++ b/llvm/tools/llvm-ifs/llvm-ifs.cpp
@@ -533,33 +533,34 @@ int main(int argc, char *argv[]) {
             << "Triple should be defined when output format is TBD";
         return -1;
       }
-      return writeTbdStub(llvm::Triple(Stub.Target.Triple.value()),
+      return writeTbdStub(llvm::Triple(Stub.Target.Triple.getValue()),
                           Stub.Symbols, "TBD", Out);
     }
     case FileFormat::IFS: {
       Stub.IfsVersion = IfsVersionCurrent;
-      if (Config.InputFormat.value() == FileFormat::ELF &&
+      if (Config.InputFormat.getValue() == FileFormat::ELF &&
           Config.HintIfsTarget) {
         std::error_code HintEC(1, std::generic_category());
         IFSTarget HintTarget = parseTriple(*Config.HintIfsTarget);
-        if (Stub.Target.Arch.value() != HintTarget.Arch.value())
+        if (Stub.Target.Arch.getValue() != HintTarget.Arch.getValue())
           fatalError(make_error<StringError>(
               "Triple hint does not match the actual architecture", HintEC));
-        if (Stub.Target.Endianness.value() != HintTarget.Endianness.value())
+        if (Stub.Target.Endianness.getValue() !=
+            HintTarget.Endianness.getValue())
           fatalError(make_error<StringError>(
               "Triple hint does not match the actual endianness", HintEC));
-        if (Stub.Target.BitWidth.value() != HintTarget.BitWidth.value())
+        if (Stub.Target.BitWidth.getValue() != HintTarget.BitWidth.getValue())
           fatalError(make_error<StringError>(
               "Triple hint does not match the actual bit width", HintEC));
 
         stripIFSTarget(Stub, true, false, false, false);
-        Stub.Target.Triple = Config.HintIfsTarget.value();
+        Stub.Target.Triple = Config.HintIfsTarget.getValue();
       } else {
         stripIFSTarget(Stub, Config.StripIfsTarget, Config.StripIfsArch,
                        Config.StripIfsEndianness, Config.StripIfsBitwidth);
       }
       Error IFSWriteError =
-          writeIFS(Config.Output.value(), Stub, Config.WriteIfChanged);
+          writeIFS(Config.Output.getValue(), Stub, Config.WriteIfChanged);
       if (IFSWriteError)
         fatalError(std::move(IFSWriteError));
       break;
@@ -588,28 +589,29 @@ int main(int argc, char *argv[]) {
     }
     if (Config.OutputIfs) {
       Stub.IfsVersion = IfsVersionCurrent;
-      if (Config.InputFormat.value() == FileFormat::ELF &&
+      if (Config.InputFormat.getValue() == FileFormat::ELF &&
           Config.HintIfsTarget) {
         std::error_code HintEC(1, std::generic_category());
         IFSTarget HintTarget = parseTriple(*Config.HintIfsTarget);
-        if (Stub.Target.Arch.value() != HintTarget.Arch.value())
+        if (Stub.Target.Arch.getValue() != HintTarget.Arch.getValue())
           fatalError(make_error<StringError>(
               "Triple hint does not match the actual architecture", HintEC));
-        if (Stub.Target.Endianness.value() != HintTarget.Endianness.value())
+        if (Stub.Target.Endianness.getValue() !=
+            HintTarget.Endianness.getValue())
           fatalError(make_error<StringError>(
               "Triple hint does not match the actual endianness", HintEC));
-        if (Stub.Target.BitWidth.value() != HintTarget.BitWidth.value())
+        if (Stub.Target.BitWidth.getValue() != HintTarget.BitWidth.getValue())
           fatalError(make_error<StringError>(
               "Triple hint does not match the actual bit width", HintEC));
 
         stripIFSTarget(Stub, true, false, false, false);
-        Stub.Target.Triple = Config.HintIfsTarget.value();
+        Stub.Target.Triple = Config.HintIfsTarget.getValue();
       } else {
         stripIFSTarget(Stub, Config.StripIfsTarget, Config.StripIfsArch,
                        Config.StripIfsEndianness, Config.StripIfsBitwidth);
       }
       Error IFSWriteError =
-          writeIFS(Config.OutputIfs.value(), Stub, Config.WriteIfChanged);
+          writeIFS(Config.OutputIfs.getValue(), Stub, Config.WriteIfChanged);
       if (IFSWriteError)
         fatalError(std::move(IFSWriteError));
     }
@@ -626,8 +628,8 @@ int main(int argc, char *argv[]) {
             << "Triple should be defined when output format is TBD";
         return -1;
       }
-      return writeTbdStub(llvm::Triple(*Stub.Target.Triple), Stub.Symbols,
-                          "TBD", Out);
+      return writeTbdStub(llvm::Triple(Stub.Target.Triple.getValue()),
+                          Stub.Symbols, "TBD", Out);
     }
   }
   return 0;

diff  --git a/llvm/tools/llvm-mca/Views/InstructionInfoView.cpp b/llvm/tools/llvm-mca/Views/InstructionInfoView.cpp
index d3f9738b63234..28915e5a2ae53 100644
--- a/llvm/tools/llvm-mca/Views/InstructionInfoView.cpp
+++ b/llvm/tools/llvm-mca/Views/InstructionInfoView.cpp
@@ -70,8 +70,8 @@ void InstructionInfoView::printView(raw_ostream &OS) const {
     else if (IIVDEntry.Latency < 100)
       TempStream << ' ';
 
-    if (IIVDEntry.RThroughput) {
-      double RT = IIVDEntry.RThroughput.value();
+    if (IIVDEntry.RThroughput.hasValue()) {
+      double RT = IIVDEntry.RThroughput.getValue();
       TempStream << format("%.2f", RT) << ' ';
       if (RT < 10.0)
         TempStream << "  ";

diff  --git a/llvm/tools/llvm-objdump/XCOFFDump.cpp b/llvm/tools/llvm-objdump/XCOFFDump.cpp
index befc9c04fc17e..159741bebb67c 100644
--- a/llvm/tools/llvm-objdump/XCOFFDump.cpp
+++ b/llvm/tools/llvm-objdump/XCOFFDump.cpp
@@ -97,8 +97,8 @@ std::string objdump::getXCOFFSymbolDescription(const SymbolInfoTy &SymbolInfo,
   std::string Result;
   // Dummy symbols have no symbol index.
   if (SymbolInfo.XCOFFSymInfo.Index)
-    Result = ("(idx: " + Twine(SymbolInfo.XCOFFSymInfo.Index.value()) + ") " +
-              SymbolName)
+    Result = ("(idx: " + Twine(SymbolInfo.XCOFFSymInfo.Index.getValue()) +
+              ") " + SymbolName)
                  .str();
   else
     Result.append(SymbolName.begin(), SymbolName.end());

diff  --git a/llvm/tools/llvm-objdump/llvm-objdump.cpp b/llvm/tools/llvm-objdump/llvm-objdump.cpp
index e95e7453ab3d8..42c38207a30e3 100644
--- a/llvm/tools/llvm-objdump/llvm-objdump.cpp
+++ b/llvm/tools/llvm-objdump/llvm-objdump.cpp
@@ -1408,8 +1408,8 @@ static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj,
       // Right now, most targets return None i.e ignore to treat a symbol
       // separately. But WebAssembly decodes preludes for some symbols.
       //
-      if (Status) {
-        if (*Status == MCDisassembler::Fail) {
+      if (Status.hasValue()) {
+        if (Status.getValue() == MCDisassembler::Fail) {
           outs() << "// Error in decoding " << SymbolName
                  << " : Decoding failed region as bytes.\n";
           for (uint64_t I = 0; I < Size; ++I) {
@@ -2139,8 +2139,8 @@ void objdump::printSymbol(const ObjectFile *O, const SymbolRef &Symbol,
             SymName = demangle(SymName);
 
           if (SymbolDescription)
-            SymName = getXCOFFSymbolDescription(createSymbolInfo(O, *SymRef),
-                                                SymName);
+            SymName = getXCOFFSymbolDescription(
+                createSymbolInfo(O, SymRef.getValue()), SymName);
 
           outs() << ' ' << SymName;
           outs() << ") ";
@@ -2247,8 +2247,8 @@ static void printRawClangAST(const ObjectFile *Obj) {
   if (!ClangASTSection)
     return;
 
-  StringRef ClangASTContents =
-      unwrapOrError(ClangASTSection->getContents(), Obj->getFileName());
+  StringRef ClangASTContents = unwrapOrError(
+      ClangASTSection.getValue().getContents(), Obj->getFileName());
   outs().write(ClangASTContents.data(), ClangASTContents.size());
 }
 

diff  --git a/llvm/tools/llvm-profdata/llvm-profdata.cpp b/llvm/tools/llvm-profdata/llvm-profdata.cpp
index 9c6586483ef03..11387ac2882cc 100644
--- a/llvm/tools/llvm-profdata/llvm-profdata.cpp
+++ b/llvm/tools/llvm-profdata/llvm-profdata.cpp
@@ -777,12 +777,12 @@ mergeSampleProfile(const WeightedFileVector &Inputs, SymbolRemapper *Remapper,
     }
 
     SampleProfileMap &Profiles = Reader->getProfiles();
-    if (ProfileIsProbeBased &&
+    if (ProfileIsProbeBased.hasValue() &&
         ProfileIsProbeBased != FunctionSamples::ProfileIsProbeBased)
       exitWithError(
           "cannot merge probe-based profile with non-probe-based profile");
     ProfileIsProbeBased = FunctionSamples::ProfileIsProbeBased;
-    if (ProfileIsCS && ProfileIsCS != FunctionSamples::ProfileIsCS)
+    if (ProfileIsCS.hasValue() && ProfileIsCS != FunctionSamples::ProfileIsCS)
       exitWithError("cannot merge CS profile with non-CS profile");
     ProfileIsCS = FunctionSamples::ProfileIsCS;
     for (SampleProfileMap::iterator I = Profiles.begin(), E = Profiles.end();

diff  --git a/llvm/tools/llvm-profgen/ProfiledBinary.cpp b/llvm/tools/llvm-profgen/ProfiledBinary.cpp
index aaf7a007a82ed..adf7770f5cdbd 100644
--- a/llvm/tools/llvm-profgen/ProfiledBinary.cpp
+++ b/llvm/tools/llvm-profgen/ProfiledBinary.cpp
@@ -100,25 +100,26 @@ BinarySizeContextTracker::getFuncSizeForContext(const SampleContext &Context) {
     PrevNode = CurrNode;
     CurrNode =
         CurrNode->getChildContext(ChildFrame.Location, ChildFrame.FuncName);
-    if (CurrNode && CurrNode->getFunctionSize())
-      Size = CurrNode->getFunctionSize().value();
+    if (CurrNode && CurrNode->getFunctionSize().hasValue())
+      Size = CurrNode->getFunctionSize().getValue();
   }
 
   // If we traversed all nodes along the path of the context and haven't
   // found a size yet, pivot to look for size from sibling nodes, i.e size
   // of inlinee under 
diff erent context.
-  if (!Size) {
+  if (!Size.hasValue()) {
     if (!CurrNode)
       CurrNode = PrevNode;
-    while (!Size && CurrNode && !CurrNode->getAllChildContext().empty()) {
+    while (!Size.hasValue() && CurrNode &&
+           !CurrNode->getAllChildContext().empty()) {
       CurrNode = &CurrNode->getAllChildContext().begin()->second;
-      if (CurrNode->getFunctionSize())
-        Size = CurrNode->getFunctionSize().value();
+      if (CurrNode->getFunctionSize().hasValue())
+        Size = CurrNode->getFunctionSize().getValue();
     }
   }
 
-  assert(Size && "We should at least find one context size.");
-  return Size.value();
+  assert(Size.hasValue() && "We should at least find one context size.");
+  return Size.getValue();
 }
 
 void BinarySizeContextTracker::trackInlineesOptimizedAway(

diff  --git a/llvm/tools/llvm-sim/llvm-sim.cpp b/llvm/tools/llvm-sim/llvm-sim.cpp
index 2b717d72e48a2..26e370ff30f1e 100644
--- a/llvm/tools/llvm-sim/llvm-sim.cpp
+++ b/llvm/tools/llvm-sim/llvm-sim.cpp
@@ -85,13 +85,14 @@ exportToFile(const StringRef FilePath,
       Optional<unsigned> End =
           getPositionInModule((*C.back()).Inst, LLVMInstNum);
 
-      assert(Start &&
+      assert(Start.hasValue() &&
              "Could not find instruction number for first instruction");
-      assert(End && "Could not find instruction number for last instruction");
+      assert(End.hasValue() &&
+             "Could not find instruction number for last instruction");
 
       J.object([&] {
-        J.attribute("start", Start.value());
-        J.attribute("end", End.value());
+        J.attribute("start", Start.getValue());
+        J.attribute("end", End.getValue());
       });
     }
     J.arrayEnd();

diff  --git a/llvm/tools/obj2yaml/dwarf2yaml.cpp b/llvm/tools/obj2yaml/dwarf2yaml.cpp
index 4436cef084f63..c0c23ea10eccd 100644
--- a/llvm/tools/obj2yaml/dwarf2yaml.cpp
+++ b/llvm/tools/obj2yaml/dwarf2yaml.cpp
@@ -247,15 +247,15 @@ void dumpDebugInfo(DWARFContext &DCtx, DWARFYAML::Data &Y) {
           auto FormValue = DIEWrapper.find(AttrSpec.Attr);
           if (!FormValue)
             return;
-          auto Form = FormValue->getForm();
+          auto Form = FormValue.getValue().getForm();
           bool indirect = false;
           do {
             indirect = false;
             switch (Form) {
             case dwarf::DW_FORM_addr:
             case dwarf::DW_FORM_GNU_addr_index:
-              if (auto Val = FormValue->getAsAddress())
-                NewValue.Value = Val.value();
+              if (auto Val = FormValue.getValue().getAsAddress())
+                NewValue.Value = Val.getValue();
               break;
             case dwarf::DW_FORM_ref_addr:
             case dwarf::DW_FORM_ref1:
@@ -264,16 +264,16 @@ void dumpDebugInfo(DWARFContext &DCtx, DWARFYAML::Data &Y) {
             case dwarf::DW_FORM_ref8:
             case dwarf::DW_FORM_ref_udata:
             case dwarf::DW_FORM_ref_sig8:
-              if (auto Val = FormValue->getAsReferenceUVal())
-                NewValue.Value = Val.value();
+              if (auto Val = FormValue.getValue().getAsReferenceUVal())
+                NewValue.Value = Val.getValue();
               break;
             case dwarf::DW_FORM_exprloc:
             case dwarf::DW_FORM_block:
             case dwarf::DW_FORM_block1:
             case dwarf::DW_FORM_block2:
             case dwarf::DW_FORM_block4:
-              if (auto Val = FormValue->getAsBlock()) {
-                auto BlockData = Val.value();
+              if (auto Val = FormValue.getValue().getAsBlock()) {
+                auto BlockData = Val.getValue();
                 std::copy(BlockData.begin(), BlockData.end(),
                           std::back_inserter(NewValue.BlockData));
               }
@@ -288,8 +288,8 @@ void dumpDebugInfo(DWARFContext &DCtx, DWARFYAML::Data &Y) {
             case dwarf::DW_FORM_udata:
             case dwarf::DW_FORM_ref_sup4:
             case dwarf::DW_FORM_ref_sup8:
-              if (auto Val = FormValue->getAsUnsignedConstant())
-                NewValue.Value = Val.value();
+              if (auto Val = FormValue.getValue().getAsUnsignedConstant())
+                NewValue.Value = Val.getValue();
               break;
             case dwarf::DW_FORM_string:
               if (auto Val = dwarf::toString(FormValue))
@@ -297,10 +297,10 @@ void dumpDebugInfo(DWARFContext &DCtx, DWARFYAML::Data &Y) {
               break;
             case dwarf::DW_FORM_indirect:
               indirect = true;
-              if (auto Val = FormValue->getAsUnsignedConstant()) {
-                NewValue.Value = Val.value();
+              if (auto Val = FormValue.getValue().getAsUnsignedConstant()) {
+                NewValue.Value = Val.getValue();
                 NewEntry.Values.push_back(NewValue);
-                Form = static_cast<dwarf::Form>(Val.value());
+                Form = static_cast<dwarf::Form>(Val.getValue());
               }
               break;
             case dwarf::DW_FORM_strp:
@@ -311,8 +311,8 @@ void dumpDebugInfo(DWARFContext &DCtx, DWARFYAML::Data &Y) {
             case dwarf::DW_FORM_strp_sup:
             case dwarf::DW_FORM_GNU_str_index:
             case dwarf::DW_FORM_strx:
-              if (auto Val = FormValue->getAsCStringOffset())
-                NewValue.Value = Val.value();
+              if (auto Val = FormValue.getValue().getAsCStringOffset())
+                NewValue.Value = Val.getValue();
               break;
             case dwarf::DW_FORM_flag_present:
               NewValue.Value = 1;

diff  --git a/llvm/tools/obj2yaml/dxcontainer2yaml.cpp b/llvm/tools/obj2yaml/dxcontainer2yaml.cpp
index 122ae7df50a04..a57b8cfdec956 100644
--- a/llvm/tools/obj2yaml/dxcontainer2yaml.cpp
+++ b/llvm/tools/obj2yaml/dxcontainer2yaml.cpp
@@ -40,8 +40,8 @@ dumpDXContainer(MemoryBufferRef Source) {
     Obj->Header.PartOffsets->push_back(P.Offset);
     if (P.Part.getName() == "DXIL") {
       Optional<DXContainer::DXILData> DXIL = Container.getDXIL();
-      assert(DXIL && "Since we are iterating and found a DXIL part, "
-                     "this should never not have a value");
+      assert(DXIL.hasValue() && "Since we are iterating and found a DXIL part, "
+                                "this should never not have a value");
       Obj->Parts.push_back(DXContainerYAML::Part{
           P.Part.getName().str(), P.Part.Size,
           DXContainerYAML::DXILProgram{

diff  --git a/llvm/unittests/ADT/OptionalTest.cpp b/llvm/unittests/ADT/OptionalTest.cpp
index 94032c6a80b60..f88437f0ab294 100644
--- a/llvm/unittests/ADT/OptionalTest.cpp
+++ b/llvm/unittests/ADT/OptionalTest.cpp
@@ -29,13 +29,13 @@ void OptionalWorksInConstexpr() {
   constexpr Optional<int> x2{};
   static_assert(!x1.has_value() && !x2.has_value(),
                 "Default construction and hasValue() are contexpr");
-  static_assert(!x1.has_value() && !x2.has_value(),
+  static_assert(!x1.hasValue() && !x2.hasValue(),
                 "Default construction and hasValue() are contexpr");
   constexpr auto y1 = Optional<int>(3);
   constexpr Optional<int> y2{3};
   static_assert(y1.value() == y2.value() && y1.value() == 3,
                 "Construction with value and getValue() are constexpr");
-  static_assert(y1.value() == *y2 && *y1 == 3,
+  static_assert(y1.getValue() == y2.getValue() && y1.getValue() == 3,
                 "Construction with value and getValue() are constexpr");
   static_assert(Optional<int>{3} >= 2 && Optional<int>{1} < Optional<int>{2},
                 "Comparisons work in constexpr");
@@ -252,14 +252,14 @@ TEST(OptionalTest, Emplace) {
   
   A.emplace(1, 2);
   EXPECT_TRUE(A.has_value());
-  EXPECT_TRUE(A.has_value());
+  EXPECT_TRUE(A.hasValue());
   EXPECT_EQ(1, A->x);
   EXPECT_EQ(2, A->y);
   EXPECT_EQ(0u, MultiArgConstructor::Destructions);
 
   A.emplace(5, false);
   EXPECT_TRUE(A.has_value());
-  EXPECT_TRUE(A.has_value());
+  EXPECT_TRUE(A.hasValue());
   EXPECT_EQ(5, A->x);
   EXPECT_EQ(-5, A->y);
   EXPECT_EQ(1u, MultiArgConstructor::Destructions);
@@ -270,12 +270,12 @@ TEST(OptionalTest, InPlaceConstructionMultiArgConstructorTest) {
   {
     Optional<MultiArgConstructor> A{in_place, 1, 2};
     EXPECT_TRUE(A.has_value());
-    EXPECT_TRUE(A.has_value());
+    EXPECT_TRUE(A.hasValue());
     EXPECT_EQ(1, A->x);
     EXPECT_EQ(2, A->y);
     Optional<MultiArgConstructor> B{in_place, 5, false};
     EXPECT_TRUE(B.has_value());
-    EXPECT_TRUE(B.has_value());
+    EXPECT_TRUE(B.hasValue());
     EXPECT_EQ(5, B->x);
     EXPECT_EQ(-5, B->y);
     EXPECT_EQ(0u, MultiArgConstructor::Destructions);

diff  --git a/llvm/unittests/ADT/StatisticTest.cpp b/llvm/unittests/ADT/StatisticTest.cpp
index 523f510cccdde..17d9911915550 100644
--- a/llvm/unittests/ADT/StatisticTest.cpp
+++ b/llvm/unittests/ADT/StatisticTest.cpp
@@ -92,8 +92,8 @@ TEST(StatisticTest, API) {
     OptionalStatistic S2;
     extractCounters(Range1, S1, S2);
 
-    EXPECT_EQ(S1.has_value(), true);
-    EXPECT_EQ(S2.has_value(), false);
+    EXPECT_EQ(S1.hasValue(), true);
+    EXPECT_EQ(S2.hasValue(), false);
   }
 
   // Counter2 will be registered when it's first touched.
@@ -108,8 +108,8 @@ TEST(StatisticTest, API) {
     OptionalStatistic S2;
     extractCounters(Range, S1, S2);
 
-    EXPECT_EQ(S1.has_value(), true);
-    EXPECT_EQ(S2.has_value(), true);
+    EXPECT_EQ(S1.hasValue(), true);
+    EXPECT_EQ(S2.hasValue(), true);
 
     EXPECT_EQ(S1->first, "Counter");
     EXPECT_EQ(S1->second, 2u);
@@ -135,8 +135,8 @@ TEST(StatisticTest, API) {
     OptionalStatistic S1;
     OptionalStatistic S2;
     extractCounters(Range, S1, S2);
-    EXPECT_EQ(S1.has_value(), false);
-    EXPECT_EQ(S2.has_value(), false);
+    EXPECT_EQ(S1.hasValue(), false);
+    EXPECT_EQ(S2.hasValue(), false);
   }
 
   // Now check that they successfully re-register and count.
@@ -153,8 +153,8 @@ TEST(StatisticTest, API) {
     OptionalStatistic S2;
     extractCounters(Range, S1, S2);
 
-    EXPECT_EQ(S1.has_value(), true);
-    EXPECT_EQ(S2.has_value(), true);
+    EXPECT_EQ(S1.hasValue(), true);
+    EXPECT_EQ(S2.hasValue(), true);
 
     EXPECT_EQ(S1->first, "Counter");
     EXPECT_EQ(S1->second, 1u);

diff  --git a/llvm/unittests/Analysis/BlockFrequencyInfoTest.cpp b/llvm/unittests/Analysis/BlockFrequencyInfoTest.cpp
index 91009ab7d074f..5dd399517164c 100644
--- a/llvm/unittests/Analysis/BlockFrequencyInfoTest.cpp
+++ b/llvm/unittests/Analysis/BlockFrequencyInfoTest.cpp
@@ -75,11 +75,11 @@ TEST_F(BlockFrequencyInfoTest, Basic) {
   EXPECT_EQ(BB0Freq, BB1Freq + BB2Freq);
   EXPECT_EQ(BB0Freq, BB3Freq);
 
-  EXPECT_EQ(BFI.getBlockProfileCount(&BB0).value(), UINT64_C(100));
-  EXPECT_EQ(BFI.getBlockProfileCount(BB3).value(), UINT64_C(100));
-  EXPECT_EQ(BFI.getBlockProfileCount(BB1).value(),
+  EXPECT_EQ(BFI.getBlockProfileCount(&BB0).getValue(), UINT64_C(100));
+  EXPECT_EQ(BFI.getBlockProfileCount(BB3).getValue(), UINT64_C(100));
+  EXPECT_EQ(BFI.getBlockProfileCount(BB1).getValue(),
             (100 * BB1Freq + BB0Freq / 2) / BB0Freq);
-  EXPECT_EQ(BFI.getBlockProfileCount(BB2).value(),
+  EXPECT_EQ(BFI.getBlockProfileCount(BB2).getValue(),
             (100 * BB2Freq + BB0Freq / 2) / BB0Freq);
 
   // Scale the frequencies of BB0, BB1 and BB2 by a factor of two.

diff  --git a/llvm/unittests/Analysis/IRSimilarityIdentifierTest.cpp b/llvm/unittests/Analysis/IRSimilarityIdentifierTest.cpp
index f6a053792f852..cfe2c25fc8393 100644
--- a/llvm/unittests/Analysis/IRSimilarityIdentifierTest.cpp
+++ b/llvm/unittests/Analysis/IRSimilarityIdentifierTest.cpp
@@ -2188,9 +2188,9 @@ TEST(IRSimilarityCandidate, CanonicalNumbering) {
   for (std::pair<unsigned, DenseSet<unsigned>> &P : Mapping2) {
     unsigned Source = P.first;
 
-    ASSERT_TRUE(Cand2.getCanonicalNum(Source).has_value());
+    ASSERT_TRUE(Cand2.getCanonicalNum(Source).hasValue());
     unsigned Canon = *Cand2.getCanonicalNum(Source);
-    ASSERT_TRUE(Cand1.fromCanonicalNum(Canon).has_value());
+    ASSERT_TRUE(Cand1.fromCanonicalNum(Canon).hasValue());
     unsigned Dest = *Cand1.fromCanonicalNum(Canon);
 
     DenseSet<unsigned>::iterator It = P.second.find(Dest);

diff  --git a/llvm/unittests/Analysis/MemorySSATest.cpp b/llvm/unittests/Analysis/MemorySSATest.cpp
index 4c8942f30121f..298a8bc5d9fc7 100644
--- a/llvm/unittests/Analysis/MemorySSATest.cpp
+++ b/llvm/unittests/Analysis/MemorySSATest.cpp
@@ -1191,13 +1191,14 @@ TEST_F(MemorySSATest, TestStoreMayAlias) {
     EXPECT_EQ(MemDef->isOptimized(), true)
         << "Store " << I << " was not optimized";
     if (I == 1 || I == 3 || I == 4)
-      EXPECT_EQ(MemDef->getOptimizedAccessType().value(), AliasResult::MayAlias)
+      EXPECT_EQ(MemDef->getOptimizedAccessType().getValue(),
+                AliasResult::MayAlias)
           << "Store " << I << " doesn't have the correct alias information";
     else if (I == 0 || I == 2)
       EXPECT_EQ(MemDef->getOptimizedAccessType(), None)
           << "Store " << I << " doesn't have the correct alias information";
     else
-      EXPECT_EQ(MemDef->getOptimizedAccessType().value(),
+      EXPECT_EQ(MemDef->getOptimizedAccessType().getValue(),
                 AliasResult::MustAlias)
           << "Store " << I << " doesn't have the correct alias information";
     // EXPECT_EQ expands such that if we increment I above, it won't get

diff  --git a/llvm/unittests/Analysis/VectorFunctionABITest.cpp b/llvm/unittests/Analysis/VectorFunctionABITest.cpp
index 026732c26be11..7ac1b0384f87b 100644
--- a/llvm/unittests/Analysis/VectorFunctionABITest.cpp
+++ b/llvm/unittests/Analysis/VectorFunctionABITest.cpp
@@ -75,8 +75,8 @@ class VFABIParserTest : public ::testing::Test {
     reset(Name, IRType);
 
     const auto OptInfo = VFABI::tryDemangleForVFABI(MangledName, *(M.get()));
-    if (OptInfo) {
-      Info = OptInfo.value();
+    if (OptInfo.hasValue()) {
+      Info = OptInfo.getValue();
       return true;
     }
 

diff  --git a/llvm/unittests/BinaryFormat/DwarfTest.cpp b/llvm/unittests/BinaryFormat/DwarfTest.cpp
index ddafbb4102bde..5e49a5cc2ee68 100644
--- a/llvm/unittests/BinaryFormat/DwarfTest.cpp
+++ b/llvm/unittests/BinaryFormat/DwarfTest.cpp
@@ -147,48 +147,48 @@ TEST(DwarfTest, FixedFormSizes) {
   FormParams Params_2_4_32 = {2, 4, DWARF32};
   RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_2_4_32);
   AddrSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_2_4_32);
-  EXPECT_TRUE(RefSize.has_value());
-  EXPECT_TRUE(AddrSize.has_value());
+  EXPECT_TRUE(RefSize.hasValue());
+  EXPECT_TRUE(AddrSize.hasValue());
   EXPECT_EQ(*RefSize, *AddrSize);
 
   // Test 32 bit DWARF version 2 with 8 byte addresses.
   FormParams Params_2_8_32 = {2, 8, DWARF32};
   RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_2_8_32);
   AddrSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_2_8_32);
-  EXPECT_TRUE(RefSize.has_value());
-  EXPECT_TRUE(AddrSize.has_value());
+  EXPECT_TRUE(RefSize.hasValue());
+  EXPECT_TRUE(AddrSize.hasValue());
   EXPECT_EQ(*RefSize, *AddrSize);
 
   // DW_FORM_ref_addr is 4 bytes in DWARF 32 in DWARF version 3 and beyond.
   FormParams Params_3_4_32 = {3, 4, DWARF32};
   RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_3_4_32);
-  EXPECT_TRUE(RefSize.has_value());
+  EXPECT_TRUE(RefSize.hasValue());
   EXPECT_EQ(*RefSize, 4);
 
   FormParams Params_4_4_32 = {4, 4, DWARF32};
   RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_4_4_32);
-  EXPECT_TRUE(RefSize.has_value());
+  EXPECT_TRUE(RefSize.hasValue());
   EXPECT_EQ(*RefSize, 4);
 
   FormParams Params_5_4_32 = {5, 4, DWARF32};
   RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_5_4_32);
-  EXPECT_TRUE(RefSize.has_value());
+  EXPECT_TRUE(RefSize.hasValue());
   EXPECT_EQ(*RefSize, 4);
 
   // DW_FORM_ref_addr is 8 bytes in DWARF 64 in DWARF version 3 and beyond.
   FormParams Params_3_8_64 = {3, 8, DWARF64};
   RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_3_8_64);
-  EXPECT_TRUE(RefSize.has_value());
+  EXPECT_TRUE(RefSize.hasValue());
   EXPECT_EQ(*RefSize, 8);
 
   FormParams Params_4_8_64 = {4, 8, DWARF64};
   RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_4_8_64);
-  EXPECT_TRUE(RefSize.has_value());
+  EXPECT_TRUE(RefSize.hasValue());
   EXPECT_EQ(*RefSize, 8);
 
   FormParams Params_5_8_64 = {5, 8, DWARF64};
   RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_5_8_64);
-  EXPECT_TRUE(RefSize.has_value());
+  EXPECT_TRUE(RefSize.hasValue());
   EXPECT_EQ(*RefSize, 8);
 }
 

diff  --git a/llvm/unittests/CodeGen/GlobalISel/ConstantFoldingTest.cpp b/llvm/unittests/CodeGen/GlobalISel/ConstantFoldingTest.cpp
index 33c1f0f32de66..5053d542d2bac 100644
--- a/llvm/unittests/CodeGen/GlobalISel/ConstantFoldingTest.cpp
+++ b/llvm/unittests/CodeGen/GlobalISel/ConstantFoldingTest.cpp
@@ -83,157 +83,157 @@ TEST_F(AArch64GISelMITest, FoldBinOp) {
   Optional<APInt> FoldGAddInt =
       ConstantFoldBinOp(TargetOpcode::G_ADD, MIBCst1.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGAddInt.has_value());
-  EXPECT_EQ(25ULL, FoldGAddInt->getLimitedValue());
+  EXPECT_TRUE(FoldGAddInt.hasValue());
+  EXPECT_EQ(25ULL, FoldGAddInt.getValue().getLimitedValue());
   Optional<APInt> FoldGAddMix =
       ConstantFoldBinOp(TargetOpcode::G_ADD, MIBCst1.getReg(0),
                         MIBFCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGAddMix.has_value());
-  EXPECT_EQ(1073741840ULL, FoldGAddMix->getLimitedValue());
+  EXPECT_TRUE(FoldGAddMix.hasValue());
+  EXPECT_EQ(1073741840ULL, FoldGAddMix.getValue().getLimitedValue());
 
   // Test G_AND folding Integer + Mixed Int-Float cases
   Optional<APInt> FoldGAndInt =
       ConstantFoldBinOp(TargetOpcode::G_AND, MIBCst1.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGAndInt.has_value());
-  EXPECT_EQ(0ULL, FoldGAndInt->getLimitedValue());
+  EXPECT_TRUE(FoldGAndInt.hasValue());
+  EXPECT_EQ(0ULL, FoldGAndInt.getValue().getLimitedValue());
   Optional<APInt> FoldGAndMix =
       ConstantFoldBinOp(TargetOpcode::G_AND, MIBCst2.getReg(0),
                         MIBFCst1.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGAndMix.has_value());
-  EXPECT_EQ(1ULL, FoldGAndMix->getLimitedValue());
+  EXPECT_TRUE(FoldGAndMix.hasValue());
+  EXPECT_EQ(1ULL, FoldGAndMix.getValue().getLimitedValue());
 
   // Test G_ASHR folding Integer + Mixed cases
   Optional<APInt> FoldGAShrInt =
       ConstantFoldBinOp(TargetOpcode::G_ASHR, MIBCst1.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGAShrInt.has_value());
-  EXPECT_EQ(0ULL, FoldGAShrInt->getLimitedValue());
+  EXPECT_TRUE(FoldGAShrInt.hasValue());
+  EXPECT_EQ(0ULL, FoldGAShrInt.getValue().getLimitedValue());
   Optional<APInt> FoldGAShrMix =
       ConstantFoldBinOp(TargetOpcode::G_ASHR, MIBFCst2.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGAShrMix.has_value());
-  EXPECT_EQ(2097152ULL, FoldGAShrMix->getLimitedValue());
+  EXPECT_TRUE(FoldGAShrMix.hasValue());
+  EXPECT_EQ(2097152ULL, FoldGAShrMix.getValue().getLimitedValue());
 
   // Test G_LSHR folding Integer + Mixed Int-Float cases
   Optional<APInt> FoldGLShrInt =
       ConstantFoldBinOp(TargetOpcode::G_LSHR, MIBCst1.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGLShrInt.has_value());
-  EXPECT_EQ(0ULL, FoldGLShrInt->getLimitedValue());
+  EXPECT_TRUE(FoldGLShrInt.hasValue());
+  EXPECT_EQ(0ULL, FoldGLShrInt.getValue().getLimitedValue());
   Optional<APInt> FoldGLShrMix =
       ConstantFoldBinOp(TargetOpcode::G_LSHR, MIBFCst1.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGLShrMix.has_value());
-  EXPECT_EQ(2080768ULL, FoldGLShrMix->getLimitedValue());
+  EXPECT_TRUE(FoldGLShrMix.hasValue());
+  EXPECT_EQ(2080768ULL, FoldGLShrMix.getValue().getLimitedValue());
 
   // Test G_MUL folding Integer + Mixed Int-Float cases
   Optional<APInt> FoldGMulInt =
       ConstantFoldBinOp(TargetOpcode::G_MUL, MIBCst1.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGMulInt.has_value());
-  EXPECT_EQ(144ULL, FoldGMulInt->getLimitedValue());
+  EXPECT_TRUE(FoldGMulInt.hasValue());
+  EXPECT_EQ(144ULL, FoldGMulInt.getValue().getLimitedValue());
   Optional<APInt> FoldGMulMix =
       ConstantFoldBinOp(TargetOpcode::G_MUL, MIBCst1.getReg(0),
                         MIBFCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGMulMix.has_value());
-  EXPECT_EQ(0ULL, FoldGMulMix->getLimitedValue());
+  EXPECT_TRUE(FoldGMulMix.hasValue());
+  EXPECT_EQ(0ULL, FoldGMulMix.getValue().getLimitedValue());
 
   // Test G_OR folding Integer + Mixed Int-Float cases
   Optional<APInt> FoldGOrInt =
       ConstantFoldBinOp(TargetOpcode::G_OR, MIBCst1.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGOrInt.has_value());
-  EXPECT_EQ(25ULL, FoldGOrInt->getLimitedValue());
+  EXPECT_TRUE(FoldGOrInt.hasValue());
+  EXPECT_EQ(25ULL, FoldGOrInt.getValue().getLimitedValue());
   Optional<APInt> FoldGOrMix =
       ConstantFoldBinOp(TargetOpcode::G_OR, MIBCst1.getReg(0),
                         MIBFCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGOrMix.has_value());
-  EXPECT_EQ(1073741840ULL, FoldGOrMix->getLimitedValue());
+  EXPECT_TRUE(FoldGOrMix.hasValue());
+  EXPECT_EQ(1073741840ULL, FoldGOrMix.getValue().getLimitedValue());
 
   // Test G_SHL folding Integer + Mixed Int-Float cases
   Optional<APInt> FoldGShlInt =
       ConstantFoldBinOp(TargetOpcode::G_SHL, MIBCst1.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGShlInt.has_value());
-  EXPECT_EQ(8192ULL, FoldGShlInt->getLimitedValue());
+  EXPECT_TRUE(FoldGShlInt.hasValue());
+  EXPECT_EQ(8192ULL, FoldGShlInt.getValue().getLimitedValue());
   Optional<APInt> FoldGShlMix =
       ConstantFoldBinOp(TargetOpcode::G_SHL, MIBCst1.getReg(0),
                         MIBFCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGShlMix.has_value());
-  EXPECT_EQ(0ULL, FoldGShlMix->getLimitedValue());
+  EXPECT_TRUE(FoldGShlMix.hasValue());
+  EXPECT_EQ(0ULL, FoldGShlMix.getValue().getLimitedValue());
 
   // Test G_SUB folding Integer + Mixed Int-Float cases
   Optional<APInt> FoldGSubInt =
       ConstantFoldBinOp(TargetOpcode::G_SUB, MIBCst1.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGSubInt.has_value());
-  EXPECT_EQ(7ULL, FoldGSubInt->getLimitedValue());
+  EXPECT_TRUE(FoldGSubInt.hasValue());
+  EXPECT_EQ(7ULL, FoldGSubInt.getValue().getLimitedValue());
   Optional<APInt> FoldGSubMix =
       ConstantFoldBinOp(TargetOpcode::G_SUB, MIBCst1.getReg(0),
                         MIBFCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGSubMix.has_value());
-  EXPECT_EQ(3221225488ULL, FoldGSubMix->getLimitedValue());
+  EXPECT_TRUE(FoldGSubMix.hasValue());
+  EXPECT_EQ(3221225488ULL, FoldGSubMix.getValue().getLimitedValue());
 
   // Test G_XOR folding Integer + Mixed Int-Float cases
   Optional<APInt> FoldGXorInt =
       ConstantFoldBinOp(TargetOpcode::G_XOR, MIBCst1.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGXorInt.has_value());
-  EXPECT_EQ(25ULL, FoldGXorInt->getLimitedValue());
+  EXPECT_TRUE(FoldGXorInt.hasValue());
+  EXPECT_EQ(25ULL, FoldGXorInt.getValue().getLimitedValue());
   Optional<APInt> FoldGXorMix =
       ConstantFoldBinOp(TargetOpcode::G_XOR, MIBCst1.getReg(0),
                         MIBFCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGXorMix.has_value());
-  EXPECT_EQ(1073741840ULL, FoldGXorMix->getLimitedValue());
+  EXPECT_TRUE(FoldGXorMix.hasValue());
+  EXPECT_EQ(1073741840ULL, FoldGXorMix.getValue().getLimitedValue());
 
   // Test G_UDIV folding Integer + Mixed Int-Float cases
   Optional<APInt> FoldGUdivInt =
       ConstantFoldBinOp(TargetOpcode::G_UDIV, MIBCst1.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGUdivInt.has_value());
-  EXPECT_EQ(1ULL, FoldGUdivInt->getLimitedValue());
+  EXPECT_TRUE(FoldGUdivInt.hasValue());
+  EXPECT_EQ(1ULL, FoldGUdivInt.getValue().getLimitedValue());
   Optional<APInt> FoldGUdivMix =
       ConstantFoldBinOp(TargetOpcode::G_UDIV, MIBCst1.getReg(0),
                         MIBFCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGUdivMix.has_value());
-  EXPECT_EQ(0ULL, FoldGUdivMix->getLimitedValue());
+  EXPECT_TRUE(FoldGUdivMix.hasValue());
+  EXPECT_EQ(0ULL, FoldGUdivMix.getValue().getLimitedValue());
 
   // Test G_SDIV folding Integer + Mixed Int-Float cases
   Optional<APInt> FoldGSdivInt =
       ConstantFoldBinOp(TargetOpcode::G_SDIV, MIBCst1.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGSdivInt.has_value());
-  EXPECT_EQ(1ULL, FoldGSdivInt->getLimitedValue());
+  EXPECT_TRUE(FoldGSdivInt.hasValue());
+  EXPECT_EQ(1ULL, FoldGSdivInt.getValue().getLimitedValue());
   Optional<APInt> FoldGSdivMix =
       ConstantFoldBinOp(TargetOpcode::G_SDIV, MIBCst1.getReg(0),
                         MIBFCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGSdivMix.has_value());
-  EXPECT_EQ(0ULL, FoldGSdivMix->getLimitedValue());
+  EXPECT_TRUE(FoldGSdivMix.hasValue());
+  EXPECT_EQ(0ULL, FoldGSdivMix.getValue().getLimitedValue());
 
   // Test G_UREM folding Integer + Mixed Int-Float cases
   Optional<APInt> FoldGUremInt =
       ConstantFoldBinOp(TargetOpcode::G_UDIV, MIBCst1.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGUremInt.has_value());
-  EXPECT_EQ(1ULL, FoldGUremInt->getLimitedValue());
+  EXPECT_TRUE(FoldGUremInt.hasValue());
+  EXPECT_EQ(1ULL, FoldGUremInt.getValue().getLimitedValue());
   Optional<APInt> FoldGUremMix =
       ConstantFoldBinOp(TargetOpcode::G_UDIV, MIBCst1.getReg(0),
                         MIBFCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGUremMix.has_value());
-  EXPECT_EQ(0ULL, FoldGUremMix->getLimitedValue());
+  EXPECT_TRUE(FoldGUremMix.hasValue());
+  EXPECT_EQ(0ULL, FoldGUremMix.getValue().getLimitedValue());
 
   // Test G_SREM folding Integer + Mixed Int-Float cases
   Optional<APInt> FoldGSremInt =
       ConstantFoldBinOp(TargetOpcode::G_SREM, MIBCst1.getReg(0),
                         MIBCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGSremInt.has_value());
-  EXPECT_EQ(7ULL, FoldGSremInt->getLimitedValue());
+  EXPECT_TRUE(FoldGSremInt.hasValue());
+  EXPECT_EQ(7ULL, FoldGSremInt.getValue().getLimitedValue());
   Optional<APInt> FoldGSremMix =
       ConstantFoldBinOp(TargetOpcode::G_SREM, MIBCst1.getReg(0),
                         MIBFCst2.getReg(0), *MRI);
-  EXPECT_TRUE(FoldGSremMix.has_value());
-  EXPECT_EQ(16ULL, FoldGSremMix->getLimitedValue());
+  EXPECT_TRUE(FoldGSremMix.hasValue());
+  EXPECT_EQ(16ULL, FoldGSremMix.getValue().getLimitedValue());
 }
 
 } // namespace

diff  --git a/llvm/unittests/DebugInfo/DWARF/DWARFDebugFrameTest.cpp b/llvm/unittests/DebugInfo/DWARF/DWARFDebugFrameTest.cpp
index dbc54e7bdb8ef..6a8f23c05a576 100644
--- a/llvm/unittests/DebugInfo/DWARF/DWARFDebugFrameTest.cpp
+++ b/llvm/unittests/DebugInfo/DWARF/DWARFDebugFrameTest.cpp
@@ -424,31 +424,31 @@ TEST(DWARFDebugFrame, RegisterLocations) {
   // Verify RegisterLocations::getRegisterLocation() works as expected.
   Optional<dwarf::UnwindLocation> OptionalLoc;
   OptionalLoc = Locs.getRegisterLocation(0);
-  EXPECT_FALSE(OptionalLoc.has_value());
+  EXPECT_FALSE(OptionalLoc.hasValue());
 
   OptionalLoc = Locs.getRegisterLocation(12);
-  EXPECT_TRUE(OptionalLoc.has_value());
+  EXPECT_TRUE(OptionalLoc.hasValue());
   EXPECT_EQ(*OptionalLoc, Reg12Loc);
 
   OptionalLoc = Locs.getRegisterLocation(13);
-  EXPECT_TRUE(OptionalLoc.has_value());
+  EXPECT_TRUE(OptionalLoc.hasValue());
   EXPECT_EQ(*OptionalLoc, Reg13Loc);
 
   OptionalLoc = Locs.getRegisterLocation(14);
-  EXPECT_TRUE(OptionalLoc.has_value());
+  EXPECT_TRUE(OptionalLoc.hasValue());
   EXPECT_EQ(*OptionalLoc, Reg14Loc);
 
   // Verify registers are correctly removed when multiple exist in the list.
   Locs.removeRegisterLocation(13);
-  EXPECT_FALSE(Locs.getRegisterLocation(13).has_value());
+  EXPECT_FALSE(Locs.getRegisterLocation(13).hasValue());
   EXPECT_TRUE(Locs.hasLocations());
   expectDumpResult(Locs, "reg12=[CFA+4], reg14=same");
   Locs.removeRegisterLocation(14);
-  EXPECT_FALSE(Locs.getRegisterLocation(14).has_value());
+  EXPECT_FALSE(Locs.getRegisterLocation(14).hasValue());
   EXPECT_TRUE(Locs.hasLocations());
   expectDumpResult(Locs, "reg12=[CFA+4]");
   Locs.removeRegisterLocation(12);
-  EXPECT_FALSE(Locs.getRegisterLocation(12).has_value());
+  EXPECT_FALSE(Locs.getRegisterLocation(12).hasValue());
   EXPECT_FALSE(Locs.hasLocations());
   expectDumpResult(Locs, "");
 }

diff  --git a/llvm/unittests/DebugInfo/DWARF/DWARFDebugInfoTest.cpp b/llvm/unittests/DebugInfo/DWARF/DWARFDebugInfoTest.cpp
index e4c65c0414635..367e89e4970d3 100644
--- a/llvm/unittests/DebugInfo/DWARF/DWARFDebugInfoTest.cpp
+++ b/llvm/unittests/DebugInfo/DWARF/DWARFDebugInfoTest.cpp
@@ -252,32 +252,32 @@ void TestAllForms() {
   FormValue = DieDG.find(Attr_DW_FORM_block);
   EXPECT_TRUE((bool)FormValue);
   BlockDataOpt = FormValue->getAsBlock();
-  EXPECT_TRUE(BlockDataOpt.has_value());
-  ExtractedBlockData = *BlockDataOpt;
+  EXPECT_TRUE(BlockDataOpt.hasValue());
+  ExtractedBlockData = BlockDataOpt.getValue();
   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
 
   FormValue = DieDG.find(Attr_DW_FORM_block1);
   EXPECT_TRUE((bool)FormValue);
   BlockDataOpt = FormValue->getAsBlock();
-  EXPECT_TRUE(BlockDataOpt.has_value());
-  ExtractedBlockData = *BlockDataOpt;
+  EXPECT_TRUE(BlockDataOpt.hasValue());
+  ExtractedBlockData = BlockDataOpt.getValue();
   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
 
   FormValue = DieDG.find(Attr_DW_FORM_block2);
   EXPECT_TRUE((bool)FormValue);
   BlockDataOpt = FormValue->getAsBlock();
-  EXPECT_TRUE(BlockDataOpt.has_value());
-  ExtractedBlockData = *BlockDataOpt;
+  EXPECT_TRUE(BlockDataOpt.hasValue());
+  ExtractedBlockData = BlockDataOpt.getValue();
   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
 
   FormValue = DieDG.find(Attr_DW_FORM_block4);
   EXPECT_TRUE((bool)FormValue);
   BlockDataOpt = FormValue->getAsBlock();
-  EXPECT_TRUE(BlockDataOpt.has_value());
-  ExtractedBlockData = *BlockDataOpt;
+  EXPECT_TRUE(BlockDataOpt.hasValue());
+  ExtractedBlockData = BlockDataOpt.getValue();
   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
 
@@ -286,8 +286,8 @@ void TestAllForms() {
     FormValue = DieDG.find(Attr_DW_FORM_data16);
     EXPECT_TRUE((bool)FormValue);
     BlockDataOpt = FormValue->getAsBlock();
-    EXPECT_TRUE(BlockDataOpt.has_value());
-    ExtractedBlockData = *BlockDataOpt;
+    EXPECT_TRUE(BlockDataOpt.hasValue());
+    ExtractedBlockData = BlockDataOpt.getValue();
     EXPECT_EQ(ExtractedBlockData.size(), 16u);
     EXPECT_TRUE(memcmp(ExtractedBlockData.data(), Data16, 16) == 0);
   }
@@ -989,21 +989,21 @@ template <uint16_t Version, class AddrType> void TestAddresses() {
     EXPECT_FALSE((bool)OptU64);
   } else {
     EXPECT_TRUE((bool)OptU64);
-    EXPECT_EQ(*OptU64, ActualHighPC);
+    EXPECT_EQ(OptU64.getValue(), ActualHighPC);
   }
   // Get the high PC as an unsigned constant. This should succeed if the high PC
   // was encoded as an offset and fail if the high PC was encoded as an address.
   OptU64 = toUnsigned(SubprogramDieLowHighPC.find(DW_AT_high_pc));
   if (SupportsHighPCAsOffset) {
     EXPECT_TRUE((bool)OptU64);
-    EXPECT_EQ(*OptU64, ActualHighPCOffset);
+    EXPECT_EQ(OptU64.getValue(), ActualHighPCOffset);
   } else {
     EXPECT_FALSE((bool)OptU64);
   }
 
   OptU64 = SubprogramDieLowHighPC.getHighPC(ActualLowPC);
   EXPECT_TRUE((bool)OptU64);
-  EXPECT_EQ(*OptU64, ActualHighPC);
+  EXPECT_EQ(OptU64.getValue(), ActualHighPC);
 
   EXPECT_TRUE(SubprogramDieLowHighPC.getLowAndHighPC(LowPC, HighPC, SectionIndex));
   EXPECT_EQ(LowPC, ActualLowPC);
@@ -1638,13 +1638,13 @@ TEST(DWARFDebugInfo, TestDwarfToFunctions) {
   // First test that we don't get valid values back when using an optional with
   // no value.
   Optional<DWARFFormValue> FormValOpt1 = DWARFFormValue();
-  EXPECT_FALSE(toString(FormValOpt1).has_value());
-  EXPECT_FALSE(toUnsigned(FormValOpt1).has_value());
-  EXPECT_FALSE(toReference(FormValOpt1).has_value());
-  EXPECT_FALSE(toSigned(FormValOpt1).has_value());
-  EXPECT_FALSE(toAddress(FormValOpt1).has_value());
-  EXPECT_FALSE(toSectionOffset(FormValOpt1).has_value());
-  EXPECT_FALSE(toBlock(FormValOpt1).has_value());
+  EXPECT_FALSE(toString(FormValOpt1).hasValue());
+  EXPECT_FALSE(toUnsigned(FormValOpt1).hasValue());
+  EXPECT_FALSE(toReference(FormValOpt1).hasValue());
+  EXPECT_FALSE(toSigned(FormValOpt1).hasValue());
+  EXPECT_FALSE(toAddress(FormValOpt1).hasValue());
+  EXPECT_FALSE(toSectionOffset(FormValOpt1).hasValue());
+  EXPECT_FALSE(toBlock(FormValOpt1).hasValue());
   EXPECT_EQ(nullptr, toString(FormValOpt1, nullptr));
   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt1, InvalidU64));
   EXPECT_EQ(InvalidU64, toReference(FormValOpt1, InvalidU64));
@@ -1657,13 +1657,13 @@ TEST(DWARFDebugInfo, TestDwarfToFunctions) {
   Optional<DWARFFormValue> FormValOpt2 =
       DWARFFormValue::createFromUValue(DW_FORM_addr, Address);
 
-  EXPECT_FALSE(toString(FormValOpt2).has_value());
-  EXPECT_FALSE(toUnsigned(FormValOpt2).has_value());
-  EXPECT_FALSE(toReference(FormValOpt2).has_value());
-  EXPECT_FALSE(toSigned(FormValOpt2).has_value());
-  EXPECT_TRUE(toAddress(FormValOpt2).has_value());
-  EXPECT_FALSE(toSectionOffset(FormValOpt2).has_value());
-  EXPECT_FALSE(toBlock(FormValOpt2).has_value());
+  EXPECT_FALSE(toString(FormValOpt2).hasValue());
+  EXPECT_FALSE(toUnsigned(FormValOpt2).hasValue());
+  EXPECT_FALSE(toReference(FormValOpt2).hasValue());
+  EXPECT_FALSE(toSigned(FormValOpt2).hasValue());
+  EXPECT_TRUE(toAddress(FormValOpt2).hasValue());
+  EXPECT_FALSE(toSectionOffset(FormValOpt2).hasValue());
+  EXPECT_FALSE(toBlock(FormValOpt2).hasValue());
   EXPECT_EQ(nullptr, toString(FormValOpt2, nullptr));
   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt2, InvalidU64));
   EXPECT_EQ(InvalidU64, toReference(FormValOpt2, InvalidU64));
@@ -1676,13 +1676,13 @@ TEST(DWARFDebugInfo, TestDwarfToFunctions) {
   Optional<DWARFFormValue> FormValOpt3 =
       DWARFFormValue::createFromUValue(DW_FORM_udata, UData8);
 
-  EXPECT_FALSE(toString(FormValOpt3).has_value());
-  EXPECT_TRUE(toUnsigned(FormValOpt3).has_value());
-  EXPECT_FALSE(toReference(FormValOpt3).has_value());
-  EXPECT_TRUE(toSigned(FormValOpt3).has_value());
-  EXPECT_FALSE(toAddress(FormValOpt3).has_value());
-  EXPECT_FALSE(toSectionOffset(FormValOpt3).has_value());
-  EXPECT_FALSE(toBlock(FormValOpt3).has_value());
+  EXPECT_FALSE(toString(FormValOpt3).hasValue());
+  EXPECT_TRUE(toUnsigned(FormValOpt3).hasValue());
+  EXPECT_FALSE(toReference(FormValOpt3).hasValue());
+  EXPECT_TRUE(toSigned(FormValOpt3).hasValue());
+  EXPECT_FALSE(toAddress(FormValOpt3).hasValue());
+  EXPECT_FALSE(toSectionOffset(FormValOpt3).hasValue());
+  EXPECT_FALSE(toBlock(FormValOpt3).hasValue());
   EXPECT_EQ(nullptr, toString(FormValOpt3, nullptr));
   EXPECT_EQ(UData8, toUnsigned(FormValOpt3, InvalidU64));
   EXPECT_EQ(InvalidU64, toReference(FormValOpt3, InvalidU64));
@@ -1695,13 +1695,13 @@ TEST(DWARFDebugInfo, TestDwarfToFunctions) {
   Optional<DWARFFormValue> FormValOpt4 =
       DWARFFormValue::createFromUValue(DW_FORM_ref_addr, RefData);
 
-  EXPECT_FALSE(toString(FormValOpt4).has_value());
-  EXPECT_FALSE(toUnsigned(FormValOpt4).has_value());
-  EXPECT_TRUE(toReference(FormValOpt4).has_value());
-  EXPECT_FALSE(toSigned(FormValOpt4).has_value());
-  EXPECT_FALSE(toAddress(FormValOpt4).has_value());
-  EXPECT_FALSE(toSectionOffset(FormValOpt4).has_value());
-  EXPECT_FALSE(toBlock(FormValOpt4).has_value());
+  EXPECT_FALSE(toString(FormValOpt4).hasValue());
+  EXPECT_FALSE(toUnsigned(FormValOpt4).hasValue());
+  EXPECT_TRUE(toReference(FormValOpt4).hasValue());
+  EXPECT_FALSE(toSigned(FormValOpt4).hasValue());
+  EXPECT_FALSE(toAddress(FormValOpt4).hasValue());
+  EXPECT_FALSE(toSectionOffset(FormValOpt4).hasValue());
+  EXPECT_FALSE(toBlock(FormValOpt4).hasValue());
   EXPECT_EQ(nullptr, toString(FormValOpt4, nullptr));
   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt4, InvalidU64));
   EXPECT_EQ(RefData, toReference(FormValOpt4, InvalidU64));
@@ -1714,13 +1714,13 @@ TEST(DWARFDebugInfo, TestDwarfToFunctions) {
   Optional<DWARFFormValue> FormValOpt5 =
       DWARFFormValue::createFromSValue(DW_FORM_udata, SData8);
 
-  EXPECT_FALSE(toString(FormValOpt5).has_value());
-  EXPECT_TRUE(toUnsigned(FormValOpt5).has_value());
-  EXPECT_FALSE(toReference(FormValOpt5).has_value());
-  EXPECT_TRUE(toSigned(FormValOpt5).has_value());
-  EXPECT_FALSE(toAddress(FormValOpt5).has_value());
-  EXPECT_FALSE(toSectionOffset(FormValOpt5).has_value());
-  EXPECT_FALSE(toBlock(FormValOpt5).has_value());
+  EXPECT_FALSE(toString(FormValOpt5).hasValue());
+  EXPECT_TRUE(toUnsigned(FormValOpt5).hasValue());
+  EXPECT_FALSE(toReference(FormValOpt5).hasValue());
+  EXPECT_TRUE(toSigned(FormValOpt5).hasValue());
+  EXPECT_FALSE(toAddress(FormValOpt5).hasValue());
+  EXPECT_FALSE(toSectionOffset(FormValOpt5).hasValue());
+  EXPECT_FALSE(toBlock(FormValOpt5).hasValue());
   EXPECT_EQ(nullptr, toString(FormValOpt5, nullptr));
   EXPECT_EQ((uint64_t)SData8, toUnsigned(FormValOpt5, InvalidU64));
   EXPECT_EQ(InvalidU64, toReference(FormValOpt5, InvalidU64));
@@ -1734,14 +1734,14 @@ TEST(DWARFDebugInfo, TestDwarfToFunctions) {
   Optional<DWARFFormValue> FormValOpt6 =
       DWARFFormValue::createFromBlockValue(DW_FORM_block1, Array);
 
-  EXPECT_FALSE(toString(FormValOpt6).has_value());
-  EXPECT_FALSE(toUnsigned(FormValOpt6).has_value());
-  EXPECT_FALSE(toReference(FormValOpt6).has_value());
-  EXPECT_FALSE(toSigned(FormValOpt6).has_value());
-  EXPECT_FALSE(toAddress(FormValOpt6).has_value());
-  EXPECT_FALSE(toSectionOffset(FormValOpt6).has_value());
+  EXPECT_FALSE(toString(FormValOpt6).hasValue());
+  EXPECT_FALSE(toUnsigned(FormValOpt6).hasValue());
+  EXPECT_FALSE(toReference(FormValOpt6).hasValue());
+  EXPECT_FALSE(toSigned(FormValOpt6).hasValue());
+  EXPECT_FALSE(toAddress(FormValOpt6).hasValue());
+  EXPECT_FALSE(toSectionOffset(FormValOpt6).hasValue());
   auto BlockOpt = toBlock(FormValOpt6);
-  EXPECT_TRUE(BlockOpt.has_value());
+  EXPECT_TRUE(BlockOpt.hasValue());
   EXPECT_EQ(*BlockOpt, Array);
   EXPECT_EQ(nullptr, toString(FormValOpt6, nullptr));
   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt6, InvalidU64));
@@ -1799,24 +1799,24 @@ TEST(DWARFDebugInfo, TestFindAttrs) {
   auto FuncDie = FuncSpecDie.getSibling();
 
   // Make sure that passing in an empty attribute list behave correctly.
-  EXPECT_FALSE(FuncDie.find(ArrayRef<dwarf::Attribute>()).has_value());
+  EXPECT_FALSE(FuncDie.find(ArrayRef<dwarf::Attribute>()).hasValue());
 
   // Make sure that passing in a list of attribute that are not contained
   // in the DIE returns nothing.
-  EXPECT_FALSE(FuncDie.find({DW_AT_low_pc, DW_AT_entry_pc}).has_value());
+  EXPECT_FALSE(FuncDie.find({DW_AT_low_pc, DW_AT_entry_pc}).hasValue());
 
   const dwarf::Attribute Attrs[] = {DW_AT_linkage_name,
                                     DW_AT_MIPS_linkage_name};
 
   // Make sure we can't extract the linkage name attributes when using
   // DWARFDie::find() since it won't check the DW_AT_specification DIE.
-  EXPECT_FALSE(FuncDie.find(Attrs).has_value());
+  EXPECT_FALSE(FuncDie.find(Attrs).hasValue());
 
   // Make sure we can extract the name from the specification die when using
   // DWARFDie::findRecursively() since it should recurse through the
   // DW_AT_specification DIE.
   auto NameOpt = FuncDie.findRecursively(Attrs);
-  EXPECT_TRUE(NameOpt.has_value());
+  EXPECT_TRUE(NameOpt.hasValue());
   EXPECT_EQ(DieMangled, toString(NameOpt, ""));
 }
 

diff  --git a/llvm/unittests/DebugInfo/DWARF/DWARFFormValueTest.cpp b/llvm/unittests/DebugInfo/DWARF/DWARFFormValueTest.cpp
index c81059c8d589f..9976777005a18 100644
--- a/llvm/unittests/DebugInfo/DWARF/DWARFFormValueTest.cpp
+++ b/llvm/unittests/DebugInfo/DWARF/DWARFFormValueTest.cpp
@@ -79,17 +79,17 @@ TEST(DWARFFormValue, SignedConstantForms) {
   auto Sign2 = createDataXFormValue<uint16_t>(DW_FORM_data2, -12345);
   auto Sign4 = createDataXFormValue<uint32_t>(DW_FORM_data4, -123456789);
   auto Sign8 = createDataXFormValue<uint64_t>(DW_FORM_data8, -1);
-  EXPECT_EQ(Sign1.getAsSignedConstant().value(), -123);
-  EXPECT_EQ(Sign2.getAsSignedConstant().value(), -12345);
-  EXPECT_EQ(Sign4.getAsSignedConstant().value(), -123456789);
-  EXPECT_EQ(Sign8.getAsSignedConstant().value(), -1);
+  EXPECT_EQ(Sign1.getAsSignedConstant().getValue(), -123);
+  EXPECT_EQ(Sign2.getAsSignedConstant().getValue(), -12345);
+  EXPECT_EQ(Sign4.getAsSignedConstant().getValue(), -123456789);
+  EXPECT_EQ(Sign8.getAsSignedConstant().getValue(), -1);
 
   // Check that we can handle big positive values, but that we return
   // an error just over the limit.
   auto UMax = createULEBFormValue(LLONG_MAX);
   auto TooBig = createULEBFormValue(uint64_t(LLONG_MAX) + 1);
-  EXPECT_EQ(UMax.getAsSignedConstant().value(), LLONG_MAX);
-  EXPECT_EQ(TooBig.getAsSignedConstant().has_value(), false);
+  EXPECT_EQ(UMax.getAsSignedConstant().getValue(), LLONG_MAX);
+  EXPECT_EQ(TooBig.getAsSignedConstant().hasValue(), false);
 
   // Sanity check some other forms.
   auto Data1 = createDataXFormValue<uint8_t>(DW_FORM_data1, 120);
@@ -100,14 +100,14 @@ TEST(DWARFFormValue, SignedConstantForms) {
   auto LEBMax = createSLEBFormValue(LLONG_MAX);
   auto LEB1 = createSLEBFormValue(-42);
   auto LEB2 = createSLEBFormValue(42);
-  EXPECT_EQ(Data1.getAsSignedConstant().value(), 120);
-  EXPECT_EQ(Data2.getAsSignedConstant().value(), 32000);
-  EXPECT_EQ(Data4.getAsSignedConstant().value(), 2000000000);
-  EXPECT_EQ(Data8.getAsSignedConstant().value(), 0x1234567812345678LL);
-  EXPECT_EQ(LEBMin.getAsSignedConstant().value(), LLONG_MIN);
-  EXPECT_EQ(LEBMax.getAsSignedConstant().value(), LLONG_MAX);
-  EXPECT_EQ(LEB1.getAsSignedConstant().value(), -42);
-  EXPECT_EQ(LEB2.getAsSignedConstant().value(), 42);
+  EXPECT_EQ(Data1.getAsSignedConstant().getValue(), 120);
+  EXPECT_EQ(Data2.getAsSignedConstant().getValue(), 32000);
+  EXPECT_EQ(Data4.getAsSignedConstant().getValue(), 2000000000);
+  EXPECT_EQ(Data8.getAsSignedConstant().getValue(), 0x1234567812345678LL);
+  EXPECT_EQ(LEBMin.getAsSignedConstant().getValue(), LLONG_MIN);
+  EXPECT_EQ(LEBMax.getAsSignedConstant().getValue(), LLONG_MAX);
+  EXPECT_EQ(LEB1.getAsSignedConstant().getValue(), -42);
+  EXPECT_EQ(LEB2.getAsSignedConstant().getValue(), 42);
 
   // Data16 is a little tricky.
   char Cksum[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};

diff  --git a/llvm/unittests/DebugInfo/GSYM/GSYMTest.cpp b/llvm/unittests/DebugInfo/GSYM/GSYMTest.cpp
index bfe66f0cef1c2..977231d81143a 100644
--- a/llvm/unittests/DebugInfo/GSYM/GSYMTest.cpp
+++ b/llvm/unittests/DebugInfo/GSYM/GSYMTest.cpp
@@ -1349,8 +1349,8 @@ TEST(GSYMTest, TestDWARFFunctionWithAddresses) {
   auto ExpFI = GR->getFunctionInfo(0x1000);
   ASSERT_THAT_EXPECTED(ExpFI, Succeeded());
   ASSERT_EQ(ExpFI->Range, AddressRange(0x1000, 0x2000));
-  EXPECT_FALSE(ExpFI->OptLineTable.has_value());
-  EXPECT_FALSE(ExpFI->Inline.has_value());
+  EXPECT_FALSE(ExpFI->OptLineTable.hasValue());
+  EXPECT_FALSE(ExpFI->Inline.hasValue());
 }
 
 TEST(GSYMTest, TestDWARFFunctionWithAddressAndOffset) {
@@ -1426,8 +1426,8 @@ TEST(GSYMTest, TestDWARFFunctionWithAddressAndOffset) {
   auto ExpFI = GR->getFunctionInfo(0x1000);
   ASSERT_THAT_EXPECTED(ExpFI, Succeeded());
   ASSERT_EQ(ExpFI->Range, AddressRange(0x1000, 0x2000));
-  EXPECT_FALSE(ExpFI->OptLineTable.has_value());
-  EXPECT_FALSE(ExpFI->Inline.has_value());
+  EXPECT_FALSE(ExpFI->OptLineTable.hasValue());
+  EXPECT_FALSE(ExpFI->Inline.hasValue());
 }
 
 TEST(GSYMTest, TestDWARFStructMethodNoMangled) {
@@ -1533,8 +1533,8 @@ TEST(GSYMTest, TestDWARFStructMethodNoMangled) {
   auto ExpFI = GR->getFunctionInfo(0x1000);
   ASSERT_THAT_EXPECTED(ExpFI, Succeeded());
   ASSERT_EQ(ExpFI->Range, AddressRange(0x1000, 0x2000));
-  EXPECT_FALSE(ExpFI->OptLineTable.has_value());
-  EXPECT_FALSE(ExpFI->Inline.has_value());
+  EXPECT_FALSE(ExpFI->OptLineTable.hasValue());
+  EXPECT_FALSE(ExpFI->Inline.hasValue());
   StringRef MethodName = GR->getString(ExpFI->Name);
   EXPECT_EQ(MethodName, "Foo::dump");
 }
@@ -1638,8 +1638,8 @@ TEST(GSYMTest, TestDWARFTextRanges) {
   auto ExpFI = GR->getFunctionInfo(0x1000);
   ASSERT_THAT_EXPECTED(ExpFI, Succeeded());
   ASSERT_EQ(ExpFI->Range, AddressRange(0x1000, 0x2000));
-  EXPECT_FALSE(ExpFI->OptLineTable.has_value());
-  EXPECT_FALSE(ExpFI->Inline.has_value());
+  EXPECT_FALSE(ExpFI->OptLineTable.hasValue());
+  EXPECT_FALSE(ExpFI->Inline.hasValue());
   StringRef MethodName = GR->getString(ExpFI->Name);
   EXPECT_EQ(MethodName, "main");
 }
@@ -1667,8 +1667,8 @@ TEST(GSYMTest, TestEmptySymbolEndAddressOfTextRanges) {
   auto ExpFI = GR->getFunctionInfo(0x1500);
   ASSERT_THAT_EXPECTED(ExpFI, Succeeded());
   ASSERT_EQ(ExpFI->Range, AddressRange(0x1500, 0x2000));
-  EXPECT_FALSE(ExpFI->OptLineTable.has_value());
-  EXPECT_FALSE(ExpFI->Inline.has_value());
+  EXPECT_FALSE(ExpFI->OptLineTable.hasValue());
+  EXPECT_FALSE(ExpFI->Inline.hasValue());
   StringRef MethodName = GR->getString(ExpFI->Name);
   EXPECT_EQ(MethodName, "symbol");
 }
@@ -1836,8 +1836,8 @@ TEST(GSYMTest, TestDWARFInlineInfo) {
   auto ExpFI = GR->getFunctionInfo(0x1000);
   ASSERT_THAT_EXPECTED(ExpFI, Succeeded());
   ASSERT_EQ(ExpFI->Range, AddressRange(0x1000, 0x2000));
-  EXPECT_TRUE(ExpFI->OptLineTable.has_value());
-  EXPECT_TRUE(ExpFI->Inline.has_value());
+  EXPECT_TRUE(ExpFI->OptLineTable.hasValue());
+  EXPECT_TRUE(ExpFI->Inline.hasValue());
   StringRef MethodName = GR->getString(ExpFI->Name);
   EXPECT_EQ(MethodName, "main");
 
@@ -2122,14 +2122,14 @@ TEST(GSYMTest, TestDWARFNoLines) {
   ASSERT_THAT_EXPECTED(ExpFI, Succeeded());
   ASSERT_EQ(ExpFI->Range, AddressRange(0x3000, 0x4000));
   // Make sure we have no line table.
-  EXPECT_FALSE(ExpFI->OptLineTable.has_value());
+  EXPECT_FALSE(ExpFI->OptLineTable.hasValue());
   MethodName = GR->getString(ExpFI->Name);
   EXPECT_EQ(MethodName, "no_lines_no_decl");
 
   ExpFI = GR->getFunctionInfo(0x4000);
   ASSERT_THAT_EXPECTED(ExpFI, Succeeded());
   ASSERT_EQ(ExpFI->Range, AddressRange(0x4000, 0x5000));
-  EXPECT_TRUE(ExpFI->OptLineTable.has_value());
+  EXPECT_TRUE(ExpFI->OptLineTable.hasValue());
   MethodName = GR->getString(ExpFI->Name);
   EXPECT_EQ(MethodName, "no_lines_with_decl");
   // Make sure we have one line table entry that uses the DW_AT_decl_file/line

diff  --git a/llvm/unittests/FileCheck/FileCheckTest.cpp b/llvm/unittests/FileCheck/FileCheckTest.cpp
index 39230c49bdbae..f3b5d3d2aaab6 100644
--- a/llvm/unittests/FileCheck/FileCheckTest.cpp
+++ b/llvm/unittests/FileCheck/FileCheckTest.cpp
@@ -766,8 +766,8 @@ TEST_F(FileCheckTest, NumericVariable) {
   ASSERT_TRUE(Value);
   EXPECT_EQ(925, cantFail(Value->getSignedValue()));
   // getStringValue should return the same memory not just the same characters.
-  EXPECT_EQ(StringValue.begin(), FooVar.getStringValue()->begin());
-  EXPECT_EQ(StringValue.end(), FooVar.getStringValue()->end());
+  EXPECT_EQ(StringValue.begin(), FooVar.getStringValue().getValue().begin());
+  EXPECT_EQ(StringValue.end(), FooVar.getStringValue().getValue().end());
   EvalResult = FooVarUse.eval();
   ASSERT_THAT_EXPECTED(EvalResult, Succeeded());
   EXPECT_EQ(925, cantFail(EvalResult->getSignedValue()));

diff  --git a/llvm/unittests/IR/MetadataTest.cpp b/llvm/unittests/IR/MetadataTest.cpp
index a755dfa81ab44..0c73aaa69b31f 100644
--- a/llvm/unittests/IR/MetadataTest.cpp
+++ b/llvm/unittests/IR/MetadataTest.cpp
@@ -1045,51 +1045,52 @@ TEST_F(DILocationTest, cloneTemporary) {
 }
 
 TEST_F(DILocationTest, discriminatorEncoding) {
-  EXPECT_EQ(0U, DILocation::encodeDiscriminator(0, 0, 0).value());
+  EXPECT_EQ(0U, DILocation::encodeDiscriminator(0, 0, 0).getValue());
 
   // Encode base discriminator as a component: lsb is 0, then the value.
   // The other components are all absent, so we leave all the other bits 0.
-  EXPECT_EQ(2U, DILocation::encodeDiscriminator(1, 0, 0).value());
+  EXPECT_EQ(2U, DILocation::encodeDiscriminator(1, 0, 0).getValue());
 
   // Base discriminator component is empty, so lsb is 1. Next component is not
   // empty, so its lsb is 0, then its value (1). Next component is empty.
   // So the bit pattern is 101.
-  EXPECT_EQ(5U, DILocation::encodeDiscriminator(0, 1, 0).value());
+  EXPECT_EQ(5U, DILocation::encodeDiscriminator(0, 1, 0).getValue());
 
   // First 2 components are empty, so the bit pattern is 11. Then the
   // next component - ending up with 1011.
-  EXPECT_EQ(0xbU, DILocation::encodeDiscriminator(0, 0, 1).value());
+  EXPECT_EQ(0xbU, DILocation::encodeDiscriminator(0, 0, 1).getValue());
 
   // The bit pattern for the first 2 components is 11. The next bit is 0,
   // because the last component is not empty. We have 29 bits usable for
   // encoding, but we cap it at 12 bits uniformously for all components. We
   // encode the last component over 14 bits.
-  EXPECT_EQ(0xfffbU, DILocation::encodeDiscriminator(0, 0, 0xfff).value());
+  EXPECT_EQ(0xfffbU, DILocation::encodeDiscriminator(0, 0, 0xfff).getValue());
 
-  EXPECT_EQ(0x102U, DILocation::encodeDiscriminator(1, 1, 0).value());
+  EXPECT_EQ(0x102U, DILocation::encodeDiscriminator(1, 1, 0).getValue());
 
-  EXPECT_EQ(0x13eU, DILocation::encodeDiscriminator(0x1f, 1, 0).value());
+  EXPECT_EQ(0x13eU, DILocation::encodeDiscriminator(0x1f, 1, 0).getValue());
 
-  EXPECT_EQ(0x87feU, DILocation::encodeDiscriminator(0x1ff, 1, 0).value());
+  EXPECT_EQ(0x87feU, DILocation::encodeDiscriminator(0x1ff, 1, 0).getValue());
 
-  EXPECT_EQ(0x1f3eU, DILocation::encodeDiscriminator(0x1f, 0x1f, 0).value());
+  EXPECT_EQ(0x1f3eU, DILocation::encodeDiscriminator(0x1f, 0x1f, 0).getValue());
 
-  EXPECT_EQ(0x3ff3eU, DILocation::encodeDiscriminator(0x1f, 0x1ff, 0).value());
+  EXPECT_EQ(0x3ff3eU,
+            DILocation::encodeDiscriminator(0x1f, 0x1ff, 0).getValue());
 
   EXPECT_EQ(0x1ff87feU,
-            DILocation::encodeDiscriminator(0x1ff, 0x1ff, 0).value());
+            DILocation::encodeDiscriminator(0x1ff, 0x1ff, 0).getValue());
 
   EXPECT_EQ(0xfff9f3eU,
-            DILocation::encodeDiscriminator(0x1f, 0x1f, 0xfff).value());
+            DILocation::encodeDiscriminator(0x1f, 0x1f, 0xfff).getValue());
 
   EXPECT_EQ(0xffc3ff3eU,
-            DILocation::encodeDiscriminator(0x1f, 0x1ff, 0x1ff).value());
+            DILocation::encodeDiscriminator(0x1f, 0x1ff, 0x1ff).getValue());
 
   EXPECT_EQ(0xffcf87feU,
-            DILocation::encodeDiscriminator(0x1ff, 0x1f, 0x1ff).value());
+            DILocation::encodeDiscriminator(0x1ff, 0x1f, 0x1ff).getValue());
 
   EXPECT_EQ(0xe1ff87feU,
-            DILocation::encodeDiscriminator(0x1ff, 0x1ff, 7).value());
+            DILocation::encodeDiscriminator(0x1ff, 0x1ff, 7).getValue());
 }
 
 TEST_F(DILocationTest, discriminatorEncodingNegativeTests) {
@@ -1112,36 +1113,36 @@ TEST_F(DILocationTest, discriminatorSpecialCases) {
   EXPECT_EQ(0U, L1->getBaseDiscriminator());
   EXPECT_EQ(1U, L1->getDuplicationFactor());
 
-  EXPECT_EQ(L1, L1->cloneWithBaseDiscriminator(0).value());
-  EXPECT_EQ(L1, L1->cloneByMultiplyingDuplicationFactor(0).value());
-  EXPECT_EQ(L1, L1->cloneByMultiplyingDuplicationFactor(1).value());
+  EXPECT_EQ(L1, L1->cloneWithBaseDiscriminator(0).getValue());
+  EXPECT_EQ(L1, L1->cloneByMultiplyingDuplicationFactor(0).getValue());
+  EXPECT_EQ(L1, L1->cloneByMultiplyingDuplicationFactor(1).getValue());
 
-  auto L2 = L1->cloneWithBaseDiscriminator(1).value();
+  auto L2 = L1->cloneWithBaseDiscriminator(1).getValue();
   EXPECT_EQ(0U, L1->getBaseDiscriminator());
   EXPECT_EQ(1U, L1->getDuplicationFactor());
 
   EXPECT_EQ(1U, L2->getBaseDiscriminator());
   EXPECT_EQ(1U, L2->getDuplicationFactor());
 
-  auto L3 = L2->cloneByMultiplyingDuplicationFactor(2).value();
+  auto L3 = L2->cloneByMultiplyingDuplicationFactor(2).getValue();
   EXPECT_EQ(1U, L3->getBaseDiscriminator());
   EXPECT_EQ(2U, L3->getDuplicationFactor());
 
-  EXPECT_EQ(L2, L2->cloneByMultiplyingDuplicationFactor(1).value());
+  EXPECT_EQ(L2, L2->cloneByMultiplyingDuplicationFactor(1).getValue());
 
-  auto L4 = L3->cloneByMultiplyingDuplicationFactor(4).value();
+  auto L4 = L3->cloneByMultiplyingDuplicationFactor(4).getValue();
   EXPECT_EQ(1U, L4->getBaseDiscriminator());
   EXPECT_EQ(8U, L4->getDuplicationFactor());
 
-  auto L5 = L4->cloneWithBaseDiscriminator(2).value();
+  auto L5 = L4->cloneWithBaseDiscriminator(2).getValue();
   EXPECT_EQ(2U, L5->getBaseDiscriminator());
   EXPECT_EQ(8U, L5->getDuplicationFactor());
 
   // Check extreme cases
-  auto L6 = L1->cloneWithBaseDiscriminator(0xfff).value();
+  auto L6 = L1->cloneWithBaseDiscriminator(0xfff).getValue();
   EXPECT_EQ(0xfffU, L6->getBaseDiscriminator());
   EXPECT_EQ(0xfffU, L6->cloneByMultiplyingDuplicationFactor(0xfff)
-                        .value()
+                        .getValue()
                         ->getDuplicationFactor());
 
   // Check we return None for unencodable cases.
@@ -2932,24 +2933,22 @@ TEST_F(DIExpressionTest, createFragmentExpression) {
 #define EXPECT_VALID_FRAGMENT(Offset, Size, ...)                               \
   do {                                                                         \
     uint64_t Elements[] = {__VA_ARGS__};                                       \
-    DIExpression *Expression = DIExpression::get(Context, Elements);           \
-    EXPECT_TRUE(                                                               \
-        DIExpression::createFragmentExpression(Expression, Offset, Size)       \
-            .has_value());                                                     \
+    DIExpression* Expression = DIExpression::get(Context, Elements);           \
+    EXPECT_TRUE(DIExpression::createFragmentExpression(                        \
+      Expression, Offset, Size).hasValue());                                   \
   } while (false)
 #define EXPECT_INVALID_FRAGMENT(Offset, Size, ...)                             \
   do {                                                                         \
     uint64_t Elements[] = {__VA_ARGS__};                                       \
-    DIExpression *Expression = DIExpression::get(Context, Elements);           \
-    EXPECT_FALSE(                                                              \
-        DIExpression::createFragmentExpression(Expression, Offset, Size)       \
-            .has_value());                                                     \
+    DIExpression* Expression = DIExpression::get(Context, Elements);           \
+    EXPECT_FALSE(DIExpression::createFragmentExpression(                       \
+      Expression, Offset, Size).hasValue());                                   \
   } while (false)
 
   // createFragmentExpression adds correct ops.
   Optional<DIExpression*> R = DIExpression::createFragmentExpression(
     DIExpression::get(Context, {}), 0, 32);
-  EXPECT_EQ(R.has_value(), true);
+  EXPECT_EQ(R.hasValue(), true);
   EXPECT_EQ(3u, (*R)->getNumElements());
   EXPECT_EQ(dwarf::DW_OP_LLVM_fragment, (*R)->getElement(0));
   EXPECT_EQ(0u, (*R)->getElement(1));
@@ -3456,20 +3455,20 @@ TEST_F(FunctionAttachmentTest, Verifier) {
 
 TEST_F(FunctionAttachmentTest, RealEntryCount) {
   Function *F = getFunction("foo");
-  EXPECT_FALSE(F->getEntryCount().has_value());
+  EXPECT_FALSE(F->getEntryCount().hasValue());
   F->setEntryCount(12304, Function::PCT_Real);
   auto Count = F->getEntryCount();
-  EXPECT_TRUE(Count.has_value());
+  EXPECT_TRUE(Count.hasValue());
   EXPECT_EQ(12304u, Count->getCount());
   EXPECT_EQ(Function::PCT_Real, Count->getType());
 }
 
 TEST_F(FunctionAttachmentTest, SyntheticEntryCount) {
   Function *F = getFunction("bar");
-  EXPECT_FALSE(F->getEntryCount().has_value());
+  EXPECT_FALSE(F->getEntryCount().hasValue());
   F->setEntryCount(123, Function::PCT_Synthetic);
   auto Count = F->getEntryCount(true /*allow synthetic*/);
-  EXPECT_TRUE(Count.has_value());
+  EXPECT_TRUE(Count.hasValue());
   EXPECT_EQ(123u, Count->getCount());
   EXPECT_EQ(Function::PCT_Synthetic, Count->getType());
 }

diff  --git a/llvm/unittests/IR/VPIntrinsicTest.cpp b/llvm/unittests/IR/VPIntrinsicTest.cpp
index 34123efd18ba3..62e16df1f4916 100644
--- a/llvm/unittests/IR/VPIntrinsicTest.cpp
+++ b/llvm/unittests/IR/VPIntrinsicTest.cpp
@@ -128,25 +128,25 @@ class VPIntrinsicTest : public testing::Test {
 TEST_F(VPIntrinsicTest, VPIntrinsicsDefScopes) {
   Optional<Intrinsic::ID> ScopeVPID;
 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...)                                 \
-  ASSERT_FALSE(ScopeVPID.has_value());                                         \
+  ASSERT_FALSE(ScopeVPID.hasValue());                                          \
   ScopeVPID = Intrinsic::VPID;
 #define END_REGISTER_VP_INTRINSIC(VPID)                                        \
-  ASSERT_TRUE(ScopeVPID.has_value());                                          \
-  ASSERT_EQ(*ScopeVPID, Intrinsic::VPID);                                      \
+  ASSERT_TRUE(ScopeVPID.hasValue());                                           \
+  ASSERT_EQ(ScopeVPID.getValue(), Intrinsic::VPID);                            \
   ScopeVPID = None;
 
   Optional<ISD::NodeType> ScopeOPC;
 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...)                                   \
-  ASSERT_FALSE(ScopeOPC.has_value());                                          \
+  ASSERT_FALSE(ScopeOPC.hasValue());                                           \
   ScopeOPC = ISD::SDOPC;
 #define END_REGISTER_VP_SDNODE(SDOPC)                                          \
-  ASSERT_TRUE(ScopeOPC.has_value());                                           \
-  ASSERT_EQ(*ScopeOPC, ISD::SDOPC);                                            \
+  ASSERT_TRUE(ScopeOPC.hasValue());                                            \
+  ASSERT_EQ(ScopeOPC.getValue(), ISD::SDOPC);                                  \
   ScopeOPC = None;
 #include "llvm/IR/VPIntrinsics.def"
 
-  ASSERT_FALSE(ScopeVPID.has_value());
-  ASSERT_FALSE(ScopeOPC.has_value());
+  ASSERT_FALSE(ScopeVPID.hasValue());
+  ASSERT_FALSE(ScopeOPC.hasValue());
 }
 
 /// Check that every VP intrinsic in the test module is recognized as a VP
@@ -233,8 +233,8 @@ TEST_F(VPIntrinsicTest, GetParamPos) {
     ASSERT_TRUE(F.isIntrinsic());
     Optional<unsigned> MaskParamPos =
         VPIntrinsic::getMaskParamPos(F.getIntrinsicID());
-    if (MaskParamPos) {
-      Type *MaskParamType = F.getArg(*MaskParamPos)->getType();
+    if (MaskParamPos.hasValue()) {
+      Type *MaskParamType = F.getArg(MaskParamPos.getValue())->getType();
       ASSERT_TRUE(MaskParamType->isVectorTy());
       ASSERT_TRUE(
           cast<VectorType>(MaskParamType)->getElementType()->isIntegerTy(1));
@@ -242,8 +242,8 @@ TEST_F(VPIntrinsicTest, GetParamPos) {
 
     Optional<unsigned> VecLenParamPos =
         VPIntrinsic::getVectorLengthParamPos(F.getIntrinsicID());
-    if (VecLenParamPos) {
-      Type *VecLenParamType = F.getArg(*VecLenParamPos)->getType();
+    if (VecLenParamPos.hasValue()) {
+      Type *VecLenParamType = F.getArg(VecLenParamPos.getValue())->getType();
       ASSERT_TRUE(VecLenParamType->isIntegerTy(32));
     }
   }
@@ -406,13 +406,13 @@ TEST_F(VPIntrinsicTest, VPReductions) {
 
     if (!VPReductionIntrinsic::isVPReduction(ID)) {
       EXPECT_EQ(VPRedI, nullptr);
-      EXPECT_EQ(VPReductionIntrinsic::getStartParamPos(ID).has_value(), false);
-      EXPECT_EQ(VPReductionIntrinsic::getVectorParamPos(ID).has_value(), false);
+      EXPECT_EQ(VPReductionIntrinsic::getStartParamPos(ID).hasValue(), false);
+      EXPECT_EQ(VPReductionIntrinsic::getVectorParamPos(ID).hasValue(), false);
       continue;
     }
 
-    EXPECT_EQ(VPReductionIntrinsic::getStartParamPos(ID).has_value(), true);
-    EXPECT_EQ(VPReductionIntrinsic::getVectorParamPos(ID).has_value(), true);
+    EXPECT_EQ(VPReductionIntrinsic::getStartParamPos(ID).hasValue(), true);
+    EXPECT_EQ(VPReductionIntrinsic::getVectorParamPos(ID).hasValue(), true);
     ASSERT_NE(VPRedI, nullptr);
     EXPECT_EQ(VPReductionIntrinsic::getStartParamPos(ID),
               VPRedI->getStartParamPos());

diff  --git a/llvm/unittests/InterfaceStub/ELFYAMLTest.cpp b/llvm/unittests/InterfaceStub/ELFYAMLTest.cpp
index d347e1755cea3..404dfd3e6b686 100644
--- a/llvm/unittests/InterfaceStub/ELFYAMLTest.cpp
+++ b/llvm/unittests/InterfaceStub/ELFYAMLTest.cpp
@@ -47,9 +47,9 @@ TEST(ElfYamlTextAPI, YAMLReadableTBE) {
   ASSERT_THAT_ERROR(StubOrErr.takeError(), Succeeded());
   std::unique_ptr<IFSStub> Stub = std::move(StubOrErr.get());
   EXPECT_NE(Stub.get(), nullptr);
-  EXPECT_FALSE(Stub->SoName.has_value());
-  EXPECT_TRUE(Stub->Target.Arch.has_value());
-  EXPECT_EQ(Stub->Target.Arch.value(), (uint16_t)llvm::ELF::EM_X86_64);
+  EXPECT_FALSE(Stub->SoName.hasValue());
+  EXPECT_TRUE(Stub->Target.Arch.hasValue());
+  EXPECT_EQ(Stub->Target.Arch.getValue(), (uint16_t)llvm::ELF::EM_X86_64);
   EXPECT_EQ(Stub->NeededLibs.size(), 3u);
   EXPECT_STREQ(Stub->NeededLibs[0].c_str(), "libc.so");
   EXPECT_STREQ(Stub->NeededLibs[1].c_str(), "libfoo.so");
@@ -94,24 +94,24 @@ TEST(ElfYamlTextAPI, YAMLReadsTBESymbols) {
   EXPECT_EQ(SymBaz.Type, IFSSymbolType::TLS);
   EXPECT_FALSE(SymBaz.Undefined);
   EXPECT_FALSE(SymBaz.Weak);
-  EXPECT_FALSE(SymBaz.Warning.has_value());
+  EXPECT_FALSE(SymBaz.Warning.hasValue());
 
   IFSSymbol const &SymFoo = *Iterator++;
   EXPECT_STREQ(SymFoo.Name.c_str(), "foo");
-  EXPECT_FALSE(SymFoo.Size.has_value());
+  EXPECT_FALSE(SymFoo.Size.hasValue());
   EXPECT_EQ(SymFoo.Type, IFSSymbolType::Func);
   EXPECT_FALSE(SymFoo.Undefined);
   EXPECT_FALSE(SymFoo.Weak);
-  EXPECT_TRUE(SymFoo.Warning.has_value());
+  EXPECT_TRUE(SymFoo.Warning.hasValue());
   EXPECT_STREQ(SymFoo.Warning->c_str(), "Deprecated!");
 
   IFSSymbol const &SymNor = *Iterator++;
   EXPECT_STREQ(SymNor.Name.c_str(), "nor");
-  EXPECT_FALSE(SymNor.Size.has_value());
+  EXPECT_FALSE(SymNor.Size.hasValue());
   EXPECT_EQ(SymNor.Type, IFSSymbolType::NoType);
   EXPECT_TRUE(SymNor.Undefined);
   EXPECT_FALSE(SymNor.Weak);
-  EXPECT_FALSE(SymNor.Warning.has_value());
+  EXPECT_FALSE(SymNor.Warning.hasValue());
 
   IFSSymbol const &SymNot = *Iterator++;
   EXPECT_STREQ(SymNot.Name.c_str(), "not");

diff  --git a/llvm/unittests/Object/XCOFFObjectFileTest.cpp b/llvm/unittests/Object/XCOFFObjectFileTest.cpp
index cf2be43c33988..41662be0b6dbb 100644
--- a/llvm/unittests/Object/XCOFFObjectFileTest.cpp
+++ b/llvm/unittests/Object/XCOFFObjectFileTest.cpp
@@ -83,16 +83,16 @@ TEST(XCOFFObjectFileTest, XCOFFTracebackTableAPIGeneral) {
   EXPECT_TRUE(TT.hasParmsOnStack());
 
   ASSERT_TRUE(TT.getParmsType());
-  EXPECT_EQ(TT.getParmsType().value(), "i, f, d");
+  EXPECT_EQ(TT.getParmsType().getValue(), "i, f, d");
 
   ASSERT_TRUE(TT.getTraceBackTableOffset());
-  EXPECT_EQ(TT.getTraceBackTableOffset().value(), 64u);
+  EXPECT_EQ(TT.getTraceBackTableOffset().getValue(), 64u);
 
   EXPECT_FALSE(TT.getHandlerMask());
 
   ASSERT_TRUE(TT.getFunctionName());
-  EXPECT_EQ(TT.getFunctionName().value(), "add_all");
-  EXPECT_EQ(TT.getFunctionName()->size(), 7u);
+  EXPECT_EQ(TT.getFunctionName().getValue(), "add_all");
+  EXPECT_EQ(TT.getFunctionName().getValue().size(), 7u);
 
   EXPECT_FALSE(TT.getAllocaRegister());
   EXPECT_EQ(Size, 25u);
@@ -171,11 +171,11 @@ TEST(XCOFFObjectFileTest, XCOFFTracebackTableAPIControlledStorageInfoDisp) {
   XCOFFTracebackTable TT = *TTOrErr;
   EXPECT_TRUE(TT.hasControlledStorage());
   ASSERT_TRUE(TT.getNumOfCtlAnchors());
-  EXPECT_EQ(TT.getNumOfCtlAnchors().value(), 2u);
+  EXPECT_EQ(TT.getNumOfCtlAnchors().getValue(), 2u);
 
   ASSERT_TRUE(TT.getControlledStorageInfoDisp());
 
-  SmallVector<uint32_t, 8> Disp = TT.getControlledStorageInfoDisp().value();
+  SmallVector<uint32_t, 8> Disp = TT.getControlledStorageInfoDisp().getValue();
 
   ASSERT_EQ(Disp.size(), 2UL);
   EXPECT_EQ(Disp[0], 0x05050000u);
@@ -207,10 +207,10 @@ TEST(XCOFFObjectFileTest, XCOFFTracebackTableAPIHasVectorInfo) {
   EXPECT_TRUE(TT.hasExtensionTable());
 
   ASSERT_TRUE(TT.getParmsType());
-  EXPECT_EQ(TT.getParmsType().value(), "v, i, f, i, d, i, v");
+  EXPECT_EQ(TT.getParmsType().getValue(), "v, i, f, i, d, i, v");
 
   ASSERT_TRUE(TT.getVectorExt());
-  TBVectorExt VecExt = TT.getVectorExt().value();
+  TBVectorExt VecExt = TT.getVectorExt().getValue();
 
   EXPECT_EQ(VecExt.getNumberOfVRSaved(), 0);
   EXPECT_TRUE(VecExt.isVRSavedOnStack());
@@ -240,10 +240,10 @@ TEST(XCOFFObjectFileTest, XCOFFTracebackTableAPIHasVectorInfo1) {
   XCOFFTracebackTable TT = *TTOrErr;
 
   ASSERT_TRUE(TT.getParmsType());
-  EXPECT_EQ(TT.getParmsType().value(), "v, i, f, i, d, i, v, v");
+  EXPECT_EQ(TT.getParmsType().getValue(), "v, i, f, i, d, i, v, v");
 
   ASSERT_TRUE(TT.getVectorExt());
-  TBVectorExt VecExt = TT.getVectorExt().value();
+  TBVectorExt VecExt = TT.getVectorExt().getValue();
 
   EXPECT_EQ(VecExt.getNumberOfVRSaved(), 4);
   EXPECT_FALSE(VecExt.isVRSavedOnStack());

diff  --git a/llvm/unittests/ObjectYAML/DWARFYAMLTest.cpp b/llvm/unittests/ObjectYAML/DWARFYAMLTest.cpp
index 09c9e352460de..91febffdfcc3a 100644
--- a/llvm/unittests/ObjectYAML/DWARFYAMLTest.cpp
+++ b/llvm/unittests/ObjectYAML/DWARFYAMLTest.cpp
@@ -91,8 +91,8 @@ TEST(DebugPubSection, TestDebugPubSection) {
   DWARFYAML::Data Data;
   ASSERT_THAT_ERROR(parseDWARFYAML(Yaml, Data), Succeeded());
 
-  ASSERT_TRUE(Data.PubNames.has_value());
-  DWARFYAML::PubSection PubNames = Data.PubNames.value();
+  ASSERT_TRUE(Data.PubNames.hasValue());
+  DWARFYAML::PubSection PubNames = Data.PubNames.getValue();
 
   ASSERT_EQ(PubNames.Entries.size(), 2u);
   EXPECT_EQ((uint32_t)PubNames.Entries[0].DieOffset, 0x1234u);
@@ -100,8 +100,8 @@ TEST(DebugPubSection, TestDebugPubSection) {
   EXPECT_EQ((uint32_t)PubNames.Entries[1].DieOffset, 0x4321u);
   EXPECT_EQ(PubNames.Entries[1].Name, "def");
 
-  ASSERT_TRUE(Data.PubTypes.has_value());
-  DWARFYAML::PubSection PubTypes = Data.PubTypes.value();
+  ASSERT_TRUE(Data.PubTypes.hasValue());
+  DWARFYAML::PubSection PubTypes = Data.PubTypes.getValue();
 
   ASSERT_EQ(PubTypes.Entries.size(), 2u);
   EXPECT_EQ((uint32_t)PubTypes.Entries[0].DieOffset, 0x1234u);
@@ -157,8 +157,8 @@ TEST(DebugGNUPubSection, TestDebugGNUPubSections) {
   DWARFYAML::Data Data;
   ASSERT_THAT_ERROR(parseDWARFYAML(Yaml, Data), Succeeded());
 
-  ASSERT_TRUE(Data.GNUPubNames.has_value());
-  DWARFYAML::PubSection GNUPubNames = Data.GNUPubNames.value();
+  ASSERT_TRUE(Data.GNUPubNames.hasValue());
+  DWARFYAML::PubSection GNUPubNames = Data.GNUPubNames.getValue();
 
   ASSERT_EQ(GNUPubNames.Entries.size(), 2u);
   EXPECT_EQ((uint32_t)GNUPubNames.Entries[0].DieOffset, 0x1234u);
@@ -168,8 +168,8 @@ TEST(DebugGNUPubSection, TestDebugGNUPubSections) {
   EXPECT_EQ((uint8_t)GNUPubNames.Entries[1].Descriptor, 0x34);
   EXPECT_EQ(GNUPubNames.Entries[1].Name, "def");
 
-  ASSERT_TRUE(Data.GNUPubTypes.has_value());
-  DWARFYAML::PubSection GNUPubTypes = Data.GNUPubTypes.value();
+  ASSERT_TRUE(Data.GNUPubTypes.hasValue());
+  DWARFYAML::PubSection GNUPubTypes = Data.GNUPubTypes.getValue();
 
   ASSERT_EQ(GNUPubTypes.Entries.size(), 2u);
   EXPECT_EQ((uint32_t)GNUPubTypes.Entries[0].DieOffset, 0x1234u);

diff  --git a/llvm/unittests/ProfileData/MemProfTest.cpp b/llvm/unittests/ProfileData/MemProfTest.cpp
index 290d33154e6c0..480848100446b 100644
--- a/llvm/unittests/ProfileData/MemProfTest.cpp
+++ b/llvm/unittests/ProfileData/MemProfTest.cpp
@@ -104,9 +104,9 @@ MATCHER_P4(FrameContains, FunctionName, LineOffset, Column, Inline, "") {
     *result_listener << "Hash mismatch";
     return false;
   }
-  if (F.SymbolName && F.SymbolName.value() != FunctionName) {
+  if (F.SymbolName.hasValue() && F.SymbolName.getValue() != FunctionName) {
     *result_listener << "SymbolName mismatch\nWant: " << FunctionName
-                     << "\nGot: " << F.SymbolName.value();
+                     << "\nGot: " << F.SymbolName.getValue();
     return false;
   }
   if (F.LineOffset == LineOffset && F.Column == Column &&

diff  --git a/llvm/unittests/Support/AlignmentTest.cpp b/llvm/unittests/Support/AlignmentTest.cpp
index fa26b60521165..fa9199706b412 100644
--- a/llvm/unittests/Support/AlignmentTest.cpp
+++ b/llvm/unittests/Support/AlignmentTest.cpp
@@ -63,11 +63,11 @@ TEST(AlignmentTest, ValidCTors) {
 
 TEST(AlignmentTest, CheckMaybeAlignHasValue) {
   EXPECT_TRUE(MaybeAlign(1));
-  EXPECT_TRUE(MaybeAlign(1).has_value());
+  EXPECT_TRUE(MaybeAlign(1).hasValue());
   EXPECT_FALSE(MaybeAlign(0));
-  EXPECT_FALSE(MaybeAlign(0).has_value());
+  EXPECT_FALSE(MaybeAlign(0).hasValue());
   EXPECT_FALSE(MaybeAlign());
-  EXPECT_FALSE(MaybeAlign().has_value());
+  EXPECT_FALSE(MaybeAlign().hasValue());
 }
 
 TEST(AlignmentTest, Division) {
@@ -165,8 +165,8 @@ TEST(AlignmentTest, isAligned_isAddrAligned) {
     MaybeAlign A(T.alignment);
     // Test Align
     if (A) {
-      EXPECT_EQ(isAligned(*A, T.offset), T.isAligned);
-      EXPECT_EQ(isAddrAligned(*A, T.forgedAddr()), T.isAligned);
+      EXPECT_EQ(isAligned(A.getValue(), T.offset), T.isAligned);
+      EXPECT_EQ(isAddrAligned(A.getValue(), T.forgedAddr()), T.isAligned);
     }
   }
 }

diff  --git a/llvm/unittests/Support/Casting.cpp b/llvm/unittests/Support/Casting.cpp
index bebb36fc61f22..311fefd728785 100644
--- a/llvm/unittests/Support/Casting.cpp
+++ b/llvm/unittests/Support/Casting.cpp
@@ -248,11 +248,11 @@ TEST(CastingTest, dyn_cast_value_types) {
 TEST(CastingTest, dyn_cast_if_present) {
   Optional<T1> empty{};
   Optional<T2> F1 = dyn_cast_if_present<T2>(empty);
-  EXPECT_FALSE(F1.has_value());
+  EXPECT_FALSE(F1.hasValue());
 
   T1 t1;
   Optional<T2> F2 = dyn_cast_if_present<T2>(t1);
-  EXPECT_TRUE(F2.has_value());
+  EXPECT_TRUE(F2.hasValue());
 
   T1 *t1Null = nullptr;
 

diff  --git a/llvm/unittests/Support/KnownBitsTest.cpp b/llvm/unittests/Support/KnownBitsTest.cpp
index 1411c2edf608b..9ef62bb90fcc4 100644
--- a/llvm/unittests/Support/KnownBitsTest.cpp
+++ b/llvm/unittests/Support/KnownBitsTest.cpp
@@ -358,38 +358,38 @@ TEST(KnownBitsTest, ICmpExhaustive) {
       Optional<bool> KnownSLT = KnownBits::slt(Known1, Known2);
       Optional<bool> KnownSLE = KnownBits::sle(Known1, Known2);
 
-      EXPECT_EQ(AllEQ || NoneEQ, KnownEQ.has_value());
-      EXPECT_EQ(AllNE || NoneNE, KnownNE.has_value());
-      EXPECT_EQ(AllUGT || NoneUGT, KnownUGT.has_value());
-      EXPECT_EQ(AllUGE || NoneUGE, KnownUGE.has_value());
-      EXPECT_EQ(AllULT || NoneULT, KnownULT.has_value());
-      EXPECT_EQ(AllULE || NoneULE, KnownULE.has_value());
-      EXPECT_EQ(AllSGT || NoneSGT, KnownSGT.has_value());
-      EXPECT_EQ(AllSGE || NoneSGE, KnownSGE.has_value());
-      EXPECT_EQ(AllSLT || NoneSLT, KnownSLT.has_value());
-      EXPECT_EQ(AllSLE || NoneSLE, KnownSLE.has_value());
-
-      EXPECT_EQ(AllEQ, KnownEQ && *KnownEQ);
-      EXPECT_EQ(AllNE, KnownNE && *KnownNE);
-      EXPECT_EQ(AllUGT, KnownUGT && *KnownUGT);
-      EXPECT_EQ(AllUGE, KnownUGE && *KnownUGE);
-      EXPECT_EQ(AllULT, KnownULT && *KnownULT);
-      EXPECT_EQ(AllULE, KnownULE && *KnownULE);
-      EXPECT_EQ(AllSGT, KnownSGT && *KnownSGT);
-      EXPECT_EQ(AllSGE, KnownSGE && *KnownSGE);
-      EXPECT_EQ(AllSLT, KnownSLT && *KnownSLT);
-      EXPECT_EQ(AllSLE, KnownSLE && *KnownSLE);
-
-      EXPECT_EQ(NoneEQ, KnownEQ && !*KnownEQ);
-      EXPECT_EQ(NoneNE, KnownNE && !*KnownNE);
-      EXPECT_EQ(NoneUGT, KnownUGT && !*KnownUGT);
-      EXPECT_EQ(NoneUGE, KnownUGE && !*KnownUGE);
-      EXPECT_EQ(NoneULT, KnownULT && !*KnownULT);
-      EXPECT_EQ(NoneULE, KnownULE && !*KnownULE);
-      EXPECT_EQ(NoneSGT, KnownSGT && !*KnownSGT);
-      EXPECT_EQ(NoneSGE, KnownSGE && !*KnownSGE);
-      EXPECT_EQ(NoneSLT, KnownSLT && !*KnownSLT);
-      EXPECT_EQ(NoneSLE, KnownSLE && !*KnownSLE);
+      EXPECT_EQ(AllEQ || NoneEQ, KnownEQ.hasValue());
+      EXPECT_EQ(AllNE || NoneNE, KnownNE.hasValue());
+      EXPECT_EQ(AllUGT || NoneUGT, KnownUGT.hasValue());
+      EXPECT_EQ(AllUGE || NoneUGE, KnownUGE.hasValue());
+      EXPECT_EQ(AllULT || NoneULT, KnownULT.hasValue());
+      EXPECT_EQ(AllULE || NoneULE, KnownULE.hasValue());
+      EXPECT_EQ(AllSGT || NoneSGT, KnownSGT.hasValue());
+      EXPECT_EQ(AllSGE || NoneSGE, KnownSGE.hasValue());
+      EXPECT_EQ(AllSLT || NoneSLT, KnownSLT.hasValue());
+      EXPECT_EQ(AllSLE || NoneSLE, KnownSLE.hasValue());
+
+      EXPECT_EQ(AllEQ, KnownEQ.hasValue() && KnownEQ.getValue());
+      EXPECT_EQ(AllNE, KnownNE.hasValue() && KnownNE.getValue());
+      EXPECT_EQ(AllUGT, KnownUGT.hasValue() && KnownUGT.getValue());
+      EXPECT_EQ(AllUGE, KnownUGE.hasValue() && KnownUGE.getValue());
+      EXPECT_EQ(AllULT, KnownULT.hasValue() && KnownULT.getValue());
+      EXPECT_EQ(AllULE, KnownULE.hasValue() && KnownULE.getValue());
+      EXPECT_EQ(AllSGT, KnownSGT.hasValue() && KnownSGT.getValue());
+      EXPECT_EQ(AllSGE, KnownSGE.hasValue() && KnownSGE.getValue());
+      EXPECT_EQ(AllSLT, KnownSLT.hasValue() && KnownSLT.getValue());
+      EXPECT_EQ(AllSLE, KnownSLE.hasValue() && KnownSLE.getValue());
+
+      EXPECT_EQ(NoneEQ, KnownEQ.hasValue() && !KnownEQ.getValue());
+      EXPECT_EQ(NoneNE, KnownNE.hasValue() && !KnownNE.getValue());
+      EXPECT_EQ(NoneUGT, KnownUGT.hasValue() && !KnownUGT.getValue());
+      EXPECT_EQ(NoneUGE, KnownUGE.hasValue() && !KnownUGE.getValue());
+      EXPECT_EQ(NoneULT, KnownULT.hasValue() && !KnownULT.getValue());
+      EXPECT_EQ(NoneULE, KnownULE.hasValue() && !KnownULE.getValue());
+      EXPECT_EQ(NoneSGT, KnownSGT.hasValue() && !KnownSGT.getValue());
+      EXPECT_EQ(NoneSGE, KnownSGE.hasValue() && !KnownSGE.getValue());
+      EXPECT_EQ(NoneSLT, KnownSLT.hasValue() && !KnownSLT.getValue());
+      EXPECT_EQ(NoneSLE, KnownSLE.hasValue() && !KnownSLE.getValue());
     });
   });
 }

diff  --git a/llvm/unittests/Support/YAMLParserTest.cpp b/llvm/unittests/Support/YAMLParserTest.cpp
index 14def9c528875..692d963828318 100644
--- a/llvm/unittests/Support/YAMLParserTest.cpp
+++ b/llvm/unittests/Support/YAMLParserTest.cpp
@@ -344,12 +344,12 @@ TEST(YAMLParser, FlowSequenceTokensOutsideFlowSequence) {
 
 static void expectCanParseBool(StringRef S, bool Expected) {
   llvm::Optional<bool> Parsed = yaml::parseBool(S);
-  EXPECT_TRUE(Parsed.has_value());
+  EXPECT_TRUE(Parsed.hasValue());
   EXPECT_EQ(*Parsed, Expected);
 }
 
 static void expectCannotParseBool(StringRef S) {
-  EXPECT_FALSE(yaml::parseBool(S).has_value());
+  EXPECT_FALSE(yaml::parseBool(S).hasValue());
 }
 
 TEST(YAMLParser, ParsesBools) {

diff  --git a/llvm/unittests/TableGen/ParserEntryPointTest.cpp b/llvm/unittests/TableGen/ParserEntryPointTest.cpp
index a227f3d6715bc..23642b6fd751c 100644
--- a/llvm/unittests/TableGen/ParserEntryPointTest.cpp
+++ b/llvm/unittests/TableGen/ParserEntryPointTest.cpp
@@ -35,6 +35,6 @@ TEST(Parser, SanityTest) {
 
   Record *Foo = Records.getDef("Foo");
   Optional<StringRef> Field = Foo->getValueAsOptionalString("strField");
-  EXPECT_TRUE(Field.has_value());
-  EXPECT_EQ(*Field, "value");
+  EXPECT_TRUE(Field.hasValue());
+  EXPECT_EQ(Field.getValue(), "value");
 }

diff  --git a/llvm/utils/TableGen/GlobalISel/GIMatchTree.h b/llvm/utils/TableGen/GlobalISel/GIMatchTree.h
index 55a86259661db..56df37731c09a 100644
--- a/llvm/utils/TableGen/GlobalISel/GIMatchTree.h
+++ b/llvm/utils/TableGen/GlobalISel/GIMatchTree.h
@@ -32,11 +32,11 @@ class GIMatchTreeVariableBinding {
                              Optional<unsigned> OpIdx = None)
       : Name(Name), InstrID(InstrID), OpIdx(OpIdx) {}
 
-  bool isInstr() const { return !OpIdx; }
+  bool isInstr() const { return !OpIdx.hasValue(); }
   StringRef getName() const { return Name; }
   unsigned getInstrID() const { return InstrID; }
   unsigned getOpIdx() const {
-    assert(OpIdx && "Is not an operand binding");
+    assert(OpIdx.hasValue() && "Is not an operand binding");
     return *OpIdx;
   }
 };

diff  --git a/llvm/utils/TableGen/GlobalISelEmitter.cpp b/llvm/utils/TableGen/GlobalISelEmitter.cpp
index e5e216baa74d7..e4ea6daee9deb 100644
--- a/llvm/utils/TableGen/GlobalISelEmitter.cpp
+++ b/llvm/utils/TableGen/GlobalISelEmitter.cpp
@@ -2936,14 +2936,14 @@ class RenderComplexPatternOperand : public OperandRenderer {
   }
 
   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
-    Table << MatchTable::Opcode(SubOperand ? "GIR_ComplexSubOperandRenderer"
-                                           : "GIR_ComplexRenderer")
+    Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
+                                                      : "GIR_ComplexRenderer")
           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
           << MatchTable::Comment("RendererID")
           << MatchTable::IntValue(RendererID);
-    if (SubOperand)
+    if (SubOperand.hasValue())
       Table << MatchTable::Comment("SubOperand")
-            << MatchTable::IntValue(*SubOperand);
+            << MatchTable::IntValue(SubOperand.getValue());
     Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
   }
 };
@@ -4946,8 +4946,8 @@ Error GlobalISelEmitter::importDefaultOperandRenderers(
       auto Def = DefaultDefOp->getDef();
       if (Def->getName() == "undef_tied_input") {
         unsigned TempRegID = M.allocateTempRegID();
-        M.insertAction<MakeTempRegisterAction>(InsertPt, *OpTyOrNone,
-                                               TempRegID);
+        M.insertAction<MakeTempRegisterAction>(
+          InsertPt, OpTyOrNone.getValue(), TempRegID);
         InsertPt = M.insertAction<BuildMIAction>(
           InsertPt, M.allocateOutputInsnID(),
           &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));

diff  --git a/mlir/include/mlir/Dialect/Affine/Analysis/AffineStructures.h b/mlir/include/mlir/Dialect/Affine/Analysis/AffineStructures.h
index d4f9414840872..b307f0d4d2e33 100644
--- a/mlir/include/mlir/Dialect/Affine/Analysis/AffineStructures.h
+++ b/mlir/include/mlir/Dialect/Affine/Analysis/AffineStructures.h
@@ -400,13 +400,13 @@ class FlatAffineValueConstraints : public presburger::IntegerPolyhedron {
   inline Value getValue(unsigned pos) const {
     assert(pos < getNumDimAndSymbolIds() && "Invalid position");
     assert(hasValue(pos) && "identifier's Value not set");
-    return values[pos].value();
+    return values[pos].getValue();
   }
 
   /// Returns true if the pos^th identifier has an associated Value.
   inline bool hasValue(unsigned pos) const {
     assert(pos < getNumDimAndSymbolIds() && "Invalid position");
-    return values[pos].has_value();
+    return values[pos].hasValue();
   }
 
   /// Returns true if at least one identifier has an associated Value.

diff  --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
index 52a7ef3dfaa03..1b547bb89ef19 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
@@ -347,8 +347,8 @@ def LLVM_FNegOp : LLVM_UnaryFloatArithmeticOp<
 // of LLVM ops that accept such an attribute.
 class MemoryOpWithAlignmentBase {
   code setAlignmentCode = [{
-    if ($alignment) {
-      auto align = *$alignment;
+    if ($alignment.hasValue()) {
+      auto align = $alignment.getValue();
       if (align != 0)
         inst->setAlignment(llvm::Align(align));
     }

diff  --git a/mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td b/mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td
index e51460ed8b290..24287f1397083 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td
@@ -568,8 +568,8 @@ class MMA_SYNC_INTR {
        # op[1].ptx_elt_type # "\" == eltypeB && " 
        # " \"" # op[2].ptx_elt_type # "\" == eltypeC && "
        # " \"" # op[3].ptx_elt_type # "\" == eltypeD "
-       # " && (sat  ? " # sat # " == static_cast<int>(*sat) : true)"
-       # !if(!ne(b1op, ""), " && (b1Op ? MMAB1Op::" # b1op # " == *b1Op : true)", "") # ")\n"
+       # " && (sat.hasValue()  ? " # sat # " == static_cast<int>(*sat) : true)"
+       # !if(!ne(b1op, ""), " && (b1Op.hasValue() ? MMAB1Op::" # b1op # " == b1Op.getValue() : true)", "") # ")\n"
        # "  return " #
        MMA_SYNC_NAME<layoutA, layoutB, b1op, sat, op[0], op[1], op[2], op[3]>.id # ";", 
           "") // if supported
@@ -995,8 +995,8 @@ def NVVM_MmaOp : NVVM_Op<"mma.sync", [AttrSizedOperandSegments]> {
         $shape.getM(), $shape.getN(), $shape.getK(), 
         $b1Op, $intOverflowBehavior,
         $layoutA, $layoutB,
-        *$multiplicandAPtxType,
-        *$multiplicandBPtxType,
+        $multiplicandAPtxType.getValue(), 
+        $multiplicandBPtxType.getValue(),
         op.accumPtxType(), 
         op.resultPtxType());
 

diff  --git a/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h b/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h
index 2aea098e28594..ef891dd2ddc51 100644
--- a/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h
+++ b/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h
@@ -75,11 +75,11 @@ class LLVM_NODISCARD DiagnosedSilenceableFailure {
   }
 
   /// Returns `true` if this is a silencable failure.
-  bool isSilenceableFailure() const { return diagnostic.has_value(); }
+  bool isSilenceableFailure() const { return diagnostic.hasValue(); }
 
   /// Returns `true` if this is a success.
   bool succeeded() const {
-    return !diagnostic.has_value() && ::mlir::succeeded(result);
+    return !diagnostic.hasValue() && ::mlir::succeeded(result);
   }
 
   /// Returns the diagnostic message without emitting it. Expects this object

diff  --git a/mlir/include/mlir/IR/OpDefinition.h b/mlir/include/mlir/IR/OpDefinition.h
index 602317234e139..42eccde488919 100644
--- a/mlir/include/mlir/IR/OpDefinition.h
+++ b/mlir/include/mlir/IR/OpDefinition.h
@@ -44,11 +44,11 @@ class OptionalParseResult {
   OptionalParseResult(llvm::NoneType) : impl(llvm::None) {}
 
   /// Returns true if we contain a valid ParseResult value.
-  bool has_value() const { return impl.has_value(); }
+  bool hasValue() const { return impl.hasValue(); }
 
   /// Access the internal ParseResult value.
-  ParseResult value() const { return impl.value(); }
-  ParseResult operator*() const { return value(); }
+  ParseResult getValue() const { return impl.getValue(); }
+  ParseResult operator*() const { return getValue(); }
 
 private:
   Optional<ParseResult> impl;

diff  --git a/mlir/include/mlir/IR/OpImplementation.h b/mlir/include/mlir/IR/OpImplementation.h
index af75fed0fc1f3..2acb2c799d83b 100644
--- a/mlir/include/mlir/IR/OpImplementation.h
+++ b/mlir/include/mlir/IR/OpImplementation.h
@@ -555,7 +555,7 @@ class AsmParser {
   ParseResult parseInteger(IntT &result) {
     auto loc = getCurrentLocation();
     OptionalParseResult parseResult = parseOptionalInteger(result);
-    if (!parseResult.has_value())
+    if (!parseResult.hasValue())
       return emitError(loc, "expected integer value");
     return *parseResult;
   }
@@ -570,7 +570,7 @@ class AsmParser {
     // Parse the unsigned variant.
     APInt uintResult;
     OptionalParseResult parseResult = parseOptionalInteger(uintResult);
-    if (!parseResult.has_value() || failed(*parseResult))
+    if (!parseResult.hasValue() || failed(*parseResult))
       return parseResult;
 
     // Try to convert to the provided integer type.  sextOrTrunc is correct even
@@ -817,7 +817,7 @@ class AsmParser {
                                              StringRef attrName,
                                              NamedAttrList &attrs) {
     OptionalParseResult parseResult = parseOptionalAttribute(result, type);
-    if (parseResult.has_value() && succeeded(*parseResult))
+    if (parseResult.hasValue() && succeeded(*parseResult))
       attrs.append(attrName, result);
     return parseResult;
   }
@@ -1299,9 +1299,9 @@ class OpAsmParser : public AsmParser {
   ParseResult parseAssignmentList(SmallVectorImpl<Argument> &lhs,
                                   SmallVectorImpl<UnresolvedOperand> &rhs) {
     OptionalParseResult result = parseOptionalAssignmentList(lhs, rhs);
-    if (!result.has_value())
+    if (!result.hasValue())
       return emitError(getCurrentLocation(), "expected '('");
-    return result.value();
+    return result.getValue();
   }
 
   virtual OptionalParseResult

diff  --git a/mlir/include/mlir/Support/LogicalResult.h b/mlir/include/mlir/Support/LogicalResult.h
index b2cf736fef9b6..29408283a2480 100644
--- a/mlir/include/mlir/Support/LogicalResult.h
+++ b/mlir/include/mlir/Support/LogicalResult.h
@@ -90,12 +90,12 @@ template <typename T> class LLVM_NODISCARD FailureOr : public Optional<T> {
   FailureOr(const FailureOr<U> &other)
       : Optional<T>(failed(other) ? Optional<T>() : Optional<T>(*other)) {}
 
-  operator LogicalResult() const { return success(this->has_value()); }
+  operator LogicalResult() const { return success(this->hasValue()); }
 
 private:
   /// Hide the bool conversion as it easily creates confusion.
   using Optional<T>::operator bool;
-  using Optional<T>::has_value;
+  using Optional<T>::hasValue;
 };
 
 /// This class represents success/failure for parsing-like operations that find

diff  --git a/mlir/include/mlir/TableGen/Operator.h b/mlir/include/mlir/TableGen/Operator.h
index ab03a1af8a240..6bac85075622e 100644
--- a/mlir/include/mlir/TableGen/Operator.h
+++ b/mlir/include/mlir/TableGen/Operator.h
@@ -263,12 +263,12 @@ class Operator {
     explicit ArgOrType(TypeConstraint constraint)
         : index(None), constraint(constraint) {}
     bool isArg() const {
-      assert(constraint.has_value() ^ index.has_value());
-      return index.has_value();
+      assert(constraint.hasValue() ^ index.hasValue());
+      return index.hasValue();
     }
     bool isType() const {
-      assert(constraint.has_value() ^ index.has_value());
-      return constraint.has_value();
+      assert(constraint.hasValue() ^ index.hasValue());
+      return constraint.hasValue();
     }
 
     int getArg() const { return *index; }

diff  --git a/mlir/include/mlir/Transforms/DialectConversion.h b/mlir/include/mlir/Transforms/DialectConversion.h
index 678bf02d731ef..feac434da68f5 100644
--- a/mlir/include/mlir/Transforms/DialectConversion.h
+++ b/mlir/include/mlir/Transforms/DialectConversion.h
@@ -251,9 +251,9 @@ class TypeConverter {
         [callback = std::forward<FnT>(callback)](
             T type, SmallVectorImpl<Type> &results, ArrayRef<Type>) {
           if (Optional<Type> resultOpt = callback(type)) {
-            bool wasSuccess = static_cast<bool>(resultOpt.value());
+            bool wasSuccess = static_cast<bool>(resultOpt.getValue());
             if (wasSuccess)
-              results.push_back(resultOpt.value());
+              results.push_back(resultOpt.getValue());
             return Optional<LogicalResult>(success(wasSuccess));
           }
           return Optional<LogicalResult>();

diff  --git a/mlir/lib/Analysis/Presburger/IntegerRelation.cpp b/mlir/lib/Analysis/Presburger/IntegerRelation.cpp
index baeb467c9c035..7376747663e62 100644
--- a/mlir/lib/Analysis/Presburger/IntegerRelation.cpp
+++ b/mlir/lib/Analysis/Presburger/IntegerRelation.cpp
@@ -2015,14 +2015,14 @@ IntegerRelation::unionBoundingBox(const IntegerRelation &otherCst) {
   int64_t lbFloorDivisor, otherLbFloorDivisor;
   for (unsigned d = 0, e = getNumDimIds(); d < e; ++d) {
     auto extent = getConstantBoundOnDimSize(d, &lb, &lbFloorDivisor, &ub);
-    if (!extent.has_value())
+    if (!extent.hasValue())
       // TODO: symbolic extents when necessary.
       // TODO: handle union if a dimension is unbounded.
       return failure();
 
     auto otherExtent = otherCst.getConstantBoundOnDimSize(
         d, &otherLb, &otherLbFloorDivisor, &otherUb);
-    if (!otherExtent.has_value() || lbFloorDivisor != otherLbFloorDivisor)
+    if (!otherExtent.hasValue() || lbFloorDivisor != otherLbFloorDivisor)
       // TODO: symbolic extents when necessary.
       return failure();
 
@@ -2043,10 +2043,10 @@ IntegerRelation::unionBoundingBox(const IntegerRelation &otherCst) {
       // Uncomparable - check for constant lower/upper bounds.
       auto constLb = getConstantBound(BoundType::LB, d);
       auto constOtherLb = otherCst.getConstantBound(BoundType::LB, d);
-      if (!constLb.has_value() || !constOtherLb.has_value())
+      if (!constLb.hasValue() || !constOtherLb.hasValue())
         return failure();
       std::fill(minLb.begin(), minLb.end(), 0);
-      minLb.back() = std::min(*constLb, constOtherLb.value());
+      minLb.back() = std::min(constLb.getValue(), constOtherLb.getValue());
     }
 
     // Do the same for ub's but max of upper bounds. Identify max.
@@ -2059,10 +2059,10 @@ IntegerRelation::unionBoundingBox(const IntegerRelation &otherCst) {
       // Uncomparable - check for constant lower/upper bounds.
       auto constUb = getConstantBound(BoundType::UB, d);
       auto constOtherUb = otherCst.getConstantBound(BoundType::UB, d);
-      if (!constUb.has_value() || !constOtherUb.has_value())
+      if (!constUb.hasValue() || !constOtherUb.hasValue())
         return failure();
       std::fill(maxUb.begin(), maxUb.end(), 0);
-      maxUb.back() = std::max(*constUb, constOtherUb.value());
+      maxUb.back() = std::max(constUb.getValue(), constOtherUb.getValue());
     }
 
     std::fill(newLb.begin(), newLb.end(), 0);

diff  --git a/mlir/lib/Conversion/SPIRVToLLVM/SPIRVToLLVM.cpp b/mlir/lib/Conversion/SPIRVToLLVM/SPIRVToLLVM.cpp
index 3d2dae573fb23..6e0f007efc4b3 100644
--- a/mlir/lib/Conversion/SPIRVToLLVM/SPIRVToLLVM.cpp
+++ b/mlir/lib/Conversion/SPIRVToLLVM/SPIRVToLLVM.cpp
@@ -645,8 +645,8 @@ class ExecutionModePattern
     ModuleOp module = op->getParentOfType<ModuleOp>();
     IntegerAttr executionModeAttr = op.execution_modeAttr();
     std::string moduleName;
-    if (module.getName().has_value())
-      moduleName = "_" + module.getName()->str();
+    if (module.getName().hasValue())
+      moduleName = "_" + module.getName().getValue().str();
     else
       moduleName = "";
     std::string executionModeInfoName =
@@ -1585,10 +1585,10 @@ void mlir::encodeBindAttribute(ModuleOp module) {
       if (descriptorSet && binding) {
         // Encode these numbers into the variable's symbolic name. If the
         // SPIR-V module has a name, add it at the beginning.
-        auto moduleAndName =
-            spvModule.getName().has_value()
-                ? spvModule.getName()->str() + "_" + op.sym_name().str()
-                : op.sym_name().str();
+        auto moduleAndName = spvModule.getName().hasValue()
+                                 ? spvModule.getName().getValue().str() + "_" +
+                                       op.sym_name().str()
+                                 : op.sym_name().str();
         std::string name =
             llvm::formatv("{0}_descriptor_set{1}_binding{2}", moduleAndName,
                           std::to_string(descriptorSet.getInt()),

diff  --git a/mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp b/mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp
index c7917a46678c8..133a3631b7d5a 100644
--- a/mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp
+++ b/mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp
@@ -147,8 +147,8 @@ createLinalgBodyCalculationForElementwiseOp(Operation *op, ValueRange args,
       cast<tosa::NegateOp>(op).quantization_info()) {
     auto quantizationInfo = cast<tosa::NegateOp>(op).quantization_info();
     int32_t inputBitWidth = elementTy.getIntOrFloatBitWidth();
-    int64_t inZp = quantizationInfo->getInputZp();
-    int64_t outZp = quantizationInfo->getOutputZp();
+    int64_t inZp = quantizationInfo.getValue().getInputZp();
+    int64_t outZp = quantizationInfo.getValue().getOutputZp();
 
     // Compute the maximum value that can occur in the intermediate buffer.
     int64_t zpAdd = inZp + outZp;
@@ -1153,9 +1153,9 @@ class RescaleConverter : public OpRewritePattern<tosa::RescaleOp> {
 
     auto dynamicDimsOr =
         checkHasDynamicBatchDims(rewriter, op, {input, op.output()});
-    if (!dynamicDimsOr.has_value())
+    if (!dynamicDimsOr.hasValue())
       return failure();
-    SmallVector<Value> dynamicDims = dynamicDimsOr.value();
+    SmallVector<Value> dynamicDims = dynamicDimsOr.getValue();
 
     // The shift and multiplier values.
     SmallVector<int32_t> multiplierValues;
@@ -1345,9 +1345,9 @@ class ResizeConverter : public OpRewritePattern<tosa::ResizeOp> {
 
     auto dynamicDimsOr =
         checkHasDynamicBatchDims(rewriter, op, {input, op.output()});
-    if (!dynamicDimsOr.has_value())
+    if (!dynamicDimsOr.hasValue())
       return failure();
-    SmallVector<Value> dynamicDims = dynamicDimsOr.value();
+    SmallVector<Value> dynamicDims = dynamicDimsOr.getValue();
 
     if (op.mode() != "NEAREST_NEIGHBOR" && op.mode() != "BILINEAR")
       return failure();
@@ -2040,9 +2040,9 @@ class GatherConverter : public OpConversionPattern<tosa::GatherOp> {
 
     auto dynamicDimsOr =
         checkHasDynamicBatchDims(rewriter, op, {input, indices, op.output()});
-    if (!dynamicDimsOr.has_value())
+    if (!dynamicDimsOr.hasValue())
       return failure();
-    SmallVector<Value> dynamicDims = dynamicDimsOr.value();
+    SmallVector<Value> dynamicDims = dynamicDimsOr.getValue();
 
     auto resultElementTy = resultTy.getElementType();
 

diff  --git a/mlir/lib/Conversion/TosaToLinalg/TosaToLinalgNamed.cpp b/mlir/lib/Conversion/TosaToLinalg/TosaToLinalgNamed.cpp
index 531824c874d48..866fea818e8f8 100644
--- a/mlir/lib/Conversion/TosaToLinalg/TosaToLinalgNamed.cpp
+++ b/mlir/lib/Conversion/TosaToLinalg/TosaToLinalgNamed.cpp
@@ -694,9 +694,9 @@ class MaxPool2dConverter : public OpRewritePattern<tosa::MaxPool2dOp> {
 
     auto dynamicDimsOr =
         checkHasDynamicBatchDims(rewriter, op, {input, op.output()});
-    if (!dynamicDimsOr.has_value())
+    if (!dynamicDimsOr.hasValue())
       return failure();
-    SmallVector<Value> dynamicDims = dynamicDimsOr.value();
+    SmallVector<Value> dynamicDims = dynamicDimsOr.getValue();
 
     // Determine what the initial value needs to be for the max pool op.
     Attribute initialAttr;
@@ -771,9 +771,9 @@ class AvgPool2dConverter : public OpRewritePattern<tosa::AvgPool2dOp> {
 
     auto dynamicDimsOr =
         checkHasDynamicBatchDims(rewriter, op, {input, op.output()});
-    if (!dynamicDimsOr.has_value())
+    if (!dynamicDimsOr.hasValue())
       return failure();
-    SmallVector<Value> dynamicDims = dynamicDimsOr.value();
+    SmallVector<Value> dynamicDims = dynamicDimsOr.getValue();
 
     // Apply padding as necessary.
     llvm::SmallVector<int64_t> pad;

diff  --git a/mlir/lib/Conversion/VectorToSCF/VectorToSCF.cpp b/mlir/lib/Conversion/VectorToSCF/VectorToSCF.cpp
index 2356136f92d42..9ead9e29c71da 100644
--- a/mlir/lib/Conversion/VectorToSCF/VectorToSCF.cpp
+++ b/mlir/lib/Conversion/VectorToSCF/VectorToSCF.cpp
@@ -90,12 +90,12 @@ static void getXferIndices(OpBuilder &b, OpTy xferOp, Value iv,
   indices.append(prevIndices.begin(), prevIndices.end());
 
   Location loc = xferOp.getLoc();
-  bool isBroadcast = !dim.has_value();
+  bool isBroadcast = !dim.hasValue();
   if (!isBroadcast) {
     AffineExpr d0, d1;
     bindDims(xferOp.getContext(), d0, d1);
-    Value offset = adaptor.getIndices()[dim.value()];
-    indices[dim.value()] =
+    Value offset = adaptor.getIndices()[dim.getValue()];
+    indices[dim.getValue()] =
         makeComposedAffineApply(b, loc, d0 + d1, {offset, iv});
   }
 }

diff  --git a/mlir/lib/Dialect/Affine/Analysis/AffineStructures.cpp b/mlir/lib/Dialect/Affine/Analysis/AffineStructures.cpp
index 1ce9c3c8b4a4e..e1e66219d0143 100644
--- a/mlir/lib/Dialect/Affine/Analysis/AffineStructures.cpp
+++ b/mlir/lib/Dialect/Affine/Analysis/AffineStructures.cpp
@@ -322,7 +322,7 @@ unsigned FlatAffineValueConstraints::insertId(IdKind kind, unsigned pos,
 
 bool FlatAffineValueConstraints::hasValues() const {
   return llvm::find_if(values, [](Optional<Value> id) {
-           return id.has_value();
+           return id.hasValue();
          }) != values.end();
 }
 
@@ -401,11 +401,11 @@ static void mergeAndAlignIds(unsigned offset, FlatAffineValueConstraints *a,
 
   assert(std::all_of(a->getMaybeValues().begin() + offset,
                      a->getMaybeValues().end(),
-                     [](Optional<Value> id) { return id.has_value(); }));
+                     [](Optional<Value> id) { return id.hasValue(); }));
 
   assert(std::all_of(b->getMaybeValues().begin() + offset,
                      b->getMaybeValues().end(),
-                     [](Optional<Value> id) { return id.has_value(); }));
+                     [](Optional<Value> id) { return id.hasValue(); }));
 
   SmallVector<Value, 4> aDimValues;
   a->getValues(offset, a->getNumDimIds(), &aDimValues);
@@ -1008,18 +1008,18 @@ void FlatAffineValueConstraints::getSliceBounds(
 
       auto lbConst = getConstantBound(BoundType::LB, pos);
       auto ubConst = getConstantBound(BoundType::UB, pos);
-      if (lbConst.has_value() && ubConst.has_value()) {
+      if (lbConst.hasValue() && ubConst.hasValue()) {
         // Detect equality to a constant.
-        if (lbConst.value() == ubConst.value()) {
-          memo[pos] = getAffineConstantExpr(*lbConst, context);
+        if (lbConst.getValue() == ubConst.getValue()) {
+          memo[pos] = getAffineConstantExpr(lbConst.getValue(), context);
           changed = true;
           continue;
         }
 
         // Detect an identifier as modulo of another identifier w.r.t a
         // constant.
-        if (detectAsMod(*this, pos, lbConst.value(), ubConst.value(), memo,
-                        context)) {
+        if (detectAsMod(*this, pos, lbConst.getValue(), ubConst.getValue(),
+                        memo, context)) {
           changed = true;
           continue;
         }
@@ -1119,19 +1119,21 @@ void FlatAffineValueConstraints::getSliceBounds(
         LLVM_DEBUG(llvm::dbgs()
                    << "WARNING: Potentially over-approximating slice lb\n");
         auto lbConst = getConstantBound(BoundType::LB, pos + offset);
-        if (lbConst) {
-          lbMap = AffineMap::get(numMapDims, numMapSymbols,
-                                 getAffineConstantExpr(*lbConst, context));
+        if (lbConst.hasValue()) {
+          lbMap = AffineMap::get(
+              numMapDims, numMapSymbols,
+              getAffineConstantExpr(lbConst.getValue(), context));
         }
       }
       if (!ubMap || ubMap.getNumResults() > 1) {
         LLVM_DEBUG(llvm::dbgs()
                    << "WARNING: Potentially over-approximating slice ub\n");
         auto ubConst = getConstantBound(BoundType::UB, pos + offset);
-        if (ubConst) {
-          ubMap = AffineMap::get(
-              numMapDims, numMapSymbols,
-              getAffineConstantExpr(ubConst.value() + ubAdjustment, context));
+        if (ubConst.hasValue()) {
+          ubMap =
+              AffineMap::get(numMapDims, numMapSymbols,
+                             getAffineConstantExpr(
+                                 ubConst.getValue() + ubAdjustment, context));
         }
       }
     }
@@ -1669,13 +1671,13 @@ void FlatAffineRelation::compose(const FlatAffineRelation &other) {
 
   // Add and match domain of `rel` to domain of `this`.
   for (unsigned i = 0, e = rel.getNumDomainDims(); i < e; ++i)
-    if (relMaybeValues[i].has_value())
-      setValue(i, relMaybeValues[i].value());
+    if (relMaybeValues[i].hasValue())
+      setValue(i, relMaybeValues[i].getValue());
   // Add and match range of `this` to range of `rel`.
   for (unsigned i = 0, e = getNumRangeDims(); i < e; ++i) {
     unsigned rangeIdx = rel.getNumDomainDims() + i;
-    if (thisMaybeValues[rangeIdx].has_value())
-      rel.setValue(rangeIdx, thisMaybeValues[rangeIdx].value());
+    if (thisMaybeValues[rangeIdx].hasValue())
+      rel.setValue(rangeIdx, thisMaybeValues[rangeIdx].getValue());
   }
 
   // Append `this` to `rel` and simplify constraints.

diff  --git a/mlir/lib/Dialect/Affine/Analysis/LoopAnalysis.cpp b/mlir/lib/Dialect/Affine/Analysis/LoopAnalysis.cpp
index f8c43e7ca4dc5..0620a593d2063 100644
--- a/mlir/lib/Dialect/Affine/Analysis/LoopAnalysis.cpp
+++ b/mlir/lib/Dialect/Affine/Analysis/LoopAnalysis.cpp
@@ -92,9 +92,9 @@ Optional<uint64_t> mlir::getConstantTripCount(AffineForOp forOp) {
   Optional<uint64_t> tripCount;
   for (auto resultExpr : map.getResults()) {
     if (auto constExpr = resultExpr.dyn_cast<AffineConstantExpr>()) {
-      if (tripCount)
-        tripCount =
-            std::min(*tripCount, static_cast<uint64_t>(constExpr.getValue()));
+      if (tripCount.hasValue())
+        tripCount = std::min(tripCount.getValue(),
+                             static_cast<uint64_t>(constExpr.getValue()));
       else
         tripCount = constExpr.getValue();
     } else
@@ -132,13 +132,13 @@ uint64_t mlir::getLargestDivisorOfTripCount(AffineForOp forOp) {
       // Trip count is not a known constant; return its largest known divisor.
       thisGcd = resultExpr.getLargestKnownDivisor();
     }
-    if (gcd)
-      gcd = llvm::GreatestCommonDivisor64(*gcd, thisGcd);
+    if (gcd.hasValue())
+      gcd = llvm::GreatestCommonDivisor64(gcd.getValue(), thisGcd);
     else
       gcd = thisGcd;
   }
-  assert(gcd.has_value() && "value expected per above logic");
-  return gcd.value();
+  assert(gcd.hasValue() && "value expected per above logic");
+  return gcd.getValue();
 }
 
 /// Given an induction variable `iv` of type AffineForOp and an access `index`

diff  --git a/mlir/lib/Dialect/Affine/Analysis/Utils.cpp b/mlir/lib/Dialect/Affine/Analysis/Utils.cpp
index 501570633f353..6a9a03886f5d9 100644
--- a/mlir/lib/Dialect/Affine/Analysis/Utils.cpp
+++ b/mlir/lib/Dialect/Affine/Analysis/Utils.cpp
@@ -375,8 +375,8 @@ Optional<int64_t> MemRefRegion::getConstantBoundingSizeAndShape(
     SmallVector<int64_t, 4> lb;
     Optional<int64_t> 
diff  =
         cstWithShapeBounds.getConstantBoundOnDimSize(d, &lb, &lbDivisor);
-    if (
diff ) {
-      
diff Constant = 
diff .value();
+    if (
diff .hasValue()) {
+      
diff Constant = 
diff .getValue();
       assert(
diff Constant >= 0 && "Dim size bound can't be negative");
       assert(lbDivisor > 0);
     } else {
@@ -1012,17 +1012,17 @@ bool mlir::buildSliceTripCountMap(
         continue;
       }
       Optional<uint64_t> maybeConstTripCount = getConstantTripCount(forOp);
-      if (maybeConstTripCount) {
-        (*tripCountMap)[op] = maybeConstTripCount.value();
+      if (maybeConstTripCount.hasValue()) {
+        (*tripCountMap)[op] = maybeConstTripCount.getValue();
         continue;
       }
       return false;
     }
     Optional<uint64_t> tripCount = getConstDifference(lbMap, ubMap);
     // Slice bounds are created with a constant ub - lb 
diff erence.
-    if (!tripCount.has_value())
+    if (!tripCount.hasValue())
       return false;
-    (*tripCountMap)[op] = tripCount.value();
+    (*tripCountMap)[op] = tripCount.getValue();
   }
   return true;
 }
@@ -1320,9 +1320,9 @@ static Optional<int64_t> getMemoryFootprintBytes(Block &block,
   int64_t totalSizeInBytes = 0;
   for (const auto &region : regions) {
     Optional<int64_t> size = region.second->getRegionSize();
-    if (!size.has_value())
+    if (!size.hasValue())
       return None;
-    totalSizeInBytes += size.value();
+    totalSizeInBytes += size.getValue();
   }
   return totalSizeInBytes;
 }

diff  --git a/mlir/lib/Dialect/Affine/IR/AffineOps.cpp b/mlir/lib/Dialect/Affine/IR/AffineOps.cpp
index 6a6827c9f3eb3..01f651d4f57fa 100644
--- a/mlir/lib/Dialect/Affine/IR/AffineOps.cpp
+++ b/mlir/lib/Dialect/Affine/IR/AffineOps.cpp
@@ -336,8 +336,9 @@ static bool isDimOpValidSymbol(OpTy dimOp, Region *region) {
   // The dim op is also okay if its operand memref is a view/subview whose
   // corresponding size is a valid symbol.
   Optional<int64_t> index = dimOp.getConstantIndex();
-  assert(index && "expect only `dim` operations with a constant index");
-  int64_t i = *index;
+  assert(index.hasValue() &&
+         "expect only `dim` operations with a constant index");
+  int64_t i = index.getValue();
   return TypeSwitch<Operation *, bool>(dimOp.source().getDefiningOp())
       .Case<memref::ViewOp, memref::SubViewOp, memref::AllocOp>(
           [&](auto op) { return isMemRefSizeValidSymbol(op, i, region); })
@@ -1712,12 +1713,12 @@ struct AffineForEmptyLoopFolder : public OpRewritePattern<AffineForOp> {
     }
     // Bail out when the trip count is unknown and the loop returns any value
     // defined outside of the loop or any iterArg out of order.
-    if (!tripCount.has_value() &&
+    if (!tripCount.hasValue() &&
         (hasValDefinedOutsideLoop || iterArgsNotInOrder))
       return failure();
     // Bail out when the loop iterates more than once and it returns any iterArg
     // out of order.
-    if (tripCount.has_value() && *tripCount >= 2 && iterArgsNotInOrder)
+    if (tripCount.hasValue() && tripCount.getValue() >= 2 && iterArgsNotInOrder)
       return failure();
     rewriter.replaceOp(forOp, replacements);
     return success();
@@ -1750,18 +1751,19 @@ OperandRange AffineForOp::getSuccessorEntryOperands(Optional<unsigned> index) {
 void AffineForOp::getSuccessorRegions(
     Optional<unsigned> index, ArrayRef<Attribute> operands,
     SmallVectorImpl<RegionSuccessor> &regions) {
-  assert((!index || *index == 0) && "expected loop region");
+  assert((!index.hasValue() || index.getValue() == 0) &&
+         "expected loop region");
   // The loop may typically branch back to its body or to the parent operation.
   // If the predecessor is the parent op and the trip count is known to be at
   // least one, branch into the body using the iterator arguments. And in cases
   // we know the trip count is zero, it can only branch back to its parent.
   Optional<uint64_t> tripCount = getTrivialConstantTripCount(*this);
-  if (!index && tripCount) {
-    if (tripCount.value() > 0) {
+  if (!index.hasValue() && tripCount.hasValue()) {
+    if (tripCount.getValue() > 0) {
       regions.push_back(RegionSuccessor(&getLoopBody(), getRegionIterArgs()));
       return;
     }
-    if (tripCount.value() == 0) {
+    if (tripCount.getValue() == 0) {
       regions.push_back(RegionSuccessor(getResults()));
       return;
     }
@@ -3588,8 +3590,8 @@ ParseResult AffineParallelOp::parse(OpAsmParser &parser,
           arith::symbolizeAtomicRMWKind(attrVal.getValue());
       if (!reduction)
         return parser.emitError(loc, "invalid reduction value: ") << attrVal;
-      reductions.push_back(
-          builder.getI64IntegerAttr(static_cast<int64_t>(reduction.value())));
+      reductions.push_back(builder.getI64IntegerAttr(
+          static_cast<int64_t>(reduction.getValue())));
       // While we keep getting commas, keep parsing.
       return success();
     };

diff  --git a/mlir/lib/Dialect/Affine/Transforms/AffineDataCopyGeneration.cpp b/mlir/lib/Dialect/Affine/Transforms/AffineDataCopyGeneration.cpp
index 18a10c493eb7c..864f10991c748 100644
--- a/mlir/lib/Dialect/Affine/Transforms/AffineDataCopyGeneration.cpp
+++ b/mlir/lib/Dialect/Affine/Transforms/AffineDataCopyGeneration.cpp
@@ -142,8 +142,9 @@ void AffineDataCopyGeneration::runOnBlock(Block *block,
         Optional<int64_t> footprint =
             getMemoryFootprintBytes(forOp,
                                     /*memorySpace=*/0);
-        return (footprint &&
-                static_cast<uint64_t>(*footprint) > fastMemCapacityBytes);
+        return (footprint.hasValue() &&
+                static_cast<uint64_t>(footprint.getValue()) >
+                    fastMemCapacityBytes);
       };
 
       // If the memory footprint of the 'affine.for' loop is higher than fast

diff  --git a/mlir/lib/Dialect/Affine/Transforms/LoopFusion.cpp b/mlir/lib/Dialect/Affine/Transforms/LoopFusion.cpp
index f68662080e70f..b77ef90b471b9 100644
--- a/mlir/lib/Dialect/Affine/Transforms/LoopFusion.cpp
+++ b/mlir/lib/Dialect/Affine/Transforms/LoopFusion.cpp
@@ -441,15 +441,15 @@ struct MemRefDependenceGraph {
       ++pos;
     }
 
-    if (firstSrcDepPos) {
-      if (lastDstDepPos) {
-        if (firstSrcDepPos.value() <= lastDstDepPos.value()) {
+    if (firstSrcDepPos.hasValue()) {
+      if (lastDstDepPos.hasValue()) {
+        if (firstSrcDepPos.getValue() <= lastDstDepPos.getValue()) {
           // No valid insertion point exists which preserves dependences.
           return nullptr;
         }
       }
       // Return the insertion point at 'firstSrcDepPos'.
-      return depInsts[firstSrcDepPos.value()];
+      return depInsts[firstSrcDepPos.getValue()];
     }
     // No dependence targets in range (or only dst deps in range), return
     // 'dstNodInst' insertion point.
@@ -942,10 +942,10 @@ static Value createPrivateMemRef(AffineForOp forOp, Operation *srcStoreOpInst,
   // Create 'newMemRefType' using 'newShape' from MemRefRegion accessed
   // by 'srcStoreOpInst'.
   uint64_t bufSize =
-      getMemRefEltSizeInBytes(oldMemRefType) * numElements.value();
+      getMemRefEltSizeInBytes(oldMemRefType) * numElements.getValue();
   unsigned newMemSpace;
-  if (bufSize <= localBufSizeThreshold && fastMemorySpace.has_value()) {
-    newMemSpace = fastMemorySpace.value();
+  if (bufSize <= localBufSizeThreshold && fastMemorySpace.hasValue()) {
+    newMemSpace = fastMemorySpace.getValue();
   } else {
     newMemSpace = oldMemRefType.getMemorySpaceAsInt();
   }
@@ -1141,9 +1141,9 @@ static bool isFusionProfitable(Operation *srcOpInst, Operation *srcStoreOpInst,
 
   Optional<int64_t> maybeSrcWriteRegionSizeBytes =
       srcWriteRegion.getRegionSize();
-  if (!maybeSrcWriteRegionSizeBytes.has_value())
+  if (!maybeSrcWriteRegionSizeBytes.hasValue())
     return false;
-  int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.value();
+  int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.getValue();
 
   // Compute op instance count for the src loop nest.
   uint64_t dstLoopNestCost = getComputeCost(dstForOp, dstLoopNestStats);
@@ -1183,14 +1183,15 @@ static bool isFusionProfitable(Operation *srcOpInst, Operation *srcStoreOpInst,
 
     Optional<int64_t> maybeSliceWriteRegionSizeBytes =
         sliceWriteRegion.getRegionSize();
-    if (!maybeSliceWriteRegionSizeBytes.has_value() ||
-        *maybeSliceWriteRegionSizeBytes == 0) {
+    if (!maybeSliceWriteRegionSizeBytes.hasValue() ||
+        maybeSliceWriteRegionSizeBytes.getValue() == 0) {
       LLVM_DEBUG(llvm::dbgs()
                  << "Failed to get slice write region size at loopDepth: " << i
                  << "\n");
       continue;
     }
-    int64_t sliceWriteRegionSizeBytes = maybeSliceWriteRegionSizeBytes.value();
+    int64_t sliceWriteRegionSizeBytes =
+        maybeSliceWriteRegionSizeBytes.getValue();
 
     // If we are fusing for reuse, check that write regions remain the same.
     // TODO: Write region check should check sizes and offsets in
@@ -1267,11 +1268,11 @@ static bool isFusionProfitable(Operation *srcOpInst, Operation *srcStoreOpInst,
     return false;
   }
 
-  auto srcMemSizeVal = srcMemSize.value();
-  auto dstMemSizeVal = dstMemSize.value();
+  auto srcMemSizeVal = srcMemSize.getValue();
+  auto dstMemSizeVal = dstMemSize.getValue();
 
   assert(sliceMemEstimate && "expected value");
-  auto fusedMem = dstMemSizeVal + sliceMemEstimate.value();
+  auto fusedMem = dstMemSizeVal + sliceMemEstimate.getValue();
 
   LLVM_DEBUG(llvm::dbgs() << "   src mem: " << srcMemSizeVal << "\n"
                           << "   dst mem: " << dstMemSizeVal << "\n"

diff  --git a/mlir/lib/Dialect/Affine/Utils/LoopUtils.cpp b/mlir/lib/Dialect/Affine/Utils/LoopUtils.cpp
index 04586c90a7b55..09f11ebfaeab3 100644
--- a/mlir/lib/Dialect/Affine/Utils/LoopUtils.cpp
+++ b/mlir/lib/Dialect/Affine/Utils/LoopUtils.cpp
@@ -405,13 +405,13 @@ checkTilingLegalityImpl(MutableArrayRef<mlir::AffineForOp> origLoops) {
         LLVM_DEBUG(dstAccess.opInst->dump(););
         for (unsigned k = 0, e = depComps.size(); k < e; k++) {
           DependenceComponent depComp = depComps[k];
-          if (depComp.lb.has_value() && depComp.ub.has_value() &&
-              depComp.lb.value() < depComp.ub.value() &&
-              depComp.ub.value() < 0) {
+          if (depComp.lb.hasValue() && depComp.ub.hasValue() &&
+              depComp.lb.getValue() < depComp.ub.getValue() &&
+              depComp.ub.getValue() < 0) {
             LLVM_DEBUG(llvm::dbgs()
                        << "Dependence component lb = "
-                       << Twine(depComp.lb.value())
-                       << " ub = " << Twine(depComp.ub.value())
+                       << Twine(depComp.lb.getValue())
+                       << " ub = " << Twine(depComp.ub.getValue())
                        << " is negative  at depth: " << Twine(d)
                        << " and thus violates the legality rule.\n");
             return false;
@@ -802,11 +802,11 @@ constructTiledIndexSetHyperRect(MutableArrayRef<AffineForOp> origLoops,
     newLoops[width + i].setStep(origLoops[i].getStep());
 
     // Set the upper bound.
-    if (mayBeConstantCount && *mayBeConstantCount < tileSizes[i]) {
+    if (mayBeConstantCount && mayBeConstantCount.getValue() < tileSizes[i]) {
       // Trip count is less than the tile size: upper bound is lower bound +
       // trip count * stepSize.
-      AffineMap ubMap = b.getSingleDimShiftAffineMap(*mayBeConstantCount *
-                                                     origLoops[i].getStep());
+      AffineMap ubMap = b.getSingleDimShiftAffineMap(
+          mayBeConstantCount.getValue() * origLoops[i].getStep());
       newLoops[width + i].setUpperBound(
           /*operands=*/newLoops[i].getInductionVar(), ubMap);
     } else if (largestDiv % tileSizes[i] != 0) {
@@ -974,8 +974,8 @@ void mlir::getTileableBands(func::FuncOp f,
 /// Unrolls this loop completely.
 LogicalResult mlir::loopUnrollFull(AffineForOp forOp) {
   Optional<uint64_t> mayBeConstantTripCount = getConstantTripCount(forOp);
-  if (mayBeConstantTripCount) {
-    uint64_t tripCount = mayBeConstantTripCount.value();
+  if (mayBeConstantTripCount.hasValue()) {
+    uint64_t tripCount = mayBeConstantTripCount.getValue();
     if (tripCount == 0)
       return success();
     if (tripCount == 1)
@@ -990,8 +990,9 @@ LogicalResult mlir::loopUnrollFull(AffineForOp forOp) {
 LogicalResult mlir::loopUnrollUpToFactor(AffineForOp forOp,
                                          uint64_t unrollFactor) {
   Optional<uint64_t> mayBeConstantTripCount = getConstantTripCount(forOp);
-  if (mayBeConstantTripCount && *mayBeConstantTripCount < unrollFactor)
-    return loopUnrollByFactor(forOp, mayBeConstantTripCount.value());
+  if (mayBeConstantTripCount.hasValue() &&
+      mayBeConstantTripCount.getValue() < unrollFactor)
+    return loopUnrollByFactor(forOp, mayBeConstantTripCount.getValue());
   return loopUnrollByFactor(forOp, unrollFactor);
 }
 
@@ -1149,8 +1150,9 @@ LogicalResult mlir::loopUnrollByFactor(
 LogicalResult mlir::loopUnrollJamUpToFactor(AffineForOp forOp,
                                             uint64_t unrollJamFactor) {
   Optional<uint64_t> mayBeConstantTripCount = getConstantTripCount(forOp);
-  if (mayBeConstantTripCount && *mayBeConstantTripCount < unrollJamFactor)
-    return loopUnrollJamByFactor(forOp, mayBeConstantTripCount.value());
+  if (mayBeConstantTripCount.hasValue() &&
+      mayBeConstantTripCount.getValue() < unrollJamFactor)
+    return loopUnrollJamByFactor(forOp, mayBeConstantTripCount.getValue());
   return loopUnrollJamByFactor(forOp, unrollJamFactor);
 }
 
@@ -1571,8 +1573,8 @@ AffineForOp mlir::sinkSequentialLoops(AffineForOp forOp) {
     assert(depComps.size() >= maxLoopDepth);
     for (unsigned j = 0; j < maxLoopDepth; ++j) {
       DependenceComponent &depComp = depComps[j];
-      assert(depComp.lb.has_value() && depComp.ub.has_value());
-      if (depComp.lb.value() != 0 || depComp.ub.value() != 0)
+      assert(depComp.lb.hasValue() && depComp.ub.hasValue());
+      if (depComp.lb.getValue() != 0 || depComp.ub.getValue() != 0)
         isParallelLoop[j] = false;
     }
   }
@@ -2404,12 +2406,12 @@ LogicalResult mlir::affineDataCopyGenerate(Block::iterator begin,
   block->walk(begin, end, [&](Operation *opInst) {
     // Gather regions to allocate to buffers in faster memory space.
     if (auto loadOp = dyn_cast<AffineLoadOp>(opInst)) {
-      if ((filterMemRef.has_value() && filterMemRef != loadOp.getMemRef()) ||
+      if ((filterMemRef.hasValue() && filterMemRef != loadOp.getMemRef()) ||
           (loadOp.getMemRefType().getMemorySpaceAsInt() !=
            copyOptions.slowMemorySpace))
         return;
     } else if (auto storeOp = dyn_cast<AffineStoreOp>(opInst)) {
-      if ((filterMemRef.has_value() && filterMemRef != storeOp.getMemRef()) ||
+      if ((filterMemRef.hasValue() && filterMemRef != storeOp.getMemRef()) ||
           storeOp.getMemRefType().getMemorySpaceAsInt() !=
               copyOptions.slowMemorySpace)
         return;

diff  --git a/mlir/lib/Dialect/Affine/Utils/Utils.cpp b/mlir/lib/Dialect/Affine/Utils/Utils.cpp
index 5cfebeb668b72..5f9eee572cbbe 100644
--- a/mlir/lib/Dialect/Affine/Utils/Utils.cpp
+++ b/mlir/lib/Dialect/Affine/Utils/Utils.cpp
@@ -1792,11 +1792,11 @@ MemRefType mlir::normalizeMemRefType(MemRefType memrefType, OpBuilder b,
       // For a static memref and an affine map with no symbols, this is
       // always bounded.
       assert(ubConst && "should always have an upper bound");
-      if (ubConst.value() < 0)
+      if (ubConst.getValue() < 0)
         // This is due to an invalid map that maps to a negative space.
         return memrefType;
       // If dimension of new memrefType is dynamic, the value is -1.
-      newShape[d] = *ubConst + 1;
+      newShape[d] = ubConst.getValue() + 1;
     }
   }
 

diff  --git a/mlir/lib/Dialect/Arithmetic/Transforms/UnsignedWhenEquivalent.cpp b/mlir/lib/Dialect/Arithmetic/Transforms/UnsignedWhenEquivalent.cpp
index f4e0415c39b5c..f84990d0a8c47 100644
--- a/mlir/lib/Dialect/Arithmetic/Transforms/UnsignedWhenEquivalent.cpp
+++ b/mlir/lib/Dialect/Arithmetic/Transforms/UnsignedWhenEquivalent.cpp
@@ -23,9 +23,9 @@ using namespace mlir::arith;
 static LogicalResult staticallyNonNegative(IntRangeAnalysis &analysis,
                                            Value v) {
   Optional<ConstantIntRanges> result = analysis.getResult(v);
-  if (!result.has_value())
+  if (!result.hasValue())
     return failure();
-  const ConstantIntRanges &range = result.value();
+  const ConstantIntRanges &range = result.getValue();
   return success(range.smin().isNonNegative());
 }
 

diff  --git a/mlir/lib/Dialect/Bufferization/IR/BufferizationOps.cpp b/mlir/lib/Dialect/Bufferization/IR/BufferizationOps.cpp
index 20273c675a41b..37ff8e9be79e2 100644
--- a/mlir/lib/Dialect/Bufferization/IR/BufferizationOps.cpp
+++ b/mlir/lib/Dialect/Bufferization/IR/BufferizationOps.cpp
@@ -444,11 +444,11 @@ struct SimplifyClones : public OpRewritePattern<CloneOp> {
     llvm::Optional<Operation *> maybeCloneDeallocOp =
         memref::findDealloc(cloneOp.getOutput());
     // Skip if either of them has > 1 deallocate operations.
-    if (!maybeCloneDeallocOp.has_value())
+    if (!maybeCloneDeallocOp.hasValue())
       return failure();
     llvm::Optional<Operation *> maybeSourceDeallocOp =
         memref::findDealloc(source);
-    if (!maybeSourceDeallocOp.has_value())
+    if (!maybeSourceDeallocOp.hasValue())
       return failure();
     Operation *cloneDeallocOp = *maybeCloneDeallocOp;
     Operation *sourceDeallocOp = *maybeSourceDeallocOp;

diff  --git a/mlir/lib/Dialect/Bufferization/Transforms/BufferUtils.cpp b/mlir/lib/Dialect/Bufferization/Transforms/BufferUtils.cpp
index 7240e5b02a726..d631dc30982e3 100644
--- a/mlir/lib/Dialect/Bufferization/Transforms/BufferUtils.cpp
+++ b/mlir/lib/Dialect/Bufferization/Transforms/BufferUtils.cpp
@@ -158,11 +158,11 @@ bufferization::getGlobalFor(arith::ConstantOp constantOp, uint64_t alignment) {
     auto globalOp = dyn_cast<memref::GlobalOp>(&op);
     if (!globalOp)
       continue;
-    if (!globalOp.initial_value().has_value())
+    if (!globalOp.initial_value().hasValue())
       continue;
     uint64_t opAlignment =
-        globalOp.alignment().has_value() ? globalOp.alignment().value() : 0;
-    Attribute initialValue = globalOp.initial_value().value();
+        globalOp.alignment().hasValue() ? globalOp.alignment().getValue() : 0;
+    Attribute initialValue = globalOp.initial_value().getValue();
     if (opAlignment == alignment && initialValue == constantOp.getValue())
       return globalOp;
   }

diff  --git a/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp b/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp
index 1cff6f9c6b79d..3689522dd065e 100644
--- a/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp
+++ b/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp
@@ -114,9 +114,9 @@ static FuncOpAnalysisState getFuncOpAnalysisState(const AnalysisState &state,
   Optional<const FuncAnalysisState *> maybeState =
       state.getDialectState<FuncAnalysisState>(
           func::FuncDialect::getDialectNamespace());
-  if (!maybeState.has_value())
+  if (!maybeState.hasValue())
     return FuncOpAnalysisState::NotAnalyzed;
-  const auto &analyzedFuncOps = maybeState.value()->analyzedFuncOps;
+  const auto &analyzedFuncOps = maybeState.getValue()->analyzedFuncOps;
   auto it = analyzedFuncOps.find(funcOp);
   if (it == analyzedFuncOps.end())
     return FuncOpAnalysisState::NotAnalyzed;

diff  --git a/mlir/lib/Dialect/DLTI/DLTI.cpp b/mlir/lib/Dialect/DLTI/DLTI.cpp
index eaf6f1e619a01..046152a670924 100644
--- a/mlir/lib/Dialect/DLTI/DLTI.cpp
+++ b/mlir/lib/Dialect/DLTI/DLTI.cpp
@@ -73,11 +73,11 @@ DataLayoutEntryAttr DataLayoutEntryAttr::parse(AsmParser &parser) {
   std::string identifier;
   SMLoc idLoc = parser.getCurrentLocation();
   OptionalParseResult parsedType = parser.parseOptionalType(type);
-  if (parsedType.has_value() && failed(parsedType.value()))
+  if (parsedType.hasValue() && failed(parsedType.getValue()))
     return {};
-  if (!parsedType.has_value()) {
+  if (!parsedType.hasValue()) {
     OptionalParseResult parsedString = parser.parseOptionalString(&identifier);
-    if (!parsedString.has_value() || failed(parsedString.value())) {
+    if (!parsedString.hasValue() || failed(parsedString.getValue())) {
       parser.emitError(idLoc) << "expected a type or a quoted string";
       return {};
     }

diff  --git a/mlir/lib/Dialect/EmitC/IR/EmitC.cpp b/mlir/lib/Dialect/EmitC/IR/EmitC.cpp
index f2a19cd0a55af..be6dd41c029d0 100644
--- a/mlir/lib/Dialect/EmitC/IR/EmitC.cpp
+++ b/mlir/lib/Dialect/EmitC/IR/EmitC.cpp
@@ -151,7 +151,7 @@ ParseResult IncludeOp::parse(OpAsmParser &parser, OperationState &result) {
   StringAttr include;
   OptionalParseResult includeParseResult =
       parser.parseOptionalAttribute(include, "include", result.attributes);
-  if (!includeParseResult.has_value())
+  if (!includeParseResult.hasValue())
     return parser.emitError(parser.getNameLoc()) << "expected string attribute";
 
   if (standardInclude && parser.parseOptionalGreater())

diff  --git a/mlir/lib/Dialect/GPU/Transforms/SerializeToBlob.cpp b/mlir/lib/Dialect/GPU/Transforms/SerializeToBlob.cpp
index 29f244884ac13..35bf5942f24d0 100644
--- a/mlir/lib/Dialect/GPU/Transforms/SerializeToBlob.cpp
+++ b/mlir/lib/Dialect/GPU/Transforms/SerializeToBlob.cpp
@@ -75,10 +75,10 @@ void gpu::SerializeToBlobPass::runOnOperation() {
   Optional<std::string> maybeTargetISA =
       translateToISA(*llvmModule, *targetMachine);
 
-  if (!maybeTargetISA.has_value())
+  if (!maybeTargetISA.hasValue())
     return signalPassFailure();
 
-  std::string targetISA = std::move(maybeTargetISA.value());
+  std::string targetISA = std::move(maybeTargetISA.getValue());
 
   LLVM_DEBUG({
     llvm::dbgs() << "ISA for module: " << getOperation().getNameAttr() << "\n";

diff  --git a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
index 0cc2fca7b70b2..63a89d5ec10e5 100644
--- a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
+++ b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
@@ -237,8 +237,9 @@ ParseResult AllocaOp::parse(OpAsmParser &parser, OperationState &result) {
 
   Optional<NamedAttribute> alignmentAttr =
       result.attributes.getNamed("alignment");
-  if (alignmentAttr.has_value()) {
-    auto alignmentInt = alignmentAttr->getValue().dyn_cast<IntegerAttr>();
+  if (alignmentAttr.hasValue()) {
+    auto alignmentInt =
+        alignmentAttr.getValue().getValue().dyn_cast<IntegerAttr>();
     if (!alignmentInt)
       return parser.emitError(parser.getNameLoc(),
                               "expected integer alignment");
@@ -271,11 +272,11 @@ ParseResult AllocaOp::parse(OpAsmParser &parser, OperationState &result) {
 /// the attribute, but not both.
 static LogicalResult verifyOpaquePtr(Operation *op, LLVMPointerType ptrType,
                                      Optional<Type> ptrElementType) {
-  if (ptrType.isOpaque() && !ptrElementType.has_value()) {
+  if (ptrType.isOpaque() && !ptrElementType.hasValue()) {
     return op->emitOpError() << "expected '" << kElemTypeAttrName
                              << "' attribute if opaque pointer type is used";
   }
-  if (!ptrType.isOpaque() && ptrElementType.has_value()) {
+  if (!ptrType.isOpaque() && ptrElementType.hasValue()) {
     return op->emitOpError()
            << "unexpected '" << kElemTypeAttrName
            << "' attribute when non-opaque pointer type is used";
@@ -340,10 +341,10 @@ static ParseResult parseSwitchOpCases(
   do {
     int64_t value = 0;
     OptionalParseResult integerParseResult = parser.parseOptionalInteger(value);
-    if (values.empty() && !integerParseResult.has_value())
+    if (values.empty() && !integerParseResult.hasValue())
       return success();
 
-    if (!integerParseResult.has_value() || integerParseResult.value())
+    if (!integerParseResult.hasValue() || integerParseResult.getValue())
       return failure();
     values.push_back(APInt(bitWidth, value));
 
@@ -616,8 +617,8 @@ parseGEPIndices(OpAsmParser &parser,
     int32_t constantIndex;
     OptionalParseResult parsedInteger =
         parser.parseOptionalInteger(constantIndex);
-    if (parsedInteger.has_value()) {
-      if (failed(parsedInteger.value()))
+    if (parsedInteger.hasValue()) {
+      if (failed(parsedInteger.getValue()))
         return failure();
       constantIndices.push_back(constantIndex);
       return success();
@@ -915,13 +916,13 @@ LogicalResult InvokeOp::verify() {
 
 void InvokeOp::print(OpAsmPrinter &p) {
   auto callee = getCallee();
-  bool isDirect = callee.has_value();
+  bool isDirect = callee.hasValue();
 
   p << ' ';
 
   // Either function name or pointer
   if (isDirect)
-    p.printSymbolName(callee.value());
+    p.printSymbolName(callee.getValue());
   else
     p << getOperand(0);
 
@@ -1208,13 +1209,13 @@ LogicalResult CallOp::verify() {
 
 void CallOp::print(OpAsmPrinter &p) {
   auto callee = getCallee();
-  bool isDirect = callee.has_value();
+  bool isDirect = callee.hasValue();
 
   // Print the direct callee if present as a function attribute, or an indirect
   // callee (first operand) otherwise.
   p << ' ';
   if (isDirect)
-    p.printSymbolName(callee.value());
+    p.printSymbolName(callee.getValue());
   else
     p << getOperand(0);
 
@@ -1926,7 +1927,7 @@ ParseResult GlobalOp::parse(OpAsmParser &parser, OperationState &result) {
     OptionalParseResult parseResult =
         parser.parseOptionalRegion(initRegion, /*arguments=*/{},
                                    /*argTypes=*/{});
-    if (parseResult.has_value() && failed(*parseResult))
+    if (parseResult.hasValue() && failed(*parseResult))
       return failure();
   }
 
@@ -1986,8 +1987,8 @@ LogicalResult GlobalOp::verify() {
   }
 
   Optional<uint64_t> alignAttr = getAlignment();
-  if (alignAttr.has_value()) {
-    uint64_t value = alignAttr.value();
+  if (alignAttr.hasValue()) {
+    uint64_t value = alignAttr.getValue();
     if (!llvm::isPowerOf2_64(value))
       return emitError() << "alignment attribute is not a power of 2";
   }
@@ -2260,7 +2261,7 @@ ParseResult LLVMFuncOp::parse(OpAsmParser &parser, OperationState &result) {
   auto *body = result.addRegion();
   OptionalParseResult parseResult =
       parser.parseOptionalRegion(*body, entryArgs);
-  return failure(parseResult.has_value() && failed(*parseResult));
+  return failure(parseResult.hasValue() && failed(*parseResult));
 }
 
 // Print the LLVMFuncOp. Collects argument and result types and passes them to

diff  --git a/mlir/lib/Dialect/LLVMIR/IR/LLVMTypeSyntax.cpp b/mlir/lib/Dialect/LLVMIR/IR/LLVMTypeSyntax.cpp
index 295f59f6b6d55..04015efea3e9f 100644
--- a/mlir/lib/Dialect/LLVMIR/IR/LLVMTypeSyntax.cpp
+++ b/mlir/lib/Dialect/LLVMIR/IR/LLVMTypeSyntax.cpp
@@ -232,7 +232,7 @@ static LLVMPointerType parsePointerType(AsmParser &parser) {
 
   unsigned addressSpace = 0;
   OptionalParseResult opr = parser.parseOptionalInteger(addressSpace);
-  if (opr.has_value()) {
+  if (opr.hasValue()) {
     if (failed(*opr) || parser.parseGreater())
       return LLVMPointerType();
     return parser.getChecked<LLVMPointerType>(loc, parser.getContext(),
@@ -442,8 +442,8 @@ static Type dispatchParse(AsmParser &parser, bool allowAny = true) {
   // Try parsing any MLIR type.
   Type type;
   OptionalParseResult result = parser.parseOptionalType(type);
-  if (result.has_value()) {
-    if (failed(result.value()))
+  if (result.hasValue()) {
+    if (failed(result.getValue()))
       return nullptr;
     if (!allowAny) {
       parser.emitError(keyLoc) << "unexpected type, expected keyword";

diff  --git a/mlir/lib/Dialect/LLVMIR/IR/NVVMDialect.cpp b/mlir/lib/Dialect/LLVMIR/IR/NVVMDialect.cpp
index d5d84bdd470d7..7d4691a96b823 100644
--- a/mlir/lib/Dialect/LLVMIR/IR/NVVMDialect.cpp
+++ b/mlir/lib/Dialect/LLVMIR/IR/NVVMDialect.cpp
@@ -117,15 +117,15 @@ static bool isIntegerPtxType(MMATypes type) {
 MMATypes MmaOp::accumPtxType() {
   Optional<mlir::NVVM::MMATypes> val = inferOperandMMAType(
       getODSOperands(2).getTypes().front(), /*isAccum=*/true);
-  assert(val && "accumulator PTX type should always be inferrable");
-  return val.value();
+  assert(val.hasValue() && "accumulator PTX type should always be inferrable");
+  return val.getValue();
 }
 
 MMATypes MmaOp::resultPtxType() {
   Optional<mlir::NVVM::MMATypes> val =
       inferOperandMMAType(getResult().getType(), /*isAccum=*/true);
-  assert(val && "result PTX type should always be inferrable");
-  return val.value();
+  assert(val.hasValue() && "result PTX type should always be inferrable");
+  return val.getValue();
 }
 
 void MmaOp::print(OpAsmPrinter &p) {
@@ -224,10 +224,10 @@ void MmaOp::build(OpBuilder &builder, OperationState &result, Type resultType,
     result.addAttribute("layoutB", MMALayoutAttr::get(ctx, MMALayout::col));
   }
 
-  if (intOverflow)
+  if (intOverflow.hasValue())
     result.addAttribute("intOverflowBehavior",
                         MMAIntOverflowAttr::get(ctx, *intOverflow));
-  if (b1Op)
+  if (b1Op.hasValue())
     result.addAttribute("b1Op", MMAB1OpAttr::get(ctx, *b1Op));
 
   result.addTypes(resultType);
@@ -311,13 +311,13 @@ ParseResult MmaOp::parse(OpAsmParser &parser, OperationState &result) {
   for (unsigned idx = 0; idx < names.size(); idx++) {
     const auto &frag = frags[idx];
     Optional<NamedAttribute> attr = namedAttributes.getNamed(names[idx]);
-    if (!frag.elemtype.has_value() && !attr) {
+    if (!frag.elemtype.hasValue() && !attr.hasValue()) {
       return parser.emitError(
           parser.getNameLoc(),
           "attribute " + names[idx] +
               " is not provided explicitly and cannot be inferred");
     }
-    if (!attr)
+    if (!attr.hasValue())
       result.addAttribute(
           names[idx], MMATypesAttr::get(parser.getContext(), *frag.elemtype));
   }
@@ -399,10 +399,10 @@ LogicalResult MmaOp::verify() {
       break;
     default:
       return emitError("invalid shape or multiplicand type: " +
-                       stringifyEnum(getMultiplicandAPtxType().value()));
+                       stringifyEnum(getMultiplicandAPtxType().getValue()));
     }
 
-    if (isIntegerPtxType(getMultiplicandAPtxType().value())) {
+    if (isIntegerPtxType(getMultiplicandAPtxType().getValue())) {
       expectedResult.push_back(s32x4StructTy);
       expectedC.emplace_back(4, i32Ty);
       multiplicandFragType = i32Ty;
@@ -440,16 +440,16 @@ LogicalResult MmaOp::verify() {
           context, SmallVector<Type>(2, f64Ty)));
       allowedShapes.push_back({8, 8, 4});
     }
-    if (isIntegerPtxType(getMultiplicandAPtxType().value())) {
+    if (isIntegerPtxType(getMultiplicandAPtxType().getValue())) {
       expectedA.push_back({i32Ty});
       expectedB.push_back({i32Ty});
       expectedC.push_back({i32Ty, i32Ty});
       expectedResult.push_back(s32x2StructTy);
-      if (isInt4PtxType(getMultiplicandAPtxType().value()))
+      if (isInt4PtxType(getMultiplicandAPtxType().getValue()))
         allowedShapes.push_back({8, 8, 32});
-      if (isInt8PtxType(getMultiplicandAPtxType().value()))
+      if (isInt8PtxType(getMultiplicandAPtxType().getValue()))
         allowedShapes.push_back({8, 8, 16});
-      if (getMultiplicandAPtxType().value() == MMATypes::b1)
+      if (getMultiplicandAPtxType().getValue() == MMATypes::b1)
         allowedShapes.push_back({8, 8, 128});
     }
   }

diff  --git a/mlir/lib/Dialect/Linalg/Transforms/Fusion.cpp b/mlir/lib/Dialect/Linalg/Transforms/Fusion.cpp
index 8bff2c2b2f268..2b783a85263b4 100644
--- a/mlir/lib/Dialect/Linalg/Transforms/Fusion.cpp
+++ b/mlir/lib/Dialect/Linalg/Transforms/Fusion.cpp
@@ -777,14 +777,16 @@ fuseOperations(OpBuilder &b, LinalgOp rootOp, TiledLinalgOp tiledLinalgOp,
           LinalgDependenceGraph::DependenceType::RAW)
         continue;
 
-      unsigned resultIndex = dependence.getDependentOpViewResultNum().value();
+      unsigned resultIndex =
+          dependence.getDependentOpViewResultNum().getValue();
       LinalgOp consumer = origOpToFusedOp.lookup(dependence.getIndexingOp());
       if (!consumer)
         continue;
 
       Value replacementValue = fusedOp.getOperation()->getResult(resultIndex);
       consumer.getOperation()->setOperand(
-          dependence.getIndexingOpViewOperandNum().value(), replacementValue);
+          dependence.getIndexingOpViewOperandNum().getValue(),
+          replacementValue);
     }
 
     // At this point, all Linalg uses of the tensors produced by `origOp` have

diff  --git a/mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp b/mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp
index 88d986bd0037a..1f2ca258ce33f 100644
--- a/mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp
+++ b/mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp
@@ -49,8 +49,8 @@ static Value allocBuffer(ImplicitLocOpBuilder &b,
   auto width = layout.getTypeSize(elementType);
 
   IntegerAttr alignmentAttr;
-  if (alignment)
-    alignmentAttr = b.getI64IntegerAttr(alignment.value());
+  if (alignment.hasValue())
+    alignmentAttr = b.getI64IntegerAttr(alignment.getValue());
 
   // Static buffer.
   if (auto cst = allocSize.getDefiningOp<arith::ConstantIndexOp>()) {
@@ -233,7 +233,7 @@ FailureOr<PromotionInfo> mlir::linalg::promoteSubviewAsNewBuffer(
     Value size =
         failed(upperBound)
             ? rangeValue.size
-            : b.create<arith::ConstantIndexOp>(loc, upperBound.value());
+            : b.create<arith::ConstantIndexOp>(loc, upperBound.getValue());
     LLVM_DEBUG(llvm::dbgs() << "Extracted tightest: " << size << "\n");
     fullSizes.push_back(size);
     partialSizes.push_back(

diff  --git a/mlir/lib/Dialect/Linalg/Transforms/Transforms.cpp b/mlir/lib/Dialect/Linalg/Transforms/Transforms.cpp
index 67ca94b95f1e2..a3b95b3fffefc 100644
--- a/mlir/lib/Dialect/Linalg/Transforms/Transforms.cpp
+++ b/mlir/lib/Dialect/Linalg/Transforms/Transforms.cpp
@@ -102,8 +102,9 @@ LogicalResult mlir::linalg::LinalgTransformationFilter::checkAndNotify(
 void mlir::linalg::LinalgTransformationFilter::
     replaceLinalgTransformationFilter(PatternRewriter &rewriter,
                                       Operation *op) const {
-  if (replacement)
-    op->setAttr(LinalgTransforms::kLinalgTransformMarker, replacement.value());
+  if (replacement.hasValue())
+    op->setAttr(LinalgTransforms::kLinalgTransformMarker,
+                replacement.getValue());
   else
     op->removeAttr(
         rewriter.getStringAttr(LinalgTransforms::kLinalgTransformMarker));
@@ -440,10 +441,10 @@ LogicalResult mlir::linalg::LinalgBaseTileAndFusePattern::matchAndRewrite(
     if (failed(unfusedTiledOp))
       return failure();
     rewriter.replaceOp(tiledAndFusedOps->op,
-                       getTiledOpResult(unfusedTiledOp.value()));
+                       getTiledOpResult(unfusedTiledOp.getValue()));
     tiledAndFusedOps->op = unfusedTiledOp->op;
   }
-  op->replaceAllUsesWith(getTiledAndFusedOpResult(tiledAndFusedOps.value()));
+  op->replaceAllUsesWith(getTiledAndFusedOpResult(tiledAndFusedOps.getValue()));
 
   filter.replaceLinalgTransformationFilter(rewriter,
                                            tiledAndFusedOps->op.getOperation());

diff  --git a/mlir/lib/Dialect/MemRef/IR/MemRefOps.cpp b/mlir/lib/Dialect/MemRef/IR/MemRefOps.cpp
index 85351c570d9e9..014c5be2c3648 100644
--- a/mlir/lib/Dialect/MemRef/IR/MemRefOps.cpp
+++ b/mlir/lib/Dialect/MemRef/IR/MemRefOps.cpp
@@ -1297,8 +1297,8 @@ LogicalResult GlobalOp::verify() {
 
   // Verify that the initial value, if present, is either a unit attribute or
   // an elements attribute.
-  if (initial_value().has_value()) {
-    Attribute initValue = initial_value().value();
+  if (initial_value().hasValue()) {
+    Attribute initValue = initial_value().getValue();
     if (!initValue.isa<UnitAttr>() && !initValue.isa<ElementsAttr>())
       return emitOpError("initial value should be a unit or elements "
                          "attribute, but got ")
@@ -1329,8 +1329,8 @@ LogicalResult GlobalOp::verify() {
 
 ElementsAttr GlobalOp::getConstantInitValue() {
   auto initVal = initial_value();
-  if (constant() && initVal.has_value())
-    return initVal->cast<ElementsAttr>();
+  if (constant() && initVal.hasValue())
+    return initVal.getValue().cast<ElementsAttr>();
   return {};
 }
 
@@ -2483,14 +2483,14 @@ static bool isTrivialSubViewOp(SubViewOp subViewOp) {
   // Check offsets are zero.
   if (llvm::any_of(mixedOffsets, [](OpFoldResult ofr) {
         Optional<int64_t> intValue = getConstantIntValue(ofr);
-        return !intValue || *intValue != 0;
+        return !intValue || intValue.getValue() != 0;
       }))
     return false;
 
   // Check strides are one.
   if (llvm::any_of(mixedStrides, [](OpFoldResult ofr) {
         Optional<int64_t> intValue = getConstantIntValue(ofr);
-        return !intValue || *intValue != 1;
+        return !intValue || intValue.getValue() != 1;
       }))
     return false;
 

diff  --git a/mlir/lib/Dialect/OpenACC/IR/OpenACC.cpp b/mlir/lib/Dialect/OpenACC/IR/OpenACC.cpp
index b2960a68144f9..ec1b6e942e80c 100644
--- a/mlir/lib/Dialect/OpenACC/IR/OpenACC.cpp
+++ b/mlir/lib/Dialect/OpenACC/IR/OpenACC.cpp
@@ -243,7 +243,7 @@ ParseResult ParallelOp::parse(OpAsmParser &parser, OperationState &result) {
   // async()?
   async = parseOptionalOperandAndType(parser, ParallelOp::getAsyncKeyword(),
                                       result);
-  if (async.has_value() && failed(*async))
+  if (async.hasValue() && failed(*async))
     return failure();
 
   // wait()?
@@ -254,19 +254,19 @@ ParseResult ParallelOp::parse(OpAsmParser &parser, OperationState &result) {
   // num_gangs(value)?
   numGangs = parseOptionalOperandAndType(
       parser, ParallelOp::getNumGangsKeyword(), result);
-  if (numGangs.has_value() && failed(*numGangs))
+  if (numGangs.hasValue() && failed(*numGangs))
     return failure();
 
   // num_workers(value)?
   numWorkers = parseOptionalOperandAndType(
       parser, ParallelOp::getNumWorkersKeyword(), result);
-  if (numWorkers.has_value() && failed(*numWorkers))
+  if (numWorkers.hasValue() && failed(*numWorkers))
     return failure();
 
   // vector_length(value)?
   vectorLength = parseOptionalOperandAndType(
       parser, ParallelOp::getVectorLengthKeyword(), result);
-  if (vectorLength.has_value() && failed(*vectorLength))
+  if (vectorLength.hasValue() && failed(*vectorLength))
     return failure();
 
   // if()?
@@ -362,11 +362,11 @@ ParseResult ParallelOp::parse(OpAsmParser &parser, OperationState &result) {
   result.addAttribute(
       ParallelOp::getOperandSegmentSizeAttr(),
       builder.getI32VectorAttr(
-          {static_cast<int32_t>(async.has_value() ? 1 : 0),
+          {static_cast<int32_t>(async.hasValue() ? 1 : 0),
            static_cast<int32_t>(waitOperands.size()),
-           static_cast<int32_t>(numGangs.has_value() ? 1 : 0),
-           static_cast<int32_t>(numWorkers.has_value() ? 1 : 0),
-           static_cast<int32_t>(vectorLength.has_value() ? 1 : 0),
+           static_cast<int32_t>(numGangs.hasValue() ? 1 : 0),
+           static_cast<int32_t>(numWorkers.hasValue() ? 1 : 0),
+           static_cast<int32_t>(vectorLength.hasValue() ? 1 : 0),
            static_cast<int32_t>(hasIfCond ? 1 : 0),
            static_cast<int32_t>(hasSelfCond ? 1 : 0),
            static_cast<int32_t>(reductionOperands.size()),
@@ -531,13 +531,13 @@ ParseResult LoopOp::parse(OpAsmParser &parser, OperationState &result) {
   if (succeeded(parser.parseOptionalLParen())) {
     gangNum = parserOptionalOperandAndTypeWithPrefix(
         parser, result, LoopOp::getGangNumKeyword());
-    if (gangNum.has_value() && failed(*gangNum))
+    if (gangNum.hasValue() && failed(*gangNum))
       return failure();
     // FIXME: Comma should require subsequent operands.
     (void)parser.parseOptionalComma();
     gangStatic = parserOptionalOperandAndTypeWithPrefix(
         parser, result, LoopOp::getGangStaticKeyword());
-    if (gangStatic.has_value() && failed(*gangStatic))
+    if (gangStatic.hasValue() && failed(*gangStatic))
       return failure();
     // FIXME: Why allow optional last commas?
     (void)parser.parseOptionalComma();
@@ -551,7 +551,7 @@ ParseResult LoopOp::parse(OpAsmParser &parser, OperationState &result) {
 
   // optional worker operand
   worker = parseOptionalOperandAndType(parser, result);
-  if (worker.has_value() && failed(*worker))
+  if (worker.hasValue() && failed(*worker))
     return failure();
 
   // vector?
@@ -560,7 +560,7 @@ ParseResult LoopOp::parse(OpAsmParser &parser, OperationState &result) {
 
   // optional vector operand
   vector = parseOptionalOperandAndType(parser, result);
-  if (vector.has_value() && failed(*vector))
+  if (vector.hasValue() && failed(*vector))
     return failure();
 
   // tile()?
@@ -591,10 +591,10 @@ ParseResult LoopOp::parse(OpAsmParser &parser, OperationState &result) {
 
   result.addAttribute(LoopOp::getOperandSegmentSizeAttr(),
                       builder.getI32VectorAttr(
-                          {static_cast<int32_t>(gangNum.has_value() ? 1 : 0),
-                           static_cast<int32_t>(gangStatic.has_value() ? 1 : 0),
-                           static_cast<int32_t>(worker.has_value() ? 1 : 0),
-                           static_cast<int32_t>(vector.has_value() ? 1 : 0),
+                          {static_cast<int32_t>(gangNum.hasValue() ? 1 : 0),
+                           static_cast<int32_t>(gangStatic.hasValue() ? 1 : 0),
+                           static_cast<int32_t>(worker.hasValue() ? 1 : 0),
+                           static_cast<int32_t>(vector.hasValue() ? 1 : 0),
                            static_cast<int32_t>(tileOperands.size()),
                            static_cast<int32_t>(privateOperands.size()),
                            static_cast<int32_t>(reductionOperands.size())}));

diff  --git a/mlir/lib/Dialect/PDL/IR/PDLTypes.cpp b/mlir/lib/Dialect/PDL/IR/PDLTypes.cpp
index f3b19236522c2..13e19d4276ebe 100644
--- a/mlir/lib/Dialect/PDL/IR/PDLTypes.cpp
+++ b/mlir/lib/Dialect/PDL/IR/PDLTypes.cpp
@@ -40,7 +40,7 @@ static Type parsePDLType(AsmParser &parser) {
   {
     Type genType;
     auto parseResult = generatedTypeParser(parser, typeTag, genType);
-    if (parseResult.has_value())
+    if (parseResult.hasValue())
       return genType;
   }
 

diff  --git a/mlir/lib/Dialect/Quant/IR/TypeParser.cpp b/mlir/lib/Dialect/Quant/IR/TypeParser.cpp
index 91e7ec78aaa5d..951f62a76c44d 100644
--- a/mlir/lib/Dialect/Quant/IR/TypeParser.cpp
+++ b/mlir/lib/Dialect/Quant/IR/TypeParser.cpp
@@ -30,7 +30,7 @@ static IntegerType parseStorageType(DialectAsmParser &parser, bool &isSigned) {
   StringRef identifier;
   unsigned storageTypeWidth = 0;
   OptionalParseResult result = parser.parseOptionalType(type);
-  if (result.has_value()) {
+  if (result.hasValue()) {
     if (!succeeded(*result))
       return nullptr;
     isSigned = !type.isUnsigned();

diff  --git a/mlir/lib/Dialect/SCF/IR/SCF.cpp b/mlir/lib/Dialect/SCF/IR/SCF.cpp
index 503c36d0517b6..293238e82b169 100644
--- a/mlir/lib/Dialect/SCF/IR/SCF.cpp
+++ b/mlir/lib/Dialect/SCF/IR/SCF.cpp
@@ -2711,7 +2711,7 @@ ParseResult scf::WhileOp::parse(OpAsmParser &parser, OperationState &result) {
 
   OptionalParseResult listResult =
       parser.parseOptionalAssignmentList(regionArgs, operands);
-  if (listResult.has_value() && failed(listResult.value()))
+  if (listResult.hasValue() && failed(listResult.getValue()))
     return failure();
 
   FunctionType functionType;

diff  --git a/mlir/lib/Dialect/SCF/Transforms/TileUsingInterface.cpp b/mlir/lib/Dialect/SCF/Transforms/TileUsingInterface.cpp
index 63d34e47b45a7..1bad67f3d7f4d 100644
--- a/mlir/lib/Dialect/SCF/Transforms/TileUsingInterface.cpp
+++ b/mlir/lib/Dialect/SCF/Transforms/TileUsingInterface.cpp
@@ -340,11 +340,11 @@ scf::TileConsumerAndFuseProducersUsingSCFForOp::returningMatchAndRewrite(
     // 2c. Generate the tiled implementation of the producer of the source
     rewriter.setInsertionPoint(candidateSliceOp);
     FailureOr<Value> fusedProducerValue =
-        tensor::replaceExtractSliceWithTiledProducer(rewriter, candidateSliceOp,
-                                                     fusableProducer.value());
+        tensor::replaceExtractSliceWithTiledProducer(
+            rewriter, candidateSliceOp, fusableProducer.getValue());
     if (failed(fusedProducerValue))
       continue;
-    rewriter.replaceOp(candidateSliceOp, fusedProducerValue.value());
+    rewriter.replaceOp(candidateSliceOp, fusedProducerValue.getValue());
 
     // 2d. The operands of the fused producer might themselved be slices of
     //     values produced by operations that implement the `TilingInterface`.

diff  --git a/mlir/lib/Dialect/SCF/Utils/AffineCanonicalizationUtils.cpp b/mlir/lib/Dialect/SCF/Utils/AffineCanonicalizationUtils.cpp
index 024731a9222c3..958b5a2757148 100644
--- a/mlir/lib/Dialect/SCF/Utils/AffineCanonicalizationUtils.cpp
+++ b/mlir/lib/Dialect/SCF/Utils/AffineCanonicalizationUtils.cpp
@@ -27,8 +27,9 @@ using namespace presburger;
 
 static void unpackOptionalValues(ArrayRef<Optional<Value>> source,
                                  SmallVector<Value> &target) {
-  target = llvm::to_vector<4>(llvm::map_range(
-      source, [](Optional<Value> val) { return val ? *val : Value(); }));
+  target = llvm::to_vector<4>(llvm::map_range(source, [](Optional<Value> val) {
+    return val.hasValue() ? *val : Value();
+  }));
 }
 
 /// Bound an identifier `pos` in a given FlatAffineValueConstraints with

diff  --git a/mlir/lib/Dialect/SPIRV/IR/SPIRVAttributes.cpp b/mlir/lib/Dialect/SPIRV/IR/SPIRVAttributes.cpp
index 7b7ff84bfd26f..4accfc173a592 100644
--- a/mlir/lib/Dialect/SPIRV/IR/SPIRVAttributes.cpp
+++ b/mlir/lib/Dialect/SPIRV/IR/SPIRVAttributes.cpp
@@ -387,7 +387,7 @@ static Attribute parseInterfaceVarABIAttr(DialectAsmParser &parser) {
     uint32_t descriptorSet = 0;
     auto descriptorSetParseResult = parser.parseOptionalInteger(descriptorSet);
 
-    if (!descriptorSetParseResult.has_value() ||
+    if (!descriptorSetParseResult.hasValue() ||
         failed(*descriptorSetParseResult)) {
       parser.emitError(loc, "missing descriptor set");
       return {};
@@ -404,7 +404,7 @@ static Attribute parseInterfaceVarABIAttr(DialectAsmParser &parser) {
     uint32_t binding = 0;
     auto bindingParseResult = parser.parseOptionalInteger(binding);
 
-    if (!bindingParseResult.has_value() || failed(*bindingParseResult)) {
+    if (!bindingParseResult.hasValue() || failed(*bindingParseResult)) {
       parser.emitError(loc, "missing binding");
       return {};
     }
@@ -583,8 +583,8 @@ Attribute SPIRVDialect::parseAttribute(DialectAsmParser &parser,
   Attribute attr;
   OptionalParseResult result =
       generatedAttributeParser(parser, attrKind, type, attr);
-  if (result.has_value()) {
-    if (failed(result.value()))
+  if (result.hasValue()) {
+    if (failed(result.getValue()))
       return {};
     return attr;
   }

diff  --git a/mlir/lib/Dialect/SPIRV/IR/SPIRVCanonicalization.cpp b/mlir/lib/Dialect/SPIRV/IR/SPIRVCanonicalization.cpp
index 9ca9c15e119fc..aaa0fb33ae912 100644
--- a/mlir/lib/Dialect/SPIRV/IR/SPIRVCanonicalization.cpp
+++ b/mlir/lib/Dialect/SPIRV/IR/SPIRVCanonicalization.cpp
@@ -216,11 +216,11 @@ OpFoldResult spirv::LogicalAndOp::fold(ArrayRef<Attribute> operands) {
 
   if (Optional<bool> rhs = getScalarOrSplatBoolAttr(operands.back())) {
     // x && true = x
-    if (rhs.value())
+    if (rhs.getValue())
       return operand1();
 
     // x && false = false
-    if (!rhs.value())
+    if (!rhs.getValue())
       return operands.back();
   }
 
@@ -247,12 +247,12 @@ OpFoldResult spirv::LogicalOrOp::fold(ArrayRef<Attribute> operands) {
   assert(operands.size() == 2 && "spv.LogicalOr should take two operands");
 
   if (auto rhs = getScalarOrSplatBoolAttr(operands.back())) {
-    if (rhs.value())
+    if (rhs.getValue())
       // x || true = true
       return operands.back();
 
     // x || false = x
-    if (!rhs.value())
+    if (!rhs.getValue())
       return operand1();
   }
 

diff  --git a/mlir/lib/Dialect/SPIRV/IR/SPIRVDialect.cpp b/mlir/lib/Dialect/SPIRV/IR/SPIRVDialect.cpp
index dff597141cc25..ee717d2fe8595 100644
--- a/mlir/lib/Dialect/SPIRV/IR/SPIRVDialect.cpp
+++ b/mlir/lib/Dialect/SPIRV/IR/SPIRVDialect.cpp
@@ -496,8 +496,8 @@ template <typename ParseType, typename... Args> struct ParseCommaSeparatedList {
     auto remainingValues = ParseCommaSeparatedList<Args...>{}(dialect, parser);
     if (!remainingValues)
       return llvm::None;
-    return std::tuple_cat(std::tuple<ParseType>(parseVal.value()),
-                          remainingValues.value());
+    return std::tuple_cat(std::tuple<ParseType>(parseVal.getValue()),
+                          remainingValues.getValue());
   }
 };
 
@@ -571,7 +571,7 @@ static ParseResult parseStructMemberDecorations(
   SMLoc offsetLoc = parser.getCurrentLocation();
   StructType::OffsetInfo offset = 0;
   OptionalParseResult offsetParseResult = parser.parseOptionalInteger(offset);
-  if (offsetParseResult.has_value()) {
+  if (offsetParseResult.hasValue()) {
     if (failed(*offsetParseResult))
       return failure();
 
@@ -588,7 +588,7 @@ static ParseResult parseStructMemberDecorations(
     return success();
 
   // If there was an offset, make sure to parse the comma.
-  if (offsetParseResult.has_value() && parser.parseComma())
+  if (offsetParseResult.hasValue() && parser.parseComma())
     return failure();
 
   // Check for spirv::Decorations.
@@ -607,11 +607,11 @@ static ParseResult parseStructMemberDecorations(
 
       memberDecorationInfo.emplace_back(
           static_cast<uint32_t>(memberTypes.size() - 1), 1,
-          memberDecoration.value(), memberDecorationValue.value());
+          memberDecoration.getValue(), memberDecorationValue.getValue());
     } else {
       memberDecorationInfo.emplace_back(
           static_cast<uint32_t>(memberTypes.size() - 1), 0,
-          memberDecoration.value(), 0);
+          memberDecoration.getValue(), 0);
     }
     return success();
   };

diff  --git a/mlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp b/mlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp
index 4af79a1c33d2e..4e7338fa1133c 100644
--- a/mlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp
+++ b/mlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp
@@ -2236,7 +2236,7 @@ ParseResult spirv::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
   // Parse the optional function body.
   auto *body = state.addRegion();
   OptionalParseResult result = parser.parseOptionalRegion(*body, entryArgs);
-  return failure(result.has_value() && failed(*result));
+  return failure(result.hasValue() && failed(*result));
 }
 
 void spirv::FuncOp::print(OpAsmPrinter &printer) {

diff  --git a/mlir/lib/Dialect/SPIRV/Transforms/LowerABIAttributesPass.cpp b/mlir/lib/Dialect/SPIRV/Transforms/LowerABIAttributesPass.cpp
index 263f00ef1d863..3ea2224a4408a 100644
--- a/mlir/lib/Dialect/SPIRV/Transforms/LowerABIAttributesPass.cpp
+++ b/mlir/lib/Dialect/SPIRV/Transforms/LowerABIAttributesPass.cpp
@@ -131,8 +131,8 @@ static LogicalResult lowerEntryPointABIAttr(spirv::FuncOp funcOp,
     return funcOp.emitRemark("lower entry point failure: could not select "
                              "execution model based on 'spv.target_env'");
 
-  builder.create<spirv::EntryPointOp>(funcOp.getLoc(), executionModel.value(),
-                                      funcOp, interfaceVars);
+  builder.create<spirv::EntryPointOp>(
+      funcOp.getLoc(), executionModel.getValue(), funcOp, interfaceVars);
 
   // Specifies the spv.ExecutionModeOp.
   auto localSizeAttr = entryPointAttr.getLocalSize();

diff  --git a/mlir/lib/Dialect/Shape/IR/Shape.cpp b/mlir/lib/Dialect/Shape/IR/Shape.cpp
index 6fd8fa666a595..b3f6c4cc2cea7 100644
--- a/mlir/lib/Dialect/Shape/IR/Shape.cpp
+++ b/mlir/lib/Dialect/Shape/IR/Shape.cpp
@@ -1247,11 +1247,11 @@ OpFoldResult GetExtentOp::fold(ArrayRef<Attribute> operands) {
   if (!elements)
     return nullptr;
   Optional<int64_t> dim = getConstantDim();
-  if (!dim.has_value())
+  if (!dim.hasValue())
     return nullptr;
-  if (dim.value() >= elements.getNumElements())
+  if (dim.getValue() >= elements.getNumElements())
     return nullptr;
-  return elements.getValues<Attribute>()[(uint64_t)dim.value()];
+  return elements.getValues<Attribute>()[(uint64_t)dim.getValue()];
 }
 
 void GetExtentOp::build(OpBuilder &builder, OperationState &result, Value shape,

diff  --git a/mlir/lib/Dialect/SparseTensor/Transforms/Sparsification.cpp b/mlir/lib/Dialect/SparseTensor/Transforms/Sparsification.cpp
index 0504ea08d97cd..8c62290b5e0cf 100644
--- a/mlir/lib/Dialect/SparseTensor/Transforms/Sparsification.cpp
+++ b/mlir/lib/Dialect/SparseTensor/Transforms/Sparsification.cpp
@@ -1729,9 +1729,9 @@ struct GenericOpSparsifier : public OpRewritePattern<linalg::GenericOp> {
 
     // Builds the tensor expression for the Linalg operation in SSA form.
     Optional<unsigned> optExp = merger.buildTensorExpFromLinalg(op);
-    if (!optExp.has_value())
+    if (!optExp.hasValue())
       return failure();
-    unsigned exp = optExp.value();
+    unsigned exp = optExp.getValue();
 
     // Rejects an inadmissable tensor expression.
     OpOperand *sparseOut = nullptr;

diff  --git a/mlir/lib/Dialect/SparseTensor/Utils/Merger.cpp b/mlir/lib/Dialect/SparseTensor/Utils/Merger.cpp
index 9482e71a6eeef..ed19cf7a18690 100644
--- a/mlir/lib/Dialect/SparseTensor/Utils/Merger.cpp
+++ b/mlir/lib/Dialect/SparseTensor/Utils/Merger.cpp
@@ -893,8 +893,8 @@ Optional<unsigned> Merger::buildTensorExp(linalg::GenericOp op, Value v) {
   // Construct unary operations if subexpression can be built.
   if (def->getNumOperands() == 1) {
     auto x = buildTensorExp(op, def->getOperand(0));
-    if (x) {
-      unsigned e = x.value();
+    if (x.hasValue()) {
+      unsigned e = x.getValue();
       if (isa<math::AbsOp>(def))
         return addExp(kAbsF, e);
       if (isa<complex::AbsOp>(def))
@@ -966,9 +966,9 @@ Optional<unsigned> Merger::buildTensorExp(linalg::GenericOp op, Value v) {
   if (def->getNumOperands() == 2) {
     auto x = buildTensorExp(op, def->getOperand(0));
     auto y = buildTensorExp(op, def->getOperand(1));
-    if (x.has_value() && y.has_value()) {
-      unsigned e0 = x.value();
-      unsigned e1 = y.value();
+    if (x.hasValue() && y.hasValue()) {
+      unsigned e0 = x.getValue();
+      unsigned e1 = y.getValue();
       if (isa<arith::MulFOp>(def))
         return addExp(kMulF, e0, e1);
       if (isa<complex::MulOp>(def))

diff  --git a/mlir/lib/Dialect/Tensor/Transforms/SwapExtractSliceWithProducer.cpp b/mlir/lib/Dialect/Tensor/Transforms/SwapExtractSliceWithProducer.cpp
index 87981646d0ffa..8d570cfdf7592 100644
--- a/mlir/lib/Dialect/Tensor/Transforms/SwapExtractSliceWithProducer.cpp
+++ b/mlir/lib/Dialect/Tensor/Transforms/SwapExtractSliceWithProducer.cpp
@@ -39,5 +39,5 @@ FailureOr<Value> tensor::replaceExtractSliceWithTiledProducer(
   if (failed(tiledResult))
     return failure();
 
-  return tiledResult.value();
+  return tiledResult.getValue();
 }

diff  --git a/mlir/lib/Dialect/Tosa/Transforms/TosaDecomposeTransposeConv.cpp b/mlir/lib/Dialect/Tosa/Transforms/TosaDecomposeTransposeConv.cpp
index a0a9262539c8b..120e5024837d4 100644
--- a/mlir/lib/Dialect/Tosa/Transforms/TosaDecomposeTransposeConv.cpp
+++ b/mlir/lib/Dialect/Tosa/Transforms/TosaDecomposeTransposeConv.cpp
@@ -208,8 +208,8 @@ class TransposeConvStridedConverter
     Value weightPaddingVal = createOpAndInfer<tosa::ConstOp>(
         rewriter, loc, weightPaddingAttr.getType(), weightPaddingAttr);
 
-    if (op.quantization_info().has_value()) {
-      auto quantInfo = op.quantization_info().value();
+    if (op.quantization_info().hasValue()) {
+      auto quantInfo = op.quantization_info().getValue();
       weight = createOpAndInfer<tosa::PadOp>(
           rewriter, loc, UnrankedTensorType::get(weightETy), weight,
           weightPaddingVal, nullptr,
@@ -272,8 +272,8 @@ class TransposeConvStridedConverter
     Value inputPaddingVal = createOpAndInfer<tosa::ConstOp>(
         rewriter, loc, inputPaddingAttr.getType(), inputPaddingAttr);
 
-    if (op.quantization_info().has_value()) {
-      auto quantInfo = op.quantization_info().value();
+    if (op.quantization_info().hasValue()) {
+      auto quantInfo = op.quantization_info().getValue();
       input = createOpAndInfer<tosa::PadOp>(
           rewriter, loc, UnrankedTensorType::get(inputETy), input,
           inputPaddingVal, nullptr,

diff  --git a/mlir/lib/Dialect/Transform/IR/TransformOps.cpp b/mlir/lib/Dialect/Transform/IR/TransformOps.cpp
index 23e7b5d190000..d83a9de96be9d 100644
--- a/mlir/lib/Dialect/Transform/IR/TransformOps.cpp
+++ b/mlir/lib/Dialect/Transform/IR/TransformOps.cpp
@@ -134,12 +134,12 @@ void transform::AlternativesOp::getSuccessorRegions(
     Optional<unsigned> index, ArrayRef<Attribute> operands,
     SmallVectorImpl<RegionSuccessor> &regions) {
   for (Region &alternative :
-       llvm::drop_begin(getAlternatives(), index ? *index + 1 : 0)) {
+       llvm::drop_begin(getAlternatives(), index.hasValue() ? *index + 1 : 0)) {
     regions.emplace_back(&alternative, !getOperands().empty()
                                            ? alternative.getArguments()
                                            : Block::BlockArgListType());
   }
-  if (index)
+  if (index.hasValue())
     regions.emplace_back(getOperation()->getResults());
 }
 

diff  --git a/mlir/lib/Dialect/Utils/ReshapeOpsUtils.cpp b/mlir/lib/Dialect/Utils/ReshapeOpsUtils.cpp
index b26b3d93541a2..64937be9fac05 100644
--- a/mlir/lib/Dialect/Utils/ReshapeOpsUtils.cpp
+++ b/mlir/lib/Dialect/Utils/ReshapeOpsUtils.cpp
@@ -238,7 +238,7 @@ LogicalResult mlir::reshapeLikeShapesAreCompatible(
           return emitError("invalid to have a single dimension (" +
                            Twine(map.index()) +
                            ") expanded into multiple dynamic dims (" +
-                           Twine(expandedDimStart + dynamicShape.value()) +
+                           Twine(expandedDimStart + dynamicShape.getValue()) +
                            "," + Twine(expandedDimStart + dim.index()) + ")");
         }
         dynamicShape = dim.index();

diff  --git a/mlir/lib/Dialect/Vector/IR/VectorOps.cpp b/mlir/lib/Dialect/Vector/IR/VectorOps.cpp
index 387e5f1293031..ebf36627b6308 100644
--- a/mlir/lib/Dialect/Vector/IR/VectorOps.cpp
+++ b/mlir/lib/Dialect/Vector/IR/VectorOps.cpp
@@ -2677,8 +2677,8 @@ void TransferReadOp::build(OpBuilder &builder, OperationState &result,
                            ValueRange indices, AffineMap permutationMap,
                            Optional<ArrayRef<bool>> inBounds) {
   auto permutationMapAttr = AffineMapAttr::get(permutationMap);
-  auto inBoundsAttr = (inBounds && !inBounds->empty())
-                          ? builder.getBoolArrayAttr(inBounds.value())
+  auto inBoundsAttr = (inBounds && !inBounds.getValue().empty())
+                          ? builder.getBoolArrayAttr(inBounds.getValue())
                           : ArrayAttr();
   build(builder, result, vectorType, source, indices, permutationMapAttr,
         inBoundsAttr);
@@ -2692,8 +2692,8 @@ void TransferReadOp::build(OpBuilder &builder, OperationState &result,
   AffineMap permutationMap = getTransferMinorIdentityMap(
       source.getType().cast<ShapedType>(), vectorType);
   auto permutationMapAttr = AffineMapAttr::get(permutationMap);
-  auto inBoundsAttr = (inBounds && !inBounds->empty())
-                          ? builder.getBoolArrayAttr(inBounds.value())
+  auto inBoundsAttr = (inBounds && !inBounds.getValue().empty())
+                          ? builder.getBoolArrayAttr(inBounds.getValue())
                           : ArrayAttr();
   build(builder, result, vectorType, source, indices, permutationMapAttr,
         padding,
@@ -3216,8 +3216,8 @@ void TransferWriteOp::build(OpBuilder &builder, OperationState &result,
                             AffineMap permutationMap,
                             Optional<ArrayRef<bool>> inBounds) {
   auto permutationMapAttr = AffineMapAttr::get(permutationMap);
-  auto inBoundsAttr = (inBounds && !inBounds->empty())
-                          ? builder.getBoolArrayAttr(inBounds.value())
+  auto inBoundsAttr = (inBounds && !inBounds.getValue().empty())
+                          ? builder.getBoolArrayAttr(inBounds.getValue())
                           : ArrayAttr();
   build(builder, result, vector, dest, indices, permutationMapAttr,
         /*mask=*/Value(), inBoundsAttr);

diff  --git a/mlir/lib/Dialect/Vector/Transforms/VectorTransferPermutationMapRewritePatterns.cpp b/mlir/lib/Dialect/Vector/Transforms/VectorTransferPermutationMapRewritePatterns.cpp
index e419fc2db87a0..948814556b157 100644
--- a/mlir/lib/Dialect/Vector/Transforms/VectorTransferPermutationMapRewritePatterns.cpp
+++ b/mlir/lib/Dialect/Vector/Transforms/VectorTransferPermutationMapRewritePatterns.cpp
@@ -105,9 +105,10 @@ struct TransferReadPermutationLowering
 
     // Transpose in_bounds attribute.
     ArrayAttr newInBoundsAttr =
-        op.getInBounds() ? transposeInBoundsAttr(
-                               rewriter, op.getInBounds().value(), permutation)
-                         : ArrayAttr();
+        op.getInBounds()
+            ? transposeInBoundsAttr(rewriter, op.getInBounds().getValue(),
+                                    permutation)
+            : ArrayAttr();
 
     // Generate new transfer_read operation.
     VectorType newReadType =
@@ -175,9 +176,10 @@ struct TransferWritePermutationLowering
 
     // Transpose in_bounds attribute.
     ArrayAttr newInBoundsAttr =
-        op.getInBounds() ? transposeInBoundsAttr(
-                               rewriter, op.getInBounds().value(), permutation)
-                         : ArrayAttr();
+        op.getInBounds()
+            ? transposeInBoundsAttr(rewriter, op.getInBounds().getValue(),
+                                    permutation)
+            : ArrayAttr();
 
     // Generate new transfer_write operation.
     Value newVec = rewriter.create<vector::TransposeOp>(

diff  --git a/mlir/lib/Dialect/Vector/Transforms/VectorTransforms.cpp b/mlir/lib/Dialect/Vector/Transforms/VectorTransforms.cpp
index 26e4caca0587c..67635d69ddeaf 100644
--- a/mlir/lib/Dialect/Vector/Transforms/VectorTransforms.cpp
+++ b/mlir/lib/Dialect/Vector/Transforms/VectorTransforms.cpp
@@ -553,9 +553,9 @@ class OuterProductOpLowering : public OpRewritePattern<vector::OuterProductOp> {
       Value b = rewriter.create<vector::BroadcastOp>(loc, lhsType, op.getRhs());
       Optional<Value> mult = createContractArithOp(loc, op.getLhs(), b, acc,
                                                    kind, rewriter, isInt);
-      if (!mult.has_value())
+      if (!mult.hasValue())
         return failure();
-      rewriter.replaceOp(op, mult.value());
+      rewriter.replaceOp(op, mult.getValue());
       return success();
     }
 
@@ -571,9 +571,9 @@ class OuterProductOpLowering : public OpRewritePattern<vector::OuterProductOp> {
         r = rewriter.create<vector::ExtractOp>(loc, rhsType, acc, pos);
       Optional<Value> m =
           createContractArithOp(loc, a, op.getRhs(), r, kind, rewriter, isInt);
-      if (!m.has_value())
+      if (!m.hasValue())
         return failure();
-      result = rewriter.create<vector::InsertOp>(loc, resType, m.value(),
+      result = rewriter.create<vector::InsertOp>(loc, resType, m.getValue(),
                                                  result, pos);
     }
     rewriter.replaceOp(op, result);
@@ -1824,8 +1824,8 @@ Value ContractionOpLowering::lowerParallel(vector::ContractionOp op,
   }
   assert(iterIndex >= 0 && "parallel index not listed in operand mapping");
   Optional<int64_t> lookup = getResultIndex(iMap[2], iterIndex);
-  assert(lookup && "parallel index not listed in reduction");
-  int64_t resIndex = lookup.value();
+  assert(lookup.hasValue() && "parallel index not listed in reduction");
+  int64_t resIndex = lookup.getValue();
   // Construct new iterator types and affine map array attribute.
   std::array<AffineMap, 3> lowIndexingMaps = {
       adjustMap(iMap[0], iterIndex, rewriter),
@@ -1864,10 +1864,10 @@ Value ContractionOpLowering::lowerReduction(vector::ContractionOp op,
   SmallVector<AffineMap, 4> iMap = op.getIndexingMaps();
   Optional<int64_t> lookupLhs = getResultIndex(iMap[0], iterIndex);
   Optional<int64_t> lookupRhs = getResultIndex(iMap[1], iterIndex);
-  assert(lookupLhs && "missing LHS parallel index");
-  assert(lookupRhs && "missing RHS parallel index");
-  int64_t lhsIndex = lookupLhs.value();
-  int64_t rhsIndex = lookupRhs.value();
+  assert(lookupLhs.hasValue() && "missing LHS parallel index");
+  assert(lookupRhs.hasValue() && "missing RHS parallel index");
+  int64_t lhsIndex = lookupLhs.getValue();
+  int64_t rhsIndex = lookupRhs.getValue();
   int64_t dimSize = lhsType.getDimSize(lhsIndex);
   assert(dimSize == rhsType.getDimSize(rhsIndex) && "corrupt shape");
   // Base case.

diff  --git a/mlir/lib/IR/FunctionImplementation.cpp b/mlir/lib/IR/FunctionImplementation.cpp
index 9481e4ae8175b..a9160a9bc2e2b 100644
--- a/mlir/lib/IR/FunctionImplementation.cpp
+++ b/mlir/lib/IR/FunctionImplementation.cpp
@@ -41,8 +41,8 @@ parseFunctionArgumentList(OpAsmParser &parser, bool allowVariadic,
         OpAsmParser::Argument argument;
         auto argPresent = parser.parseOptionalArgument(
             argument, /*allowType=*/true, /*allowAttrs=*/true);
-        if (argPresent.has_value()) {
-          if (failed(argPresent.value()))
+        if (argPresent.hasValue()) {
+          if (failed(argPresent.getValue()))
             return failure(); // Present but malformed.
 
           // Reject this if the preceding argument was missing a name.
@@ -229,7 +229,7 @@ ParseResult mlir::function_interface_impl::parseFunctionOp(
   OptionalParseResult parseResult =
       parser.parseOptionalRegion(*body, entryArgs,
                                  /*enableNameShadowing=*/false);
-  if (parseResult.has_value()) {
+  if (parseResult.hasValue()) {
     if (failed(*parseResult))
       return failure();
     // Function body was parsed, make sure its not empty.

diff  --git a/mlir/lib/Interfaces/ControlFlowInterfaces.cpp b/mlir/lib/Interfaces/ControlFlowInterfaces.cpp
index d84218c195516..991f16e23b7e4 100644
--- a/mlir/lib/Interfaces/ControlFlowInterfaces.cpp
+++ b/mlir/lib/Interfaces/ControlFlowInterfaces.cpp
@@ -107,20 +107,20 @@ verifyTypesAlongAllEdges(Operation *op, Optional<unsigned> sourceNo,
     auto printEdgeName = [&](InFlightDiagnostic &diag) -> InFlightDiagnostic & {
       diag << "from ";
       if (sourceNo)
-        diag << "Region #" << sourceNo.value();
+        diag << "Region #" << sourceNo.getValue();
       else
         diag << "parent operands";
 
       diag << " to ";
       if (succRegionNo)
-        diag << "Region #" << succRegionNo.value();
+        diag << "Region #" << succRegionNo.getValue();
       else
         diag << "parent results";
       return diag;
     };
 
     Optional<TypeRange> sourceTypes = getInputsTypesForRegion(succRegionNo);
-    if (!sourceTypes.has_value())
+    if (!sourceTypes.hasValue())
       continue;
 
     TypeRange succInputsTypes = succ.getSuccessorInputs().getTypes();

diff  --git a/mlir/lib/Interfaces/ViewLikeInterface.cpp b/mlir/lib/Interfaces/ViewLikeInterface.cpp
index 36489d41b1645..4ecf5390edc75 100644
--- a/mlir/lib/Interfaces/ViewLikeInterface.cpp
+++ b/mlir/lib/Interfaces/ViewLikeInterface.cpp
@@ -121,7 +121,7 @@ static ParseResult parseOperandsOrIntegersImpl(
   while (true) {
     OpAsmParser::UnresolvedOperand operand;
     auto res = parser.parseOptionalOperand(operand);
-    if (res.has_value() && succeeded(res.value())) {
+    if (res.hasValue() && succeeded(res.getValue())) {
       values.push_back(operand);
       attrVals.push_back(dynVal);
     } else {

diff  --git a/mlir/lib/Parser/AffineParser.cpp b/mlir/lib/Parser/AffineParser.cpp
index eb65ddea56ded..f62455c37b450 100644
--- a/mlir/lib/Parser/AffineParser.cpp
+++ b/mlir/lib/Parser/AffineParser.cpp
@@ -324,11 +324,11 @@ AffineExpr AffineParser::parseSymbolSSAIdExpr() {
 ///   affine-expr ::= integer-literal
 AffineExpr AffineParser::parseIntegerExpr() {
   auto val = getToken().getUInt64IntegerValue();
-  if (!val.has_value() || (int64_t)val.value() < 0)
+  if (!val.hasValue() || (int64_t)val.getValue() < 0)
     return emitError("constant too large for index"), nullptr;
 
   consumeToken(Token::integer);
-  return builder.getAffineConstantExpr((int64_t)val.value());
+  return builder.getAffineConstantExpr((int64_t)val.getValue());
 }
 
 /// Parses an expression that can be a valid operand of an affine expression.

diff  --git a/mlir/lib/Parser/AttributeParser.cpp b/mlir/lib/Parser/AttributeParser.cpp
index eafebe9a6f14b..efc1c226a2aa0 100644
--- a/mlir/lib/Parser/AttributeParser.cpp
+++ b/mlir/lib/Parser/AttributeParser.cpp
@@ -211,7 +211,7 @@ Attribute Parser::parseAttribute(Type type) {
     // better error message.
     Type type;
     OptionalParseResult result = parseOptionalType(type);
-    if (!result.has_value())
+    if (!result.hasValue())
       return emitWrongTokenError("expected attribute value"), Attribute();
     return failed(*result) ? Attribute() : TypeAttr::get(type);
   }
@@ -245,7 +245,7 @@ OptionalParseResult Parser::parseOptionalAttribute(Attribute &attribute,
     // Parse an optional type attribute.
     Type type;
     OptionalParseResult result = parseOptionalType(type);
-    if (result.has_value() && succeeded(*result))
+    if (result.hasValue() && succeeded(*result))
       attribute = TypeAttr::get(type);
     return result;
   }
@@ -666,8 +666,8 @@ TensorLiteralParser::getFloatAttrElements(SMLoc loc, FloatType eltTy,
 DenseElementsAttr TensorLiteralParser::getStringAttr(SMLoc loc,
                                                      ShapedType type,
                                                      Type eltTy) {
-  if (hexStorage) {
-    auto stringValue = hexStorage->getStringValue();
+  if (hexStorage.hasValue()) {
+    auto stringValue = hexStorage.getValue().getStringValue();
     return DenseStringElementsAttr::get(type, {stringValue});
   }
 

diff  --git a/mlir/lib/Parser/LocationParser.cpp b/mlir/lib/Parser/LocationParser.cpp
index cf1e8afaab281..4749c16ab31ac 100644
--- a/mlir/lib/Parser/LocationParser.cpp
+++ b/mlir/lib/Parser/LocationParser.cpp
@@ -118,11 +118,11 @@ ParseResult Parser::parseNameOrFileLineColLocation(LocationAttr &loc) {
       return emitWrongTokenError(
           "expected integer column number in FileLineColLoc");
     auto column = getToken().getUnsignedIntegerValue();
-    if (!column.has_value())
+    if (!column.hasValue())
       return emitError("expected integer column number in FileLineColLoc");
     consumeToken(Token::integer);
 
-    loc = FileLineColLoc::get(ctx, str, line.value(), column.value());
+    loc = FileLineColLoc::get(ctx, str, line.getValue(), column.getValue());
     return success();
   }
 

diff  --git a/mlir/lib/Parser/Parser.cpp b/mlir/lib/Parser/Parser.cpp
index 61001343a188d..170d571c26929 100644
--- a/mlir/lib/Parser/Parser.cpp
+++ b/mlir/lib/Parser/Parser.cpp
@@ -1857,8 +1857,8 @@ ParseResult OperationParser::parseRegionBody(Region &region, SMLoc startLoc,
                    .attachNote(getEncodedSourceLocation(*defLoc))
                << "previously referenced here";
       }
-      Location loc = entryArg.sourceLoc.has_value()
-                         ? entryArg.sourceLoc.value()
+      Location loc = entryArg.sourceLoc.hasValue()
+                         ? entryArg.sourceLoc.getValue()
                          : getEncodedSourceLocation(argInfo.location);
       BlockArgument arg = block->addArgument(entryArg.type, loc);
 

diff  --git a/mlir/lib/Parser/TypeParser.cpp b/mlir/lib/Parser/TypeParser.cpp
index 5c69ad2333722..52fae4b50d03e 100644
--- a/mlir/lib/Parser/TypeParser.cpp
+++ b/mlir/lib/Parser/TypeParser.cpp
@@ -310,9 +310,9 @@ Type Parser::parseNonFunctionType() {
   // integer-type
   case Token::inttype: {
     auto width = getToken().getIntTypeBitwidth();
-    if (!width.has_value())
+    if (!width.hasValue())
       return (emitError("invalid integer width"), nullptr);
-    if (width.value() > IntegerType::kMaxWidth) {
+    if (width.getValue() > IntegerType::kMaxWidth) {
       emitError(getToken().getLoc(), "integer bitwidth is limited to ")
           << IntegerType::kMaxWidth << " bits";
       return nullptr;

diff  --git a/mlir/lib/Target/LLVMIR/ConvertFromLLVMIR.cpp b/mlir/lib/Target/LLVMIR/ConvertFromLLVMIR.cpp
index 1b1a18f855daf..32237bd022e7b 100644
--- a/mlir/lib/Target/LLVMIR/ConvertFromLLVMIR.cpp
+++ b/mlir/lib/Target/LLVMIR/ConvertFromLLVMIR.cpp
@@ -432,8 +432,8 @@ GlobalOp Importer::processGlobal(llvm::GlobalVariable *gv) {
 
   uint64_t alignment = 0;
   llvm::MaybeAlign maybeAlign = gv->getAlign();
-  if (maybeAlign) {
-    llvm::Align align = maybeAlign.value();
+  if (maybeAlign.hasValue()) {
+    llvm::Align align = maybeAlign.getValue();
     alignment = align.value();
   }
 

diff  --git a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index fac9b64d31045..d0cb2d3562d39 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -28,9 +28,9 @@ using namespace mlir;
 namespace {
 static llvm::omp::ScheduleKind
 convertToScheduleKind(Optional<omp::ClauseScheduleKind> schedKind) {
-  if (!schedKind.has_value())
+  if (!schedKind.hasValue())
     return llvm::omp::OMP_SCHEDULE_Default;
-  switch (schedKind.value()) {
+  switch (schedKind.getValue()) {
   case omp::ClauseScheduleKind::Static:
     return llvm::omp::OMP_SCHEDULE_Static;
   case omp::ClauseScheduleKind::Dynamic:

diff  --git a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
index 93498c744ebe3..923cffc1caf11 100644
--- a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
@@ -666,17 +666,17 @@ LogicalResult ModuleTranslation::convertGlobals() {
                              : llvm::GlobalValue::NotThreadLocal,
         addrSpace);
 
-    if (op.getUnnamedAddr().has_value())
+    if (op.getUnnamedAddr().hasValue())
       var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.getUnnamedAddr()));
 
-    if (op.getSection().has_value())
+    if (op.getSection().hasValue())
       var->setSection(*op.getSection());
 
     addRuntimePreemptionSpecifier(op.getDsoLocal(), var);
 
     Optional<uint64_t> alignment = op.getAlignment();
-    if (alignment)
-      var->setAlignment(llvm::MaybeAlign(alignment.value()));
+    if (alignment.hasValue())
+      var->setAlignment(llvm::MaybeAlign(alignment.getValue()));
 
     globalsMapping.try_emplace(op, var);
   }

diff  --git a/mlir/lib/Target/SPIRV/Deserialization/Deserializer.cpp b/mlir/lib/Target/SPIRV/Deserialization/Deserializer.cpp
index 383bdc4c905a9..361413ee24cfd 100644
--- a/mlir/lib/Target/SPIRV/Deserialization/Deserializer.cpp
+++ b/mlir/lib/Target/SPIRV/Deserialization/Deserializer.cpp
@@ -377,7 +377,7 @@ spirv::Deserializer::processFunction(ArrayRef<uint32_t> operands) {
 
   std::string fnName = getFunctionSymbol(fnID);
   auto funcOp = opBuilder.create<spirv::FuncOp>(
-      unknownLoc, fnName, functionType, fnControl.value());
+      unknownLoc, fnName, functionType, fnControl.getValue());
   curFunction = funcMap[fnID] = funcOp;
   auto *entryBlock = funcOp.addEntryBlock();
   LLVM_DEBUG({
@@ -883,7 +883,7 @@ spirv::Deserializer::processCooperativeMatrixType(ArrayRef<uint32_t> operands) {
   unsigned columns = getConstantInt(operands[4]).getInt();
 
   typeMap[operands[0]] = spirv::CooperativeMatrixNVType::get(
-      elementTy, scope.value(), rows, columns);
+      elementTy, scope.getValue(), rows, columns);
   return success();
 }
 
@@ -1067,8 +1067,8 @@ spirv::Deserializer::processImageType(ArrayRef<uint32_t> operands) {
            << operands[7];
 
   typeMap[operands[0]] = spirv::ImageType::get(
-      elementTy, dim.value(), depthInfo.value(), arrayedInfo.value(),
-      samplingInfo.value(), samplerUseInfo.value(), format.value());
+      elementTy, dim.getValue(), depthInfo.getValue(), arrayedInfo.getValue(),
+      samplingInfo.getValue(), samplerUseInfo.getValue(), format.getValue());
   return success();
 }
 

diff  --git a/mlir/test/lib/Analysis/TestMemRefDependenceCheck.cpp b/mlir/test/lib/Analysis/TestMemRefDependenceCheck.cpp
index a45e21afb5761..eebd9e3631530 100644
--- a/mlir/test/lib/Analysis/TestMemRefDependenceCheck.cpp
+++ b/mlir/test/lib/Analysis/TestMemRefDependenceCheck.cpp
@@ -52,14 +52,16 @@ getDirectionVectorStr(bool ret, unsigned numCommonLoops, unsigned loopNestDepth,
   std::string result;
   for (const auto &dependenceComponent : dependenceComponents) {
     std::string lbStr = "-inf";
-    if (dependenceComponent.lb.has_value() &&
-        dependenceComponent.lb.value() != std::numeric_limits<int64_t>::min())
-      lbStr = std::to_string(dependenceComponent.lb.value());
+    if (dependenceComponent.lb.hasValue() &&
+        dependenceComponent.lb.getValue() !=
+            std::numeric_limits<int64_t>::min())
+      lbStr = std::to_string(dependenceComponent.lb.getValue());
 
     std::string ubStr = "+inf";
-    if (dependenceComponent.ub.has_value() &&
-        dependenceComponent.ub.value() != std::numeric_limits<int64_t>::max())
-      ubStr = std::to_string(dependenceComponent.ub.value());
+    if (dependenceComponent.ub.hasValue() &&
+        dependenceComponent.ub.getValue() !=
+            std::numeric_limits<int64_t>::max())
+      ubStr = std::to_string(dependenceComponent.ub.getValue());
 
     result += "[" + lbStr + ", " + ubStr + "]";
   }

diff  --git a/mlir/test/lib/Dialect/Test/TestDialect.cpp b/mlir/test/lib/Dialect/Test/TestDialect.cpp
index 64cf476a0386b..45d345e0a4f51 100644
--- a/mlir/test/lib/Dialect/Test/TestDialect.cpp
+++ b/mlir/test/lib/Dialect/Test/TestDialect.cpp
@@ -1310,8 +1310,8 @@ void RegionIfOp::getSuccessorRegions(
     Optional<unsigned> index, ArrayRef<Attribute> operands,
     SmallVectorImpl<RegionSuccessor> &regions) {
   // We always branch to the join region.
-  if (index) {
-    if (index.value() < 2)
+  if (index.hasValue()) {
+    if (index.getValue() < 2)
       regions.push_back(RegionSuccessor(&getJoinRegion(), getJoinArgs()));
     else
       regions.push_back(RegionSuccessor(getResults()));

diff  --git a/mlir/test/lib/Dialect/Test/TestTypeDefs.td b/mlir/test/lib/Dialect/Test/TestTypeDefs.td
index 9853b4a18bc92..fd50dd3e0e90b 100644
--- a/mlir/test/lib/Dialect/Test/TestTypeDefs.td
+++ b/mlir/test/lib/Dialect/Test/TestTypeDefs.td
@@ -292,9 +292,9 @@ class DefaultValuedAPFloat<string value>
   let parser = [{ [&]() -> mlir::FailureOr<llvm::Optional<llvm::APFloat>> {
     mlir::FloatAttr attr;
     auto result = $_parser.parseOptionalAttribute(attr);
-    if (result.has_value() && mlir::succeeded(*result))
+    if (result.hasValue() && mlir::succeeded(*result))
       return {attr.getValue()};
-    if (!result.has_value())
+    if (!result.hasValue())
       return llvm::Optional<llvm::APFloat>();
     return mlir::failure();
   }() }];

diff  --git a/mlir/test/lib/Dialect/Test/TestTypes.cpp b/mlir/test/lib/Dialect/Test/TestTypes.cpp
index 76e67ed0d1342..5418025d501c9 100644
--- a/mlir/test/lib/Dialect/Test/TestTypes.cpp
+++ b/mlir/test/lib/Dialect/Test/TestTypes.cpp
@@ -414,15 +414,15 @@ Type TestDialect::parseTestType(AsmParser &parser,
   {
     Type genType;
     auto parseResult = generatedTypeParser(parser, typeTag, genType);
-    if (parseResult.has_value())
+    if (parseResult.hasValue())
       return genType;
   }
 
   {
     Type dynType;
     auto parseResult = parseOptionalDynamicType(typeTag, parser, dynType);
-    if (parseResult.has_value()) {
-      if (succeeded(parseResult.value()))
+    if (parseResult.hasValue()) {
+      if (succeeded(parseResult.getValue()))
         return dynType;
       return Type();
     }

diff  --git a/mlir/test/lib/Dialect/Test/TestTypes.h b/mlir/test/lib/Dialect/Test/TestTypes.h
index 654600bbfb455..bd6421d04735e 100644
--- a/mlir/test/lib/Dialect/Test/TestTypes.h
+++ b/mlir/test/lib/Dialect/Test/TestTypes.h
@@ -77,7 +77,7 @@ struct FieldParser<Optional<int>> {
     Optional<int> value;
     value.emplace();
     OptionalParseResult result = parser.parseOptionalInteger(*value);
-    if (result.has_value()) {
+    if (result.hasValue()) {
       if (succeeded(*result))
         return value;
       return failure();

diff  --git a/mlir/test/lib/Dialect/Transform/TestTransformDialectExtension.cpp b/mlir/test/lib/Dialect/Transform/TestTransformDialectExtension.cpp
index a81090bc06abb..9242a51dbb840 100644
--- a/mlir/test/lib/Dialect/Transform/TestTransformDialectExtension.cpp
+++ b/mlir/test/lib/Dialect/Transform/TestTransformDialectExtension.cpp
@@ -52,12 +52,12 @@ class TestTransformOp
   static ParseResult parse(OpAsmParser &parser, OperationState &state) {
     StringAttr message;
     OptionalParseResult result = parser.parseOptionalAttribute(message);
-    if (!result.has_value())
+    if (!result.hasValue())
       return success();
 
-    if (result.value().succeeded())
+    if (result.getValue().succeeded())
       state.addAttribute("message", message);
-    return result.value();
+    return result.getValue();
   }
 
   void print(OpAsmPrinter &printer) {

diff  --git a/mlir/test/lib/Transforms/TestIntRangeInference.cpp b/mlir/test/lib/Transforms/TestIntRangeInference.cpp
index f9f8db46bb3a3..1bd2a24d3ce6c 100644
--- a/mlir/test/lib/Transforms/TestIntRangeInference.cpp
+++ b/mlir/test/lib/Transforms/TestIntRangeInference.cpp
@@ -25,9 +25,9 @@ static LogicalResult replaceWithConstant(IntRangeAnalysis &analysis,
   Optional<ConstantIntRanges> maybeInferredRange = analysis.getResult(value);
   if (!maybeInferredRange)
     return failure();
-  const ConstantIntRanges &inferredRange = maybeInferredRange.value();
+  const ConstantIntRanges &inferredRange = maybeInferredRange.getValue();
   Optional<APInt> maybeConstValue = inferredRange.getConstantValue();
-  if (!maybeConstValue.has_value())
+  if (!maybeConstValue.hasValue())
     return failure();
 
   Operation *maybeDefiningOp = value.getDefiningOp();

diff  --git a/mlir/test/mlir-tblgen/default-type-attr-print-parser.td b/mlir/test/mlir-tblgen/default-type-attr-print-parser.td
index 88328fd05d3b8..ac898a97d9eee 100644
--- a/mlir/test/mlir-tblgen/default-type-attr-print-parser.td
+++ b/mlir/test/mlir-tblgen/default-type-attr-print-parser.td
@@ -32,7 +32,7 @@ def AttrA : TestAttr<"AttrA"> {
 // ATTR:   {
 // ATTR:     ::mlir::Attribute attr;
 // ATTR:     auto parseResult = generatedAttributeParser(parser, attrTag, type, attr);
-// ATTR:     if (parseResult.has_value())
+// ATTR:     if (parseResult.hasValue())
 // ATTR:       return attr;
 // ATTR:   }
 // ATTR:   parser.emitError(typeLoc) << "unknown attribute `"
@@ -61,7 +61,7 @@ def TypeA : TestType<"TypeA"> {
 // TYPE:     return ::mlir::Type();
 // TYPE:   ::mlir::Type genType;
 // TYPE:   auto parseResult = generatedTypeParser(parser, mnemonic, genType);
-// TYPE:   if (parseResult.has_value())
+// TYPE:   if (parseResult.hasValue())
 // TYPE:     return genType;
 // TYPE:   parser.emitError(typeLoc) << "unknown  type `"
 // TYPE:       << mnemonic << "` in dialect `" << getNamespace() << "`";

diff  --git a/mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-yaml-gen.cpp b/mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-yaml-gen.cpp
index 2c28d0ec1f702..9140c53c41dfa 100644
--- a/mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-yaml-gen.cpp
+++ b/mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-yaml-gen.cpp
@@ -730,16 +730,16 @@ static LogicalResult generateNamedGenericOpOds(LinalgOpConfig &opConfig,
       }
       // Add the index attributes to the op definition and builders.
       if (arg.kind == LinalgOperandDefKind::IndexAttr) {
-        assert(arg.indexAttrMap.has_value());
-        assert(arg.defaultIndices.has_value());
+        assert(arg.indexAttrMap.hasValue());
+        assert(arg.defaultIndices.hasValue());
         size_t size = arg.indexAttrMap->affineMap().getNumResults();
-        assert(arg.defaultIndices->size() == size);
+        assert(arg.defaultIndices.getValue().size() == size);
         static const char typeFmt[] = "RankedI64ElementsAttr<[{0}]>";
         static const char defFmt[] = "DefaultValuedAttr<{0}, \"{ {1} }\">:${2}";
         std::string defaultVals;
         llvm::raw_string_ostream ss(defaultVals);
         llvm::interleave(
-            arg.defaultIndices.value(), ss,
+            arg.defaultIndices.getValue(), ss,
             [&](int64_t val) { ss << "static_cast<int64_t>(" << val << ")"; },
             ", ");
         attrDefs.push_back(llvm::formatv(defFmt, llvm::formatv(typeFmt, size),
@@ -1088,11 +1088,11 @@ if ({1}Iter != attrs.end()) {{
           if (expression.scalarFn->attrName) {
             if (llvm::none_of(args, [&](LinalgOperandDef &arg) {
                   return isFunctionAttribute(arg.kind) &&
-                         arg.name == expression.scalarFn->attrName.value();
+                         arg.name == expression.scalarFn->attrName.getValue();
                 })) {
               emitError(genContext.getLoc())
                   << "missing function attribute "
-                  << expression.scalarFn->attrName.value();
+                  << expression.scalarFn->attrName.getValue();
             }
             funcType = llvm::formatv("{0}Val", *expression.scalarFn->attrName);
           }
@@ -1101,17 +1101,17 @@ if ({1}Iter != attrs.end()) {{
           // Add the optional type parameter to the operands.
           SmallVector<std::string> operandCppValues;
           if (expression.scalarFn->kind == ScalarFnKind::Type) {
-            assert(expression.scalarFn->typeVar.has_value());
+            assert(expression.scalarFn->typeVar.hasValue());
             Optional<std::string> typeCppValue =
-                findTypeValue(expression.scalarFn->typeVar.value(), args);
+                findTypeValue(expression.scalarFn->typeVar.getValue(), args);
             if (!typeCppValue) {
               emitError(genContext.getLoc())
-                  << "type variable " << expression.scalarFn->typeVar.value()
+                  << "type variable " << expression.scalarFn->typeVar.getValue()
                   << ", used in a type conversion, must map to a predefined or "
                   << "an argument type but it does not";
               return None;
             }
-            operandCppValues.push_back(typeCppValue.value());
+            operandCppValues.push_back(typeCppValue.getValue());
           }
 
           // Collect the scalar operands.

diff  --git a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
index 53cc698c957fa..759143dc606b0 100644
--- a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
+++ b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
@@ -678,7 +678,7 @@ ::mlir::Attribute {0}::parseAttribute(::mlir::DialectAsmParser &parser,
   {{
     ::mlir::Attribute attr;
     auto parseResult = generatedAttributeParser(parser, attrTag, type, attr);
-    if (parseResult.has_value())
+    if (parseResult.hasValue())
       return attr;
   }
   {1}
@@ -700,8 +700,8 @@ static const char *const dialectDynamicAttrParserDispatch = R"(
   {
     ::mlir::Attribute genAttr;
     auto parseResult = parseOptionalDynamicAttr(attrTag, parser, genAttr);
-    if (parseResult.has_value()) {
-      if (::mlir::succeeded(*parseResult))
+    if (parseResult.hasValue()) {
+      if (::mlir::succeeded(parseResult.getValue()))
         return genAttr;
       return Attribute();
     }
@@ -727,7 +727,7 @@ ::mlir::Type {0}::parseType(::mlir::DialectAsmParser &parser) const {{
     return ::mlir::Type();
   ::mlir::Type genType;
   auto parseResult = generatedTypeParser(parser, mnemonic, genType);
-  if (parseResult.has_value())
+  if (parseResult.hasValue())
     return genType;
   {1}
   parser.emitError(typeLoc) << "unknown  type `"
@@ -747,7 +747,7 @@ void {0}::printType(::mlir::Type type,
 static const char *const dialectDynamicTypeParserDispatch = R"(
   {
     auto parseResult = parseOptionalDynamicType(mnemonic, parser, genType);
-    if (parseResult.has_value()) {
+    if (parseResult.hasValue()) {
       if (::mlir::succeeded(parseResult.getValue()))
         return genType;
       return Type();

diff  --git a/mlir/tools/mlir-tblgen/OpFormatGen.cpp b/mlir/tools/mlir-tblgen/OpFormatGen.cpp
index 1269622a142ae..212fe0e1204e5 100644
--- a/mlir/tools/mlir-tblgen/OpFormatGen.cpp
+++ b/mlir/tools/mlir-tblgen/OpFormatGen.cpp
@@ -408,7 +408,7 @@ const char *const optionalAttrParserCode = R"(
   {
     ::mlir::OptionalParseResult parseResult =
       parser.parseOptionalAttribute({0}Attr, {1}, "{0}", result.attributes);
-    if (parseResult.has_value() && failed(*parseResult))
+    if (parseResult.hasValue() && failed(*parseResult))
       return ::mlir::failure();
   }
 )";
@@ -445,7 +445,7 @@ const char *const enumAttrParserCode = R"(
         parser.parseOptionalAttribute(attrVal,
                                       parser.getBuilder().getNoneType(),
                                       "{0}", attrStorage);
-      if (parseResult.has_value()) {{
+      if (parseResult.hasValue()) {{
         if (failed(*parseResult))
           return ::mlir::failure();
         attrStr = attrVal.getValue();
@@ -479,7 +479,7 @@ const char *const optionalOperandParserCode = R"(
     ::mlir::OpAsmParser::UnresolvedOperand operand;
     ::mlir::OptionalParseResult parseResult =
                                     parser.parseOptionalOperand(operand);
-    if (parseResult.has_value()) {
+    if (parseResult.hasValue()) {
       if (failed(*parseResult))
         return ::mlir::failure();
       {0}Operands.push_back(operand);
@@ -532,7 +532,7 @@ const char *const optionalTypeParserCode = R"(
     ::mlir::Type optionalType;
     ::mlir::OptionalParseResult parseResult =
                                     parser.parseOptionalType(optionalType);
-    if (parseResult.has_value()) {
+    if (parseResult.hasValue()) {
       if (failed(*parseResult))
         return ::mlir::failure();
       {0}Types.push_back(optionalType);
@@ -584,7 +584,7 @@ const char *regionListParserCode = R"(
   {
     std::unique_ptr<::mlir::Region> region;
     auto firstRegionResult = parser.parseOptionalRegion(region);
-    if (firstRegionResult.has_value()) {
+    if (firstRegionResult.hasValue()) {
       if (failed(*firstRegionResult))
         return ::mlir::failure();
       {0}Regions.emplace_back(std::move(region));
@@ -622,7 +622,7 @@ const char *regionListEnsureSingleBlockParserCode = R"(
 const char *optionalRegionParserCode = R"(
   {
      auto parseResult = parser.parseOptionalRegion(*{0}Region);
-     if (parseResult.has_value() && failed(*parseResult))
+     if (parseResult.hasValue() && failed(*parseResult))
        return ::mlir::failure();
   }
 )";
@@ -656,7 +656,7 @@ const char *successorListParserCode = R"(
   {
     ::mlir::Block *succ;
     auto firstSucc = parser.parseOptionalSuccessor(succ);
-    if (firstSucc.has_value()) {
+    if (firstSucc.hasValue()) {
       if (failed(*firstSucc))
         return ::mlir::failure();
       {0}Successors.emplace_back(succ);

diff  --git a/mlir/unittests/Analysis/Presburger/IntegerPolyhedronTest.cpp b/mlir/unittests/Analysis/Presburger/IntegerPolyhedronTest.cpp
index 5929e92231f6f..f69b4ee7a6e7f 100644
--- a/mlir/unittests/Analysis/Presburger/IntegerPolyhedronTest.cpp
+++ b/mlir/unittests/Analysis/Presburger/IntegerPolyhedronTest.cpp
@@ -66,8 +66,8 @@ static void checkSample(bool hasSample, const IntegerPolyhedron &poly,
     maybeLexMin = poly.findIntegerLexMin();
 
     if (!hasSample) {
-      EXPECT_FALSE(maybeSample.has_value());
-      if (maybeSample.has_value()) {
+      EXPECT_FALSE(maybeSample.hasValue());
+      if (maybeSample.hasValue()) {
         llvm::errs() << "findIntegerSample gave sample: ";
         dump(*maybeSample);
       }
@@ -78,7 +78,7 @@ static void checkSample(bool hasSample, const IntegerPolyhedron &poly,
         dump(*maybeLexMin);
       }
     } else {
-      ASSERT_TRUE(maybeSample.has_value());
+      ASSERT_TRUE(maybeSample.hasValue());
       EXPECT_TRUE(poly.containsPoint(*maybeSample));
 
       ASSERT_FALSE(maybeLexMin.isEmpty());

diff  --git a/mlir/unittests/Analysis/Presburger/PWMAFunctionTest.cpp b/mlir/unittests/Analysis/Presburger/PWMAFunctionTest.cpp
index 1c959c687554a..27d02524ec15b 100644
--- a/mlir/unittests/Analysis/Presburger/PWMAFunctionTest.cpp
+++ b/mlir/unittests/Analysis/Presburger/PWMAFunctionTest.cpp
@@ -138,7 +138,7 @@ TEST(PWMAFunction, valueAt) {
   EXPECT_THAT(*nonNegPWMAF.valueAt({2, 3}), ElementsAre(11, 23));
   EXPECT_THAT(*nonNegPWMAF.valueAt({-2, 3}), ElementsAre(11, 23));
   EXPECT_THAT(*nonNegPWMAF.valueAt({2, -3}), ElementsAre(-1, -1));
-  EXPECT_FALSE(nonNegPWMAF.valueAt({-2, -3}).has_value());
+  EXPECT_FALSE(nonNegPWMAF.valueAt({-2, -3}).hasValue());
 
   PWMAFunction divPWMAF = parsePWMAF(
       /*numInputs=*/2, /*numOutputs=*/2,
@@ -149,11 +149,11 @@ TEST(PWMAFunction, valueAt) {
       });
   EXPECT_THAT(*divPWMAF.valueAt({4, 3}), ElementsAre(11, 23));
   EXPECT_THAT(*divPWMAF.valueAt({4, -3}), ElementsAre(-1, -1));
-  EXPECT_FALSE(divPWMAF.valueAt({3, 3}).has_value());
-  EXPECT_FALSE(divPWMAF.valueAt({3, -3}).has_value());
+  EXPECT_FALSE(divPWMAF.valueAt({3, 3}).hasValue());
+  EXPECT_FALSE(divPWMAF.valueAt({3, -3}).hasValue());
 
   EXPECT_THAT(*divPWMAF.valueAt({-2, 3}), ElementsAre(11, 23));
-  EXPECT_FALSE(divPWMAF.valueAt({-2, -3}).has_value());
+  EXPECT_FALSE(divPWMAF.valueAt({-2, -3}).hasValue());
 }
 
 TEST(PWMAFunction, removeIdRangeRegressionTest) {

diff  --git a/mlir/unittests/Analysis/Presburger/PresburgerSetTest.cpp b/mlir/unittests/Analysis/Presburger/PresburgerSetTest.cpp
index aa7182596443b..0c98f488ea074 100644
--- a/mlir/unittests/Analysis/Presburger/PresburgerSetTest.cpp
+++ b/mlir/unittests/Analysis/Presburger/PresburgerSetTest.cpp
@@ -762,7 +762,7 @@ void testComputeReprAtPoints(IntegerPolyhedron poly,
   EXPECT_TRUE(repr.hasOnlyDivLocals());
   EXPECT_TRUE(repr.getSpace().isCompatible(poly.getSpace()));
   for (const SmallVector<int64_t, 4> &point : points) {
-    EXPECT_EQ(poly.containsPointNoLocal(point).has_value(),
+    EXPECT_EQ(poly.containsPointNoLocal(point).hasValue(),
               repr.containsPoint(point));
   }
 }

diff  --git a/mlir/unittests/Analysis/Presburger/SimplexTest.cpp b/mlir/unittests/Analysis/Presburger/SimplexTest.cpp
index df03935e16f30..4c55c922a91b4 100644
--- a/mlir/unittests/Analysis/Presburger/SimplexTest.cpp
+++ b/mlir/unittests/Analysis/Presburger/SimplexTest.cpp
@@ -196,7 +196,7 @@ TEST(SimplexTest, getSamplePointIfIntegral) {
                                       },
                                       {})
                    .getSamplePointIfIntegral()
-                   .has_value());
+                   .hasValue());
 
   auto maybeSample = simplexFromConstraints(2,
                                             {// x = y - 2.
@@ -208,7 +208,7 @@ TEST(SimplexTest, getSamplePointIfIntegral) {
                                             {})
                          .getSamplePointIfIntegral();
 
-  EXPECT_TRUE(maybeSample.has_value());
+  EXPECT_TRUE(maybeSample.hasValue());
   EXPECT_THAT(*maybeSample, testing::ElementsAre(0, 2));
 
   auto maybeSample2 = simplexFromConstraints(2,
@@ -220,7 +220,7 @@ TEST(SimplexTest, getSamplePointIfIntegral) {
                                                  {0, 1, -2} // y = 2.
                                              })
                           .getSamplePointIfIntegral();
-  EXPECT_TRUE(maybeSample2.has_value());
+  EXPECT_TRUE(maybeSample2.hasValue());
   EXPECT_THAT(*maybeSample2, testing::ElementsAre(0, 2));
 
   EXPECT_FALSE(simplexFromConstraints(1,
@@ -229,7 +229,7 @@ TEST(SimplexTest, getSamplePointIfIntegral) {
                                        {-2, +1}},
                                       {})
                    .getSamplePointIfIntegral()
-                   .has_value());
+                   .hasValue());
 }
 
 /// Some basic sanity checks involving zero or one variables.
@@ -545,7 +545,7 @@ TEST(SimplexTest, addDivisionVariable) {
   simplex.addInequality({1, 0, -3}); // x >= 3.
   simplex.addInequality({-1, 0, 9}); // x <= 9.
   Optional<SmallVector<int64_t, 8>> sample = simplex.findIntegerSample();
-  ASSERT_TRUE(sample.has_value());
+  ASSERT_TRUE(sample.hasValue());
   EXPECT_EQ((*sample)[0] / 2, (*sample)[1]);
 }
 

diff  --git a/mlir/unittests/IR/OperationSupportTest.cpp b/mlir/unittests/IR/OperationSupportTest.cpp
index 4f6a98ddc659f..2511a5d3b6bfd 100644
--- a/mlir/unittests/IR/OperationSupportTest.cpp
+++ b/mlir/unittests/IR/OperationSupportTest.cpp
@@ -247,7 +247,7 @@ TEST(NamedAttrListTest, TestAppendAssign) {
   attrs.append("foo", b.getStringAttr("zoo"));
   {
     auto dup = attrs.findDuplicate();
-    ASSERT_TRUE(dup.has_value());
+    ASSERT_TRUE(dup.hasValue());
   }
 
   SmallVector<NamedAttribute> newAttrs = {
@@ -257,7 +257,7 @@ TEST(NamedAttrListTest, TestAppendAssign) {
   attrs.assign(newAttrs);
 
   auto dup = attrs.findDuplicate();
-  ASSERT_FALSE(dup.has_value());
+  ASSERT_FALSE(dup.hasValue());
 
   {
     auto *it = attrs.begin();

diff  --git a/mlir/unittests/Interfaces/ControlFlowInterfacesTest.cpp b/mlir/unittests/Interfaces/ControlFlowInterfacesTest.cpp
index af02a45e27aed..b92f3199eacfb 100644
--- a/mlir/unittests/Interfaces/ControlFlowInterfacesTest.cpp
+++ b/mlir/unittests/Interfaces/ControlFlowInterfacesTest.cpp
@@ -79,7 +79,7 @@ struct DoubleLoopRegionsOp
   void getSuccessorRegions(Optional<unsigned> index,
                            ArrayRef<Attribute> operands,
                            SmallVectorImpl<RegionSuccessor> &regions) {
-    if (index.has_value()) {
+    if (index.hasValue()) {
       regions.push_back(RegionSuccessor());
       regions.push_back(RegionSuccessor(&getOperation()->getRegion(*index)));
     }

diff  --git a/mlir/unittests/Pass/AnalysisManagerTest.cpp b/mlir/unittests/Pass/AnalysisManagerTest.cpp
index 5fa17f3ccd1a9..cef8da7634c7a 100644
--- a/mlir/unittests/Pass/AnalysisManagerTest.cpp
+++ b/mlir/unittests/Pass/AnalysisManagerTest.cpp
@@ -52,8 +52,8 @@ TEST(AnalysisManagerTest, FineGrainModuleAnalysisPreservation) {
   am.invalidate(pa);
 
   // Check that only MyAnalysis is preserved.
-  EXPECT_TRUE(am.getCachedAnalysis<MyAnalysis>().has_value());
-  EXPECT_FALSE(am.getCachedAnalysis<OtherAnalysis>().has_value());
+  EXPECT_TRUE(am.getCachedAnalysis<MyAnalysis>().hasValue());
+  EXPECT_FALSE(am.getCachedAnalysis<OtherAnalysis>().hasValue());
 }
 
 TEST(AnalysisManagerTest, FineGrainFunctionAnalysisPreservation) {
@@ -83,8 +83,8 @@ TEST(AnalysisManagerTest, FineGrainFunctionAnalysisPreservation) {
   fam.invalidate(pa);
 
   // Check that only MyAnalysis is preserved.
-  EXPECT_TRUE(fam.getCachedAnalysis<MyAnalysis>().has_value());
-  EXPECT_FALSE(fam.getCachedAnalysis<OtherAnalysis>().has_value());
+  EXPECT_TRUE(fam.getCachedAnalysis<MyAnalysis>().hasValue());
+  EXPECT_FALSE(fam.getCachedAnalysis<OtherAnalysis>().hasValue());
 }
 
 TEST(AnalysisManagerTest, FineGrainChildFunctionAnalysisPreservation) {
@@ -106,7 +106,7 @@ TEST(AnalysisManagerTest, FineGrainChildFunctionAnalysisPreservation) {
   AnalysisManager am = mam;
 
   // Check that the analysis cache is initially empty.
-  EXPECT_FALSE(am.getCachedChildAnalysis<MyAnalysis>(func1).has_value());
+  EXPECT_FALSE(am.getCachedChildAnalysis<MyAnalysis>(func1).hasValue());
 
   // Query two 
diff erent analyses, but only preserve one before invalidating.
   am.getChildAnalysis<MyAnalysis>(func1);
@@ -117,8 +117,8 @@ TEST(AnalysisManagerTest, FineGrainChildFunctionAnalysisPreservation) {
   am.invalidate(pa);
 
   // Check that only MyAnalysis is preserved.
-  EXPECT_TRUE(am.getCachedChildAnalysis<MyAnalysis>(func1).has_value());
-  EXPECT_FALSE(am.getCachedChildAnalysis<OtherAnalysis>(func1).has_value());
+  EXPECT_TRUE(am.getCachedChildAnalysis<MyAnalysis>(func1).hasValue());
+  EXPECT_FALSE(am.getCachedChildAnalysis<OtherAnalysis>(func1).hasValue());
 }
 
 /// Test analyses with custom invalidation logic.
@@ -150,13 +150,13 @@ TEST(AnalysisManagerTest, CustomInvalidation) {
   // Check that the analysis is invalidated properly.
   am.getAnalysis<CustomInvalidatingAnalysis>();
   am.invalidate(pa);
-  EXPECT_FALSE(am.getCachedAnalysis<CustomInvalidatingAnalysis>().has_value());
+  EXPECT_FALSE(am.getCachedAnalysis<CustomInvalidatingAnalysis>().hasValue());
 
   // Check that the analysis is preserved properly.
   am.getAnalysis<CustomInvalidatingAnalysis>();
   pa.preserve<TestAnalysisSet>();
   am.invalidate(pa);
-  EXPECT_TRUE(am.getCachedAnalysis<CustomInvalidatingAnalysis>().has_value());
+  EXPECT_TRUE(am.getCachedAnalysis<CustomInvalidatingAnalysis>().hasValue());
 }
 
 TEST(AnalysisManagerTest, OpSpecificAnalysis) {
@@ -169,7 +169,7 @@ TEST(AnalysisManagerTest, OpSpecificAnalysis) {
 
   // Query the op specific analysis for the module and verify that its cached.
   am.getAnalysis<OpSpecificAnalysis, ModuleOp>();
-  EXPECT_TRUE(am.getCachedAnalysis<OpSpecificAnalysis>().has_value());
+  EXPECT_TRUE(am.getCachedAnalysis<OpSpecificAnalysis>().hasValue());
 }
 
 struct AnalysisWithDependency {
@@ -194,15 +194,15 @@ TEST(AnalysisManagerTest, DependentAnalysis) {
   AnalysisManager am = mam;
 
   am.getAnalysis<AnalysisWithDependency>();
-  EXPECT_TRUE(am.getCachedAnalysis<AnalysisWithDependency>().has_value());
-  EXPECT_TRUE(am.getCachedAnalysis<MyAnalysis>().has_value());
+  EXPECT_TRUE(am.getCachedAnalysis<AnalysisWithDependency>().hasValue());
+  EXPECT_TRUE(am.getCachedAnalysis<MyAnalysis>().hasValue());
 
   detail::PreservedAnalyses pa;
   pa.preserve<AnalysisWithDependency>();
   am.invalidate(pa);
 
-  EXPECT_FALSE(am.getCachedAnalysis<AnalysisWithDependency>().has_value());
-  EXPECT_FALSE(am.getCachedAnalysis<MyAnalysis>().has_value());
+  EXPECT_FALSE(am.getCachedAnalysis<AnalysisWithDependency>().hasValue());
+  EXPECT_FALSE(am.getCachedAnalysis<MyAnalysis>().hasValue());
 }
 
 struct AnalysisWithNestedDependency {
@@ -227,19 +227,18 @@ TEST(AnalysisManagerTest, NestedDependentAnalysis) {
   AnalysisManager am = mam;
 
   am.getAnalysis<AnalysisWithNestedDependency>();
-  EXPECT_TRUE(am.getCachedAnalysis<AnalysisWithNestedDependency>().has_value());
-  EXPECT_TRUE(am.getCachedAnalysis<AnalysisWithDependency>().has_value());
-  EXPECT_TRUE(am.getCachedAnalysis<MyAnalysis>().has_value());
+  EXPECT_TRUE(am.getCachedAnalysis<AnalysisWithNestedDependency>().hasValue());
+  EXPECT_TRUE(am.getCachedAnalysis<AnalysisWithDependency>().hasValue());
+  EXPECT_TRUE(am.getCachedAnalysis<MyAnalysis>().hasValue());
 
   detail::PreservedAnalyses pa;
   pa.preserve<AnalysisWithDependency>();
   pa.preserve<AnalysisWithNestedDependency>();
   am.invalidate(pa);
 
-  EXPECT_FALSE(
-      am.getCachedAnalysis<AnalysisWithNestedDependency>().has_value());
-  EXPECT_FALSE(am.getCachedAnalysis<AnalysisWithDependency>().has_value());
-  EXPECT_FALSE(am.getCachedAnalysis<MyAnalysis>().has_value());
+  EXPECT_FALSE(am.getCachedAnalysis<AnalysisWithNestedDependency>().hasValue());
+  EXPECT_FALSE(am.getCachedAnalysis<AnalysisWithDependency>().hasValue());
+  EXPECT_FALSE(am.getCachedAnalysis<MyAnalysis>().hasValue());
 }
 
 struct AnalysisWith2Ctors {

diff  --git a/polly/lib/Exchange/JSONExporter.cpp b/polly/lib/Exchange/JSONExporter.cpp
index d882ea67bc447..e92055bfb9af6 100644
--- a/polly/lib/Exchange/JSONExporter.cpp
+++ b/polly/lib/Exchange/JSONExporter.cpp
@@ -218,8 +218,8 @@ static bool importContext(Scop &S, const json::Object &JScop) {
     return false;
   }
 
-  isl::set NewContext =
-      isl::set{S.getIslCtx().get(), JScop.getString("context")->str()};
+  isl::set NewContext = isl::set{S.getIslCtx().get(),
+                                 JScop.getString("context").getValue().str()};
 
   // Check whether the context was parsed successfully.
   if (NewContext.is_null()) {
@@ -290,10 +290,10 @@ static bool importSchedule(Scop &S, const json::Object &JScop,
     }
     Optional<StringRef> Schedule =
         statements[Index].getAsObject()->getString("schedule");
-    assert(Schedule &&
+    assert(Schedule.hasValue() &&
            "Schedules that contain extension nodes require special handling.");
-    isl_map *Map =
-        isl_map_read_from_str(S.getIslCtx().get(), Schedule->str().c_str());
+    isl_map *Map = isl_map_read_from_str(S.getIslCtx().get(),
+                                         Schedule.getValue().str().c_str());
 
     // Check whether the schedule was parsed successfully
     if (!Map) {
@@ -575,14 +575,14 @@ static bool areArraysEqual(ScopArrayInfo *SAI, const json::Object &Array) {
   for (unsigned i = 1; i < Array.getArray("sizes")->size(); i++) {
     SAI->getDimensionSize(i)->print(RawStringOstream);
     const json::Array &SizesArray = *Array.getArray("sizes");
-    if (RawStringOstream.str() != SizesArray[i].getAsString().value())
+    if (RawStringOstream.str() != SizesArray[i].getAsString().getValue())
       return false;
     Buffer.clear();
   }
 
   // Check if key 'type' 
diff ers from the current one or is not valid.
   SAI->getElementType()->print(RawStringOstream);
-  if (RawStringOstream.str() != Array.getString("type").value()) {
+  if (RawStringOstream.str() != Array.getString("type").getValue()) {
     errs() << "Array has not a valid type.\n";
     return false;
   }
@@ -652,8 +652,9 @@ static bool importArrays(Scop &S, const json::Object &JScop) {
 
   for (; ArrayIdx < Arrays.size(); ArrayIdx++) {
     const json::Object &Array = *Arrays[ArrayIdx].getAsObject();
-    auto *ElementType = parseTextType(Array.get("type")->getAsString()->str(),
-                                      S.getSE()->getContext());
+    auto *ElementType =
+        parseTextType(Array.get("type")->getAsString().getValue().str(),
+                      S.getSE()->getContext());
     if (!ElementType) {
       errs() << "Error while parsing element type for new array.\n";
       return false;
@@ -673,10 +674,10 @@ static bool importArrays(Scop &S, const json::Object &JScop) {
     }
 
     auto NewSAI = S.createScopArrayInfo(
-        ElementType, Array.getString("name")->str(), DimSizes);
+        ElementType, Array.getString("name").getValue().str(), DimSizes);
 
     if (Array.get("allocation")) {
-      NewSAI->setIsOnHeap(Array.getString("allocation").value() == "heap");
+      NewSAI->setIsOnHeap(Array.getString("allocation").getValue() == "heap");
     }
   }
 

diff  --git a/polly/lib/Transform/ManualOptimizer.cpp b/polly/lib/Transform/ManualOptimizer.cpp
index 21d83d9f86a05..ef705eca8740c 100644
--- a/polly/lib/Transform/ManualOptimizer.cpp
+++ b/polly/lib/Transform/ManualOptimizer.cpp
@@ -42,8 +42,8 @@ static TransformationMode hasUnrollTransformation(MDNode *LoopID) {
 
   Optional<int> Count =
       getOptionalIntLoopAttribute(LoopID, "llvm.loop.unroll.count");
-  if (Count)
-    return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
+  if (Count.hasValue())
+    return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
 
   if (getBooleanLoopAttribute(LoopID, "llvm.loop.unroll.enable"))
     return TM_ForcedByUser;

diff  --git a/polly/lib/Transform/MatmulOptimizer.cpp b/polly/lib/Transform/MatmulOptimizer.cpp
index d7418d3e90a8f..4a40fac0d03be 100644
--- a/polly/lib/Transform/MatmulOptimizer.cpp
+++ b/polly/lib/Transform/MatmulOptimizer.cpp
@@ -570,29 +570,29 @@ static void getTargetCacheParameters(const llvm::TargetTransformInfo *TTI) {
   auto L1DCache = llvm::TargetTransformInfo::CacheLevel::L1D;
   auto L2DCache = llvm::TargetTransformInfo::CacheLevel::L2D;
   if (FirstCacheLevelSize == -1) {
-    if (TTI->getCacheSize(L1DCache).has_value())
-      FirstCacheLevelSize = TTI->getCacheSize(L1DCache).value();
+    if (TTI->getCacheSize(L1DCache).hasValue())
+      FirstCacheLevelSize = TTI->getCacheSize(L1DCache).getValue();
     else
       FirstCacheLevelSize = static_cast<int>(FirstCacheLevelDefaultSize);
   }
   if (SecondCacheLevelSize == -1) {
-    if (TTI->getCacheSize(L2DCache).has_value())
-      SecondCacheLevelSize = TTI->getCacheSize(L2DCache).value();
+    if (TTI->getCacheSize(L2DCache).hasValue())
+      SecondCacheLevelSize = TTI->getCacheSize(L2DCache).getValue();
     else
       SecondCacheLevelSize = static_cast<int>(SecondCacheLevelDefaultSize);
   }
   if (FirstCacheLevelAssociativity == -1) {
-    if (TTI->getCacheAssociativity(L1DCache).has_value())
+    if (TTI->getCacheAssociativity(L1DCache).hasValue())
       FirstCacheLevelAssociativity =
-          TTI->getCacheAssociativity(L1DCache).value();
+          TTI->getCacheAssociativity(L1DCache).getValue();
     else
       FirstCacheLevelAssociativity =
           static_cast<int>(FirstCacheLevelDefaultAssociativity);
   }
   if (SecondCacheLevelAssociativity == -1) {
-    if (TTI->getCacheAssociativity(L2DCache).has_value())
+    if (TTI->getCacheAssociativity(L2DCache).hasValue())
       SecondCacheLevelAssociativity =
-          TTI->getCacheAssociativity(L2DCache).value();
+          TTI->getCacheAssociativity(L2DCache).getValue();
     else
       SecondCacheLevelAssociativity =
           static_cast<int>(SecondCacheLevelDefaultAssociativity);


        


More information about the llvm-commits mailing list