[clang] [clang][CodeGen] Use guarded init for weak static locals without constant initialization (PR #226645)

Divyansh Yadav via cfe-commits cfe-commits at lists.llvm.org
Sun Sep 27 01:39:23 PDT 2026


schizophrenicmaniac wrote:

> Missing testcase. And somehow you mixed in your FROUND patch.
> 
> There's a FIXME related to this in CodeGenFunction::EmitVarDecl.
> 
> Skipping the guarded init is not threadsafe: if one thread accesses the variable while another thread is performing init, that's a race, even if the stored values are actually equal.
> 
> On targets that support comdats, we might be able to emit a guard variable in initialized form; that way, we wouldn't write to the variable even if it isn't constant-folded in some translation unit.



> Missing testcase. And somehow you mixed in your FROUND patch.
> 
> There's a FIXME related to this in CodeGenFunction::EmitVarDecl.
> 
> Skipping the guarded init is not threadsafe: if one thread accesses the variable while another thread is performing init, that's a race, even if the stored values are actually equal.
> 
> On targets that support comdats, we might be able to emit a guard variable in initialized form; that way, we wouldn't write to the variable even if it isn't constant-folded in some translation unit.


Thanks for the review! Updated:

- Rebased onto `main`, so the FROUND patch is gone.
- Added `clang/test/CodeGenCXX/static-local-inline-non-constant-init.cpp` (Itanium and MSVC).
- Addressed the FIXME in `EmitVarDecl`: a weak static local that isn't constant-initialized is no longer folded and always uses the guarded init. Every TU now follows the same guard protocol, which also fixes the race. This matches GCC.
- Dropped the `EmitGlobalVarDefinition` change, which caused the `dllexport-members.cpp` failure. Inline variables might have a similar issue; should I handle that here or in a separate PR?

I didn't do the initialized-guard approach. Static-local guards are in a separate comdat from the variable, so a TU's initialized guard could get paired with another TU's uninitialized variable. I'm happy to try it as a follow-up.

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


More information about the cfe-commits mailing list