A question about "memory" clobbers in asm

Jamie Lokier jamie@shareable.org
Fri Sep 17 15:32:00 GMT 2004


I'm having trouble understand when it's appropriate to use a "memory"
clobber, when to use volatile, and when to use both.  The manual is
unclear to me.  Although I see that someone has tried to clarify it
since I last read it, it's still not obvious how "memory" is different
from `volatile'.

GCC 3.3.4 manual, "Extended Asm" says:

   If your assembler instructions access memory in an unpredictable
   fashion, add `memory' to the list of clobbered registers.  This will
   cause GCC to not keep memory values cached in registers across the
   assembler instruction and not optimize stores or loads to that memory.
   You will also want to add the `volatile' keyword if the memory affected
   is not listed in the inputs or outputs of the `asm', as the
   `memory' clobber does not count as a side-effect of the `asm'.

This says the `memory' clobber doesn't count as a side-effect.
What is the difference between a clobber and a side-effect?

More precisely, the text says:

   You will also want to add the `volatile' keyword if the memory affected
   is not listed in the inputs or outputs of the `asm'...

but the subsequent example explains that if the affected memory _is_
listed in the inputs or outputs of the `asm', then you don't use "memory".

   If you know how large the accessed memory is, you can add it as
   input or output but if this is not known, you should add `memory'.
   As an example, if you access ten bytes of a string, you can use a
   memory input like:

     {"m"( ({ struct { char x[10]; } *p = (void *)ptr ; *p; }) )}.

The text logically says: if the code affects memory which _is_ listed
in the inputs and outputs, then don't use "memory".  If the code
affects memory which _isn't_ listed, then use `volatile'.

Does this mean that the following three propositions are true?:

  1. The only valid use for "memory" is in conjunction with `volatile'.
  2. "memory" without `volatile' doesn't mean anything useful.
  3. `volatile' by itself means the asm should not be eliminated just
     because it's outputs are unused, but it is safe for GCC to cache
     memory values across the asm.

Thanks,
-- Jamie



More information about the Gcc mailing list