Optimization with inline assembly
Xi Ruoyao
ryxi@stu.xidian.edu.cn
Tue Aug 15 06:30:00 GMT 2017
On 2017-08-14 21:39 +0100, Marcel Keller wrote:
> Hi,
>
> I've found that the attached code behaves differently when compilingÂ
> with or without -O in GCC 7.2.
>
> $ gcc asm.cpp ; ./a.out
> 1
> $ gcc -O asm.cpp ; ./a.out
> 0
>
> Looking at the compiled program in the second case, GCC seems to omitÂ
> the inline assembly:
>
> 00000000004004e7 <f(long*)>:
> Â Â Â 4004e7: f3 c3Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â repz retq
>
> My understanding is that the "memory" cobbler should tell GCC to assumeÂ
> that the assembly changes the memory (which it does). Am I missingÂ
> something here?
<https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Extended-Asm.html#Volatile>:
GCCâs optimizers sometimes discard asm statements if they determine
there is no need for the output variables. Also, the optimizers may move
code out of loops if they believe that the code will always return the
same result (i.e. none of its input values change between calls). Using
the volatile qualifier disables these optimizations. asm statements that
have no output operands, including asm goto statements, are implicitly
volatile.
In your code:
    asm(
            "addl $1,(%1)"
            : "=r"(res)
            : "rdi"(z)
            : "memory"
    );
"res" is an unused output variable. So GCC just optimize it away. You
should use "asm volatile".
> Best regards,
> Marcel
>
--
Xi Ruoyao <ryxi@stu.xidian.edu.cn>
School of Aerospace Science and Technology, Xidian University
More information about the Gcc-help
mailing list