Can I force a word read-modify-write instread of a byte write?

Ian Lance Taylor iant@google.com
Mon Jul 2 17:18:00 GMT 2007


"Phil Endecott" <spam_from_gcc_help@chezphil.org> writes:

> Could you help me out with an example?  Say I have a uint8_t* that I
> want to write to:
> 
> uint8_t* ptr = ......;
> *ptr = 123;
> 
> How do I change that so that it does a read/modify/write?  Are you
> saying that I can do something like
> 
> volatile uint32_t* ptr = .....;
> uint8_t* ptr2 = ptr;
> *ptr2 = 123;
> 
> with appropriate extra casts and 'volatile's, and it will do what I want?

Oh, I see, you want the compiler to figure stuff out for you.
Unfortunately, that won't work.  You need to write the 32-bit
read/modify/write instructions yourself.

volatile uint32_t* ptr = .....;
uint32_t v = *ptr;
v = (v & 0xffffff00) | 123;
*ptr = v;

Note that if you don't use the volatile qualifier, gcc is wholly
capable of optimizing that into an 8-bit memory write.

There is nothing in gcc which will force it to use 32-bit memory
accesses if you don't explicitly write 32-bit memory accesses.

Ian



More information about the Gcc-help mailing list