Re: Subject: Reordering of __builtin functions around inline asm volatile

Georg-Johann Lay <[email protected]> Sun, 24 Sep 2023 15:18:08 +0200
Newsgroups gmane.comp.hardware.avr.gcc
Message-ID <[email protected]>
Am 24.09.23 um 03:48 schrieb Ricardo Cosme:
> Hi,
> 
> I have a question regarding the reordering of statements involving a 
> builtin function and extended asm volatile expressions in avr-gcc.
> 
> Consider the following code snippet:
> 
> //C++
> {
>    asm volatile(/* template plus operands */);
>    __builtin_avr_delay_cycles(cycles);
>    asm volatile(/* template plus operands */);
> }
> 
> I understand that the compiler is allowed to reorder statements as long 
> as it doesn't affect the observable behavior of the program. However, in 
> this specific case, the __builtin_avr_delay_cycles function is a 
> compiler intrinsic.
> 
> Assuming there are no other expressions on the above block, is it 
> possible for the compiler to reorder the three statements?
> 
> Cheers,
> Ricardo Cosme

No. __builtin_avr_delay_cycles is implicitly volatile, so it may not
be reordered against other volatile statements.

This also applies to built-ins like 
__builtin_avr_sei/cli/nop/nops/wdr/sleep,
whereas arithmetic built-ins like __builtin_avr_swap/fmul/insert_bits
etc. are purely arithmetic any may be reordered or optimized out.

The volatile built-ins also have a memory clobber similar to

__asm volatile ("" ::: "memory");

so they may not be reordered against memory accesses.  They may be
reordered against arithmetic operations like divisions though, cf.

https://stackoverflow.com/q/37897848/1556746


Johann