assemblyx86x86-64dereferenceinstruction-set

Why can't we do arithmetic on an operand in x86 asm?


mov rax,r9+rcx*2

Why is this invalid syntax? Doesn't this count as "mov r64,r/m64" ? I'm a beginner so I'm sorry for my ignorance.

It becomes valid when the expression is enclosed in square brackets mov rax,[r9+rcx*2]. Why is that?


Solution

  • mov rax,r9+rcx*2
    

    This is an invalid syntax because the source operand (rightmost operand) contains registers and operations that the assembler can't perform at compile-time simply because the assembler does not know what values these registers contain. Only at runtime are these values revealed.

    Using the square brackets, [r9 + rcx * 2] becomes a valid addressing mode that uses a base register (R9) and an index register (RCX) that gets scaled by a factor (2).

    mov rax, [r9 + rcx * 2]
    

    When combined with the mov instruction, the memory contents at the calculated address will be returned in the indicated register (RAX).

    lea rax, [r9 + rcx * 2]
    

    When combined with the lea instruction, the calculated address itself will be returned in the indicated register (RAX).

    In both cases, the address calculation happens at runtime.