Zophar's Message Domain

Zophar's Message Domain (http://www.zophar.net/forums/index.php)
-   General Emulation (http://www.zophar.net/forums/forumdisplay.php?f=5)
-   -   Unconditional jumps and PC increment (http://www.zophar.net/forums/showthread.php?t=15237)

ajsimpson 05-15-2012 10:21 PM

Unconditional jumps and PC increment

I'm writing a simple GB emulator (wow, now that's something new, isn't it), since I'm really taking my first steps in emu.

What i don't seem to understand is how to correctly implement the CPU cycle and unconditional jumps.

Consider the command JP nn (unconditional jump to memory adress pointed out), like JP 1000h, if I have a basic loop of


increment PC
read opcode
execute command

Then after the JP opcode has been read and the command executed (read 1000h from memory and set PC = 1000h), the PC gets incremented and becomes 1001h, thus resulting in bad emulation.

tl;dr How do you emulate jumps in emulators, so that PC value stays correct, when having cpu loops that increment PC?

I've looked into source code in this GB emulator (written in C#) [url]http://meatfighter.com/gameboy/[/url] and it got me really confused. What it has is a cpu loop, similar to proposed above, then a switch statement to parse commands, but the JP nn command just loads the supplied value to PC, so I fail to understand how the emulator functions correctly, if the PC gets increased afterwards.


int opCode = 0x00;
      if (!halted) {
        opCode = ReadByte(PC);
        if (stopCounting) {
          stopCounting = false;
        } else {


    case 0xC3: // JP N

    private void Jump() {
          PC = ReadWord(PC);
          ticks += 10;

I wish to thank in advance if someone points me to the right direction. Thank you!

hcs 05-27-2012 11:53 PM

It's actually a slightly different order:

1. Read opcode
2. Increment PC (you are now pointing at the next opcode or the data for the current opcode)
3. Do whatever

You'll notice that this is the order that the GB emulator you linked to uses.

The PC in general will be incremented whenever something is read from the instruction stream, so that it will point to the next byte to be read.

This does get somewhat confusing when the instruction does something with PC before the increment happens, like the 6502's JSR/RTS instructions. The Z80 Call/Return is more straightforward than that, fortunately.

All times are GMT. The time now is 06:09 AM.

Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2021, Jelsoft Enterprises Ltd.