Disappointment of the day: compare_exchange_weak is useless in practice

(This is a followup on this post)

compare_exchange_weak is advertised as:

function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms

My understanding was that "some platforms" here imply targets with LL/SC instructions which include ARM, PowerPC, and RISC-V. But in practice... there is absolutely on difference between compare_exchange_weak and compare_exchange on these targets.

Try changing one to another in this snippet: Compiler Explorer The generated assembly stays absolutely the same! I had hopes for RISC-V in this regard, but as you can see in this issue because of the (IMO) bonkers restriction in the ISA spec on retry loops used with LR/SC sequences, compilers (both LLVM and GCC) can not produce a more efficient code for compare_exchange_weak.

So if you want to optimize your atomic code, you may not bother with using compare_exchange_weak.

1 Like

From my limited understanding of ARM assembly, it seems clang on ARM also does this, but gcc on ARM does not: Compiler Explorer.

1 Like

If you're unhappy with the generated assembly, you're probably looking for https://github.com/llvm/llvm-project/issues/new/choose.

As you can see in https://rust.godbolt.org/z/Wxvfxzje4, rustc gives the weak flag to LLVM. If it doesn't do anything on your target, there's nothing rustc can do about that.

3 Likes

I already did it. See the LLVM issue linked in the OP.