https://github.com/thejh created 
https://github.com/llvm/llvm-project/pull/134899

Attr.td names the first alloc_size argument "ElemSizeParam" and the second 
optional argument "NumElemsParam"; but the semantics of how the two-argument 
version is used in practice is the opposite of that.

glibc declares calloc() like this, so the second alloc_size argument is the 
element size:
```
extern void *calloc (size_t __nmemb, size_t __size)
__THROW __attribute_malloc__ __attribute_alloc_size__ ((1, 2)) __wur;
```

The Linux kernel declares array allocation functions like 
`kmalloc_array_noprof()` the same way.

Add a comment explaining that the names used inside clang are misleading.

>From b395bb99917022e8da4a101f47d0fec2b8555628 Mon Sep 17 00:00:00 2001
From: Jann Horn <ja...@google.com>
Date: Tue, 8 Apr 2025 20:05:15 +0200
Subject: [PATCH] [clang] Add comment about misleading alloc_size argument
 names

Attr.td names the first alloc_size argument "ElemSizeParam" and the
second optional argument "NumElemsParam"; but the semantics of how the
two-argument version is used in practice is the opposite of that.

glibc declares calloc() like this, so the second alloc_size argument is
the element size:
```
extern void *calloc (size_t __nmemb, size_t __size)
__THROW __attribute_malloc__ __attribute_alloc_size__ ((1, 2)) __wur;
```

The Linux kernel declares array allocation functions like
`kmalloc_array_noprof()` the same way.

Add a comment explaining that the names used inside clang are
misleading.
---
 clang/include/clang/Basic/Attr.td | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index fd9e686485552..b7ad432738b29 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1709,6 +1709,13 @@ def EmptyBases : InheritableAttr, 
TargetSpecificAttr<TargetMicrosoftCXXABI> {
 def AllocSize : InheritableAttr {
   let Spellings = [GCC<"alloc_size">];
   let Subjects = SubjectList<[HasFunctionProto]>;
+  // The parameter names here are a bit misleading.
+  // When used with a single argument, the first argument is obviously the
+  // allocation size; but when used with two arguments, the first argument is
+  // usually the number of elements, while the second argument is usually the
+  // element size - the reverse of how they are named here.
+  // The documentation of both GCC and clang does not describe any semantic
+  // difference between the first and second argument.
   let Args = [ParamIdxArgument<"ElemSizeParam">,
               ParamIdxArgument<"NumElemsParam", /*opt*/ 1>];
   let TemplateDependent = 1;

_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to