[llvm-branch-commits] [clang] [BoundsSafety] Support counted_by on out parameters (PR #244630)
Mohammed Ashraf via llvm-branch-commits
llvm-branch-commits at lists.llvm.org
Fri Nov 20 08:00:53 PST 2026
https://github.com/Holo-xy updated https://github.com/llvm/llvm-project/pull/244630
>From 45a6998e8b8b71ffdfbbc67c27f59c28b0bab239 Mon Sep 17 00:00:00 2001
From: Holo-xy <mohammedashraf4599 at gmail.com>
Date: Mon, 19 Oct 2026 19:52:27 +0300
Subject: [PATCH 1/2] [BoundsSafety] Support counted_by on out parameters
One pointer level below a parameter may have a count, as for an out
parameter, and a parameter's count may dereference a parameter:
`int *__counted_by(*len) *buf`. The parameter's own pointer may not
have a count too.
---
clang/include/clang/Sema/Sema.h | 8 ++-
clang/lib/Sema/SemaBoundsSafety.cpp | 36 ++++++----
clang/lib/Sema/SemaType.cpp | 71 +++++++++++++++----
.../AST/attr-counted-by-function-params.c | 10 +++
.../Sema/attr-counted-by-function-params.c | 69 +++++++++++++-----
5 files changed, 150 insertions(+), 44 deletions(-)
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d95e0af922f4e..bb3aad8fa7125 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2533,6 +2533,12 @@ class Sema final : public SemaBase {
static BoundsAttributedType::BoundsAttrKind
getBoundsAttrKind(const BoundsAttrFlags &);
+ /// The reference that the count \p E of a counted_by-family attribute is
+ /// made of: \p E itself, or the operand of `*` in \p E, which sets \p IsDeref
+ /// (a parameter's count may be a dereferenced parameter, `*len`). Null if
+ /// \p E is neither.
+ static DeclRefExpr *getCountDeclRef(Expr *E, bool &IsDeref);
+
/// 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.
@@ -2638,7 +2644,7 @@ class Sema final : public SemaBase {
FieldDecl *FD, Expr *Arg);
/// Check that \p E is a valid count for a counted_by-family attribute on
- /// \p ParamTy, the type of a parameter.
+ /// \p ParamTy, the type of a parameter or of the pointer it points to.
///
/// \returns false iff semantically valid.
bool CheckCountedByAttrOnParam(QualType ParamTy, Expr *E, bool CountInBytes,
diff --git a/clang/lib/Sema/SemaBoundsSafety.cpp b/clang/lib/Sema/SemaBoundsSafety.cpp
index 6fcce221a26f7..e61c68d3447ba 100644
--- a/clang/lib/Sema/SemaBoundsSafety.cpp
+++ b/clang/lib/Sema/SemaBoundsSafety.cpp
@@ -54,6 +54,16 @@ Sema::BoundsAttrFlags Sema::BoundsAttrFlags::get(AttributeCommonInfo::Kind K) {
return Flags;
}
+DeclRefExpr *Sema::getCountDeclRef(Expr *E, bool &IsDeref) {
+ IsDeref = false;
+ if (auto *UO = dyn_cast<UnaryOperator>(E);
+ UO && UO->getOpcode() == UO_Deref) {
+ E = UO->getSubExpr()->IgnoreImpCasts();
+ IsDeref = true;
+ }
+ return dyn_cast<DeclRefExpr>(E);
+}
+
static const RecordDecl *
GetEnclosingNamedOrTopAnonRecord(const RecordDecl *RD) {
// An unnamed struct is treated as anonymous struct at this point.
@@ -240,11 +250,8 @@ bool Sema::ValidateBoundsAttrPosition(BoundsAttributedType::BoundsAttrKind Kind,
}
// Currently, only attributes at the outermost level of the declared type
- // are supported.
- //
- // FIXME: Support indirect parameters such as:
- // void f(int *__counted_by(*len) *buf, int *len);
- // See https://github.com/llvm/llvm-project/issues/166411.
+ // are supported. The caller passes zero for the pointer that a parameter
+ // points to, as for an out parameter: `int *__counted_by(*len) *buf`.
if (PointerNestLevel > 0) {
Diag(AttrLoc, diag::err_counted_by_on_nested_pointer) << Kind;
return false;
@@ -279,17 +286,20 @@ bool Sema::ValidateBoundsAttrTypeForTypePosition(
}
/// The checks shared by the counts of fields and parameters: \p E must be a
-/// non-boolean integer and a plain reference to a declaration. Returns that
-/// declaration, or null after diagnosing.
-static ValueDecl *checkCountRefersToDecl(Sema &S, Expr *E, unsigned Kind) {
+/// non-boolean integer and a plain reference to a declaration, or if
+/// \p AllowDeref, a dereference of one. Returns that declaration, or null after
+/// diagnosing.
+static ValueDecl *checkCountRefersToDecl(Sema &S, Expr *E, unsigned Kind,
+ bool AllowDeref) {
if (!E->getType()->isIntegerType() || E->getType()->isBooleanType()) {
S.Diag(E->getBeginLoc(), diag::err_count_attr_argument_not_integer)
<< Kind << E->getSourceRange();
return nullptr;
}
- auto *DRE = dyn_cast<DeclRefExpr>(E);
- if (!DRE) {
+ bool IsDeref;
+ auto *DRE = Sema::getCountDeclRef(E, IsDeref);
+ if (!DRE || (IsDeref && !AllowDeref)) {
S.Diag(E->getBeginLoc(),
diag::err_count_attr_only_support_simple_decl_reference)
<< Kind << E->getSourceRange();
@@ -321,7 +331,8 @@ bool Sema::CheckCountedByAttrInRecord(const DeclContext *DC, QualType Ty,
return true;
}
- ValueDecl *CountDecl = checkCountRefersToDecl(*this, E, Kind);
+ ValueDecl *CountDecl =
+ checkCountRefersToDecl(*this, E, Kind, /*AllowDeref=*/false);
if (!CountDecl)
return true;
@@ -403,7 +414,8 @@ bool Sema::CheckCountedByAttrOnParam(QualType ParamTy, Expr *E,
return true;
}
- ValueDecl *CountDecl = checkCountRefersToDecl(*this, E, Kind);
+ ValueDecl *CountDecl =
+ checkCountRefersToDecl(*this, E, Kind, /*AllowDeref=*/true);
if (!CountDecl)
return true;
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 5215c9acab9c5..10eac661a2ff6 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -182,6 +182,13 @@ static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
case ParsedAttr::AT_TypeNullableResult: \
case ParsedAttr::AT_TypeNullUnspecified
+// Bounds attributes of the counted_by family.
+#define COUNTED_BY_TYPE_ATTRS_CASELIST \
+ case ParsedAttr::AT_CountedBy: \
+ case ParsedAttr::AT_CountedByOrNull: \
+ case ParsedAttr::AT_SizedBy: \
+ case ParsedAttr::AT_SizedByOrNull
+
namespace {
/// An object which stores processing state for the entire
/// GetTypeForDeclarator process.
@@ -4388,6 +4395,41 @@ static bool shouldHaveNullability(QualType T) {
T->getCanonicalTypeInternal());
}
+/// Whether the count on declarator chunk \p ChunkIndex of \p D (on its
+/// declaration specifiers if \p ChunkIndex is the number of chunks) is on the
+/// pointer that a parameter's own pointer or array points to, as for an out
+/// parameter: `int *__counted_by(*len) *buf`. Only that one level may have a
+/// count, so the parameter's own type may not have one too.
+static bool isIndirectParamCount(const Declarator &D, unsigned ChunkIndex) {
+ if (D.getContext() != DeclaratorContext::Prototype)
+ return false;
+
+ auto IsCount = [](const ParsedAttr &A) {
+ switch (A.getKind()) {
+ COUNTED_BY_TYPE_ATTRS_CASELIST:
+ return true;
+ default:
+ return false;
+ }
+ };
+ if (llvm::any_of(D.getAttributes(), IsCount))
+ return false;
+
+ unsigned Levels = 0;
+ for (unsigned I = 0; I != ChunkIndex; ++I) {
+ const DeclaratorChunk &Chunk = D.getTypeObject(I);
+ if (Chunk.isParen())
+ continue;
+ if (Chunk.Kind != DeclaratorChunk::Pointer &&
+ Chunk.Kind != DeclaratorChunk::Array)
+ return false;
+ if (llvm::any_of(Chunk.getAttrs(), IsCount))
+ return false;
+ ++Levels;
+ }
+ return Levels == 1;
+}
+
static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
QualType declSpecType,
TypeSourceInfo *TInfo) {
@@ -9146,6 +9188,13 @@ static void HandleCountedByAttrOnType(TypeProcessingState &State,
}
unsigned chunkIndex = State.getCurrentChunkIndex();
+ unsigned PointerNestLevel = getPointerNestLevel(D, chunkIndex);
+
+ // A parameter may point to a counted pointer, as an out parameter does:
+ // `int *__counted_by(*len) *buf`. That count is nested, but allowed.
+ if (PointerNestLevel == 1 && CurType->isPointerType() &&
+ isIndirectParamCount(D, chunkIndex))
+ PointerNestLevel = 0;
bool IsParameter = D.getContext() == DeclaratorContext::Prototype ||
D.getContext() == DeclaratorContext::ObjCParameter;
@@ -9153,8 +9202,8 @@ static void HandleCountedByAttrOnType(TypeProcessingState &State,
Sema::BoundsAttrFlags Flags;
if (!S.ValidateBoundsAttrTypeForTypePosition(
CurType, Attr.getKind(), Attr.getLoc(), Attr.getRange(),
- getPointerNestLevel(D, chunkIndex),
- isOnFunctionReturnType(D, chunkIndex), Flags, IsParameter)) {
+ PointerNestLevel, isOnFunctionReturnType(D, chunkIndex), Flags,
+ IsParameter)) {
Attr.setInvalid();
return;
}
@@ -9460,10 +9509,7 @@ static void processTypeAttrs(TypeProcessingState &state, QualType &type,
break;
}
- case ParsedAttr::AT_CountedBy:
- case ParsedAttr::AT_CountedByOrNull:
- case ParsedAttr::AT_SizedBy:
- case ParsedAttr::AT_SizedByOrNull: {
+ COUNTED_BY_TYPE_ATTRS_CASELIST: {
DeclaratorContext Ctx = state.getDeclarator().getContext();
bool OnParam = Ctx == DeclaratorContext::Prototype ||
Ctx == DeclaratorContext::ObjCParameter ||
@@ -10223,9 +10269,10 @@ QualType Sema::BuildTypeofExprType(Expr *E, TypeOfKind Kind) {
static void
BuildTypeCoupledDecls(Expr *E,
llvm::SmallVectorImpl<TypeCoupledDeclRefInfo> &Decls) {
- // Currently, 'counted_by' only allows direct DeclRefExpr to FieldDecl.
- auto *CountDecl = cast<DeclRefExpr>(E)->getDecl();
- Decls.push_back(TypeCoupledDeclRefInfo(CountDecl, /*IsDref*/ false));
+ bool IsDeref;
+ DeclRefExpr *DRE = Sema::getCountDeclRef(E, IsDeref);
+ assert(DRE && "count is not a reference");
+ Decls.push_back(TypeCoupledDeclRefInfo(DRE->getDecl(), IsDeref));
}
bool Sema::ActOnLateParsedTypeAttrArgument(BoundsAttributedType *BATy,
@@ -10268,10 +10315,10 @@ QualType Sema::BuildCountAttributedArrayOrPointerType(QualType WrappedTy,
bool OrNull) {
// Accept any array or pointer type here. The caller has checked the
// declaration and its count (see CheckCountedByAttrInRecord and
- // CheckCountedByAttrOnParam), so the count is a DeclRefExpr, and an array is
- // a flexible array member or a parameter.
+ // CheckCountedByAttrOnParam), so the count is a reference, or a dereferenced
+ // one for a parameter, and an array is a flexible array member or a
+ // parameter.
assert(WrappedTy->isArrayType() || WrappedTy->isPointerType());
- assert(isa<DeclRefExpr>(CountExpr) && "count must be checked by the caller");
llvm::SmallVector<TypeCoupledDeclRefInfo, 1> Decls;
BuildTypeCoupledDecls(CountExpr, Decls);
diff --git a/clang/test/AST/attr-counted-by-function-params.c b/clang/test/AST/attr-counted-by-function-params.c
index 67a6decbc94ff..7ab9967830071 100644
--- a/clang/test/AST/attr-counted-by-function-params.c
+++ b/clang/test/AST/attr-counted-by-function-params.c
@@ -59,11 +59,21 @@ void typeof_fam(__typeof__(((struct fam *)0)->arr) arr);
// expected-error at +1{{'counted_by' attribute cannot be applied to a pointer that already has a 'counted_by' attribute}}
void repeated_array(int n, int m, int arr[] __counted_by(n) __counted_by(m));
+// An out parameter's count, here a dereferenced parameter, is on the pointer
+// that the parameter points to.
+// CHECK: FunctionDecl {{.*}} out 'void (int *, int * __counted_by(*len)*)'
+void out(int *len, int *__counted_by(*len) *buf);
+
// A rejected count is not applied, and the function stays valid.
// CHECK: FunctionDecl {{.*}} not_a_param 'void (int *)'
// expected-error at +1{{count expression in function declaration may only reference function parameters}}
void not_a_param(int *__counted_by(global_count) buf);
+// A nested count is dropped; the parameter's own count stays.
+// CHECK: FunctionDecl {{.*}} both_counted 'void (int, int, int ** __counted_by(m))'
+// expected-error at +1{{'counted_by' attribute on nested pointer type is not allowed}}
+void both_counted(int n, int m, int *__counted_by(n) *__counted_by(m) buf);
+
// A count on a K&R parameter declaration is ignored.
// CHECK: FunctionDecl {{.*}} knr 'void (int, int *)'
// expected-warning at +2{{a function definition without a prototype is deprecated}}
diff --git a/clang/test/Sema/attr-counted-by-function-params.c b/clang/test/Sema/attr-counted-by-function-params.c
index ff1abe099da7f..76e5059581120 100644
--- a/clang/test/Sema/attr-counted-by-function-params.c
+++ b/clang/test/Sema/attr-counted-by-function-params.c
@@ -169,29 +169,55 @@ void array_attr_after(int count,
void array_attr_after(int count, int *__counted_by(count) arr);
//==============================================================================
-// Not supported yet
+// Indirect parameters
//==============================================================================
+// A parameter may point to a counted pointer, as an out parameter does, and a
+// parameter's count may dereference a parameter.
+void out(int *len, int *__counted_by(*len) *buf);
+void out_or_null(int *len, int *__counted_by_or_null(*len) *buf);
+void out_sized(int *len, void *__sized_by(*len) *buf);
+void out_sized_or_null(int *len, void *__sized_by_or_null(*len) *buf);
+void out_count(int count, int *__counted_by(count) *buf);
+void out_array(int count, int *__counted_by(count) buf[]);
+void own_deref(int *count, int *__counted_by(*count) buf);
+void own_deref_or_null(int *count, int *__counted_by_or_null(*count) buf);
+void own_deref_sized(int *count, void *__sized_by(*count) buf);
+void own_deref_sized_or_null(int *count, void *__sized_by_or_null(*count) buf);
+
+// Only one level down, and not below a pointer that has a count itself.
// expected-error at +1{{'counted_by' attribute on nested pointer type is not allowed}}
-void out(int count, int *__counted_by(count) *buf);
+void two_levels(int count, int *__counted_by(count) **buf);
// expected-error at +1{{'counted_by_or_null' attribute on nested pointer type is not allowed}}
-void out_or_null(int count, int *__counted_by_or_null(count) *buf);
+void two_levels_or_null(int count, int *__counted_by_or_null(count) **buf);
// expected-error at +1{{'sized_by' attribute on nested pointer type is not allowed}}
-void out_sized(int count, void *__sized_by(count) *buf);
+void two_levels_sized(int count, void *__sized_by(count) **buf);
// expected-error at +1{{'sized_by_or_null' attribute on nested pointer type is not allowed}}
-void out_sized_or_null(int count, void *__sized_by_or_null(count) *buf);
-
-// The nesting is diagnosed before what the count names.
+void two_levels_sized_or_null(int count, void *__sized_by_or_null(count) **buf);
// expected-error at +1{{'counted_by' attribute on nested pointer type is not allowed}}
-void nested_inner(int *__counted_by(global_count) *buf);
+void both_counted(int n, int m, int *__counted_by(n) *__counted_by(m) buf);
// expected-error at +1{{'counted_by_or_null' attribute on nested pointer type is not allowed}}
-void nested_inner_or_null(int *__counted_by_or_null(global_count) *buf);
+void both_counted_or_null(int n, int m, int *__counted_by_or_null(n) *__counted_by_or_null(m) buf);
// expected-error at +1{{'sized_by' attribute on nested pointer type is not allowed}}
-void nested_inner_sized(void *__sized_by(global_count) *buf);
+void both_counted_sized(int n, int m, void *__sized_by(n) *__sized_by(m) buf);
// expected-error at +1{{'sized_by_or_null' attribute on nested pointer type is not allowed}}
+void both_counted_sized_or_null(int n, int m, void *__sized_by_or_null(n) *__sized_by_or_null(m) buf);
+// FIXME: With late parsing, a count after the declarator is parsed once the
+// pointer that the parameter points to already has its count, so both stay.
+// eager-error at +1{{'counted_by' attribute on nested pointer type is not allowed}}
+void both_counted_trailing(int *len, int n, int *__counted_by(*len) *buf __counted_by(n));
+
+// The count of the pointer that a parameter points to names a parameter too.
+// expected-error at +1{{count expression in function declaration may only reference function parameters}}
+void nested_inner(int *__counted_by(global_count) *buf);
+// expected-error at +1{{count expression in function declaration may only reference function parameters}}
+void nested_inner_or_null(int *__counted_by_or_null(global_count) *buf);
+// expected-error at +1{{count expression in function declaration may only reference function parameters}}
+void nested_inner_sized(void *__sized_by(global_count) *buf);
+// expected-error at +1{{count expression in function declaration may only reference function parameters}}
void nested_inner_sized_or_null(void *__sized_by_or_null(global_count) *buf);
-// A count on the outer pointer still names a parameter.
+// So does a count on the parameter's own pointer.
// expected-error at +1{{count expression in function declaration may only reference function parameters}}
void nested_outer_global(int **__counted_by(global_count) buf);
// expected-error at +1{{count expression in function declaration may only reference function parameters}}
@@ -201,14 +227,19 @@ void nested_outer_global_sized(int **__sized_by(global_count) buf);
// expected-error at +1{{count expression in function declaration may only reference function parameters}}
void nested_outer_global_sized_or_null(int **__sized_by_or_null(global_count) buf);
-// expected-error at +1{{'counted_by' argument must be a simple declaration reference}}
-void deref(int *count, int *__counted_by(*count) buf);
-// expected-error at +1{{'counted_by_or_null' argument must be a simple declaration reference}}
-void deref_or_null(int *count, int *__counted_by_or_null(*count) buf);
-// expected-error at +1{{'sized_by' argument must be a simple declaration reference}}
-void deref_sized(int *count, void *__sized_by(*count) buf);
-// expected-error at +1{{'sized_by_or_null' argument must be a simple declaration reference}}
-void deref_sized_or_null(int *count, void *__sized_by_or_null(*count) buf);
+// A count that comes with another declaration's type, through '__typeof__', was
+// checked where it was written, so it is not nested here.
+void typeof_param(int count, int *__counted_by(count) buf,
+ __typeof__(buf) **out, __typeof__(buf) (**out_paren));
+struct with_count { int n; int *__counted_by(n) p; };
+void typeof_field(struct with_count *s) {
+ __typeof__(s->p) (**x);
+ (void)x;
+}
+
+//==============================================================================
+// Not supported yet
+//==============================================================================
// expected-warning at +2{{a function definition without a prototype is deprecated}}
// expected-warning at +1{{'counted_by' attribute ignored}}
>From 91df70b039038a5ff8734410b448c6c671506392 Mon Sep 17 00:00:00 2001
From: Holo-xy <mohammedashraf4599 at gmail.com>
Date: Fri, 20 Nov 2026 17:55:32 +0200
Subject: [PATCH 2/2] [BoundsSafety] Fix formatting
---
clang/lib/Sema/SemaType.cpp | 17 ++++++++---------
1 file changed, 8 insertions(+), 9 deletions(-)
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 10eac661a2ff6..d1306b35884fb 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -182,13 +182,6 @@ static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
case ParsedAttr::AT_TypeNullableResult: \
case ParsedAttr::AT_TypeNullUnspecified
-// Bounds attributes of the counted_by family.
-#define COUNTED_BY_TYPE_ATTRS_CASELIST \
- case ParsedAttr::AT_CountedBy: \
- case ParsedAttr::AT_CountedByOrNull: \
- case ParsedAttr::AT_SizedBy: \
- case ParsedAttr::AT_SizedByOrNull
-
namespace {
/// An object which stores processing state for the entire
/// GetTypeForDeclarator process.
@@ -4406,7 +4399,10 @@ static bool isIndirectParamCount(const Declarator &D, unsigned ChunkIndex) {
auto IsCount = [](const ParsedAttr &A) {
switch (A.getKind()) {
- COUNTED_BY_TYPE_ATTRS_CASELIST:
+ case ParsedAttr::AT_CountedBy:
+ case ParsedAttr::AT_CountedByOrNull:
+ case ParsedAttr::AT_SizedBy:
+ case ParsedAttr::AT_SizedByOrNull:
return true;
default:
return false;
@@ -9509,7 +9505,10 @@ static void processTypeAttrs(TypeProcessingState &state, QualType &type,
break;
}
- COUNTED_BY_TYPE_ATTRS_CASELIST: {
+ case ParsedAttr::AT_CountedBy:
+ case ParsedAttr::AT_CountedByOrNull:
+ case ParsedAttr::AT_SizedBy:
+ case ParsedAttr::AT_SizedByOrNull: {
DeclaratorContext Ctx = state.getDeclarator().getContext();
bool OnParam = Ctx == DeclaratorContext::Prototype ||
Ctx == DeclaratorContext::ObjCParameter ||
More information about the llvm-branch-commits
mailing list