[clang] [BoundsSafety] Support counted by on function params (PR #213305)
Mohammed Ashraf via cfe-commits
cfe-commits at lists.llvm.org
Fri Sep 4 09:52:58 PDT 2026
https://github.com/Holo-xy updated https://github.com/llvm/llvm-project/pull/213305
>From 45c5dd3400bf6c8eef0504b7efbb63de610486aa Mon Sep 17 00:00:00 2001
From: Yeoul Na <yeoul_na at apple.com>
Date: Mon, 13 Jul 2026 16:05:22 -0700
Subject: [PATCH 1/9] [BoundsSafety][NFC] Introduce logic to replace the
LateParsedAttrType placeholder with CountAttributedType
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Split from #179612 alongside #204125 (LateParsedAttrType AST node).
Adds the resolver logic that walks a `FieldDecl`'s type, finds any
`LateParsedAttrType` placeholder inside it, parses the cached attribute
tokens, and replaces the placeholder with a concrete
`CountAttributedType`. Purely NFC: nothing on this commit creates a
`LateParsedAttrType` placeholder in the AST, so the resolver never
fires — the producer (parser dispatch + `ActOnLateParsedTypeAttr`
wire-up) lands in follow-up commits.
Sold as an NFC to keep the review of the mechanism halved.
Follow-up PR will add the end-to-end wire-up that populates
`LateParsedAttrType` placeholders so this resolver can start firing.
---
clang/include/clang/AST/DependenceFlags.h | 9 +-
clang/include/clang/AST/TypeBase.h | 10 +-
.../clang/Basic/DiagnosticSemaKinds.td | 3 +
clang/include/clang/Sema/Sema.h | 40 ++++
clang/lib/Sema/SemaDecl.cpp | 202 +++++++++++++++++-
5 files changed, 260 insertions(+), 4 deletions(-)
diff --git a/clang/include/clang/AST/DependenceFlags.h b/clang/include/clang/AST/DependenceFlags.h
index c4395259f0758..0a5dd53f7696a 100644
--- a/clang/include/clang/AST/DependenceFlags.h
+++ b/clang/include/clang/AST/DependenceFlags.h
@@ -69,12 +69,17 @@ struct TypeDependenceScope {
/// yields an error type.
Error = 16,
+ /// Whether this type contains a placeholder for a type attribute
+ /// awaiting late parsing, e.g. `int *__counted_by(count)` where
+ /// `count` is a later field of the same struct.
+ LateParsedAttr = 32,
+
None = 0,
- All = 31,
+ All = 63,
DependentInstantiation = Dependent | Instantiation,
- LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/Error)
+ LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/LateParsedAttr)
};
};
using TypeDependence = TypeDependenceScope::TypeDependence;
diff --git a/clang/include/clang/AST/TypeBase.h b/clang/include/clang/AST/TypeBase.h
index 530bfe72dac2b..1dbcadbfde574 100644
--- a/clang/include/clang/AST/TypeBase.h
+++ b/clang/include/clang/AST/TypeBase.h
@@ -2866,6 +2866,13 @@ class alignas(TypeAlignment) Type : public ExtQualsTypeCommonBase {
return getDependence() & TypeDependence::VariablyModified;
}
+ /// Whether this type contains a placeholder for a type attribute awaiting
+ /// late parsing, e.g. `int *__counted_by(count)` where `count` is a later
+ /// field of the same struct.
+ bool hasLateParsedAttr() const {
+ return getDependence() & TypeDependence::LateParsedAttr;
+ }
+
/// Whether this type involves a variable-length array type
/// with a definite size.
bool hasSizedVLAType() const;
@@ -3565,7 +3572,8 @@ class LateParsedAttrType : public Type {
LateParsedAttrType(QualType Wrapped, QualType Canon,
LateParsedTypeAttribute *Attr)
- : Type(LateParsedAttr, Canon, Wrapped->getDependence()),
+ : Type(LateParsedAttr, Canon,
+ TypeDependence::LateParsedAttr | Wrapped->getDependence()),
WrappedTy(Wrapped), LateParsedTypeAttr(Attr) {}
public:
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 01527e87c903f..db118c699ce02 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7245,6 +7245,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/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 778c1a2f5c427..d8081e0095d09 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -142,6 +142,8 @@ class InitializationKind;
class InitializationSequence;
class InitializedEntity;
enum class LangAS : unsigned int;
+struct LateParsedAttribute;
+struct LateParsedTypeAttribute;
class LocalInstantiationScope;
class LookupResult;
class MangleNumberingContext;
@@ -1360,6 +1362,11 @@ class Sema final : public SemaBase {
OpaqueParser = P;
}
+ /// Callback type to parse and consume a LateParsedTypeAttribute. Used as an
+ /// argument to ProcessLateParsedTypeAttributes.
+ typedef void ParseLateParsedTypeAttributeCB(LateParsedTypeAttribute *LTA,
+ ParsedAttributes *OutAttrs);
+
/// Callback to the parser to parse a type expressed as a string.
std::function<TypeResult(StringRef, StringRef, SourceLocation)>
ParseTypeFromStringCallback;
@@ -4428,6 +4435,39 @@ class Sema final : public SemaBase {
ArrayRef<Decl *> Fields, SourceLocation LBrac,
SourceLocation RBrac, const ParsedAttributesView &AttrList);
+ /// Resolve placeholders left in field types by late-parsed type
+ /// attributes, now that \p EnclosingDecl's fields are all visible and
+ /// name lookup for the attribute's argument can succeed.
+ ///
+ /// Called for each record whose scope makes a previously-deferred
+ /// argument resolvable. That is usually the same record that carries
+ /// the annotated field, e.g.
+ /// \code
+ /// struct Flat {
+ /// char *__counted_by(len) p;
+ /// unsigned len; // resolved when Flat finishes parsing
+ /// };
+ /// \endcode
+ /// but the resolving record can also be an inner or outer record when
+ /// the count and the annotated field are separated by nested records:
+ /// \code
+ /// struct NestedNamed {
+ /// struct {
+ /// char *__counted_by(len) p;
+ /// unsigned len; // resolved when the nested struct finishes,
+ /// } inner; // since name lookup is closed at that scope
+ /// };
+ ///
+ /// struct NestedAnon {
+ /// struct {
+ /// char *__counted_by(len) p; // len isn't in scope until
+ /// }; // the anonymous struct is
+ /// unsigned len; // flattened into NestedAnon,
+ /// }; // so resolved when it finishes
+ /// \endcode
+ void ProcessLateParsedTypeAttributes(RecordDecl *EnclosingDecl,
+ ParseLateParsedTypeAttributeCB *ParseCB);
+
/// ActOnTagStartDefinition - Invoked when we have entered the
/// scope of a tag's definition (e.g., for an enumeration, class,
/// struct, or union).
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index c46d2d780fad7..bf9c1a9dac5b0 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -10,6 +10,7 @@
//
//===----------------------------------------------------------------------===//
+#include "TreeTransform.h"
#include "TypeLocBuilder.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
@@ -17259,7 +17260,7 @@ void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
// Always attach attributes to the underlying decl.
if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
D = TD->getTemplatedDecl();
- ProcessDeclAttributeList(S, D, Attrs);
+ ProcessDeclAttributeList(S, D, Attrs, ProcessDeclAttributeOptions());
ProcessAPINotes(D);
if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
@@ -20002,6 +20003,205 @@ bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
}
+static QualType handleCountedByAttrField(Sema &S, QualType T, Decl *D,
+ const ParsedAttr &AL) {
+ if (!AL.diagnoseLangOpts(S))
+ return QualType();
+
+ assert(isa<FieldDecl>(D));
+
+ auto *CountExpr = AL.getArgAsExpr(0);
+ if (!CountExpr)
+ return QualType();
+
+ bool CountInBytes;
+ bool OrNull;
+ switch (AL.getKind()) {
+ case ParsedAttr::AT_CountedBy:
+ CountInBytes = false;
+ OrNull = false;
+ break;
+ case ParsedAttr::AT_CountedByOrNull:
+ CountInBytes = false;
+ OrNull = true;
+ break;
+ case ParsedAttr::AT_SizedBy:
+ CountInBytes = true;
+ OrNull = false;
+ break;
+ case ParsedAttr::AT_SizedByOrNull:
+ CountInBytes = true;
+ OrNull = true;
+ break;
+ default:
+ llvm_unreachable("unexpected counted_by family attribute");
+ }
+
+ return S.BuildCountAttributedArrayOrPointerType(T, CountExpr, CountInBytes,
+ OrNull);
+}
+struct RebuildTypeWithLateParsedAttr
+ : TreeTransform<RebuildTypeWithLateParsedAttr> {
+ FieldDecl *FD;
+ Sema::ParseLateParsedTypeAttributeCB *ParseCallback;
+
+ /// Non-zero while transforming under a pointer or array. Used to reject
+ /// nested counted_by (e.g. `int *__counted_by(n) *p` or
+ /// `int *__counted_by(n) arr[10]`), where the resolved CountAttributedType
+ /// would sit inside another wrapper.
+ unsigned PointerOrArrayDepth = 0;
+
+ RebuildTypeWithLateParsedAttr(Sema &SemaRef, FieldDecl *FD,
+ Sema::ParseLateParsedTypeAttributeCB *ParseCB)
+ : TreeTransform(SemaRef), FD(FD), ParseCallback(ParseCB) {}
+
+ QualType TransformLateParsedAttrType(TypeLocBuilder &TLB,
+ LateParsedAttrTypeLoc TL) {
+ const LateParsedAttrType *LPA = TL.getTypePtr();
+ auto *LTA = LPA->getLateParsedAttribute();
+
+ assert(LTA && "LateParsedAttrType must have a LateParsedTypeAttribute");
+
+ AttributeFactory AF{};
+ ParsedAttributes Attrs(AF);
+
+ // Invoke the parser callback to parse and consume the cached tokens.
+ // ParseCallback is also responsible for deleting LTA.
+ assert(ParseCallback);
+ ParseCallback(LTA, &Attrs);
+
+ // Invalid argument
+ if (Attrs.empty())
+ return QualType();
+
+ assert(Attrs.size() == 1);
+ auto &AL = Attrs[0];
+
+ QualType InnerType = TransformType(TLB, TL.getInnerLoc());
+ if (InnerType.isNull()) {
+ FD->setInvalidDecl();
+ return QualType();
+ }
+
+ QualType T = handleCountedByAttrField(SemaRef, InnerType, FD, AL);
+ if (T.isNull()) {
+ AL.setInvalid();
+ FD->setInvalidDecl();
+ return QualType();
+ }
+
+ // Reject nested counted_by, e.g. `int *__counted_by(n) *p` or
+ // `int *__counted_by(n) arr[10]` — the resolved CountAttributedType
+ // must sit at the outermost level of the field's type.
+ //
+ // FIXME: In the -fbounds-safety model:
+ // - `counted_by` / `sized_by` on nested pointers is permitted only
+ // for function parameters, and only one level of nesting.
+ // - `counted_by_or_null` / `sized_by_or_null` on nested pointers is
+ // generally permitted, because it makes sense to allow such a
+ // pointer to be valid when the top-level pointer is null (the
+ // inner counted_by / sized_by simply doesn't need to hold in
+ // that case).
+ // We reject unconditionally here because this slice only covers
+ // struct fields; extending coverage will need to relax this check
+ // along those lines.
+ if (PointerOrArrayDepth > 0) {
+ SemaRef.Diag(TL.getAttrNameLoc(), diag::err_counted_by_on_nested_pointer)
+ << T->getAs<CountAttributedType>()->getKind();
+ FD->setInvalidDecl();
+ return QualType();
+ }
+
+ AL.setUsedAsTypeAttr();
+
+ TLB.push<CountAttributedTypeLoc>(T);
+ return T;
+ }
+
+ // The five overrides below only track pointer/array depth so
+ // TransformLateParsedAttrType can reject nested counted_by. Recursion,
+ // rebuild, and TypeLoc pushing are delegated to the base TreeTransform.
+
+ QualType TransformPointerType(TypeLocBuilder &TLB, PointerTypeLoc TL) {
+ ++PointerOrArrayDepth;
+ QualType Result = TreeTransform::TransformPointerType(TLB, TL);
+ --PointerOrArrayDepth;
+ if (Result.isNull())
+ FD->setInvalidDecl();
+ return Result;
+ }
+
+ QualType TransformConstantArrayType(TypeLocBuilder &TLB,
+ ConstantArrayTypeLoc TL) {
+ ++PointerOrArrayDepth;
+ QualType Result = TreeTransform::TransformConstantArrayType(TLB, TL);
+ --PointerOrArrayDepth;
+ if (Result.isNull())
+ FD->setInvalidDecl();
+ return Result;
+ }
+
+ QualType TransformIncompleteArrayType(TypeLocBuilder &TLB,
+ IncompleteArrayTypeLoc TL) {
+ ++PointerOrArrayDepth;
+ QualType Result = TreeTransform::TransformIncompleteArrayType(TLB, TL);
+ --PointerOrArrayDepth;
+ if (Result.isNull())
+ FD->setInvalidDecl();
+ return Result;
+ }
+
+ QualType TransformVariableArrayType(TypeLocBuilder &TLB,
+ VariableArrayTypeLoc TL) {
+ ++PointerOrArrayDepth;
+ QualType Result = TreeTransform::TransformVariableArrayType(TLB, TL);
+ --PointerOrArrayDepth;
+ if (Result.isNull())
+ FD->setInvalidDecl();
+ return Result;
+ }
+
+ QualType TransformDependentSizedArrayType(TypeLocBuilder &TLB,
+ DependentSizedArrayTypeLoc TL) {
+ ++PointerOrArrayDepth;
+ QualType Result = TreeTransform::TransformDependentSizedArrayType(TLB, TL);
+ --PointerOrArrayDepth;
+ if (Result.isNull())
+ FD->setInvalidDecl();
+ return Result;
+ }
+};
+
+void Sema::ProcessLateParsedTypeAttributes(
+ RecordDecl *EnclosingDecl, ParseLateParsedTypeAttributeCB *ParseCB) {
+ for (auto *I : EnclosingDecl->decls()) {
+ FieldDecl *FD = dyn_cast<FieldDecl>(I);
+ IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(I);
+ if (!FD && IFD) {
+ FD = IFD->getAnonField();
+ }
+ if (!FD || !FD->getType()->hasLateParsedAttr() ||
+ FD->getType()->isRecordType())
+ continue;
+
+ RebuildTypeWithLateParsedAttr RebuildFieldType(*this, FD, ParseCB);
+ auto *OldTSI = FD->getTypeSourceInfo();
+ auto *TSI = RebuildFieldType.TransformType(FD->getTypeSourceInfo());
+ if (TSI && TSI != OldTSI) {
+ FD->setTypeSourceInfo(TSI);
+ FD->setType(TSI->getType());
+ if (IFD) {
+ IFD->setType(TSI->getType());
+ }
+ }
+
+ if (auto *CAT = FD->getType()->getAs<CountAttributedType>()) {
+ CheckCountedByAttrOnField(FD, CAT->getCountExpr(), CAT->isCountInBytes(),
+ CAT->isOrNull());
+ }
+ }
+}
+
void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
ArrayRef<Decl *> Fields, SourceLocation LBrac,
SourceLocation RBrac,
>From 89aaaea8c7c07abe7b4e3f889abd56b39f8a495a Mon Sep 17 00:00:00 2001
From: Yeoul Na <yeoul_na at apple.com>
Date: Mon, 3 Aug 2026 13:08:54 -0700
Subject: [PATCH 2/9] Add LargestValue to TypeDependence enum
---
clang/include/clang/AST/DependenceFlags.h | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/clang/include/clang/AST/DependenceFlags.h b/clang/include/clang/AST/DependenceFlags.h
index 0a5dd53f7696a..f1f00d6b2fd82 100644
--- a/clang/include/clang/AST/DependenceFlags.h
+++ b/clang/include/clang/AST/DependenceFlags.h
@@ -79,7 +79,9 @@ struct TypeDependenceScope {
DependentInstantiation = Dependent | Instantiation,
- LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/LateParsedAttr)
+ LargestValue = LateParsedAttr,
+
+ LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/LargestValue)
};
};
using TypeDependence = TypeDependenceScope::TypeDependence;
>From 9dc267a28799b5332d1dca6ebe45b6ba8dfcfa9c Mon Sep 17 00:00:00 2001
From: Yeoul Na <yeoul_na at apple.com>
Date: Thu, 6 Aug 2026 11:54:30 -0700
Subject: [PATCH 3/9] Address style feedback
---
clang/lib/Sema/SemaDecl.cpp | 54 +++++++++++++++----------------------
1 file changed, 22 insertions(+), 32 deletions(-)
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index bf9c1a9dac5b0..30a0c9ca6d1a7 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -20122,53 +20122,44 @@ struct RebuildTypeWithLateParsedAttr
// TransformLateParsedAttrType can reject nested counted_by. Recursion,
// rebuild, and TypeLoc pushing are delegated to the base TreeTransform.
- QualType TransformPointerType(TypeLocBuilder &TLB, PointerTypeLoc TL) {
- ++PointerOrArrayDepth;
- QualType Result = TreeTransform::TransformPointerType(TLB, TL);
- --PointerOrArrayDepth;
+ /// Run \p Transform one pointer/array level deeper, restoring the previous
+ /// depth afterwards and marking the field invalid if the transform failed.
+ template <typename Fn> QualType TransformNested(Fn &&Transform) {
+ llvm::SaveAndRestore Depth(PointerOrArrayDepth, PointerOrArrayDepth + 1);
+ QualType Result = Transform();
if (Result.isNull())
FD->setInvalidDecl();
return Result;
}
+ QualType TransformPointerType(TypeLocBuilder &TLB, PointerTypeLoc TL) {
+ return TransformNested(
+ [&] { return TreeTransform::TransformPointerType(TLB, TL); });
+ }
+
QualType TransformConstantArrayType(TypeLocBuilder &TLB,
ConstantArrayTypeLoc TL) {
- ++PointerOrArrayDepth;
- QualType Result = TreeTransform::TransformConstantArrayType(TLB, TL);
- --PointerOrArrayDepth;
- if (Result.isNull())
- FD->setInvalidDecl();
- return Result;
+ return TransformNested(
+ [&] { return TreeTransform::TransformConstantArrayType(TLB, TL); });
}
QualType TransformIncompleteArrayType(TypeLocBuilder &TLB,
IncompleteArrayTypeLoc TL) {
- ++PointerOrArrayDepth;
- QualType Result = TreeTransform::TransformIncompleteArrayType(TLB, TL);
- --PointerOrArrayDepth;
- if (Result.isNull())
- FD->setInvalidDecl();
- return Result;
+ return TransformNested(
+ [&] { return TreeTransform::TransformIncompleteArrayType(TLB, TL); });
}
QualType TransformVariableArrayType(TypeLocBuilder &TLB,
VariableArrayTypeLoc TL) {
- ++PointerOrArrayDepth;
- QualType Result = TreeTransform::TransformVariableArrayType(TLB, TL);
- --PointerOrArrayDepth;
- if (Result.isNull())
- FD->setInvalidDecl();
- return Result;
+ return TransformNested(
+ [&] { return TreeTransform::TransformVariableArrayType(TLB, TL); });
}
QualType TransformDependentSizedArrayType(TypeLocBuilder &TLB,
DependentSizedArrayTypeLoc TL) {
- ++PointerOrArrayDepth;
- QualType Result = TreeTransform::TransformDependentSizedArrayType(TLB, TL);
- --PointerOrArrayDepth;
- if (Result.isNull())
- FD->setInvalidDecl();
- return Result;
+ return TransformNested([&] {
+ return TreeTransform::TransformDependentSizedArrayType(TLB, TL);
+ });
}
};
@@ -20177,9 +20168,9 @@ void Sema::ProcessLateParsedTypeAttributes(
for (auto *I : EnclosingDecl->decls()) {
FieldDecl *FD = dyn_cast<FieldDecl>(I);
IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(I);
- if (!FD && IFD) {
+ if (!FD && IFD)
FD = IFD->getAnonField();
- }
+
if (!FD || !FD->getType()->hasLateParsedAttr() ||
FD->getType()->isRecordType())
continue;
@@ -20190,9 +20181,8 @@ void Sema::ProcessLateParsedTypeAttributes(
if (TSI && TSI != OldTSI) {
FD->setTypeSourceInfo(TSI);
FD->setType(TSI->getType());
- if (IFD) {
+ if (IFD)
IFD->setType(TSI->getType());
- }
}
if (auto *CAT = FD->getType()->getAs<CountAttributedType>()) {
>From 450a32d0eae97245385fa2eb81fb16616e845999 Mon Sep 17 00:00:00 2001
From: Yeoul Na <yeoul_na at apple.com>
Date: Tue, 25 Aug 2026 11:15:58 -0700
Subject: [PATCH 4/9] Update TypeDependence to use 1<<N syntax
---
clang/include/clang/AST/DependenceFlags.h | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
diff --git a/clang/include/clang/AST/DependenceFlags.h b/clang/include/clang/AST/DependenceFlags.h
index f1f00d6b2fd82..ff9828fdea840 100644
--- a/clang/include/clang/AST/DependenceFlags.h
+++ b/clang/include/clang/AST/DependenceFlags.h
@@ -52,30 +52,30 @@ struct TypeDependenceScope {
enum TypeDependence : uint8_t {
/// Whether this type contains an unexpanded parameter pack
/// (for C++11 variadic templates)
- UnexpandedPack = 1,
+ UnexpandedPack = 1 << 0,
/// Whether this type somehow involves
/// - a template parameter, even if the resolution of the type does not
/// depend on a template parameter.
/// - or an error.
- Instantiation = 2,
+ Instantiation = 1 << 1,
/// Whether this type
/// - is a dependent type (C++ [temp.dep.type])
/// - or it somehow involves an error, e.g. decltype(recovery-expr)
- Dependent = 4,
+ Dependent = 1 << 2,
/// Whether this type is a variably-modified type (C99 6.7.5).
- VariablyModified = 8,
+ VariablyModified = 1 << 3,
/// Whether this type references an error, e.g. decltype(err-expression)
/// yields an error type.
- Error = 16,
+ Error = 1 << 4,
/// Whether this type contains a placeholder for a type attribute
/// awaiting late parsing, e.g. `int *__counted_by(count)` where
/// `count` is a later field of the same struct.
- LateParsedAttr = 32,
+ LateParsedAttr = 1 << 5,
None = 0,
- All = 63,
+ All = (1 << 6) - 1,
DependentInstantiation = Dependent | Instantiation,
>From c9adb593566d55aac0ef757e3d3bb19635537da6 Mon Sep 17 00:00:00 2001
From: Yeoul Na <yeoul_na at apple.com>
Date: Tue, 25 Aug 2026 15:17:22 -0700
Subject: [PATCH 5/9] Address Oliver's comments about assertions
---
clang/lib/Sema/SemaDecl.cpp | 13 ++++++-------
1 file changed, 6 insertions(+), 7 deletions(-)
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 30a0c9ca6d1a7..0962f05042667 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -20003,16 +20003,13 @@ bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
}
-static QualType handleCountedByAttrField(Sema &S, QualType T, Decl *D,
+static QualType buildCountAttributedType(Sema &S, QualType T,
const ParsedAttr &AL) {
if (!AL.diagnoseLangOpts(S))
return QualType();
- assert(isa<FieldDecl>(D));
-
auto *CountExpr = AL.getArgAsExpr(0);
- if (!CountExpr)
- return QualType();
+ assert(CountExpr);
bool CountInBytes;
bool OrNull;
@@ -20083,7 +20080,7 @@ struct RebuildTypeWithLateParsedAttr
return QualType();
}
- QualType T = handleCountedByAttrField(SemaRef, InnerType, FD, AL);
+ QualType T = buildCountAttributedType(SemaRef, InnerType, AL);
if (T.isNull()) {
AL.setInvalid();
FD->setInvalidDecl();
@@ -20168,8 +20165,10 @@ void Sema::ProcessLateParsedTypeAttributes(
for (auto *I : EnclosingDecl->decls()) {
FieldDecl *FD = dyn_cast<FieldDecl>(I);
IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(I);
- if (!FD && IFD)
+ if (IFD) {
+ assert(!FD);
FD = IFD->getAnonField();
+ }
if (!FD || !FD->getType()->hasLateParsedAttr() ||
FD->getType()->isRecordType())
>From 6af3ef05bd3511c8abdde1a332bf9c649fd6f6cb Mon Sep 17 00:00:00 2001
From: Yeoul Na <yeoul_na at apple.com>
Date: Tue, 25 Aug 2026 15:24:09 -0700
Subject: [PATCH 6/9] Move new LateParsing resolution related logic to
SemaBoundsSafety.cpp
---
clang/lib/Sema/SemaBoundsSafety.cpp | 191 ++++++++++++++++++++++++++++
clang/lib/Sema/SemaDecl.cpp | 188 ---------------------------
2 files changed, 191 insertions(+), 188 deletions(-)
diff --git a/clang/lib/Sema/SemaBoundsSafety.cpp b/clang/lib/Sema/SemaBoundsSafety.cpp
index 066dab2f0bef2..171b18aa1ccf1 100644
--- a/clang/lib/Sema/SemaBoundsSafety.cpp
+++ b/clang/lib/Sema/SemaBoundsSafety.cpp
@@ -11,9 +11,12 @@
/// (e.g. `counted_by`)
///
//===----------------------------------------------------------------------===//
+#include "TreeTransform.h"
+#include "TypeLocBuilder.h"
#include "clang/Lex/Lexer.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Sema.h"
+#include "llvm/Support/SaveAndRestore.h"
namespace clang {
@@ -412,4 +415,192 @@ bool Sema::BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E) {
return false;
}
+static QualType buildCountAttributedType(Sema &S, QualType T,
+ const ParsedAttr &AL) {
+ if (!AL.diagnoseLangOpts(S))
+ return QualType();
+
+ auto *CountExpr = AL.getArgAsExpr(0);
+ assert(CountExpr);
+
+ bool CountInBytes;
+ bool OrNull;
+ switch (AL.getKind()) {
+ case ParsedAttr::AT_CountedBy:
+ CountInBytes = false;
+ OrNull = false;
+ break;
+ case ParsedAttr::AT_CountedByOrNull:
+ CountInBytes = false;
+ OrNull = true;
+ break;
+ case ParsedAttr::AT_SizedBy:
+ CountInBytes = true;
+ OrNull = false;
+ break;
+ case ParsedAttr::AT_SizedByOrNull:
+ CountInBytes = true;
+ OrNull = true;
+ break;
+ default:
+ llvm_unreachable("unexpected counted_by family attribute");
+ }
+
+ return S.BuildCountAttributedArrayOrPointerType(T, CountExpr, CountInBytes,
+ OrNull);
+}
+struct RebuildTypeWithLateParsedAttr
+ : TreeTransform<RebuildTypeWithLateParsedAttr> {
+ FieldDecl *FD;
+ Sema::ParseLateParsedTypeAttributeCB *ParseCallback;
+
+ /// Non-zero while transforming under a pointer or array. Used to reject
+ /// nested counted_by (e.g. `int *__counted_by(n) *p` or
+ /// `int *__counted_by(n) arr[10]`), where the resolved CountAttributedType
+ /// would sit inside another wrapper.
+ unsigned PointerOrArrayDepth = 0;
+
+ RebuildTypeWithLateParsedAttr(Sema &SemaRef, FieldDecl *FD,
+ Sema::ParseLateParsedTypeAttributeCB *ParseCB)
+ : TreeTransform(SemaRef), FD(FD), ParseCallback(ParseCB) {}
+
+ QualType TransformLateParsedAttrType(TypeLocBuilder &TLB,
+ LateParsedAttrTypeLoc TL) {
+ const LateParsedAttrType *LPA = TL.getTypePtr();
+ auto *LTA = LPA->getLateParsedAttribute();
+
+ assert(LTA && "LateParsedAttrType must have a LateParsedTypeAttribute");
+
+ AttributeFactory AF{};
+ ParsedAttributes Attrs(AF);
+
+ // Invoke the parser callback to parse and consume the cached tokens.
+ // ParseCallback is also responsible for deleting LTA.
+ assert(ParseCallback);
+ ParseCallback(LTA, &Attrs);
+
+ // Invalid argument
+ if (Attrs.empty())
+ return QualType();
+
+ assert(Attrs.size() == 1);
+ auto &AL = Attrs[0];
+
+ QualType InnerType = TransformType(TLB, TL.getInnerLoc());
+ if (InnerType.isNull()) {
+ FD->setInvalidDecl();
+ return QualType();
+ }
+
+ QualType T = buildCountAttributedType(SemaRef, InnerType, AL);
+ if (T.isNull()) {
+ AL.setInvalid();
+ FD->setInvalidDecl();
+ return QualType();
+ }
+
+ // Reject nested counted_by, e.g. `int *__counted_by(n) *p` or
+ // `int *__counted_by(n) arr[10]` — the resolved CountAttributedType
+ // must sit at the outermost level of the field's type.
+ //
+ // FIXME: In the -fbounds-safety model:
+ // - `counted_by` / `sized_by` on nested pointers is permitted only
+ // for function parameters, and only one level of nesting.
+ // - `counted_by_or_null` / `sized_by_or_null` on nested pointers is
+ // generally permitted, because it makes sense to allow such a
+ // pointer to be valid when the top-level pointer is null (the
+ // inner counted_by / sized_by simply doesn't need to hold in
+ // that case).
+ // We reject unconditionally here because this slice only covers
+ // struct fields; extending coverage will need to relax this check
+ // along those lines.
+ if (PointerOrArrayDepth > 0) {
+ SemaRef.Diag(TL.getAttrNameLoc(), diag::err_counted_by_on_nested_pointer)
+ << T->getAs<CountAttributedType>()->getKind();
+ FD->setInvalidDecl();
+ return QualType();
+ }
+
+ AL.setUsedAsTypeAttr();
+
+ TLB.push<CountAttributedTypeLoc>(T);
+ return T;
+ }
+
+ // The five overrides below only track pointer/array depth so
+ // TransformLateParsedAttrType can reject nested counted_by. Recursion,
+ // rebuild, and TypeLoc pushing are delegated to the base TreeTransform.
+
+ /// Run \p Transform one pointer/array level deeper, restoring the previous
+ /// depth afterwards and marking the field invalid if the transform failed.
+ template <typename Fn> QualType TransformNested(Fn &&Transform) {
+ llvm::SaveAndRestore Depth(PointerOrArrayDepth, PointerOrArrayDepth + 1);
+ QualType Result = Transform();
+ if (Result.isNull())
+ FD->setInvalidDecl();
+ return Result;
+ }
+
+ QualType TransformPointerType(TypeLocBuilder &TLB, PointerTypeLoc TL) {
+ return TransformNested(
+ [&] { return TreeTransform::TransformPointerType(TLB, TL); });
+ }
+
+ QualType TransformConstantArrayType(TypeLocBuilder &TLB,
+ ConstantArrayTypeLoc TL) {
+ return TransformNested(
+ [&] { return TreeTransform::TransformConstantArrayType(TLB, TL); });
+ }
+
+ QualType TransformIncompleteArrayType(TypeLocBuilder &TLB,
+ IncompleteArrayTypeLoc TL) {
+ return TransformNested(
+ [&] { return TreeTransform::TransformIncompleteArrayType(TLB, TL); });
+ }
+
+ QualType TransformVariableArrayType(TypeLocBuilder &TLB,
+ VariableArrayTypeLoc TL) {
+ return TransformNested(
+ [&] { return TreeTransform::TransformVariableArrayType(TLB, TL); });
+ }
+
+ QualType TransformDependentSizedArrayType(TypeLocBuilder &TLB,
+ DependentSizedArrayTypeLoc TL) {
+ return TransformNested([&] {
+ return TreeTransform::TransformDependentSizedArrayType(TLB, TL);
+ });
+ }
+};
+
+void Sema::ProcessLateParsedTypeAttributes(
+ RecordDecl *EnclosingDecl, ParseLateParsedTypeAttributeCB *ParseCB) {
+ for (auto *I : EnclosingDecl->decls()) {
+ FieldDecl *FD = dyn_cast<FieldDecl>(I);
+ IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(I);
+ if (IFD) {
+ assert(!FD);
+ FD = IFD->getAnonField();
+ }
+
+ if (!FD || !FD->getType()->hasLateParsedAttr() ||
+ FD->getType()->isRecordType())
+ continue;
+
+ RebuildTypeWithLateParsedAttr RebuildFieldType(*this, FD, ParseCB);
+ auto *OldTSI = FD->getTypeSourceInfo();
+ auto *TSI = RebuildFieldType.TransformType(FD->getTypeSourceInfo());
+ if (TSI && TSI != OldTSI) {
+ FD->setTypeSourceInfo(TSI);
+ FD->setType(TSI->getType());
+ if (IFD)
+ IFD->setType(TSI->getType());
+ }
+
+ if (auto *CAT = FD->getType()->getAs<CountAttributedType>()) {
+ CheckCountedByAttrOnField(FD, CAT->getCountExpr(), CAT->isCountInBytes(),
+ CAT->isOrNull());
+ }
+ }
+}
+
} // namespace clang
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 0962f05042667..ed54099934116 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -10,7 +10,6 @@
//
//===----------------------------------------------------------------------===//
-#include "TreeTransform.h"
#include "TypeLocBuilder.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
@@ -20003,193 +20002,6 @@ bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
}
-static QualType buildCountAttributedType(Sema &S, QualType T,
- const ParsedAttr &AL) {
- if (!AL.diagnoseLangOpts(S))
- return QualType();
-
- auto *CountExpr = AL.getArgAsExpr(0);
- assert(CountExpr);
-
- bool CountInBytes;
- bool OrNull;
- switch (AL.getKind()) {
- case ParsedAttr::AT_CountedBy:
- CountInBytes = false;
- OrNull = false;
- break;
- case ParsedAttr::AT_CountedByOrNull:
- CountInBytes = false;
- OrNull = true;
- break;
- case ParsedAttr::AT_SizedBy:
- CountInBytes = true;
- OrNull = false;
- break;
- case ParsedAttr::AT_SizedByOrNull:
- CountInBytes = true;
- OrNull = true;
- break;
- default:
- llvm_unreachable("unexpected counted_by family attribute");
- }
-
- return S.BuildCountAttributedArrayOrPointerType(T, CountExpr, CountInBytes,
- OrNull);
-}
-struct RebuildTypeWithLateParsedAttr
- : TreeTransform<RebuildTypeWithLateParsedAttr> {
- FieldDecl *FD;
- Sema::ParseLateParsedTypeAttributeCB *ParseCallback;
-
- /// Non-zero while transforming under a pointer or array. Used to reject
- /// nested counted_by (e.g. `int *__counted_by(n) *p` or
- /// `int *__counted_by(n) arr[10]`), where the resolved CountAttributedType
- /// would sit inside another wrapper.
- unsigned PointerOrArrayDepth = 0;
-
- RebuildTypeWithLateParsedAttr(Sema &SemaRef, FieldDecl *FD,
- Sema::ParseLateParsedTypeAttributeCB *ParseCB)
- : TreeTransform(SemaRef), FD(FD), ParseCallback(ParseCB) {}
-
- QualType TransformLateParsedAttrType(TypeLocBuilder &TLB,
- LateParsedAttrTypeLoc TL) {
- const LateParsedAttrType *LPA = TL.getTypePtr();
- auto *LTA = LPA->getLateParsedAttribute();
-
- assert(LTA && "LateParsedAttrType must have a LateParsedTypeAttribute");
-
- AttributeFactory AF{};
- ParsedAttributes Attrs(AF);
-
- // Invoke the parser callback to parse and consume the cached tokens.
- // ParseCallback is also responsible for deleting LTA.
- assert(ParseCallback);
- ParseCallback(LTA, &Attrs);
-
- // Invalid argument
- if (Attrs.empty())
- return QualType();
-
- assert(Attrs.size() == 1);
- auto &AL = Attrs[0];
-
- QualType InnerType = TransformType(TLB, TL.getInnerLoc());
- if (InnerType.isNull()) {
- FD->setInvalidDecl();
- return QualType();
- }
-
- QualType T = buildCountAttributedType(SemaRef, InnerType, AL);
- if (T.isNull()) {
- AL.setInvalid();
- FD->setInvalidDecl();
- return QualType();
- }
-
- // Reject nested counted_by, e.g. `int *__counted_by(n) *p` or
- // `int *__counted_by(n) arr[10]` — the resolved CountAttributedType
- // must sit at the outermost level of the field's type.
- //
- // FIXME: In the -fbounds-safety model:
- // - `counted_by` / `sized_by` on nested pointers is permitted only
- // for function parameters, and only one level of nesting.
- // - `counted_by_or_null` / `sized_by_or_null` on nested pointers is
- // generally permitted, because it makes sense to allow such a
- // pointer to be valid when the top-level pointer is null (the
- // inner counted_by / sized_by simply doesn't need to hold in
- // that case).
- // We reject unconditionally here because this slice only covers
- // struct fields; extending coverage will need to relax this check
- // along those lines.
- if (PointerOrArrayDepth > 0) {
- SemaRef.Diag(TL.getAttrNameLoc(), diag::err_counted_by_on_nested_pointer)
- << T->getAs<CountAttributedType>()->getKind();
- FD->setInvalidDecl();
- return QualType();
- }
-
- AL.setUsedAsTypeAttr();
-
- TLB.push<CountAttributedTypeLoc>(T);
- return T;
- }
-
- // The five overrides below only track pointer/array depth so
- // TransformLateParsedAttrType can reject nested counted_by. Recursion,
- // rebuild, and TypeLoc pushing are delegated to the base TreeTransform.
-
- /// Run \p Transform one pointer/array level deeper, restoring the previous
- /// depth afterwards and marking the field invalid if the transform failed.
- template <typename Fn> QualType TransformNested(Fn &&Transform) {
- llvm::SaveAndRestore Depth(PointerOrArrayDepth, PointerOrArrayDepth + 1);
- QualType Result = Transform();
- if (Result.isNull())
- FD->setInvalidDecl();
- return Result;
- }
-
- QualType TransformPointerType(TypeLocBuilder &TLB, PointerTypeLoc TL) {
- return TransformNested(
- [&] { return TreeTransform::TransformPointerType(TLB, TL); });
- }
-
- QualType TransformConstantArrayType(TypeLocBuilder &TLB,
- ConstantArrayTypeLoc TL) {
- return TransformNested(
- [&] { return TreeTransform::TransformConstantArrayType(TLB, TL); });
- }
-
- QualType TransformIncompleteArrayType(TypeLocBuilder &TLB,
- IncompleteArrayTypeLoc TL) {
- return TransformNested(
- [&] { return TreeTransform::TransformIncompleteArrayType(TLB, TL); });
- }
-
- QualType TransformVariableArrayType(TypeLocBuilder &TLB,
- VariableArrayTypeLoc TL) {
- return TransformNested(
- [&] { return TreeTransform::TransformVariableArrayType(TLB, TL); });
- }
-
- QualType TransformDependentSizedArrayType(TypeLocBuilder &TLB,
- DependentSizedArrayTypeLoc TL) {
- return TransformNested([&] {
- return TreeTransform::TransformDependentSizedArrayType(TLB, TL);
- });
- }
-};
-
-void Sema::ProcessLateParsedTypeAttributes(
- RecordDecl *EnclosingDecl, ParseLateParsedTypeAttributeCB *ParseCB) {
- for (auto *I : EnclosingDecl->decls()) {
- FieldDecl *FD = dyn_cast<FieldDecl>(I);
- IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(I);
- if (IFD) {
- assert(!FD);
- FD = IFD->getAnonField();
- }
-
- if (!FD || !FD->getType()->hasLateParsedAttr() ||
- FD->getType()->isRecordType())
- continue;
-
- RebuildTypeWithLateParsedAttr RebuildFieldType(*this, FD, ParseCB);
- auto *OldTSI = FD->getTypeSourceInfo();
- auto *TSI = RebuildFieldType.TransformType(FD->getTypeSourceInfo());
- if (TSI && TSI != OldTSI) {
- FD->setTypeSourceInfo(TSI);
- FD->setType(TSI->getType());
- if (IFD)
- IFD->setType(TSI->getType());
- }
-
- if (auto *CAT = FD->getType()->getAs<CountAttributedType>()) {
- CheckCountedByAttrOnField(FD, CAT->getCountExpr(), CAT->isCountInBytes(),
- CAT->isOrNull());
- }
- }
-}
void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
ArrayRef<Decl *> Fields, SourceLocation LBrac,
>From 4eaf53d57f38fe7e1e5b44ac105092cb9c026bb9 Mon Sep 17 00:00:00 2001
From: Yeoul Na <yeoul_na at apple.com>
Date: Wed, 26 Aug 2026 10:26:51 -0700
Subject: [PATCH 7/9] Address some more comments
---
clang/lib/Sema/SemaBoundsSafety.cpp | 9 +--------
clang/lib/Sema/SemaDecl.cpp | 1 -
2 files changed, 1 insertion(+), 9 deletions(-)
diff --git a/clang/lib/Sema/SemaBoundsSafety.cpp b/clang/lib/Sema/SemaBoundsSafety.cpp
index 171b18aa1ccf1..bcc8f6f8eb47c 100644
--- a/clang/lib/Sema/SemaBoundsSafety.cpp
+++ b/clang/lib/Sema/SemaBoundsSafety.cpp
@@ -417,9 +417,6 @@ bool Sema::BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E) {
static QualType buildCountAttributedType(Sema &S, QualType T,
const ParsedAttr &AL) {
- if (!AL.diagnoseLangOpts(S))
- return QualType();
-
auto *CountExpr = AL.getArgAsExpr(0);
assert(CountExpr);
@@ -493,11 +490,7 @@ struct RebuildTypeWithLateParsedAttr
}
QualType T = buildCountAttributedType(SemaRef, InnerType, AL);
- if (T.isNull()) {
- AL.setInvalid();
- FD->setInvalidDecl();
- return QualType();
- }
+ assert(!T.isNull());
// Reject nested counted_by, e.g. `int *__counted_by(n) *p` or
// `int *__counted_by(n) arr[10]` — the resolved CountAttributedType
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index ed54099934116..2801664df9a05 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -20002,7 +20002,6 @@ bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
}
-
void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
ArrayRef<Decl *> Fields, SourceLocation LBrac,
SourceLocation RBrac,
>From 701795d6ae521ccfaa70583cf7e4c9f6613f0a2a Mon Sep 17 00:00:00 2001
From: Holo-xy <mohammedashraf4599 at gmail.com>
Date: Fri, 4 Sep 2026 19:39:44 +0300
Subject: [PATCH 8/9] make the counted_by family (counted_by,
counted_by_or_null, sized_by, sized_by_or_null) work in type position on a
function parameter, with and without -fexperimental-late-parse-attributes.
---
.../clang/Basic/DiagnosticSemaKinds.td | 9 +
clang/include/clang/Parse/Parser.h | 18 +-
clang/include/clang/Sema/DeclSpec.h | 6 +-
clang/include/clang/Sema/Sema.h | 58 ++
clang/lib/Parse/ParseDecl.cpp | 116 +++-
clang/lib/Parse/Parser.cpp | 5 +
clang/lib/Sema/SemaBoundsSafety.cpp | 592 ++++++++++++++++--
clang/lib/Sema/SemaType.cpp | 39 ++
8 files changed, 765 insertions(+), 78 deletions(-)
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index db118c699ce02..b5dfd3bfa8900 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7179,6 +7179,15 @@ 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_not_param_of_same_function : Error<
+ "'%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}1' argument %0 is not a parameter of the same function as the annotated pointer">;
+def err_count_attr_param_declared_later : Error<
+ "'%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}1' argument %0 is declared after the annotated pointer; "
+ "referring to a later parameter requires '-fexperimental-late-parse-attributes'">;
+def err_count_attr_on_nested_type : Error<
+ "'%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}0' is not supported on "
+ "%select{a nested pointer|an array element}1; it must apply to the "
+ "annotated declaration's own type">;
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/Parse/Parser.h b/clang/include/clang/Parse/Parser.h
index 08b67cb08cdd5..e21f6078761fc 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -2664,7 +2664,8 @@ class Parser : public CodeCompletionHandler {
void ParseTypeQualifierListOpt(
DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed,
bool AtomicOrPtrauthAllowed = true, bool IdentifierRequired = false,
- llvm::function_ref<void()> CodeCompletionHandler = {});
+ llvm::function_ref<void()> CodeCompletionHandler = {},
+ LateParsedAttrList *LateAttrs = nullptr);
/// ParseDirectDeclarator
/// \verbatim
@@ -8114,6 +8115,21 @@ class Parser : public CodeCompletionHandler {
static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
+ /// Parse the cached tokens of \p LTA into \p OutAttrs. Takes ownership of
+ /// \p LTA.
+ static void ParseLateParsedTypeAttributeCallback(LateParsedTypeAttribute *LTA,
+ ParsedAttributes *OutAttrs);
+
+ /// Validate \p LA against \p type and, if it applies, wrap \p type in a
+ /// \c LateParsedAttrType placeholder. Returns false if the attribute is
+ /// invalid for \p type.
+ static bool ProcessLateParsedTypeAttrCallback(LateParsedAttribute *LA,
+ QualType &type);
+
+ /// Return the source location of the attribute name stored in \p LTA.
+ static SourceLocation
+ GetLateParsedAttributeLocationCallback(const LateParsedTypeAttribute *LTA);
+
/// We've parsed something that could plausibly be intended to be a template
/// name (\p LHS) followed by a '<' token, and the following code can't
/// possibly be an expression. Determine if this is likely to be a template-id
diff --git a/clang/include/clang/Sema/DeclSpec.h b/clang/include/clang/Sema/DeclSpec.h
index f5f26830c6b96..759ab24c94557 100644
--- a/clang/include/clang/Sema/DeclSpec.h
+++ b/clang/include/clang/Sema/DeclSpec.h
@@ -1352,6 +1352,7 @@ struct DeclaratorChunk {
}
ParsedAttributesView AttrList;
+ LateParsedAttrList LateAttrList;
struct PointerTypeInfo {
/// The type qualifiers: const/volatile/restrict/unaligned/atomic.
@@ -2452,13 +2453,16 @@ class Declarator {
/// This function takes attrs by R-Value reference because it takes ownership
/// of those attributes from the parameter.
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs,
- SourceLocation EndLoc) {
+ SourceLocation EndLoc,
+ const LateParsedAttrList &LateAttrs = {}) {
DeclTypeInfo.push_back(TI);
DeclTypeInfo.back().getAttrs().prepend(attrs.begin(), attrs.end());
getAttributePool().takeAllFrom(attrs.getPool());
if (!EndLoc.isInvalid())
SetRangeEnd(EndLoc);
+
+ DeclTypeInfo.back().LateAttrList.append(LateAttrs);
}
/// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d8081e0095d09..7a64248bb58ec 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1367,6 +1367,64 @@ class Sema final : public SemaBase {
typedef void ParseLateParsedTypeAttributeCB(LateParsedTypeAttribute *LTA,
ParsedAttributes *OutAttrs);
+ /// Validate \p LA against \p type and, if it applies, wrap \p type in a
+ /// \c LateParsedAttrType placeholder. Returns false if the attribute is
+ /// invalid for \p type.
+ typedef bool ProcessLateParsedTypeAttrCB(LateParsedAttribute *LA,
+ QualType &type);
+ ProcessLateParsedTypeAttrCB *ProcessLateParsedTypeAttrCallback = nullptr;
+
+ /// Return the source location of the attribute name stored in \p LTA.
+ typedef SourceLocation
+ GetLateParsedAttributeLocationCB(const LateParsedTypeAttribute *LTA);
+ GetLateParsedAttributeLocationCB *GetLateParsedAttributeLocationCallback =
+ nullptr;
+
+ /// Wrap \p type in a LateParsedAttrType placeholder for \p LTA, after
+ /// checking that the attribute is applicable to \p type at all. Returns
+ /// false if the attribute should be dropped.
+ bool ActOnLateParsedTypeAttr(ParsedAttr::Kind AttrKind,
+ SourceLocation AttrNameLoc, QualType &type,
+ LateParsedTypeAttribute *LTA);
+
+ /// RAII object that pushes a function prototype scope holding \p Params and
+ /// restores the previous scope on destruction.
+ ///
+ /// A count expression written inside a *nested* function prototype, as in
+ ///
+ /// \code
+ /// void f(int *__counted_by(len) (*cb)(int len));
+ /// \endcode
+ ///
+ /// names a parameter of that inner prototype, whose scope has already been
+ /// popped by the time the attribute's tokens are parsed. Re-creating the
+ /// scope lets ordinary name lookup resolve the count at any nesting depth.
+ class FunctionPrototypeScopeRAII {
+ Sema &S;
+ Scope ProtoScope;
+
+ public:
+ FunctionPrototypeScopeRAII(Sema &S, ArrayRef<Decl *> Params);
+ ~FunctionPrototypeScopeRAII();
+
+ FunctionPrototypeScopeRAII(const FunctionPrototypeScopeRAII &) = delete;
+ FunctionPrototypeScopeRAII &
+ operator=(const FunctionPrototypeScopeRAII &) = delete;
+ };
+
+ /// Resolve late-parsed type attributes in the types of \p Params.
+ ///
+ /// Called once the whole parameter clause has been parsed, so that a count
+ /// expression may refer to any parameter of the function, including one
+ /// declared after the annotated parameter.
+ ///
+ /// This pushes its own prototype scope for \p Params, so it does not require
+ /// the caller's prototype scope to still be open. It does need *some* scope
+ /// to be current, since lookup has to be able to reach file scope to
+ /// diagnose a count that names a global.
+ void ProcessLateParsedTypeAttributesForParams(
+ ArrayRef<Decl *> Params, ParseLateParsedTypeAttributeCB *ParseCB);
+
/// Callback to the parser to parse a type expressed as a string.
std::function<TypeResult(StringRef, StringRef, SourceLocation)>
ParseTypeFromStringCallback;
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 9fa3b96527c08..417b37030c3f0 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -118,6 +118,15 @@ static bool IsAttributeArgsParsedInFunctionScope(const IdentifierInfo &II) {
#undef CLANG_ATTR_PARSE_ARGS_IN_FUNCTION_SCOPE_LIST
}
+/// Returns true iff the attribute kind corresponds to a TypeAttr or
+/// DeclOrTypeAttr in Attr.td.
+static bool IsAttributeTypeAttr(ParsedAttr::Kind Kind) {
+ const auto &Infos = ParsedAttrInfo::getAllBuiltin();
+ if ((size_t)Kind < Infos.size())
+ return Infos[Kind]->IsType;
+ return false;
+}
+
/// Check if the a start and end source location expand to the same macro.
static bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc,
SourceLocation EndLoc) {
@@ -174,8 +183,15 @@ bool Parser::ParseSingleGNUAttribute(ParsedAttributes &Attrs,
// The caller requested that this attribute **only** be late
// parsed for `LateAttrParseExperimentalExt` attributes. This will
// only be late parsed if the experimental language option is enabled.
- LateParse = getLangOpts().ExperimentalLateParseAttributes &&
- IsAttributeLateParsedExperimentalExt(*AttrName);
+ // A type-attr-only list takes type attributes only; a decl attribute like
+ // `guarded_by` captured there would be silently dropped.
+ ParsedAttr::Kind AttrKind = ParsedAttr::getParsedKind(
+ AttrName, nullptr, ParsedAttr::Form::GNU().getSyntax());
+ bool TypeAttrOnly = LateAttrs->lateAttrParseTypeAttrOnly();
+ LateParse = (getLangOpts().ExperimentalLateParseAttributes ||
+ TypeAttrOnly) &&
+ IsAttributeLateParsedExperimentalExt(*AttrName) &&
+ (IsAttributeTypeAttr(AttrKind) || !TypeAttrOnly);
} else {
// The caller did not restrict late parsing to only
// `LateAttrParseExperimentalExt` attributes so late parse
@@ -194,7 +210,9 @@ bool Parser::ParseSingleGNUAttribute(ParsedAttributes &Attrs,
// Handle attributes with arguments that require late parsing.
LateParsedAttribute *LA =
- new LateParsedAttribute(this, *AttrName, AttrNameLoc);
+ LateAttrs->lateAttrParseTypeAttrOnly()
+ ? new LateParsedTypeAttribute(this, *AttrName, AttrNameLoc)
+ : new LateParsedAttribute(this, *AttrName, AttrNameLoc);
LateAttrs->push_back(LA);
// Attributes in a class are parsed at the end of the class, along
@@ -4933,6 +4951,35 @@ void LateParsedTypeAttribute::ParseInto(ParsedAttributes &OutAttrs) {
Self->ParseLexedTypeAttribute(*this, OutAttrs);
}
+void Parser::ParseLateParsedTypeAttributeCallback(LateParsedTypeAttribute *LTA,
+ ParsedAttributes *OutAttrs) {
+ LTA->ParseInto(*OutAttrs);
+ delete LTA;
+}
+
+SourceLocation Parser::GetLateParsedAttributeLocationCallback(
+ const LateParsedTypeAttribute *LTA) {
+ assert(LTA);
+ return LTA->AttrNameLoc;
+}
+
+bool Parser::ProcessLateParsedTypeAttrCallback(LateParsedAttribute *LA,
+ QualType &type) {
+ auto *LTA = dyn_cast_if_present<LateParsedTypeAttribute>(LA);
+ if (!LTA)
+ return true;
+
+ ParsedAttr::Kind AttrKind = ParsedAttr::getParsedKind(
+ <A->AttrName, nullptr, ParsedAttr::Form::GNU().getSyntax());
+ if (LTA->Self->Actions.ActOnLateParsedTypeAttr(AttrKind, LTA->AttrNameLoc,
+ type, LTA))
+ return true;
+
+ // No placeholder was built, so nothing else will ever own these tokens.
+ delete LTA;
+ return false;
+}
+
void Parser::TakeTypeAttrsAppendingFrom(LateParsedAttrList &To,
LateParsedAttrList &From) {
LateParsedAttrList::iterator It =
@@ -6255,7 +6302,8 @@ bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide,
void Parser::ParseTypeQualifierListOpt(
DeclSpec &DS, unsigned AttrReqs, bool AtomicOrPtrauthAllowed,
- bool IdentifierRequired, llvm::function_ref<void()> CodeCompletionHandler) {
+ bool IdentifierRequired, llvm::function_ref<void()> CodeCompletionHandler,
+ LateParsedAttrList *LateAttrs) {
if ((AttrReqs & AR_CXX11AttributesParsed) &&
isAllowedCXX11AttributeSpecifier()) {
ParsedAttributes Attrs(AttrFactory);
@@ -6417,7 +6465,7 @@ void Parser::ParseTypeQualifierListOpt(
// recovery is graceful.
if (AttrReqs & AR_GNUAttributesParsed ||
AttrReqs & AR_GNUAttributesParsedAndRejected) {
- ParseGNUAttributes(DS.getAttributes());
+ ParseGNUAttributes(DS.getAttributes(), LateAttrs);
continue; // do *not* consume the next token!
}
// otherwise, FALL THROUGH!
@@ -6604,8 +6652,19 @@ void Parser::ParseDeclaratorInternal(Declarator &D,
((D.getContext() != DeclaratorContext::CXXNew)
? AR_GNUAttributesParsed
: AR_GNUAttributesParsedAndRejected);
+
+ LateParsedAttrList LateAttrs(/*PSoon=*/true,
+ /*LateAttrParseExperimentalExtOnly=*/true,
+ /*LateAttrParseTypeAttrOnly=*/true);
+
+ LateParsedAttrList *LateAttrsPtr =
+ D.getContext() == DeclaratorContext::Prototype &&
+ !getLangOpts().CPlusPlus
+ ? &LateAttrs
+ : nullptr;
+
ParseTypeQualifierListOpt(DS, Reqs, /*AtomicOrPtrauthAllowed=*/true,
- !D.mayOmitIdentifier());
+ !D.mayOmitIdentifier(), {}, LateAttrsPtr);
D.ExtendWithDeclSpec(DS);
// Recursively parse the declarator.
@@ -6618,12 +6677,12 @@ void Parser::ParseDeclaratorInternal(Declarator &D,
DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc(),
DS.getOverflowBehaviorLoc(), DS.isWrapSpecified()),
- std::move(DS.getAttributes()), SourceLocation());
+ std::move(DS.getAttributes()), SourceLocation(), LateAttrs);
else
// Remember that we parsed a Block type, and remember the type-quals.
D.AddTypeInfo(
DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
- std::move(DS.getAttributes()), SourceLocation());
+ std::move(DS.getAttributes()), SourceLocation(), LateAttrs);
} else {
// Is a reference
DeclSpec DS(AttrFactory);
@@ -7374,6 +7433,18 @@ void Parser::ParseFunctionDeclarator(Declarator &D,
else if (RequiresArg)
Diag(Tok, diag::err_argument_required_after_attribute);
+ // Every parameter is now declared and the prototype scope is still active,
+ // so resolve late-parsed attributes here.
+ // Unconditional in C: a placeholder is created whenever the language
+ // option is off too, so it always has to be resolved here.
+ if (!getLangOpts().CPlusPlus && !ParamInfo.empty()) {
+ SmallVector<Decl *, 16> Params;
+ for (const DeclaratorChunk::ParamInfo &PI : ParamInfo)
+ Params.push_back(PI.Param);
+ Actions.ProcessLateParsedTypeAttributesForParams(
+ Params, &Parser::ParseLateParsedTypeAttributeCallback);
+ }
+
// OpenCL disallows functions without a prototype, but it doesn't enforce
// strict prototypes as in C23 because it allows a function definition to
// have an identifier list. See OpenCL 3.0 6.11/g for more details.
@@ -7687,7 +7758,34 @@ void Parser::ParseParameterDeclarationClause(
ParmDeclarator.SetRangeBegin(ThisLoc);
// Parse GNU attributes, if present.
- MaybeParseGNUAttributes(ParmDeclarator);
+ //
+ // A trailing counted_by-family attribute describes the parameter's own
+ // type, exactly as the same attribute written inside the declarator does:
+ // void f(int *p __counted_by(n), int n);
+ // void f(int *__counted_by(n) p, int n);
+ // so defer it the same way and hand it to the outermost declarator chunk.
+ // GetFullTypeForDeclarator applies chunks back to front, making index 0
+ // the outermost, and processes a chunk's late attributes only after
+ // building that chunk's type -- which is what lets the placeholder see a
+ // pointer rather than the declaration-specifier type.
+ //
+ // Without this the attribute stays a declaration attribute, where the
+ // counted_by subject list rejects it as applying to fields only. A
+ // parameter with no declarator chunk has no pointer for the attribute to
+ // describe, so leave that case eagerly parsed and let the subject list
+ // diagnose it as before.
+ LateParsedAttrList LateParmAttrs(
+ /*PSoon=*/true,
+ /*LateAttrParseExperimentalExtOnly=*/true,
+ /*LateAttrParseTypeAttrOnly=*/true);
+ const bool DeferTrailingAttrs =
+ !getLangOpts().CPlusPlus &&
+ ParmDeclarator.getContext() == DeclaratorContext::Prototype &&
+ ParmDeclarator.getNumTypeObjects() > 0;
+ MaybeParseGNUAttributes(ParmDeclarator,
+ DeferTrailingAttrs ? &LateParmAttrs : nullptr);
+ if (!LateParmAttrs.empty())
+ ParmDeclarator.getTypeObject(0).LateAttrList.append(LateParmAttrs);
if (getLangOpts().HLSL)
MaybeParseHLSLAnnotations(DS.getAttributes());
diff --git a/clang/lib/Parse/Parser.cpp b/clang/lib/Parse/Parser.cpp
index e52a14d1a007e..ab136e4db8768 100644
--- a/clang/lib/Parse/Parser.cpp
+++ b/clang/lib/Parse/Parser.cpp
@@ -84,6 +84,11 @@ Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies)
return this->ParseTypeFromString(TypeStr, Context, IncludeLoc);
};
+ Actions.ProcessLateParsedTypeAttrCallback =
+ &Parser::ProcessLateParsedTypeAttrCallback;
+ Actions.GetLateParsedAttributeLocationCallback =
+ &Parser::GetLateParsedAttributeLocationCallback;
+
Initialize();
}
diff --git a/clang/lib/Sema/SemaBoundsSafety.cpp b/clang/lib/Sema/SemaBoundsSafety.cpp
index bcc8f6f8eb47c..507843f241224 100644
--- a/clang/lib/Sema/SemaBoundsSafety.cpp
+++ b/clang/lib/Sema/SemaBoundsSafety.cpp
@@ -17,6 +17,7 @@
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Sema.h"
#include "llvm/Support/SaveAndRestore.h"
+#include <optional>
namespace clang {
@@ -29,6 +30,55 @@ getCountAttrKind(bool CountInBytes, bool OrNull) {
: CountAttributedType::CountedBy;
}
+namespace {
+struct BoundsAttrFlags {
+ bool CountInBytes = false;
+ bool OrNull = false;
+};
+} // namespace
+
+static std::optional<BoundsAttrFlags> getBoundsAttrFlags(ParsedAttr::Kind K) {
+ BoundsAttrFlags Flags;
+ switch (K) {
+ case ParsedAttr::AT_CountedBy:
+ break;
+ case ParsedAttr::AT_CountedByOrNull:
+ Flags.OrNull = true;
+ break;
+ case ParsedAttr::AT_SizedBy:
+ Flags.CountInBytes = true;
+ break;
+ case ParsedAttr::AT_SizedByOrNull:
+ Flags.CountInBytes = true;
+ Flags.OrNull = true;
+ break;
+ default:
+ return std::nullopt;
+ }
+ return Flags;
+}
+
+bool Sema::ActOnLateParsedTypeAttr(ParsedAttr::Kind AttrKind,
+ SourceLocation AttrNameLoc, QualType &type,
+ LateParsedTypeAttribute *LTA) {
+ std::optional<BoundsAttrFlags> Flags = getBoundsAttrFlags(AttrKind);
+ if (!Flags)
+ return false;
+
+ // The argument-independent validation, run before the attribute's argument
+ // has been parsed. An array parameter has already decayed to a pointer, so
+ // unlike a flexible array member there is no array spelling to accept here.
+ if (!type->isPointerType()) {
+ unsigned Kind = getCountAttrKind(Flags->CountInBytes, Flags->OrNull);
+ Diag(AttrNameLoc, diag::err_count_attr_not_on_ptr_or_flexible_array_member)
+ << Kind << AttrNameLoc << /*do not suggest counted_by*/ 0;
+ return false;
+ }
+
+ type = Context.getLateParsedAttrType(type, LTA);
+ return true;
+}
+
static const RecordDecl *GetEnclosingNamedOrTopAnonRecord(const FieldDecl *FD) {
const auto *RD = FD->getParent();
// An unnamed struct is treated as anonymous struct at this point.
@@ -52,59 +102,19 @@ enum class CountedByInvalidPointeeTypeKind {
VALID,
};
-bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
- bool OrNull) {
- // Check the context the attribute is used in
-
- unsigned Kind = getCountAttrKind(CountInBytes, OrNull);
-
- if (FD->getParent()->isUnion()) {
- Diag(FD->getBeginLoc(), diag::err_count_attr_in_union)
- << Kind << FD->getSourceRange();
- return true;
- }
-
- const auto FieldTy = FD->getType();
- if (FieldTy->isArrayType() && (CountInBytes || OrNull)) {
- Diag(FD->getBeginLoc(),
- diag::err_count_attr_not_on_ptr_or_flexible_array_member)
- << Kind << FD->getLocation() << /* suggest counted_by */ 1;
- return true;
- }
- if (!FieldTy->isArrayType() && !FieldTy->isPointerType()) {
- Diag(FD->getBeginLoc(),
- diag::err_count_attr_not_on_ptr_or_flexible_array_member)
- << Kind << FD->getLocation() << /* do not suggest counted_by */ 0;
- return true;
- }
-
- LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
- LangOptions::StrictFlexArraysLevelKind::IncompleteOnly;
- if (FieldTy->isArrayType() &&
- !Decl::isFlexibleArrayMemberLike(getASTContext(), FD, FieldTy,
- StrictFlexArraysLevel, true)) {
- Diag(FD->getBeginLoc(),
- diag::err_counted_by_attr_on_array_not_flexible_array_member)
- << Kind << FD->getLocation();
- return true;
- }
-
+/// Diagnose a counted_by-family attribute whose pointee (or array element)
+/// type \p PointeeTy cannot support bounds computation. Shared between the
+/// struct-field and function-parameter paths so both accept and reject the
+/// same shapes. \p DowngradeFAMPointeeErrToWarn is the Linux-kernel
+/// workaround; see the caller in CheckCountedByAttrOnField. Returns true if
+/// the attribute cannot be applied.
+static bool CheckCountAttrPointeeType(Sema &S, QualType PointeeTy,
+ bool CountInBytes, unsigned Kind,
+ int SelectPtrOrArr,
+ bool DowngradeFAMPointeeErrToWarn,
+ SourceLocation Loc, SourceRange Range) {
CountedByInvalidPointeeTypeKind InvalidTypeKind =
CountedByInvalidPointeeTypeKind::VALID;
- QualType PointeeTy;
- int SelectPtrOrArr = 0;
- if (FieldTy->isPointerType()) {
- PointeeTy = FieldTy->getPointeeType();
- SelectPtrOrArr = 0;
- } else {
- assert(FieldTy->isArrayType());
- const ArrayType *AT = getASTContext().getAsArrayType(FieldTy);
- PointeeTy = AT->getElementType();
- SelectPtrOrArr = 1;
- }
- // Note: The `Decl::isFlexibleArrayMemberLike` check earlier on means
- // only `PointeeTy->isStructureTypeWithFlexibleArrayMember()` is reachable
- // when `FieldTy->isArrayType()`.
bool ShouldWarn = false;
if (!CountInBytes && PointeeTy->isAlwaysIncompleteType()) {
// In general using `counted_by` or `counted_by_or_null` on
@@ -128,8 +138,8 @@ bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
// * 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`,
+ // but later uses of the annotated declaration are checked that the pointee
+ // type is complete see `BoundsSafetyCheckAssignmentToCountAttrPtr`,
// `BoundsSafetyCheckInitialization`, and
// `BoundsSafetyCheckUseOfCountAttrPtr`
//
@@ -144,9 +154,8 @@ bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
bool IsVoidPtr = PointeeTy->isVoidType();
if (IsVoidPtr) {
// Emit a warning that this is a GNU extension.
- Diag(FD->getBeginLoc(), diag::ext_gnu_counted_by_void_ptr) << Kind;
- Diag(FD->getBeginLoc(), diag::note_gnu_counted_by_void_ptr_use_sized_by)
- << Kind;
+ S.Diag(Loc, diag::ext_gnu_counted_by_void_ptr) << Kind;
+ S.Diag(Loc, diag::note_gnu_counted_by_void_ptr_use_sized_by) << Kind;
assert(InvalidTypeKind == CountedByInvalidPointeeTypeKind::VALID);
} else {
InvalidTypeKind = CountedByInvalidPointeeTypeKind::INCOMPLETE;
@@ -157,15 +166,8 @@ bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
InvalidTypeKind = CountedByInvalidPointeeTypeKind::FUNCTION;
} else if (!CountInBytes &&
PointeeTy->isStructureTypeWithFlexibleArrayMember()) {
- if (FieldTy->isArrayType() && !getLangOpts().BoundsSafety) {
- // This is a workaround for the Linux kernel that has already adopted
- // `counted_by` on a FAM where the pointee is a struct with a FAM. This
- // should be an error because computing the bounds of the array cannot be
- // done correctly without manually traversing every struct object in the
- // array at runtime. To allow the code to be built this error is
- // downgraded to a warning.
+ if (DowngradeFAMPointeeErrToWarn)
ShouldWarn = true;
- }
InvalidTypeKind = CountedByInvalidPointeeTypeKind::FLEXIBLE_ARRAY_MEMBER;
}
@@ -173,12 +175,78 @@ bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
unsigned DiagID = ShouldWarn
? diag::warn_counted_by_attr_elt_type_unknown_size
: diag::err_counted_by_attr_pointee_unknown_size;
- Diag(FD->getBeginLoc(), DiagID)
- << SelectPtrOrArr << PointeeTy << (int)InvalidTypeKind
- << (ShouldWarn ? 1 : 0) << Kind << FD->getSourceRange();
+ S.Diag(Loc, DiagID) << SelectPtrOrArr << PointeeTy << (int)InvalidTypeKind
+ << (ShouldWarn ? 1 : 0) << Kind << Range;
+ return true;
+ }
+ return false;
+}
+
+bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
+ bool OrNull) {
+ // Check the context the attribute is used in
+
+ unsigned Kind = getCountAttrKind(CountInBytes, OrNull);
+
+ if (FD->getParent()->isUnion()) {
+ Diag(FD->getBeginLoc(), diag::err_count_attr_in_union)
+ << Kind << FD->getSourceRange();
return true;
}
+ const auto FieldTy = FD->getType();
+ if (FieldTy->isArrayType() && (CountInBytes || OrNull)) {
+ Diag(FD->getBeginLoc(),
+ diag::err_count_attr_not_on_ptr_or_flexible_array_member)
+ << Kind << FD->getLocation() << /* suggest counted_by */ 1;
+ return true;
+ }
+ if (!FieldTy->isArrayType() && !FieldTy->isPointerType()) {
+ Diag(FD->getBeginLoc(),
+ diag::err_count_attr_not_on_ptr_or_flexible_array_member)
+ << Kind << FD->getLocation() << /* do not suggest counted_by */ 0;
+ return true;
+ }
+
+ LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
+ LangOptions::StrictFlexArraysLevelKind::IncompleteOnly;
+ if (FieldTy->isArrayType() &&
+ !Decl::isFlexibleArrayMemberLike(getASTContext(), FD, FieldTy,
+ StrictFlexArraysLevel, true)) {
+ Diag(FD->getBeginLoc(),
+ diag::err_counted_by_attr_on_array_not_flexible_array_member)
+ << Kind << FD->getLocation();
+ return true;
+ }
+
+ QualType PointeeTy;
+ int SelectPtrOrArr = 0;
+ if (FieldTy->isPointerType()) {
+ PointeeTy = FieldTy->getPointeeType();
+ SelectPtrOrArr = 0;
+ } else {
+ assert(FieldTy->isArrayType());
+ const ArrayType *AT = getASTContext().getAsArrayType(FieldTy);
+ PointeeTy = AT->getElementType();
+ SelectPtrOrArr = 1;
+ }
+ // Note: The `Decl::isFlexibleArrayMemberLike` check earlier on means
+ // only `PointeeTy->isStructureTypeWithFlexibleArrayMember()` is reachable
+ // when `FieldTy->isArrayType()`.
+ //
+ // Downgrading the FAM-pointee error to a warning on such arrays is a
+ // workaround for the Linux kernel that has already adopted `counted_by` on
+ // a FAM where the pointee is a struct with a FAM. This should be an error
+ // because computing the bounds of the array cannot be done correctly
+ // without manually traversing every struct object in the array at runtime.
+ // To allow the code to be built the error is downgraded to a warning.
+ bool DowngradeFAMPointeeErrToWarn =
+ FieldTy->isArrayType() && !getLangOpts().BoundsSafety;
+ if (CheckCountAttrPointeeType(*this, PointeeTy, CountInBytes, Kind,
+ SelectPtrOrArr, DowngradeFAMPointeeErrToWarn,
+ FD->getBeginLoc(), FD->getSourceRange()))
+ return true;
+
// Check the expression
if (!E->getType()->isIntegerType() || E->getType()->isBooleanType()) {
@@ -596,4 +664,394 @@ void Sema::ProcessLateParsedTypeAttributes(
}
}
+/// What a placeholder's count may name, decided by where the placeholder sits.
+enum class CountScope {
+ /// A parameter type: any parameter, this prototype's or an enclosing one's.
+ AnyParam,
+ /// A return type: this prototype's own parameters.
+ OwnParam,
+};
+
+/// Whether \p Count is already declared where the annotated parameter is.
+///
+/// \p Enclosing is the chain of parameters whose types the placeholder sits
+/// inside, outermost first; the count must precede whichever member of the
+/// chain shares its prototype. A count from a prototype *enclosing* the chain
+/// always precedes it -- that clause is still mid-parse, so its scope holds
+/// only the parameters written before this one, and lookup finding the count
+/// there is itself the proof. One from a prototype *nested* below the chain
+/// never does; that is the return-type case.
+///
+/// Ordering rather than source location, so that a parameter list produced by
+/// a single macro expansion is not read as declaring everything at once.
+static bool isCountDeclaredBefore(ArrayRef<ParmVarDecl *> Enclosing,
+ const ParmVarDecl *Count) {
+ for (const ParmVarDecl *Param : Enclosing)
+ if (Param->getFunctionScopeDepth() == Count->getFunctionScopeDepth())
+ return Count->getFunctionScopeIndex() < Param->getFunctionScopeIndex();
+ assert(!Enclosing.empty() && "chain is seeded with the annotated parameter");
+ return Count->getFunctionScopeDepth() <
+ Enclosing.front()->getFunctionScopeDepth();
+}
+
+/// Build the type an attribute on a prototype-scoped placeholder denotes.
+///
+/// \p Params is the parameter list of the prototype that owns the annotated
+/// type, and \p Scope what its count is allowed to name -- see the comment on
+/// the check below.
+static QualType buildCountAttributedTypeForParam(Sema &S, QualType InnerTy,
+ ArrayRef<Decl *> Params,
+ ArrayRef<ParmVarDecl *> Enclosing,
+ CountScope Scope,
+ ParsedAttr &AL) {
+ std::optional<BoundsAttrFlags> Flags = getBoundsAttrFlags(AL.getKind());
+ assert(Flags && "placeholder for a non-counted_by-family attribute");
+ auto [CountInBytes, OrNull] = *Flags;
+ unsigned Kind = getCountAttrKind(CountInBytes, OrNull);
+
+ // The same pointee rules as the struct-field path, checked in the same
+ // order: the pointee's size before the count expression. A placeholder is
+ // only created for a pointer, so the pointee is always there to take.
+ if (CheckCountAttrPointeeType(S, InnerTy->getPointeeType(), CountInBytes,
+ Kind, /*SelectPtrOrArr=*/0,
+ /*DowngradeFAMPointeeErrToWarn=*/false,
+ AL.getLoc(), AL.getRange()))
+ return QualType();
+
+ Expr *CountExpr = AL.getArgAsExpr(0);
+
+ // The argument must name a single declaration, so that assignments to the
+ // count can be related back to the pointer. No paren-stripping: the
+ // expression handed to BuildCountAttributedArrayOrPointerType must itself be
+ // the DeclRefExpr (BuildTypeCoupledDecls casts it), and the field path in
+ // CheckCountedByAttrOnField rejects parens the same way.
+ auto *DRE = dyn_cast<DeclRefExpr>(CountExpr);
+ if (!DRE) {
+ S.Diag(CountExpr->getBeginLoc(),
+ diag::err_count_attr_only_support_simple_decl_reference)
+ << Kind << CountExpr->getSourceRange();
+ return QualType();
+ }
+
+ // The count must name a parameter, and which prototype's depends on where
+ // the attribute sits.
+ //
+ // On a parameter type an enclosing prototype's parameter is allowed, as in
+ // void f(int n, void (*cb)(int *__counted_by(n) p));
+ // and being a ParmVarDecl is the whole test. Nothing stronger is available:
+ // each prototype's parameters are resolved as its own clause closes, so the
+ // enclosing lists are not in hand here.
+ //
+ // A return type is checked against its own prototype's list, which is. Test
+ // the list rather than the DeclContext: mid-parse every ParmVarDecl shares
+ // the enclosing context, so a DeclContext test could not tell which
+ // prototype one belongs to.
+ auto *CountDecl = dyn_cast<ParmVarDecl>(DRE->getDecl());
+ if (!CountDecl || (Scope == CountScope::OwnParam &&
+ !llvm::is_contained(Params, CountDecl))) {
+ S.Diag(DRE->getBeginLoc(), diag::err_count_attr_not_param_of_same_function)
+ << DRE->getDecl() << Kind << DRE->getSourceRange();
+ return QualType();
+ }
+
+ if (!CountDecl->getType()->isIntegerType() ||
+ CountDecl->getType()->isBooleanType()) {
+ S.Diag(DRE->getBeginLoc(), diag::err_count_attr_argument_not_integer)
+ << Kind << DRE->getSourceRange();
+ return QualType();
+ }
+
+ // Every counted_by-family attribute in a prototype is late parsed, whether
+ // or not -fexperimental-late-parse-attributes is on, so that a forward
+ // reference reaches this point as a resolvable name rather than as "use of
+ // undeclared identifier". Without the flag that is only a better
+ // diagnostic, not a feature: reject the forward reference here, or the flag
+ // would make no difference to what compiles.
+ if (!S.getLangOpts().ExperimentalLateParseAttributes &&
+ !isCountDeclaredBefore(Enclosing, CountDecl)) {
+ S.Diag(DRE->getBeginLoc(), diag::err_count_attr_param_declared_later)
+ << DRE->getDecl() << Kind << DRE->getSourceRange();
+ return QualType();
+ }
+
+ return S.BuildCountAttributedArrayOrPointerType(InnerTy, CountExpr,
+ CountInBytes, OrNull);
+}
+
+namespace {
+
+/// Where a LateParsedAttrType placeholder sits inside the type being rebuilt.
+///
+/// Parameter and ReturnType are both "the annotated declaration's own type",
+/// and differ only in which prototypes their count may name; the other two are
+/// positions no bounds attribute may occupy.
+enum class LateAttrPosition {
+ Parameter,
+ ReturnType,
+ NestedPointer,
+ ArrayElement,
+};
+
+/// Rebuilds a type, replacing each LateParsedAttrType placeholder with the
+/// concrete type its attribute denotes, parsing the cached tokens on the way.
+///
+/// Every placeholder is replaced, including the ones whose attribute turns out
+/// to be unusable: a placeholder may not reach the finalized AST, and once its
+/// tokens are parsed it no longer refers to a live attribute either.
+struct RebuildParamTypeWithLateParsedAttr
+ : TreeTransform<RebuildParamTypeWithLateParsedAttr> {
+ ParmVarDecl *PVD;
+ ArrayRef<Decl *> Params;
+ Sema::ParseLateParsedTypeAttributeCB *ParseCallback;
+
+ /// Where the node currently being transformed sits relative to the annotated
+ /// declaration's own type. Only ever demoted on the way down: once a
+ /// placeholder is out of the running for describing that type it cannot
+ /// come back into it, except by crossing a function type, which starts a new
+ /// declaration and so resets it.
+ LateAttrPosition CurPos = LateAttrPosition::Parameter;
+
+ /// The parameters whose types enclose the node being transformed, outermost
+ /// first. The last is the one a placeholder reached here annotates, and the
+ /// chain is what decides whether its count is already declared -- see
+ /// isCountDeclaredBefore. Seeded with the parameter being rebuilt, which
+ /// TransformType is entered on directly rather than through
+ /// TransformFunctionTypeParam.
+ SmallVector<ParmVarDecl *, 4> Enclosing;
+
+ RebuildParamTypeWithLateParsedAttr(Sema &SemaRef, ParmVarDecl *PVD,
+ ArrayRef<Decl *> Params,
+ Sema::ParseLateParsedTypeAttributeCB *ParseCB)
+ : TreeTransform(SemaRef), PVD(PVD), Params(Params),
+ ParseCallback(ParseCB), Enclosing({PVD}) {}
+
+ /// Run \p Transform with the position demoted to \p To, if not already.
+ template <typename Fn>
+ QualType transformDemotedTo(LateAttrPosition To, Fn Transform) {
+ const bool IsOwnType = CurPos == LateAttrPosition::Parameter ||
+ CurPos == LateAttrPosition::ReturnType;
+ SaveAndRestore<LateAttrPosition> SavedPos(CurPos, IsOwnType ? To : CurPos);
+ return Transform();
+ }
+
+ // The four overrides below only demote the position, so that
+ // TransformLateParsedAttrType can reject nested counted_by.
+ //
+ // BlockPointerType needs no override: its pointee is always a function type
+ // (ASTContext::getBlockPointerType asserts it), so a demotion there would be
+ // overwritten by the prototype below it before any placeholder saw it.
+
+ QualType TransformPointerType(TypeLocBuilder &TLB, PointerTypeLoc TL) {
+ return transformDemotedTo(LateAttrPosition::NestedPointer, [&] {
+ return TreeTransform::TransformPointerType(TLB, TL);
+ });
+ }
+
+ QualType TransformConstantArrayType(TypeLocBuilder &TLB,
+ ConstantArrayTypeLoc TL) {
+ return transformDemotedTo(LateAttrPosition::ArrayElement, [&] {
+ return TreeTransform::TransformConstantArrayType(TLB, TL);
+ });
+ }
+
+ QualType TransformIncompleteArrayType(TypeLocBuilder &TLB,
+ IncompleteArrayTypeLoc TL) {
+ return transformDemotedTo(LateAttrPosition::ArrayElement, [&] {
+ return TreeTransform::TransformIncompleteArrayType(TLB, TL);
+ });
+ }
+
+ QualType TransformVariableArrayType(TypeLocBuilder &TLB,
+ VariableArrayTypeLoc TL) {
+ return transformDemotedTo(LateAttrPosition::ArrayElement, [&] {
+ return TreeTransform::TransformVariableArrayType(TLB, TL);
+ });
+ }
+
+ // TransformFunctionProtoType is overloaded; overriding one would hide the
+ // rest. The base two-argument version dispatches to the five-argument one
+ // through getDerived().
+ using TreeTransform::TransformFunctionProtoType;
+
+ /// A count inside a nested prototype names *that* prototype's parameters, as
+ /// in `void f(int *__counted_by(len) (*cb)(int len), int len2);`. Two things
+ /// are needed and they are not alternatives: the re-entered scope makes `len`
+ /// findable at all (the inner prototype's scope was popped when its
+ /// declarator finished), and the parameter list decides whether what lookup
+ /// found is allowed (lookup falls through to the enclosing scopes).
+ ///
+ /// The position resets for the same reason the list is swapped: below a
+ /// prototype, the return type and each parameter type are an "own type"
+ /// again, just of a different declaration.
+ QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
+ FunctionProtoTypeLoc TL) {
+ SmallVector<Decl *, 4> InnerParams;
+ for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I)
+ if (ParmVarDecl *PD = TL.getParam(I))
+ InnerParams.push_back(PD);
+
+ Sema::FunctionPrototypeScopeRAII ProtoScope(SemaRef, InnerParams);
+ SaveAndRestore<ArrayRef<Decl *>> SavedParams(Params, InnerParams);
+ SaveAndRestore<LateAttrPosition> SavedPos(CurPos,
+ LateAttrPosition::ReturnType);
+ return TreeTransform::TransformFunctionProtoType(TLB, TL);
+ }
+
+ /// Where the enclosing chain grows. Called via getDerived().
+ ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
+ int indexAdjustment,
+ UnsignedOrNone NumExpansions,
+ bool ExpectParameterPack) {
+ Enclosing.push_back(OldParm);
+ ParmVarDecl *Result = TreeTransform::TransformFunctionTypeParam(
+ OldParm, indexAdjustment, NumExpansions, ExpectParameterPack);
+ Enclosing.pop_back();
+ return Result;
+ }
+
+ // As with TransformFunctionProtoType: overriding one overload would hide the
+ // other, which the base class calls through getDerived().
+ using TreeTransform::TransformFunctionTypeParams;
+
+ /// The return type is transformed at the position set by
+ /// TransformFunctionProtoType; the parameter types are transformed here, and
+ /// only they may name an enclosing prototype's parameters.
+ bool TransformFunctionTypeParams(
+ SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
+ const QualType *ParamTypes,
+ const FunctionProtoType::ExtParameterInfo *ParamInfos,
+ SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
+ Sema::ExtParameterInfoBuilder &PInfos, unsigned *LastParamTransformed) {
+ SaveAndRestore<LateAttrPosition> SavedPos(CurPos,
+ LateAttrPosition::Parameter);
+ return TreeTransform::TransformFunctionTypeParams(
+ Loc, Params, ParamTypes, ParamInfos, PTypes, PVars, PInfos,
+ LastParamTransformed);
+ }
+
+ /// A no-prototype function declares no parameters, so nothing in its return
+ /// type can name one: `void f(int *__counted_by(len) (*cb)(), int len);`.
+ /// Clearing the list is what rejects that; otherwise the list is still the
+ /// enclosing prototype's and `len` is accepted. There is no scope worth
+ /// re-entering: an empty one would not change what lookup finds.
+ QualType TransformFunctionNoProtoType(TypeLocBuilder &TLB,
+ FunctionNoProtoTypeLoc TL) {
+ SaveAndRestore<ArrayRef<Decl *>> SavedParams(Params, ArrayRef<Decl *>());
+ SaveAndRestore<LateAttrPosition> SavedPos(CurPos,
+ LateAttrPosition::ReturnType);
+ return TreeTransform::TransformFunctionNoProtoType(TLB, TL);
+ }
+
+ QualType TransformLateParsedAttrType(TypeLocBuilder &TLB,
+ LateParsedAttrTypeLoc TL) {
+ LateParsedTypeAttribute *LTA = TL.getTypePtr()->getLateParsedAttribute();
+ assert(LTA && "LateParsedAttrType without a LateParsedTypeAttribute");
+
+ const LateAttrPosition Pos = CurPos;
+
+ AttributeFactory AF;
+ ParsedAttributes Attrs(AF);
+
+ // Parse the cached tokens. The callback also destroys LTA, so from here on
+ // the placeholder refers to an attribute that no longer exists.
+ assert(ParseCallback);
+ ParseCallback(LTA, &Attrs);
+
+ QualType InnerTy = TransformType(TLB, TL.getInnerLoc());
+ if (InnerTy.isNull()) {
+ PVD->setInvalidDecl();
+ return QualType();
+ }
+
+ // An empty list means the argument failed to parse, which is already
+ // diagnosed.
+ QualType T;
+ if (!Attrs.empty()) {
+ assert(Attrs.size() == 1);
+ if (Pos == LateAttrPosition::Parameter ||
+ Pos == LateAttrPosition::ReturnType) {
+ T = buildCountAttributedTypeForParam(
+ SemaRef, InnerTy, Params, Enclosing,
+ Pos == LateAttrPosition::Parameter ? CountScope::AnyParam
+ : CountScope::OwnParam,
+ Attrs[0]);
+ } else {
+ std::optional<BoundsAttrFlags> Flags =
+ getBoundsAttrFlags(Attrs[0].getKind());
+ assert(Flags && "placeholder for a non-counted_by-family attribute");
+ SemaRef.Diag(TL.getAttrNameLoc(), diag::err_count_attr_on_nested_type)
+ << getCountAttrKind(Flags->CountInBytes, Flags->OrNull)
+ << (Pos == LateAttrPosition::NestedPointer ? /*nested pointer*/ 0
+ : /*array element*/ 1);
+ }
+ }
+
+ if (T.isNull()) {
+ // Drop the attribute and keep the type it wrapped. Returning nothing
+ // would leave the caller holding the original type, placeholder and all.
+ PVD->setInvalidDecl();
+ return InnerTy;
+ }
+
+ TLB.push<CountAttributedTypeLoc>(T);
+ return T;
+ }
+};
+
+} // namespace
+
+Sema::FunctionPrototypeScopeRAII::FunctionPrototypeScopeRAII(
+ Sema &S, ArrayRef<Decl *> Params)
+ : S(S), ProtoScope(S.getCurScope(),
+ Scope::FunctionPrototypeScope | Scope::DeclScope,
+ S.getDiagnostics()) {
+ S.CurScope = &ProtoScope;
+ for (Decl *D : Params)
+ S.ActOnReenterCXXMethodParameter(&ProtoScope,
+ dyn_cast_if_present<ParmVarDecl>(D));
+}
+
+Sema::FunctionPrototypeScopeRAII::~FunctionPrototypeScopeRAII() {
+ // ActOnPopScope is what takes the parameters back out of the IdResolver. It
+ // is a no-op otherwise here: a scope holding only ParmVarDecls produces no
+ // end-of-scope diagnostics.
+ S.ActOnPopScope(SourceLocation(), &ProtoScope);
+ S.CurScope = ProtoScope.getParent();
+}
+
+void Sema::ProcessLateParsedTypeAttributesForParams(
+ ArrayRef<Decl *> Params, ParseLateParsedTypeAttributeCB *ParseCB) {
+ // The parameters of a nested prototype are put back in scope by
+ // RebuildParamTypeWithLateParsedAttr::TransformFunctionProtoType. Do the same for
+ // the outermost prototype's own parameters rather than relying on the
+ // caller's scope, so that resolution works wherever this is called from.
+ //
+ // Created on the first parameter that needs it: the parser calls this for
+ // every prototype in C, and almost none carry a late-parsed attribute.
+ std::optional<FunctionPrototypeScopeRAII> ProtoScope;
+
+ for (Decl *D : Params) {
+ auto *PVD = dyn_cast_if_present<ParmVarDecl>(D);
+ if (!PVD || !PVD->getTypeSourceInfo())
+ continue;
+
+ TypeSourceInfo *OldTSI = PVD->getTypeSourceInfo();
+ if (!OldTSI->getType()->hasLateParsedAttr())
+ continue;
+
+ if (!ProtoScope)
+ ProtoScope.emplace(*this, Params);
+
+ RebuildParamTypeWithLateParsedAttr Rebuild(*this, PVD, Params, ParseCB);
+ TypeSourceInfo *TSI = Rebuild.TransformType(OldTSI);
+ if (!TSI) {
+ PVD->setInvalidDecl();
+ continue;
+ }
+ PVD->setTypeSourceInfo(TSI);
+ // A parameter's declared type is the adjusted form of its written type.
+ PVD->setType(Context.getAdjustedParameterType(TSI->getType()));
+ }
+}
+
} // namespace clang
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index dc3564c8b17fd..dd03a6c9b27ec 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -400,11 +400,21 @@ enum TypeAttrLocation {
TAL_DeclName
};
+static void fillAttrNameLocForLateParsedAttrTypeLoc(Sema &S,
+ LateParsedAttrTypeLoc TL) {
+ if (auto *LateAttr = TL.getLateParsedAttribute())
+ if (S.GetLateParsedAttributeLocationCallback)
+ TL.setAttrNameLoc(S.GetLateParsedAttributeLocationCallback(LateAttr));
+}
+
static void
processTypeAttrs(TypeProcessingState &state, QualType &type,
TypeAttrLocation TAL, const ParsedAttributesView &attrs,
CUDAFunctionTarget CFT = CUDAFunctionTarget::HostDevice);
+static void processLateTypeAttrs(TypeProcessingState &state, QualType &type,
+ const LateParsedAttrList &LateAttrs);
+
static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
QualType &type, CUDAFunctionTarget CFT);
@@ -5477,6 +5487,10 @@ static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs(),
S.CUDA().IdentifyTarget(D.getAttributes()));
+ // Wrap the type in a LateParsedAttrType placeholder for any not-yet-parsed
+ // attribute on this chunk, to be resolved once its arguments are in scope.
+ processLateTypeAttrs(state, T, DeclType.LateAttrList);
+
if (DeclType.Kind != DeclaratorChunk::Paren) {
if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
@@ -6248,6 +6262,9 @@ namespace {
void VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
// nothing
}
+ void VisitLateParsedAttrTypeLoc(LateParsedAttrTypeLoc TL) {
+ fillAttrNameLocForLateParsedAttrTypeLoc(State.getSema(), TL);
+ }
void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
// nothing
}
@@ -6415,6 +6432,13 @@ GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
break;
}
+ case TypeLoc::LateParsedAttr: {
+ auto TL = CurrTL.castAs<LateParsedAttrTypeLoc>();
+ fillAttrNameLocForLateParsedAttrTypeLoc(S, TL);
+ CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
+ break;
+ }
+
case TypeLoc::Adjusted:
case TypeLoc::BTFTagAttributed: {
CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
@@ -9384,6 +9408,21 @@ static void processTypeAttrs(TypeProcessingState &state, QualType &type,
}
}
+static void processLateTypeAttrs(TypeProcessingState &state, QualType &type,
+ const LateParsedAttrList &LateAttrs) {
+ if (LateAttrs.empty())
+ return;
+
+ Sema &S = state.getSema();
+ assert(S.ProcessLateParsedTypeAttrCallback &&
+ "late-parsed type attribute without a parser callback");
+
+ // Every attribute has to be offered, even after one is rejected: the
+ // callback is what hands each one to a placeholder or destroys it.
+ for (auto *LA : LateAttrs)
+ S.ProcessLateParsedTypeAttrCallback(LA, type);
+}
+
void Sema::completeExprArrayBound(Expr *E) {
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
>From 55db8aaf9b91403f3abd448eb969289b9cd391b2 Mon Sep 17 00:00:00 2001
From: Holo-xy <mohammedashraf4599 at gmail.com>
Date: Fri, 4 Sep 2026 19:39:46 +0300
Subject: [PATCH 9/9] [Clang] Add tests for counted_by on function parameters
Cover both orderings of the annotated pointer and its count, counts written
in nested function-pointer prototypes, the pointee-kind and referent rules
shared with the struct-field path, and the deferred incomplete-pointee
checks. The AST test pins that both orderings converge on the same
CountAttributedType.
Co-Authored-By: Claude Opus 5 <noreply at anthropic.com>
---
.../AST/attr-counted-by-function-params.c | 43 +++
.../CodeGen/attr-counted-by-function-params.c | 73 ++++
...unted-by-function-params-late-parsed-off.c | 84 ++++
.../Sema/attr-counted-by-function-params.c | 362 ++++++++++++++++++
clang/test/Sema/warn-thread-safety-analysis.c | 5 +
5 files changed, 567 insertions(+)
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-late-parsed-off.c
create mode 100644 clang/test/Sema/attr-counted-by-function-params.c
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 0000000000000..c64d60ef7a81b
--- /dev/null
+++ b/clang/test/AST/attr-counted-by-function-params.c
@@ -0,0 +1,43 @@
+// RUN: %clang_cc1 -fexperimental-late-parse-attributes %s -ast-dump | FileCheck %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)))
+
+//==============================================================================
+// Both declaration orders produce the same CountAttributedType
+//==============================================================================
+
+// Still late-parsed here: that is decided by the attribute and the language
+// option, not by whether the name is already in scope.
+void back_ref(int count, int *__counted_by(count) buf);
+// CHECK-LABEL: FunctionDecl {{.*}} back_ref 'void (int, int * __counted_by(count))'
+// CHECK-NEXT: | |-ParmVarDecl {{.*}} used count 'int'
+// CHECK-NEXT: | `-ParmVarDecl {{.*}} buf 'int * __counted_by(count)':'int *'
+
+// Parsed only once the whole prototype is known.
+void fwd_ref(int *__counted_by(count) buf, int count);
+// CHECK-LABEL: FunctionDecl {{.*}} fwd_ref 'void (int * __counted_by(count), int)'
+// CHECK-NEXT: | |-ParmVarDecl {{.*}} buf 'int * __counted_by(count)':'int *'
+// CHECK-NEXT: | `-ParmVarDecl {{.*}} used count 'int'
+
+void fwd_ref_or_null(int *__counted_by_or_null(count) buf, int count);
+// CHECK-LABEL: FunctionDecl {{.*}} fwd_ref_or_null 'void (int * __counted_by_or_null(count), int)'
+
+void fwd_ref_sized(void *__sized_by(count) buf, int count);
+// CHECK-LABEL: FunctionDecl {{.*}} fwd_ref_sized 'void (void * __sized_by(count), int)'
+
+// Two parameters referring to the same count.
+void two_buffers(int *__counted_by(count) a, int *__counted_by(count) b,
+ int count);
+// CHECK-LABEL: FunctionDecl {{.*}} two_buffers 'void (int * __counted_by(count), int * __counted_by(count), int)'
+
+//==============================================================================
+// The count resolves to the parameter, not the global of the same name
+//==============================================================================
+
+int count;
+void shadowed(int *__counted_by(count) buf, int count);
+// CHECK-LABEL: FunctionDecl {{.*}} shadowed 'void (int * __counted_by(count), int)'
+// CHECK-NEXT: |-ParmVarDecl {{.*}} buf 'int * __counted_by(count)':'int *'
+// CHECK-NEXT: `-ParmVarDecl {{.*}} used count 'int'
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 0000000000000..d6b85b129f410
--- /dev/null
+++ b/clang/test/CodeGen/attr-counted-by-function-params.c
@@ -0,0 +1,73 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fexperimental-late-parse-attributes -DLATE_PARSING -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,LATE
+
+// Test that counted_by on a function parameter is consumed entirely by Sema:
+// CodeGen ignores it, and late parsing does not change what is emitted.
+
+#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)))
+
+// CHECK-LABEL: define dso_local i32 @sum(
+// CHECK-SAME: i32 noundef %count, ptr noundef %buf)
+// CHECK-NOT: counted_by
+// CHECK: getelementptr inbounds i32, ptr
+int sum(int count, int *__counted_by(count) buf) {
+ int t = 0;
+ for (int i = 0; i < count; ++i)
+ t += buf[i];
+ return t;
+}
+
+// CHECK-LABEL: define dso_local i64 @bdos(
+// CHECK-NOT: counted_by.load
+// CHECK: call i64 @llvm.objectsize.i64.p0(
+unsigned long bdos(int count, int *__counted_by(count) buf) {
+ return __builtin_dynamic_object_size(buf, 0);
+}
+
+// CHECK-LABEL: define dso_local void @family(
+// CHECK-SAME: i32 noundef %n, ptr noundef %a, ptr noundef %b, ptr noundef %c)
+// CHECK-NOT: counted_by
+//
+// Verify: the _or_null and byte-count spellings behave the same way
+void family(int n, int *__counted_by(n) a, int *__counted_by_or_null(n) b,
+ void *__sized_by(n) c) {
+ (void)a;
+ (void)b;
+ (void)c;
+}
+
+// CHECK-LABEL: define dso_local void @takes_cb(
+// CHECK-SAME: i32 noundef %n, ptr noundef %cb, ptr noundef %p)
+// CHECK: call void %{{.*}}(i32 noundef %{{.*}}, ptr noundef %{{.*}})
+//
+// Verify: an attribute inside a function-pointer parameter's own prototype
+// does not change the callee's signature
+void takes_cb(int n, void (*cb)(int m, int *__counted_by(m) q),
+ int *__counted_by(n) p) {
+ cb(n, p);
+}
+
+void sum_redecl(int count, int *__counted_by(count) buf);
+void sum_redecl(int count, int *buf);
+
+// CHECK-LABEL: define dso_local i32 @call_site(
+// CHECK: call i32 @sum(i32 noundef 4, ptr noundef %{{.*}})
+//
+// Verify: declaring with the attribute and defining without it does not split
+// the symbol
+int call_site(void) {
+ int a[4];
+ return sum(4, a);
+}
+
+#ifdef LATE_PARSING
+// LATE-LABEL: define dso_local i32 @fwd_ref(
+// LATE-SAME: ptr noundef %buf, i32 noundef %count)
+// LATE-NOT: counted_by
+// LATE: getelementptr inbounds i32, ptr
+//
+// Verify: a count declared after the annotated parameter emits identically
+int fwd_ref(int *__counted_by(count) buf, int count) { return buf[count - 1]; }
+#endif
diff --git a/clang/test/Sema/attr-counted-by-function-params-late-parsed-off.c b/clang/test/Sema/attr-counted-by-function-params-late-parsed-off.c
new file mode 100644
index 0000000000000..56d603e5ae026
--- /dev/null
+++ b/clang/test/Sema/attr-counted-by-function-params-late-parsed-off.c
@@ -0,0 +1,84 @@
+// RUN: %clang_cc1 -DNEEDS_LATE_PARSING -fno-experimental-late-parse-attributes -fsyntax-only -verify %s
+// RUN: %clang_cc1 -DNEEDS_LATE_PARSING -fsyntax-only -verify %s
+
+// RUN: %clang_cc1 -UNEEDS_LATE_PARSING -fno-experimental-late-parse-attributes -fsyntax-only -verify=ok %s
+// RUN: %clang_cc1 -UNEEDS_LATE_PARSING -fsyntax-only -verify=ok %s
+
+// On a parameter the argument is always parsed at the end of the prototype, so
+// the language option decides only whether a count declared *after* the
+// annotated parameter may be named.
+
+#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)))
+
+#ifdef NEEDS_LATE_PARSING
+
+// expected-error at +1{{'counted_by' argument 'count' is declared after the annotated pointer; referring to a later parameter requires '-fexperimental-late-parse-attributes'}}
+void fwd_ref(int *__counted_by(count) buf, int count);
+
+// expected-error at +1{{'counted_by_or_null' argument 'count' is declared after the annotated pointer; referring to a later parameter requires '-fexperimental-late-parse-attributes'}}
+void fwd_ref_or_null(int *__counted_by_or_null(count) buf, int count);
+
+// expected-error at +1{{'sized_by' argument 'count' is declared after the annotated pointer; referring to a later parameter requires '-fexperimental-late-parse-attributes'}}
+void fwd_ref_sized(void *__sized_by(count) buf, int count);
+
+// expected-error at +1{{'sized_by_or_null' argument 'count' is declared after the annotated pointer; referring to a later parameter requires '-fexperimental-late-parse-attributes'}}
+void fwd_ref_sized_or_null(void *__sized_by_or_null(count) buf, int count);
+
+// A count in a nested prototype is a forward reference just the same.
+// expected-error at +1{{'counted_by' argument 'len' is declared after the annotated pointer; referring to a later parameter requires '-fexperimental-late-parse-attributes'}}
+void inner_fwd_ref(void (*cb)(int *__counted_by(len) p, int len));
+
+// Decided by parameter order, not source location: one macro expansion gives
+// the attribute and the count the same expansion location.
+#define PARAMS int *__counted_by(count) buf, int count
+// expected-error at +1{{'counted_by' argument 'count' is declared after the annotated pointer; referring to a later parameter requires '-fexperimental-late-parse-attributes'}}
+void macro_fwd_ref(PARAMS);
+
+// The same, written after the declarator.
+#define PARAMS_TRAILING int *buf __counted_by(count), int count
+// expected-error at +1{{'counted_by' argument 'count' is declared after the annotated pointer; referring to a later parameter requires '-fexperimental-late-parse-attributes'}}
+void macro_fwd_ref_trailing(PARAMS_TRAILING);
+
+#else
+
+// ok-no-diagnostics
+
+// A count already in scope needs nothing from the language option.
+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);
+
+// The count and the annotated pointer may be separated by other parameters.
+void back_ref_interleaved(int count, int other, int *__counted_by(count) buf);
+
+// Several parameters may share one count.
+void two_buffers(int count, int *__counted_by(count) a,
+ int *__counted_by(count) b);
+
+// A nested prototype's own earlier parameter is in scope for the same reason.
+void inner_back_ref(void (*cb)(int len, int *__counted_by(len) p));
+
+// So is an enclosing prototype's earlier parameter: that clause is still being
+// parsed, so its scope holds only what precedes the callback.
+void outer_back_ref(int n, void (*cb)(int *__counted_by(n) p));
+
+// A macro-built list is accepted for the same reason: the count still precedes.
+#define PARAMS_OK int count, int *__counted_by(count) buf
+void macro_back_ref(PARAMS_OK);
+
+#define PARAMS_OK_TRAILING int count, int *buf __counted_by(count)
+void macro_back_ref_trailing(PARAMS_OK_TRAILING);
+
+// A definition, not just a prototype.
+int sum(int count, int *__counted_by(count) buf) {
+ int total = 0;
+ for (int i = 0; i < count; ++i)
+ total += buf[i];
+ return total;
+}
+
+#endif
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 0000000000000..bd3ecc8cb46c3
--- /dev/null
+++ b/clang/test/Sema/attr-counted-by-function-params.c
@@ -0,0 +1,362 @@
+// RUN: %clang_cc1 -fexperimental-late-parse-attributes -fblocks -Wpointer-arith -fsyntax-only -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)))
+
+struct size_unknown;
+struct size_known {
+ int field;
+};
+
+//==============================================================================
+// Valid: the count parameter 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);
+
+//==============================================================================
+// Valid: the count parameter is declared *after* the annotated pointer
+//==============================================================================
+
+// Requires late parsing: `count` is not yet in scope where it is written.
+void fwd_ref(int *__counted_by(count) buf, int count);
+void fwd_ref_or_null(int *__counted_by_or_null(count) buf, int count);
+void fwd_ref_sized(void *__sized_by(count) buf, int count);
+
+// The annotated pointer and the count may be separated by other parameters.
+void fwd_ref_interleaved(int *__counted_by(count) buf, int other, int count);
+
+// Several parameters may refer to the same count.
+void two_buffers(int *__counted_by(count) a, int *__counted_by(count) b,
+ int count);
+
+// Both orderings in one prototype.
+void mixed(int first, int *__counted_by(first) a, int *__counted_by(second) b,
+ int second);
+
+// Incomplete pointee types are allowed, as for struct fields.
+void incomplete_pointee(struct size_unknown *__counted_by(count) buf,
+ int count); // ok
+void const_pointee(const struct size_known *__counted_by(count) buf,
+ int count); // ok
+
+// Binds to the `*` immediately preceding it, so it annotates the parameter.
+void outer_of_two(int **__counted_by(count) buf, int count);
+
+// Qualifiers on the annotated pointer itself do not disturb the attribute.
+void qualified_ptr(int *__counted_by(count) const buf, int count); // ok
+
+// A definition, not just a prototype.
+int sum(int *__counted_by(count) buf, int count) {
+ int total = 0;
+ for (int i = 0; i < count; ++i)
+ total += buf[i];
+ return total;
+}
+
+//==============================================================================
+// Valid: the attribute written after the declarator
+//==============================================================================
+
+// The spelling struct fields use. It describes the parameter's own type just as
+// the spelling inside the declarator does, in either order.
+void trailing_or_null(int *buf __counted_by_or_null(count), int count);
+void trailing_sized(void *buf __sized_by(count), int count);
+void trailing_sized_or_null(void *buf __sized_by_or_null(count), int count);
+
+// Applies to the parameter's own pointer, as the leading spelling does.
+void trailing_outer_of_two(int **buf __counted_by(count), int count);
+
+// The count may be separated from the annotated pointer.
+void trailing_interleaved(int *buf __counted_by(count), int other, int count);
+
+// The two spellings may be mixed within one prototype.
+void trailing_mixed(int *__counted_by(count) a, int *b __counted_by(count),
+ int count);
+
+// A definition, not just a prototype.
+int trailing_sum(int *buf __counted_by(count), int count) {
+ int total = 0;
+ for (int i = 0; i < count; ++i)
+ total += buf[i];
+ return total;
+}
+
+//==============================================================================
+// Invalid: the attribute written after the declarator, on an unsupported type
+//==============================================================================
+
+// The trailing spelling reaches the same checks as the leading one.
+
+// expected-error at +1{{'counted_by' only applies to pointers or C99 flexible array members}}
+void trailing_on_array(int arr[10] __counted_by(count), int count);
+
+// No declarator chunk, so it is left to the declaration-attribute path.
+// expected-error at +1{{'counted_by' attribute only applies to non-static data members}}
+void trailing_on_int(int count, int x __counted_by(count));
+// Being eagerly parsed, it also cannot see a count declared after it.
+// expected-error at +1{{use of undeclared identifier 'count'}}
+void trailing_on_int_fwd(int x __counted_by(count), int count);
+
+//==============================================================================
+// Invalid: the argument does not name a parameter of this function
+//==============================================================================
+
+int global_count;
+
+// expected-error at +1{{'counted_by' argument 'global_count' is not a parameter of the same function as the annotated pointer}}
+void not_a_param(int *__counted_by(global_count) buf);
+
+// expected-error at +1{{use of undeclared identifier 'nope'}}
+void undeclared(int *__counted_by(nope) buf);
+
+// A count on a nested prototype's parameter may name an enclosing prototype's
+// parameter: the callback is only called where that parameter is in scope.
+void outer_param_ok(int n, void (*cb)(int *__counted_by(n) p));
+
+// Two levels of nesting are allowed for the same reason.
+void outer_param_two_levels(int n,
+ void (*cb)(void (*inner)(int *__counted_by(n) p)));
+
+// The same shape, but referring to the inner prototype's own parameter.
+void inner_param_ok(void (*cb)(int *__counted_by(m) p, int m));
+
+// A return type is stricter: the pointer outlives the call, so a bound naming
+// the caller's parameter says nothing checkable about it.
+// expected-error at +1{{'counted_by' argument 'n' is not a parameter of the same function as the annotated pointer}}
+void outer_param_leak_return(int n, int *__counted_by(n) (*cb)(int m));
+
+// Its own prototype's parameter is fine there.
+void inner_param_ok_return(int *__counted_by(m) (*cb)(int m));
+
+// Parsed at the end of the parameter clause, so this fails in lookup.
+// expected-error at +1{{use of undeclared identifier 'later_global'}}
+void global_declared_later(int *__counted_by(later_global) buf);
+int later_global;
+
+//==============================================================================
+// Invalid: the argument must be a simple declaration reference
+//==============================================================================
+
+// expected-error at +1{{'counted_by' argument must be a simple declaration reference}}
+void not_simple_ref(int *__counted_by(count + 1) buf, int count);
+
+// expected-error at +1{{'counted_by' argument must be a simple declaration reference}}
+void not_simple_ref_deref(int *__counted_by(*count) buf, int *count);
+
+// Rejected as on the struct-field path: the count must itself be the reference.
+// expected-error at +1{{'counted_by' argument must be a simple declaration reference}}
+void not_simple_ref_paren(int *__counted_by((count)) buf, int count);
+
+// Meaningful under -fbounds-safety, but not supported here.
+// expected-error at +1{{'counted_by' argument must be a simple declaration reference}}
+void count_is_literal(int *__counted_by(4) buf);
+
+//==============================================================================
+// Invalid: the count parameter must have a non-boolean integer type
+//==============================================================================
+
+// expected-error at +1{{'counted_by' requires a non-boolean integer type argument}}
+void count_is_ptr(int *__counted_by(count) buf, int *count);
+
+// expected-error at +1{{'counted_by' requires a non-boolean integer type argument}}
+void count_is_float(int *__counted_by(count) buf, float count);
+
+// expected-error at +1{{'counted_by' requires a non-boolean integer type argument}}
+void count_is_bool(int *__counted_by(count) buf, _Bool count);
+
+//==============================================================================
+// Attributes in the declaration-specifiers are not part of this mechanism
+//==============================================================================
+
+// Parsed eagerly and handled as declaration attributes; pre-existing behavior,
+// recorded so a change is noticed.
+
+// expected-error at +1{{use of undeclared identifier 'count'}}
+void on_int(int __counted_by(count) buf, int count);
+
+// With `count` already in scope, it reaches the declaration-attribute path,
+// whose subject list only permits struct fields.
+// expected-error at +1{{'counted_by' attribute only applies to non-static data members}}
+void on_int_count_first(int count, int __counted_by(count) buf);
+
+//==============================================================================
+// Invalid: nested pointers are not supported for parameters
+//==============================================================================
+
+// Bounds on a pointer that is not the parameter itself are never checked.
+
+// expected-error at +1{{'counted_by' is not supported on a nested pointer; it must apply to the annotated declaration's own type}}
+void nested(int *__counted_by(count) *buf, int count);
+
+// expected-error at +1{{'sized_by' is not supported on a nested pointer; it must apply to the annotated declaration's own type}}
+void nested_sized(void *__sized_by(count) *buf, int count);
+
+// expected-error at +1{{'counted_by_or_null' is not supported on a nested pointer; it must apply to the annotated declaration's own type}}
+void nested_or_null(int *__counted_by_or_null(count) *buf, int count);
+
+// _Atomic is a real AtomicType node, not sugar; the walk must step through it.
+// expected-error at +1{{'counted_by' is not supported on a nested pointer; it must apply to the annotated declaration's own type}}
+void nested_atomic(int *__counted_by(count) * _Atomic buf, int count);
+
+//==============================================================================
+// Valid: the count names a nested function-pointer prototype's own parameters
+//==============================================================================
+
+// Both its parameters and its return type may be annotated.
+void inner_return(int *__counted_by(len) (*cb)(int len), int other);
+void inner_return_sized(void *__sized_by(len) (*cb)(int len));
+void inner_param_and_return(
+ int *__counted_by(len) (*cb)(int *__counted_by(len) p, int len));
+
+// Spelled as a function, which adjusts to a function pointer.
+void inner_return_fn(int *__counted_by(len) cb(int len)); // ok
+
+// The inner prototype's parameter shadows the outer one, and wins.
+void inner_shadows_outer(int len, int *__counted_by(len) (*cb)(int len));
+
+// A parameter shadowing a global binds to the parameter. The second needs the
+// inner prototype's scope re-entered, since it is gone by then.
+void shadows_global(int *__counted_by(global_count) buf, int global_count);
+void inner_shadows_global(void (*cb)(int *__counted_by(global_count) p,
+ int global_count));
+
+// With no parameter to shadow it, the same spelling reaches the global.
+// expected-error at +1{{'counted_by' argument 'global_count' is not a parameter of the same function as the annotated pointer}}
+void inner_reaches_global(void (*cb)(int *__counted_by(global_count) p));
+
+//==============================================================================
+// Invalid: a count in the return type of a *no-prototype* inner function
+//==============================================================================
+
+// `()` is a FunctionNoProtoType, which declares no parameters, so no count in
+// its return type can name one. Lookup still finds the enclosing prototype's.
+
+// expected-error at +1{{'counted_by' argument 'len' is not a parameter of the same function as the annotated pointer}}
+void noproto_reaches_outer_param(int *__counted_by(len) (*cb)(), int len);
+
+// expected-error at +1{{'sized_by' argument 'len' is not a parameter of the same function as the annotated pointer}}
+void noproto_reaches_outer_param_sized(void *__sized_by(len) (*cb)(), int len);
+
+// The same shape spelled as a function rather than a function pointer.
+// expected-error at +1{{'counted_by' argument 'len' is not a parameter of the same function as the annotated pointer}}
+void noproto_fn_reaches_outer_param(int *__counted_by(len) cb(), int len);
+
+// Rejected for not naming a parameter, not by the no-prototype handling.
+// expected-error at +1{{'counted_by' argument 'global_count' is not a parameter of the same function as the annotated pointer}}
+void noproto_reaches_global(int *__counted_by(global_count) (*cb)());
+
+// `(void)` is a zero-parameter FunctionProtoType, so it takes that path.
+// expected-error at +1{{'counted_by' argument 'len' is not a parameter of the same function as the annotated pointer}}
+void protovoid_reaches_outer_param(int *__counted_by(len) (*cb)(void), int len);
+
+//==============================================================================
+// Invalid: the attribute is not on any declaration's own type
+//==============================================================================
+
+// Rejected rather than ignored: a placeholder must never reach the finalized
+// AST, which asserts on it when serialized.
+
+// Applies to the array's element type, not to the parameter.
+// expected-error at +1{{'counted_by' is not supported on an array element; it must apply to the annotated declaration's own type}}
+void on_array_element(int *__counted_by(count) buf[10], int count);
+
+// The return type may only name that prototype's own parameters; it has none.
+// expected-error at +1{{'counted_by' argument 'count' is not a parameter of the same function as the annotated pointer}}
+void on_fn_ptr_return(int *__counted_by(count) (*cb)(void), int count);
+
+// The same, spelled as a function parameter rather than a function pointer.
+// expected-error at +1{{'counted_by' argument 'count' is not a parameter of the same function as the annotated pointer}}
+void on_fn_return(int *__counted_by(count) cb(void), int count);
+
+// An already-invalid prototype must not leave a placeholder behind. The count
+// is a global, since naming the enclosing parameter would be valid here.
+// expected-error at +1{{'counted_by' argument 'global_count' is not a parameter of the same function as the annotated pointer}}
+void outer_then_nested(int n, void (*cb)(int *__counted_by(global_count) p));
+// expected-error at +1{{'counted_by' is not supported on a nested pointer; it must apply to the annotated declaration's own type}}
+void after_invalid_nested(int *__counted_by(count) *buf, int count);
+
+//==============================================================================
+// Invalid: the annotated type is not a pointer at all.
+//==============================================================================
+
+// A block pointer shares the declarator syntax but is not a pointer type, so it
+// must be rejected here too rather than silently dropped.
+// expected-error at +1{{'counted_by' only applies to pointers or C99 flexible array members}}
+void on_block_pointer(int (^__counted_by(count) blk)(void), int count);
+
+// An _Atomic pointer is an AtomicType, so no placeholder is created at all.
+// expected-error at +1{{'counted_by' only applies to pointers or C99 flexible array members}}
+void on_atomic_pointer(int *__counted_by(count) _Atomic p, int count);
+
+//==============================================================================
+// Invalid: the pointee type cannot support bounds computation
+//==============================================================================
+
+// Parameters share the struct-field path's pointee rules.
+
+struct fam { int count; int elems[]; };
+
+// expected-error at +1{{'counted_by' cannot be applied to a pointer with pointee of unknown size because 'void (int)' is a function type}}
+void fn_pointee(void (*__counted_by(count) fp)(int), int count);
+
+// expected-error at +1{{'sized_by' cannot be applied to a pointer with pointee of unknown size because 'void (int)' is a function type}}
+void fn_pointee_sized(void (*__sized_by(count) fp)(int), int count);
+
+// expected-error at +1{{'counted_by' cannot be applied to a pointer with pointee of unknown size because 'struct fam' is a struct type with a flexible array member}}
+void fam_pointee(struct fam *__counted_by(count) p, int count);
+
+// A GNU extension, warned on exactly as for a struct field.
+// expected-warning at +2{{'counted_by' on a pointer to void is a GNU extension, treated as 'sized_by'}}
+// expected-note at +1{{use '__sized_by' to suppress this warning}}
+void void_pointee(void *__counted_by(count) p, int count);
+
+//==============================================================================
+// The deferred incomplete-pointee model applies to parameters as to fields
+//==============================================================================
+
+// Accepted while the pointee may still be completed; each use then requires the
+// complete type.
+
+// expected-note at +1 2{{consider providing a complete definition for 'struct deferred_pointee'}}
+struct deferred_pointee;
+
+void take_deferred(struct deferred_pointee *q);
+
+// expected-note at +1{{consider using '__sized_by' instead of '__counted_by'}}
+void deferred_use(struct deferred_pointee *__counted_by(count) p, int count) {
+ // expected-error at +1{{cannot use 'p' with '__counted_by' attributed type 'struct deferred_pointee * __counted_by(count)' (aka 'struct deferred_pointee *') because the pointee type 'struct deferred_pointee' is incomplete}}
+ take_deferred(p);
+}
+
+// expected-note at +1{{consider using '__sized_by' instead of '__counted_by'}}
+void deferred_assign(struct deferred_pointee *__counted_by(count) p, int count,
+ struct deferred_pointee *q) {
+ // expected-error at +1{{cannot assign to 'p' with '__counted_by' attributed type 'struct deferred_pointee * __counted_by(count)' (aka 'struct deferred_pointee *') because the pointee type 'struct deferred_pointee' is incomplete}}
+ p = q;
+}
+
+//==============================================================================
+// Where the attribute sits in the parameter's declarator
+//==============================================================================
+
+// The type position -- after the '*', before the identifier -- is late parsed.
+void pos_type_fwd(int *__counted_by(count) buf, int count);
+void pos_type_back(int count, int *__counted_by(count) buf);
+
+// So is the position after the declarator; both give the same type.
+void pos_declname_back(int count, int *buf __counted_by(count));
+void pos_declname_fwd(int *buf __counted_by(count), int count);
+
+// The declaration-specifier position is not: there it stays a declaration
+// attribute, never reaching the type.
+
+// expected-error at +1{{'counted_by' attribute only applies to non-static data members}}
+void pos_declspec_back(int count, __counted_by(count) int *buf);
+// expected-error at +1{{use of undeclared identifier 'count'}}
+void pos_declspec_fwd(__counted_by(count) int *buf, int count);
diff --git a/clang/test/Sema/warn-thread-safety-analysis.c b/clang/test/Sema/warn-thread-safety-analysis.c
index c61152d59a7dd..6d22ddc7ba359 100644
--- a/clang/test/Sema/warn-thread-safety-analysis.c
+++ b/clang/test/Sema/warn-thread-safety-analysis.c
@@ -413,6 +413,11 @@ void test_trylock_void_conditional_via_var(void) {
// attribute in a single __attribute__.
void run(void) __attribute__((guarded_by(mu1), guarded_by(mu1))); // expected-warning 2{{only applies to non-static data members and global variables}}
+// Under late parsing, a guarded_by written in the type-qualifier position of
+// a function parameter used to be captured by the type-attr-only late list
+// and silently dropped, losing the warning below.
+void misplaced_in_param(int *__attribute__((guarded_by(mu1))) p); // expected-warning {{only applies to non-static data members and global variables}}
+
int value_with_multiple_guarded_args GUARDED_BY(mu1, mu2);
int *ptr_with_multiple_guarded_args PT_GUARDED_BY(mu1, mu2);
More information about the cfe-commits
mailing list