[clang] [clang][CodeGen] Zero init unspecified fields in initializers in C (PR #97121)

John McCall via cfe-commits cfe-commits at lists.llvm.org
Thu Aug 1 17:51:49 PDT 2024


================
@@ -361,6 +368,13 @@ CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
     }
     return GV;
   }
+  if (!getLangOpts().CPlusPlus) {
+    // In C, when an initializer is given, the Linux kernel relies on clang to
+    // zero-initialize all members not explicitly initialized, including padding
+    // bits.
----------------
rjmccall wrote:

> The standard is ambiguous on this, so can't be used as a reason for the change. Please let me know if you have better idea about how to reword the comment.

I suggest quoting the standard, identifying the ambiguity, and then saying that we've chosen to interpret it as requiring all padding in the object to be zeroed.  Since there are multiple paths in the compiler that need this logic, you may want to write this in a single place and then cross-reference it from other places.

> I agree. But when I was trying to do it before, I need to fix a lot more tests. And the Linux kernel only has C code. I don't have strong reason to push this to C++. So I want to limit the change to C at first. If reviewers think we should also do it in C++, shall I do it in a follow up change?

I don't mind staging it in over multiple commits in principle.  If you'd like to switch to an implementation that adds explicit padding fields when building the original constant, you *could* still stage that and only add those fields in certain language modes.

> No, the non-constant initializer goes through the same implemented path as "variables assigned by Compound literals after variable definition". I guess I'd better do it in the same patch. Do you have any suggestions on how to implement it?

We probably do need to consider it when deciding whether to memset, but naively I'd expect that you'd just emit little memsets for each individual piece of padding when we recognize that there's a gap between successive fields.  Does that not work?

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


More information about the cfe-commits mailing list