[llvm-branch-commits] [clang] [BoundsSafety] Support the counted_by family on function parameters (PR #244628)

Mohammed Ashraf via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Fri Nov 20 07:48:19 PST 2026


https://github.com/Holo-xy created https://github.com/llvm/llvm-project/pull/244628

Allow counted_by, sized_by, and their _or_null variants on function parameters. This covers the non-late-parsed path: the count is parsed where it is written, so it must refer to an earlier parameter. With -fexperimental-late-parse-attributes, a count written after the declarator is parsed at the end of the parameter list.

  - The count must name a parameter of the function, or of an enclosing
    function declarator.
  - Counts on K&R parameter declarations are ignored with a warning.
  - Objective-C method parameters are checked the same way. A count can't
    name the method's own parameters yet, because they are declared only
    after the whole selector is parsed.
  - Array parameters, out parameters and dereferenced counts are not
    supported yet.

The checks that the count is an integer and a plain reference to a
declaration are shared with fields.

CodeGen does not use parameter counts yet, either for -fsanitize=array-bounds checks
 or for __builtin_dynamic_object_size.

Based on #233582. This is the first of four PRs split out of #230538.


>From 49e8f7a9640bfa3d71fdb97387b295d7878c96b4 Mon Sep 17 00:00:00 2001
From: Holo-xy <mohammedashraf4599 at gmail.com>
Date: Fri, 20 Nov 2026 15:17:53 +0200
Subject: [PATCH 1/2] [BoundsSafety] Support the counted_by family on function
 parameters

Allow counted_by, sized_by and their _or_null variants on function
parameters. The count is parsed where it is written, so it names a
parameter declared before the annotated one. With
-fexperimental-late-parse-attributes, a count written after the
declarator is parsed at the end of the parameter list.

  - The count must name a parameter of the function, or of an enclosing
    function declarator.
  - Counts on K&R parameter declarations are dropped.
  - Objective-C method parameters are checked the same way.
  - Array parameters, out parameters and dereferenced counts are not
    supported yet.

The checks that the count is an integer and a plain reference to a
declaration are shared with fields.

CodeGen does not use parameter counts yet: they bound neither
-fsanitize=array-bounds nor __builtin_dynamic_object_size.
---
 clang/include/clang/Basic/Attr.td             |  8 +-
 .../clang/Basic/DiagnosticSemaKinds.td        |  2 +
 clang/include/clang/Sema/Sema.h               |  7 ++
 clang/lib/Sema/SemaBoundsSafety.cpp           | 64 ++++++++++----
 clang/lib/Sema/SemaDeclAttr.cpp               | 27 +++++-
 clang/lib/Sema/SemaType.cpp                   | 33 ++++++--
 .../AST/attr-counted-by-function-params.c     | 28 +++++++
 .../CodeGen/attr-counted-by-function-params.c | 25 ++++++
 .../Sema/attr-counted-by-function-params.c    | 84 +++++++++++++++++++
 .../attr-counted-by-std-syntax-on-chunk.c     |  9 +-
 .../SemaObjC/attr-counted-by-method-params.m  | 15 ++++
 11 files changed, 272 insertions(+), 30 deletions(-)
 create mode 100644 clang/test/AST/attr-counted-by-function-params.c
 create mode 100644 clang/test/CodeGen/attr-counted-by-function-params.c
 create mode 100644 clang/test/Sema/attr-counted-by-function-params.c
 create mode 100644 clang/test/SemaObjC/attr-counted-by-method-params.m

diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td
index 5de5059cc18c0e..9bc093173c230f 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2713,7 +2713,7 @@ def TypeNullUnspecified : TypeAttr {
 
 def CountedBy : DeclOrTypeAttr {
   let Spellings = [Clang<"counted_by">];
-  let Subjects = SubjectList<[Field], ErrorDiag>;
+  let Subjects = SubjectList<[Field, ParmVar], ErrorDiag>;
   let Args = [ExprArgument<"Count">, IntArgument<"NestedLevel", 1>];
   let LateParsed = LateAttrParseExperimentalExt;
   let ParseArgumentsAsUnevaluated = 1;
@@ -2723,7 +2723,7 @@ def CountedBy : DeclOrTypeAttr {
 
 def CountedByOrNull : DeclOrTypeAttr {
   let Spellings = [Clang<"counted_by_or_null">];
-  let Subjects = SubjectList<[Field], ErrorDiag>;
+  let Subjects = SubjectList<[Field, ParmVar], ErrorDiag>;
   let Args = [ExprArgument<"Count">, IntArgument<"NestedLevel", 1>];
   let LateParsed = LateAttrParseExperimentalExt;
   let ParseArgumentsAsUnevaluated = 1;
@@ -2746,7 +2746,7 @@ def PointerFieldProtection : DeclOrTypeAttr {
 
 def SizedBy : DeclOrTypeAttr {
   let Spellings = [Clang<"sized_by">];
-  let Subjects = SubjectList<[Field], ErrorDiag>;
+  let Subjects = SubjectList<[Field, ParmVar], ErrorDiag>;
   let Args = [ExprArgument<"Size">, IntArgument<"NestedLevel", 1>];
   let LateParsed = LateAttrParseExperimentalExt;
   let ParseArgumentsAsUnevaluated = 1;
@@ -2756,7 +2756,7 @@ def SizedBy : DeclOrTypeAttr {
 
 def SizedByOrNull : DeclOrTypeAttr {
   let Spellings = [Clang<"sized_by_or_null">];
-  let Subjects = SubjectList<[Field], ErrorDiag>;
+  let Subjects = SubjectList<[Field, ParmVar], ErrorDiag>;
   let Args = [ExprArgument<"Size">, IntArgument<"NestedLevel", 1>];
   let LateParsed = LateAttrParseExperimentalExt;
   let ParseArgumentsAsUnevaluated = 1;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index b7d0c1d9b96c5b..18f12697424226 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7210,6 +7210,8 @@ def err_counted_by_attr_refer_to_itself : Error<
   "'counted_by' cannot refer to the flexible array member %0">;
 def err_count_attr_must_be_in_structure : Error<
   "field %0 in '%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}1' not inside structure">;
+def err_count_attr_refer_to_non_param : Error<
+  "count expression in function declaration may only reference function parameters">;
 def err_count_attr_argument_not_integer : Error<
   "'%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}0' requires a non-boolean integer type argument">;
 def err_count_attr_only_support_simple_decl_reference : Error<
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 8f49db399f9471..9cb1bd877edf89 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2636,6 +2636,13 @@ class Sema final : public SemaBase {
   bool ActOnLateParsedTypeAttrArgument(BoundsAttributedType *BATy,
                                        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.
+  ///
+  /// \returns false iff semantically valid.
+  bool CheckCountedByAttrOnParam(QualType ParamTy, Expr *E, bool CountInBytes,
+                                 bool OrNull);
+
   /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
   /// `__counted_by_or_null` pointer type \param LHSTy.
   ///
diff --git a/clang/lib/Sema/SemaBoundsSafety.cpp b/clang/lib/Sema/SemaBoundsSafety.cpp
index 89e91c51e1aa38..91452c8db27158 100644
--- a/clang/lib/Sema/SemaBoundsSafety.cpp
+++ b/clang/lib/Sema/SemaBoundsSafety.cpp
@@ -271,6 +271,26 @@ bool Sema::ValidateBoundsAttrTypeForTypePosition(
   return true;
 }
 
+/// 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) {
+  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) {
+    S.Diag(E->getBeginLoc(),
+           diag::err_count_attr_only_support_simple_decl_reference)
+        << Kind << E->getSourceRange();
+    return nullptr;
+  }
+  return DRE->getDecl();
+}
+
 bool Sema::CheckCountedByAttrInRecord(const DeclContext *DC, QualType Ty,
                                       Expr *E, SourceLocation Loc,
                                       SourceRange Range, bool CountInBytes,
@@ -294,23 +314,11 @@ bool Sema::CheckCountedByAttrInRecord(const DeclContext *DC, QualType Ty,
     return true;
   }
 
-  // Validate the expression type
-  if (!E->getType()->isIntegerType() || E->getType()->isBooleanType()) {
-    Diag(E->getBeginLoc(), diag::err_count_attr_argument_not_integer)
-        << Kind << E->getSourceRange();
+  ValueDecl *CountDecl = checkCountRefersToDecl(*this, E, Kind);
+  if (!CountDecl)
     return true;
-  }
-
-  auto *DRE = dyn_cast<DeclRefExpr>(E);
-  if (!DRE) {
-    Diag(E->getBeginLoc(),
-         diag::err_count_attr_only_support_simple_decl_reference)
-        << Kind << E->getSourceRange();
-    return true;
-  }
 
   // Validate count field references
-  auto *CountDecl = DRE->getDecl();
   FieldDecl *CountFD = dyn_cast<FieldDecl>(CountDecl);
   if (auto *IFD = dyn_cast<IndirectFieldDecl>(CountDecl)) {
     CountFD = IFD->getAnonField();
@@ -373,6 +381,34 @@ bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
                                     CountInBytes, OrNull);
 }
 
+bool Sema::CheckCountedByAttrOnParam(QualType ParamTy, Expr *E,
+                                     bool CountInBytes, bool OrNull) {
+  // An invalid count was already diagnosed.
+  if (E->containsErrors())
+    return true;
+
+  // FIXME: Support array parameters. The count has to move to the pointer
+  // that the array decays to.
+  if (ParamTy->isArrayType()) {
+    Diag(E->getBeginLoc(),
+         diag::err_counted_by_attr_on_array_not_flexible_array_member);
+    return true;
+  }
+
+  const unsigned Kind = getCountAttrKind(CountInBytes, OrNull);
+  ValueDecl *CountDecl = checkCountRefersToDecl(*this, E, Kind);
+  if (!CountDecl)
+    return true;
+
+  // The parameters of an enclosing function declarator are in scope too.
+  if (!isa<ParmVarDecl>(CountDecl)) {
+    Diag(E->getBeginLoc(), diag::err_count_attr_refer_to_non_param)
+        << E->getSourceRange();
+    return true;
+  }
+  return false;
+}
+
 static void EmitIncompleteCountedByPointeeNotes(Sema &S,
                                                 const CountAttributedType *CATy,
                                                 NamedDecl *IncompleteTyDecl) {
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 7337a88948b286..89ff88e425f08a 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -7122,8 +7122,33 @@ static void handleCountedByAttrField(Sema &S, Decl *D, const ParsedAttr &AL) {
   if (!CountExpr)
     return;
 
-  auto *FD = cast<FieldDecl>(D);
   Sema::BoundsAttrFlags Flags = Sema::BoundsAttrFlags::get(AL.getKind());
+
+  // A parameter's count written after its declarator is parsed at the end of
+  // the parameter list, before the function's type is built from the
+  // parameters' types.
+  if (auto *PVD = dyn_cast<ParmVarDecl>(D)) {
+    // An array or function parameter has decayed to a pointer by now; check
+    // it as written.
+    QualType Ty = PVD->getType();
+    if (!PVD->getOriginalType()->isPointerType())
+      Ty = PVD->getOriginalType();
+    if (!S.ValidateBoundsAttrTypeShape(Ty, AL.getLoc(), AL.getRange(), Flags,
+                                       /*AttrSpelling=*/{},
+                                       /*AllowRedecl=*/false,
+                                       /*AttrArg=*/nullptr,
+                                       /*UpdateFlags=*/false) ||
+        S.CheckCountedByAttrOnParam(Ty, CountExpr, Flags.CountInBytes,
+                                    Flags.OrNull))
+      return;
+    QualType CAT = S.BuildCountAttributedArrayOrPointerType(
+        PVD->getType(), CountExpr, Flags.CountInBytes, Flags.OrNull);
+    if (!CAT.isNull())
+      PVD->setType(CAT);
+    return;
+  }
+
+  auto *FD = cast<FieldDecl>(D);
   if (!S.ValidateBoundsAttrTypeShape(FD->getType(), AL.getLoc(), AL.getRange(),
                                      Flags, /*AttrSpelling=*/{},
                                      /*AllowRedecl=*/false, /*AttrArg=*/nullptr,
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 33d0e45f604e56..45f89efd0210a9 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -9136,7 +9136,12 @@ static void HandleCountedByAttrOnType(TypeProcessingState &State,
   if (!CountExpr)
     return;
 
+  // Counts are not supported on K&R parameter declarations, which C23
+  // removed; drop the count.
   const Declarator &D = State.getDeclarator();
+  if (D.getContext() == DeclaratorContext::KNRTypeList)
+    return;
+
   unsigned chunkIndex = State.getCurrentChunkIndex();
 
   Sema::BoundsAttrFlags Flags;
@@ -9161,6 +9166,16 @@ static void HandleCountedByAttrOnType(TypeProcessingState &State,
     }
   }
 
+  // A parameter's count is checked before the type is built, and dropped if
+  // invalid.
+  if ((D.getContext() == DeclaratorContext::Prototype ||
+       D.getContext() == DeclaratorContext::ObjCParameter) &&
+      S.CheckCountedByAttrOnParam(CurType, CountExpr, Flags.CountInBytes,
+                                  Flags.OrNull)) {
+    Attr.setInvalid();
+    return;
+  }
+
   QualType NewType = S.BuildCountAttributedArrayOrPointerType(
       CurType, CountExpr, Flags.CountInBytes, Flags.OrNull);
   if (NewType.isNull()) {
@@ -9444,18 +9459,22 @@ static void processTypeAttrs(TypeProcessingState &state, QualType &type,
     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 ||
+                     Ctx == DeclaratorContext::KNRTypeList;
       // FIXME: Only the GNU spelling is late-parsed, and the late-parsing path
       // hasn't been switched to the new mechanism to support type-position
       // attributes yet. Leave a late-parsed one to declaration attribute
-      // processing.
+      // processing. A parameter's is parsed where it is written.
       if (state.getSema().getLangOpts().ExperimentalLateParseAttributes &&
-          attr.isGNUAttribute())
+          attr.isGNUAttribute() && !OnParam)
         break;
-      // The attribute only applies to fields for now. Leave it to declaration
-      // attribute processing, which diagnoses the GNU spelling. That doesn't
-      // see a [[]] one on a declarator chunk, so diagnose it here as the
-      // default case would.
-      if (state.getDeclarator().getContext() != DeclaratorContext::Member) {
+      // The attribute only applies to fields and parameters for now. Leave it
+      // to declaration attribute processing, which diagnoses the GNU spelling.
+      // That doesn't see a [[]] one on a declarator chunk, so diagnose it here
+      // as the default case would.
+      if (Ctx != DeclaratorContext::Member && !OnParam) {
         if (!attr.isGNUAttribute() && TAL == TAL_DeclChunk) {
           state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
               << attr << attr.isRegularKeywordAttribute();
diff --git a/clang/test/AST/attr-counted-by-function-params.c b/clang/test/AST/attr-counted-by-function-params.c
new file mode 100644
index 00000000000000..976159b924682d
--- /dev/null
+++ b/clang/test/AST/attr-counted-by-function-params.c
@@ -0,0 +1,28 @@
+// RUN: %clang_cc1 -verify %s -ast-dump | FileCheck %s
+// RUN: %clang_cc1 -fexperimental-late-parse-attributes -verify %s -ast-dump | FileCheck %s
+
+#define __counted_by(f)  __attribute__((counted_by(f)))
+
+int global_count;
+
+// CHECK: FunctionDecl {{.*}} back_ref 'void (int, int * __counted_by(count))'
+// CHECK-NEXT: ParmVarDecl {{.*}} count 'int'
+// CHECK-NEXT: ParmVarDecl {{.*}} buf 'int * __counted_by(count)':'int *'
+void back_ref(int count, int *__counted_by(count) buf);
+
+// A count written after the declarator, which late parsing parses at the end of
+// the parameter list.
+// CHECK: FunctionDecl {{.*}} trailing 'void (int, int * __counted_by(count))'
+// CHECK-NEXT: ParmVarDecl {{.*}} count 'int'
+// CHECK-NEXT: ParmVarDecl {{.*}} buf 'int * __counted_by(count)':'int *'
+void trailing(int count, int *buf __counted_by(count));
+
+// 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 count on a K&R parameter declaration is dropped.
+// CHECK: FunctionDecl {{.*}} knr 'void (int, int *)'
+// expected-warning at +1{{a function definition without a prototype is deprecated}}
+void knr(count, buf) int count; int *__counted_by(count) buf; {}
diff --git a/clang/test/CodeGen/attr-counted-by-function-params.c b/clang/test/CodeGen/attr-counted-by-function-params.c
new file mode 100644
index 00000000000000..bab6d00b376864
--- /dev/null
+++ b/clang/test/CodeGen/attr-counted-by-function-params.c
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fsanitize=array-bounds -emit-llvm -o - %s | FileCheck %s
+
+// CodeGen does not use a function parameter's count yet: unlike a field's
+// count, it bounds neither -fsanitize=array-bounds nor
+// __builtin_dynamic_object_size.
+
+#define __counted_by(f)  __attribute__((counted_by(f)))
+
+// CHECK-LABEL: define dso_local i32 @subscript(
+// CHECK-NOT:     __ubsan_handle_out_of_bounds
+// CHECK:         ret i32
+//
+// FIXME: Check the index against the count.
+int subscript(int count, int *__counted_by(count) buf, int i) {
+  return buf[i];
+}
+
+// CHECK-LABEL: define dso_local i64 @bdos(
+// CHECK-NOT:     counted_by.load
+// CHECK:         call i64 @llvm.objectsize.i64.p0(
+//
+// FIXME: Compute the object size from the count.
+unsigned long bdos(int count, int *__counted_by(count) buf) {
+  return __builtin_dynamic_object_size(buf, 0);
+}
diff --git a/clang/test/Sema/attr-counted-by-function-params.c b/clang/test/Sema/attr-counted-by-function-params.c
new file mode 100644
index 00000000000000..60ad611294cbca
--- /dev/null
+++ b/clang/test/Sema/attr-counted-by-function-params.c
@@ -0,0 +1,84 @@
+// RUN: %clang_cc1 -fsyntax-only -verify=expected,eager %s
+// RUN: %clang_cc1 -fexperimental-late-parse-attributes -fsyntax-only -verify %s
+
+// The counted_by family on a function parameter. The count is parsed where it
+// is written, so it names a parameter declared before the annotated one. With
+// late parsing, a count written after the declarator is parsed at the end of
+// the parameter list.
+
+#define __counted_by(f)  __attribute__((counted_by(f)))
+#define __counted_by_or_null(f)  __attribute__((counted_by_or_null(f)))
+#define __sized_by(f)  __attribute__((sized_by(f)))
+#define __sized_by_or_null(f)  __attribute__((sized_by_or_null(f)))
+
+typedef int *int_ptr;
+int global_count;
+
+//==============================================================================
+// Valid: the count is declared before the annotated pointer
+//==============================================================================
+
+void back_ref(int count, int *__counted_by(count) buf);
+void back_ref_or_null(int count, int *__counted_by_or_null(count) buf);
+void back_ref_sized(int count, void *__sized_by(count) buf);
+void back_ref_sized_or_null(int count, void *__sized_by_or_null(count) buf);
+
+// Two pointers may share a count, but a pointer has only one.
+void two_buffers(int count, int *__counted_by(count) a,
+                 int *__counted_by(count) b);
+// expected-error at +1{{'counted_by' attribute cannot be applied to a pointer that already has a 'counted_by' attribute}}
+void repeated(int n, int m, int *buf __counted_by(n) __counted_by(m));
+
+// Written after the declarator, or in the declaration specifiers.
+void trailing(int count, int *buf __counted_by(count));
+void declspec(int count, int_ptr __counted_by(count) buf);
+
+// The C23 spelling is checked the same way.
+void c23_spelling(int count, int *[[clang::counted_by(count)]] buf);
+
+int sum(int count, int *__counted_by(count) buf) {
+  int total = 0;
+  for (int i = 0; i < count; ++i)
+    total += buf[i];
+  return total;
+}
+
+//==============================================================================
+// The count is parsed where it is written
+//==============================================================================
+
+// expected-error at +1{{use of undeclared identifier 'count'}}
+void fwd_ref(int *__counted_by(count) buf, int count);
+
+// eager-error at +1{{use of undeclared identifier 'count'}}
+void fwd_ref_trailing(int *buf __counted_by(count), int count);
+
+//==============================================================================
+// What the count may name
+//==============================================================================
+
+// A parameter of the function, or of an enclosing function declarator.
+void inner(void (*cb)(int len, int *__counted_by(len) p));
+void outer(int n, void (*cb)(int *__counted_by(n) p));
+
+// expected-error at +1{{count expression in function declaration may only reference function parameters}}
+void not_a_param(int *__counted_by(global_count) buf);
+// expected-error at +1{{'counted_by' requires a non-boolean integer type argument}}
+void not_an_integer(float count, int *__counted_by(count) buf);
+// expected-error at +1{{'counted_by' argument must be a simple declaration reference}}
+void not_a_reference(int count, int *__counted_by(count + 1) buf);
+
+//==============================================================================
+// Not supported yet
+//==============================================================================
+
+// expected-error at +1{{'counted_by' on arrays only applies to C99 flexible array members}}
+void array(int count, int arr[] __counted_by(count));
+
+// expected-error at +1{{'counted_by' attribute on nested pointer type is not allowed}}
+void out(int count, int *__counted_by(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' attribute on a function return type is not yet supported}}
+void cb_return(int len, int *__counted_by(len) (*cb)(void));
diff --git a/clang/test/Sema/attr-counted-by-std-syntax-on-chunk.c b/clang/test/Sema/attr-counted-by-std-syntax-on-chunk.c
index de34a2fb27d5ea..495e1ab6c90d80 100644
--- a/clang/test/Sema/attr-counted-by-std-syntax-on-chunk.c
+++ b/clang/test/Sema/attr-counted-by-std-syntax-on-chunk.c
@@ -4,11 +4,12 @@
 // RUN: not %clang_cc1 -std=c23 -fsyntax-only -fexperimental-late-parse-attributes -ast-dump %s 2>/dev/null | FileCheck %s
 
 // A [[]] counted_by-family attribute on a declarator chunk is a type
-// attribute. It applies to a field's pointer, and is rejected rather than
-// dropped elsewhere. It isn't late-parsed, so the late-parsing mode handles it
-// the same way.
+// attribute. It applies to a field's or a parameter's pointer, and is rejected
+// rather than dropped elsewhere. It isn't late-parsed, so the late-parsing mode
+// handles it the same way.
 
-void f(int n, int *[[clang::counted_by(n)]] p); // expected-error{{'clang::counted_by' attribute cannot be applied to types}}
+// CHECK: ParmVarDecl {{.*}} p 'int * __counted_by(n)':'int *'
+void f(int n, int *[[clang::counted_by(n)]] p);
 
 int gn;
 int *[[clang::sized_by(gn)]] gp; // expected-error{{'clang::sized_by' attribute cannot be applied to types}}
diff --git a/clang/test/SemaObjC/attr-counted-by-method-params.m b/clang/test/SemaObjC/attr-counted-by-method-params.m
new file mode 100644
index 00000000000000..efccacbc27553d
--- /dev/null
+++ b/clang/test/SemaObjC/attr-counted-by-method-params.m
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+#define __counted_by(f)  __attribute__((counted_by(f)))
+
+int global_count;
+
+// An Objective-C method parameter's count is checked like a function
+// parameter's.
+ at interface I
+// expected-error at +1{{count expression in function declaration may only reference function parameters}}
+- (void)global:(int *__counted_by(global_count))buf;
+// The method's earlier parameters are not in scope yet.
+// expected-error at +1{{use of undeclared identifier 'n'}}
+- (void)count:(int)n buf:(int *__counted_by(n))buf;
+ at end

>From 59247598b6cb346c86cfd1014419be6cecbfda85 Mon Sep 17 00:00:00 2001
From: Holo-xy <mohammedashraf4599 at gmail.com>
Date: Fri, 20 Nov 2026 15:18:02 +0200
Subject: [PATCH 2/2] [BoundsSafety] Address review feedback

- Warn when a count on a K&R parameter declaration is ignored.
- Test each case for all four attributes, and add nested pointer tests.
- Add Objective-C positive tests, and a FIXME for a count that names a
  method's own parameter.
---
 clang/lib/Sema/SemaType.cpp                   |   7 +-
 .../AST/attr-counted-by-function-params.c     |   5 +-
 .../Sema/attr-counted-by-function-params.c    | 141 +++++++++++++++++-
 .../SemaObjC/attr-counted-by-method-params.m  |  16 +-
 4 files changed, 158 insertions(+), 11 deletions(-)

diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 45f89efd0210a9..3f6040de8bb2ed 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -9137,10 +9137,13 @@ static void HandleCountedByAttrOnType(TypeProcessingState &State,
     return;
 
   // Counts are not supported on K&R parameter declarations, which C23
-  // removed; drop the count.
+  // removed; ignore the count.
   const Declarator &D = State.getDeclarator();
-  if (D.getContext() == DeclaratorContext::KNRTypeList)
+  if (D.getContext() == DeclaratorContext::KNRTypeList) {
+    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr;
+    Attr.setInvalid();
     return;
+  }
 
   unsigned chunkIndex = State.getCurrentChunkIndex();
 
diff --git a/clang/test/AST/attr-counted-by-function-params.c b/clang/test/AST/attr-counted-by-function-params.c
index 976159b924682d..c53afd81b396da 100644
--- a/clang/test/AST/attr-counted-by-function-params.c
+++ b/clang/test/AST/attr-counted-by-function-params.c
@@ -22,7 +22,8 @@ void trailing(int count, int *buf __counted_by(count));
 // 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 count on a K&R parameter declaration is dropped.
+// A count on a K&R parameter declaration is ignored.
 // CHECK: FunctionDecl {{.*}} knr 'void (int, int *)'
-// expected-warning at +1{{a function definition without a prototype is deprecated}}
+// expected-warning at +2{{a function definition without a prototype is deprecated}}
+// expected-warning at +1{{'counted_by' attribute ignored}}
 void knr(count, buf) int count; int *__counted_by(count) buf; {}
diff --git a/clang/test/Sema/attr-counted-by-function-params.c b/clang/test/Sema/attr-counted-by-function-params.c
index 60ad611294cbca..ba7bdeaaa87781 100644
--- a/clang/test/Sema/attr-counted-by-function-params.c
+++ b/clang/test/Sema/attr-counted-by-function-params.c
@@ -12,6 +12,7 @@
 #define __sized_by_or_null(f)  __attribute__((sized_by_or_null(f)))
 
 typedef int *int_ptr;
+typedef void *void_ptr;
 int global_count;
 
 //==============================================================================
@@ -23,18 +24,39 @@ void back_ref_or_null(int count, int *__counted_by_or_null(count) buf);
 void back_ref_sized(int count, void *__sized_by(count) buf);
 void back_ref_sized_or_null(int count, void *__sized_by_or_null(count) buf);
 
-// Two pointers may share a count, but a pointer has only one.
+// Two pointers may share a count.
 void two_buffers(int count, int *__counted_by(count) a,
                  int *__counted_by(count) b);
-// expected-error at +1{{'counted_by' attribute cannot be applied to a pointer that already has a 'counted_by' attribute}}
-void repeated(int n, int m, int *buf __counted_by(n) __counted_by(m));
-
-// Written after the declarator, or in the declaration specifiers.
+void two_buffers_or_null(int count, int *__counted_by_or_null(count) a,
+                         int *__counted_by_or_null(count) b);
+void two_buffers_sized(int count, void *__sized_by(count) a,
+                       void *__sized_by(count) b);
+void two_buffers_sized_or_null(int count, void *__sized_by_or_null(count) a,
+                               void *__sized_by_or_null(count) b);
+
+// Written after the declarator.
 void trailing(int count, int *buf __counted_by(count));
+void trailing_or_null(int count, int *buf __counted_by_or_null(count));
+void trailing_sized(int count, void *buf __sized_by(count));
+void trailing_sized_or_null(int count, void *buf __sized_by_or_null(count));
+
+// Written in the declaration specifiers.
 void declspec(int count, int_ptr __counted_by(count) buf);
+void declspec_or_null(int count, int_ptr __counted_by_or_null(count) buf);
+void declspec_sized(int count, void_ptr __sized_by(count) buf);
+void declspec_sized_or_null(int count, void_ptr __sized_by_or_null(count) buf);
 
 // The C23 spelling is checked the same way.
 void c23_spelling(int count, int *[[clang::counted_by(count)]] buf);
+void c23_spelling_or_null(int count, int *[[clang::counted_by_or_null(count)]] buf);
+void c23_spelling_sized(int count, void *[[clang::sized_by(count)]] buf);
+void c23_spelling_sized_or_null(int count, void *[[clang::sized_by_or_null(count)]] buf);
+
+// A count on the outer pointer of a pointer to pointer.
+void nested_outer(int count, int **__counted_by(count) buf);
+void nested_outer_or_null(int count, int **__counted_by_or_null(count) buf);
+void nested_outer_sized(int count, int **__sized_by(count) buf);
+void nested_outer_sized_or_null(int count, int **__sized_by_or_null(count) buf);
 
 int sum(int count, int *__counted_by(count) buf) {
   int total = 0;
@@ -43,15 +65,40 @@ int sum(int count, int *__counted_by(count) buf) {
   return total;
 }
 
+//==============================================================================
+// A pointer has only one count
+//==============================================================================
+
+// expected-error at +1{{'counted_by' attribute cannot be applied to a pointer that already has a 'counted_by' attribute}}
+void repeated(int n, int m, int *buf __counted_by(n) __counted_by(m));
+// expected-error at +1{{'counted_by_or_null' attribute cannot be applied to a pointer that already has a 'counted_by_or_null' attribute}}
+void repeated_or_null(int n, int m, int *buf __counted_by_or_null(n) __counted_by_or_null(m));
+// expected-error at +1{{'sized_by' attribute cannot be applied to a pointer that already has a 'sized_by' attribute}}
+void repeated_sized(int n, int m, void *buf __sized_by(n) __sized_by(m));
+// expected-error at +1{{'sized_by_or_null' attribute cannot be applied to a pointer that already has a 'sized_by_or_null' attribute}}
+void repeated_sized_or_null(int n, int m, void *buf __sized_by_or_null(n) __sized_by_or_null(m));
+
 //==============================================================================
 // The count is parsed where it is written
 //==============================================================================
 
 // expected-error at +1{{use of undeclared identifier 'count'}}
 void fwd_ref(int *__counted_by(count) buf, int count);
+// expected-error at +1{{use of undeclared identifier 'count'}}
+void fwd_ref_or_null(int *__counted_by_or_null(count) buf, int count);
+// expected-error at +1{{use of undeclared identifier 'count'}}
+void fwd_ref_sized(void *__sized_by(count) buf, int count);
+// expected-error at +1{{use of undeclared identifier 'count'}}
+void fwd_ref_sized_or_null(void *__sized_by_or_null(count) buf, int count);
 
 // eager-error at +1{{use of undeclared identifier 'count'}}
 void fwd_ref_trailing(int *buf __counted_by(count), int count);
+// eager-error at +1{{use of undeclared identifier 'count'}}
+void fwd_ref_trailing_or_null(int *buf __counted_by_or_null(count), int count);
+// eager-error at +1{{use of undeclared identifier 'count'}}
+void fwd_ref_trailing_sized(void *buf __sized_by(count), int count);
+// eager-error at +1{{use of undeclared identifier 'count'}}
+void fwd_ref_trailing_sized_or_null(void *buf __sized_by_or_null(count), int count);
 
 //==============================================================================
 // What the count may name
@@ -59,14 +106,40 @@ void fwd_ref_trailing(int *buf __counted_by(count), int count);
 
 // A parameter of the function, or of an enclosing function declarator.
 void inner(void (*cb)(int len, int *__counted_by(len) p));
+void inner_or_null(void (*cb)(int len, int *__counted_by_or_null(len) p));
+void inner_sized(void (*cb)(int len, void *__sized_by(len) p));
+void inner_sized_or_null(void (*cb)(int len, void *__sized_by_or_null(len) p));
 void outer(int n, void (*cb)(int *__counted_by(n) p));
+void outer_or_null(int n, void (*cb)(int *__counted_by_or_null(n) p));
+void outer_sized(int n, void (*cb)(void *__sized_by(n) p));
+void outer_sized_or_null(int n, void (*cb)(void *__sized_by_or_null(n) p));
 
 // expected-error at +1{{count expression in function declaration may only reference function parameters}}
 void not_a_param(int *__counted_by(global_count) buf);
+// expected-error at +1{{count expression in function declaration may only reference function parameters}}
+void not_a_param_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 not_a_param_sized(void *__sized_by(global_count) buf);
+// expected-error at +1{{count expression in function declaration may only reference function parameters}}
+void not_a_param_sized_or_null(void *__sized_by_or_null(global_count) buf);
+
 // expected-error at +1{{'counted_by' requires a non-boolean integer type argument}}
 void not_an_integer(float count, int *__counted_by(count) buf);
+// expected-error at +1{{'counted_by_or_null' requires a non-boolean integer type argument}}
+void not_an_integer_or_null(float count, int *__counted_by_or_null(count) buf);
+// expected-error at +1{{'sized_by' requires a non-boolean integer type argument}}
+void not_an_integer_sized(float count, void *__sized_by(count) buf);
+// expected-error at +1{{'sized_by_or_null' requires a non-boolean integer type argument}}
+void not_an_integer_sized_or_null(float count, void *__sized_by_or_null(count) buf);
+
 // expected-error at +1{{'counted_by' argument must be a simple declaration reference}}
 void not_a_reference(int count, int *__counted_by(count + 1) buf);
+// expected-error at +1{{'counted_by_or_null' argument must be a simple declaration reference}}
+void not_a_reference_or_null(int count, int *__counted_by_or_null(count + 1) buf);
+// expected-error at +1{{'sized_by' argument must be a simple declaration reference}}
+void not_a_reference_sized(int count, void *__sized_by(count + 1) buf);
+// expected-error at +1{{'sized_by_or_null' argument must be a simple declaration reference}}
+void not_a_reference_sized_or_null(int count, void *__sized_by_or_null(count + 1) buf);
 
 //==============================================================================
 // Not supported yet
@@ -74,11 +147,69 @@ void not_a_reference(int count, int *__counted_by(count + 1) buf);
 
 // expected-error at +1{{'counted_by' on arrays only applies to C99 flexible array members}}
 void array(int count, int arr[] __counted_by(count));
+// expected-error at +1{{'counted_by_or_null' only applies to pointers; did you mean to use 'counted_by'?}}
+void array_or_null(int count, int arr[] __counted_by_or_null(count));
+// expected-error at +1{{'sized_by' only applies to pointers; did you mean to use 'counted_by'?}}
+void array_sized(int count, int arr[] __sized_by(count));
+// expected-error at +1{{'sized_by_or_null' only applies to pointers; did you mean to use 'counted_by'?}}
+void array_sized_or_null(int count, int arr[] __sized_by_or_null(count));
 
 // expected-error at +1{{'counted_by' attribute on nested pointer type is not allowed}}
 void out(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);
+// expected-error at +1{{'sized_by' attribute on nested pointer type is not allowed}}
+void out_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.
+// expected-error at +1{{'counted_by' attribute on nested pointer type is not allowed}}
+void nested_inner(int *__counted_by(global_count) *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);
+// expected-error at +1{{'sized_by' attribute on nested pointer type is not allowed}}
+void nested_inner_sized(void *__sized_by(global_count) *buf);
+// expected-error at +1{{'sized_by_or_null' attribute on nested pointer type is not allowed}}
+void nested_inner_sized_or_null(void *__sized_by_or_null(global_count) *buf);
+
+// A count on the outer pointer still names a parameter.
+// 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}}
+void nested_outer_global_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_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);
+
+// expected-warning at +2{{a function definition without a prototype is deprecated}}
+// expected-warning at +1{{'counted_by' attribute ignored}}
+void knr(count, buf) int count; int *__counted_by(count) buf; {}
+// expected-warning at +2{{a function definition without a prototype is deprecated}}
+// expected-warning at +1{{'counted_by_or_null' attribute ignored}}
+void knr_or_null(count, buf) int count; int *__counted_by_or_null(count) buf; {}
+// expected-warning at +2{{a function definition without a prototype is deprecated}}
+// expected-warning at +1{{'sized_by' attribute ignored}}
+void knr_sized(count, buf) int count; void *__sized_by(count) buf; {}
+// expected-warning at +2{{a function definition without a prototype is deprecated}}
+// expected-warning at +1{{'sized_by_or_null' attribute ignored}}
+void knr_sized_or_null(count, buf) int count; void *__sized_by_or_null(count) buf; {}
 
 // expected-error at +1{{'counted_by' attribute on a function return type is not yet supported}}
 void cb_return(int len, int *__counted_by(len) (*cb)(void));
+// expected-error at +1{{'counted_by_or_null' attribute on a function return type is not yet supported}}
+void cb_return_or_null(int len, int *__counted_by_or_null(len) (*cb)(void));
+// expected-error at +1{{'sized_by' attribute on a function return type is not yet supported}}
+void cb_return_sized(int len, void *__sized_by(len) (*cb)(void));
+// expected-error at +1{{'sized_by_or_null' attribute on a function return type is not yet supported}}
+void cb_return_sized_or_null(int len, void *__sized_by_or_null(len) (*cb)(void));
diff --git a/clang/test/SemaObjC/attr-counted-by-method-params.m b/clang/test/SemaObjC/attr-counted-by-method-params.m
index efccacbc27553d..30df3fc6750cef 100644
--- a/clang/test/SemaObjC/attr-counted-by-method-params.m
+++ b/clang/test/SemaObjC/attr-counted-by-method-params.m
@@ -1,15 +1,27 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -fblocks -verify %s
 
 #define __counted_by(f)  __attribute__((counted_by(f)))
+#define __counted_by_or_null(f)  __attribute__((counted_by_or_null(f)))
+#define __sized_by(f)  __attribute__((sized_by(f)))
+#define __sized_by_or_null(f)  __attribute__((sized_by_or_null(f)))
 
 int global_count;
 
 // An Objective-C method parameter's count is checked like a function
 // parameter's.
 @interface I
+// A count inside a callback or block parameter names that parameter's own
+// parameters.
+- (void)callback:(void (*)(int len, int *__counted_by(len) p))cb;
+- (void)callback_or_null:(void (*)(int len, int *__counted_by_or_null(len) p))cb;
+- (void)callback_sized:(void (*)(int len, void *__sized_by(len) p))cb;
+- (void)callback_sized_or_null:(void (*)(int len, void *__sized_by_or_null(len) p))cb;
+- (void)block:(void (^)(int len, int *__counted_by(len) p))blk;
+
 // expected-error at +1{{count expression in function declaration may only reference function parameters}}
 - (void)global:(int *__counted_by(global_count))buf;
-// The method's earlier parameters are not in scope yet.
+// FIXME: Accept this. The method's parameters are declared only after all of
+// them are parsed, so 'n' is not in scope yet.
 // expected-error at +1{{use of undeclared identifier 'n'}}
 - (void)count:(int)n buf:(int *__counted_by(n))buf;
 @end



More information about the llvm-branch-commits mailing list