Re: Proper way to write inline assembly
Posted: Tue Aug 04, 2020 1:05 am
The memory clobber tells the compiler that the inline assembly could read or write values in memory for which it has the address. That means that, if the value in memory matches the value in the register, there is no reason to re-read it from memory. But it also means that future accesses must re-read the value in memory.
Inserting another memory clobber before the inline assembly acts as an appropriate barrier.
However, there is another problem: you're using a local variable. Local variables do not have addresses until an address is taken, so the compiler can assume (if the local variable's address is never taken) that it may optimize away your attempts at putting its value into memory. Right now you're using scanf() to force it to be spilled to memory, but there's no guarantee that that will work properly in the future, since the compiler may in the future become aware that scanf() does not make the addresses of its arguments available in the global namespace indicated by the memory clobber. (There are ways to work around this as well, but at that point you're working against the optimizer, and it really doesn't make sense to use inline assembly unless the optimizer is helping you.)
Inserting another memory clobber before the inline assembly acts as an appropriate barrier.
Code: Select all
inline void force_read(int* address)
{
asm volatile ("": : : "memory" );
asm volatile ("": :"r"(*address):"memory" );
}