| 1 | // Copyright 2025 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include <bit> |
| 5 | |
| 6 | #include "Common/CommonTypes.h" |
| 7 | #include "Common/FloatUtils.h" |
| 8 | #include "Common/ScopeGuard.h" |
| 9 | #include "Common/x64ABI.h" |
| 10 | #include "Core/Core.h" |
| 11 | #include "Core/PowerPC/Jit64/Jit.h" |
| 12 | #include "Core/PowerPC/Jit64Common/Jit64AsmCommon.h" |
| 13 | #include "Core/PowerPC/Jit64Common/Jit64PowerPCState.h" |
| 14 | #include "Core/System.h" |
| 15 | |
| 16 | #include "../TestValues.h" |
| 17 | |
| 18 | #include <gtest/gtest.h> |
| 19 | |
| 20 | namespace |
| 21 | { |
| 22 | class TestFres : public CommonAsmRoutines |
| 23 | { |
| 24 | public: |
| 25 | explicit TestFres(Core::System& system) : CommonAsmRoutines(jit), jit(system) |
| 26 | { |
| 27 | using namespace Gen; |
| 28 | |
| 29 | AllocCodeSpace(4096); |
| 30 | m_const_pool.Init(AllocChildCodeSpace(1024), 1024); |
| 31 | |
| 32 | const auto raw_fres = reinterpret_cast<double (*)(double)>(AlignCode4()); |
| 33 | GenFres(); |
| 34 | |
| 35 | wrapped_fres = reinterpret_cast<u64 (*)(u64, const UReg_FPSCR&)>(AlignCode4()); |
| 36 | ABI_PushRegistersAndAdjustStack(ABI_ALL_CALLEE_SAVED, 8, 16); |
| 37 | |
| 38 | // We know that the only part of PowerPCState that the fres routine accesses is the fpscr. |
| 39 | // We manufacture a PPCSTATE pointer so it reads from our provided fpscr instead. |
| 40 | LEA(64, RPPCSTATE, MDisp(ABI_PARAM2, -PPCSTATE_OFF(fpscr))); |
| 41 | |
| 42 | // Call |
| 43 | MOVQ_xmm(XMM0, R(ABI_PARAM1)); |
| 44 | ABI_CallFunction(raw_fres); |
| 45 | MOVQ_xmm(R(ABI_RETURN), XMM0); |
| 46 | |
| 47 | ABI_PopRegistersAndAdjustStack(ABI_ALL_CALLEE_SAVED, 8, 16); |
| 48 | RET(); |
| 49 | } |
| 50 | |
| 51 | u64 (*wrapped_fres)(u64, const UReg_FPSCR&); |
| 52 | Jit64 jit; |
| 53 | }; |
| 54 | |
| 55 | } // namespace |
| 56 | |
| 57 | TEST(Jit64, Fres) |
| 58 | { |
| 59 | Core::DeclareAsCPUThread(); |
| 60 | Common::ScopeGuard cpu_thread_guard([] { Core::UndeclareAsCPUThread(); }); |
| 61 | |
| 62 | TestFres test(Core::System::GetInstance()); |
| 63 | |
| 64 | // FPSCR with NI set |
| 65 | const UReg_FPSCR fpscr = UReg_FPSCR(0x00000004); |
| 66 | |
| 67 | for (const u64 ivalue : double_test_values) |
| 68 | { |
| 69 | const double dvalue = std::bit_cast<double>(ivalue); |
| 70 | |
| 71 | const u64 expected = std::bit_cast<u64>(Common::ApproximateReciprocal(dvalue)); |
| 72 | const u64 actual = test.wrapped_fres(ivalue, fpscr); |
| 73 | |
| 74 | if (expected != actual) |
| 75 | fmt::print("{:016x} -> {:016x} == {:016x}\n", ivalue, actual, expected); |
| 76 | |
| 77 | EXPECT_EQ(expected, actual); |
| 78 | } |
| 79 | } |