Re: Local variables reordering and 'asm volatile("" ::: "memory");'

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Sun, Sep 08, 2019 at 03:03:10PM +0300, Ayrat Gaskarov wrote:
> Hello, I have some questions about code reordering and 'asm volatile("" :::
> "memory");'
> >From gcc docs: 'The "memory" clobber tells the compiler that the assembly
> code performs memory reads or writes to items other than those listed in
> the input and output operands (for example, accessing the memory pointed to
> by one of the input parameters). To ensure memory contains correct values,
> GCC may need to flush specific register values to memory before executing
> the asm. Further, the compiler does not assume that any values read from
> memory before an asm remain unchanged after that asm; it reloads them as
> needed. Using the "memory" clobber effectively forms a read/write memory
> barrier for the compiler.'
> Does this mean that all data could be accessed including global variables,
> data in heap and local variables? Or is it not true for local variables?

"All data in memory" means "all data in memory".  If your local variable
is in memory, an inline asm with a memory clobber will stay in order with
accesses to that variable.  If your local variable is not in memory, no
such thing happens.

> For example:
> int local = 5;
> asm volatile("" ::: "memory");
> local += 6;
> Could it be reordered in the following way (because 'local' is local
> variable and could not be accessed):
> int local = 5;
> local += 6;
> asm volatile("" ::: "memory");
> Could 'local' be optimized out in this case?

Yes, it will likely end up in a register, and then it can be optimised
in such ways.  You'll have to force the variable into memory in some
way to avoid this.  One of the cheapest ways to do that is passing its
address to the asm, like in

  asm("" : : "g"(&local) : "memory");

Hope that helps,


Segher



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux