This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: A question about "memory" clobbers in asm


On Fri, 17 Sep 2004, Nathan Sidwell wrote:

> Jamie Lokier wrote:
> > 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'.
> 
> 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'.

This definition of memory clobbers is incomplete.

A memory clobber is required when the inline assembly either reads from or
writes to arbitrary memory or both. Not just "writes to".

I've seen cases like this:

	*ptr = 5;


	/* basically result = (*ptr == 5) */
	__asm__ volatile ("mov.l @%1,%0; mov #5,%2; cmp/eq %1,%2;
			   movt %0"
			   : "r" (result), "r" (temp)
			   : "r" (ptr));

	
	if (!result) {
		...
	}

If the memory clobber is omitted, then the scheduler can move *ptr = 5
AFTER the inline assembly fragment, which will result in the incorrect
result.

So if the inline assembly reads arbitrary memory, then it needs a memory
clobber regardless of whether it writes to memory.

Toshi





Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]