[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
https://github.com/Holo-xy updated
https://github.com/llvm/llvm-project/pull/227774
>From e907e22da9a91a44a08495294e2feb48dcff99ad Mon Sep 17 00:00:00 2001
From: Holo-xy
Date: Wed, 30 Sep 2026 18:58:29 +0300
Subject: [PATCH 1/4] [clang][bounds-safety][nfc] add shared bounds attribute
validation
introduce shared type-shape and nesting validation for counted_by,
sized_by and their nullable variants. keep declaration-specific checks
separate so eager and late parsing can share the validation as support
expands to parameters, return types, globals and locals.
add attribute flags, declarator nesting support and a disabled
bounds-safety attribute-mode hook for later integration. the helpers
have no active callers, so existing behavior is unchanged.
co-authored-by: rapidsna
---
.../clang/Basic/DiagnosticSemaKinds.td| 3 +
clang/include/clang/Basic/LangOptions.h | 6 +
clang/include/clang/Sema/Sema.h | 40 +
clang/lib/Sema/SemaBoundsSafety.cpp | 145 ++
clang/lib/Sema/SemaType.cpp | 26
5 files changed, 220 insertions(+)
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 79f10b8240aa47..0765dedeab66dd 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7269,6 +7269,9 @@ def err_builtin_counted_by_ref_invalid_use : Error<
"value returned by '__builtin_counted_by_ref' cannot be used in "
"%select{an array subscript|a binary}0 expression">;
+def err_counted_by_on_nested_pointer : Error<
+ "'%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}0'
attribute on nested pointer type is not allowed">;
+
let CategoryName = "ARC Semantic Issue" in {
// ARC-mode diagnostics.
diff --git a/clang/include/clang/Basic/LangOptions.h
b/clang/include/clang/Basic/LangOptions.h
index 7539e000d03f98..eedb3b8f46 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -710,6 +710,12 @@ class LangOptions : public LangOptionsBase {
return ConvergentFunctions;
}
+ /// Return true if bounds attributes follow the -fbounds-safety programming
+ /// model, including its attributes-only mode.
+ ///
+ /// Always false until that model is implemented upstream.
+ bool hasBoundsSafetyAttributes() const { return false; }
+
/// Return true if atomicrmw operations targeting allocations in private
/// memory are undefined.
bool threadPrivateMemoryAtomicsAreUndefined() const {
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 2c4986d56eede4..e1101238061c65 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2521,6 +2521,46 @@ class Sema final : public SemaBase {
/// Implementations are in SemaBoundsSafety.cpp
///@{
public:
+ struct BoundsAttrFlags {
+bool CountInBytes = false;
+bool OrNull = false;
+bool IsEndedBy = false;
+
+/// Return the flags for a bounds attribute of kind \p K.
+static BoundsAttrFlags get(AttributeCommonInfo::Kind K);
+ };
+ static BoundsAttributedType::BoundsAttrKind
+ getBoundsAttrKind(const BoundsAttrFlags &);
+
+ /// Check the type shape for counted_by, sized_by and their _or_null
variants.
+ /// The caller checks declaration context, count expressions, flexible array
+ /// member eligibility and nesting.
+ ///
+ /// \p Flags selects the attribute variant. For void pointers, counted_by is
+ /// treated as a byte count outside the -fbounds-safety attribute model. Set
+ /// \c Flags.CountInBytes in this case if \p UpdateFlags is true.
+ /// \p AttrSpelling, \p AllowRedecl and \p AttrArg are reserved for that
model
+ /// (see LangOptions::hasBoundsSafetyAttributes).
+ ///
+ /// \returns true if the shape is valid, or false after diagnosing a rejected
+ /// attribute. Rejection may produce a warning rather than an error.
+ bool ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc,
+ SourceRange AttrRange,
+ BoundsAttrFlags &Flags,
+ StringRef AttrSpelling = {},
+ bool AllowRedecl = false,
+ Expr *AttrArg = nullptr,
+ bool UpdateFlags = true);
+
+ /// Check a counted_by-family attribute in type position and initialize
+ /// \p Flags from \p AttrKind. \p PointerNestLevel counts the pointer, array
+ /// and function declarator chunks enclosing the attribute.
+ ///
+ /// \returns true if valid, or false after diagnosing a rejected attribute.
+ bool ValidateBoundsAttrTypeForTypePosition(
+ QualType Ty, AttributeCommonInfo::Kind AttrKind, SourceLocation AttrLoc,
+ SourceRange AttrRange, unsigned PointerNestLevel, BoundsAttrFlags
&Flags);
+
/// Check if applying the
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
@@ -710,6 +710,12 @@ class LangOptions : public LangOptionsBase {
return ConvergentFunctions;
}
+ /// Return true if bounds attributes follow the -fbounds-safety programming
+ /// model. Downstream, which has the full -fbounds-safety implementation,
uses
+ /// this predicate to gate behavior that differs from upstream. Remove it
once
+ /// that divergence is resolved.
+ bool hasBoundsSafetyAttributes() const { return BoundsSafety; }
Holo-xy wrote:
changed it to what you suggested.
LMK if we want to make an issue and link it or just leave it as a todo for now.
https://github.com/llvm/llvm-project/pull/227774
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
@@ -49,6 +77,169 @@ enum class CountedByInvalidPointeeTypeKind {
VALID,
};
+/// Check type conflicts under the -fbounds-safety attribute model.
+/// Return std::nullopt if validation should continue with the shared checks.
+static std::optional checkBoundsAttrTypeConflictsAndMisc(
+Sema &S, QualType Ty, SourceLocation AttrLoc,
+const Sema::BoundsAttrFlags &Flags, StringRef AttrSpelling,
+bool AllowRedecl, Expr *AttrArg) {
+ // The -fbounds-safety model's checks for conflicting attributes, atomic
+ // pointers and array shapes are not upstream yet.
+ return std::nullopt;
+}
+
+bool Sema::ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc,
+ SourceRange AttrRange,
+ BoundsAttrFlags &Flags,
+ StringRef AttrSpelling, bool
AllowRedecl,
+ Expr *AttrArg, bool UpdateFlags) {
+ if (getLangOpts().hasBoundsSafetyAttributes())
+if (std::optional Result = checkBoundsAttrTypeConflictsAndMisc(
+*this, Ty, AttrLoc, Flags, AttrSpelling, AllowRedecl, AttrArg))
+ return *Result;
+
+ BoundsAttributedType::BoundsAttrKind Kind = getBoundsAttrKind(Flags);
+
+ // counted_by and sized_by require a pointer or array.
+ if (!Ty->isPointerType() && !Ty->isArrayType()) {
+Diag(AttrLoc, diag::err_count_attr_not_on_ptr_or_flexible_array_member)
+<< Kind << 0;
+return false;
+ }
+
+ // Arrays only support counted_by outside the -fbounds-safety attribute
model.
+ if (!getLangOpts().hasBoundsSafetyAttributes() && Ty->isArrayType() &&
+ (Flags.CountInBytes || Flags.OrNull)) {
+Diag(AttrLoc, diag::err_count_attr_not_on_ptr_or_flexible_array_member)
+<< Kind << /*suggest counted_by*/ 1;
+return false;
+ }
+
+ // Check the pointee or element type.
+ QualType PointeeTy;
+ int SelectPtrOrArr;
+ if (Ty->isPointerType()) {
+PointeeTy = Ty->getPointeeType();
+SelectPtrOrArr = 0;
+ } else {
+const ArrayType *AT = getASTContext().getAsArrayType(Ty);
+PointeeTy = AT->getElementType();
+SelectPtrOrArr = 1;
+ }
+
+ auto InvalidTypeKind = CountedByInvalidPointeeTypeKind::VALID;
+ bool ShouldWarn = false;
+ if (!Flags.CountInBytes && PointeeTy->isAlwaysIncompleteType()) {
+// In general using `counted_by` or `counted_by_or_null` on
+// pointers where the pointee is an incomplete type are problematic. This
+// is because it isn't possible to compute the pointer's bounds without
+// knowing the pointee type size. At the same time it is common to forward
+// declare types in header files.
+//
+// E.g.:
+//
+// struct Handle;
+// struct Wrapper {
+// size_t count;
+// struct Handle* __counted_by(count) handles;
+// }
+//
+// To allow the above code pattern but still prevent the pointee type from
+// being incomplete in places where bounds checks are needed the following
+// scheme is used:
+//
+// * When the pointee type might not always be an incomplete type (i.e.
+// a type that is currently incomplete but might be completed later
+// on in the translation unit) the attribute is allowed by this method
+// but later uses of the FieldDecl are checked that the pointee type
+// is complete see `BoundsSafetyCheckAssignmentToCountAttrPtr`,
+// `BoundsSafetyCheckInitialization`, and
+// `BoundsSafetyCheckUseOfCountAttrPtr`
+//
+// * When the pointee type is always an incomplete type (e.g.
+// `void` in strict C mode) the attribute is disallowed by this method
+// because we know the type can never be completed so there's no reason
+// to allow it.
+//
+// Exception: void has an implicit size of 1 byte for pointer arithmetic
+// (following GNU convention). Therefore, counted_by on void* is allowed
+// and behaves equivalently to sized_by (treating the count as bytes).
+if (PointeeTy->isVoidType() && !getLangOpts().hasBoundsSafetyAttributes())
{
+ // Emit a warning that this is a GNU extension.
+ Diag(AttrLoc, diag::ext_gnu_counted_by_void_ptr) << Kind;
+ Diag(AttrLoc, diag::note_gnu_counted_by_void_ptr_use_sized_by) << Kind;
+ assert(!Ty->isArrayType() && "sized_by is not allowed on arrays");
+ if (UpdateFlags)
+Flags.CountInBytes = true;
+ return true;
+}
+InvalidTypeKind = CountedByInvalidPointeeTypeKind::INCOMPLETE;
+ } else if (PointeeTy->isSizelessType()) {
+InvalidTypeKind = CountedByInvalidPointeeTypeKind::SIZELESS;
+ } else if (PointeeTy->isFunctionType()) {
+InvalidTypeKind = CountedByInvalidPointeeTypeKind::FUNCTION;
+ } else if (!Flags.CountInBytes &&
+ PointeeTy->isStructureTypeWithFlexibleArrayMember()) {
+if (Ty->isArrayType()) {
+ // This is a workaround for the Linux kernel that has already adopted
+ // `counted_by` on a FAM where
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
@@ -710,6 +710,12 @@ class LangOptions : public LangOptionsBase {
return ConvergentFunctions;
}
+ /// Return true if bounds attributes follow the -fbounds-safety programming
+ /// model. Downstream, which has the full -fbounds-safety implementation,
uses
+ /// this predicate to gate behavior that differs from upstream. Remove it
once
+ /// that divergence is resolved.
+ bool hasBoundsSafetyAttributes() const { return BoundsSafety; }
rapidsna wrote:
I agree we could try to find a better name for this that works for both
upstream and downstream.
https://github.com/llvm/llvm-project/pull/227774
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
https://github.com/rapidsna edited https://github.com/llvm/llvm-project/pull/227774 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
https://github.com/rapidsna edited https://github.com/llvm/llvm-project/pull/227774 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
@@ -710,6 +710,12 @@ class LangOptions : public LangOptionsBase {
return ConvergentFunctions;
}
+ /// Return true if bounds attributes follow the -fbounds-safety programming
+ /// model. Downstream, which has the full -fbounds-safety implementation,
uses
+ /// this predicate to gate behavior that differs from upstream. Remove it
once
+ /// that divergence is resolved.
+ bool hasBoundsSafetyAttributes() const { return BoundsSafety; }
rapidsna wrote:
fwiw, I don't think we should actually upstream attribute-only mode as is. Once
all the attributes are available upstream, there's no need "attribute-only"
mode. It's currently used as a predicate to gate divergent behavior in
downstream. So `hasBoundsSafetyAttributes()` doesn't make a lot of sense in
upstream but it's included in this patch to minimize the divergence from
downstream.
https://github.com/llvm/llvm-project/pull/227774
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
https://github.com/delcypher requested changes to this pull request. Thanks for addressing my first set of comments. I noticed a few more minor issues. Once we've resolved those we should take this PR out of being a draft and add more reviewers. https://github.com/llvm/llvm-project/pull/227774 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
@@ -710,6 +710,12 @@ class LangOptions : public LangOptionsBase {
return ConvergentFunctions;
}
+ /// Return true if bounds attributes follow the -fbounds-safety programming
+ /// model. Downstream, which has the full -fbounds-safety implementation,
uses
+ /// this predicate to gate behavior that differs from upstream. Remove it
once
+ /// that divergence is resolved.
+ bool hasBoundsSafetyAttributes() const { return BoundsSafety; }
delcypher wrote:
We may want to consider renaming `hasBoundsSafetyAttributes()` (maybe a
separate PR) because the name is confusing because `__counted_by` can be used
without any kind of `-fbounds-safety` mode.
For now we might want to consider rewording to comments (which I also think are
confusing) and also refer to a GitHub issue that tracks upstreaming
"-fbounds-safety attribute-only mode".
Suggested rewording:
```
/// Return true if using -fbounds-safety in full or attribute-only mode
bool hasBoundsSafetyAttributes() const {
// TODO: Upstream attribute-only mode (refer to github issue here)
return BoundsSafety;
}
```
https://github.com/llvm/llvm-project/pull/227774
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
@@ -49,6 +77,169 @@ enum class CountedByInvalidPointeeTypeKind {
VALID,
};
+/// Check type conflicts under the -fbounds-safety attribute model.
+/// Return std::nullopt if validation should continue with the shared checks.
+static std::optional checkBoundsAttrTypeConflictsAndMisc(
+Sema &S, QualType Ty, SourceLocation AttrLoc,
+const Sema::BoundsAttrFlags &Flags, StringRef AttrSpelling,
+bool AllowRedecl, Expr *AttrArg) {
+ // The -fbounds-safety model's checks for conflicting attributes, atomic
+ // pointers and array shapes are not upstream yet.
+ return std::nullopt;
+}
+
+bool Sema::ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc,
+ SourceRange AttrRange,
+ BoundsAttrFlags &Flags,
+ StringRef AttrSpelling, bool
AllowRedecl,
+ Expr *AttrArg, bool UpdateFlags) {
+ if (getLangOpts().hasBoundsSafetyAttributes())
+if (std::optional Result = checkBoundsAttrTypeConflictsAndMisc(
+*this, Ty, AttrLoc, Flags, AttrSpelling, AllowRedecl, AttrArg))
+ return *Result;
+
+ BoundsAttributedType::BoundsAttrKind Kind = getBoundsAttrKind(Flags);
+
+ // counted_by and sized_by require a pointer or array.
+ if (!Ty->isPointerType() && !Ty->isArrayType()) {
+Diag(AttrLoc, diag::err_count_attr_not_on_ptr_or_flexible_array_member)
+<< Kind << 0;
+return false;
+ }
+
+ // Arrays only support counted_by outside the -fbounds-safety attribute
model.
+ if (!getLangOpts().hasBoundsSafetyAttributes() && Ty->isArrayType() &&
+ (Flags.CountInBytes || Flags.OrNull)) {
+Diag(AttrLoc, diag::err_count_attr_not_on_ptr_or_flexible_array_member)
+<< Kind << /*suggest counted_by*/ 1;
+return false;
+ }
+
+ // Check the pointee or element type.
+ QualType PointeeTy;
+ int SelectPtrOrArr;
+ if (Ty->isPointerType()) {
+PointeeTy = Ty->getPointeeType();
+SelectPtrOrArr = 0;
+ } else {
+const ArrayType *AT = getASTContext().getAsArrayType(Ty);
+PointeeTy = AT->getElementType();
+SelectPtrOrArr = 1;
+ }
+
+ auto InvalidTypeKind = CountedByInvalidPointeeTypeKind::VALID;
+ bool ShouldWarn = false;
+ if (!Flags.CountInBytes && PointeeTy->isAlwaysIncompleteType()) {
+// In general using `counted_by` or `counted_by_or_null` on
+// pointers where the pointee is an incomplete type are problematic. This
+// is because it isn't possible to compute the pointer's bounds without
+// knowing the pointee type size. At the same time it is common to forward
+// declare types in header files.
+//
+// E.g.:
+//
+// struct Handle;
+// struct Wrapper {
+// size_t count;
+// struct Handle* __counted_by(count) handles;
+// }
+//
+// To allow the above code pattern but still prevent the pointee type from
+// being incomplete in places where bounds checks are needed the following
+// scheme is used:
+//
+// * When the pointee type might not always be an incomplete type (i.e.
+// a type that is currently incomplete but might be completed later
+// on in the translation unit) the attribute is allowed by this method
+// but later uses of the FieldDecl are checked that the pointee type
+// is complete see `BoundsSafetyCheckAssignmentToCountAttrPtr`,
+// `BoundsSafetyCheckInitialization`, and
+// `BoundsSafetyCheckUseOfCountAttrPtr`
+//
+// * When the pointee type is always an incomplete type (e.g.
+// `void` in strict C mode) the attribute is disallowed by this method
+// because we know the type can never be completed so there's no reason
+// to allow it.
+//
+// Exception: void has an implicit size of 1 byte for pointer arithmetic
+// (following GNU convention). Therefore, counted_by on void* is allowed
+// and behaves equivalently to sized_by (treating the count as bytes).
+if (PointeeTy->isVoidType() && !getLangOpts().hasBoundsSafetyAttributes())
{
+ // Emit a warning that this is a GNU extension.
+ Diag(AttrLoc, diag::ext_gnu_counted_by_void_ptr) << Kind;
+ Diag(AttrLoc, diag::note_gnu_counted_by_void_ptr_use_sized_by) << Kind;
+ assert(!Ty->isArrayType() && "sized_by is not allowed on arrays");
+ if (UpdateFlags)
+Flags.CountInBytes = true;
+ return true;
+}
+InvalidTypeKind = CountedByInvalidPointeeTypeKind::INCOMPLETE;
+ } else if (PointeeTy->isSizelessType()) {
+InvalidTypeKind = CountedByInvalidPointeeTypeKind::SIZELESS;
+ } else if (PointeeTy->isFunctionType()) {
+InvalidTypeKind = CountedByInvalidPointeeTypeKind::FUNCTION;
+ } else if (!Flags.CountInBytes &&
+ PointeeTy->isStructureTypeWithFlexibleArrayMember()) {
+if (Ty->isArrayType()) {
+ // This is a workaround for the Linux kernel that has already adopted
+ // `counted_by` on a FAM where
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
https://github.com/delcypher edited https://github.com/llvm/llvm-project/pull/227774 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
https://github.com/Holo-xy updated
https://github.com/llvm/llvm-project/pull/227774
>From e907e22da9a91a44a08495294e2feb48dcff99ad Mon Sep 17 00:00:00 2001
From: Holo-xy
Date: Wed, 30 Sep 2026 18:58:29 +0300
Subject: [PATCH 1/3] [clang][bounds-safety][nfc] add shared bounds attribute
validation
introduce shared type-shape and nesting validation for counted_by,
sized_by and their nullable variants. keep declaration-specific checks
separate so eager and late parsing can share the validation as support
expands to parameters, return types, globals and locals.
add attribute flags, declarator nesting support and a disabled
bounds-safety attribute-mode hook for later integration. the helpers
have no active callers, so existing behavior is unchanged.
co-authored-by: rapidsna
---
.../clang/Basic/DiagnosticSemaKinds.td| 3 +
clang/include/clang/Basic/LangOptions.h | 6 +
clang/include/clang/Sema/Sema.h | 40 +
clang/lib/Sema/SemaBoundsSafety.cpp | 145 ++
clang/lib/Sema/SemaType.cpp | 26
5 files changed, 220 insertions(+)
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 79f10b8240aa4..0765dedeab66d 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7269,6 +7269,9 @@ def err_builtin_counted_by_ref_invalid_use : Error<
"value returned by '__builtin_counted_by_ref' cannot be used in "
"%select{an array subscript|a binary}0 expression">;
+def err_counted_by_on_nested_pointer : Error<
+ "'%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}0'
attribute on nested pointer type is not allowed">;
+
let CategoryName = "ARC Semantic Issue" in {
// ARC-mode diagnostics.
diff --git a/clang/include/clang/Basic/LangOptions.h
b/clang/include/clang/Basic/LangOptions.h
index 7539e000d03f9..eedb3b8f4 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -710,6 +710,12 @@ class LangOptions : public LangOptionsBase {
return ConvergentFunctions;
}
+ /// Return true if bounds attributes follow the -fbounds-safety programming
+ /// model, including its attributes-only mode.
+ ///
+ /// Always false until that model is implemented upstream.
+ bool hasBoundsSafetyAttributes() const { return false; }
+
/// Return true if atomicrmw operations targeting allocations in private
/// memory are undefined.
bool threadPrivateMemoryAtomicsAreUndefined() const {
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 2c4986d56eede..e1101238061c6 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2521,6 +2521,46 @@ class Sema final : public SemaBase {
/// Implementations are in SemaBoundsSafety.cpp
///@{
public:
+ struct BoundsAttrFlags {
+bool CountInBytes = false;
+bool OrNull = false;
+bool IsEndedBy = false;
+
+/// Return the flags for a bounds attribute of kind \p K.
+static BoundsAttrFlags get(AttributeCommonInfo::Kind K);
+ };
+ static BoundsAttributedType::BoundsAttrKind
+ getBoundsAttrKind(const BoundsAttrFlags &);
+
+ /// Check the type shape for counted_by, sized_by and their _or_null
variants.
+ /// The caller checks declaration context, count expressions, flexible array
+ /// member eligibility and nesting.
+ ///
+ /// \p Flags selects the attribute variant. For void pointers, counted_by is
+ /// treated as a byte count outside the -fbounds-safety attribute model. Set
+ /// \c Flags.CountInBytes in this case if \p UpdateFlags is true.
+ /// \p AttrSpelling, \p AllowRedecl and \p AttrArg are reserved for that
model
+ /// (see LangOptions::hasBoundsSafetyAttributes).
+ ///
+ /// \returns true if the shape is valid, or false after diagnosing a rejected
+ /// attribute. Rejection may produce a warning rather than an error.
+ bool ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc,
+ SourceRange AttrRange,
+ BoundsAttrFlags &Flags,
+ StringRef AttrSpelling = {},
+ bool AllowRedecl = false,
+ Expr *AttrArg = nullptr,
+ bool UpdateFlags = true);
+
+ /// Check a counted_by-family attribute in type position and initialize
+ /// \p Flags from \p AttrKind. \p PointerNestLevel counts the pointer, array
+ /// and function declarator chunks enclosing the attribute.
+ ///
+ /// \returns true if valid, or false after diagnosing a rejected attribute.
+ bool ValidateBoundsAttrTypeForTypePosition(
+ QualType Ty, AttributeCommonInfo::Kind AttrKind, SourceLocation AttrLoc,
+ SourceRange AttrRange, unsigned PointerNestLevel, BoundsAttrFlags
&Flags);
+
/// Check if applying the
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
https://github.com/delcypher edited https://github.com/llvm/llvm-project/pull/227774 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
@@ -49,6 +77,123 @@ enum class CountedByInvalidPointeeTypeKind {
VALID,
};
+/// Check type conflicts under the -fbounds-safety attribute model.
+/// Return std::nullopt if validation should continue with the shared checks.
+static std::optional checkBoundsAttrTypeConflictsAndMisc(
+Sema &S, QualType Ty, SourceLocation AttrLoc,
+const Sema::BoundsAttrFlags &Flags, StringRef AttrSpelling,
+bool AllowRedecl, Expr *AttrArg) {
+ // The -fbounds-safety model's checks for conflicting attributes, atomic
+ // pointers and array shapes are not upstream yet.
+ return std::nullopt;
+}
+
+bool Sema::ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc,
+ SourceRange AttrRange,
+ BoundsAttrFlags &Flags,
+ StringRef AttrSpelling, bool
AllowRedecl,
+ Expr *AttrArg, bool UpdateFlags) {
+ if (getLangOpts().hasBoundsSafetyAttributes())
+if (std::optional Result = checkBoundsAttrTypeConflictsAndMisc(
+*this, Ty, AttrLoc, Flags, AttrSpelling, AllowRedecl, AttrArg))
+ return *Result;
+
+ BoundsAttributedType::BoundsAttrKind Kind = getBoundsAttrKind(Flags);
+
+ // counted_by and sized_by require a pointer or array.
+ if (!Ty->isPointerType() && !Ty->isArrayType()) {
+Diag(AttrLoc, diag::err_count_attr_not_on_ptr_or_flexible_array_member)
+<< Kind << 0;
+return false;
+ }
+
+ // Arrays only support counted_by outside the -fbounds-safety attribute
model.
+ if (!getLangOpts().hasBoundsSafetyAttributes() && Ty->isArrayType() &&
rapidsna wrote:
Okay, let's do that.
https://github.com/llvm/llvm-project/pull/227774
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
@@ -49,6 +77,123 @@ enum class CountedByInvalidPointeeTypeKind {
VALID,
};
+/// Check type conflicts under the -fbounds-safety attribute model.
+/// Return std::nullopt if validation should continue with the shared checks.
+static std::optional checkBoundsAttrTypeConflictsAndMisc(
+Sema &S, QualType Ty, SourceLocation AttrLoc,
+const Sema::BoundsAttrFlags &Flags, StringRef AttrSpelling,
+bool AllowRedecl, Expr *AttrArg) {
+ // The -fbounds-safety model's checks for conflicting attributes, atomic
+ // pointers and array shapes are not upstream yet.
+ return std::nullopt;
+}
+
+bool Sema::ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc,
+ SourceRange AttrRange,
+ BoundsAttrFlags &Flags,
+ StringRef AttrSpelling, bool
AllowRedecl,
+ Expr *AttrArg, bool UpdateFlags) {
+ if (getLangOpts().hasBoundsSafetyAttributes())
rapidsna wrote:
Okay. Let's try to keep then.
https://github.com/llvm/llvm-project/pull/227774
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
rapidsna wrote: You may want to rebase this branch to the latest main, which contains another change from a prior late-parsing related PR. https://github.com/llvm/llvm-project/pull/227774 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [BoundsSafety][NFC] Add counted_by type-shape validation helper (PR #227774)
@@ -49,6 +77,123 @@ enum class CountedByInvalidPointeeTypeKind {
VALID,
};
+/// Check type conflicts under the -fbounds-safety attribute model.
+/// Return std::nullopt if validation should continue with the shared checks.
+static std::optional checkBoundsAttrTypeConflictsAndMisc(
+Sema &S, QualType Ty, SourceLocation AttrLoc,
+const Sema::BoundsAttrFlags &Flags, StringRef AttrSpelling,
+bool AllowRedecl, Expr *AttrArg) {
+ // The -fbounds-safety model's checks for conflicting attributes, atomic
+ // pointers and array shapes are not upstream yet.
+ return std::nullopt;
+}
+
+bool Sema::ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc,
+ SourceRange AttrRange,
+ BoundsAttrFlags &Flags,
+ StringRef AttrSpelling, bool
AllowRedecl,
+ Expr *AttrArg, bool UpdateFlags) {
+ if (getLangOpts().hasBoundsSafetyAttributes())
+if (std::optional Result = checkBoundsAttrTypeConflictsAndMisc(
+*this, Ty, AttrLoc, Flags, AttrSpelling, AllowRedecl, AttrArg))
+ return *Result;
+
+ BoundsAttributedType::BoundsAttrKind Kind = getBoundsAttrKind(Flags);
+
+ // counted_by and sized_by require a pointer or array.
+ if (!Ty->isPointerType() && !Ty->isArrayType()) {
+Diag(AttrLoc, diag::err_count_attr_not_on_ptr_or_flexible_array_member)
+<< Kind << 0;
+return false;
+ }
+
+ // Arrays only support counted_by outside the -fbounds-safety attribute
model.
+ if (!getLangOpts().hasBoundsSafetyAttributes() && Ty->isArrayType() &&
+ (Flags.CountInBytes || Flags.OrNull)) {
+Diag(AttrLoc, diag::err_count_attr_not_on_ptr_or_flexible_array_member)
+<< Kind << /*suggest counted_by*/ 1;
+return false;
+ }
+
+ // Check the pointee or element type.
+ QualType PointeeTy;
+ int SelectPtrOrArr;
+ if (Ty->isPointerType()) {
+PointeeTy = Ty->getPointeeType();
+SelectPtrOrArr = 0;
+ } else {
+const ArrayType *AT = getASTContext().getAsArrayType(Ty);
+PointeeTy = AT->getElementType();
+SelectPtrOrArr = 1;
+ }
+
+ auto InvalidTypeKind = CountedByInvalidPointeeTypeKind::VALID;
+ bool ShouldWarn = false;
+ if (!Flags.CountInBytes && PointeeTy->isAlwaysIncompleteType()) {
+// GNU void pointer arithmetic treats each element as one byte, so allow
+// counted_by on void pointers outside the -fbounds-safety attribute model.
+if (PointeeTy->isVoidType() && !getLangOpts().hasBoundsSafetyAttributes())
{
+ Diag(AttrLoc, diag::ext_gnu_counted_by_void_ptr) << Kind;
+ Diag(AttrLoc, diag::note_gnu_counted_by_void_ptr_use_sized_by) << Kind;
+ if (UpdateFlags)
+Flags.CountInBytes = true;
+ return true;
+}
+InvalidTypeKind = CountedByInvalidPointeeTypeKind::INCOMPLETE;
+ } else if (PointeeTy->isSizelessType()) {
+InvalidTypeKind = CountedByInvalidPointeeTypeKind::SIZELESS;
+ } else if (PointeeTy->isFunctionType()) {
+InvalidTypeKind = CountedByInvalidPointeeTypeKind::FUNCTION;
+ } else if (!Flags.CountInBytes &&
+ PointeeTy->isStructureTypeWithFlexibleArrayMember()) {
+if (Ty->isArrayType() && !getLangOpts().BoundsSafety) {
rapidsna wrote:
Let's take the change in downstream:
https://github.com/swiftlang/llvm-project/pull/14186/changes#diff-b622d95f208dd56aed93b32de4a0189e8dac608cab6288fafa943e51059be217R350
https://github.com/llvm/llvm-project/pull/227774
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
