This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: A question about "memory" clobbers in asm
Nathan Sidwell wrote:
> my understanding is
>
> * volatile asm says something to the effect 'this changes state that you
> (the compiler) don't know about' -- such as writing to an IO port.
>
> * memory clobber says 'this asm will change memory, so don't cache anything
> across this asm'.
You and Ian agree, and that makes sense to me.
So I think the semantics are fine, but the documentation is unclear.
You have both explained the semantics in clear and concise language, so
my only issue is with the documentation.
Specifically, "You will also want to add the `volatile' keyword if the
memory affected is not listed in the inpus or outputs of the `asm'" is
misleading.
How about changing:
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'. 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:
to:
If your assembler instruction loads from memory which is not listed
in the inputs of the `asm', or stores to memory which is not listed
in the outputs, 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.
and later add:
When to clobber `memory' and when to use `volatile'
...................................................
Clobbering `memory' is independent of `volatile', although it is
usually the case that if you clobber `memory' then you want
`volatile' as well.
Putting `memory' in the list of clobbered registers tells the
compiler to not keep memory values cached acress the `asm'
instruction, and not make other assumptions about the contents of
memory. (This is sometimes called a compiler memory barrier). The
compiler may still cache local variables whose addresses have not
been taken. Unless `volatile' is also specified, the `asm' can
still be deleted, moved, or two combined if they're a common
subexpression.
Writing the `volatile' keyword after `asm' tells the compiler not
to delete or significantly move the `asm' instruction, or combine
two of them if they're a common subexpression. Unless `memory' is
clobbered as well, the compiler is permitted to cache memory values
across an `asm volatile'.
How about that?
-- Jamie