Inline asm - unexpected optimization

Georg-Johann Lay
Wed Aug 24 14:17:00 GMT 2011

Jeremy Hall wrote:
> On 24 August 2011 11:11, Georg-Johann Lay wrote:
>> It's not a bug in gcc.
>> The inlne asm has side effects you didn't report to gcc, so you need the
>> volatile here.
> OK thanks.  I guess there is no way to report this kind of side
> effect?  so you have to use volatile or call rdrand twice in the same
> asm().

Putting rdrand twice in the same asm won't help because when you then use
that asm twice or more to get several 64-bit numbers you might face a
similar problem.

> The only spanner in the works is that this problem does NOT occur with
> the similar rdtsc instruction.  I wondered if rdtsc was flagged within

If the same sequence behaves different with just an other string dropped
in instead of "rdrand" that would be very strange and astonishing.

GCC does not scan the inline assembler string except for %-operands to
replace and maybe new lines to estimate the number of instructions.


> gcc in some way to say its output was volatile, and that perhaps this
> had yet to be done with rdrand (as its a new instruction not available
> for a few months until Ivy Bridge comes out).
>>> I know its a new instruction.  The retry loop etc is removed to
>>> simplify the test case.
>>> #include <stdio.h>
>>> typedef unsigned long long qword;
>>> // #define asm __asm__ __volatile__
>>> int
>>> main( int argc, char *argv[] )
>>> {
>>>  qword result;
>>>    /* for 32 bit mode call rdrand twice */
>>>  unsigned int low, high;
>>>  asm( "rdrand %0" : "=r" (low) );
>>>  asm( "rdrand %0" : "=r" (high) );
>>>  result = ((qword)high << 32U) | low;
>>>  printf("64 bit random number: %llu\n", result );
>>> }

More information about the Gcc-help mailing list