improve branching cycle accuracy

This commit is contained in:
Vineet K 2024-07-03 20:40:57 -04:00
parent 2236e79556
commit 4fcc8d48f4

39
cpu.c
View File

@ -1,4 +1,5 @@
#include <libgen.h> #include <libgen.h>
#include <stdbool.h>
#include <stdint.h> #include <stdint.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
@ -151,6 +152,20 @@ opcode_mem(enum addressing_mode mode)
return val; return val;
} }
static void
branch(uint16_t addr, bool cond)
{
if (!cond)
return;
cycles++;
addr += regs.pc;
if ((regs.pc + 1) & 0xFF00 != addr & 0xFF00)
cycles++;
regs.pc = addr;
}
void void
ADC(uint16_t arg) ADC(uint16_t arg)
{ {
@ -201,22 +216,19 @@ ASL(uint16_t mem)
void void
BCC(uint16_t arg) BCC(uint16_t arg)
{ {
if (regs.status.carry == 0) branch(arg, regs.status.carry == 0);
regs.pc += arg, cycles++;
} }
void void
BCS(uint16_t arg) BCS(uint16_t arg)
{ {
if (regs.status.carry == 1) branch(arg, regs.status.carry == 1);
regs.pc += arg, cycles++;
} }
void void
BEQ(uint16_t arg) BEQ(uint16_t arg)
{ {
if (regs.status.zero == 1) branch(arg, regs.status.zero == 1);
regs.pc += arg, cycles++;
} }
void void
@ -232,22 +244,19 @@ BIT(uint16_t arg)
void void
BMI(uint16_t arg) BMI(uint16_t arg)
{ {
if (regs.status.negative == 1) branch(arg, regs.status.negative == 1);
regs.pc += arg, cycles++;
} }
void void
BNE(uint16_t arg) BNE(uint16_t arg)
{ {
if (regs.status.zero == 0) branch(arg, regs.status.zero == 0);
regs.pc += arg, cycles++;
} }
void void
BPL(uint16_t arg) BPL(uint16_t arg)
{ {
if (regs.status.negative == 0) branch(arg, regs.status.negative == 0);
regs.pc += arg, cycles++;
} }
void void
@ -263,16 +272,14 @@ BVC(uint16_t arg)
{ {
//regs.status.overflow = (STATUS_TO_INT() & (1 << 6)) == 0; //regs.status.overflow = (STATUS_TO_INT() & (1 << 6)) == 0;
//if (regs.status.overflow == 0) //if (regs.status.overflow == 0)
if ((STATUS_TO_INT() & (1 << 6)) == 0) branch(arg, (STATUS_TO_INT() & (1 << 6)) == 0);
regs.pc += arg, cycles++;
} }
void void
BVS(uint16_t arg) BVS(uint16_t arg)
{ {
regs.status.overflow = (STATUS_TO_INT() & (1 << 6)) != 0; regs.status.overflow = (STATUS_TO_INT() & (1 << 6)) != 0;
if (regs.status.overflow == 1) branch(arg, regs.status.overflow == 1);
regs.pc += arg, cycles++;
} }
void void