</>EmbeddedInterview

What does the inline assembly __asm volatile("" ::: "memory") do?

HardEmbedded C

Short answer: It is a compiler barrier. The empty assembly statement with a "memory" clobber tells the compiler that the (empty) code might read or write any memory, so it must not move memory accesses across this point, must write out values it is holding in registers before it, and must reload values from memory after it. It emits no instruction, so it does not stop the CPU or the bus from reordering anything.

#define compiler_barrier() __asm volatile ("" ::: "memory")

flag_data = compute();
compiler_barrier();        /* the store to flag_data is emitted before the store to ready */
ready = 1;

What each part means

  • __asm volatile: do not delete or move this statement (volatile asm).
  • "": no instructions.
  • ::: "memory": the clobber list says "memory may have changed", which forces the compiler to forget cached values.

Where it is used

  • The Linux kernel's barrier() is exactly this.
  • Inside lock and critical-section macros, so that accesses to protected data are not moved outside the lock by the compiler (CMSIS __disable_irq() includes a memory clobber for the same reason).
  • Benchmarking, to stop the compiler from optimising away or reordering the code being measured.
  • Preventing the compiler from merging or removing memory accesses in tight polling loops on non-volatile data (better: use volatile or atomics).

Compiler barrier vs hardware barrier

Compiler barrier Hardware barrier (DMB/DSB)
Prevents compiler reordering yes yes (CMSIS versions include a memory clobber)
Prevents CPU/bus reordering no yes
Instructions emitted none one
Enough for single-core code vs interrupts, when the CPU itself does not reorder visibly multi-core, DMA, write buffers, device memory

C11 equivalents: atomic_signal_fence(memory_order_seq_cst) is a compiler-only fence (for code vs signal handlers/ISRs on the same core); atomic_thread_fence() is a full fence that also emits a hardware barrier.