Skip to content

Fix SQRT.S operand selection in the FPU translator - #277

Open
yanm1103 wants to merge 1 commit into
ran-j:mainfrom
yanm1103:fix/fpu-sqrt-rsqrt-operands
Open

yanm1103 wants to merge 1 commit into
ran-j:mainfrom
yanm1103:fix/fpu-sqrt-rsqrt-operands

Conversation

@yanm1103

@yanm1103 yanm1103 commented Oct 9, 2026 •

Copy link
Copy Markdown

Problem

FpuTranslator reads the wrong operand for SQRT.S:

case COP1_S_SQRT: return fmt::format("ctx->f[{}] = FPU_SQRT_S(ctx->f[{}]);", fd, fs);

On the R5900, SQRT.S fd, ft takes its source from the ft field; the fs field is 0 in the encoding. For example sqrt.s $f2, $f2 is the word 0x46020084 (fmt=S, ft=2, fs=0, fd=2, funct=4), and it is translated to ctx->f[2] = FPU_SQRT_S(ctx->f[0]);, the square root of the wrong register.

Fix

Read ft. FPU_SQRT_S (ps2_fsqrt, from #272) already takes the magnitude of its input, so nothing else changes.

Scope

This PR originally also fixed RSQRT.S (1/sqrt(fs) instead of fs/sqrt(ft)). #272 fixed that part in the meantime, so it has been rebased onto current main and reduced to SQRT.S only. #218 proposed the same SQRT.S change earlier.

Verification

  • Added a ps2x_tests case in code_generator_tests.cpp for sqrt.s $f2, $f2 (0x46020084). Full suite on Linux (GCC, Release): 446/446 pass with the fix; without it, this new case is the only failure.
  • Found while recompiling a retail PS2 game whose ELF has sqrt.s in 108 functions. An original function and an independent reimplementation, both recompiled with PS2Recomp, disagreed in 300/300 random states without the fix and matched 300/300 with it.

🤖 Generated with Claude Code

https://claude.ai/code/session_01HhodgessnwK5k3pipLwFp3

On the R5900, SQRT.S fd, ft takes its source from the ft field (the fs
field is 0 in the encoding). The translator read fs, so a real
"sqrt.s $f2, $f2" (word 0x46020084) became FPU_SQRT_S(f[0]).

Read ft instead. FPU_SQRT_S already ignores the sign of its input, as
the hardware does. Add a code generator test for the encoding.

RSQRT.S had the same kind of bug and was fixed in ran-j#272.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HhodgessnwK5k3pipLwFp3
@yanm1103 yanm1103 changed the title Fix SQRT.S and RSQRT.S operand selection in the FPU translator Fix SQRT.S operand selection in the FPU translator Oct 19, 2026
@yanm1103
yanm1103 force-pushed the fix/fpu-sqrt-rsqrt-operands branch from 9a7ca59 to cb3a848 Compare October 19, 2026 18:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant