[clang] [Clang][Sema] Support 'counted_by' attribute on FAM/pointers in anonymous unions (PR #171996)

Yeoul Na via cfe-commits cfe-commits at lists.llvm.org
Wed Jan 14 09:46:18 PST 2026


================
@@ -221,3 +221,49 @@ struct on_void_ty {
   // expected-error at +1{{field has incomplete type 'void'}}
   void wrong_ty __counted_by(count);
 };
+
+//==============================================================================
+// __counted_by on pointer members in unions
+//==============================================================================
+
+// Pointer in anonymous union with count in parent struct - OK
+struct ptr_in_anon_union_count_in_parent {
+  int count;
+  union {
+    int a;
+    struct size_known *buf __counted_by(count);
+  };
+};
----------------
rapidsna wrote:

@hnrklssn  Fields in unions should follow this rule that was mentioned here:
https://github.com/llvm/llvm-project/pull/171996#discussion_r2678170251

> For __counted_by to work on a union, one of the following must be true:
> 
> Homogeneous Sizes: All members of the union must have the exact same sizeof().
> Byte-Size Semantics: The attribute would need to be __sized_by.

Plus, if a union field has `counted_by` or `sized_by` all other union fields must have the same annotation that follows the above rule.

And then, the assignment analysis should be adjusted so that you can update count and either one of the union pointer fields. Do you think that would address the concerns?

https://github.com/llvm/llvm-project/pull/171996


More information about the cfe-commits mailing list