diff --git a/CMakeLists.txt b/CMakeLists.txt index 5e4c6756b..8cd7e68bf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -767,6 +767,25 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME cpu_aot_x87_div COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_div.py" check "$" "$" "$" ${x87_div_control_files}) + cpu_asm_fixture(cpu_x87_sub x87_sub) + # The lifted DLL and seven mutated controls that the check requires to mismatch. + set(x87_sub_control_files "") + foreach(variant IN ITEMS lifted pc64 double nansign reverse cancel nosticky memquiet) + set(x87_sub_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_x87_sub_${variant}.cpp") + add_custom_command(OUTPUT "${x87_sub_fixture}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_sub.py" + emit "$" "${x87_sub_fixture}" ${variant} + DEPENDS cpu_x87_sub tests/cpu/x87_sub.py tests/cpu/x87_div.py tests/cpu/x87_mul.py + tests/cpu/x87_add.py tools/ffx_version_query.py tools/x87_lower.py tools/x87_soft.h + tools/cpu_ranges.py tools/cpu_leaf_aot.py VERBATIM) + add_library(cpu_x87_sub_${variant} SHARED "${x87_sub_fixture}") + if(NOT variant STREQUAL "lifted") + list(APPEND x87_sub_control_files "$") + endif() + endforeach() + add_test(NAME cpu_aot_x87_sub COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_sub.py" + check "$" "$" + "$" ${x87_sub_control_files}) cpu_asm_fixture(cpu_create create_context) set(create_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_create_lifted.cpp") add_custom_command(OUTPUT "${create_fixture}" diff --git a/docs/experiments.md b/docs/experiments.md index caa073327..d024835db 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -491,15 +491,17 @@ The local Bink DLL imports ordinal 1 from XAudio2_9.dll. A read-only check confi ## x87 in the shared lowering -`lower(..., x87=True)` in `tools/ffx_version_query.py` accepts an opt-in x87 leaf-function profile. The default (`x87=False`) still rejects every x87 instruction, so existing callers are unchanged. The profile accepts `fld` and `fstp` with an m32, m64 or m80 memory operand, `faddp st(i), st` with `i` from 1 to 7 (`faddp st(0), st` is rejected), the multiplication forms `fmul m32`, `fmul m64`, `fmul st, st(i)`, `fmul st(i), st` and `fmulp st(i), st`, and the same five division forms for each of `fdiv` and `fdivr`, with `fdivp` and `fdivrp` (a popping form with `st(0)` as the destination is rejected). A function enters with control word 0x027F (53-bit precision, round to nearest-even, all exceptions masked), TOP 0, all eight registers empty and a clear status word, and it must return with the stack empty. The stack depth before each instruction is fixed at translation time (`tools/x87_lower.py`), so each register becomes a C++ slot and no TOP exists at run time. Translation rejects any other x87 instruction, including control-word, status-word, environment and `wait` access; a ninth push; a pop or `faddp` without enough values; depths that differ where control flow joins; an x87 instruction that is not reachable from the entry through direct edges; and a nonempty stack at a return, a call, an indirect branch or an external edge. +`lower(..., x87=True)` in `tools/ffx_version_query.py` accepts an opt-in x87 leaf-function profile. The default (`x87=False`) still rejects every x87 instruction, so existing callers are unchanged. The profile accepts `fld` and `fstp` with an m32, m64 or m80 memory operand, and five forms of each of `fadd`, `fsub`, `fsubr`, `fmul`, `fdiv` and `fdivr`: an m32 or m64 operand, `st, st(i)`, `st(i), st`, and the popping form (`faddp`, `fsubp`, `fsubrp`, `fmulp`, `fdivp`, `fdivrp`) with `st(i), st` for `i` from 1 to 7. A popping form with `st(0)` as the destination is rejected. A function enters with control word 0x027F (53-bit precision, round to nearest-even, all exceptions masked), TOP 0, all eight registers empty and a clear status word, and it must return with the stack empty. The stack depth before each instruction is fixed at translation time (`tools/x87_lower.py`), so each register becomes a C++ slot and no TOP exists at run time. Translation rejects any other x87 instruction, including control-word, status-word, environment and `wait` access; a ninth push; a pop or `faddp` without enough values; depths that differ where control flow joins; an x87 instruction that is not reachable from the entry through direct edges; and a nonempty stack at a return, a call, an indirect branch or an external edge. The helpers in `tools/x87_soft.h` compute in integers and do not use host floating point. A register holds the full 80-bit encoding. m80 loads and stores copy all 80 bits, including NaN payloads, denormals, pseudo-denormals and unnormals. m32 and m64 loads convert exactly and quiet a signaling NaN. A sum rounds to 53 significand bits within the extended exponent range; a result below that range is denormalized first and then rounded at the same bit positions. The sum rounds again when it is stored to m32 or m64. NaN operands follow the x87 column of Intel SDM Vol. 1, Table 4-7: a QNaN beats an SNaN, and otherwise the larger significand wins. When two NaNs have equal significands, the positive one wins in either operand order. This tie rule was measured, not taken from the table. Infinities of opposite sign, unnormals, pseudo-infinities and pseudo-NaNs give the indefinite. An exact zero sum of nonzero addends is +0, and -0 + -0 is -0. The status word, exceptions and the other rounding modes are not modelled. Their absence is safe only because the profile rejects every instruction that could observe or change them. `cpu_aot_x87_add` builds 16 exports from generated MASM source (`tests/cpu/x87_add.asm`, from `tests/cpu/x87_add.py asm`) and translates them. The exports cover the nine load/store width pairs, additions stored to each width, and a three-value chain that uses `faddp st(2), st`. A native-only harness (`tests/cpu/x87_harness.asm`) saves the caller's whole x87 state with `fnsave` (environment and register values), which also leaves TOP 0 and an empty stack. It then loads control word 0x027F, calls the export, records the control, status and tag words the export left, and restores the caller's state with `frstor`. A harness check enters each export with a live caller value (pi with all 64 significand bits) in the register the export reuses and control word 0x0F7F loaded. It requires the value bytes, the control word, TOP and the tags to come back unchanged. A control harness that keeps only the environment (`fnstenv`/`fldenv`) must lose the value around every export. Native and translated exports receive the same input bytes and run through that harness. The check compares each output block and the 64 guard bytes on each side of the input and output against an independent `Fraction` model. It requires every export to return with control word 0x027F, TOP 0 and all tags empty. The 8085 cases include all pairs of 34 special encodings, halfway sums that separate 53-bit from 64-bit precision, double rounding through m64, sums beyond the binary64 range, extended-range overflow and underflow, denormal results, cancellation, NaN ties and 700 random pairs. Six mutated translations must each mismatch: 64-bit precision, the binary64 exponent range, m80 loads through binary64, a dropped sticky bit, the first NaN operand always winning, and -0 for an exact cancellation. On an AMD Ryzen 7 7700 (Windows 11 build 26200), every case matched in the native and translated DLLs, and the controls gave 1089, 3845, 1485, 48, 58 and 18 mismatches. The check also confirms that the default lowering rejects `fld` and that the profile rejects 16 sequences outside it. Only `faddp st(1), st` and `faddp st(2), st` are exercised. Intel CPUs have not been measured. Run `cmake --build --preset dev --target cpu_x87_add_lifted` and `ctest --preset dev --no-tests=error -R '^cpu_aot_x87_add$' -V`. -`cpu_aot_x87_mul` checks the multiplication forms the same way, through the same harness, guards and live-value check, with 12 exports and 14951 cases. The product of the two 64-bit significands is exact in 128 bits and rounds like a sum. Its sign is the exclusive or of the operand signs, including for zero and infinite results, and infinity times zero gives the indefinite. An m32 or m64 operand of `fmul` converts exactly but keeps a signaling NaN signaling, so the NaN rules see the operand's own kind. A plain `fld` quiets it on load. The cases cover every pair of the 34 special encodings, each special m80 value times each of 17 m32 and 18 m64 special encodings, products that are exact halfway cases at 53 bits, products whose upper 64 bits sit exactly on a tie so that only the low 64 bits decide, `x * 1` rounding, products beyond the binary64 range, extended overflow and underflow thresholds, denormal results, the square through `fmul st, st(0)`, a three-value chain through `fmulp st(2), st`, a product followed by an add, and random operands. Six mutated translations must each mismatch: 64-bit precision, the binary64 exponent range, dropping the low 64 bits of the product, the first operand's sign, infinity times zero giving infinity, and quieting memory operands before the NaN rules. On the AMD Ryzen 7 7700 every case matched in the native and translated DLLs, and the controls gave 4836, 8059, 62, 4409, 73 and 36 mismatches. The check also confirms that translation rejects nine sequences, including `fmulp st(0), st`, `fimul`, `fsub`, the still unsupported `fadd m32`, and multiplications without enough stack values. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_x87_mul$' -V`. +`cpu_aot_x87_mul` checks the multiplication forms the same way, through the same harness, guards and live-value check, with 12 exports and 14951 cases. The product of the two 64-bit significands is exact in 128 bits and rounds like a sum. Its sign is the exclusive or of the operand signs, including for zero and infinite results, and infinity times zero gives the indefinite. An m32 or m64 operand of `fmul` converts exactly but keeps a signaling NaN signaling, so the NaN rules see the operand's own kind. A plain `fld` quiets it on load. The cases cover every pair of the 34 special encodings, each special m80 value times each of 17 m32 and 18 m64 special encodings, products that are exact halfway cases at 53 bits, products whose upper 64 bits sit exactly on a tie so that only the low 64 bits decide, `x * 1` rounding, products beyond the binary64 range, extended overflow and underflow thresholds, denormal results, the square through `fmul st, st(0)`, a three-value chain through `fmulp st(2), st`, a product followed by an add, and random operands. Six mutated translations must each mismatch: 64-bit precision, the binary64 exponent range, dropping the low 64 bits of the product, the first operand's sign, infinity times zero giving infinity, and quieting memory operands before the NaN rules. On the AMD Ryzen 7 7700 every case matched in the native and translated DLLs, and the controls gave 4836, 8059, 62, 4409, 73 and 36 mismatches. The check also confirms that translation rejects nine sequences, including `fmulp st(0), st`, `fimul`, `fcomp`, `fiadd`, and multiplications without enough stack values. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_x87_mul$' -V`. -`cpu_aot_x87_div` checks the division forms in the same way, with 17 exports and 23939 cases. `fdivr` and `fdivrp` divide the source by the destination. Each export's decoded x87 instructions must match the forms its sequence names, so an assembler that exchanged the `fdiv` and `fdivr` register encodings would fail before the run. The helper divides the 64-bit significands into a 64-bit quotient and folds a nonzero remainder into a sticky bit. That is enough to round to 53 bits, and the result goes through the same rounding as the sum and the product. Zero by zero and infinity by infinity give the indefinite. A finite nonzero value by zero gives a signed infinity (the masked divide-by-zero response). A finite value by infinity, and zero by a finite value, give a signed zero. The cases cover every pair of the 34 special encodings and every special m80 value against the m32 and m64 special encodings, in both orders. They also cover exact quotients halfway between 53-bit neighbours, quotients whose 64-bit significand ends exactly on a tie so that only the remainder decides, `x / x` through `fdiv st, st(0)`, quotients beyond the binary64 range, the extended overflow and underflow thresholds, denormal results, two three-value chains through `fdivp st(1), st`, `fdivp st(2), st` and `fdivrp st(1), st`, and random operands. Seven mutated translations must each mismatch: 64-bit precision, the binary64 exponent range, an ignored remainder, the indefinite for a finite value by zero, `fdivr` in the `fdiv` order, an unsigned zero quotient, and quieting memory operands before the NaN rules. On the AMD Ryzen 7 7700 every case matched in the native and translated DLLs, and the controls gave 8785, 14373, 253, 602, 6829, 551 and 54 mismatches. Translation still rejects `fdivp st(0), st`, `fdivrp st(0), st`, `fidiv`, `fidivr`, `fsqrt`, `fprem`, `fadd m32` and divisions without enough stack values. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_x87_div$' -V`. +`cpu_aot_x87_div` checks the division forms in the same way, with 17 exports and 23939 cases. `fdivr` and `fdivrp` divide the source by the destination. Each export's decoded x87 instructions must match the forms its sequence names, so an assembler that exchanged the `fdiv` and `fdivr` register encodings would fail before the run. The helper divides the 64-bit significands into a 64-bit quotient and folds a nonzero remainder into a sticky bit. That is enough to round to 53 bits, and the result goes through the same rounding as the sum and the product. Zero by zero and infinity by infinity give the indefinite. A finite nonzero value by zero gives a signed infinity (the masked divide-by-zero response). A finite value by infinity, and zero by a finite value, give a signed zero. The cases cover every pair of the 34 special encodings and every special m80 value against the m32 and m64 special encodings, in both orders. They also cover exact quotients halfway between 53-bit neighbours, quotients whose 64-bit significand ends exactly on a tie so that only the remainder decides, `x / x` through `fdiv st, st(0)`, quotients beyond the binary64 range, the extended overflow and underflow thresholds, denormal results, two three-value chains through `fdivp st(1), st`, `fdivp st(2), st` and `fdivrp st(1), st`, and random operands. Seven mutated translations must each mismatch: 64-bit precision, the binary64 exponent range, an ignored remainder, the indefinite for a finite value by zero, `fdivr` in the `fdiv` order, an unsigned zero quotient, and quieting memory operands before the NaN rules. On the AMD Ryzen 7 7700 every case matched in the native and translated DLLs, and the controls gave 8785, 14373, 253, 602, 6829, 551 and 54 mismatches. Translation still rejects `fdivp st(0), st`, `fdivrp st(0), st`, `fidiv`, `fidivr`, `fsqrt`, `fprem`, `fiadd` and divisions without enough stack values. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_x87_div$' -V`. + +`cpu_aot_x87_sub` checks `fsub`, `fsubr`, `fsubp`, `fsubrp` and the `fadd` forms besides `faddp` in the same way, with 22 exports and 35023 cases. `fsubr` and `fsubrp` subtract the destination from the source. The helper computes `a - b` as `a + (-b)`, but it selects a NaN or invalid operand before negating, so a NaN result keeps its own sign. `x - x` is +0, and -0 - +0 is -0. The cases reuse the addition pairs of `cpu_aot_x87_add`, and again with the second operand negated. They also cover `x - x` and `x + x` through `st(0)`, m32 and m64 operands against the special encodings, `float` and `double` differences, a three-value chain through `fsubp st(2), st` and `fsubrp st(1), st`, and random operands. Seven mutated translations must each mismatch: 64-bit precision, the binary64 exponent range, negating a NaN subtrahend, `fsubr` in the `fsub` order, -0 for an exact cancellation, a dropped sticky bit, and quieting memory operands before the NaN rules. On the AMD Ryzen 7 7700 every case matched in the native and translated DLLs, and the controls gave 15680, 24289, 2022, 7753, 777, 108 and 81 mismatches. Translation still rejects `fsubp st(0), st`, `fsubrp st(0), st`, `fisub`, `fisubr`, `fchs`, `fabs`, `fcom` and arithmetic without enough stack values. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_x87_sub$' -V`. ## Mapping an image without LoadLibrary diff --git a/tests/cpu/x87_add.py b/tests/cpu/x87_add.py index 763ae84dc..04edcb246 100644 --- a/tests/cpu/x87_add.py +++ b/tests/cpu/x87_add.py @@ -484,7 +484,7 @@ def attempt(hex_bytes, *, x87=True, calls=None, exits=None): rejected = { "the profile off (default)": (attempt(f"{fld} {fstp} c3", x87=False), "unsupported query operation"), "fld st(1)": (attempt(f"{fld} d9 c1 de c1 de c1 {fstp} c3"), "unsupported x87 operand"), - "fadd st, st(1)": (attempt(f"{fld} {fld} d8 c1 de c1 {fstp} c3"), "fadd"), + "fcom st(1)": (attempt(f"{fld} {fld} d8 d1 de c1 {fstp} c3"), "fcom"), "fnstsw ax": (attempt(f"{fld} df e0 {fstp} c3"), "unsupported x87 operation"), "fldcw": (attempt(f"d9 29 {fld} {fstp} c3"), "fldcw"), "fninit": (attempt(f"{fld} db e3 {fstp} c3"), "unsupported x87 operation"), diff --git a/tests/cpu/x87_div.py b/tests/cpu/x87_div.py index 0d6aac656..e1fecb571 100644 --- a/tests/cpu/x87_div.py +++ b/tests/cpu/x87_div.py @@ -364,7 +364,7 @@ def attempt(hex_bytes): "fidivr m16": (attempt(f"{fld} de 39 {fstp} c3"), "unsupported x87 operation"), "fsqrt": (attempt(f"{fld} d9 fa {fstp} c3"), "unsupported x87 operation"), "fprem": (attempt(f"{fld} {fld} d9 f8 {fstp} {fstp} c3"), "unsupported x87 operation"), - "fadd m32": (attempt(f"{fld} d8 01 {fstp} c3"), "unsupported x87 operation"), + "fiadd m32": (attempt(f"{fld} da 01 {fstp} c3"), "unsupported x87 operation"), } for case, (message, needle) in rejected.items(): if message is None or needle not in message: diff --git a/tests/cpu/x87_mul.py b/tests/cpu/x87_mul.py index 79118b71a..029212453 100644 --- a/tests/cpu/x87_mul.py +++ b/tests/cpu/x87_mul.py @@ -331,8 +331,8 @@ def attempt(hex_bytes): "fmulp with one value": (attempt(f"{fld} de c9 {fstp} c3"), "x87 stack underflow"), "fimul m32": (attempt(f"{fld} da 09 {fstp} c3"), "unsupported x87 operation"), "fimul m16": (attempt(f"{fld} de 09 {fstp} c3"), "unsupported x87 operation"), - "fsub st, st(1)": (attempt(f"{fld} {fld} d8 e1 {fstp} {fstp} c3"), "unsupported x87 operation"), - "fadd m32": (attempt(f"{fld} d8 01 {fstp} c3"), "unsupported x87 operation"), + "fcomp st(1)": (attempt(f"{fld} {fld} d8 d9 {fstp} c3"), "unsupported x87 operation"), + "fiadd m32": (attempt(f"{fld} da 01 {fstp} c3"), "unsupported x87 operation"), } for case, (message, needle) in rejected.items(): if message is None or needle not in message: diff --git a/tests/cpu/x87_sub.asm b/tests/cpu/x87_sub.asm new file mode 100644 index 000000000..ef084b16e --- /dev/null +++ b/tests/cpu/x87_sub.asm @@ -0,0 +1,202 @@ +; Generated by tests/cpu/x87_sub.py asm; edit SEQUENCES there and regenerate. +; Source-owned differential fixture for the FSUB, FSUBR and FADD forms of the x87 leaf-function +; profile. Each export reads an input block at RCX, writes an output block at RDX and returns with +; the x87 stack empty. +.code + +sub_m80 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fld tbyte ptr [rcx+16] + fsubp st(1), st + fstp tbyte ptr [rdx+0] + ret +sub_m80 ENDP + +sub_to_m64 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fld tbyte ptr [rcx+16] + fsubp st(1), st + fstp qword ptr [rdx+0] + ret +sub_to_m64 ENDP + +sub_to_m32 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fld tbyte ptr [rcx+16] + fsubp st(1), st + fstp dword ptr [rdx+0] + ret +sub_to_m32 ENDP + +subr_m80 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fld tbyte ptr [rcx+16] + fsubrp st(1), st + fstp tbyte ptr [rdx+0] + ret +subr_m80 ENDP + +sub_st0_sti PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fld tbyte ptr [rcx+16] + fsub st, st(1) + fstp tbyte ptr [rdx+0] + fstp tbyte ptr [rdx+16] + ret +sub_st0_sti ENDP + +sub_sti_st0 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fld tbyte ptr [rcx+16] + fsub st(1), st + fstp tbyte ptr [rdx+0] + fstp tbyte ptr [rdx+16] + ret +sub_sti_st0 ENDP + +subr_st0_sti PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fld tbyte ptr [rcx+16] + fsubr st, st(1) + fstp tbyte ptr [rdx+0] + fstp tbyte ptr [rdx+16] + ret +subr_st0_sti ENDP + +subr_sti_st0 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fld tbyte ptr [rcx+16] + fsubr st(1), st + fstp tbyte ptr [rdx+0] + fstp tbyte ptr [rdx+16] + ret +subr_sti_st0 ENDP + +add_st0_sti PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fld tbyte ptr [rcx+16] + fadd st, st(1) + fstp tbyte ptr [rdx+0] + fstp tbyte ptr [rdx+16] + ret +add_st0_sti ENDP + +add_sti_st0 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fld tbyte ptr [rcx+16] + fadd st(1), st + fstp tbyte ptr [rdx+0] + fstp tbyte ptr [rdx+16] + ret +add_sti_st0 ENDP + +sub_self PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fsub st, st(0) + fstp tbyte ptr [rdx+0] + ret +sub_self ENDP + +add_self PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fadd st, st(0) + fstp tbyte ptr [rdx+0] + ret +add_self ENDP + +sub_mem32 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fsub dword ptr [rcx+16] + fstp tbyte ptr [rdx+0] + ret +sub_mem32 ENDP + +sub_mem64 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fsub qword ptr [rcx+16] + fstp tbyte ptr [rdx+0] + ret +sub_mem64 ENDP + +subr_mem32 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fsubr dword ptr [rcx+16] + fstp tbyte ptr [rdx+0] + ret +subr_mem32 ENDP + +subr_mem64 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fsubr qword ptr [rcx+16] + fstp tbyte ptr [rdx+0] + ret +subr_mem64 ENDP + +add_mem32 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fadd dword ptr [rcx+16] + fstp tbyte ptr [rdx+0] + ret +add_mem32 ENDP + +add_mem64 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fadd qword ptr [rcx+16] + fstp tbyte ptr [rdx+0] + ret +add_mem64 ENDP + +sub_f32 PROC FRAME + .endprolog + fld dword ptr [rcx+0] + fsub dword ptr [rcx+4] + fstp dword ptr [rdx+0] + ret +sub_f32 ENDP + +sub_f64 PROC FRAME + .endprolog + fld qword ptr [rcx+0] + fsub qword ptr [rcx+8] + fstp qword ptr [rdx+0] + ret +sub_f64 ENDP + +add_f64 PROC FRAME + .endprolog + fld qword ptr [rcx+0] + fadd qword ptr [rcx+8] + fstp qword ptr [rdx+0] + ret +add_f64 ENDP + +sub_three PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fld tbyte ptr [rcx+16] + fld tbyte ptr [rcx+32] + fsubp st(2), st + fsubrp st(1), st + fstp tbyte ptr [rdx+0] + ret +sub_three ENDP + +END diff --git a/tests/cpu/x87_sub.def b/tests/cpu/x87_sub.def new file mode 100644 index 000000000..0e1495972 --- /dev/null +++ b/tests/cpu/x87_sub.def @@ -0,0 +1,23 @@ +EXPORTS + sub_m80 + sub_to_m64 + sub_to_m32 + subr_m80 + sub_st0_sti + sub_sti_st0 + subr_st0_sti + subr_sti_st0 + add_st0_sti + add_sti_st0 + sub_self + add_self + sub_mem32 + sub_mem64 + subr_mem32 + subr_mem64 + add_mem32 + add_mem64 + sub_f32 + sub_f64 + add_f64 + sub_three diff --git a/tests/cpu/x87_sub.py b/tests/cpu/x87_sub.py new file mode 100644 index 000000000..a1445c5e1 --- /dev/null +++ b/tests/cpu/x87_sub.py @@ -0,0 +1,308 @@ +"""Compare native and translated FSUB and FSUBR forms, and the FADD forms besides FADDP, of the x87 +leaf-function profile: m32 and m64 operands, ST(0), ST(i), ST(i), ST(0), FSUBP and FSUBRP ST(i), ST(0). + +Usage: + python tests/cpu/x87_sub.py asm regenerate the MASM source and exports + python tests/cpu/x87_sub.py emit [control] translate (and optionally mutate) the fixture + python tests/cpu/x87_sub.py check [controls...] + +The exports, harness and guards follow tests/cpu/x87_add.py; the step format, the assembler and the +decode check of every x87 form come from tests/cpu/x87_div.py. The difference model below negates the +subtrahend in exact rational arithmetic and is independent of tools/x87_soft.h. +""" +from pathlib import Path +import platform +import random +import re +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +import x87_add as base # noqa: E402 (tests/cpu is the script directory) +import x87_div as forms # noqa: E402 +from x87_add import INDEFINITE, J, classify, from_binary, m80, m80_bytes, round_format, to_binary # noqa: E402 +from x87_mul import nan_result, operand # noqa: E402 + +INPUT, OUTPUT, SIZE = base.INPUT, base.OUTPUT, forms.SIZE + +P80 = [("fld", "m80", 0), ("fld", "m80", 16)] +SEQUENCES = { + "sub_m80": ("pair80", P80 + [("fsubp", "pop", 1), ("fstp", "m80", 0)]), + "sub_to_m64": ("pair80", P80 + [("fsubp", "pop", 1), ("fstp", "m64", 0)]), + "sub_to_m32": ("pair80", P80 + [("fsubp", "pop", 1), ("fstp", "m32", 0)]), + "subr_m80": ("pair80", P80 + [("fsubrp", "pop", 1), ("fstp", "m80", 0)]), + "sub_st0_sti": ("pair80", P80 + [("fsub", "st0", 1), ("fstp", "m80", 0), ("fstp", "m80", 16)]), + "sub_sti_st0": ("pair80", P80 + [("fsub", "sti", 1), ("fstp", "m80", 0), ("fstp", "m80", 16)]), + "subr_st0_sti": ("pair80", P80 + [("fsubr", "st0", 1), ("fstp", "m80", 0), ("fstp", "m80", 16)]), + "subr_sti_st0": ("pair80", P80 + [("fsubr", "sti", 1), ("fstp", "m80", 0), ("fstp", "m80", 16)]), + "add_st0_sti": ("pair80", P80 + [("fadd", "st0", 1), ("fstp", "m80", 0), ("fstp", "m80", 16)]), + "add_sti_st0": ("pair80", P80 + [("fadd", "sti", 1), ("fstp", "m80", 0), ("fstp", "m80", 16)]), + "sub_self": ("m80", [("fld", "m80", 0), ("fsub", "st0", 0), ("fstp", "m80", 0)]), + "add_self": ("m80", [("fld", "m80", 0), ("fadd", "st0", 0), ("fstp", "m80", 0)]), + "sub_mem32": ("m80_f32", [("fld", "m80", 0), ("fsub", "mem", "m32", 16), ("fstp", "m80", 0)]), + "sub_mem64": ("m80_f64", [("fld", "m80", 0), ("fsub", "mem", "m64", 16), ("fstp", "m80", 0)]), + "subr_mem32": ("m80_f32", [("fld", "m80", 0), ("fsubr", "mem", "m32", 16), ("fstp", "m80", 0)]), + "subr_mem64": ("m80_f64", [("fld", "m80", 0), ("fsubr", "mem", "m64", 16), ("fstp", "m80", 0)]), + "add_mem32": ("m80_f32", [("fld", "m80", 0), ("fadd", "mem", "m32", 16), ("fstp", "m80", 0)]), + "add_mem64": ("m80_f64", [("fld", "m80", 0), ("fadd", "mem", "m64", 16), ("fstp", "m80", 0)]), + "sub_f32": ("pair32", [("fld", "m32", 0), ("fsub", "mem", "m32", 4), ("fstp", "m32", 0)]), + "sub_f64": ("pair64", [("fld", "m64", 0), ("fsub", "mem", "m64", 8), ("fstp", "m64", 0)]), + "add_f64": ("pair64", [("fld", "m64", 0), ("fadd", "mem", "m64", 8), ("fstp", "m64", 0)]), + # b - (a - c) through FSUBP ST(2), ST(0) and then FSUBRP ST(1), ST(0). + "sub_three": ("triple80", [("fld", "m80", 0), ("fld", "m80", 16), ("fld", "m80", 32), ("fsubp", "pop", 2), + ("fsubrp", "pop", 1), ("fstp", "m80", 0)]), +} + +# Source mutations of the generated C++ (the helper header is part of it). Each control must mismatch. +CONTROLS = { + # The difference rounds to 64 significand bits, as with precision control 64. + "pc64": (base.ARITH, "x87_arith{64, 16383, 0x7ffe}"), + # The difference rounds in the binary64 exponent range, as host double arithmetic would. + "double": (base.ARITH, "x87_arith{53, 1023, 0x7fe}"), + # The subtrahend is negated before the NaN rules, so a NaN subtrahend comes back with its sign flipped. + "nansign": (re.compile(r"(x87_sub\(X87Value a, X87Value b\) \{\s+X87Value out;\s+)" + r"if \(x87_special_operands\(a, b, &out\)\) return out;"), r"\1"), + # FSUBR subtracts in the FSUB order. + "reverse": (re.compile(r"x87_subr\(X87Value a, X87Value b\) \{ return x87_sub\(b, a\); \}"), + "x87_subr(X87Value a, X87Value b) { return x87_sub(a, b); }"), + # An exact zero difference of nonzero values is -0. + "cancel": (re.compile(r"return \{0, 0\}; // x \+ \(-x\)"), "return {0, 0x8000}; // x + (-x)"), + # Bits shifted out when aligning the smaller operand are dropped instead of kept as a sticky bit. + "nosticky": (re.compile(r"lo \|= sticky;|lo = \(hi \| lo\) != 0;"), + lambda m: ";" if m.group(0).startswith("lo |=") else "lo = 0;"), + # m32 and m64 operands are quieted before the NaN rules see them, as a plain load would. + "memquiet": (re.compile(r"(x87_operand_f(?:32|64)\(uint(?:32|64)_t bits\) \{ return x87_from_binary\([^)]*), false\)"), + r"\1, true)"), +} + + +def write_asm(asm_path, def_path): + lines = ["; Generated by tests/cpu/x87_sub.py asm; edit SEQUENCES there and regenerate.", + "; Source-owned differential fixture for the FSUB, FSUBR and FADD forms of the x87 leaf-function", + "; profile. Each export reads an input block at RCX, writes an output block at RDX and returns with", + "; the x87 stack empty.", ".code", ""] + for name, (_, steps) in SEQUENCES.items(): + lines += [f"{name} PROC FRAME", " .endprolog", *(forms.asm_line(s) for s in steps), " ret", + f"{name} ENDP", ""] + lines.append("END") + Path(asm_path).write_text("\n".join(lines) + "\n", encoding="ascii") + Path(def_path).write_text("EXPORTS\n" + "".join(f" {name}\n" for name in SEQUENCES), encoding="ascii") + + +def emit(image, output, control="lifted"): + import pefile + from cpu_leaf_aot import export_rva + from cpu_ranges import function_ranges + from ffx_version_query import INTEGER_HEADER, lower, region + from x87_lower import X87_HEADER, is_x87 + + parts = [INTEGER_HEADER, X87_HEADER] + with pefile.PE(str(image), fast_load=True) as pe: + for name, (_, steps) in SEQUENCES.items(): + (bounds,) = function_ranges(pe, export_rva(pe, name)) + body = region(pe, *bounds) + decoded = [forms.decoded_form(i) for i in body if is_x87(i)] + wanted = [forms.expected_form(s) for s in steps] + if decoded != wanted: + raise AssertionError(f"{name} assembled as {decoded}, expected {wanted}") + code = lower(body, ["rcx = a; rdx = b;"], {}, {}, {}, x87=True) + parts.append(f'extern "C" __declspec(dllexport) word {name}(word a, word b) {{\n{code}\n}}\n') + text = "".join(parts) + if control != "lifted": + expression, replacement = CONTROLS[control] + text, count = expression.subn(replacement, text) + if not count: + raise AssertionError(f"control {control} changed nothing") + print(f"control {control}: {count} replacements") + output.write_text(text, encoding="ascii") + + +# ---- Independent model ----------------------------------------------------------------------------- + +def sub(a, b): + """FSUB a - b with control word 0x027F. A NaN operand is selected as it is (its sign kept); otherwise + the exact difference rounds to 53 bits in the extended exponent range, and an exact zero is +0 unless + a is -0 and b is +0.""" + ca, cb = classify(a), classify(b) + if "unsupported" in (ca[0], cb[0]): + return INDEFINITE + if "nan" in (ca[0], cb[0]): + return nan_result(a, b) + if ca[0] == "inf" or cb[0] == "inf": + if ca[0] == cb[0] == "inf" and ca[1] == cb[1]: + return INDEFINITE + return a if ca[0] == "inf" else (J, (cb[1] ^ 1) << 15 | 0x7FFF) + if ca[0] == cb[0] == "zero": + return 0, 0x8000 if ca[1] and not cb[1] else 0 + value = sum((-c[2] if c[1] else c[2]) * k for c, k in ((ca, 1), (cb, -1)) if c[0] == "finite") + if value == 0: + return 0, 0 + sign = int(value < 0) + rounded = round_format(abs(value), 53, 16383, 0x7FFE) + if rounded is None: + return J, sign << 15 | 0x7FFF + m, biased = rounded + return m << 11, sign << 15 | biased + + +FUNCTIONS = {"fsub": sub, "fsubp": sub, "fsubr": lambda a, b: sub(b, a), "fsubrp": lambda a, b: sub(b, a), + "fadd": base.add} + + +def reference(name, data): + slots, out = [], bytearray(b"\xcc" * OUTPUT) + + def read(kind, offset): + return int.from_bytes(data[offset:offset + SIZE[kind]], "little") + + for op, *args in SEQUENCES[name][1]: + if op == "fld": + raw = read(*args) + slots.append((raw & (2 ** 64 - 1), raw >> 64) if args[0] == "m80" else from_binary(args[0], raw)) + continue + if op == "fstp": + kind, offset = args + v = slots.pop() + encoded = v[0] | v[1] << 64 if kind == "m80" else to_binary(kind, v) + out[offset:offset + SIZE[kind]] = encoded.to_bytes(SIZE[kind], "little") + continue + f, form = FUNCTIONS[op], args[0] + if form == "mem": + slots[-1] = f(slots[-1], operand(args[1], read(args[1], args[2]))) + elif form == "st0": + slots[-1] = f(slots[-1], slots[-1 - args[1]]) + else: + slots[-1 - args[1]] = f(slots[-1 - args[1]], slots[-1]) + if form == "pop": + slots.pop() + assert not slots + return bytes(out) + + +# ---- Inputs ---------------------------------------------------------------------------------------- + +def pairs80(): + """The addition pairs of tests/cpu/x87_add.py (specials, halfway sums, sticky tails, range edges, + random) plus the same pairs with the second operand negated, so each case is also a subtraction.""" + rows = base.pairs80() + rows += [(a, (b[0], b[1] ^ 0x8000)) for a, b in rows[len(base.special_m80()) ** 2:]] + rows += [(m80(1), m80(1)), (m80(-3), m80(-3)), ((J - 1, 0), (J - 1, 0)), ((0, 0x8000), (0, 0)), + ((0, 0), (0, 0x8000)), ((0, 0x8000), (0, 0x8000)), ((J, 0x7FFF), (J, 0x7FFF)), ((J, 0xFFFF), (J, 0x7FFF)), + (m80((1 << 64) - 1, -63), m80(1)), (m80(1), m80((1 << 64) - 1, -64))] + return rows + + +def cases(): + f64, f32 = base.f64_bits(), base.f32_bits() + specials = base.special_m80() + rng = random.Random(11) + + def random_m80(): + return J | rng.getrandbits(63), rng.randint(0x3FFF - 70, 0x3FFF + 70) | rng.choice((0, 0x8000)) + + def m80_block(*values): + return b"".join(m80_bytes(v) for v in values) + + blocks = { + "pair80": [m80_block(a, b) for a, b in pairs80()], + "m80": [m80_bytes(v) for v in base.m80_singles()] + [m80_bytes(random_m80()) for _ in range(200)], + "m80_f32": [m80_bytes(v) + b.to_bytes(4, "little") for v in specials for b in f32[:17]] + + [m80_bytes(random_m80()) + rng.getrandbits(32).to_bytes(4, "little") for _ in range(300)], + "m80_f64": [m80_bytes(v) + b.to_bytes(8, "little") for v in specials for b in f64[:18]] + + [m80_bytes(random_m80()) + rng.getrandbits(64).to_bytes(8, "little") for _ in range(300)], + "pair32": [a.to_bytes(4, "little") + b.to_bytes(4, "little") for a in f32[:17] for b in f32[:17]] + + [rng.getrandbits(32).to_bytes(4, "little") + rng.getrandbits(32).to_bytes(4, "little") + for _ in range(300)], + "pair64": [a.to_bytes(8, "little") + b.to_bytes(8, "little") for a in f64[:18] for b in f64[:18]] + + [rng.getrandbits(64).to_bytes(8, "little") + rng.getrandbits(64).to_bytes(8, "little") + for _ in range(300)], + "triple80": [m80_block(*rng.sample(specials, 3)) for _ in range(200)] + + [m80_block(random_m80(), random_m80(), random_m80()) for _ in range(300)], + } + for name, (kind, _) in SEQUENCES.items(): + for block in blocks[kind]: + yield name, block.ljust(INPUT, b"\0") + + +# ---- Check ----------------------------------------------------------------------------------------- + +def check(harness_path, native_path, lifted_path, *control_paths): + expected = [(name, data, reference(name, data)) for name, data in cases()] + for label, path in (("native", native_path), ("lifted", lifted_path)): + run = base.Runner(harness_path, path) + bad = 0 + for name, data, want in expected: + got, state = run(name, data) + if not base.entry_state_ok(state): + raise AssertionError(f"{label} {name} left state {state:#014x}; the profile requires control " + "0x027f and an empty stack at TOP 0") + if got != want: + if not bad: + print(f"{label} first mismatch: {name}(input {data[:48].hex()})\n got {got[:16].hex()}\n" + f" expected {want[:16].hex()}") + bad += 1 + if bad: + raise AssertionError(f"{label}: {bad}/{len(expected)} mismatches") + print(f"{len(expected)} cases over {len(SEQUENCES)} exports (output block and guards) matched the reference " + "in native and translated DLLs; each export returned with control 0x027f and an empty stack") + print(f"processor: {platform.processor()}") + first = {} + for name, data, want in expected: + first.setdefault(name, (data, want)) + for label, path in (("native", native_path), ("lifted", lifted_path)): + run = base.Runner(harness_path, path) + failed = [name for name, (data, want) in first.items() if not base.preserved(run, "x87_call", name, data, want)] + if failed: + raise AssertionError(f"x87_call lost a live caller value or control word around {label} {failed}") + print(f"x87_call kept a live caller ST(0) value and control word around all {len(first)} native and " + "translated exports") + for path in control_paths: + control = Path(path).stem.rsplit("_", 1)[-1] + run = base.Runner(harness_path, path) + bad = sum(1 for name, data, want in expected if run(name, data)[0] != want) + print(f"control {control}: {bad}/{len(expected)} mismatches") + if not bad: + raise AssertionError(f"control {control} matched every case") + check_rejections() + + +def check_rejections(): + from iced_x86 import Decoder + from ffx_version_query import lower + + def attempt(hex_bytes): + body = list(Decoder(64, bytes.fromhex(hex_bytes), ip=0x1000)) + try: + lower(body, [], {}, {}, {}, x87=True) + except ValueError as exc: + return str(exc) + return None + + fld, fstp = "db 29", "db 3a" # fld tbyte ptr [rcx]; fstp tbyte ptr [rdx] + rejected = { + "fsubp st(0), st": (attempt(f"{fld} {fld} de e8 {fstp} {fstp} c3"), "unsupported x87 operation"), + "fsubrp st(0), st": (attempt(f"{fld} {fld} de e0 {fstp} {fstp} c3"), "unsupported x87 operation"), + "fsub m32 on an empty stack": (attempt(f"d8 21 {fld} {fstp} c3"), "x87 stack underflow"), + "fadd st, st(1) with one value": (attempt(f"{fld} d8 c1 {fstp} c3"), "x87 stack underflow"), + "fsubr st(2), st with two values": (attempt(f"{fld} {fld} dc e2 {fstp} {fstp} c3"), "x87 stack underflow"), + "fisub m32": (attempt(f"{fld} da 21 {fstp} c3"), "unsupported x87 operation"), + "fisubr m16": (attempt(f"{fld} de 29 {fstp} c3"), "unsupported x87 operation"), + "fchs": (attempt(f"{fld} d9 e0 {fstp} c3"), "unsupported x87 operation"), + "fabs": (attempt(f"{fld} d9 e1 {fstp} c3"), "unsupported x87 operation"), + "fcom st(1)": (attempt(f"{fld} {fld} d8 d1 {fstp} {fstp} c3"), "unsupported x87 operation"), + } + for case, (message, needle) in rejected.items(): + if message is None or needle not in message: + raise AssertionError(f"{case}: expected a rejection containing {needle!r}, got {message!r}") + print(f"rejected {len(rejected)} sequences outside the profile: " + "; ".join(rejected)) + + +if __name__ == "__main__": + mode, first, second, *rest = sys.argv[1:] + if mode == "asm": + write_asm(first, second) + elif mode == "emit": + emit(Path(first), Path(second), *rest) + elif mode == "check": + check(first, second, *rest) + else: + raise ValueError(mode) diff --git a/tools/form_coverage.py b/tools/form_coverage.py index 1c2ee487e..c242e70fc 100644 --- a/tools/form_coverage.py +++ b/tools/form_coverage.py @@ -45,6 +45,7 @@ "x87_add": "cpu_aot_x87_add", "x87_mul": "cpu_aot_x87_mul", "x87_div": "cpu_aot_x87_div", + "x87_sub": "cpu_aot_x87_sub", "x87_harness": None, # native x87 entry and exit state for x87_add "destroy": "cpu_aot_destroy_contract", "create_context": "cpu_aot_context_lifecycle", diff --git a/tools/x87_lower.py b/tools/x87_lower.py index 2d72b93da..ae16d3acc 100644 --- a/tools/x87_lower.py +++ b/tools/x87_lower.py @@ -1,23 +1,24 @@ """Opt-in x87 leaf-function profile for ffx_version_query.lower(x87=True). -The profile accepts FLD and FSTP with an m32, m64 or m80 operand; FADDP ST(i), ST(0); FMUL, FDIV and -FDIVR with an m32 or m64 operand, with ST(0), ST(i) and with ST(i), ST(0); and FMULP, FDIVP and FDIVRP -ST(i), ST(0), for i from 1 to 7. A function starts with control word 0x027F, TOP 0, eight empty registers -and a clear status word, and must return with the stack empty. The stack depth before every instruction -is fixed at translation time, so each register maps to a C++ slot and no TOP is needed at run time. -Translation rejects any x87 instruction outside the profile (including control-word and status-word -access, and a popping form with ST(0) as the destination), a stack overflow or underflow, a depth that -differs where control flow joins, an x87 instruction it cannot reach from the entry through direct -edges, and x87 state that is live at a call, a return, an indirect branch or an external edge. The -helpers are in tools/x87_soft.h, which the generated source must include before the lowered functions -(X87_HEADER). +The profile accepts FLD and FSTP with an m32, m64 or m80 operand; FADD, FSUB, FSUBR, FMUL, FDIV and +FDIVR with an m32 or m64 operand, with ST(0), ST(i) and with ST(i), ST(0); and FADDP, FSUBP, FSUBRP, +FMULP, FDIVP and FDIVRP ST(i), ST(0), for i from 1 to 7. A function starts with control word 0x027F, +TOP 0, eight empty registers and a clear status word, and must return with the stack empty. The stack +depth before every instruction is fixed at translation time, so each register maps to a C++ slot and no +TOP is needed at run time. Translation rejects any x87 instruction outside the profile (including +control-word and status-word access, and a popping form with ST(0) as the destination), a stack +overflow or underflow, a depth that differs where control flow joins, an x87 instruction it cannot +reach from the entry through direct edges, and x87 state that is live at a call, a return, an indirect +branch or an external edge. The helpers are in tools/x87_soft.h, which the generated source must +include before the lowered functions (X87_HEADER). """ from pathlib import Path from iced_x86 import FlowControl, MemorySize as S, Mnemonic as M, OpKind as K, Register as R X87_HEADER = Path(__file__).with_name("x87_soft.h").read_text(encoding="ascii") -X87_OPS = frozenset({M.FLD, M.FSTP, M.FADDP, M.FMUL, M.FMULP, M.FDIV, M.FDIVP, M.FDIVR, M.FDIVRP}) +X87_OPS = frozenset({M.FLD, M.FSTP, M.FADD, M.FADDP, M.FSUB, M.FSUBP, M.FSUBR, M.FSUBRP, M.FMUL, M.FMULP, + M.FDIV, M.FDIVP, M.FDIVR, M.FDIVRP}) DECLARATION = "X87Value x87_slot[8]{};" LOADS = {S.FLOAT32: "x87_from_f32(load(a))", S.FLOAT64: "x87_from_f64(load(a))", @@ -25,11 +26,12 @@ # An arithmetic memory operand keeps a signaling NaN signaling until the NaN rules have seen it. OPERANDS = {S.FLOAT32: "x87_operand_f32(load(a))", S.FLOAT64: "x87_operand_f64(load(a))"} # Two-operand register arithmetic: mnemonic -> helper. The P forms pop after writing ST(i). -ARITHMETIC = {M.FADDP: "x87_add", M.FMUL: "x87_mul", M.FMULP: "x87_mul", M.FDIV: "x87_div", M.FDIVP: "x87_div", +ARITHMETIC = {M.FADD: "x87_add", M.FADDP: "x87_add", M.FSUB: "x87_sub", M.FSUBP: "x87_sub", M.FSUBR: "x87_subr", + M.FSUBRP: "x87_subr", M.FMUL: "x87_mul", M.FMULP: "x87_mul", M.FDIV: "x87_div", M.FDIVP: "x87_div", M.FDIVR: "x87_divr", M.FDIVRP: "x87_divr"} # Arithmetic with a memory operand or with ST(0), ST(i) / ST(i), ST(0), which keeps the stack depth. -TWO_FORM = frozenset({M.FMUL, M.FDIV, M.FDIVR}) -POPPING = frozenset({M.FADDP, M.FMULP, M.FDIVP, M.FDIVRP}) +TWO_FORM = frozenset({M.FADD, M.FSUB, M.FSUBR, M.FMUL, M.FDIV, M.FDIVR}) +POPPING = frozenset({M.FADDP, M.FSUBP, M.FSUBRP, M.FMULP, M.FDIVP, M.FDIVRP}) # Every x87 mnemonic in iced starts with F (including FXSAVE/FXRSTOR, which store the x87 state, and @@ -119,7 +121,7 @@ def statement(i, depth, address): store = {S.FLOAT32: f"store(a, x87_to_f32({v}));", S.FLOAT64: f"store(a, x87_to_f64({v}));", S.FLOAT80: f"store(a, {v}.sig); store(a + 8, {v}.se);"}[i.memory_size] return f"{{ const word a = {address()}; {store} }}" - if i.op_count == 1: # FMUL, FDIV, FDIVR m32/m64: ST(0) = ST(0) op operand + if i.op_count == 1: # arithmetic with an m32/m64 operand: ST(0) = ST(0) op operand return (f"{{ const word a = {address()}; " f"x87_slot[{top}] = {ARITHMETIC[op]}(x87_slot[{top}], {OPERANDS[i.memory_size]}); }}") # The destination is the first operand: ST(i) for FMUL ST(i), ST(0) and the P forms, ST(0) otherwise. diff --git a/tools/x87_soft.h b/tools/x87_soft.h index 9d6b372da..5fa93f3fa 100644 --- a/tools/x87_soft.h +++ b/tools/x87_soft.h @@ -258,3 +258,14 @@ static inline X87Value x87_div(X87Value a, X87Value b) { } // FDIVR: the same division with the operands exchanged. static inline X87Value x87_divr(X87Value a, X87Value b) { return x87_div(b, a); } + +// FSUB: a - b as a + (-b). A NaN or invalid operand is selected before the negation, so a NaN result keeps +// its own sign; x - x is +0, as x + (-x) is. +static inline X87Value x87_sub(X87Value a, X87Value b) { + X87Value out; + if (x87_special_operands(a, b, &out)) return out; + b.se ^= 0x8000; + return x87_add(a, b); +} +// FSUBR: the same subtraction with the operands exchanged. +static inline X87Value x87_subr(X87Value a, X87Value b) { return x87_sub(b, a); }