Calculating x*log_2(y) with x86 assembly

Viewed 209

So I'm in a middle of trying to get the processor to calculate the x*log_2(y) below is my current assembly code (nasm syntax). I have the input value for y in XMM0 register and X would be a constant of 10.

    MOVSD QWORD [RSP], XMM0 ;Copy result of prev calculation to the stack
    FLD QWORD [RSP] ;Load the float from XMM0 to the fpu stack

    ;Load number 10 to the fpu stack
    MOV RAX, 10
    PUSH RAX
    FLD QWORD [RSP] ;ST(0)
    POP RAX
    ;Do the math y = xmm0, x=10 X*LOG2(Y)
    FYL2X ;ST(1) = OUT
    FSTP ;just remove ST(0), no need to preserve
    FSTP QWORD [RSP];Pop the result from the logarithm to the stack

    MOV RDI, QWORD [RSP]

    call printfcallfloat

I have tested with a value of 2.0 in the XMM0 register but I always get plain zeroes out. What am I doing wrong here?

1 Answers

FYL2X does a pop. There’s no need for FSTP after it.
Also the operands are reversed. It needs to push 10 first.
To load an integer, use FILD, not FLD.

;Load number 10 to the fpu stack
PUSH 10
FILD QWORD [RSP]

MOVSD QWORD [RSP], XMM0 ;Copy result of prev calculation to the stack
FLD QWORD [RSP] ;Load the float from XMM0 to the fpu stack

;Do the math x = xmm0, y = 10; y * LOG2(x)
FYL2X
FSTP QWORD [RSP];Pop the result from the logarithm to the stack

POP RDI
call printfcallfloat
Related