Search code examples
assemblyx86-64lazarusfreepascal

64 bit bsr asm is truncating the upper 32 bits


I want bsr to operate on a 64 bit number. However, the following only works on the lower 32 bits of the input:

function BSR64(const Val: Int64): Integer;
begin
asm
  bsr           eax, [Val]   
...

How do I do this?

I'm compiling in 64 bit mode using Lazarus.


Solution

  • Access the 64-bit register as follows:

     bsr rax, [val]
    

    eax is the low 32-bits. ax is the low 16, and al is the low 8.

    Using a 32-bit register destination implies a 32-bit operand size for memory. BSR requires that they match, like pretty much every other instruction other than movzx and movsx.