3 ms·
> No, this is definitely not how atomics with memory orderings work. If you do two atomic reads, the CPU will do two load instructions. Neither the compiler or
by comex 5y ago
> No, this is definitely not how atomics with memory orderings work. If you do two atomic reads, the CPU will do two load instructions. Neither the compiler or the CPU is allowed to optimize this.
Yes they are. And other optimizations are allowed too. If you do an 32-bit atomic load and then mask the result with `& 0xff`, the compiler can theoretically narrow it into an 8-bit atomic load, as long as the architecture guarantees that such a load still provides the necessary ordering guarantees – which I think is true on most architectures. This won't necessarily work for MMIO, where incorrectly-sized accesses may trap or return the wrong data. But the compiler is not responsible for preserving MMIO semantics if you only asked for atomic.
That said, I'm not aware of any major compilers performing /any/ significant optimizations on atomics, so you won't get in trouble for this in practice.
> This is exactly how ARM SoCs work. The CPU core does not know if a load address is mmio or not and may reorder the loads as it sees fit. It's up to the memory subsystem to deal with this, the CPU core does not care.
You can configure in memory attributes whether to allow reordering or not.
> They are quite tricky on ARMv8, as mmio can be either on the system bus or the main memory bus which need distinct kinds of memory barriers.
Which SoC?