<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/103485>103485</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
clang-cl generates suboptimal code for __declspec(thread) thread-local variables that have constructor
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
mcfi
</td>
</tr>
</table>
<pre>
Consider this example https://godbolt.org/z/x7jjavdjP
```
struct A {
A(){ a = 0; }
int a;
};
extern __declspec(thread) struct A a;
struct A&
getA(void)
{
return a;
}
```
clang-cl generates the following code.
```
getA: # @getA
.seh_proc getA
# %bb.0:
sub rsp, 40
.seh_stackalloc 40
.seh_endprologue
mov eax, dword ptr [rip + _tls_index]
mov rcx, qword ptr gs:[88]
mov rax, qword ptr [rcx + 8*rax]
cmp byte ptr [rax + __tls_guard@SECREL32], 0
jne .LBB0_2
# %bb.1:
call __dyn_tls_on_demand_init
.LBB0_2:
mov eax, dword ptr [rip + _tls_index]
mov rcx, qword ptr gs:[88]
mov rax, qword ptr [rcx + 8*rax]
mov eax, dword ptr [rax + a@SECREL32]
add rsp, 40
ret
```
The problem is that if `cmp byte ptr [rax + __tls_guard@SECREL32], 0` results in a unequal result, it jumps to `.LBB0_2`, which then repeats three instructions that have already been executed above. This is not as efficient as what MSVC generates.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJzMVUGP6jYQ_jXmMlpkHALJIQfYfZxeparvqddoYg-JqWNnbYdl--srZ7MsorSHniohiGfmm_lmxvnAEHRriSqW71n-ssAxds5XvTzqRePUe_XsbNCKPMROB6AL9oMh6GIcAst2TByYOLRONc7EpfMtE4c_mThctqcTntXpV8ZfGN-xDZ8_0zFEP8oIO2Db_YcFAGDHRMFEybZ7QGDZC3CW7YFtX-Yc10BtIyDLZmgKuD5P33SJ5C3UtSJpwkCSiSJ2nlAxUcK1ON7BPh1Mb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