[clang] [clang] Add a new nonnull_if_nonzero attribute (PR #248827)
Chris Down via cfe-commits
cfe-commits at lists.llvm.org
Fri Dec 4 00:06:54 PST 2026
https://github.com/cdown created https://github.com/llvm/llvm-project/pull/248827
In systemd, we are making use of this to catch NULL buffers being passed with a nonzero size to helpers like `hexmem()` and `random_bytes()`, but we can only do that in GCC 15 and later right now [0]. It would be great to also have those checks enforced when using Clang. It was also mentioned in the review of #160988 [1] that this may be useful for APIs like `memcpy()` and `fread()`, which accept a null pointer only when a size or count is zero.
For context, GCC 15 added `nonnull_if_nonzero(p, n)` [2], which says that pointer parameter `p` must not be null when integer parameter `n` is nonzero. It is meant for functions like `memcpy()`, where C2y (N3322) permits a null pointer as long as the length is zero. GCC 16 then added `nonnull_if_nonzero(p, n, m)`, where `p` must not be null when `n` and `m` are both nonzero. That form is meant for functions like `fread()`, which take both a size and a count.
Let's add both forms. Unlike `nonnull`, the indices cannot refer to variadic arguments (which GCC doesn't allow either).
In terms of differences, GCC drops the attribute with a warning when an index is out of range or a parameter has the wrong type, whereas Clang makes both errors, in the vein of `alloc_size`, `alloc_align` and friends.
The attribute does not yet affect code generation, `-fsanitize=nonnull-attribute` or constant evaluation, so a call in a `static_assert` is not diagnosed. Let me know if you'd like to have that now, but for now I kept it simple.
Claude helped in generating tests, I have reviewed them and am happy with them and their coverage.
[0]: https://github.com/systemd/systemd/blob/6871ff4b831560e527b95fdd36df048e4c1c8776/src/fundamental/macro.h#L111-L115
[1]: https://github.com/llvm/llvm-project/pull/160988#issuecomment-3402674805
[2]: https://gcc.gnu.org/onlinedocs/gcc/Common-Attributes.html#index-nonnull_005fif_005fnonzero
>From 2373c5af0e00acd7074c2708bd3e465f3bd32b32 Mon Sep 17 00:00:00 2001
From: Chris Down <chris at chrisdown.name>
Date: Thu, 3 Dec 2026 09:27:34 -0800
Subject: [PATCH] [clang] Add a new nonnull_if_nonzero attribute
In systemd, we are making use of this to catch NULL buffers being
passed with a nonzero size to helpers like hexmem() and random_bytes(),
but we can only do that in GCC 15 and later right now [0]. It would be
great to also have those checks enforced when using Clang. It was also
mentioned in the review of #160988 [1] that this may be useful for APIs
like memcpy() and fread(), which accept a null pointer only when a size
or count is zero.
For context, GCC 15 added nonnull_if_nonzero(p, n) [2], which says that
pointer parameter p must not be null when integer parameter n is
nonzero. It is meant for functions like memcpy(), where C2y (N3322)
permits a null pointer as long as the length is zero. GCC 16 then added
nonnull_if_nonzero(p, n, m), where p must not be null when n and m are
both nonzero. That form is meant for functions like fread(), which take
both a size and a count.
Let's add both forms. Unlike nonnull, the indices cannot refer to
variadic arguments (which GCC doesn't allow either).
In terms of differences, GCC drops the attribute with a warning when an
index is out of range or a parameter has the wrong type, whereas Clang
makes both errors, in the vein of alloc_size, alloc_align and friends.
The attribute does not yet affect code generation,
-fsanitize=nonnull-attribute or constant evaluation, so a call in a
static_assert is not diagnosed. Let me know if you'd like to have that
now, but for now I kept it simple.
Claude helped in generating tests, I have reviewed them and am happy
with them and their coverage.
[0]: https://github.com/systemd/systemd/blob/6871ff4b831560e527b95fdd36df048e4c1c8776/src/fundamental/macro.h#L111-L115
[1]: https://github.com/llvm/llvm-project/pull/160988#issuecomment-3402674805
[2]: https://gcc.gnu.org/onlinedocs/gcc/Common-Attributes.html#index-nonnull_005fif_005fnonzero
---
clang/docs/ReleaseNotes.md | 18 ++
clang/include/clang/Basic/Attr.td | 10 ++
clang/include/clang/Basic/AttrDocs.td | 44 +++++
clang/lib/Sema/SemaChecking.cpp | 26 +++
clang/lib/Sema/SemaDeclAttr.cpp | 40 +++++
clang/test/AST/attr-print-emit.cpp | 12 ++
clang/test/Sema/attr-nonnull-if-nonzero.c | 166 ++++++++++++++++++
.../test/SemaCXX/attr-nonnull-if-nonzero.cpp | 128 ++++++++++++++
clang/test/SemaObjC/attr-nonnull-if-nonzero.m | 30 ++++
9 files changed, 474 insertions(+)
create mode 100644 clang/test/Sema/attr-nonnull-if-nonzero.c
create mode 100644 clang/test/SemaCXX/attr-nonnull-if-nonzero.cpp
create mode 100644 clang/test/SemaObjC/attr-nonnull-if-nonzero.m
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 9af260e7ff4769..60c660acb97c11 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -577,6 +577,24 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
`s->dst.len`, and is reported as `dst->Scratch::lock` when no enclosing
object is reachable.
+- Added support for GCC's `nonnull_if_nonzero` attribute, which marks a
+ pointer parameter as nonnull only when an integer parameter is nonzero, or
+ in its three-argument form, only when two integer parameters are both
+ nonzero. `-Wnonnull` diagnoses a call which passes a null pointer constant
+ together with nonzero constants:
+
+ ```c
+ void copy(void *dst, const void *src, size_t n)
+ __attribute__((nonnull_if_nonzero(1, 3), nonnull_if_nonzero(2, 3)));
+ void read_items(void *buf, size_t size, size_t count)
+ __attribute__((nonnull_if_nonzero(1, 2, 3)));
+
+ copy(NULL, NULL, 0); // OK
+ copy(NULL, NULL, 4); // warning: null passed to a callee that requires a non-null argument
+ read_items(NULL, 4, 0); // OK
+ read_items(NULL, 4, 4); // warning: null passed to a callee that requires a non-null argument
+ ```
+
### Improvements to Clang's diagnostics
- Errors for invalid element types during instantiation of an `ext_vector_type`
diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td
index 806debfe13cda8..ee2646280897f2 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2670,6 +2670,16 @@ def NonNull : InheritableParamAttr {
let Documentation = [NonNullDocs];
}
+def NonNullIfNonZero : InheritableAttr {
+ let Spellings = [GCC<"nonnull_if_nonzero">];
+ let Subjects = SubjectList<[HasFunctionProto]>;
+ let Args = [ParamIdxArgument<"PointerParam">,
+ ParamIdxArgument<"IntegerParam">,
+ ParamIdxArgument<"SecondIntegerParam", /*opt=*/ 1>];
+ let InheritEvenIfAlreadyPresent = 1;
+ let Documentation = [NonNullIfNonZeroDocs];
+}
+
def ReturnsNonNull : InheritableAttr {
let Spellings = [GCC<"returns_nonnull">];
let Subjects = SubjectList<[ObjCMethod, Function]>;
diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td
index 5ff48c25d4e7db..288cd534701ac1 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -5775,6 +5775,50 @@ system) and does not imply undefined behavior, making it more widely applicable.
}];
}
+def NonNullIfNonZeroDocs : Documentation {
+ let Category = NullabilityDocs;
+ let Content = [{
+The `nonnull_if_nonzero` attribute is a conditional form of the `nonnull`
+attribute for functions (or Objective-C methods) which accept a null pointer
+only when there is nothing for the pointer to refer to, such as a buffer which
+may be null when its length is zero. It takes two or three parameter indices:
+the first names a parameter of pointer type, and each of the others names a
+parameter of integer or enumeration type other than `bool`. The pointer must
+not be null when the integer is nonzero, and may be null when the integer is
+zero. With three indices, the pointer must not be null when both integers are
+nonzero, and may be null when either of them is zero. A function can have
+several of these attributes to describe more than one pointer parameter. For
+example:
+
+```c
+extern void * my_memcpy (void *dest, const void *src, size_t len)
+ __attribute__((nonnull_if_nonzero (1, 3),
+ nonnull_if_nonzero (2, 3)));
+extern size_t my_fread (void *buf, size_t size, size_t count, FILE *stream)
+ __attribute__((nonnull_if_nonzero (1, 2, 3)));
+```
+
+Here, `my_memcpy (NULL, NULL, 0)` is a valid call, but
+`my_memcpy (NULL, NULL, 4)` is not. Likewise, `my_fread (NULL, 4, 0, stream)`
+and `my_fread (NULL, 0, 4, stream)` are valid calls, but
+`my_fread (NULL, 4, 4, stream)` is not. Parameter indices start at one, and as
+with `nonnull`, the implicit `this` parameter of a non-static member function
+is counted as the first parameter and cannot itself be named by the attribute.
+
+Clang diagnoses a call under `-Wnonnull` when the pointer argument is a null
+pointer constant and each integer argument is a nonzero constant. Unlike with
+`nonnull`, the attribute does not currently affect constant evaluation, code
+generation or `-fsanitize=nonnull-attribute`, so such a call is not diagnosed
+in a constant-evaluated context, such as a `static_assert`, the initializer of
+a `constexpr` variable or the body of a `consteval` function.
+
+This attribute is compatible with
+[GCC's attribute of the same name](https://gcc.gnu.org/onlinedocs/gcc/Common-Attributes.html#index-nonnull_005fif_005fnonzero),
+which has had the two-argument form since GCC 15 and the three-argument form
+since GCC 16.
+ }];
+}
+
def RestrictDocs : Documentation {
let Category = DocCatFunction;
let Heading = "malloc";
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 7355ab4749d6c1..e19d2ed0cc8466 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -4609,6 +4609,32 @@ static void CheckNonNullArguments(Sema &S,
NonNullArgs.set(IdxAST);
}
}
+
+ for (const auto *A : FDecl->specific_attrs<NonNullIfNonZeroAttr>()) {
+ unsigned PointerIdx = A->getPointerParam().getASTIndex();
+ if (PointerIdx >= Args.size() ||
+ !S.isValidPointerAttrType(Args[PointerIdx]->getType()))
+ continue;
+
+ auto IsNonZeroConstant = [&](ParamIdx Idx) {
+ if (Idx.getASTIndex() >= Args.size())
+ return false;
+ const Expr *Arg = Args[Idx.getASTIndex()];
+ Expr::EvalResult Result;
+ return !Arg->getType()->isBooleanType() && !Arg->isValueDependent() &&
+ Arg->EvaluateAsInt(Result, S.Context) &&
+ !Result.Val.getInt().isZero();
+ };
+
+ ParamIdx SecondIntegerIdx = A->getSecondIntegerParam();
+ if (!IsNonZeroConstant(A->getIntegerParam()) ||
+ (SecondIntegerIdx.isValid() && !IsNonZeroConstant(SecondIntegerIdx)))
+ continue;
+
+ if (NonNullArgs.empty())
+ NonNullArgs.resize(Args.size());
+ NonNullArgs.set(PointerIdx);
+ }
}
if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 9bf629229f0f79..13dbfcf6471e5d 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -1474,6 +1474,43 @@ static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
}
+static void handleNonNullIfNonZeroAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
+ Expr *PointerExpr = AL.getArgAsExpr(0);
+ ParamIdx PointerIdx;
+ if (!S.checkFunctionOrMethodParameterIndex(D, AL, 1, PointerExpr, PointerIdx))
+ return;
+
+ if (!S.isValidPointerAttrType(
+ getFunctionOrMethodParamType(D, PointerIdx.getASTIndex()))) {
+ S.Diag(PointerExpr->getBeginLoc(), diag::err_attribute_pointers_only)
+ << AL << 0
+ << getFunctionOrMethodParamRange(D, PointerIdx.getASTIndex());
+ return;
+ }
+
+ ParamIdx IntegerIdxs[2];
+ for (unsigned I = 1, E = AL.getNumArgs(); I != E; ++I) {
+ Expr *IntegerExpr = AL.getArgAsExpr(I);
+ ParamIdx &IntegerIdx = IntegerIdxs[I - 1];
+ if (!S.checkFunctionOrMethodParameterIndex(D, AL, I + 1, IntegerExpr,
+ IntegerIdx))
+ return;
+
+ QualType IntegerTy =
+ getFunctionOrMethodParamType(D, IntegerIdx.getASTIndex());
+ if (!IntegerTy->isDependentType() &&
+ (!IntegerTy->isIntegralOrEnumerationType() ||
+ IntegerTy->isBooleanType())) {
+ S.Diag(IntegerExpr->getBeginLoc(), diag::err_attribute_integers_only)
+ << AL << getFunctionOrMethodParamRange(D, IntegerIdx.getASTIndex());
+ return;
+ }
+ }
+
+ D->addAttr(::new (S.Context) NonNullIfNonZeroAttr(
+ S.Context, AL, PointerIdx, IntegerIdxs[0], IntegerIdxs[1]));
+}
+
static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
QualType ResultType = getFunctionOrMethodResultType(D);
SourceRange SR = getFunctionOrMethodResultSourceRange(D);
@@ -8010,6 +8047,9 @@ ProcessDeclAttribute(Sema &S, Decl *D, const ParsedAttr &AL,
else
handleNonNullAttr(S, D, AL);
break;
+ case ParsedAttr::AT_NonNullIfNonZero:
+ handleNonNullIfNonZeroAttr(S, D, AL);
+ break;
case ParsedAttr::AT_ReturnsNonNull:
handleReturnsNonNullAttr(S, D, AL);
break;
diff --git a/clang/test/AST/attr-print-emit.cpp b/clang/test/AST/attr-print-emit.cpp
index 66dbc50ecfd3c1..5ccec3da9a1bca 100644
--- a/clang/test/AST/attr-print-emit.cpp
+++ b/clang/test/AST/attr-print-emit.cpp
@@ -25,6 +25,12 @@ char *fmta(int, const char *) __attribute__((format_arg(2)));
// CHECK: void nn(int *, int *) __attribute__((nonnull(1, 2)));
void nn(int *, int *) __attribute__((nonnull(1, 2)));
+// CHECK: void nninz(int *, int) __attribute__((nonnull_if_nonzero(1, 2)));
+void nninz(int *, int) __attribute__((nonnull_if_nonzero(1, 2)));
+
+// CHECK: void nninz3(int *, int, int) __attribute__((nonnull_if_nonzero(1, 2, 3)));
+void nninz3(int *, int, int) __attribute__((nonnull_if_nonzero(1, 2, 3)));
+
// CHECK: int *aa(int i) __attribute__((alloc_align(1)));
int *aa(int i) __attribute__((alloc_align(1)));
@@ -58,6 +64,12 @@ class C {
// CHECK: void nn(int *, int *) __attribute__((nonnull(2, 3)));
void nn(int *, int *) __attribute__((nonnull(2, 3)));
+ // CHECK: void nninz(int *, int) __attribute__((nonnull_if_nonzero(2, 3)));
+ void nninz(int *, int) __attribute__((nonnull_if_nonzero(2, 3)));
+
+ // CHECK: void nninz3(int *, int, int) __attribute__((nonnull_if_nonzero(2, 3, 4)));
+ void nninz3(int *, int, int) __attribute__((nonnull_if_nonzero(2, 3, 4)));
+
// CHECK: int *aa(int i) __attribute__((alloc_align(2)));
int *aa(int i) __attribute__((alloc_align(2)));
diff --git a/clang/test/Sema/attr-nonnull-if-nonzero.c b/clang/test/Sema/attr-nonnull-if-nonzero.c
new file mode 100644
index 00000000000000..a32d08d2cbd849
--- /dev/null
+++ b/clang/test/Sema/attr-nonnull-if-nonzero.c
@@ -0,0 +1,166 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wno-strict-prototypes %s
+
+#if !__has_attribute(nonnull_if_nonzero)
+#error "expected nonnull_if_nonzero to be supported"
+#endif
+#if !__has_c_attribute(gnu::nonnull_if_nonzero)
+#error "expected gnu::nonnull_if_nonzero to be supported"
+#endif
+
+#define NULL ((void *)0)
+typedef __SIZE_TYPE__ size_t;
+enum E { E0, E1 };
+typedef union {
+ char *str;
+ int *ints;
+} Buffer __attribute__((transparent_union));
+
+void copy(void *dst, const void *src, size_t n)
+ __attribute__((nonnull_if_nonzero(1, 3), nonnull_if_nonzero(2, 3)));
+void fill(int n, char *p) __attribute__((nonnull_if_nonzero(2, 1)));
+void read_items(void *buf, size_t size, size_t count)
+ __attribute__((nonnull_if_nonzero(1, 2, 3)));
+void write_items(size_t count, const void *buf, size_t size)
+ __attribute__((nonnull_if_nonzero(2, 3, 1)));
+void same_twice(void *p, int n) __attribute__((nonnull_if_nonzero(1, 2, 2)));
+void by_char_and_enum(void *p, char n, enum E m) __attribute__((nonnull_if_nonzero(1, 2, 3)));
+void by_char(void *p, char n) __attribute__((nonnull_if_nonzero(1, 2)));
+void by_enum(void *p, enum E n) __attribute__((nonnull_if_nonzero(1, 2)));
+void by_union(Buffer b, int n) __attribute__((nonnull_if_nonzero(1, 2)));
+void variadic(void *p, int n, ...) __attribute__((nonnull_if_nonzero(1, 2)));
+[[gnu::nonnull_if_nonzero(1, 2)]] void c23_spelling(void *p, int n);
+void (*fnptr)(void *p, int n) __attribute__((nonnull_if_nonzero(1, 2)));
+
+void no_args(void *p, int n) __attribute__((nonnull_if_nonzero)); // expected-error {{'nonnull_if_nonzero' attribute takes at least 2 arguments}}
+void one_arg(void *p, int n) __attribute__((nonnull_if_nonzero(1))); // expected-error {{'nonnull_if_nonzero' attribute takes at least 2 arguments}}
+void four_args(void *p, int n, int m, int o) __attribute__((nonnull_if_nonzero(1, 2, 3, 4))); // expected-error {{'nonnull_if_nonzero' attribute takes no more than 3 arguments}}
+
+void not_constant1(void *p, int n) __attribute__((nonnull_if_nonzero("p", 2))); // expected-error {{'nonnull_if_nonzero' attribute requires parameter 1 to be an integer constant}}
+void not_constant2(void *p, int n) __attribute__((nonnull_if_nonzero(1, "n"))); // expected-error {{'nonnull_if_nonzero' attribute requires parameter 2 to be an integer constant}}
+void not_constant3(void *p, int n, int m) __attribute__((nonnull_if_nonzero(1, 2, "m"))); // expected-error {{'nonnull_if_nonzero' attribute requires parameter 3 to be an integer constant}}
+
+void bounds1(void *p, int n) __attribute__((nonnull_if_nonzero(0, 2))); // expected-error {{'nonnull_if_nonzero' attribute parameter 1 is out of bounds}}
+void bounds2(void *p, int n) __attribute__((nonnull_if_nonzero(3, 2))); // expected-error {{'nonnull_if_nonzero' attribute parameter 1 is out of bounds}}
+void bounds3(void *p, int n) __attribute__((nonnull_if_nonzero(1, 0))); // expected-error {{'nonnull_if_nonzero' attribute parameter 2 is out of bounds}}
+void bounds4(void *p, int n) __attribute__((nonnull_if_nonzero(1, 3))); // expected-error {{'nonnull_if_nonzero' attribute parameter 2 is out of bounds}}
+void bounds5(void *p, int n, ...) __attribute__((nonnull_if_nonzero(3, 2))); // expected-error {{'nonnull_if_nonzero' attribute parameter 1 is out of bounds}}
+void bounds6(void *p, int n, ...) __attribute__((nonnull_if_nonzero(1, 3))); // expected-error {{'nonnull_if_nonzero' attribute parameter 2 is out of bounds}}
+void bounds7(void *p, int n, int m) __attribute__((nonnull_if_nonzero(1, 2, 0))); // expected-error {{'nonnull_if_nonzero' attribute parameter 3 is out of bounds}}
+void bounds8(void *p, int n, int m) __attribute__((nonnull_if_nonzero(1, 2, 4))); // expected-error {{'nonnull_if_nonzero' attribute parameter 3 is out of bounds}}
+void bounds9(void *p, int n, ...) __attribute__((nonnull_if_nonzero(1, 2, 3))); // expected-error {{'nonnull_if_nonzero' attribute parameter 3 is out of bounds}}
+
+void not_pointer1(int p, int n) __attribute__((nonnull_if_nonzero(1, 2))); // expected-error {{'nonnull_if_nonzero' attribute only applies to pointer arguments}}
+void not_pointer2(void *p, int n) __attribute__((nonnull_if_nonzero(2, 2))); // expected-error {{'nonnull_if_nonzero' attribute only applies to pointer arguments}}
+void not_integer1(void *p, void *n) __attribute__((nonnull_if_nonzero(1, 2))); // expected-error {{'nonnull_if_nonzero' attribute argument may only refer to a function parameter of integer type}}
+void not_integer2(void *p, int n) __attribute__((nonnull_if_nonzero(1, 1))); // expected-error {{'nonnull_if_nonzero' attribute argument may only refer to a function parameter of integer type}}
+void not_integer3(void *p, double n) __attribute__((nonnull_if_nonzero(1, 2))); // expected-error {{'nonnull_if_nonzero' attribute argument may only refer to a function parameter of integer type}}
+void not_integer4(void *p, _Bool n) __attribute__((nonnull_if_nonzero(1, 2))); // expected-error {{'nonnull_if_nonzero' attribute argument may only refer to a function parameter of integer type}}
+void not_integer5(void *p, int n, void *m) __attribute__((nonnull_if_nonzero(1, 2, 3))); // expected-error {{'nonnull_if_nonzero' attribute argument may only refer to a function parameter of integer type}}
+void not_integer6(void *p, int n, int m) __attribute__((nonnull_if_nonzero(1, 2, 1))); // expected-error {{'nonnull_if_nonzero' attribute argument may only refer to a function parameter of integer type}}
+void not_integer7(void *p, int n, double m) __attribute__((nonnull_if_nonzero(1, 2, 3))); // expected-error {{'nonnull_if_nonzero' attribute argument may only refer to a function parameter of integer type}}
+void not_integer8(void *p, int n, _Bool m) __attribute__((nonnull_if_nonzero(1, 2, 3))); // expected-error {{'nonnull_if_nonzero' attribute argument may only refer to a function parameter of integer type}}
+void not_integer9(void *p, void *n, int m) __attribute__((nonnull_if_nonzero(1, 2, 3))); // expected-error {{'nonnull_if_nonzero' attribute argument may only refer to a function parameter of integer type}}
+
+int not_function __attribute__((nonnull_if_nonzero(1, 2))); // expected-warning {{'nonnull_if_nonzero' attribute only applies to non-K&R-style functions}}
+void no_prototype() __attribute__((nonnull_if_nonzero(1, 2))); // expected-warning {{'nonnull_if_nonzero' attribute only applies to non-K&R-style functions}}
+void on_parameter(void *p __attribute__((nonnull_if_nonzero(1, 2))), int n); // expected-warning {{'nonnull_if_nonzero' attribute only applies to non-K&R-style functions}}
+
+static const int nonzero = 4;
+
+void test_calls(void *p, char *s, size_t n, int cond) {
+ char buf[4];
+
+ copy(NULL, NULL, 0);
+ copy(NULL, NULL, n);
+ copy(buf, p, 4);
+ copy(NULL, p, 4); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ copy(p, NULL, 4); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ copy(NULL, NULL, sizeof(buf)); // expected-warning 2{{null passed to a callee that requires a non-null argument}}
+ copy(0, (char *)0, -1); // expected-warning 2{{null passed to a callee that requires a non-null argument}}
+ copy(NULL, p, 4 - 4);
+ copy(NULL, p, nonzero); // expected-warning {{null passed to a callee that requires a non-null argument}}
+
+ copy(NULL, p, n = 1);
+ copy(NULL, p, cond ? 2 : 4);
+ copy(cond ? NULL : buf, p, 4);
+
+ fill(0, NULL);
+ fill(1, NULL); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ fill(1, s);
+
+ read_items(NULL, 0, 0);
+ read_items(NULL, 4, 0);
+ read_items(NULL, 0, 4);
+ read_items(NULL, 4, 4); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ read_items(NULL, sizeof(buf[0]), sizeof(buf)); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ read_items(NULL, n, 4);
+ read_items(NULL, 4, n);
+ read_items(buf, 1, 4);
+ write_items(4, NULL, 0);
+ write_items(0, NULL, 4);
+ write_items(4, NULL, 4); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ write_items(4, p, 4);
+ same_twice(NULL, 0);
+ same_twice(NULL, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ by_char_and_enum(NULL, 'a', E0);
+ by_char_and_enum(NULL, '\0', E1);
+ by_char_and_enum(NULL, 'a', E1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+
+ by_char(NULL, '\0');
+ by_char(NULL, 'a'); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ by_enum(NULL, E0);
+ by_enum(NULL, E1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ by_union(0, 0);
+ by_union(0, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ by_union(s, 1);
+ variadic(NULL, 0, NULL);
+ variadic(NULL, 1, NULL); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ c23_spelling(NULL, 0);
+ c23_spelling(NULL, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ fnptr(NULL, 0);
+ fnptr(NULL, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+
+ (void)sizeof(fill(1, NULL), 0);
+}
+
+void test_callback(void (*cb)(void *p, int n) __attribute__((nonnull_if_nonzero(1, 2))),
+ void (*cb3)(void *p, int n, int m) __attribute__((nonnull_if_nonzero(1, 2, 3)))) {
+ cb(NULL, 0);
+ cb(NULL, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ cb3(NULL, 1, 0);
+ cb3(NULL, 1, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+}
+
+void redecl(void *p, void *q, int n) __attribute__((nonnull_if_nonzero(1, 3)));
+void redecl(void *p, void *q, int n) __attribute__((nonnull_if_nonzero(2, 3)));
+void redecl(void *p, void *q, int n);
+
+void test_redecl(void *p) {
+ redecl(NULL, NULL, 0);
+ redecl(NULL, p, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ redecl(p, NULL, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+}
+
+void mixed(void *p, void *q, int n, int m)
+ __attribute__((nonnull_if_nonzero(1, 3), nonnull_if_nonzero(2, 3, 4)));
+void either(void *p, int n, int m)
+ __attribute__((nonnull_if_nonzero(1, 2), nonnull_if_nonzero(1, 2, 3)));
+
+void test_mixed(void) {
+ mixed(NULL, NULL, 0, 1);
+ mixed(NULL, NULL, 1, 0); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ mixed(NULL, NULL, 1, 1); // expected-warning 2{{null passed to a callee that requires a non-null argument}}
+ either(NULL, 0, 1);
+ either(NULL, 1, 0); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ either(NULL, 1, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+}
+
+void both(void *p, int n) __attribute__((nonnull(1), nonnull_if_nonzero(1, 2)));
+void all(void *p, int n) __attribute__((nonnull, nonnull_if_nonzero(1, 2)));
+
+void test_both(void) {
+ both(NULL, 0); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ both(NULL, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ all(NULL, 0); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ all(NULL, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+}
diff --git a/clang/test/SemaCXX/attr-nonnull-if-nonzero.cpp b/clang/test/SemaCXX/attr-nonnull-if-nonzero.cpp
new file mode 100644
index 00000000000000..201c93bed550bb
--- /dev/null
+++ b/clang/test/SemaCXX/attr-nonnull-if-nonzero.cpp
@@ -0,0 +1,128 @@
+// RUN: %clang_cc1 -std=c++23 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -std=c++23 -fsyntax-only -verify %s -fexperimental-new-constant-interpreter
+
+#if !__has_cpp_attribute(gnu::nonnull_if_nonzero)
+#error "expected gnu::nonnull_if_nonzero to be supported"
+#endif
+
+typedef __SIZE_TYPE__ size_t;
+enum class Scoped { Zero, One };
+
+struct S {
+ S(void *p, size_t n) __attribute__((nonnull_if_nonzero(2, 3)));
+
+ static void s(void *p, size_t n) __attribute__((nonnull_if_nonzero(1, 2)));
+
+ void m(void *p, size_t n) __attribute__((nonnull_if_nonzero(2, 3)));
+ [[gnu::nonnull_if_nonzero(2, 3)]] void operator()(void *p, size_t n);
+
+ void this1(void *p, size_t n) __attribute__((nonnull_if_nonzero(1, 3))); // expected-error {{'nonnull_if_nonzero' attribute is invalid for the implicit this argument}}
+ void this2(void *p, size_t n) __attribute__((nonnull_if_nonzero(2, 1))); // expected-error {{'nonnull_if_nonzero' attribute is invalid for the implicit this argument}}
+ void bounds(void *p, size_t n) __attribute__((nonnull_if_nonzero(2, 4))); // expected-error {{'nonnull_if_nonzero' attribute parameter 2 is out of bounds}}
+
+ void m3(void *p, size_t n, size_t m) __attribute__((nonnull_if_nonzero(2, 3, 4)));
+ void this3(void *p, size_t n, size_t m) __attribute__((nonnull_if_nonzero(2, 3, 1))); // expected-error {{'nonnull_if_nonzero' attribute is invalid for the implicit this argument}}
+ void bounds3(void *p, size_t n, size_t m) __attribute__((nonnull_if_nonzero(2, 3, 5))); // expected-error {{'nonnull_if_nonzero' attribute parameter 3 is out of bounds}}
+
+ void explicit1(this S &self, void *p, size_t n) __attribute__((nonnull_if_nonzero(2, 3)));
+ void explicit2(this S &self, void *p, size_t n) __attribute__((nonnull_if_nonzero(3, 2))); // expected-error {{'nonnull_if_nonzero' attribute only applies to pointer arguments}}
+};
+
+void by_scoped_enum(void *p, Scoped n) __attribute__((nonnull_if_nonzero(1, 2)));
+void by_reference(int *const &p, size_t n) __attribute__((nonnull_if_nonzero(1, 2)));
+void not_pointer1(decltype(nullptr) p, size_t n) __attribute__((nonnull_if_nonzero(1, 2))); // expected-error {{'nonnull_if_nonzero' attribute only applies to pointer arguments}}
+void not_pointer2(int S::*p, size_t n) __attribute__((nonnull_if_nonzero(1, 2))); // expected-error {{'nonnull_if_nonzero' attribute only applies to pointer arguments}}
+void not_integer1(void *p, bool n) __attribute__((nonnull_if_nonzero(1, 2))); // expected-error {{'nonnull_if_nonzero' attribute argument may only refer to a function parameter of integer type}}
+void not_integer2(void *p, const size_t &n) __attribute__((nonnull_if_nonzero(1, 2))); // expected-error {{'nonnull_if_nonzero' attribute argument may only refer to a function parameter of integer type}}
+void not_integer3(void *p, size_t n, bool m) __attribute__((nonnull_if_nonzero(1, 2, 3))); // expected-error {{'nonnull_if_nonzero' attribute argument may only refer to a function parameter of integer type}}
+void defaulted(void *p = nullptr, size_t n = 4) __attribute__((nonnull_if_nonzero(1, 2)));
+void defaulted3(void *p = nullptr, size_t n = 4, size_t m = 0) __attribute__((nonnull_if_nonzero(1, 2, 3)));
+
+constexpr size_t Four = 4;
+
+void test(S &s, void *p) {
+ S s1(nullptr, 0);
+ S s2(nullptr, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ S s3(p, 1);
+
+ S::s(nullptr, 0);
+ S::s(nullptr, Four); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ s.m(nullptr, 0);
+ s.m(0, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ s.m(p, 1);
+ s.m3(nullptr, 0, 1);
+ s.m3(nullptr, 1, 0);
+ s.m3(nullptr, 1, Four); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ s.m3(p, 1, 1);
+ s(nullptr, 0);
+ s(nullptr, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ s.explicit1(nullptr, 0);
+ s.explicit1(nullptr, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+
+ by_scoped_enum(nullptr, Scoped::Zero);
+ by_scoped_enum(nullptr, Scoped::One); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ by_reference(nullptr, 0);
+ by_reference(nullptr, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+
+ defaulted(); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ defaulted(nullptr, 0);
+ defaulted(p);
+ defaulted3();
+ defaulted3(nullptr, 4, 4); // expected-warning {{null passed to a callee that requires a non-null argument}}
+}
+
+template <typename T>
+void typed(T *p, size_t n) __attribute__((nonnull_if_nonzero(1, 2)));
+template <typename P, typename N>
+void dependent(P p, N n) __attribute__((nonnull_if_nonzero(1, 2)));
+template <typename P, typename N, typename M>
+void dependent3(P p, N n, M m) __attribute__((nonnull_if_nonzero(1, 2, 3)));
+template <typename... Ns>
+void pack(void *p, Ns... ns) __attribute__((nonnull_if_nonzero(1, 2)));
+template <typename... Ns>
+void pack3(void *p, int n, Ns... ns) __attribute__((nonnull_if_nonzero(1, 2, 3)));
+template <typename T>
+void not_dependent(T t, int p, size_t n) __attribute__((nonnull_if_nonzero(2, 3))); // expected-error {{'nonnull_if_nonzero' attribute only applies to pointer arguments}}
+
+template <int N>
+void by_template_argument() {
+ typed<int>(nullptr, N); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ dependent3<int *, int, int>(nullptr, 1, N); // expected-warning {{null passed to a callee that requires a non-null argument}}
+}
+
+void test_templates(int *ip) {
+ typed<int>(nullptr, 0);
+ typed<int>(nullptr, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ typed(ip, 1);
+
+ dependent<int *, int>(nullptr, 0);
+ dependent<int *, int>(nullptr, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ dependent(ip, 1);
+ dependent(0, 1);
+ dependent(nullptr, 1);
+ dependent<int *, double>(nullptr, 1.0);
+ dependent<int *, bool>(nullptr, true);
+
+ dependent3<int *, int, long>(nullptr, 1, 0);
+ dependent3<int *, int, long>(nullptr, 0, 1);
+ dependent3<int *, int, long>(nullptr, 1, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ dependent3(ip, 1, 1);
+ dependent3<int *, int, bool>(nullptr, 1, true);
+ dependent3<int *, double, int>(nullptr, 1.0, 1);
+
+ pack(nullptr);
+ pack(nullptr, 0);
+ pack(nullptr, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ pack3(nullptr, 1);
+ pack3(nullptr, 1, 0);
+ pack3(nullptr, 1, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+
+ by_template_argument<0>();
+ by_template_argument<4>(); // expected-note {{in instantiation of function template specialization 'by_template_argument<4>' requested here}}
+}
+
+constexpr int in_constant(const void *p, int n) __attribute__((nonnull_if_nonzero(1, 2)));
+constexpr int in_constant(const void *p, int n) { return n; }
+static_assert(in_constant(nullptr, 1) == 1);
+constexpr int Constant = in_constant(nullptr, 1);
+int not_constant() { return in_constant(nullptr, 1); } // expected-warning {{null passed to a callee that requires a non-null argument}}
diff --git a/clang/test/SemaObjC/attr-nonnull-if-nonzero.m b/clang/test/SemaObjC/attr-nonnull-if-nonzero.m
new file mode 100644
index 00000000000000..d4537c918d750c
--- /dev/null
+++ b/clang/test/SemaObjC/attr-nonnull-if-nonzero.m
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -fblocks -fsyntax-only -verify -Wno-objc-root-class %s
+
+ at interface Buffer
+- (void)append:(const void *)bytes length:(unsigned long)length __attribute__((nonnull_if_nonzero(1, 2)));
++ (void)fill:(int)count with:(Buffer *)object __attribute__((nonnull_if_nonzero(2, 1)));
+- (void)read:(void *)items size:(unsigned long)size count:(unsigned long)count __attribute__((nonnull_if_nonzero(1, 2, 3)));
+- (void)bounds:(const void *)bytes __attribute__((nonnull_if_nonzero(1, 2))); // expected-error {{'nonnull_if_nonzero' attribute parameter 2 is out of bounds}}
+- (void)bounds:(void *)items size:(unsigned long)size __attribute__((nonnull_if_nonzero(1, 2, 3))); // expected-error {{'nonnull_if_nonzero' attribute parameter 3 is out of bounds}}
+- (void)notPointer:(int)bytes length:(unsigned long)length __attribute__((nonnull_if_nonzero(1, 2))); // expected-error {{'nonnull_if_nonzero' attribute only applies to pointer arguments}}
+ at end
+
+void with_block(void (^block)(void), int count) __attribute__((nonnull_if_nonzero(1, 2)));
+
+void test(Buffer *buffer, const void *bytes,
+ void (^callback)(void *p, int n) __attribute__((nonnull_if_nonzero(1, 2)))) {
+ [buffer append:0 length:0];
+ [buffer append:0 length:8]; // expected-warning {{null passed to a callee that requires a non-null argument}}
+ [buffer append:bytes length:8];
+ [Buffer fill:0 with:0];
+ [Buffer fill:1 with:0]; // expected-warning {{null passed to a callee that requires a non-null argument}}
+ [Buffer fill:1 with:buffer];
+ [buffer read:0 size:0 count:8];
+ [buffer read:0 size:4 count:0];
+ [buffer read:0 size:4 count:8]; // expected-warning {{null passed to a callee that requires a non-null argument}}
+
+ with_block(0, 0);
+ with_block(0, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+ callback(0, 0);
+ callback(0, 1); // expected-warning {{null passed to a callee that requires a non-null argument}}
+}
More information about the cfe-commits
mailing list