Passing 0 to __atomic_fetch_add generates mfence instead of lock xadd
| Bugzilla Link | 28498 |
| Version | trunk |
| OS | All |
| CC | @efriedma-quic,@pogo59 |
Extended Description
Using clang 3.9 on trunk at r273567 Target: x86_64-unknown-linux-gnu
When passing a '0' constant to '__atomic_fetch_add', an mfence instruction is generated instead of the usual 'lock xadd' which seems less efficient.
#include <stdint.h>
int64_t * g_ptr;
int foo() { return __atomic_fetch_add(g_ptr, 0, __ATOMIC_RELAXED); }
clang -O3 -S test.c
Generates:
movq %rdi, -8(%rsp) movq g_ptr(%rip), %rax mfence movq (%rax), %rax retq
Using gcc:
movq g_ptr(%rip), %rdx movq %rdi, -8(%rsp) xorl %eax, %eax lock xaddq %rax, (%rdx) ret
I forgot to mention that the reason for wanting to pass 0 to __atomic_fetch_add is to attempt to create a memory barrier.
For the sake of anyone dealing with your code in the future, please don't do this... if you need a fence, write a fence (or inline assembly if necessary).
AMD optimization guide 11.5.1 seems to imply that use of locked instructions should be used instead of mfence instructions in order to achieve best performances for memory barriers.
Hmm, okay... took a look at the optimization manuals, and that seems reasonable. LLVM actually already knows how to generate a locked instruction as a fence, but doesn't use it for targets with SSE2. Probably easy to change.
Hi Eli, Thanks for looking into this!
Double-checked, it should be fine; the fence isn't necessary.
I forgot to mention that the reason for wanting to pass 0 to __atomic_fetch_add is to attempt to create a memory barrier.
AMD optimization guide 11.5.1 seems to imply that use of locked instructions should be used instead of mfence instructions in order to achieve best performances for memory barriers.
In this case it would make sense to prefer 'lock xadd' over 'mfence', did I understood your point correctly?
Double-checked, it should be fine; the fence isn't necessary.
IIRC mfence is actually more efficient than lock xadd.
Off the top of my head, I think __atomic_fetch_add(g_ptr, 0, __ATOMIC_RELAXED); should be equivalent to __atomic_load(g_ptr, __ATOMIC_RELAXED);, but I'd need to double-check the standard.
The original testcase gets optimized to a simple load now.