Search code examples
assemblyfloating-pointx86fpux87

Free the x87 FPU Stack (ia32)


At my university we were just introduced to IA32 x87 FPU. But we weren't informed how to clear the FPU-Stack of no longer demanded elements.

Imagine we're performing a simple calculation like (5.6 * 2.4) + (3.9 * 10.3).

.data
        value1: .float 5.6
        value2: .float 2.4
        value3: .float 3.8
        value4: .float 10.3

        output: .string "The result is: %f\n"

.text
.global main

main:
        fld     value1          # Load / Push 5.6 into FPU
        fmul    value2          # Multiply FPU's top (5.6) with 2.4
        fld     value3          # Load / Push 3.8 into FPU
        fmul    value4          # Multiply the top element of the FPU's Stacks with 10.3
        fadd    %st(1)          # Add the value under the top element to the top elements value

.output:
        # Reserve memory for a float (64 Bit)
        subl $8, %esp
        # Pop the FPU's top element to the program's Stack
        fstpl (%esp)
        # Push the string to the stack
        pushl $output
        # Call printf function with the both parameters above
        call printf
        # Free the programs stack from the parameters for printf
        addl $12, %esp

.exit:
        movl $1, %eax
        int $0x80

The problem is: After popping the FPU's top element which holds the calculation's result. How do I free the FPU's stack from the now remaining newly top element which holds the result of (5.6*2.4).

The only way I'm capable to imagine is freeing some more program stack and popping elements from the FPU's stack until all no longer demanded elements are removed.

Is there a way to directly manipulate the top pointer?


Solution

  • To accomplish that you don't have any garbadge on the stack you need to use the FADDP and FMULP and similar instructions.