[clang] [Clang][Sema] Allow counted_by on void* in GNU mode (PR #164737)

Henrik G. Olsson via cfe-commits cfe-commits at lists.llvm.org
Thu Oct 23 23:46:03 PDT 2025


hnrklssn wrote:

> > Or just convert `counted_by` into `sized_by` with no need for another spelling (i.e. I could nudge this patch slightly so that `CountAttributedType::SizedBy` gets set earlier in Sema and then ` CodeGenFunction::emitCountedByPointerSize` would need no changes, etc.)
> 
> I.e. the only logic change (i.e. keep all the tests) needed would be this:
> 
> ```diff
> diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
> index 964a2a791e18..c97ec9cea0c6 100644
> --- a/clang/lib/Sema/SemaDeclAttr.cpp
> +++ b/clang/lib/Sema/SemaDeclAttr.cpp
> @@ -6577,6 +6577,20 @@ static void handleCountedByAttrField(Sema &S, Decl *D, const ParsedAttr &AL) {
>      llvm_unreachable("unexpected counted_by family attribute");
>    }
>  
> +  // In GNU mode, silently convert counted_by/counted_by_or_null on void*
> +  // to sized_by/sized_by_or_null, since void has size 1 in GNU pointer
> +  // arithmetic.
> +  if (!CountInBytes && FD->getType()->isPointerType()) {
> +    QualType PointeeTy = FD->getType()->getPointeeType();
> +    if (PointeeTy->isVoidType() && S.getLangOpts().GNUMode) {
> +      // Emit diagnostic before conversion
> +      S.Diag(FD->getBeginLoc(), diag::ext_gnu_counted_by_void_ptr)
> +          << (OrNull ? CountAttributedType::CountedByOrNull
> +                     : CountAttributedType::CountedBy);
> +      CountInBytes = true; // Convert to sized_by variant
> +    }
> +  }
> +
>    if (S.CheckCountedByAttrOnField(FD, CountExpr, CountInBytes, OrNull))
>      return;
>  
> ```
> 
> This is, perhaps, much cleaner?

That seems a lot easier to maintain! You may have to live with diagnostics saying `__sized_by` despite the code saying `__counted_by` though.

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


More information about the cfe-commits mailing list