gb-opcodes icon indicating copy to clipboard operation
gb-opcodes copied to clipboard

Change STOP byte count to 1

Open SonoSooS opened this issue 1 year ago • 8 comments

It doesn't make sense to have a 2-byte instruction which takes 1 M-cycle, as that's impossible to actually achieve on the CPU in any way (yes, that even includes ADD HL, r16, as it does ALU operation on both M-cycles, lower half first, then upper half in the second cycle).

There are two ways to solve this issue:

  • make it 1B 1M, as that's what it actually is
  • keep it as 2B, but make it 32769M (execution of STOP takes a single M-cycle, and wakeup from STOP mode fetches the next instruction on the 32768th cycle)

And yes, STOP is actually a single byte opcode, which can be observed when STOP fails to stop due to a button being held. The short explaination of why STOP consumes two bytes can be summarized in these points:

  • PC is always one byte ahead of the currently executed instruction
  • if STOP enters stop mode, it fetches the next opcode, incrementing PC (PC points to STOP +2)
  • the fetched opcode is discarded, and replaced with NOP
  • on wakeup, the NOP fetches the instruction at STOP +2, and executes it in the next cycle More details can be found here.

The reason HALT does not consume two bytes is because PC is not incremented when HALT fetches the next opcode, but otherwise works similar to STOP. More details here.

SonoSooS avatar Jun 14 '23 17:06 SonoSooS