[clang] Use std::optional instead of llvm::Optional (NFC)

This patch replaces (llvm::|)Optional< with std::optional<.  I'll post
a separate patch to remove #include "llvm/ADT/Optional.h".

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

https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
This commit is contained in:
Kazu Hirata 2023-01-14 12:31:01 -08:00
parent ff39b7ea89
commit 6ad0788c33
379 changed files with 2277 additions and 2197 deletions

View File

@ -1588,9 +1588,10 @@ public:
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
QualType Wrapped); QualType Wrapped);
QualType getSubstTemplateTypeParmType(QualType Replacement, QualType
Decl *AssociatedDecl, unsigned Index, getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl,
Optional<unsigned> PackIndex) const; unsigned Index,
std::optional<unsigned> PackIndex) const;
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
unsigned Index, bool Final, unsigned Index, bool Final,
const TemplateArgument &ArgPack); const TemplateArgument &ArgPack);
@ -1653,7 +1654,7 @@ public:
/// elsewhere, such as if the pattern contains a placeholder type or /// elsewhere, such as if the pattern contains a placeholder type or
/// if this is the canonical type of another pack expansion type. /// if this is the canonical type of another pack expansion type.
QualType getPackExpansionType(QualType Pattern, QualType getPackExpansionType(QualType Pattern,
Optional<unsigned> NumExpansions, std::optional<unsigned> NumExpansions,
bool ExpectPackInType = true); bool ExpectPackInType = true);
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
@ -2172,10 +2173,10 @@ public:
const IdentifierInfo *Name) const; const IdentifierInfo *Name) const;
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
OverloadedOperatorKind Operator) const; OverloadedOperatorKind Operator) const;
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, TemplateName
Decl *AssociatedDecl, getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl,
unsigned Index, unsigned Index,
Optional<unsigned> PackIndex) const; std::optional<unsigned> PackIndex) const;
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
Decl *AssociatedDecl, Decl *AssociatedDecl,
unsigned Index, unsigned Index,
@ -2289,13 +2290,13 @@ public:
CharUnits getTypeSizeInChars(QualType T) const; CharUnits getTypeSizeInChars(QualType T) const;
CharUnits getTypeSizeInChars(const Type *T) const; CharUnits getTypeSizeInChars(const Type *T) const;
Optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const { std::optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const {
if (Ty->isIncompleteType() || Ty->isDependentType()) if (Ty->isIncompleteType() || Ty->isDependentType())
return std::nullopt; return std::nullopt;
return getTypeSizeInChars(Ty); return getTypeSizeInChars(Ty);
} }
Optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const { std::optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const {
return getTypeSizeInCharsIfKnown(QualType(Ty, 0)); return getTypeSizeInCharsIfKnown(QualType(Ty, 0));
} }

View File

@ -368,7 +368,7 @@ class TypeSourceInfo;
/// in the "to" context was imported. If it was not imported or of the wrong /// in the "to" context was imported. If it was not imported or of the wrong
/// type a null value is returned. /// type a null value is returned.
template <typename DeclT> template <typename DeclT>
llvm::Optional<DeclT *> getImportedFromDecl(const DeclT *ToD) const { std::optional<DeclT *> getImportedFromDecl(const DeclT *ToD) const {
auto FromI = ImportedFromDecls.find(ToD); auto FromI = ImportedFromDecls.find(ToD);
if (FromI == ImportedFromDecls.end()) if (FromI == ImportedFromDecls.end())
return {}; return {};
@ -565,7 +565,7 @@ class TypeSourceInfo;
/// Return if import of the given declaration has failed and if yes /// Return if import of the given declaration has failed and if yes
/// the kind of the problem. This gives the first error encountered with /// the kind of the problem. This gives the first error encountered with
/// the node. /// the node.
llvm::Optional<ASTImportError> getImportDeclErrorIfAny(Decl *FromD) const; std::optional<ASTImportError> getImportDeclErrorIfAny(Decl *FromD) const;
/// Mark (newly) imported declaration with error. /// Mark (newly) imported declaration with error.
void setImportDeclError(Decl *From, ASTImportError Error); void setImportDeclError(Decl *From, ASTImportError Error);
@ -579,7 +579,7 @@ class TypeSourceInfo;
/// F should be a field (or indirect field) declaration. /// F should be a field (or indirect field) declaration.
/// \returns The index of the field in its parent context (starting from 0). /// \returns The index of the field in its parent context (starting from 0).
/// On error `std::nullopt` is returned (parent context is non-record). /// On error `std::nullopt` is returned (parent context is non-record).
static llvm::Optional<unsigned> getFieldIndex(Decl *F); static std::optional<unsigned> getFieldIndex(Decl *F);
}; };
} // namespace clang } // namespace clang

View File

