`#[thread_local]`s are pessimized in `#[no_mangle]` functions
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
#![feature(thread_local)]
use std::cell::Cell;
#[thread_local]
static THREAD_LOCAL: Cell<bool> = const { Cell::new(false) };
pub fn pub_mentions_thread_local() {
let _ = THREAD_LOCAL;
}
#[no_mangle]
fn no_mangle_uses_thread_local() {
let r = &THREAD_LOCAL;
if !r.get() {
r.set(true);
}
}
compiles to:
no_mangle_uses_thread_local:
push rax
data16
lea rdi, [rip + example::THREAD_LOCAL::h5a1be4459c52c6f4@TLSGD]
data16
data16
rex64
call __tls_get_addr@PLT
cmp byte ptr [rax], 0
jne .LBB0_2
data16
lea rdi, [rip + example::THREAD_LOCAL::h5a1be4459c52c6f4@TLSGD]
data16
data16
rex64
call __tls_get_addr@PLT
mov byte ptr [rax], 1
.LBB0_2:
pop rax
ret
example::THREAD_LOCAL::h5a1be4459c52c6f4:
.zero 1
(https://godbolt.org/z/K69s4fzzz)
i.e. two accesses under the global-dynamic TLS model. I have two questions here:
-
Why is the TLS resolved twice? It's sound to resolve it only once; in fact, the source code takes
&THREAD_LOCALjust once. This might be an LLVM problem. -
Why is
global-dynamicused instead oflocal-dynamic? Removingpubfrompub_mentions_thread_local, deletingpub_mentions_thread_localaltogether, or adding#[no_mangle]to it fixes this, even though that function literally has an empty MIR. This makes me suspect this is not an LLVM bug.
I'm not positive that #[no_mangle] is to blame here, but that's the closest I have to a non-generic title.
std::thread_local! is unaffected.
@rustbot label +A-codegen +A-thread-locals +C-optimization +F-thread_local +T-compiler
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No repository files or tests are named. Reproduce the examples in the linked Compiler Explorer snippets, then trace Rust compiler code generation for #[thread_local] references in #[no_mangle] functions and compare the TLS models and repeated accesses; done means explaining and correcting the unexpected global-dynamic, twice-resolved behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers, performance
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100