Search code examples
assemblyoptimizationx86-64nasm

Loading small numbers into 64 bit x86 registers


Under 64 bit x86 CPU normally we load number -1 in to register like:

mov     rdx, -1  //  48BAFFFFFFFFFFFFFFFF

... this instruction takes 10 bytes the way old versions of NASM assemble it.


Another way is:

xor     rdx, rdx //  4831D2        
dec     rdx      //  48FFCA  

       

... this opcode takes only 6 bytes.

EDIT:

As Jens Björnhager say (I have tested) xor edx, edx opcode should clear whole rdx register:

xor     edx, edx //  31D2        
dec     rdx      //  48FFCA 

... this opcode takes only 5 bytes.

EDIT:

Alexey Frunze found another solution:

mov     rdx, -1  // 48C7C2FFFFFFFF

... this instruction takes only 7 bytes. But how to tell assembler to use shorter encoding (without using DB)? You can hint NASM to use this encoding, in case you're using an old version which doesn't default to enabling optimization (of code size), and you don't use nasm -Ox manually.

mov     rdx, dword -1

What is faster and what is more economical?


Solution

  • There's an alternative, 7-byte, encoding of mov rdx, -1: 48C7C2FFFFFFFF.

    You can try writing the instruction as mov rdx, dword -1 in the code to aid the compiler/assembler in using this shorter encoding.