From 86ef3406503e7b4d4b71889abca570322e458d8b Mon Sep 17 00:00:00 2001 From: Adrian Conlon <98398945+AdrianConlon@users.noreply.github.com> Date: Sun, 7 Jan 2024 14:35:12 +0000 Subject: [PATCH] Tidy arithmetic overflow handling in M6502 core --- M6502/inc/mos6502.h | 8 ++++++++ M6502/src/mos6502.cpp | 6 +++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/M6502/inc/mos6502.h b/M6502/inc/mos6502.h index 9e53c5e..89e4d74 100644 --- a/M6502/inc/mos6502.h +++ b/M6502/inc/mos6502.h @@ -145,6 +145,14 @@ namespace EightBit { adjustNegative(datum); } + constexpr void adjustOverflow_add(uint8_t operand, uint8_t data, uint8_t intermediate) noexcept { + set_flag(VF, negative(~(operand ^ data) & (operand ^ intermediate))); + } + + constexpr void adjustOverflow_subtract(uint8_t operand, uint8_t data, uint8_t intermediate) noexcept { + set_flag(VF, negative((operand ^ data) & (operand ^ intermediate))); + } + // Miscellaneous void branch(int condition) noexcept; diff --git a/M6502/src/mos6502.cpp b/M6502/src/mos6502.cpp index 6fa613b..d9325f4 100644 --- a/M6502/src/mos6502.cpp +++ b/M6502/src/mos6502.cpp @@ -549,7 +549,7 @@ uint8_t EightBit::MOS6502::sbc(const uint8_t operand, const uint8_t data) noexce const auto difference = m_intermediate; adjustNZ(difference.low); - set_flag(VF, negative((operand ^ data) & (operand ^ difference.low))); + adjustOverflow_subtract(operand, data, difference.low); reset_flag(CF, difference.high); return returned; @@ -591,7 +591,7 @@ uint8_t EightBit::MOS6502::add(uint8_t operand, uint8_t data, int carrying) noex uint8_t EightBit::MOS6502::add_b(uint8_t operand, uint8_t data, int carrying) noexcept { m_intermediate.word = operand + data + carrying; - set_flag(VF, negative(~(operand ^ data) & (operand ^ m_intermediate.low))); + adjustOverflow_add(operand, data, m_intermediate.low); set_flag(CF, carry(m_intermediate.high)); adjustNZ(m_intermediate.low); @@ -612,7 +612,7 @@ uint8_t EightBit::MOS6502::add_d(uint8_t operand, uint8_t data, int carry) noexc } adjustNegative(high.low); - set_flag(VF, negative(~(operand ^ data) & (operand ^ high.low))); + adjustOverflow_add(operand, data, high.low); if (high.word > 0x90) high += 0x60;