Assembly 64bit - movl, movq. Interchanging is okay?
Asked Answered
M

1

5

Context:

Learning GAS assembly on 64 bit linux. Many tutorials are for 32-bit assembly.

Difficult to bushwhack through x86_64 assembly.

Question:

When I compile a c program with gcc, I still see some %eax and movl.

I mostly play with int32_t.

But I thought that one had to use the 64 bits instructions on x86_64 (like rax,rbx and so on).

I don't understand very well. Shouldn't they be %rax and movq ? In my assembly programs, I should use movq, right ? even for 32 bits integers ? I am a lost beginner.

Thanks

Mcdonnell answered 17/2, 2015 at 9:10 Comment(0)
A
14

You can use 32 bit registers and instructions in 64 bit mode, just like you can use 16 or 8 bit too. One thing to keep in mind is that 32 bit instructions will automatically zero the top 32 bits of the respective 64 bit registers, while 16 or 8 bit instructions don't:

movabsq $0xffffffffffffffff, %rax
movb $0, %al  # rax = 0xffffffffffffff00
movw $0, %ax  # rax = 0xffffffffffff0000
movl $0, %eax # rax = 0x0000000000000000

One reason to use 32 bit instructions is that they are shorter machine code.

Antimacassar answered 17/2, 2015 at 11:13 Comment(3)
Thanks! So gcc may be wrong when using (%rbx) when it only points to a 32 bit value, right ? Should be (%ebx). Should one understand that gcc could be improved in this area ?Mcdonnell
That's a different thing, that is a pointer indirection. The size of the pointer has nothing to do with the size of the item pointed to. movb (%rbx), %al is entirely valid and means dereference the 64 bit pointer in rbx and fetch a byte from that address into al. Pointers in 64 bit code should be 64 bit unless you are certain the top 32 bits are zero.Antimacassar
Ah yes, my bad ! It is not natural yet for me, but definitely coming :) Thanks JesterMcdonnell

© 2022 - 2024 — McMap. All rights reserved.