@ -66,7 +66,7 @@ public:
LookupTable->remove(ND); LookupTable->remove(ND);
} }
llvm::Optional<ASTImportError> getImportDeclErrorIfAny(Decl *ToD) const { std::optional<ASTImportError> getImportDeclErrorIfAny(Decl *ToD) const {
auto Pos = ImportErrors.find(ToD); auto Pos = ImportErrors.find(ToD);
if (Pos != ImportErrors.end()) if (Pos != ImportErrors.end())
return Pos->second; return Pos->second;

View File

@ -115,7 +115,7 @@ struct StructuralEquivalenceContext {
/// ///
/// FIXME: This is needed by ASTImporter and ASTStructureEquivalence. It /// FIXME: This is needed by ASTImporter and ASTStructureEquivalence. It
/// probably makes more sense in some other common place then here. /// probably makes more sense in some other common place then here.
static llvm::Optional<unsigned> static std::optional<unsigned>
findUntaggedStructOrUnionIndex(RecordDecl *Anon); findUntaggedStructOrUnionIndex(RecordDecl *Anon);
// If ErrorOnTagTypeMismatch is set, return the error, otherwise get the // If ErrorOnTagTypeMismatch is set, return the error, otherwise get the

View File

@ -16,12 +16,11 @@ namespace clang {
namespace serialization { namespace serialization {
template <class T> template <class T>
inline T makeNullableFromOptional(const Optional<T> &value) { inline T makeNullableFromOptional(const std::optional<T> &value) {
return (value ? *value : T()); return (value ? *value : T());
} }
template <class T> template <class T> inline T *makePointerFromOptional(std::optional<T *> value) {
inline T *makePointerFromOptional(Optional<T *> value) {
return value.value_or(nullptr); return value.value_or(nullptr);
} }
@ -50,7 +49,7 @@ inline T *makePointerFromOptional(Optional<T *> value) {
// type-specific readers for all the enum types. // type-specific readers for all the enum types.
// //
// template <class ValueType> // template <class ValueType>
// Optional<ValueType> writeOptional(); // std::optional<ValueType> writeOptional();
// //
// Reads an optional value from the current property. // Reads an optional value from the current property.
// //
@ -158,7 +157,7 @@ public:
} }
template <class T, class... Args> template <class T, class... Args>
llvm::Optional<T> readOptional(Args &&...args) { std::optional<T> readOptional(Args &&...args) {
return UnpackOptionalValue<T>::unpack( return UnpackOptionalValue<T>::unpack(
ReadDispatcher<T>::read(asImpl(), std::forward<Args>(args)...)); ReadDispatcher<T>::read(asImpl(), std::forward<Args>(args)...));
} }

View File

@ -17,15 +17,12 @@ namespace clang {
namespace serialization { namespace serialization {
template <class T> template <class T>
inline llvm::Optional<T> makeOptionalFromNullable(const T &value) { inline std::optional<T> makeOptionalFromNullable(const T &value) {
return (value.isNull() return (value.isNull() ? std::optional<T>() : std::optional<T>(value));
? llvm::Optional<T>()
: llvm::Optional<T>(value));
} }
template <class T> template <class T> inline std::optional<T *> makeOptionalFromPointer(T *value) {
inline llvm::Optional<T*> makeOptionalFromPointer(T *value) { return (value ? std::optional<T *>(value) : std::optional<T *>());
return (value ? llvm::Optional<T*>(value) : llvm::Optional<T*>());
} }
// PropertyWriter is a class concept that requires the following method: // PropertyWriter is a class concept that requires the following method:
@ -52,7 +49,7 @@ inline llvm::Optional<T*> makeOptionalFromPointer(T *value) {
// type-specific writers for all the enum types. // type-specific writers for all the enum types.
// //
// template <class ValueType> // template <class ValueType>
// void writeOptional(Optional<ValueType> value); // void writeOptional(std::optional<ValueType> value);
// //
// Writes an optional value as the current property. // Writes an optional value as the current property.
// //
@ -149,8 +146,7 @@ public:
} }
} }
template <class T> template <class T> void writeOptional(std::optional<T> value) {
void writeOptional(llvm::Optional<T> value) {
WriteDispatcher<T>::write(asImpl(), PackOptionalValue<T>::pack(value)); WriteDispatcher<T>::write(asImpl(), PackOptionalValue<T>::pack(value));
} }

View File

@ -59,7 +59,8 @@ inline ComparisonCategoryType commonComparisonType(ComparisonCategoryType A,
/// Get the comparison category that should be used when comparing values of /// Get the comparison category that should be used when comparing values of
/// type \c T. /// type \c T.
Optional<ComparisonCategoryType> getComparisonCategoryForBuiltinCmp(QualType T); std::optional<ComparisonCategoryType>
getComparisonCategoryForBuiltinCmp(QualType T);
/// An enumeration representing the possible results of a three-way /// An enumeration representing the possible results of a three-way
/// comparison. These values map onto instances of comparison category types /// comparison. These values map onto instances of comparison category types

View File

@ -438,7 +438,7 @@ public:
/// If visibility was explicitly specified for this /// If visibility was explicitly specified for this
/// declaration, return that visibility. /// declaration, return that visibility.
Optional<Visibility> std::optional<Visibility>
getExplicitVisibility(ExplicitVisibilityKind kind) const; getExplicitVisibility(ExplicitVisibilityKind kind) const;
/// True if the computed linkage is valid. Used for consistency /// True if the computed linkage is valid. Used for consistency
@ -2475,7 +2475,7 @@ public:
/// If this function is an allocation/deallocation function that takes /// If this function is an allocation/deallocation function that takes
/// the `std::nothrow_t` tag, return true through IsNothrow, /// the `std::nothrow_t` tag, return true through IsNothrow,
bool isReplaceableGlobalAllocationFunction( bool isReplaceableGlobalAllocationFunction(
Optional<unsigned> *AlignmentParam = nullptr, std::optional<unsigned> *AlignmentParam = nullptr,
bool *IsNothrow = nullptr) const; bool *IsNothrow = nullptr) const;
/// Determine if this function provides an inline implementation of a builtin. /// Determine if this function provides an inline implementation of a builtin.

View File

@ -1237,7 +1237,8 @@ class TemplateTypeParmDecl final : public TypeDecl,
TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc, TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
SourceLocation IdLoc, IdentifierInfo *Id, bool Typename, SourceLocation IdLoc, IdentifierInfo *Id, bool Typename,
bool HasTypeConstraint, Optional<unsigned> NumExpanded) bool HasTypeConstraint,
std::optional<unsigned> NumExpanded)
: TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename), : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename),
HasTypeConstraint(HasTypeConstraint), TypeConstraintInitialized(false), HasTypeConstraint(HasTypeConstraint), TypeConstraintInitialized(false),
ExpandedParameterPack(NumExpanded), ExpandedParameterPack(NumExpanded),
@ -1248,7 +1249,7 @@ public:
Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc,
SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id,
bool Typename, bool ParameterPack, bool HasTypeConstraint = false, bool Typename, bool ParameterPack, bool HasTypeConstraint = false,
Optional<unsigned> NumExpanded = std::nullopt); std::optional<unsigned> NumExpanded = std::nullopt);
static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C, static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
unsigned ID); unsigned ID);
static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C, static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
@ -3433,7 +3434,7 @@ inline TemplateDecl *getAsTypeTemplateDecl(Decl *D) {
/// ///
/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
/// is not a pack expansion, so returns an empty Optional. /// is not a pack expansion, so returns an empty Optional.
inline Optional<unsigned> getExpandedPackSize(const NamedDecl *Param) { inline std::optional<unsigned> getExpandedPackSize(const NamedDecl *Param) {
if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
if (TTP->isExpandedParameterPack()) if (TTP->isExpandedParameterPack())
return TTP->getNumExpansionParameters(); return TTP->getNumExpansionParameters();

View File

@ -540,9 +540,9 @@ public:
/// ///
/// Note: This does not perform the implicit conversions required by C++11 /// Note: This does not perform the implicit conversions required by C++11
/// [expr.const]p5. /// [expr.const]p5.
Optional<llvm::APSInt> getIntegerConstantExpr(const ASTContext &Ctx, std::optional<llvm::APSInt>
SourceLocation *Loc = nullptr, getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc = nullptr,
bool isEvaluated = true) const; bool isEvaluated = true) const;
bool isIntegerConstantExpr(const ASTContext &Ctx, bool isIntegerConstantExpr(const ASTContext &Ctx,
SourceLocation *Loc = nullptr) const; SourceLocation *Loc = nullptr) const;

View File

@ -2263,7 +2263,7 @@ private:
CXXNewExpr(bool IsGlobalNew, FunctionDecl *OperatorNew, CXXNewExpr(bool IsGlobalNew, FunctionDecl *OperatorNew,
FunctionDecl *OperatorDelete, bool ShouldPassAlignment, FunctionDecl *OperatorDelete, bool ShouldPassAlignment,
bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs, bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs,
SourceRange TypeIdParens, Optional<Expr *> ArraySize, SourceRange TypeIdParens, std::optional<Expr *> ArraySize,
InitializationStyle InitializationStyle, Expr *Initializer, InitializationStyle InitializationStyle, Expr *Initializer,
QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range, QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,
SourceRange DirectInitRange); SourceRange DirectInitRange);
@ -2278,7 +2278,7 @@ public:
Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew, Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew,
FunctionDecl *OperatorDelete, bool ShouldPassAlignment, FunctionDecl *OperatorDelete, bool ShouldPassAlignment,
bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs, bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs,
SourceRange TypeIdParens, Optional<Expr *> ArraySize, SourceRange TypeIdParens, std::optional<Expr *> ArraySize,
InitializationStyle InitializationStyle, Expr *Initializer, InitializationStyle InitializationStyle, Expr *Initializer,
QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range, QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,
SourceRange DirectInitRange); SourceRange DirectInitRange);
@ -2323,7 +2323,7 @@ public:
/// This might return std::nullopt even if isArray() returns true, /// This might return std::nullopt even if isArray() returns true,
/// since there might not be an array size expression. /// since there might not be an array size expression.
/// If the result is not-None, it will never wrap a nullptr. /// If the result is not-None, it will never wrap a nullptr.
Optional<Expr *> getArraySize() { std::optional<Expr *> getArraySize() {
if (!isArray()) if (!isArray())
return std::nullopt; return std::nullopt;
@ -2337,7 +2337,7 @@ public:
/// This might return std::nullopt even if isArray() returns true, /// This might return std::nullopt even if isArray() returns true,
/// since there might not be an array size expression. /// since there might not be an array size expression.
/// If the result is not-None, it will never wrap a nullptr. /// If the result is not-None, it will never wrap a nullptr.
Optional<const Expr *> getArraySize() const { std::optional<const Expr *> getArraySize() const {
if (!isArray()) if (!isArray())
return std::nullopt; return std::nullopt;
@ -4139,7 +4139,7 @@ class PackExpansionExpr : public Expr {
public: public:
PackExpansionExpr(QualType T, Expr *Pattern, SourceLocation EllipsisLoc, PackExpansionExpr(QualType T, Expr *Pattern, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions) std::optional<unsigned> NumExpansions)
: Expr(PackExpansionExprClass, T, Pattern->getValueKind(), : Expr(PackExpansionExprClass, T, Pattern->getValueKind(),
Pattern->getObjectKind()), Pattern->getObjectKind()),
EllipsisLoc(EllipsisLoc), EllipsisLoc(EllipsisLoc),
@ -4162,7 +4162,7 @@ public:
/// Determine the number of expansions that will be produced when /// Determine the number of expansions that will be produced when
/// this pack expansion is instantiated, if already known. /// this pack expansion is instantiated, if already known.
Optional<unsigned> getNumExpansions() const { std::optional<unsigned> getNumExpansions() const {
if (NumExpansions) if (NumExpansions)
return NumExpansions - 1; return NumExpansions - 1;
@ -4233,7 +4233,7 @@ class SizeOfPackExpr final
/// the given parameter pack. /// the given parameter pack.
SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack, SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
SourceLocation PackLoc, SourceLocation RParenLoc, SourceLocation PackLoc, SourceLocation RParenLoc,
Optional<unsigned> Length, std::optional<unsigned> Length,
ArrayRef<TemplateArgument> PartialArgs) ArrayRef<TemplateArgument> PartialArgs)
: Expr(SizeOfPackExprClass, SizeType, VK_PRValue, OK_Ordinary), : Expr(SizeOfPackExprClass, SizeType, VK_PRValue, OK_Ordinary),
OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc), OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
@ -4254,7 +4254,7 @@ public:
static SizeOfPackExpr * static SizeOfPackExpr *
Create(ASTContext &Context, SourceLocation OperatorLoc, NamedDecl *Pack, Create(ASTContext &Context, SourceLocation OperatorLoc, NamedDecl *Pack,
SourceLocation PackLoc, SourceLocation RParenLoc, SourceLocation PackLoc, SourceLocation RParenLoc,
Optional<unsigned> Length = std::nullopt, std::optional<unsigned> Length = std::nullopt,
ArrayRef<TemplateArgument> PartialArgs = std::nullopt); ArrayRef<TemplateArgument> PartialArgs = std::nullopt);
static SizeOfPackExpr *CreateDeserialized(ASTContext &Context, static SizeOfPackExpr *CreateDeserialized(ASTContext &Context,
unsigned NumPartialArgs); unsigned NumPartialArgs);
@ -4338,7 +4338,7 @@ public:
SubstNonTypeTemplateParmExpr(QualType Ty, ExprValueKind ValueKind, SubstNonTypeTemplateParmExpr(QualType Ty, ExprValueKind ValueKind,
SourceLocation Loc, Expr *Replacement, SourceLocation Loc, Expr *Replacement,
Decl *AssociatedDecl, unsigned Index, Decl *AssociatedDecl, unsigned Index,
Optional<unsigned> PackIndex, bool RefParam) std::optional<unsigned> PackIndex, bool RefParam)
: Expr(SubstNonTypeTemplateParmExprClass, Ty, ValueKind, OK_Ordinary), : Expr(SubstNonTypeTemplateParmExprClass, Ty, ValueKind, OK_Ordinary),
Replacement(Replacement), Replacement(Replacement),
AssociatedDeclAndRef(AssociatedDecl, RefParam), Index(Index), AssociatedDeclAndRef(AssociatedDecl, RefParam), Index(Index),
@ -4364,7 +4364,7 @@ public:
/// This should match the result of `getParameter()->getIndex()`. /// This should match the result of `getParameter()->getIndex()`.
unsigned getIndex() const { return Index; } unsigned getIndex() const { return Index; }
Optional<unsigned> getPackIndex() const { std::optional<unsigned> getPackIndex() const {
if (PackIndex == 0) if (PackIndex == 0)
return std::nullopt; return std::nullopt;
return PackIndex - 1; return PackIndex - 1;
@ -4691,7 +4691,7 @@ public:
CXXFoldExpr(QualType T, UnresolvedLookupExpr *Callee, CXXFoldExpr(QualType T, UnresolvedLookupExpr *Callee,
SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Opcode, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Opcode,
SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc,
Optional<unsigned> NumExpansions) std::optional<unsigned> NumExpansions)
: Expr(CXXFoldExprClass, T, VK_PRValue, OK_Ordinary), : Expr(CXXFoldExprClass, T, VK_PRValue, OK_Ordinary),
LParenLoc(LParenLoc), EllipsisLoc(EllipsisLoc), RParenLoc(RParenLoc), LParenLoc(LParenLoc), EllipsisLoc(EllipsisLoc), RParenLoc(RParenLoc),
NumExpansions(NumExpansions ? *NumExpansions + 1 : 0), Opcode(Opcode) { NumExpansions(NumExpansions ? *NumExpansions + 1 : 0), Opcode(Opcode) {
@ -4728,7 +4728,7 @@ public:
SourceLocation getEllipsisLoc() const { return EllipsisLoc; } SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
BinaryOperatorKind getOperator() const { return Opcode; } BinaryOperatorKind getOperator() const { return Opcode; }
Optional<unsigned> getNumExpansions() const { std::optional<unsigned> getNumExpansions() const {
if (NumExpansions) if (NumExpansions)
return NumExpansions - 1; return NumExpansions - 1;
return std::nullopt; return std::nullopt;

View File

@ -272,7 +272,7 @@ struct ObjCDictionaryElement {
/// The number of elements this pack expansion will expand to, if /// The number of elements this pack expansion will expand to, if
/// this is a pack expansion and is known. /// this is a pack expansion and is known.
Optional<unsigned> NumExpansions; std::optional<unsigned> NumExpansions;
/// Determines whether this dictionary element is a pack expansion. /// Determines whether this dictionary element is a pack expansion.
bool isPackExpansion() const { return EllipsisLoc.isValid(); } bool isPackExpansion() const { return EllipsisLoc.isValid(); }

View File

@ -161,7 +161,7 @@ public:
virtual Module *getModule(unsigned ID) { return nullptr; } virtual Module *getModule(unsigned ID) { return nullptr; }
/// Return a descriptor for the corresponding module, if one exists. /// Return a descriptor for the corresponding module, if one exists.
virtual llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID); virtual std::optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID);
enum ExtKind { EK_Always, EK_Never, EK_ReplyHazy }; enum ExtKind { EK_Always, EK_Never, EK_ReplyHazy };

View File

@ -242,7 +242,7 @@ public:
bool isPrintfKind() const { return IsPrintf; } bool isPrintfKind() const { return IsPrintf; }
Optional<ConversionSpecifier> getStandardSpecifier() const; std::optional<ConversionSpecifier> getStandardSpecifier() const;
protected: protected:
bool IsPrintf; bool IsPrintf;
@ -467,7 +467,7 @@ public:
bool hasStandardLengthModifier() const; bool hasStandardLengthModifier() const;
Optional<LengthModifier> getCorrectedLengthModifier() const; std::optional<LengthModifier> getCorrectedLengthModifier() const;
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const; bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const;

View File

@ -185,7 +185,7 @@ public:
class ItaniumMangleContext : public MangleContext { class ItaniumMangleContext : public MangleContext {
public: public:
using DiscriminatorOverrideTy = using DiscriminatorOverrideTy =
llvm::Optional<unsigned> (*)(ASTContext &, const NamedDecl *); std::optional<unsigned> (*)(ASTContext &, const NamedDecl *);
explicit ItaniumMangleContext(ASTContext &C, DiagnosticsEngine &D, explicit ItaniumMangleContext(ASTContext &C, DiagnosticsEngine &D,
bool IsAux = false) bool IsAux = false)
: MangleContext(C, D, MK_Itanium, IsAux) {} : MangleContext(C, D, MK_Itanium, IsAux) {}

View File

@ -90,7 +90,7 @@ public:
Selector getNSArraySelector(NSArrayMethodKind MK) const; Selector getNSArraySelector(NSArrayMethodKind MK) const;
/// Return NSArrayMethodKind if \p Sel is such a selector. /// Return NSArrayMethodKind if \p Sel is such a selector.
Optional<NSArrayMethodKind> getNSArrayMethodKind(Selector Sel); std::optional<NSArrayMethodKind> getNSArrayMethodKind(Selector Sel);
/// Enumerates the NSDictionary/NSMutableDictionary methods used /// Enumerates the NSDictionary/NSMutableDictionary methods used
/// to generate literals and to apply some checks. /// to generate literals and to apply some checks.
@ -115,7 +115,7 @@ public:
Selector getNSDictionarySelector(NSDictionaryMethodKind MK) const; Selector getNSDictionarySelector(NSDictionaryMethodKind MK) const;
/// Return NSDictionaryMethodKind if \p Sel is such a selector. /// Return NSDictionaryMethodKind if \p Sel is such a selector.
Optional<NSDictionaryMethodKind> getNSDictionaryMethodKind(Selector Sel); std::optional<NSDictionaryMethodKind> getNSDictionaryMethodKind(Selector Sel);
/// Enumerates the NSMutableSet/NSOrderedSet methods used /// Enumerates the NSMutableSet/NSOrderedSet methods used
/// to apply some checks. /// to apply some checks.
@ -132,7 +132,7 @@ public:
Selector getNSSetSelector(NSSetMethodKind MK) const; Selector getNSSetSelector(NSSetMethodKind MK) const;
/// Return NSSetMethodKind if \p Sel is such a selector. /// Return NSSetMethodKind if \p Sel is such a selector.
Optional<NSSetMethodKind> getNSSetMethodKind(Selector Sel); std::optional<NSSetMethodKind> getNSSetMethodKind(Selector Sel);
/// Returns selector for "objectForKeyedSubscript:". /// Returns selector for "objectForKeyedSubscript:".
Selector getObjectForKeyedSubscriptSelector() const { Selector getObjectForKeyedSubscriptSelector() const {
@ -204,13 +204,13 @@ public:
} }
/// Return NSNumberLiteralMethodKind if \p Sel is such a selector. /// Return NSNumberLiteralMethodKind if \p Sel is such a selector.
Optional<NSNumberLiteralMethodKind> std::optional<NSNumberLiteralMethodKind>
getNSNumberLiteralMethodKind(Selector Sel) const; getNSNumberLiteralMethodKind(Selector Sel) const;
/// Determine the appropriate NSNumber factory method kind for a /// Determine the appropriate NSNumber factory method kind for a
/// literal of the given type. /// literal of the given type.
Optional<NSNumberLiteralMethodKind> std::optional<NSNumberLiteralMethodKind>
getNSNumberFactoryMethodKind(QualType T) const; getNSNumberFactoryMethodKind(QualType T) const;
/// Returns true if \param T is a typedef of "BOOL" in objective-c. /// Returns true if \param T is a typedef of "BOOL" in objective-c.
bool isObjCBOOLType(QualType T) const; bool isObjCBOOLType(QualType T) const;

View File

@ -41,7 +41,7 @@ class RefPropertyType<string className> : PropertyType<className # "*"> {
let PackOptional = let PackOptional =
"value ? *value : nullptr"; "value ? *value : nullptr";
let UnpackOptional = let UnpackOptional =
"value ? llvm::Optional<" # CXXName # ">(value) : std::nullopt"; "value ? std::optional<" # CXXName # ">(value) : std::nullopt";
} }
/// Property types that correspond to a specific subclass of another type. /// Property types that correspond to a specific subclass of another type.
@ -58,7 +58,7 @@ class DefaultValuePropertyType<string typeName = ""> : PropertyType<typeName> {
let PackOptional = let PackOptional =
"value ? *value : " # CXXName # "()"; "value ? *value : " # CXXName # "()";
let UnpackOptional = let UnpackOptional =
"value.isNull() ? std::nullopt : llvm::Optional<" # CXXName # ">(value)"; "value.isNull() ? std::nullopt : std::optional<" # CXXName # ">(value)";
} }
/// Property types that correspond to integer types and support optional /// Property types that correspond to integer types and support optional
@ -67,7 +67,7 @@ class CountPropertyType<string typeName = ""> : PropertyType<typeName> {
let PackOptional = let PackOptional =
"value ? *value + 1 : 0"; "value ? *value + 1 : 0";
let UnpackOptional = let UnpackOptional =
"value ? llvm::Optional<" # CXXName # ">(value - 1) : std::nullopt"; "value ? std::optional<" # CXXName # ">(value - 1) : std::nullopt";
} }
def APInt : PropertyType<"llvm::APInt"> { let PassByReference = 1; } def APInt : PropertyType<"llvm::APInt"> { let PassByReference = 1; }
@ -155,7 +155,7 @@ class Array<PropertyType element> : PropertyType {
let BufferElementTypes = [ element ]; let BufferElementTypes = [ element ];
} }
/// llvm::Optional<T>. The corresponding C++ type is generally just the /// std::optional<T>. The corresponding C++ type is generally just the
/// corresponding C++ type of the element. /// corresponding C++ type of the element.
/// ///
/// Optional<Unsigned> may restrict the range of the operand for some /// Optional<Unsigned> may restrict the range of the operand for some

View File

@ -2149,8 +2149,8 @@ public:
/// If this is an 'if constexpr', determine which substatement will be taken. /// If this is an 'if constexpr', determine which substatement will be taken.
/// Otherwise, or if the condition is value-dependent, returns std::nullopt. /// Otherwise, or if the condition is value-dependent, returns std::nullopt.
Optional<const Stmt*> getNondiscardedCase(const ASTContext &Ctx) const; std::optional<const Stmt *> getNondiscardedCase(const ASTContext &Ctx) const;
Optional<Stmt *> getNondiscardedCase(const ASTContext &Ctx); std::optional<Stmt *> getNondiscardedCase(const ASTContext &Ctx);
bool isObjCAvailabilityCheck() const; bool isObjCAvailabilityCheck() const;

View File

@ -202,7 +202,7 @@ public:
/// ///
/// \param NumExpansions The number of expansions that will be generated by /// \param NumExpansions The number of expansions that will be generated by
/// instantiating /// instantiating
TemplateArgument(TemplateName Name, Optional<unsigned> NumExpansions) { TemplateArgument(TemplateName Name, std::optional<unsigned> NumExpansions) {
TemplateArg.Kind = TemplateExpansion; TemplateArg.Kind = TemplateExpansion;
TemplateArg.Name = Name.getAsVoidPointer(); TemplateArg.Name = Name.getAsVoidPointer();
if (NumExpansions) if (NumExpansions)
@ -307,7 +307,7 @@ public:
/// Retrieve the number of expansions that a template template argument /// Retrieve the number of expansions that a template template argument
/// expansion will produce, if known. /// expansion will produce, if known.
Optional<unsigned> getNumTemplateExpansions() const; std::optional<unsigned> getNumTemplateExpansions() const;
/// Retrieve the template argument as an integral value. /// Retrieve the template argument as an integral value.
// FIXME: Provide a way to read the integral data without copying the value. // FIXME: Provide a way to read the integral data without copying the value.

View File

@ -380,7 +380,7 @@ class SubstTemplateTemplateParmStorage
SubstTemplateTemplateParmStorage(TemplateName Replacement, SubstTemplateTemplateParmStorage(TemplateName Replacement,
Decl *AssociatedDecl, unsigned Index, Decl *AssociatedDecl, unsigned Index,
Optional<unsigned> PackIndex) std::optional<unsigned> PackIndex)
: UncommonTemplateNameStorage(SubstTemplateTemplateParm, Index, : UncommonTemplateNameStorage(SubstTemplateTemplateParm, Index,
PackIndex ? *PackIndex + 1 : 0), PackIndex ? *PackIndex + 1 : 0),
Replacement(Replacement), AssociatedDecl(AssociatedDecl) { Replacement(Replacement), AssociatedDecl(AssociatedDecl) {
@ -396,7 +396,7 @@ public:
/// This should match the result of `getParameter()->getIndex()`. /// This should match the result of `getParameter()->getIndex()`.
unsigned getIndex() const { return Bits.Index; } unsigned getIndex() const { return Bits.Index; }
Optional<unsigned> getPackIndex() const { std::optional<unsigned> getPackIndex() const {
if (Bits.Data == 0) if (Bits.Data == 0)
return std::nullopt; return std::nullopt;
return Bits.Data - 1; return Bits.Data - 1;
@ -409,7 +409,7 @@ public:
static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Replacement, static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Replacement,
Decl *AssociatedDecl, unsigned Index, Decl *AssociatedDecl, unsigned Index,
Optional<unsigned> PackIndex); std::optional<unsigned> PackIndex);
}; };
inline TemplateName TemplateName::getUnderlying() const { inline TemplateName TemplateName::getUnderlying() const {

View File

@ -2553,7 +2553,7 @@ public:
/// Note that nullability is only captured as sugar within the type /// Note that nullability is only captured as sugar within the type
/// system, not as part of the canonical type, so nullability will /// system, not as part of the canonical type, so nullability will
/// be lost by canonicalization and desugaring. /// be lost by canonicalization and desugaring.
Optional<NullabilityKind> getNullability() const; std::optional<NullabilityKind> getNullability() const;
/// Determine whether the given type can have a nullability /// Determine whether the given type can have a nullability
/// specifier applied to it, i.e., if it is any kind of pointer type. /// specifier applied to it, i.e., if it is any kind of pointer type.
@ -2577,7 +2577,7 @@ public:
/// the type parameters of the given declaration context in any type described /// the type parameters of the given declaration context in any type described
/// within that context, or an empty optional to indicate that no /// within that context, or an empty optional to indicate that no
/// substitution is required. /// substitution is required.
Optional<ArrayRef<QualType>> std::optional<ArrayRef<QualType>>
getObjCSubstitutions(const DeclContext *dc) const; getObjCSubstitutions(const DeclContext *dc) const;
/// Determines if this is an ObjC interface type that may accept type /// Determines if this is an ObjC interface type that may accept type
@ -4923,7 +4923,7 @@ public:
bool isCallingConv() const; bool isCallingConv() const;
llvm::Optional<NullabilityKind> getImmediateNullability() const; std::optional<NullabilityKind> getImmediateNullability() const;
/// Retrieve the attribute kind corresponding to the given /// Retrieve the attribute kind corresponding to the given
/// nullability kind. /// nullability kind.
@ -4953,7 +4953,7 @@ public:
/// to the underlying modified type. /// to the underlying modified type.
/// ///
/// \returns the top-level nullability, if present. /// \returns the top-level nullability, if present.
static Optional<NullabilityKind> stripOuterNullability(QualType &T); static std::optional<NullabilityKind> stripOuterNullability(QualType &T);
void Profile(llvm::FoldingSetNodeID &ID) { void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, getAttrKind(), ModifiedType, EquivalentType); Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
@ -5094,7 +5094,7 @@ class SubstTemplateTypeParmType final
Decl *AssociatedDecl; Decl *AssociatedDecl;
SubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, SubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl,
unsigned Index, Optional<unsigned> PackIndex); unsigned Index, std::optional<unsigned> PackIndex);
public: public:
/// Gets the type that was substituted for the template /// Gets the type that was substituted for the template
@ -5117,7 +5117,7 @@ public:
/// This should match the result of `getReplacedParameter()->getIndex()`. /// This should match the result of `getReplacedParameter()->getIndex()`.
unsigned getIndex() const { return SubstTemplateTypeParmTypeBits.Index; } unsigned getIndex() const { return SubstTemplateTypeParmTypeBits.Index; }
Optional<unsigned> getPackIndex() const { std::optional<unsigned> getPackIndex() const {
if (SubstTemplateTypeParmTypeBits.PackIndex == 0) if (SubstTemplateTypeParmTypeBits.PackIndex == 0)
return std::nullopt; return std::nullopt;
return SubstTemplateTypeParmTypeBits.PackIndex - 1; return SubstTemplateTypeParmTypeBits.PackIndex - 1;
@ -5133,7 +5133,7 @@ public:
static void Profile(llvm::FoldingSetNodeID &ID, QualType Replacement, static void Profile(llvm::FoldingSetNodeID &ID, QualType Replacement,
const Decl *AssociatedDecl, unsigned Index, const Decl *AssociatedDecl, unsigned Index,
Optional<unsigned> PackIndex) { std::optional<unsigned> PackIndex) {
Replacement.Profile(ID); Replacement.Profile(ID);
ID.AddPointer(AssociatedDecl); ID.AddPointer(AssociatedDecl);
ID.AddInteger(Index); ID.AddInteger(Index);
@ -5847,7 +5847,7 @@ class PackExpansionType : public Type, public llvm::FoldingSetNode {
QualType Pattern; QualType Pattern;
PackExpansionType(QualType Pattern, QualType Canon, PackExpansionType(QualType Pattern, QualType Canon,
Optional<unsigned> NumExpansions) std::optional<unsigned> NumExpansions)
: Type(PackExpansion, Canon, : Type(PackExpansion, Canon,
(Pattern->getDependence() | TypeDependence::Dependent | (Pattern->getDependence() | TypeDependence::Dependent |
TypeDependence::Instantiation) & TypeDependence::Instantiation) &
@ -5865,7 +5865,7 @@ public:
/// Retrieve the number of expansions that this pack expansion will /// Retrieve the number of expansions that this pack expansion will
/// generate, if known. /// generate, if known.
Optional<unsigned> getNumExpansions() const { std::optional<unsigned> getNumExpansions() const {
if (PackExpansionTypeBits.NumExpansions) if (PackExpansionTypeBits.NumExpansions)
return PackExpansionTypeBits.NumExpansions - 1; return PackExpansionTypeBits.NumExpansions - 1;
return std::nullopt; return std::nullopt;
@ -5879,7 +5879,7 @@ public:
} }
static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern, static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
Optional<unsigned> NumExpansions) { std::optional<unsigned> NumExpansions) {
ID.AddPointer(Pattern.getAsOpaquePtr()); ID.AddPointer(Pattern.getAsOpaquePtr());
ID.AddBoolean(NumExpansions.has_value()); ID.AddBoolean(NumExpansions.has_value());
if (NumExpansions) if (NumExpansions)

View File

@ -666,10 +666,10 @@ let Class = TemplateSpecializationType in {
def : Property<"underlyingType", Optional<QualType>> { def : Property<"underlyingType", Optional<QualType>> {
let Read = [{ let Read = [{
node->isTypeAlias() node->isTypeAlias()
? llvm::Optional<QualType>(node->getAliasedType()) ? std::optional<QualType>(node->getAliasedType())
: node->isCanonicalUnqualified() : node->isCanonicalUnqualified()
? std::nullopt ? std::nullopt
: llvm::Optional<QualType>(node->getCanonicalTypeInternal()) : std::optional<QualType>(node->getCanonicalTypeInternal())
}]; }];
} }
@ -835,7 +835,7 @@ let Class = DependentNameType in {
let Read = [{ let Read = [{
node->isCanonicalUnqualified() node->isCanonicalUnqualified()
? std::nullopt ? std::nullopt
: llvm::Optional<QualType>(node->getCanonicalTypeInternal()) : std::optional<QualType>(node->getCanonicalTypeInternal())
}]; }];
} }

View File

@ -138,7 +138,7 @@ public:
/// Enables per-check timers. /// Enables per-check timers.
/// ///
/// It prints a report after match. /// It prints a report after match.
llvm::Optional<Profiling> CheckProfiling; std::optional<Profiling> CheckProfiling;
}; };
MatchFinder(MatchFinderOptions Options = MatchFinderOptions()); MatchFinder(MatchFinderOptions Options = MatchFinderOptions());

View File

@ -318,10 +318,10 @@ AST_POLYMORPHIC_MATCHER_P(isExpandedFromMacro,
// Verifies that the statement' beginning and ending are both expanded from // Verifies that the statement' beginning and ending are both expanded from
// the same instance of the given macro. // the same instance of the given macro.
auto& Context = Finder->getASTContext(); auto& Context = Finder->getASTContext();
llvm::Optional<SourceLocation> B = std::optional<SourceLocation> B =
internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context); internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context);
if (!B) return false; if (!B) return false;
llvm::Optional<SourceLocation> E = std::optional<SourceLocation> E =
internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context); internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context);
if (!E) return false; if (!E) return false;
return *B == *E; return *B == *E;
@ -5629,7 +5629,7 @@ AST_POLYMORPHIC_MATCHER_P(
AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr, AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
CXXRewrittenBinaryOperator, UnaryOperator), CXXRewrittenBinaryOperator, UnaryOperator),
std::string, Name) { std::string, Name) {
if (Optional<StringRef> OpName = internal::getOpName(Node)) if (std::optional<StringRef> OpName = internal::getOpName(Node))
return *OpName == Name; return *OpName == Name;
return false; return false;
} }

View File

@ -483,8 +483,8 @@ public:
/// Bind the specified \p ID to the matcher. /// Bind the specified \p ID to the matcher.
/// \return A new matcher with the \p ID bound to it if this matcher supports /// \return A new matcher with the \p ID bound to it if this matcher supports
/// binding. Otherwise, returns an empty \c Optional<>. /// binding. Otherwise, returns an empty \c std::optional<>.
llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const; std::optional<DynTypedMatcher> tryBind(StringRef ID) const;
/// Returns a unique \p ID for the matcher. /// Returns a unique \p ID for the matcher.
/// ///
@ -1974,13 +1974,13 @@ struct GetBodyMatcher<
}; };
template <typename NodeType> template <typename NodeType>
inline Optional<BinaryOperatorKind> inline std::optional<BinaryOperatorKind>
equivalentBinaryOperator(const NodeType &Node) { equivalentBinaryOperator(const NodeType &Node) {
return Node.getOpcode(); return Node.getOpcode();
} }
template <> template <>
inline Optional<BinaryOperatorKind> inline std::optional<BinaryOperatorKind>
equivalentBinaryOperator<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) { equivalentBinaryOperator<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) {
if (Node.getNumArgs() != 2) if (Node.getNumArgs() != 2)
return std::nullopt; return std::nullopt;
@ -2055,13 +2055,13 @@ equivalentBinaryOperator<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) {
} }
template <typename NodeType> template <typename NodeType>
inline Optional<UnaryOperatorKind> inline std::optional<UnaryOperatorKind>
equivalentUnaryOperator(const NodeType &Node) { equivalentUnaryOperator(const NodeType &Node) {
return Node.getOpcode(); return Node.getOpcode();
} }
template <> template <>
inline Optional<UnaryOperatorKind> inline std::optional<UnaryOperatorKind>
equivalentUnaryOperator<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) { equivalentUnaryOperator<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) {
if (Node.getNumArgs() != 1 && Node.getOperator() != OO_PlusPlus && if (Node.getNumArgs() != 1 && Node.getOperator() != OO_PlusPlus &&
Node.getOperator() != OO_MinusMinus) Node.getOperator() != OO_MinusMinus)
@ -2173,20 +2173,20 @@ CompoundStmtMatcher<StmtExpr>::get(const StmtExpr &Node) {
/// location (in the chain of expansions) at which \p MacroName was /// location (in the chain of expansions) at which \p MacroName was
/// expanded. Since the macro may have been expanded inside a series of /// expanded. Since the macro may have been expanded inside a series of
/// expansions, that location may itself be a MacroID. /// expansions, that location may itself be a MacroID.
llvm::Optional<SourceLocation> std::optional<SourceLocation> getExpansionLocOfMacro(StringRef MacroName,
getExpansionLocOfMacro(StringRef MacroName, SourceLocation Loc, SourceLocation Loc,
const ASTContext &Context); const ASTContext &Context);
inline Optional<StringRef> getOpName(const UnaryOperator &Node) { inline std::optional<StringRef> getOpName(const UnaryOperator &Node) {
return Node.getOpcodeStr(Node.getOpcode()); return Node.getOpcodeStr(Node.getOpcode());
} }
inline Optional<StringRef> getOpName(const BinaryOperator &Node) { inline std::optional<StringRef> getOpName(const BinaryOperator &Node) {
return Node.getOpcodeStr(); return Node.getOpcodeStr();
} }
inline StringRef getOpName(const CXXRewrittenBinaryOperator &Node) { inline StringRef getOpName(const CXXRewrittenBinaryOperator &Node) {
return Node.getOpcodeStr(); return Node.getOpcodeStr();
} }
inline Optional<StringRef> getOpName(const CXXOperatorCallExpr &Node) { inline std::optional<StringRef> getOpName(const CXXOperatorCallExpr &Node) {
auto optBinaryOpcode = equivalentBinaryOperator(Node); auto optBinaryOpcode = equivalentBinaryOperator(Node);
if (!optBinaryOpcode) { if (!optBinaryOpcode) {
auto optUnaryOpcode = equivalentUnaryOperator(Node); auto optUnaryOpcode = equivalentUnaryOperator(Node);
@ -2217,21 +2217,21 @@ public:
: SingleNodeMatcherInterface<T>(), Names(std::move(Names)) {} : SingleNodeMatcherInterface<T>(), Names(std::move(Names)) {}
bool matchesNode(const T &Node) const override { bool matchesNode(const T &Node) const override {
Optional<StringRef> OptOpName = getOpName(Node); std::optional<StringRef> OptOpName = getOpName(Node);
return OptOpName && llvm::is_contained(Names, *OptOpName); return OptOpName && llvm::is_contained(Names, *OptOpName);
} }
private: private:
static Optional<StringRef> getOpName(const UnaryOperator &Node) { static std::optional<StringRef> getOpName(const UnaryOperator &Node) {
return Node.getOpcodeStr(Node.getOpcode()); return Node.getOpcodeStr(Node.getOpcode());
} }
static Optional<StringRef> getOpName(const BinaryOperator &Node) { static std::optional<StringRef> getOpName(const BinaryOperator &Node) {
return Node.getOpcodeStr(); return Node.getOpcodeStr();
} }
static StringRef getOpName(const CXXRewrittenBinaryOperator &Node) { static StringRef getOpName(const CXXRewrittenBinaryOperator &Node) {
return Node.getOpcodeStr(); return Node.getOpcodeStr();
} }
static Optional<StringRef> getOpName(const CXXOperatorCallExpr &Node) { static std::optional<StringRef> getOpName(const CXXOperatorCallExpr &Node) {
auto optBinaryOpcode = equivalentBinaryOperator(Node); auto optBinaryOpcode = equivalentBinaryOperator(Node);
if (!optBinaryOpcode) { if (!optBinaryOpcode) {
auto optUnaryOpcode = equivalentUnaryOperator(Node); auto optUnaryOpcode = equivalentUnaryOperator(Node);

View File

@ -96,9 +96,9 @@ public:
/// ///
/// \param MatcherName The matcher name found by the parser. /// \param MatcherName The matcher name found by the parser.
/// ///
/// \return The matcher constructor, or Optional<MatcherCtor>() if not /// \return The matcher constructor, or std::optional<MatcherCtor>() if not
/// found. /// found.
virtual llvm::Optional<MatcherCtor> virtual std::optional<MatcherCtor>
lookupMatcherCtor(StringRef MatcherName) = 0; lookupMatcherCtor(StringRef MatcherName) = 0;
virtual bool isBuilderMatcher(MatcherCtor) const = 0; virtual bool isBuilderMatcher(MatcherCtor) const = 0;
@ -139,7 +139,7 @@ public:
public: public:
~RegistrySema() override; ~RegistrySema() override;
llvm::Optional<MatcherCtor> std::optional<MatcherCtor>
lookupMatcherCtor(StringRef MatcherName) override; lookupMatcherCtor(StringRef MatcherName) override;
VariantMatcher actOnMatcherExpression(MatcherCtor Ctor, VariantMatcher actOnMatcherExpression(MatcherCtor Ctor,
@ -181,14 +181,14 @@ public:
/// Optional if an error occurred. In that case, \c Error will contain a /// Optional if an error occurred. In that case, \c Error will contain a
/// description of the error. /// description of the error.
/// The caller takes ownership of the DynTypedMatcher object returned. /// The caller takes ownership of the DynTypedMatcher object returned.
static llvm::Optional<DynTypedMatcher> static std::optional<DynTypedMatcher>
parseMatcherExpression(StringRef &MatcherCode, Sema *S, parseMatcherExpression(StringRef &MatcherCode, Sema *S,
const NamedValueMap *NamedValues, Diagnostics *Error); const NamedValueMap *NamedValues, Diagnostics *Error);
static llvm::Optional<DynTypedMatcher> static std::optional<DynTypedMatcher>
parseMatcherExpression(StringRef &MatcherCode, Sema *S, Diagnostics *Error) { parseMatcherExpression(StringRef &MatcherCode, Sema *S, Diagnostics *Error) {
return parseMatcherExpression(MatcherCode, S, nullptr, Error); return parseMatcherExpression(MatcherCode, S, nullptr, Error);
} }
static llvm::Optional<DynTypedMatcher> static std::optional<DynTypedMatcher>
parseMatcherExpression(StringRef &MatcherCode, Diagnostics *Error) { parseMatcherExpression(StringRef &MatcherCode, Diagnostics *Error) {
return parseMatcherExpression(MatcherCode, nullptr, Error); return parseMatcherExpression(MatcherCode, nullptr, Error);
} }
@ -255,7 +255,7 @@ private:
const TokenInfo &OpenToken, VariantValue *Value); const TokenInfo &OpenToken, VariantValue *Value);
bool parseMatcherExpressionImpl(const TokenInfo &NameToken, bool parseMatcherExpressionImpl(const TokenInfo &NameToken,
const TokenInfo &OpenToken, const TokenInfo &OpenToken,
llvm::Optional<MatcherCtor> Ctor, std::optional<MatcherCtor> Ctor,
VariantValue *Value); VariantValue *Value);
bool parseIdentifierPrefixImpl(VariantValue *Value); bool parseIdentifierPrefixImpl(VariantValue *Value);

View File

@ -95,8 +95,8 @@ public:
/// Look up a matcher in the registry by name, /// Look up a matcher in the registry by name,
/// ///
/// \return An opaque value which may be used to refer to the matcher /// \return An opaque value which may be used to refer to the matcher
/// constructor, or Optional<MatcherCtor>() if not found. /// constructor, or std::optional<MatcherCtor>() if not found.
static llvm::Optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName); static std::optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName);
/// Compute the list of completion types for \p Context. /// Compute the list of completion types for \p Context.
/// ///

View File

@ -119,7 +119,7 @@ class VariantMatcher {
/// Constructs a variadic typed matcher from \p InnerMatchers. /// Constructs a variadic typed matcher from \p InnerMatchers.
/// Will try to convert each inner matcher to the destination type and /// Will try to convert each inner matcher to the destination type and
/// return std::nullopt if it fails to do so. /// return std::nullopt if it fails to do so.
llvm::Optional<DynTypedMatcher> std::optional<DynTypedMatcher>
constructVariadicOperator(DynTypedMatcher::VariadicOperator Op, constructVariadicOperator(DynTypedMatcher::VariadicOperator Op,
ArrayRef<VariantMatcher> InnerMatchers) const; ArrayRef<VariantMatcher> InnerMatchers) const;
@ -133,9 +133,9 @@ class VariantMatcher {
class Payload { class Payload {
public: public:
virtual ~Payload(); virtual ~Payload();
virtual llvm::Optional<DynTypedMatcher> getSingleMatcher() const = 0; virtual std::optional<DynTypedMatcher> getSingleMatcher() const = 0;
virtual std::string getTypeAsString() const = 0; virtual std::string getTypeAsString() const = 0;
virtual llvm::Optional<DynTypedMatcher> virtual std::optional<DynTypedMatcher>
getTypedMatcher(const MatcherOps &Ops) const = 0; getTypedMatcher(const MatcherOps &Ops) const = 0;
virtual bool isConvertibleTo(ASTNodeKind Kind, virtual bool isConvertibleTo(ASTNodeKind Kind,
unsigned *Specificity) const = 0; unsigned *Specificity) const = 0;
@ -172,7 +172,7 @@ public:
/// \returns the matcher, if there is only one matcher. An empty Optional, if /// \returns the matcher, if there is only one matcher. An empty Optional, if
/// the underlying matcher is a polymorphic matcher with more than one /// the underlying matcher is a polymorphic matcher with more than one
/// representation. /// representation.
llvm::Optional<DynTypedMatcher> getSingleMatcher() const; std::optional<DynTypedMatcher> getSingleMatcher() const;
/// Determines if the contained matcher can be converted to /// Determines if the contained matcher can be converted to
/// \c Matcher<T>. /// \c Matcher<T>.

View File

@ -958,7 +958,7 @@ public:
private: private:
SExpr* Rec; SExpr* Rec;
mutable llvm::Optional<std::string> SlotName; mutable std::optional<std::string> SlotName;
const ValueDecl *Cvdecl; const ValueDecl *Cvdecl;
}; };

View File

@ -110,7 +110,7 @@ public:
/// If @c E is a generic call (to ObjC method /function/block/etc), /// If @c E is a generic call (to ObjC method /function/block/etc),
/// return a constructed @c AnyCall object. Return std::nullopt otherwise. /// return a constructed @c AnyCall object. Return std::nullopt otherwise.
static Optional<AnyCall> forExpr(const Expr *E) { static std::optional<AnyCall> forExpr(const Expr *E) {
if (const auto *ME = dyn_cast<ObjCMessageExpr>(E)) { if (const auto *ME = dyn_cast<ObjCMessageExpr>(E)) {
return AnyCall(ME); return AnyCall(ME);
} else if (const auto *CE = dyn_cast<CallExpr>(E)) { } else if (const auto *CE = dyn_cast<CallExpr>(E)) {
@ -131,7 +131,7 @@ public:
/// If @c D is a callable (Objective-C method or a function), return /// If @c D is a callable (Objective-C method or a function), return
/// a constructed @c AnyCall object. Return std::nullopt otherwise. /// a constructed @c AnyCall object. Return std::nullopt otherwise.
// FIXME: block support. // FIXME: block support.
static Optional<AnyCall> forDecl(const Decl *D) { static std::optional<AnyCall> forDecl(const Decl *D) {
if (const auto *FD = dyn_cast<FunctionDecl>(D)) { if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
return AnyCall(FD); return AnyCall(FD);
} else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {

View File

@ -42,7 +42,7 @@ public:
BodyFarm(const BodyFarm &other) = delete; BodyFarm(const BodyFarm &other) = delete;
private: private:
typedef llvm::DenseMap<const Decl *, Optional<Stmt *>> BodyMap; typedef llvm::DenseMap<const Decl *, std::optional<Stmt *>> BodyMap;
ASTContext &C; ASTContext &C;
BodyMap Bodies; BodyMap Bodies;

View File

@ -105,8 +105,7 @@ public:
/// Convert to the specified CFGElement type, returning std::nullopt if this /// Convert to the specified CFGElement type, returning std::nullopt if this
/// CFGElement is not of the desired type. /// CFGElement is not of the desired type.
template<typename T> template <typename T> std::optional<T> getAs() const {
Optional<T> getAs() const {
if (!T::isKind(*this)) if (!T::isKind(*this))
return std::nullopt; return std::nullopt;
T t; T t;
@ -1400,7 +1399,7 @@ public:
for (const_iterator I = begin(), E = end(); I != E; ++I) for (const_iterator I = begin(), E = end(); I != E; ++I)
for (CFGBlock::const_iterator BI = (*I)->begin(), BE = (*I)->end(); for (CFGBlock::const_iterator BI = (*I)->begin(), BE = (*I)->end();
BI != BE; ++BI) { BI != BE; ++BI) {
if (Optional<CFGStmt> stmt = BI->getAs<CFGStmt>()) if (std::optional<CFGStmt> stmt = BI->getAs<CFGStmt>())
O(const_cast<Stmt *>(stmt->getStmt())); O(const_cast<Stmt *>(stmt->getStmt()));
} }
} }

View File

@ -190,7 +190,7 @@ template <typename LatticeT> struct DataflowAnalysisState {
/// program point. /// program point.
template <typename AnalysisT> template <typename AnalysisT>
llvm::Expected<std::vector< llvm::Expected<std::vector<
llvm::Optional<DataflowAnalysisState<typename AnalysisT::Lattice>>>> std::optional<DataflowAnalysisState<typename AnalysisT::Lattice>>>>
runDataflowAnalysis( runDataflowAnalysis(
const ControlFlowContext &CFCtx, AnalysisT &Analysis, const ControlFlowContext &CFCtx, AnalysisT &Analysis,
const Environment &InitEnv, const Environment &InitEnv,
@ -216,8 +216,7 @@ runDataflowAnalysis(
if (!TypeErasedBlockStates) if (!TypeErasedBlockStates)
return TypeErasedBlockStates.takeError(); return TypeErasedBlockStates.takeError();
std::vector< std::vector<std::optional<DataflowAnalysisState<typename AnalysisT::Lattice>>>
llvm::Optional<DataflowAnalysisState<typename AnalysisT::Lattice>>>
BlockStates; BlockStates;
BlockStates.reserve(TypeErasedBlockStates->size()); BlockStates.reserve(TypeErasedBlockStates->size());

View File

@ -66,7 +66,7 @@ public:
/// unit, or empty to disable context-sensitive analysis. Note that this is /// unit, or empty to disable context-sensitive analysis. Note that this is
/// fundamentally limited: some constructs, such as recursion, are /// fundamentally limited: some constructs, such as recursion, are
/// explicitly unsupported. /// explicitly unsupported.
llvm::Optional<ContextSensitiveOptions> ContextSensitiveOpts; std::optional<ContextSensitiveOptions> ContextSensitiveOpts;
}; };
/// Constructs a dataflow analysis context. /// Constructs a dataflow analysis context.

View File

@ -65,7 +65,7 @@ public:
/// Returns a truth assignment to boolean values that satisfies the queried /// Returns a truth assignment to boolean values that satisfies the queried
/// boolean formula if available. Otherwise, an empty optional is returned. /// boolean formula if available. Otherwise, an empty optional is returned.
llvm::Optional<llvm::DenseMap<AtomicBoolValue *, Assignment>> std::optional<llvm::DenseMap<AtomicBoolValue *, Assignment>>
getSolution() const { getSolution() const {
return Solution; return Solution;
} }
@ -73,11 +73,11 @@ public:
private: private:
Result( Result(
enum Status SATCheckStatus, enum Status SATCheckStatus,
llvm::Optional<llvm::DenseMap<AtomicBoolValue *, Assignment>> Solution) std::optional<llvm::DenseMap<AtomicBoolValue *, Assignment>> Solution)
: SATCheckStatus(SATCheckStatus), Solution(std::move(Solution)) {} : SATCheckStatus(SATCheckStatus), Solution(std::move(Solution)) {}
Status SATCheckStatus; Status SATCheckStatus;
llvm::Optional<llvm::DenseMap<AtomicBoolValue *, Assignment>> Solution; std::optional<llvm::DenseMap<AtomicBoolValue *, Assignment>> Solution;
}; };
virtual ~Solver() = default; virtual ~Solver() = default;

View File

@ -140,7 +140,7 @@ struct TypeErasedDataflowAnalysisState {
/// `std::nullopt` represent basic blocks that are not evaluated yet. /// `std::nullopt` represent basic blocks that are not evaluated yet.
TypeErasedDataflowAnalysisState transferBlock( TypeErasedDataflowAnalysisState transferBlock(
const ControlFlowContext &CFCtx, const ControlFlowContext &CFCtx,
llvm::ArrayRef<llvm::Optional<TypeErasedDataflowAnalysisState>> BlockStates, llvm::ArrayRef<std::optional<TypeErasedDataflowAnalysisState>> BlockStates,
const CFGBlock &Block, const Environment &InitEnv, const CFGBlock &Block, const Environment &InitEnv,
TypeErasedDataflowAnalysis &Analysis, TypeErasedDataflowAnalysis &Analysis,
std::function<void(const CFGElement &, std::function<void(const CFGElement &,
@ -153,7 +153,7 @@ TypeErasedDataflowAnalysisState transferBlock(
/// dataflow analysis cannot be performed successfully. Otherwise, calls /// dataflow analysis cannot be performed successfully. Otherwise, calls
/// `PostVisitCFG` on each CFG element with the final analysis results at that /// `PostVisitCFG` on each CFG element with the final analysis results at that
/// program point. /// program point.
llvm::Expected<std::vector<llvm::Optional<TypeErasedDataflowAnalysisState>>> llvm::Expected<std::vector<std::optional<TypeErasedDataflowAnalysisState>>>
runTypeErasedDataflowAnalysis( runTypeErasedDataflowAnalysis(
const ControlFlowContext &CFCtx, TypeErasedDataflowAnalysis &Analysis, const ControlFlowContext &CFCtx, TypeErasedDataflowAnalysis &Analysis,
const Environment &InitEnv, const Environment &InitEnv,

View File

@ -87,13 +87,15 @@ public:
/// \return The textual representation of the token sequence which was /// \return The textual representation of the token sequence which was
/// substituted in place of the macro after the preprocessing. /// substituted in place of the macro after the preprocessing.
/// If no macro was expanded at that location, returns std::nullopt. /// If no macro was expanded at that location, returns std::nullopt.
Optional<StringRef> getExpandedText(SourceLocation MacroExpansionLoc) const; std::optional<StringRef>
getExpandedText(SourceLocation MacroExpansionLoc) const;
/// \param MacroExpansionLoc Must be the expansion location of a macro. /// \param MacroExpansionLoc Must be the expansion location of a macro.
/// \return The text from the original source code which were substituted by /// \return The text from the original source code which were substituted by
/// the macro expansion chain from the given location. /// the macro expansion chain from the given location.
/// If no macro was expanded at that location, returns std::nullopt. /// If no macro was expanded at that location, returns std::nullopt.
Optional<StringRef> getOriginalText(SourceLocation MacroExpansionLoc) const; std::optional<StringRef>
getOriginalText(SourceLocation MacroExpansionLoc) const;
LLVM_DUMP_METHOD void dumpExpansionRangesToStream(raw_ostream &OS) const; LLVM_DUMP_METHOD void dumpExpansionRangesToStream(raw_ostream &OS) const;
LLVM_DUMP_METHOD void dumpExpandedTextsToStream(raw_ostream &OS) const; LLVM_DUMP_METHOD void dumpExpandedTextsToStream(raw_ostream &OS) const;

View File

@ -533,7 +533,7 @@ public:
}; };
class PathDiagnosticEventPiece : public PathDiagnosticSpotPiece { class PathDiagnosticEventPiece : public PathDiagnosticSpotPiece {
Optional<bool> IsPrunable; std::optional<bool> IsPrunable;
public: public:
PathDiagnosticEventPiece(const PathDiagnosticLocation &pos, PathDiagnosticEventPiece(const PathDiagnosticLocation &pos,

View File

@ -147,8 +147,7 @@ public:
/// Convert to the specified ProgramPoint type, returning std::nullopt if this /// Convert to the specified ProgramPoint type, returning std::nullopt if this
/// ProgramPoint is not of the desired type. /// ProgramPoint is not of the desired type.
template<typename T> template <typename T> std::optional<T> getAs() const {
Optional<T> getAs() const {
if (!T::isKind(*this)) if (!T::isKind(*this))
return std::nullopt; return std::nullopt;
T t; T t;
@ -234,9 +233,9 @@ public:
return reinterpret_cast<const CFGBlock*>(getData1()); return reinterpret_cast<const CFGBlock*>(getData1());
} }
Optional<CFGElement> getFirstElement() const { std::optional<CFGElement> getFirstElement() const {
const CFGBlock *B = getBlock(); const CFGBlock *B = getBlock();
return B->empty() ? Optional<CFGElement>() : B->front(); return B->empty() ? std::optional<CFGElement>() : B->front();
} }
private: private:

View File

@ -649,8 +649,9 @@ public:
IdentityOrZero IdentityOrZero
}; };
Optional<BehaviorSummary> canEval(const CallExpr *CE, const FunctionDecl *FD, std::optional<BehaviorSummary>
bool &hasTrustedImplementationAnnotation); canEval(const CallExpr *CE, const FunctionDecl *FD,
bool &hasTrustedImplementationAnnotation);
/// \return Whether the type corresponds to a known smart pointer /// \return Whether the type corresponds to a known smart pointer
/// implementation (that is, everything about it is inlineable). /// implementation (that is, everything about it is inlineable).
@ -687,8 +688,8 @@ private:
Selector S, QualType RetTy); Selector S, QualType RetTy);
/// Determine if there is a special return effect for this function or method. /// Determine if there is a special return effect for this function or method.
Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy, std::optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
const Decl *D); const Decl *D);
void updateSummaryFromAnnotations(const RetainSummary *&Summ, void updateSummaryFromAnnotations(const RetainSummary *&Summ,
const ObjCMethodDecl *MD); const ObjCMethodDecl *MD);
@ -724,10 +725,10 @@ private:
/// std::nullopt, if none of the specified attributes are present. /// std::nullopt, if none of the specified attributes are present.
/// Crashes if passed an attribute which is not explicitly handled. /// Crashes if passed an attribute which is not explicitly handled.
template <class T> template <class T>
Optional<ObjKind> hasAnyEnabledAttrOf(const Decl *D, QualType QT); std::optional<ObjKind> hasAnyEnabledAttrOf(const Decl *D, QualType QT);
template <class T1, class T2, class... Others> template <class T1, class T2, class... Others>
Optional<ObjKind> hasAnyEnabledAttrOf(const Decl *D, QualType QT); std::optional<ObjKind> hasAnyEnabledAttrOf(const Decl *D, QualType QT);
friend class RetainSummaryTemplate; friend class RetainSummaryTemplate;
}; };

View File

@ -3786,11 +3786,11 @@ def OMPDeclareTargetDecl : InheritableAttr {
]; ];
let AdditionalMembers = [{ let AdditionalMembers = [{
void printPrettyPragma(raw_ostream &OS, const PrintingPolicy &Policy) const; void printPrettyPragma(raw_ostream &OS, const PrintingPolicy &Policy) const;
static llvm::Optional<MapTypeTy> static std::optional<MapTypeTy>
isDeclareTargetDeclaration(const ValueDecl *VD); isDeclareTargetDeclaration(const ValueDecl *VD);
static llvm::Optional<OMPDeclareTargetDeclAttr*> getActiveAttr(const ValueDecl *VD); static std::optional<OMPDeclareTargetDeclAttr*> getActiveAttr(const ValueDecl *VD);
static llvm::Optional<DevTypeTy> getDeviceType(const ValueDecl *VD); static std::optional<DevTypeTy> getDeviceType(const ValueDecl *VD);
static llvm::Optional<SourceLocation> getLocation(const ValueDecl *VD); static std::optional<SourceLocation> getLocation(const ValueDecl *VD);
}]; }];
} }

View File

@ -45,7 +45,7 @@ public:
constexpr CustomizableOptional(std::in_place_t, ArgTypes &&...Args) constexpr CustomizableOptional(std::in_place_t, ArgTypes &&...Args)
: Storage(std::in_place, std::forward<ArgTypes>(Args)...) {} : Storage(std::in_place, std::forward<ArgTypes>(Args)...) {}
// Allow conversion from Optional<T>. // Allow conversion from std::optional<T>.
constexpr CustomizableOptional(const std::optional<T> &y) constexpr CustomizableOptional(const std::optional<T> &y)
: CustomizableOptional(y ? *y : CustomizableOptional()) {} : CustomizableOptional(y ? *y : CustomizableOptional()) {}
constexpr CustomizableOptional(std::optional<T> &&y) constexpr CustomizableOptional(std::optional<T> &&y)
@ -98,7 +98,7 @@ public:
return has_value() ? std::move(operator*()) : std::forward<U>(alt); return has_value() ? std::move(operator*()) : std::forward<U>(alt);
} }
// Allow conversion to Optional<T>. // Allow conversion to std::optional<T>.
explicit operator std::optional<T> &() const & { explicit operator std::optional<T> &() const & {
return *this ? **this : std::optional<T>(); return *this ? **this : std::optional<T>();
} }

View File

@ -105,7 +105,7 @@ public:
map(const VersionTuple &Key, const VersionTuple &MinimumValue, map(const VersionTuple &Key, const VersionTuple &MinimumValue,
std::optional<VersionTuple> MaximumValue) const; std::optional<VersionTuple> MaximumValue) const;
static Optional<RelatedTargetVersionMapping> static std::optional<RelatedTargetVersionMapping>
parseJSON(const llvm::json::Object &Obj, parseJSON(const llvm::json::Object &Obj,
VersionTuple MaximumDeploymentTarget); VersionTuple MaximumDeploymentTarget);
@ -117,12 +117,13 @@ public:
llvm::DenseMap<VersionTuple, VersionTuple> Mapping; llvm::DenseMap<VersionTuple, VersionTuple> Mapping;
}; };
DarwinSDKInfo(VersionTuple Version, VersionTuple MaximumDeploymentTarget, DarwinSDKInfo(
llvm::DenseMap<OSEnvPair::StorageType, VersionTuple Version, VersionTuple MaximumDeploymentTarget,
Optional<RelatedTargetVersionMapping>> llvm::DenseMap<OSEnvPair::StorageType,
VersionMappings = std::optional<RelatedTargetVersionMapping>>
llvm::DenseMap<OSEnvPair::StorageType, VersionMappings =
Optional<RelatedTargetVersionMapping>>()) llvm::DenseMap<OSEnvPair::StorageType,
std::optional<RelatedTargetVersionMapping>>())
: Version(Version), MaximumDeploymentTarget(MaximumDeploymentTarget), : Version(Version), MaximumDeploymentTarget(MaximumDeploymentTarget),
VersionMappings(std::move(VersionMappings)) {} VersionMappings(std::move(VersionMappings)) {}
@ -155,7 +156,8 @@ private:
// Need to wrap the value in an optional here as the value has to be default // Need to wrap the value in an optional here as the value has to be default
// constructible, and std::unique_ptr doesn't like DarwinSDKInfo being // constructible, and std::unique_ptr doesn't like DarwinSDKInfo being
// Optional as Optional is trying to copy it in emplace. // Optional as Optional is trying to copy it in emplace.
llvm::DenseMap<OSEnvPair::StorageType, Optional<RelatedTargetVersionMapping>> llvm::DenseMap<OSEnvPair::StorageType,
std::optional<RelatedTargetVersionMapping>>
VersionMappings; VersionMappings;
}; };

View File

@ -1512,7 +1512,7 @@ inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
inline const StreamingDiagnostic & inline const StreamingDiagnostic &
operator<<(const StreamingDiagnostic &DB, operator<<(const StreamingDiagnostic &DB,
const llvm::Optional<SourceRange> &Opt) { const std::optional<SourceRange> &Opt) {
if (Opt) if (Opt)
DB << *Opt; DB << *Opt;
return DB; return DB;
@ -1520,15 +1520,14 @@ operator<<(const StreamingDiagnostic &DB,
inline const StreamingDiagnostic & inline const StreamingDiagnostic &
operator<<(const StreamingDiagnostic &DB, operator<<(const StreamingDiagnostic &DB,
const llvm::Optional<CharSourceRange> &Opt) { const std::optional<CharSourceRange> &Opt) {
if (Opt) if (Opt)
DB << *Opt; DB << *Opt;
return DB; return DB;
} }
inline const StreamingDiagnostic & inline const StreamingDiagnostic &
operator<<(const StreamingDiagnostic &DB, operator<<(const StreamingDiagnostic &DB, const std::optional<FixItHint> &Opt) {
const llvm::Optional<FixItHint> &Opt) {
if (Opt) if (Opt)
DB << *Opt; DB << *Opt;
return DB; return DB;

View File

@ -37,8 +37,8 @@ public:
/// Extracts and returns the diagnostic payload from the given \c Error if /// Extracts and returns the diagnostic payload from the given \c Error if
/// the error is a \c DiagnosticError. Returns none if the given error is not /// the error is a \c DiagnosticError. Returns none if the given error is not
/// a \c DiagnosticError. /// a \c DiagnosticError.
static Optional<PartialDiagnosticAt> take(llvm::Error &Err) { static std::optional<PartialDiagnosticAt> take(llvm::Error &Err) {
Optional<PartialDiagnosticAt> Result; std::optional<PartialDiagnosticAt> Result;
Err = llvm::handleErrors(std::move(Err), [&](DiagnosticError &E) { Err = llvm::handleErrors(std::move(Err), [&](DiagnosticError &E) {
Result = std::move(E.getDiagnostic()); Result = std::move(E.getDiagnostic());
}); });

View File

@ -238,10 +238,10 @@ public:
/// Given a group ID, returns the flag that toggles the group. /// Given a group ID, returns the flag that toggles the group.
/// For example, for "deprecated-declarations", returns /// For example, for "deprecated-declarations", returns
/// Group::DeprecatedDeclarations. /// Group::DeprecatedDeclarations.
static llvm::Optional<diag::Group> getGroupForWarningOption(StringRef); static std::optional<diag::Group> getGroupForWarningOption(StringRef);
/// Return the lowest-level group that contains the specified diagnostic. /// Return the lowest-level group that contains the specified diagnostic.
static llvm::Optional<diag::Group> getGroupForDiag(unsigned DiagID); static std::optional<diag::Group> getGroupForDiag(unsigned DiagID);
/// Return the lowest-level warning option that enables the specified /// Return the lowest-level warning option that enables the specified
/// diagnostic. /// diagnostic.

View File

@ -55,7 +55,7 @@ public:
protected: protected:
// FIXME: The pointer here is a non-owning/optional reference to the // FIXME: The pointer here is a non-owning/optional reference to the
// unique_ptr. Optional<unique_ptr<vfs::File>&> might be nicer, but // unique_ptr. std::optional<unique_ptr<vfs::File>&> might be nicer, but
// Optional needs some work to support references so this isn't possible yet. // Optional needs some work to support references so this isn't possible yet.
virtual std::error_code getStat(StringRef Path, llvm::vfs::Status &Status, virtual std::error_code getStat(StringRef Path, llvm::vfs::Status &Status,
bool isFile, bool isFile,

View File

@ -467,7 +467,7 @@ public:
/// C++ ABI to compile with, if specified by the frontend through -fc++-abi=. /// C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
/// This overrides the default ABI used by the target. /// This overrides the default ABI used by the target.
llvm::Optional<TargetCXXABI::Kind> CXXABI; std::optional<TargetCXXABI::Kind> CXXABI;
/// Indicates whether the front-end is explicitly told that the /// Indicates whether the front-end is explicitly told that the
/// input is a header file (i.e. -x c-header). /// input is a header file (i.e. -x c-header).

View File

@ -241,8 +241,8 @@ public:
std::string FileName; std::string FileName;
bool IsUmbrella = false; bool IsUmbrella = false;
bool HasBuiltinHeader = false; bool HasBuiltinHeader = false;
Optional<off_t> Size; std::optional<off_t> Size;
Optional<time_t> ModTime; std::optional<time_t> ModTime;
}; };
/// Headers that are mentioned in the module map file but that we have not /// Headers that are mentioned in the module map file but that we have not

View File

@ -42,8 +42,8 @@ private:
std::unique_ptr<ProfileSpecialCaseList> SCL; std::unique_ptr<ProfileSpecialCaseList> SCL;
const bool Empty; const bool Empty;
SourceManager &SM; SourceManager &SM;
llvm::Optional<ExclusionType> inSection(StringRef Section, StringRef Prefix, std::optional<ExclusionType> inSection(StringRef Section, StringRef Prefix,
StringRef Query) const; StringRef Query) const;
public: public:
ProfileList(ArrayRef<std::string> Paths, SourceManager &SM); ProfileList(ArrayRef<std::string> Paths, SourceManager &SM);
@ -52,13 +52,13 @@ public:
bool isEmpty() const { return Empty; } bool isEmpty() const { return Empty; }
ExclusionType getDefault(CodeGenOptions::ProfileInstrKind Kind) const; ExclusionType getDefault(CodeGenOptions::ProfileInstrKind Kind) const;
llvm::Optional<ExclusionType> std::optional<ExclusionType>
isFunctionExcluded(StringRef FunctionName, isFunctionExcluded(StringRef FunctionName,
CodeGenOptions::ProfileInstrKind Kind) const; CodeGenOptions::ProfileInstrKind Kind) const;
llvm::Optional<ExclusionType> std::optional<ExclusionType>
isLocationExcluded(SourceLocation Loc, isLocationExcluded(SourceLocation Loc,
CodeGenOptions::ProfileInstrKind Kind) const; CodeGenOptions::ProfileInstrKind Kind) const;
llvm::Optional<ExclusionType> std::optional<ExclusionType>
isFileExcluded(StringRef FileName, isFileExcluded(StringRef FileName,
CodeGenOptions::ProfileInstrKind Kind) const; CodeGenOptions::ProfileInstrKind Kind) const;
}; };

View File

@ -73,7 +73,7 @@ class SarifArtifactLocation {
private: private:
friend class clang::SarifDocumentWriter; friend class clang::SarifDocumentWriter;
llvm::Optional<uint32_t> Index; std::optional<uint32_t> Index;
std::string URI; std::string URI;
SarifArtifactLocation() = delete; SarifArtifactLocation() = delete;
@ -106,8 +106,8 @@ class SarifArtifact {
private: private:
friend class clang::SarifDocumentWriter; friend class clang::SarifDocumentWriter;
llvm::Optional<uint32_t> Offset; std::optional<uint32_t> Offset;
llvm::Optional<size_t> Length; std::optional<size_t> Length;
std::string MimeType; std::string MimeType;
SarifArtifactLocation Location; SarifArtifactLocation Location;
llvm::SmallVector<std::string, 4> Roles; llvm::SmallVector<std::string, 4> Roles;
@ -325,7 +325,7 @@ class SarifResult {
std::string DiagnosticMessage; std::string DiagnosticMessage;
llvm::SmallVector<CharSourceRange, 8> Locations; llvm::SmallVector<CharSourceRange, 8> Locations;
llvm::SmallVector<ThreadFlow, 8> ThreadFlows; llvm::SmallVector<ThreadFlow, 8> ThreadFlows;
llvm::Optional<SarifResultLevel> LevelOverride; std::optional<SarifResultLevel> LevelOverride;
SarifResult() = delete; SarifResult() = delete;
explicit SarifResult(uint32_t RuleIdx) : RuleIdx(RuleIdx) {} explicit SarifResult(uint32_t RuleIdx) : RuleIdx(RuleIdx) {}

View File

@ -212,7 +212,7 @@ public:
/// ///
/// \param Loc If specified, is the location that invalid file diagnostics /// \param Loc If specified, is the location that invalid file diagnostics
/// will be emitted at. /// will be emitted at.
llvm::Optional<llvm::MemoryBufferRef> std::optional<llvm::MemoryBufferRef>
getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM, getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,
SourceLocation Loc = SourceLocation()) const; SourceLocation Loc = SourceLocation()) const;
@ -235,7 +235,7 @@ public:
llvm::MemoryBuffer::BufferKind getMemoryBufferKind() const; llvm::MemoryBuffer::BufferKind getMemoryBufferKind() const;
/// Return the buffer, only if it has been loaded. /// Return the buffer, only if it has been loaded.
llvm::Optional<llvm::MemoryBufferRef> getBufferIfLoaded() const { std::optional<llvm::MemoryBufferRef> getBufferIfLoaded() const {
if (Buffer) if (Buffer)
return Buffer->getMemBufferRef(); return Buffer->getMemBufferRef();
return std::nullopt; return std::nullopt;
@ -243,7 +243,7 @@ public:
/// Return a StringRef to the source buffer data, only if it has already /// Return a StringRef to the source buffer data, only if it has already
/// been loaded. /// been loaded.
llvm::Optional<StringRef> getBufferDataIfLoaded() const { std::optional<StringRef> getBufferDataIfLoaded() const {
if (Buffer) if (Buffer)
return Buffer->getBuffer(); return Buffer->getBuffer();
return std::nullopt; return std::nullopt;
@ -258,7 +258,7 @@ public:
/// Set the buffer to one that's not owned (or to nullptr). /// Set the buffer to one that's not owned (or to nullptr).
/// ///
/// \pre Buffer cannot already be set. /// \pre Buffer cannot already be set.
void setUnownedBuffer(llvm::Optional<llvm::MemoryBufferRef> B) { void setUnownedBuffer(std::optional<llvm::MemoryBufferRef> B) {
assert(!Buffer && "Expected to be called right after construction"); assert(!Buffer && "Expected to be called right after construction");
if (B) if (B)
setBuffer(llvm::MemoryBuffer::getMemBuffer(*B)); setBuffer(llvm::MemoryBuffer::getMemBuffer(*B));
@ -941,7 +941,7 @@ public:
/// Retrieve the memory buffer associated with the given file. /// Retrieve the memory buffer associated with the given file.
/// ///
/// Returns std::nullopt if the buffer is not valid. /// Returns std::nullopt if the buffer is not valid.
llvm::Optional<llvm::MemoryBufferRef> std::optional<llvm::MemoryBufferRef>
getMemoryBufferForFileOrNone(const FileEntry *File); getMemoryBufferForFileOrNone(const FileEntry *File);
/// Retrieve the memory buffer associated with the given file. /// Retrieve the memory buffer associated with the given file.
@ -1023,7 +1023,7 @@ public:
/// ///
/// If there is an error opening this buffer the first time, return /// If there is an error opening this buffer the first time, return
/// std::nullopt. /// std::nullopt.
llvm::Optional<llvm::MemoryBufferRef> std::optional<llvm::MemoryBufferRef>
getBufferOrNone(FileID FID, SourceLocation Loc = SourceLocation()) const { getBufferOrNone(FileID FID, SourceLocation Loc = SourceLocation()) const {
if (auto *Entry = getSLocEntryForFile(FID)) if (auto *Entry = getSLocEntryForFile(FID))
return Entry->getFile().getContentCache().getBufferOrNone( return Entry->getFile().getContentCache().getBufferOrNone(
@ -1060,7 +1060,7 @@ public:
/// buffer that's not represented by a filename. /// buffer that's not represented by a filename.
/// ///
/// Returns std::nullopt for non-files and built-in files. /// Returns std::nullopt for non-files and built-in files.
Optional<StringRef> getNonBuiltinFilenameForID(FileID FID) const; std::optional<StringRef> getNonBuiltinFilenameForID(FileID FID) const;
/// Returns the FileEntry record for the provided SLocEntry. /// Returns the FileEntry record for the provided SLocEntry.
const FileEntry *getFileEntryForSLocEntry(const SrcMgr::SLocEntry &sloc) const const FileEntry *getFileEntryForSLocEntry(const SrcMgr::SLocEntry &sloc) const
@ -1079,13 +1079,13 @@ public:
/// specified FileID, returning std::nullopt if invalid. /// specified FileID, returning std::nullopt if invalid.
/// ///
/// \param FID The file ID whose contents will be returned. /// \param FID The file ID whose contents will be returned.
llvm::Optional<StringRef> getBufferDataOrNone(FileID FID) const; std::optional<StringRef> getBufferDataOrNone(FileID FID) const;
/// Return a StringRef to the source buffer data for the /// Return a StringRef to the source buffer data for the
/// specified FileID, returning std::nullopt if it's not yet loaded. /// specified FileID, returning std::nullopt if it's not yet loaded.
/// ///
/// \param FID The file ID whose contents will be returned. /// \param FID The file ID whose contents will be returned.
llvm::Optional<StringRef> getBufferDataIfLoaded(FileID FID) const; std::optional<StringRef> getBufferDataIfLoaded(FileID FID) const;
/// Get the number of FileIDs (files and macros) that were created /// Get the number of FileIDs (files and macros) that were created
/// during preprocessing of \p FID, including it. /// during preprocessing of \p FID, including it.
@ -1696,7 +1696,7 @@ public:
// Produce notes describing the current source location address space usage. // Produce notes describing the current source location address space usage.
void noteSLocAddressSpaceUsage(DiagnosticsEngine &Diag, void noteSLocAddressSpaceUsage(DiagnosticsEngine &Diag,
Optional<unsigned> MaxNotes = 32) const; std::optional<unsigned> MaxNotes = 32) const;
/// Get the number of local SLocEntries we have. /// Get the number of local SLocEntries we have.
unsigned local_sloc_entry_size() const { return LocalSLocEntryTable.size(); } unsigned local_sloc_entry_size() const { return LocalSLocEntryTable.size(); }

View File

@ -255,9 +255,9 @@ protected:
unsigned MaxOpenCLWorkGroupSize; unsigned MaxOpenCLWorkGroupSize;
Optional<unsigned> MaxBitIntWidth; std::optional<unsigned> MaxBitIntWidth;
Optional<llvm::Triple> DarwinTargetVariantTriple; std::optional<llvm::Triple> DarwinTargetVariantTriple;
// TargetInfo Constructor. Default initializes all fields. // TargetInfo Constructor. Default initializes all fields.
TargetInfo(const llvm::Triple &T); TargetInfo(const llvm::Triple &T);
@ -953,7 +953,7 @@ public:
virtual ArrayRef<Builtin::Info> getTargetBuiltins() const = 0; virtual ArrayRef<Builtin::Info> getTargetBuiltins() const = 0;
/// Returns target-specific min and max values VScale_Range. /// Returns target-specific min and max values VScale_Range.
virtual Optional<std::pair<unsigned, unsigned>> virtual std::optional<std::pair<unsigned, unsigned>>
getVScaleRange(const LangOptions &LangOpts) const { getVScaleRange(const LangOptions &LangOpts) const {
return std::nullopt; return std::nullopt;
} }
@ -1179,7 +1179,7 @@ public:
/// Replace some escaped characters with another string based on /// Replace some escaped characters with another string based on
/// target-specific rules /// target-specific rules
virtual llvm::Optional<std::string> handleAsmEscapedChar(char C) const { virtual std::optional<std::string> handleAsmEscapedChar(char C) const {
return std::nullopt; return std::nullopt;
} }
@ -1198,7 +1198,7 @@ public:
} }
/// Returns the target ID if supported. /// Returns the target ID if supported.
virtual llvm::Optional<std::string> getTargetID() const { virtual std::optional<std::string> getTargetID() const {
return std::nullopt; return std::nullopt;
} }
@ -1448,7 +1448,7 @@ public:
// Get the cache line size of a given cpu. This method switches over // Get the cache line size of a given cpu. This method switches over
// the given cpu and returns "std::nullopt" if the CPU is not found. // the given cpu and returns "std::nullopt" if the CPU is not found.
virtual Optional<unsigned> getCPUCacheLineSize() const { virtual std::optional<unsigned> getCPUCacheLineSize() const {
return std::nullopt; return std::nullopt;
} }
@ -1525,7 +1525,7 @@ public:
/// for constant global memory. It must be possible to convert pointers into /// for constant global memory. It must be possible to convert pointers into
/// this address space to LangAS::Default. If no such address space exists, /// this address space to LangAS::Default. If no such address space exists,
/// this may return std::nullopt, and such optimizations will be disabled. /// this may return std::nullopt, and such optimizations will be disabled.
virtual llvm::Optional<LangAS> getConstantAddressSpace() const { virtual std::optional<LangAS> getConstantAddressSpace() const {
return LangAS::Default; return LangAS::Default;
} }
@ -1700,10 +1700,10 @@ public:
/// Returns the version of the darwin target variant SDK which was used during /// Returns the version of the darwin target variant SDK which was used during
/// the compilation if one was specified, or an empty version otherwise. /// the compilation if one was specified, or an empty version otherwise.
const Optional<VersionTuple> getDarwinTargetVariantSDKVersion() const { const std::optional<VersionTuple> getDarwinTargetVariantSDKVersion() const {
return !getTargetOpts().DarwinTargetVariantSDKVersion.empty() return !getTargetOpts().DarwinTargetVariantSDKVersion.empty()
? getTargetOpts().DarwinTargetVariantSDKVersion ? getTargetOpts().DarwinTargetVariantSDKVersion
: Optional<VersionTuple>(); : std::optional<VersionTuple>();
} }
protected: protected:

View File

@ -182,7 +182,7 @@ public:
ASTUnit *Unit); ASTUnit *Unit);
/// Get a name to identify a named decl. /// Get a name to identify a named decl.
static llvm::Optional<std::string> getLookupName(const NamedDecl *ND); static std::optional<std::string> getLookupName(const NamedDecl *ND);
/// Emit diagnostics for the user for potential configuration errors. /// Emit diagnostics for the user for potential configuration errors.
void emitCrossTUDiagnostics(const IndexError &IE); void emitCrossTUDiagnostics(const IndexError &IE);
@ -194,7 +194,7 @@ public:
/// source-location, empty is returned. /// source-location, empty is returned.
/// \note Macro expansion tracking for imported TUs is not implemented yet. /// \note Macro expansion tracking for imported TUs is not implemented yet.
/// It returns empty unconditionally. /// It returns empty unconditionally.
llvm::Optional<clang::MacroExpansionContext> std::optional<clang::MacroExpansionContext>
getMacroExpansionContextForSourceLocation( getMacroExpansionContextForSourceLocation(
const clang::SourceLocation &ToLoc) const; const clang::SourceLocation &ToLoc) const;
@ -264,7 +264,7 @@ private:
StringRef InvocationListFilePath; StringRef InvocationListFilePath;
/// In case of on-demand parsing, the invocations for parsing the source /// In case of on-demand parsing, the invocations for parsing the source
/// files is stored. /// files is stored.
llvm::Optional<InvocationListTy> InvocationList; std::optional<InvocationListTy> InvocationList;
index_error_code PreviousParsingResult = index_error_code::success; index_error_code PreviousParsingResult = index_error_code::success;
}; };

View File

@ -68,8 +68,8 @@ public:
/// \returns an optional JSON Object representing the payload that libclang /// \returns an optional JSON Object representing the payload that libclang
/// expects for providing symbol information for a single symbol. If this is /// expects for providing symbol information for a single symbol. If this is
/// not a known symbol returns \c None. /// not a known symbol returns \c None.
static Optional<Object> serializeSingleSymbolSGF(StringRef USR, static std::optional<Object> serializeSingleSymbolSGF(StringRef USR,
const APISet &API); const APISet &API);
/// The kind of a relationship between two symbols. /// The kind of a relationship between two symbols.
enum RelationshipKind { enum RelationshipKind {
@ -121,7 +121,7 @@ private:
/// \returns \c std::nullopt if this \p Record should be skipped, or a JSON /// \returns \c std::nullopt if this \p Record should be skipped, or a JSON
/// object containing common symbol information of \p Record. /// object containing common symbol information of \p Record.
template <typename RecordTy> template <typename RecordTy>
Optional<Object> serializeAPIRecord(const RecordTy &Record) const; std::optional<Object> serializeAPIRecord(const RecordTy &Record) const;
/// Helper method to serialize second-level member records of \p Record and /// Helper method to serialize second-level member records of \p Record and
/// the member-of relationships. /// the member-of relationships.

View File

@ -4267,7 +4267,7 @@ struct FormatStyle {
WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros; WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros;
} }
llvm::Optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const; std::optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const;
// Stores per-language styles. A FormatStyle instance inside has an empty // Stores per-language styles. A FormatStyle instance inside has an empty
// StyleSet. A FormatStyle instance returned by the Get method has its // StyleSet. A FormatStyle instance returned by the Get method has its
@ -4279,7 +4279,7 @@ struct FormatStyle {
struct FormatStyleSet { struct FormatStyleSet {
typedef std::map<FormatStyle::LanguageKind, FormatStyle> MapType; typedef std::map<FormatStyle::LanguageKind, FormatStyle> MapType;
llvm::Optional<FormatStyle> Get(FormatStyle::LanguageKind Language) const; std::optional<FormatStyle> Get(FormatStyle::LanguageKind Language) const;
// Adds \p Style to this FormatStyleSet. Style must not have an associated // Adds \p Style to this FormatStyleSet. Style must not have an associated
// FormatStyleSet. // FormatStyleSet.

View File

@ -222,7 +222,7 @@ private:
llvm::StringMap<SourceLocation> PreambleSrcLocCache; llvm::StringMap<SourceLocation> PreambleSrcLocCache;
/// The contents of the preamble. /// The contents of the preamble.
llvm::Optional<PrecompiledPreamble> Preamble; std::optional<PrecompiledPreamble> Preamble;
/// When non-NULL, this is the buffer used to store the contents of /// When non-NULL, this is the buffer used to store the contents of
/// the main file when it has been padded for use with the precompiled /// the main file when it has been padded for use with the precompiled
@ -835,7 +835,7 @@ public:
bool SingleFileParse = false, bool UserFilesAreVolatile = false, bool SingleFileParse = false, bool UserFilesAreVolatile = false,
bool ForSerialization = false, bool ForSerialization = false,
bool RetainExcludedConditionalBlocks = false, bool RetainExcludedConditionalBlocks = false,
llvm::Optional<StringRef> ModuleFormat = std::nullopt, std::optional<StringRef> ModuleFormat = std::nullopt,
std::unique_ptr<ASTUnit> *ErrAST = nullptr, std::unique_ptr<ASTUnit> *ErrAST = nullptr,
IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr); IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr);

View File

@ -77,7 +77,7 @@ struct ParsedSourceRange {
/// ///
/// If the end line and column are omitted, the starting line and columns /// If the end line and column are omitted, the starting line and columns
/// are used as the end values. /// are used as the end values.
static Optional<ParsedSourceRange> fromString(StringRef Str) { static std::optional<ParsedSourceRange> fromString(StringRef Str) {
std::pair<StringRef, StringRef> RangeSplit = Str.rsplit('-'); std::pair<StringRef, StringRef> RangeSplit = Str.rsplit('-');
unsigned EndLine, EndColumn; unsigned EndLine, EndColumn;
bool HasEndLoc = false; bool HasEndLoc = false;

View File

@ -165,9 +165,10 @@ class CompilerInstance : public ModuleLoader {
/// failed. /// failed.
struct OutputFile { struct OutputFile {
std::string Filename; std::string Filename;
Optional<llvm::sys::fs::TempFile> File; std::optional<llvm::sys::fs::TempFile> File;
OutputFile(std::string filename, Optional<llvm::sys::fs::TempFile> file) OutputFile(std::string filename,
std::optional<llvm::sys::fs::TempFile> file)
: Filename(std::move(filename)), File(std::move(file)) {} : Filename(std::move(filename)), File(std::move(file)) {}
}; };

View File

@ -223,7 +223,7 @@ class FrontendInputFile {
/// The input, if it comes from a buffer rather than a file. This object /// The input, if it comes from a buffer rather than a file. This object
/// does not own the buffer, and the caller is responsible for ensuring /// does not own the buffer, and the caller is responsible for ensuring
/// that it outlives any users. /// that it outlives any users.
llvm::Optional<llvm::MemoryBufferRef> Buffer; std::optional<llvm::MemoryBufferRef> Buffer;
/// The kind of input, e.g., C source, AST file, LLVM IR. /// The kind of input, e.g., C source, AST file, LLVM IR.
InputKind Kind; InputKind Kind;
@ -493,10 +493,10 @@ public:
std::string AuxTriple; std::string AuxTriple;
/// Auxiliary target CPU for CUDA/HIP compilation. /// Auxiliary target CPU for CUDA/HIP compilation.
Optional<std::string> AuxTargetCPU; std::optional<std::string> AuxTargetCPU;
/// Auxiliary target features for CUDA/HIP compilation. /// Auxiliary target features for CUDA/HIP compilation.
Optional<std::vector<std::string>> AuxTargetFeatures; std::optional<std::vector<std::string>> AuxTargetFeatures;
/// Filename to write statistics to. /// Filename to write statistics to.
std::string StatsFile; std::string StatsFile;

View File

@ -49,7 +49,7 @@ public:
for (unsigned Bucket = 0; Bucket < NumBuckets; ++Bucket) { for (unsigned Bucket = 0; Bucket < NumBuckets; ++Bucket) {
HMapBucket B = getBucket(Bucket); HMapBucket B = getBucket(Bucket);
if (B.Key != HMAP_EmptyBucketKey) if (B.Key != HMAP_EmptyBucketKey)
if (Optional<StringRef> Key = getString(B.Key)) if (std::optional<StringRef> Key = getString(B.Key))
Callback(*Key); Callback(*Key);
} }
} }
@ -75,7 +75,7 @@ private:
/// Look up the specified string in the string table. If the string index is /// Look up the specified string in the string table. If the string index is
/// not valid, return std::nullopt. /// not valid, return std::nullopt.
Optional<StringRef> getString(unsigned StrTabIdx) const; std::optional<StringRef> getString(unsigned StrTabIdx) const;
}; };
/// This class represents an Apple concept known as a 'header map'. To the /// This class represents an Apple concept known as a 'header map'. To the

View File

@ -553,9 +553,9 @@ public:
/// Finds the token that comes right after the given location. /// Finds the token that comes right after the given location.
/// ///
/// Returns the next token, or none if the location is inside a macro. /// Returns the next token, or none if the location is inside a macro.
static Optional<Token> findNextToken(SourceLocation Loc, static std::optional<Token> findNextToken(SourceLocation Loc,
const SourceManager &SM, const SourceManager &SM,
const LangOptions &LangOpts); const LangOptions &LangOpts);
/// Checks that the given token is the first token that occurs after /// Checks that the given token is the first token that occurs after
/// the given location (this excludes comments and whitespace). Returns the /// the given location (this excludes comments and whitespace). Returns the
@ -770,10 +770,10 @@ private:
void codeCompleteIncludedFile(const char *PathStart, void codeCompleteIncludedFile(const char *PathStart,
const char *CompletionPoint, bool IsAngled); const char *CompletionPoint, bool IsAngled);
llvm::Optional<uint32_t> std::optional<uint32_t>
tryReadNumericUCN(const char *&StartPtr, const char *SlashLoc, Token *Result); tryReadNumericUCN(const char *&StartPtr, const char *SlashLoc, Token *Result);
llvm::Optional<uint32_t> tryReadNamedUCN(const char *&StartPtr, std::optional<uint32_t> tryReadNamedUCN(const char *&StartPtr,
const char *SlashLoc, Token *Result); const char *SlashLoc, Token *Result);
/// Read a universal character name. /// Read a universal character name.
/// ///

View File

@ -467,7 +467,7 @@ public:
/// provided, only headers with same size and modtime are resolved. If File /// provided, only headers with same size and modtime are resolved. If File
/// is not set, all headers are resolved. /// is not set, all headers are resolved.
void resolveHeaderDirectives(Module *Mod, void resolveHeaderDirectives(Module *Mod,
llvm::Optional<const FileEntry *> File) const; std::optional<const FileEntry *> File) const;
/// Reports errors if a module must not include a specific file. /// Reports errors if a module must not include a specific file.
/// ///
@ -733,7 +733,7 @@ public:
} }
/// Return a cached module load. /// Return a cached module load.
llvm::Optional<Module *> getCachedModuleLoad(const IdentifierInfo &II) { std::optional<Module *> getCachedModuleLoad(const IdentifierInfo &II) {
auto I = CachedModuleLoads.find(&II); auto I = CachedModuleLoads.find(&II);
if (I == CachedModuleLoads.end()) if (I == CachedModuleLoads.end())
return std::nullopt; return std::nullopt;

View File

@ -291,8 +291,8 @@ class Token;
/// Optionally returns true or false if the preallocated preprocessed /// Optionally returns true or false if the preallocated preprocessed
/// entity with index \p Index came from file \p FID. /// entity with index \p Index came from file \p FID.
virtual Optional<bool> isPreprocessedEntityInFileID(unsigned Index, virtual std::optional<bool> isPreprocessedEntityInFileID(unsigned Index,
FileID FID) { FileID FID) {
return std::nullopt; return std::nullopt;
} }

View File

@ -581,7 +581,7 @@ private:
void clearSkipInfo() { SkipInfo.reset(); } void clearSkipInfo() { SkipInfo.reset(); }
llvm::Optional<PreambleSkipInfo> SkipInfo; std::optional<PreambleSkipInfo> SkipInfo;
private: private:
SmallVector<PPConditionalInfo, 4> ConditionalStack; SmallVector<PPConditionalInfo, 4> ConditionalStack;
@ -897,9 +897,9 @@ private:
}; };
struct MacroAnnotations { struct MacroAnnotations {
llvm::Optional<MacroAnnotationInfo> DeprecationInfo; std::optional<MacroAnnotationInfo> DeprecationInfo;
llvm::Optional<MacroAnnotationInfo> RestrictExpansionInfo; std::optional<MacroAnnotationInfo> RestrictExpansionInfo;
llvm::Optional<SourceLocation> FinalAnnotationLoc; std::optional<SourceLocation> FinalAnnotationLoc;
static MacroAnnotations makeDeprecation(SourceLocation Loc, static MacroAnnotations makeDeprecation(SourceLocation Loc,
std::string Msg) { std::string Msg) {
@ -2581,14 +2581,14 @@ public:
PreambleConditionalStack.setStack(s); PreambleConditionalStack.setStack(s);
} }
void setReplayablePreambleConditionalStack(ArrayRef<PPConditionalInfo> s, void setReplayablePreambleConditionalStack(
llvm::Optional<PreambleSkipInfo> SkipInfo) { ArrayRef<PPConditionalInfo> s, std::optional<PreambleSkipInfo> SkipInfo) {
PreambleConditionalStack.startReplaying(); PreambleConditionalStack.startReplaying();
PreambleConditionalStack.setStack(s); PreambleConditionalStack.setStack(s);
PreambleConditionalStack.SkipInfo = SkipInfo; PreambleConditionalStack.SkipInfo = SkipInfo;
} }
llvm::Optional<PreambleSkipInfo> getPreambleSkipInfo() const { std::optional<PreambleSkipInfo> getPreambleSkipInfo() const {
return PreambleConditionalStack.SkipInfo; return PreambleConditionalStack.SkipInfo;
} }

View File

@ -211,7 +211,7 @@ public:
/// Enables a client to cache the directives for a file and provide them /// Enables a client to cache the directives for a file and provide them
/// across multiple compiler invocations. /// across multiple compiler invocations.
/// FIXME: Allow returning an error. /// FIXME: Allow returning an error.
std::function<Optional<ArrayRef<dependency_directives_scan::Directive>>( std::function<std::optional<ArrayRef<dependency_directives_scan::Directive>>(
FileEntryRef)> FileEntryRef)>
DependencyDirectivesForFile; DependencyDirectivesForFile;
@ -222,7 +222,7 @@ public:
bool DisablePragmaDebugCrash = false; bool DisablePragmaDebugCrash = false;
/// If set, the UNIX timestamp specified by SOURCE_DATE_EPOCH. /// If set, the UNIX timestamp specified by SOURCE_DATE_EPOCH.
Optional<uint64_t> SourceDateEpoch; std::optional<uint64_t> SourceDateEpoch;
public: public:
PreprocessorOptions() : PrecompiledPreambleBytes(0, false) {} PreprocessorOptions() : PrecompiledPreambleBytes(0, false) {}

View File

@ -2949,7 +2949,7 @@ private:
SourceLocation ScopeLoc, SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax); ParsedAttr::Syntax Syntax);
Optional<AvailabilitySpec> ParseAvailabilitySpec(); std::optional<AvailabilitySpec> ParseAvailabilitySpec();
ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
@ -3070,7 +3070,7 @@ private:
void ParseTypeQualifierListOpt( void ParseTypeQualifierListOpt(
DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
bool AtomicAllowed = true, bool IdentifierRequired = false, bool AtomicAllowed = true, bool IdentifierRequired = false,
Optional<llvm::function_ref<void()>> CodeCompletionHandler = std::optional<llvm::function_ref<void()>> CodeCompletionHandler =
std::nullopt); std::nullopt);
void ParseDirectDeclarator(Declarator &D); void ParseDirectDeclarator(Declarator &D);
void ParseDecompositionDeclarator(Declarator &D); void ParseDecompositionDeclarator(Declarator &D);
@ -3080,7 +3080,7 @@ private:
bool IsAmbiguous, bool RequiresArg = false); bool IsAmbiguous, bool RequiresArg = false);
void InitCXXThisScopeForDeclaratorIfRelevant( void InitCXXThisScopeForDeclaratorIfRelevant(
const Declarator &D, const DeclSpec &DS, const Declarator &D, const DeclSpec &DS,
llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope); std::optional<Sema::CXXThisScopeRAII> &ThisScope);
bool ParseRefQualifier(bool &RefQualifierIsLValueRef, bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
SourceLocation &RefQualifierLoc); SourceLocation &RefQualifierLoc);
bool isFunctionDeclaratorIdentifierList(); bool isFunctionDeclaratorIdentifierList();

View File

@ -359,7 +359,7 @@ private:
/// The scope specifier that comes before the completion token e.g. /// The scope specifier that comes before the completion token e.g.
/// "a::b::" /// "a::b::"
llvm::Optional<CXXScopeSpec> ScopeSpecifier; std::optional<CXXScopeSpec> ScopeSpecifier;
/// A set of declaration contexts visited by Sema when doing lookup for /// A set of declaration contexts visited by Sema when doing lookup for
/// code completion. /// code completion.
@ -422,7 +422,7 @@ public:
return VisitedContexts; return VisitedContexts;
} }
llvm::Optional<const CXXScopeSpec *> getCXXScopeSpecifier() { std::optional<const CXXScopeSpec *> getCXXScopeSpecifier() {
if (ScopeSpecifier) if (ScopeSpecifier)
return &*ScopeSpecifier; return &*ScopeSpecifier;
return std::nullopt; return std::nullopt;

View File

@ -508,7 +508,7 @@ public:
Paths = nullptr; Paths = nullptr;
} }
} else { } else {
llvm::Optional<AmbiguityKind> SavedAK; std::optional<AmbiguityKind> SavedAK;
bool WasAmbiguous = false; bool WasAmbiguous = false;
if (ResultKind == Ambiguous) { if (ResultKind == Ambiguous) {
SavedAK = Ambiguity; SavedAK = Ambiguity;

View File

@ -222,7 +222,7 @@ private:
/// (e.g. return a function parameter). /// (e.g. return a function parameter).
/// 3) std::nullopt value means that there is no NRVO candidate in this scope /// 3) std::nullopt value means that there is no NRVO candidate in this scope
/// (i.e. there are no return statements in this scope). /// (i.e. there are no return statements in this scope).
Optional<VarDecl *> NRVO; std::optional<VarDecl *> NRVO;
/// Represents return slots for NRVO candidates in the current scope. /// Represents return slots for NRVO candidates in the current scope.
/// If a variable is present in this set, it means that a return slot is /// If a variable is present in this set, it means that a return slot is

View File

@ -1348,7 +1348,7 @@ public:
ValueDecl *Decl = nullptr; ValueDecl *Decl = nullptr;
DeclContext *Context = nullptr; DeclContext *Context = nullptr;
}; };
llvm::Optional<InitializationContext> DelayedDefaultInitializationContext; std::optional<InitializationContext> DelayedDefaultInitializationContext;
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
unsigned NumCleanupObjects, unsigned NumCleanupObjects,
@ -1626,7 +1626,7 @@ public:
private: private:
std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager; std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager;
Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo; std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
bool WarnedDarwinSDKInfoMissing = false; bool WarnedDarwinSDKInfoMissing = false;
@ -1860,8 +1860,8 @@ public:
// Invariant: At most one of these Optionals has a value. // Invariant: At most one of these Optionals has a value.
// FIXME: Switch these to a Variant once that exists. // FIXME: Switch these to a Variant once that exists.
llvm::Optional<ImmediateDiagBuilder> ImmediateDiag; std::optional<ImmediateDiagBuilder> ImmediateDiag;
llvm::Optional<unsigned> PartialDiagId; std::optional<unsigned> PartialDiagId;
}; };
/// Is the last error level diagnostic immediate. This is used to determined /// Is the last error level diagnostic immediate. This is used to determined
@ -6610,7 +6610,7 @@ public:
BinaryOperatorKind Operator, BinaryOperatorKind Operator,
SourceLocation EllipsisLoc, Expr *RHS, SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc, SourceLocation RParenLoc,
Optional<unsigned> NumExpansions); std::optional<unsigned> NumExpansions);
ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
BinaryOperatorKind Operator); BinaryOperatorKind Operator);
@ -6717,16 +6717,12 @@ public:
SourceLocation PlacementRParen, SourceLocation PlacementRParen,
SourceRange TypeIdParens, Declarator &D, SourceRange TypeIdParens, Declarator &D,
Expr *Initializer); Expr *Initializer);
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, ExprResult
SourceLocation PlacementLParen, BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
MultiExprArg PlacementArgs, MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType,
SourceRange TypeIdParens, TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
QualType AllocType, SourceRange DirectInitRange, Expr *Initializer);
TypeSourceInfo *AllocTypeInfo,
Optional<Expr *> ArraySize,
SourceRange DirectInitRange,
Expr *Initializer);
/// Determine whether \p FD is an aligned allocation or deallocation /// Determine whether \p FD is an aligned allocation or deallocation
/// function that is unavailable. /// function that is unavailable.
@ -7099,7 +7095,7 @@ public:
/// Number lambda for linkage purposes if necessary. /// Number lambda for linkage purposes if necessary.
void handleLambdaNumbering( void handleLambdaNumbering(
CXXRecordDecl *Class, CXXMethodDecl *Method, CXXRecordDecl *Class, CXXMethodDecl *Method,
Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = std::optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling =
std::nullopt); std::nullopt);
/// Endow the lambda scope info with the relevant properties. /// Endow the lambda scope info with the relevant properties.
@ -7124,8 +7120,8 @@ public:
} }
QualType buildLambdaInitCaptureInitialization( QualType buildLambdaInitCaptureInitialization(
SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, std::optional<unsigned> NumExpansions, IdentifierInfo *Id,
Expr *&Init); bool DirectInit, Expr *&Init);
/// Create a dummy variable within the declcontext of the lambda's /// Create a dummy variable within the declcontext of the lambda's
/// call operator, for name lookup purposes for a lambda init capture. /// call operator, for name lookup purposes for a lambda init capture.
@ -7266,15 +7262,15 @@ private:
/// the case of lambdas) set up the LocalInstantiationScope of the current /// the case of lambdas) set up the LocalInstantiationScope of the current
/// function. /// function.
bool SetupConstraintScope( bool SetupConstraintScope(
FunctionDecl *FD, llvm::Optional<ArrayRef<TemplateArgument>> TemplateArgs, FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope); MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope);
/// Used during constraint checking, sets up the constraint template argument /// Used during constraint checking, sets up the constraint template argument
/// lists, and calls SetupConstraintScope to set up the /// lists, and calls SetupConstraintScope to set up the
/// LocalInstantiationScope to have the proper set of ParVarDecls configured. /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
llvm::Optional<MultiLevelTemplateArgumentList> std::optional<MultiLevelTemplateArgumentList>
SetupConstraintCheckingTemplateArgumentsAndScope( SetupConstraintCheckingTemplateArgumentsAndScope(
FunctionDecl *FD, llvm::Optional<ArrayRef<TemplateArgument>> TemplateArgs, FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
LocalInstantiationScope &Scope); LocalInstantiationScope &Scope);
private: private:
@ -7988,7 +7984,7 @@ public:
explicit operator bool() const { return isRequired(); } explicit operator bool() const { return isRequired(); }
private: private:
llvm::Optional<SourceLocation> TemplateKW; std::optional<SourceLocation> TemplateKW;
}; };
enum class AssumedTemplateKind { enum class AssumedTemplateKind {
@ -8802,14 +8798,13 @@ public:
/// expansion. /// expansion.
TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
SourceLocation EllipsisLoc, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions); std::optional<unsigned> NumExpansions);
/// Construct a pack expansion type from the pattern of the pack /// Construct a pack expansion type from the pattern of the pack
/// expansion. /// expansion.
QualType CheckPackExpansion(QualType Pattern, QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
SourceRange PatternRange,
SourceLocation EllipsisLoc, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions); std::optional<unsigned> NumExpansions);
/// Invoked when parsing an expression followed by an ellipsis, which /// Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion. /// creates a pack expansion.
@ -8828,7 +8823,7 @@ public:
/// ///
/// \param EllipsisLoc The location of the ellipsis. /// \param EllipsisLoc The location of the ellipsis.
ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions); std::optional<unsigned> NumExpansions);
/// Determine whether we could expand a pack expansion with the /// Determine whether we could expand a pack expansion with the
/// given set of parameter packs into separate arguments by repeatedly /// given set of parameter packs into separate arguments by repeatedly
@ -8864,13 +8859,11 @@ public:
/// are to be instantiated with arguments of different lengths), false /// are to be instantiated with arguments of different lengths), false
/// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
/// must be set. /// must be set.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, bool CheckParameterPacksForExpansion(
SourceRange PatternRange, SourceLocation EllipsisLoc, SourceRange PatternRange,
ArrayRef<UnexpandedParameterPack> Unexpanded, ArrayRef<UnexpandedParameterPack> Unexpanded,
const MultiLevelTemplateArgumentList &TemplateArgs, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
bool &ShouldExpand, bool &RetainExpansion, std::optional<unsigned> &NumExpansions);
bool &RetainExpansion,
Optional<unsigned> &NumExpansions);
/// Determine the number of arguments in the given pack expansion /// Determine the number of arguments in the given pack expansion
/// type. /// type.
@ -8879,8 +8872,8 @@ public:
/// consistent across all of the unexpanded parameter packs in its pattern. /// consistent across all of the unexpanded parameter packs in its pattern.
/// ///
/// Returns an empty Optional if the type can't be expanded. /// Returns an empty Optional if the type can't be expanded.
Optional<unsigned> getNumArgumentsInExpansion(QualType T, std::optional<unsigned> getNumArgumentsInExpansion(
const MultiLevelTemplateArgumentList &TemplateArgs); QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
/// Determine whether the given declarator contains any unexpanded /// Determine whether the given declarator contains any unexpanded
/// parameter packs. /// parameter packs.
@ -8908,9 +8901,8 @@ public:
/// \param NumExpansions Will be set to the number of expansions that will /// \param NumExpansions Will be set to the number of expansions that will
/// be generated from this pack expansion, if known a priori. /// be generated from this pack expansion, if known a priori.
TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
TemplateArgumentLoc OrigLoc, TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis,
SourceLocation &Ellipsis, std::optional<unsigned> &NumExpansions) const;
Optional<unsigned> &NumExpansions) const;
/// Given a template argument that contains an unexpanded parameter pack, but /// Given a template argument that contains an unexpanded parameter pack, but
/// which has already been substituted, attempt to determine the number of /// which has already been substituted, attempt to determine the number of
@ -8918,7 +8910,7 @@ public:
/// ///
/// This is intended for use when transforming 'sizeof...(Arg)' in order to /// This is intended for use when transforming 'sizeof...(Arg)' in order to
/// avoid actually expanding the pack where possible. /// avoid actually expanding the pack where possible.
Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); std::optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
//===--------------------------------------------------------------------===// //===--------------------------------------------------------------------===//
// C++ Template Argument Deduction (C++ [temp.deduct]) // C++ Template Argument Deduction (C++ [temp.deduct])
@ -9653,7 +9645,7 @@ public:
/// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
/// template-deduction context object, which can be used to capture /// template-deduction context object, which can be used to capture
/// diagnostics that will be suppressed. /// diagnostics that will be suppressed.
Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; std::optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
/// Determines whether we are currently in a context that /// Determines whether we are currently in a context that
/// is not evaluated as per C++ [expr] p5. /// is not evaluated as per C++ [expr] p5.
@ -9684,7 +9676,7 @@ public:
Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer; Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer;
} }
llvm::Optional<ExpressionEvaluationContextRecord::InitializationContext> std::optional<ExpressionEvaluationContextRecord::InitializationContext>
InnermostDeclarationWithDelayedImmediateInvocations() const { InnermostDeclarationWithDelayedImmediateInvocations() const {
assert(!ExprEvalContexts.empty() && assert(!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context"); "Must be in an expression evaluation context");
@ -9699,12 +9691,11 @@ public:
return std::nullopt; return std::nullopt;
} }
llvm::Optional<ExpressionEvaluationContextRecord::InitializationContext> std::optional<ExpressionEvaluationContextRecord::InitializationContext>
OutermostDeclarationWithDelayedImmediateInvocations() const { OutermostDeclarationWithDelayedImmediateInvocations() const {
assert(!ExprEvalContexts.empty() && assert(!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context"); "Must be in an expression evaluation context");
llvm::Optional<ExpressionEvaluationContextRecord::InitializationContext> std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
Res;
for (auto &Ctx : llvm::reverse(ExprEvalContexts)) { for (auto &Ctx : llvm::reverse(ExprEvalContexts)) {
if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated && if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
!Ctx.DelayedDefaultInitializationContext && Res) !Ctx.DelayedDefaultInitializationContext && Res)
@ -9949,7 +9940,7 @@ public:
ParmVarDecl * ParmVarDecl *
SubstParmVarDecl(ParmVarDecl *D, SubstParmVarDecl(ParmVarDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs, const MultiLevelTemplateArgumentList &TemplateArgs,
int indexAdjustment, Optional<unsigned> NumExpansions, int indexAdjustment, std::optional<unsigned> NumExpansions,
bool ExpectParameterPack, bool EvaluateConstraints = true); bool ExpectParameterPack, bool EvaluateConstraints = true);
bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
@ -10929,7 +10920,7 @@ private:
OpenMPDirectiveKind Kind; OpenMPDirectiveKind Kind;
/// The directive with indirect clause. /// The directive with indirect clause.
Optional<Expr *> Indirect; std::optional<Expr *> Indirect;
/// The directive location. /// The directive location.
SourceLocation Loc; SourceLocation Loc;
@ -11684,7 +11675,7 @@ public:
/// \returns std::nullopt, if the function/variant function are not compatible /// \returns std::nullopt, if the function/variant function are not compatible
/// with the pragma, pair of original function/variant ref expression /// with the pragma, pair of original function/variant ref expression
/// otherwise. /// otherwise.
Optional<std::pair<FunctionDecl *, Expr *>> std::optional<std::pair<FunctionDecl *, Expr *>>
checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
OMPTraitInfo &TI, unsigned NumAppendArgs, OMPTraitInfo &TI, unsigned NumAppendArgs,
SourceRange SR); SourceRange SR);
@ -12798,7 +12789,7 @@ public:
return std::make_pair(cast_or_null<VarDecl>(ConditionVar), return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
Condition.get()); Condition.get());
} }
llvm::Optional<bool> getKnownValue() const { std::optional<bool> getKnownValue() const {
if (!HasKnownValue) if (!HasKnownValue)
return std::nullopt; return std::nullopt;
return KnownValue; return KnownValue;
@ -13349,7 +13340,8 @@ public:
void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertyDefinition(Scope *S);
void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
IdentifierInfo *PropertyName); IdentifierInfo *PropertyName);
void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, void CodeCompleteObjCMethodDecl(Scope *S,
std::optional<bool> IsInstanceMethod,
ParsedType ReturnType); ParsedType ReturnType);
void CodeCompleteObjCMethodDeclSelector(Scope *S, void CodeCompleteObjCMethodDeclSelector(Scope *S,
bool IsInstanceMethod, bool IsInstanceMethod,

View File

@ -29,7 +29,7 @@ class Sema;
struct AtomicConstraint { struct AtomicConstraint {
const Expr *ConstraintExpr; const Expr *ConstraintExpr;
Optional<ArrayRef<TemplateArgumentLoc>> ParameterMapping; std::optional<ArrayRef<TemplateArgumentLoc>> ParameterMapping;
AtomicConstraint(Sema &S, const Expr *ConstraintExpr) : AtomicConstraint(Sema &S, const Expr *ConstraintExpr) :
ConstraintExpr(ConstraintExpr) { }; ConstraintExpr(ConstraintExpr) { };
@ -145,9 +145,9 @@ struct NormalizedConstraint {
} }
private: private:
static Optional<NormalizedConstraint> static std::optional<NormalizedConstraint>
fromConstraintExprs(Sema &S, NamedDecl *D, ArrayRef<const Expr *> E); fromConstraintExprs(Sema &S, NamedDecl *D, ArrayRef<const Expr *> E);
static Optional<NormalizedConstraint> static std::optional<NormalizedConstraint>
fromConstraintExpr(Sema &S, NamedDecl *D, const Expr *E); fromConstraintExpr(Sema &S, NamedDecl *D, const Expr *E);
}; };

View File

@ -31,7 +31,7 @@ class Sema;
/// of the capture-capable lambda's LambdaScopeInfo. /// of the capture-capable lambda's LambdaScopeInfo.
/// See Implementation for more detailed comments. /// See Implementation for more detailed comments.
Optional<unsigned> getStackIndexOfNearestEnclosingCaptureCapableLambda( std::optional<unsigned> getStackIndexOfNearestEnclosingCaptureCapableLambda(
ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes, ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
ValueDecl *VarToCapture, Sema &S); ValueDecl *VarToCapture, Sema &S);

View File

@ -601,7 +601,7 @@ enum class TemplateSubstitutionKind : char {
// A few supplemental visitor functions. // A few supplemental visitor functions.
Decl *VisitCXXMethodDecl(CXXMethodDecl *D, Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
TemplateParameterList *TemplateParams, TemplateParameterList *TemplateParams,
Optional<const ASTTemplateArgumentListInfo *> std::optional<const ASTTemplateArgumentListInfo *>
ClassScopeSpecializationArgs = std::nullopt, ClassScopeSpecializationArgs = std::nullopt,
RewriteKind RK = RewriteKind::None); RewriteKind RK = RewriteKind::None);
Decl *VisitFunctionDecl(FunctionDecl *D, Decl *VisitFunctionDecl(FunctionDecl *D,

View File

@ -285,7 +285,7 @@ struct DeductionFailureInfo {
/// Return the index of the call argument that this deduction /// Return the index of the call argument that this deduction
/// failure refers to, if any. /// failure refers to, if any.
llvm::Optional<unsigned> getCallArgIndex(); std::optional<unsigned> getCallArgIndex();
/// Free any memory associated with this deduction failure. /// Free any memory associated with this deduction failure.
void Destroy(); void Destroy();

View File

@ -463,7 +463,7 @@ private:
SourceLocation CurrentImportLoc; SourceLocation CurrentImportLoc;
/// The module kind that is currently deserializing. /// The module kind that is currently deserializing.
Optional<ModuleKind> CurrentDeserializingModuleKind; std::optional<ModuleKind> CurrentDeserializingModuleKind;
/// The global module index, if loaded. /// The global module index, if loaded.
std::unique_ptr<GlobalModuleIndex> GlobalIndex; std::unique_ptr<GlobalModuleIndex> GlobalIndex;
@ -883,7 +883,7 @@ private:
SourceLocation PointersToMembersPragmaLocation; SourceLocation PointersToMembersPragmaLocation;
/// The pragma float_control state. /// The pragma float_control state.
Optional<FPOptionsOverride> FpPragmaCurrentValue; std::optional<FPOptionsOverride> FpPragmaCurrentValue;
SourceLocation FpPragmaCurrentLocation; SourceLocation FpPragmaCurrentLocation;
struct FpPragmaStackEntry { struct FpPragmaStackEntry {
FPOptionsOverride Value; FPOptionsOverride Value;
@ -895,7 +895,7 @@ private:
llvm::SmallVector<std::string, 2> FpPragmaStrings; llvm::SmallVector<std::string, 2> FpPragmaStrings;
/// The pragma align/pack state. /// The pragma align/pack state.
Optional<Sema::AlignPackInfo> PragmaAlignPackCurrentValue; std::optional<Sema::AlignPackInfo> PragmaAlignPackCurrentValue;
SourceLocation PragmaAlignPackCurrentLocation; SourceLocation PragmaAlignPackCurrentLocation;
struct PragmaAlignPackStackEntry { struct PragmaAlignPackStackEntry {
Sema::AlignPackInfo Value; Sema::AlignPackInfo Value;
@ -1778,8 +1778,8 @@ public:
/// Optionally returns true or false if the preallocated preprocessed /// Optionally returns true or false if the preallocated preprocessed
/// entity with index \p Index came from file \p FID. /// entity with index \p Index came from file \p FID.
Optional<bool> isPreprocessedEntityInFileID(unsigned Index, std::optional<bool> isPreprocessedEntityInFileID(unsigned Index,
FileID FID) override; FileID FID) override;
/// Read a preallocated skipped range from the external source. /// Read a preallocated skipped range from the external source.
SourceRange ReadSkippedRange(unsigned Index) override; SourceRange ReadSkippedRange(unsigned Index) override;
@ -2142,7 +2142,7 @@ public:
unsigned getModuleFileID(ModuleFile *M); unsigned getModuleFileID(ModuleFile *M);
/// Return a descriptor for the corresponding module. /// Return a descriptor for the corresponding module.
llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override; std::optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override;
ExtKind hasExternalDefinitions(const Decl *D) override; ExtKind hasExternalDefinitions(const Decl *D) override;

View File

@ -453,13 +453,13 @@ public:
bool isInteresting(SVal V) const; bool isInteresting(SVal V) const;
bool isInteresting(const LocationContext *LC) const; bool isInteresting(const LocationContext *LC) const;
Optional<bugreporter::TrackingKind> std::optional<bugreporter::TrackingKind>
getInterestingnessKind(SymbolRef sym) const; getInterestingnessKind(SymbolRef sym) const;
Optional<bugreporter::TrackingKind> std::optional<bugreporter::TrackingKind>
getInterestingnessKind(const MemRegion *R) const; getInterestingnessKind(const MemRegion *R) const;
Optional<bugreporter::TrackingKind> getInterestingnessKind(SVal V) const; std::optional<bugreporter::TrackingKind> getInterestingnessKind(SVal V) const;
/// Returns whether or not this report should be considered valid. /// Returns whether or not this report should be considered valid.
/// ///
@ -779,8 +779,8 @@ public:
return T->getTagKind() == &Kind; return T->getTagKind() == &Kind;
} }
Optional<std::string> generateMessage(BugReporterContext &BRC, std::optional<std::string> generateMessage(BugReporterContext &BRC,
PathSensitiveBugReport &R) const { PathSensitiveBugReport &R) const {
std::string Msg = Cb(BRC, R); std::string Msg = Cb(BRC, R);
if (Msg.empty()) if (Msg.empty())
return std::nullopt; return std::nullopt;

View File

@ -503,13 +503,9 @@ public:
bool printValue(const Expr *CondVarExpr, raw_ostream &Out, bool printValue(const Expr *CondVarExpr, raw_ostream &Out,
const ExplodedNode *N, bool TookTrue, bool IsAssuming); const ExplodedNode *N, bool TookTrue, bool IsAssuming);
bool patternMatch(const Expr *Ex, bool patternMatch(const Expr *Ex, const Expr *ParentEx, raw_ostream &Out,
const Expr *ParentEx, BugReporterContext &BRC, PathSensitiveBugReport &R,
raw_ostream &Out, const ExplodedNode *N, std::optional<bool> &prunable,
BugReporterContext &BRC,
PathSensitiveBugReport &R,
const ExplodedNode *N,
Optional<bool> &prunable,
bool IsSameFieldName); bool IsSameFieldName);
static bool isPieceMessageGeneric(const PathDiagnosticPiece *Piece); static bool isPieceMessageGeneric(const PathDiagnosticPiece *Piece);

View File

@ -43,9 +43,9 @@ enum CallDescriptionFlags : unsigned {
/// arguments and the name of the function. /// arguments and the name of the function.
class CallDescription { class CallDescription {
friend class CallEvent; friend class CallEvent;
using MaybeCount = Optional<unsigned>; using MaybeCount = std::optional<unsigned>;
mutable Optional<const IdentifierInfo *> II; mutable std::optional<const IdentifierInfo *> II;
// The list of the qualified names used to identify the specified CallEvent, // The list of the qualified names used to identify the specified CallEvent,
// e.g. "{a, b}" represent the qualified names, like "a::b". // e.g. "{a, b}" represent the qualified names, like "a::b".
std::vector<std::string> QualifiedName; std::vector<std::string> QualifiedName;

View File

@ -154,7 +154,7 @@ private:
ProgramStateRef State; ProgramStateRef State;
const LocationContext *LCtx; const LocationContext *LCtx;
llvm::PointerUnion<const Expr *, const Decl *> Origin; llvm::PointerUnion<const Expr *, const Decl *> Origin;
mutable Optional<bool> Foreign; // Set by CTU analysis. mutable std::optional<bool> Foreign; // Set by CTU analysis.
protected: protected:
// This is user data for subclasses. // This is user data for subclasses.
@ -423,7 +423,7 @@ public:
/// This function converts an argument index to the corresponding /// This function converts an argument index to the corresponding
/// parameter index. Returns std::nullopt is the argument doesn't correspond /// parameter index. Returns std::nullopt is the argument doesn't correspond
/// to any parameter variable. /// to any parameter variable.
virtual Optional<unsigned> virtual std::optional<unsigned>
getAdjustedParameterIndex(unsigned ASTArgumentIndex) const { getAdjustedParameterIndex(unsigned ASTArgumentIndex) const {
return ASTArgumentIndex; return ASTArgumentIndex;
} }
@ -442,7 +442,7 @@ public:
/// If the call returns a C++ record type then the region of its return value /// If the call returns a C++ record type then the region of its return value
/// can be retrieved from its construction context. /// can be retrieved from its construction context.
Optional<SVal> getReturnValueUnderConstruction() const; std::optional<SVal> getReturnValueUnderConstruction() const;
// Iterator access to formal parameters and their types. // Iterator access to formal parameters and their types.
private: private:
@ -771,12 +771,13 @@ public:
return CA->getKind() == CE_CXXMemberOperator; return CA->getKind() == CE_CXXMemberOperator;
} }
Optional<unsigned> std::optional<unsigned>
getAdjustedParameterIndex(unsigned ASTArgumentIndex) const override { getAdjustedParameterIndex(unsigned ASTArgumentIndex) const override {
// For member operator calls argument 0 on the expression corresponds // For member operator calls argument 0 on the expression corresponds
// to implicit this-parameter on the declaration. // to implicit this-parameter on the declaration.
return (ASTArgumentIndex > 0) ? Optional<unsigned>(ASTArgumentIndex - 1) return (ASTArgumentIndex > 0)
: std::nullopt; ? std::optional<unsigned>(ASTArgumentIndex - 1)
: std::nullopt;
} }
unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const override { unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const override {
@ -1035,7 +1036,7 @@ public:
bool isArray() const { return getOriginExpr()->isArray(); } bool isArray() const { return getOriginExpr()->isArray(); }
Optional<const clang::Expr *> getArraySizeExpr() const { std::optional<const clang::Expr *> getArraySizeExpr() const {
return getOriginExpr()->getArraySize(); return getOriginExpr()->getArraySize();
} }

View File

@ -140,7 +140,7 @@ public:
/// example, for finding variables that the given symbol was assigned to. /// example, for finding variables that the given symbol was assigned to.
static const MemRegion *getLocationRegionIfPostStore(const ExplodedNode *N) { static const MemRegion *getLocationRegionIfPostStore(const ExplodedNode *N) {
ProgramPoint L = N->getLocation(); ProgramPoint L = N->getLocation();
if (Optional<PostStore> PSL = L.getAs<PostStore>()) if (std::optional<PostStore> PSL = L.getAs<PostStore>())
return reinterpret_cast<const MemRegion*>(PSL->getLocationValue()); return reinterpret_cast<const MemRegion*>(PSL->getLocationValue());
return nullptr; return nullptr;
} }

View File

@ -70,7 +70,7 @@ Nullability getNullabilityAnnotation(QualType Type);
/// simple expressions that consist of an optional minus sign token and then a /// simple expressions that consist of an optional minus sign token and then a
/// token for an integer. If we cannot parse the value then std::nullopt is /// token for an integer. If we cannot parse the value then std::nullopt is
/// returned. /// returned.
llvm::Optional<int> tryExpandAsInteger(StringRef Macro, const Preprocessor &PP); std::optional<int> tryExpandAsInteger(StringRef Macro, const Preprocessor &PP);
class OperatorKind { class OperatorKind {
union { union {
@ -89,7 +89,7 @@ public:
return Op.Bin; return Op.Bin;
} }
Optional<BinaryOperatorKind> GetBinaryOp() const { std::optional<BinaryOperatorKind> GetBinaryOp() const {
if (IsBinary) if (IsBinary)
return Op.Bin; return Op.Bin;
return {}; return {};
@ -101,7 +101,7 @@ public:
return Op.Un; return Op.Un;
} }
Optional<UnaryOperatorKind> GetUnaryOp() const { std::optional<UnaryOperatorKind> GetUnaryOp() const {
if (!IsBinary) if (!IsBinary)
return Op.Un; return Op.Un;
return {}; return {};

View File

@ -37,7 +37,7 @@ class ExprEngine;
class SymbolReaper; class SymbolReaper;
class ConditionTruthVal { class ConditionTruthVal {
Optional<bool> Val; std::optional<bool> Val;
public: public:
/// Construct a ConditionTruthVal indicating the constraint is constrained /// Construct a ConditionTruthVal indicating the constraint is constrained

View File

@ -168,7 +168,7 @@ public:
const ProgramStateRef &getState() const { return State; } const ProgramStateRef &getState() const { return State; }
template <typename T> Optional<T> getLocationAs() const & { template <typename T> std::optional<T> getLocationAs() const & {
return Location.getAs<T>(); return Location.getAs<T>();
} }

View File

@ -619,24 +619,24 @@ public:
} }
/// Retreives which element is being constructed in a non-POD type array. /// Retreives which element is being constructed in a non-POD type array.
static Optional<unsigned> static std::optional<unsigned>
getIndexOfElementToConstruct(ProgramStateRef State, const CXXConstructExpr *E, getIndexOfElementToConstruct(ProgramStateRef State, const CXXConstructExpr *E,
const LocationContext *LCtx); const LocationContext *LCtx);
/// Retreives which element is being destructed in a non-POD type array. /// Retreives which element is being destructed in a non-POD type array.
static Optional<unsigned> static std::optional<unsigned>
getPendingArrayDestruction(ProgramStateRef State, getPendingArrayDestruction(ProgramStateRef State,
const LocationContext *LCtx); const LocationContext *LCtx);
/// Retreives the size of the array in the pending ArrayInitLoopExpr. /// Retreives the size of the array in the pending ArrayInitLoopExpr.
static Optional<unsigned> getPendingInitLoop(ProgramStateRef State, static std::optional<unsigned>
const CXXConstructExpr *E, getPendingInitLoop(ProgramStateRef State, const CXXConstructExpr *E,
const LocationContext *LCtx); const LocationContext *LCtx);
/// By looking at a certain item that may be potentially part of an object's /// By looking at a certain item that may be potentially part of an object's
/// ConstructionContext, retrieve such object's location. A particular /// ConstructionContext, retrieve such object's location. A particular
/// statement can be transparently passed as \p Item in most cases. /// statement can be transparently passed as \p Item in most cases.
static Optional<SVal> static std::optional<SVal>
getObjectUnderConstruction(ProgramStateRef State, getObjectUnderConstruction(ProgramStateRef State,
const ConstructionContextItem &Item, const ConstructionContextItem &Item,
const LocationContext *LC); const LocationContext *LC);

View File

@ -86,7 +86,7 @@ public:
markShouldNotInline(D); markShouldNotInline(D);
} }
Optional<bool> mayInline(const Decl *D) { std::optional<bool> mayInline(const Decl *D) {
MapTy::const_iterator I = Map.find(D); MapTy::const_iterator I = Map.find(D);
if (I != Map.end() && I->second.InlineChecked) if (I != Map.end() && I->second.InlineChecked)
return I->second.MayInline; return I->second.MayInline;

View File

@ -103,7 +103,7 @@ public:
private: private:
const Kind kind; const Kind kind;
mutable Optional<RegionOffset> cachedOffset; mutable std::optional<RegionOffset> cachedOffset;
protected: protected:
MemRegion(Kind k) : kind(k) {} MemRegion(Kind k) : kind(k) {}

View File

@ -747,7 +747,7 @@ ProgramState::assumeInclusiveRange(DefinedOrUnknownSVal Val,
} }
inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V, const LocationContext *LCtx) const { inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V, const LocationContext *LCtx) const {
if (Optional<Loc> L = LV.getAs<Loc>()) if (std::optional<Loc> L = LV.getAs<Loc>())
return bindLoc(*L, V, LCtx); return bindLoc(*L, V, LCtx);
return this; return this;
} }
@ -797,7 +797,7 @@ inline SVal ProgramState::getLValue(const IndirectFieldDecl *D,
} }
inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{ inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{
if (Optional<NonLoc> N = Idx.getAs<NonLoc>()) if (std::optional<NonLoc> N = Idx.getAs<NonLoc>())
return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base); return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base);
return UnknownVal(); return UnknownVal();
} }

View File

@ -247,7 +247,7 @@ public:
bool canReasonAbout(SVal X) const override { bool canReasonAbout(SVal X) const override {
const TargetInfo &TI = getBasicVals().getContext().getTargetInfo(); const TargetInfo &TI = getBasicVals().getContext().getTargetInfo();
Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>(); std::optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
if (!SymVal) if (!SymVal)
return true; return true;

View File

@ -237,7 +237,7 @@ public:
/// manner. /// manner.
/// ///
/// If \p E is not a constant or cannot be modeled, returns \c std::nullopt. /// If \p E is not a constant or cannot be modeled, returns \c std::nullopt.
Optional<SVal> getConstantVal(const Expr *E); std::optional<SVal> getConstantVal(const Expr *E);
NonLoc makeCompoundVal(QualType type, llvm::ImmutableList<SVal> vals) { NonLoc makeCompoundVal(QualType type, llvm::ImmutableList<SVal> vals) {
return nonloc::CompoundVal(BasicVals.getCompoundValData(type, vals)); return nonloc::CompoundVal(BasicVals.getCompoundValData(type, vals));
@ -371,8 +371,8 @@ public:
} }
/// Return MemRegionVal on success cast, otherwise return std::nullopt. /// Return MemRegionVal on success cast, otherwise return std::nullopt.
Optional<loc::MemRegionVal> getCastedMemRegionVal(const MemRegion *region, std::optional<loc::MemRegionVal>
QualType type); getCastedMemRegionVal(const MemRegion *region, QualType type);
/// Make an SVal that represents the given symbol. This follows the convention /// Make an SVal that represents the given symbol. This follows the convention
/// of representing Loc-type symbols (symbolic pointers and references) /// of representing Loc-type symbols (symbolic pointers and references)

View File

@ -101,7 +101,7 @@ public:
/// Convert to the specified SVal type, returning std::nullopt if this SVal is /// Convert to the specified SVal type, returning std::nullopt if this SVal is
/// not of the desired type. /// not of the desired type.
template <typename T> Optional<T> getAs() const { template <typename T> std::optional<T> getAs() const {
return llvm::dyn_cast<T>(*this); return llvm::dyn_cast<T>(*this);
} }
@ -568,11 +568,11 @@ struct CastInfo<
static bool isPossible(const From &V) { static bool isPossible(const From &V) {
return To::classof(*static_cast<const ::clang::ento::SVal *>(&V)); return To::classof(*static_cast<const ::clang::ento::SVal *>(&V));
} }
static Optional<To> castFailed() { return Optional<To>{}; } static std::optional<To> castFailed() { return std::optional<To>{}; }
static To doCast(const From &f) { static To doCast(const From &f) {
return *static_cast<const To *>(cast<::clang::ento::SVal>(&f)); return *static_cast<const To *>(cast<::clang::ento::SVal>(&f));
} }
static Optional<To> doCastIfPossible(const From &f) { static std::optional<To> doCastIfPossible(const From &f) {
if (!Self::isPossible(f)) if (!Self::isPossible(f))
return Self::castFailed(); return Self::castFailed();
return doCast(f); return doCast(f);

View File

@ -84,7 +84,8 @@ public:
/// \param[in] R The region to find the default binding for. /// \param[in] R The region to find the default binding for.
/// \return The default value bound to the region in the store, if a default /// \return The default value bound to the region in the store, if a default
/// binding exists. /// binding exists.
virtual Optional<SVal> getDefaultBinding(Store store, const MemRegion *R) = 0; virtual std::optional<SVal> getDefaultBinding(Store store,
const MemRegion *R) = 0;
/// Return the default value bound to a LazyCompoundVal. The default binding /// Return the default value bound to a LazyCompoundVal. The default binding
/// is used to represent the value of any fields or elements within the /// is used to represent the value of any fields or elements within the
@ -94,7 +95,7 @@ public:
/// \param[in] lcv The lazy compound value. /// \param[in] lcv The lazy compound value.
/// \return The default value bound to the LazyCompoundVal \c lcv, if a /// \return The default value bound to the LazyCompoundVal \c lcv, if a
/// default binding exists. /// default binding exists.
Optional<SVal> getDefaultBinding(nonloc::LazyCompoundVal lcv) { std::optional<SVal> getDefaultBinding(nonloc::LazyCompoundVal lcv) {
return getDefaultBinding(lcv.getStore(), lcv.getRegion()); return getDefaultBinding(lcv.getStore(), lcv.getRegion());
} }
@ -175,15 +176,15 @@ public:
/// enough info to determine if the cast will succeed at run time). /// enough info to determine if the cast will succeed at run time).
/// The function returns an optional with SVal representing the derived class /// The function returns an optional with SVal representing the derived class
/// in case of a successful cast and `std::nullopt` otherwise. /// in case of a successful cast and `std::nullopt` otherwise.
Optional<SVal> evalBaseToDerived(SVal Base, QualType DerivedPtrType); std::optional<SVal> evalBaseToDerived(SVal Base, QualType DerivedPtrType);
const ElementRegion *GetElementZeroRegion(const SubRegion *R, QualType T); const ElementRegion *GetElementZeroRegion(const SubRegion *R, QualType T);
/// castRegion - Used by ExprEngine::VisitCast to handle casts from /// castRegion - Used by ExprEngine::VisitCast to handle casts from
/// a MemRegion* to a specific location type. 'R' is the region being /// a MemRegion* to a specific location type. 'R' is the region being
/// casted and 'CastToTy' the result type of the cast. /// casted and 'CastToTy' the result type of the cast.
Optional<const MemRegion *> castRegion(const MemRegion *region, std::optional<const MemRegion *> castRegion(const MemRegion *region,
QualType CastToTy); QualType CastToTy);
virtual StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx, virtual StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
SymbolReaper &SymReaper) = 0; SymbolReaper &SymReaper) = 0;

View File

@ -45,8 +45,8 @@ struct Node {
ASTNodeKind getType() const; ASTNodeKind getType() const;
StringRef getTypeLabel() const; StringRef getTypeLabel() const;
bool isLeaf() const { return Children.empty(); } bool isLeaf() const { return Children.empty(); }
llvm::Optional<StringRef> getIdentifier() const; std::optional<StringRef> getIdentifier() const;
llvm::Optional<std::string> getQualifiedIdentifier() const; std::optional<std::string> getQualifiedIdentifier() const;
}; };
/// SyntaxTree objects represent subtrees of the AST. /// SyntaxTree objects represent subtrees of the AST.

View File

@ -62,7 +62,7 @@ public:
private: private:
// Used to store the parser when the executor is initialized with parser. // Used to store the parser when the executor is initialized with parser.
llvm::Optional<CommonOptionsParser> OptionsParser; std::optional<CommonOptionsParser> OptionsParser;
const CompilationDatabase &Compilations; const CompilationDatabase &Compilations;
std::unique_ptr<ToolResults> Results; std::unique_ptr<ToolResults> Results;
ExecutionContext Context; ExecutionContext Context;

View File

@ -174,11 +174,11 @@ public:
static char ID; static char ID;
const llvm::Optional<Replacement> &getNewReplacement() const { const std::optional<Replacement> &getNewReplacement() const {
return NewReplacement; return NewReplacement;
} }
const llvm::Optional<Replacement> &getExistingReplacement() const { const std::optional<Replacement> &getExistingReplacement() const {
return ExistingReplacement; return ExistingReplacement;
} }
@ -192,10 +192,10 @@ private:
// A new replacement, which is to expected be added into a set of // A new replacement, which is to expected be added into a set of
// replacements, that is causing problem. // replacements, that is causing problem.
llvm::Optional<Replacement> NewReplacement; std::optional<Replacement> NewReplacement;
// An existing replacement in a replacements set that is causing problem. // An existing replacement in a replacements set that is causing problem.
llvm::Optional<Replacement> ExistingReplacement; std::optional<Replacement> ExistingReplacement;
}; };
/// Less-than operator between two Replacements. /// Less-than operator between two Replacements.

View File

@ -40,7 +40,7 @@ struct CachedFileContents {
SmallVector<dependency_directives_scan::Token, 10> DepDirectiveTokens; SmallVector<dependency_directives_scan::Token, 10> DepDirectiveTokens;
/// Accessor to the directive tokens that's atomic to avoid data races. /// Accessor to the directive tokens that's atomic to avoid data races.
/// \p CachedFileContents has ownership of the pointer. /// \p CachedFileContents has ownership of the pointer.
std::atomic<const Optional<DependencyDirectivesTy> *> DepDirectives; std::atomic<const std::optional<DependencyDirectivesTy> *> DepDirectives;
~CachedFileContents() { delete DepDirectives.load(); } ~CachedFileContents() { delete DepDirectives.load(); }
}; };
@ -89,7 +89,7 @@ public:
/// \returns The scanned preprocessor directive tokens of the file that are /// \returns The scanned preprocessor directive tokens of the file that are
/// used to speed up preprocessing, if available. /// used to speed up preprocessing, if available.
Optional<ArrayRef<dependency_directives_scan::Directive>> std::optional<ArrayRef<dependency_directives_scan::Directive>>
getDirectiveTokens() const { getDirectiveTokens() const {
assert(!isError() && "error"); assert(!isError() && "error");
assert(!isDirectory() && "not a file"); assert(!isDirectory() && "not a file");
@ -263,7 +263,7 @@ public:
StringRef getContents() const { return Entry.getOriginalContents(); } StringRef getContents() const { return Entry.getOriginalContents(); }
Optional<ArrayRef<dependency_directives_scan::Directive>> std::optional<ArrayRef<dependency_directives_scan::Directive>>
getDirectiveTokens() const { getDirectiveTokens() const {
return Entry.getDirectiveTokens(); return Entry.getDirectiveTokens();
} }

View File

@ -85,7 +85,7 @@ public:
/// occurred, dependency file contents otherwise. /// occurred, dependency file contents otherwise.
llvm::Expected<std::string> llvm::Expected<std::string>
getDependencyFile(const std::vector<std::string> &CommandLine, StringRef CWD, getDependencyFile(const std::vector<std::string> &CommandLine, StringRef CWD,
llvm::Optional<StringRef> ModuleName = std::nullopt); std::optional<StringRef> ModuleName = std::nullopt);
/// Collect the full module dependency graph for the input, ignoring any /// Collect the full module dependency graph for the input, ignoring any
/// modules which have already been seen. If \p ModuleName isn't empty, this /// modules which have already been seen. If \p ModuleName isn't empty, this
@ -106,13 +106,13 @@ public:
getFullDependencies(const std::vector<std::string> &CommandLine, getFullDependencies(const std::vector<std::string> &CommandLine,
StringRef CWD, const llvm::StringSet<> &AlreadySeen, StringRef CWD, const llvm::StringSet<> &AlreadySeen,
LookupModuleOutputCallback LookupModuleOutput, LookupModuleOutputCallback LookupModuleOutput,
llvm::Optional<StringRef> ModuleName = std::nullopt); std::optional<StringRef> ModuleName = std::nullopt);
llvm::Expected<FullDependenciesResult> getFullDependenciesLegacyDriverCommand( llvm::Expected<FullDependenciesResult> getFullDependenciesLegacyDriverCommand(
const std::vector<std::string> &CommandLine, StringRef CWD, const std::vector<std::string> &CommandLine, StringRef CWD,
const llvm::StringSet<> &AlreadySeen, const llvm::StringSet<> &AlreadySeen,
LookupModuleOutputCallback LookupModuleOutput, LookupModuleOutputCallback LookupModuleOutput,
llvm::Optional<StringRef> ModuleName = std::nullopt); std::optional<StringRef> ModuleName = std::nullopt);
private: private:
DependencyScanningWorker Worker; DependencyScanningWorker Worker;

View File

@ -80,14 +80,14 @@ public:
const std::vector<std::string> &CommandLine, const std::vector<std::string> &CommandLine,
DependencyConsumer &DepConsumer, DependencyConsumer &DepConsumer,
DiagnosticConsumer &DiagConsumer, DiagnosticConsumer &DiagConsumer,
llvm::Optional<StringRef> ModuleName = std::nullopt); std::optional<StringRef> ModuleName = std::nullopt);
/// \returns A \c StringError with the diagnostic output if clang errors /// \returns A \c StringError with the diagnostic output if clang errors
/// occurred, success otherwise. /// occurred, success otherwise.
llvm::Error llvm::Error
computeDependencies(StringRef WorkingDirectory, computeDependencies(StringRef WorkingDirectory,
const std::vector<std::string> &CommandLine, const std::vector<std::string> &CommandLine,
DependencyConsumer &Consumer, DependencyConsumer &Consumer,
llvm::Optional<StringRef> ModuleName = std::nullopt); std::optional<StringRef> ModuleName = std::nullopt);
bool shouldEagerLoadModules() const { return EagerLoadModules; } bool shouldEagerLoadModules() const { return EagerLoadModules; }

View File

@ -73,9 +73,9 @@ public:
/// same category in the code that should be sorted after \p IncludeName. If /// same category in the code that should be sorted after \p IncludeName. If
/// \p IncludeName already exists (with exactly the same spelling), this /// \p IncludeName already exists (with exactly the same spelling), this
/// returns std::nullopt. /// returns std::nullopt.
llvm::Optional<tooling::Replacement> insert(llvm::StringRef Header, std::optional<tooling::Replacement> insert(llvm::StringRef Header,
bool IsAngled, bool IsAngled,
IncludeDirective Directive) const; IncludeDirective Directive) const;
/// Removes all existing #includes and #imports of \p Header quoted with <> if /// Removes all existing #includes and #imports of \p Header quoted with <> if
/// \p IsAngled is true or "" if \p IsAngled is false. /// \p IsAngled is true or "" if \p IsAngled is false.

View File

@ -68,8 +68,8 @@ struct SelectedASTNode {
/// ///
/// \returns std::nullopt if no nodes are selected in the AST, or a selected AST /// \returns std::nullopt if no nodes are selected in the AST, or a selected AST
/// node that corresponds to the TranslationUnitDecl otherwise. /// node that corresponds to the TranslationUnitDecl otherwise.
Optional<SelectedASTNode> findSelectedASTNodes(const ASTContext &Context, std::optional<SelectedASTNode> findSelectedASTNodes(const ASTContext &Context,
SourceRange SelectionRange); SourceRange SelectionRange);
/// An AST selection value that corresponds to a selection of a set of /// An AST selection value that corresponds to a selection of a set of
/// statements that belong to one body of code (like one function). /// statements that belong to one body of code (like one function).
@ -131,7 +131,7 @@ public:
/// declaration doesn't exist. /// declaration doesn't exist.
const Decl *getFunctionLikeNearestParent() const; const Decl *getFunctionLikeNearestParent() const;
static Optional<CodeRangeASTSelection> static std::optional<CodeRangeASTSelection>
create(SourceRange SelectionRange, const SelectedASTNode &ASTSelection); create(SourceRange SelectionRange, const SelectedASTNode &ASTSelection);
private: private:

Some files were not shown because too many files have changed in this diff Show More