[x86 inline asm]: width of register arguments

Zdenek Sojka zsojka@seznam.cz
Mon Jun 24 12:19:00 GMT 2019


Hello,

how does gcc choose the register arguments of an inline assembler and what
can I assume about the "unused" bits?
My questions target the 64bit x86 architecture; I assume the behavior is the
same for all target triplets x86_64-*-*

1) does gcc always use register of size matching the size of the variable?

eg.
__asm__ ("mov %1, %0" : "=r"(a) : "r"(b));

will always use 8bit registers (eg. al, bl) for "int8_t / uint8_t a, b",
will always use 16bit registers (eg. ax, bx) for "int16_t / uint16_t a, b",
will always use 32bit registers (eg. eax, ebx) for "int32_t / uint32_t a, 
b",
will always use 64bit registers (eg. rax, rbx) for "int64_t / uint64_t a, 
b",
will always fail due to operand size mismatch for other combination?



2) can I assume anything about the high-order bits of the register? can I 
overwrite them freely?

2a) does gcc use the "high" 8bit registers (ah, bh, ch, dh) for variable 
allocation?

2b) can gcc allocate different 8bit variables in the "low" and "high"
registers (eg. al/ah, bl/bh, ...)?


For variables of type:

uint8_t a8, b8;
uint16_t a16, b16;
...

Enforcing same-sized arguments:
a)
__asm__ ("movb %b1, %b0" : "=r"(a8) : "r"(b8));
or
__asm__ ("movq %q1, %q0" : "=r"(a8) : "r"(b8));
is always safe to do? (eg. moving 56bits of garbage won't hurt anything)
OR might gcc assume something about the high-order 56bits (eg. zero, sign-/
zero-extension of the lower 8 bits), which might get broken by the move?


b)
__asm__ ("movw %w1, %w0" : "=r"(a8) : "r"(b16));
or
__asm__ ("movq %q1, %q0" : "=r"(a8) : "r"(b16));

is always safe to do? (eg. moving 56bits of garbage won't hurt anything)


Assuming zero-extension:
__asm__ ("movw %w1, %w0" : "=r"(a16) : "r"((uint8_t)b16));
or
__asm__ ("movw %w1, %w0" : "=r"(a16) : "r"(b8));
does not seem to work (high-order 8 bits of a16 are garbage)



Thank you,
Zdenek Sojka



More information about the Gcc-help mailing list