diff --git a/gbso/insn.py b/gbso/insn.py index ccee90a..440a7da 100644 --- a/gbso/insn.py +++ b/gbso/insn.py @@ -717,7 +717,8 @@ class ADD_SP_DD(Insn): def exec(self, cpu: CPU) -> None: sp = cpu.get_reg16(R16.SP) + self.dd cpu.carry = 1 if sp > 0xFFFF or sp < 0 else 0 - cpu.set_reg16(R16.SP, sp) + cpu.set_reg16(R16.SP, sp & 0xFFFF) + cpu.cycles += 16 def pretty(self) -> str: return f"ADD SP, {self.dd}" @@ -730,7 +731,8 @@ class LD_HL_SP_DD(Insn): def exec(self, cpu: CPU) -> None: sp = cpu.get_reg16(R16.SP) + self.dd cpu.carry = 1 if sp > 0xFFFF or sp < 0 else 0 - cpu.set_reg16(R16.HL, sp) + cpu.set_reg16(R16.HL, sp & 0xFFFF) + cpu.cycles += 12 def pretty(self) -> str: return f"LD HL, SP + {self.dd}" diff --git a/tests/insn/test_alu16.py b/tests/insn/test_alu16.py index 05c4963..a762acf 100644 --- a/tests/insn/test_alu16.py +++ b/tests/insn/test_alu16.py @@ -43,3 +43,51 @@ def test_dec_rr(rr): assert cpu.get_reg16(rr) == 0xABCC assert cpu.cycles == 8 + + +def test_add_sp_dd(): + cpu = CPU() + cpu.set_reg16(R16.SP, 0xFFFF) + + ADD_SP_DD(-1).exec(cpu) + + assert cpu.get_reg16(R16.SP) == 0xFFFE + assert cpu.carry == 0 + assert cpu.cycles == 16 + + ADD_SP_DD(2).exec(cpu) + + assert cpu.get_reg16(R16.SP) == 0 + assert cpu.carry == 1 + assert cpu.cycles == 32 + + ADD_SP_DD(-1).exec(cpu) + + assert cpu.get_reg16(R16.SP) == 0xFFFF + assert cpu.carry == 1 + assert cpu.cycles == 48 + + +def test_ld_hl_sp_dd(): + cpu = CPU() + cpu.set_reg16(R16.SP, 0xFFFF) + + LD_HL_SP_DD(1).exec(cpu) + + assert cpu.get_reg16(R16.HL) == 0 + assert cpu.carry == 1 + assert cpu.cycles == 12 + + cpu.set_reg16(R16.SP, 0) + LD_HL_SP_DD(-1).exec(cpu) + + assert cpu.get_reg16(R16.HL) == 0xFFFF + assert cpu.carry == 1 + assert cpu.cycles == 24 + + cpu.set_reg16(R16.SP, 0xFFFF) + LD_HL_SP_DD(-2).exec(cpu) + + assert cpu.get_reg16(R16.HL) == 0xFFFD + assert cpu.carry == 0 + assert cpu.cycles == 36