# SPDX-License-Identifier: MIT """WDC's Table 5-4 and Table 5-7 (W65C816S datasheet, 2024-03-13) as code: rung 0's fixture. Table 5-7 lists, for every addressing mode, each cycle's VPB, MLB, VDA, VPA, RWB and address-bus expression, with notes (1)-(17) adding or removing cycles. ``schedule()`` transcribes it, one branch per table row. With ``Machine(..., quirks=False)`` it is *literal*: no knowledge from any other source, so every disagreement with the corpus is a place where the datasheet is silent, wrong, or simplified (scripts/datasheet_timing.py measures those). With ``quirks=True`` the decided emulation-mode readings are layered on (docs/undocumented-behavior.md): U1 (direct page wraps in its page when D.l = 0, for the 6502's modes), U2 (the 6502's stack instructions wrap S in page one, the new ones and PLB (C5) do not) and U3 (C4: ``(d,x)``'s high byte from the same page when D.l is not 0). C1 (VPA) and C2 (a program read) are the datasheet's and bsnes's readings, which the transcription already gives. It evaluates only what the address bus and cycle count need, never an instruction's result. """ from __future__ import annotations from collections.abc import Iterator, Mapping from dataclasses import dataclass # --- the opcode map (datasheet Table 5-4; modes named as in Table 5-6) ------ # --- the opcode map (datasheet Table 5-4; modes named as in Table 5-6) ------ ROWS = """ BRK s ORA (d,x) COP s ORA d,s TSB d ORA d ASL d ORA [d] PHP s ORA # ASL A PHD s TSB a ORA a ASL a ORA al BPL r ORA (d),y ORA (d) ORA (d,s),y TRB d ORA d,x ASL d,x ORA [d],y CLC i ORA a,y INC A TCS i TRB a ORA a,x ASL a,x ORA al,x JSR a AND (d,x) JSL al AND d,s BIT d AND d ROL d AND [d] PLP s AND # ROL A PLD s BIT a AND a ROL a AND al BMI r AND (d),y AND (d) AND (d,s),y BIT d,x AND d,x ROL d,x AND [d],y SEC i AND a,y DEC A TSC i BIT a,x AND a,x ROL a,x AND al,x RTI s EOR (d,x) WDM i EOR d,s MVP xyc EOR d LSR d EOR [d] PHA s EOR # LSR A PHK s JMP a EOR a LSR a EOR al BVC r EOR (d),y EOR (d) EOR (d,s),y MVN xyc EOR d,x LSR d,x EOR [d],y CLI i EOR a,y PHY s TCD i JML al EOR a,x LSR a,x EOR al,x RTS s ADC (d,x) PER s ADC d,s STZ d ADC d ROR d ADC [d] PLA s ADC # ROR A RTL s JMP (a) ADC a ROR a ADC al BVS r ADC (d),y ADC (d) ADC (d,s),y STZ d,x ADC d,x ROR d,x ADC [d],y SEI i ADC a,y PLY s TDC i JMP (a,x) ADC a,x ROR a,x ADC al,x BRA r STA (d,x) BRL rl STA d,s STY d STA d STX d STA [d] DEY i BIT # TXA i PHB s STY a STA a STX a STA al BCC r STA (d),y STA (d) STA (d,s),y STY d,x STA d,x STX d,y STA [d],y TYA i STA a,y TXS i TXY i STZ a STA a,x STZ a,x STA al,x LDY # LDA (d,x) LDX # LDA d,s LDY d LDA d LDX d LDA [d] TAY i LDA # TAX i PLB s LDY a LDA a LDX a LDA al BCS r LDA (d),y LDA (d) LDA (d,s),y LDY d,x LDA d,x LDX d,y LDA [d],y CLV i LDA a,y TSX i TYX i LDY a,x LDA a,x LDX a,y LDA al,x CPY # CMP (d,x) REP # CMP d,s CPY d CMP d DEC d CMP [d] INY i CMP # DEX i WAI i CPY a CMP a DEC a CMP al BNE r CMP (d),y CMP (d) CMP (d,s),y PEI s CMP d,x DEC d,x CMP [d],y CLD i CMP a,y PHX s STP i JML (a) CMP a,x DEC a,x CMP al,x CPX # SBC (d,x) SEP # SBC d,s CPX d SBC d INC d SBC [d] INX i SBC # NOP i XBA i CPX a SBC a INC a SBC al BEQ r SBC (d),y SBC (d) SBC (d,s),y PEA s SBC d,x INC d,x SBC [d],y SED i SBC a,y PLX s XCE i JSR (a,x) SBC a,x INC a,x SBC al,x """ def opcode_map() -> list[tuple[str, str]]: table = [] for row in ROWS.strip().splitlines(): words = row.split() table.extend(zip(words[0::2], words[1::2], strict=True)) assert len(table) == 256, len(table) return table OPCODES = opcode_map() STORES = {"STA", "STX", "STY", "STZ"} RMW = {"ASL", "LSR", "ROL", "ROR", "INC", "DEC", "TSB", "TRB"} INDEX_WIDTH = {"LDX", "LDY", "STX", "STY", "CPX", "CPY", "PHX", "PHY", "PLX", "PLY"} BRANCH = { # flag mask, value that takes the branch "BPL": (0x80, 0), "BMI": (0x80, 0x80), "BVC": (0x40, 0), "BVS": (0x40, 0x40), "BCC": (0x01, 0), "BCS": (0x01, 0x01), "BNE": (0x02, 0), "BEQ": (0x02, 0x02), "BRA": (0, 0), } # fmt: skip @dataclass(frozen=True) class Cycle: """One row of Table 5-7: the bus signals and the 24-bit address.""" address: int vda: bool vpa: bool write: bool vpb: bool = False # VPB asserted (pin low): the two vector reads mlb: bool = False # MLB asserted (pin low): the read-modify-write cycles def signals(self) -> tuple[bool, bool, bool, bool, bool]: return (self.vda, self.vpa, self.vpb, self.write, self.mlb) class Machine: """Just enough state to evaluate Table 5-7's address expressions.""" def __init__(self, state: dict, ram: Mapping[int, int], quirks: bool = False) -> None: self.pc = state["pc"] self.pbr = state["pbr"] self.dbr = state["dbr"] self.d = state["d"] self.s = state["s"] self.x = state["x"] self.y = state["y"] self.p = state["p"] self.e = state["e"] self.ram = ram self.quirks = quirks self.c = state["a"] self.m16 = not self.e and not self.p & 0x20 self.x16 = not self.e and not self.p & 0x10 # Section 2.11: in emulation mode the stack is page one (SH = $01); # section 2.7: with X = 1 the index high bytes are zero. The corpus # stores whatever its generator held, so apply both before reading. if self.e: self.s = 0x100 | self.s & 0xFF if not self.x16: self.x &= 0xFF self.y &= 0xFF def byte(self, address: int) -> int: return self.ram.get(address & 0xFFFFFF, 0) def direct(self, offset: int) -> int: """'0,D+expr' for the 6502's direct-page modes; U1: with E = 1 and D.l = 0 the sum stays in page D.h.""" if self.quirks and self.e and not self.d & 0xFF: return self.d | offset & 0xFF return b0(self.d + offset) def stack_step(self, step: int, new: bool) -> None: """S += step; U2: the 6502's instructions wrap S in page one in emulation mode, the new ones step all 16 bits.""" if self.quirks and self.e and not new: self.s = (self.s & 0xFF00) | (self.s + step) & 0xFF else: self.s = (self.s + step) & 0xFFFF def prog(self, offset: int) -> int: """PBR,PC+offset (the PC increments within the bank).""" return self.pbr << 16 | (self.pc + offset) & 0xFFFF def b0(offset: int) -> int: """'0,expr': bank 0, the expression wrapped to 16 bits.""" return offset & 0xFFFF def long(bank: int, offset: int) -> int: """'BANK,expr' for data: 24-bit, the carry from the offset reaches the bank.""" return ((bank << 16) + offset) & 0xFFFFFF def schedule(op: int, m: Machine) -> Iterator[Cycle]: mnemonic, mode = OPCODES[op] store = mnemonic in STORES wide = m.x16 if mnemonic in INDEX_WIDTH else m.m16 def prog(offset: int, vda: bool = False, vpa: bool = True) -> Cycle: return Cycle(m.prog(offset), vda, vpa, False) def io(address: int) -> Cycle: return Cycle(address, False, False, False) def data(address: int, step: int = 1) -> Iterator[Cycle]: """Data Low then, with note (1), Data High at address + 1.""" yield Cycle(address, True, False, store) if wide: yield Cycle((address + step) & 0xFFFFFF, True, False, store) def rmw(low: int, high: int) -> Iterator[Cycle]: """Table 5-7 rows 1d, 6b, 10b, 16b: read, (3)(17) modify, write high first.""" yield Cycle(low, True, False, False, mlb=True) if wide: yield Cycle(high, True, False, False, mlb=True) # (17): "In the emulation mode, during a R-M-W instruction the RWB is # low during both write and modify cycles." The table prints AA+1 for # the modify cycle; with 8-bit data there is no AA+1 access, and the # address of the last read is taken instead (docs/timing.md, C-items). yield Cycle(high if wide else low, False, False, bool(m.e), mlb=True) if wide: yield Cycle(high, True, False, True, mlb=True) yield Cycle(low, True, False, True, mlb=True) def dl_cycle() -> Iterator[Cycle]: if m.d & 0xFF: # (2) yield io(m.prog(1)) def push(value_cycles: int, new: bool = False) -> Iterator[Cycle]: for _ in range(value_cycles): yield Cycle(b0(m.s), True, False, True) m.stack_step(-1, new) yield prog(0, vda=True) # cycle 1: the opcode do = m.byte(m.prog(1)) aa = m.byte(m.prog(1)) | m.byte(m.prog(2)) << 8 aab = m.byte(m.prog(3)) if mode == "#": yield prog(1) if mnemonic in ("REP", "SEP"): # (1)(8): always 3 cycles, VPA low in the third yield io(m.prog(1)) elif wide: yield prog(2) elif mode in ("i", "A"): if mnemonic == "WDM": # not in Table 5-7; Table 5-4 says 2 bytes, 2 cycles yield prog(1) else: yield io(m.prog(1)) if mnemonic in ("XBA", "WAI", "STP"): # 19b, 19c, 19d yield io(m.prog(1)) elif mode == "a": yield prog(1) yield prog(2) if mnemonic == "JMP": # 1b return if mnemonic == "JSR": # 1c yield io(m.prog(2)) yield from push(2) return if mnemonic in RMW: # 1d yield from rmw(long(m.dbr, aa), long(m.dbr, aa + 1)) else: # 1a yield from data(long(m.dbr, aa)) elif mode == "(a,x)": if mnemonic == "JMP": # 2a yield prog(1) yield prog(2) yield io(m.prog(2)) else: # 2b JSR: pushes between the operand bytes yield prog(1) yield from push(2, new=True) yield prog(2) yield io(m.prog(2)) target = m.pbr << 16 | (aa + m.x) & 0xFFFF yield Cycle(target, False, True, False) yield Cycle(m.pbr << 16 | (aa + m.x + 1) & 0xFFFF, False, True, False) elif mode == "(a)": # 3a JML (DC), 3b JMP (6C): pointer in bank 0 yield prog(1) yield prog(2) for k in range(3 if mnemonic == "JML" else 2): yield Cycle(b0(aa + k), True, False, False) elif mode == "al": yield prog(1) yield prog(2) if mnemonic == "JSL": # 4c yield Cycle(b0(m.s), True, False, True) # PBR yield io(b0(m.s)) m.stack_step(-1, True) yield prog(3) yield from push(2, new=True) return yield prog(3) if mnemonic == "JML": # 4b return yield from data(long(aab, aa)) # 4a elif mode == "al,x": # 5 yield prog(1) yield prog(2) yield prog(3) yield from data(long(aab, aa + m.x)) elif mode in ("a,x", "a,y"): # 6a, 6b, 7 index = m.x if mode == "a,x" else m.y yield prog(1) yield prog(2) crossed = (aa & 0xFF) + index > 0xFF if mnemonic in RMW or store or m.x16 or crossed: # (4) yield io(m.dbr << 16 | (aa & 0xFF00) | (aa + index) & 0xFF) target = long(m.dbr, aa + index) if mnemonic in RMW: yield from rmw(target, (target + 1) & 0xFFFFFF) else: yield from data(target) elif mode == "xyc": # 9a/9b: one 7-cycle pass per byte dba, sba = do, m.byte(m.prog(2)) step = 1 if mnemonic == "MVN" else -1 first = True while True: if not first: yield prog(0, vda=True) # each byte refetches the opcode first = False yield prog(1) yield prog(2) yield Cycle(sba << 16 | m.x, True, False, False) yield Cycle(dba << 16 | m.y, True, False, True) yield io(dba << 16 | m.y) yield io(dba << 16 | m.y) mask = 0xFFFF if m.x16 else 0xFF m.x = (m.x + step) & mask m.y = (m.y + step) & mask m.c = (m.c - 1) & 0xFFFF # C, all 16 bits whatever M is if m.c == 0xFFFF: return elif mode in ("d", "d,x", "d,y"): # 10a, 10b, 16a, 16b, 17 yield prog(1) yield from dl_cycle() index = 0 if mode != "d": yield io(m.prog(1)) index = m.x if mode == "d,x" else m.y address = m.direct(do + index) if mnemonic in RMW: yield from rmw(address, m.direct(do + index + 1)) else: yield Cycle(address, True, False, store) if wide: yield Cycle(m.direct(do + index + 1), True, False, store) elif mode in ("(d,x)", "(d)", "(d),y", "[d]", "[d],y"): # 11-15 yield prog(1) yield from dl_cycle() offset = do if mode == "(d,x)": yield io(m.prog(1)) offset += m.x if mode.startswith("["): # U1: the new modes never wrap low, high = b0(m.d + offset), b0(m.d + offset + 1) else: low, high = m.direct(offset), m.direct(offset + 1) if mode == "(d,x)" and m.quirks and m.e and m.d & 0xFF: # U3 (C4) high = (low & 0xFF00) | (low + 1) & 0xFF yield Cycle(low, True, False, False) yield Cycle(high, True, False, False) address = m.byte(low) | m.byte(high) << 8 bank = m.dbr if mode.startswith("["): yield Cycle(b0(m.d + offset + 2), True, False, False) bank = m.byte(b0(m.d + offset + 2)) if mode == "(d),y": crossed = (address & 0xFF) + m.y > 0xFF if store or m.x16 or crossed: # (4) yield io(m.dbr << 16 | (address & 0xFF00) | (address + m.y) & 0xFF) index = m.y if mode.endswith("y") else 0 yield from data(long(bank, address + index)) elif mode == "r": # 20 yield prog(1) mask, value = BRANCH[mnemonic] if (m.p & mask) == value: yield io(m.prog(1)) # (5) offset = do - 0x100 if do & 0x80 else do after = (m.pc + 2) & 0xFFFF if m.e and (after & 0xFF00) != ((after + offset) & 0xFF00): # (6) yield io(m.prog(1)) elif mode == "rl": # 21 yield prog(1) yield prog(2) yield io(m.prog(2)) elif mode == "d,s": # 23 yield prog(1) yield io(m.prog(1)) yield Cycle(b0(m.s + do), True, False, store) if wide: yield Cycle(b0(m.s + do + 1), True, False, store) elif mode == "(d,s),y": # 24 yield prog(1) yield io(m.prog(1)) yield Cycle(b0(m.s + do), True, False, False) yield Cycle(b0(m.s + do + 1), True, False, False) yield io(b0(m.s + do + 1)) address = m.byte(b0(m.s + do)) | m.byte(b0(m.s + do + 1)) << 8 yield from data(long(m.dbr, address + m.y)) elif mode == "s": yield from stack(mnemonic, m, do, wide) else: raise ValueError(mode) def stack(mnemonic: str, m: Machine, do: int, wide: bool) -> Iterator[Cycle]: def io(address: int) -> Cycle: return Cycle(address, False, False, False) def pull(count: int, new: bool = False) -> Iterator[Cycle]: for _ in range(count): m.stack_step(1, new) yield Cycle(m.s, True, False, False) def push(count: int, new: bool = False) -> Iterator[Cycle]: for _ in range(count): yield Cycle(m.s, True, False, True) m.stack_step(-1, new) sizes = {"PHB": 1, "PHK": 1, "PHP": 1, "PHD": 2, "PLB": 1, "PLP": 1, "PLD": 2} if mnemonic in ("PHA", "PHX", "PHY", "PHB", "PHK", "PHP", "PHD"): # 22c yield io(m.prog(1)) yield from push(sizes.get(mnemonic, 2 if wide else 1), new=mnemonic == "PHD") elif mnemonic in ("PLA", "PLX", "PLY", "PLB", "PLP", "PLD"): # 22b yield io(m.prog(1)) yield io(m.prog(1)) # C5: PLB steps S in 16 bits, as PLD does. yield from pull(sizes.get(mnemonic, 2 if wide else 1), new=mnemonic in ("PLB", "PLD")) elif mnemonic == "PEA": # 22d yield Cycle(m.prog(1), False, True, False) yield Cycle(m.prog(2), False, True, False) yield from push(2, new=True) elif mnemonic == "PEI": # 22e yield Cycle(m.prog(1), False, True, False) if m.d & 0xFF: yield io(m.prog(1)) yield Cycle(b0(m.d + do), True, False, False) yield Cycle(b0(m.d + do + 1), True, False, False) yield from push(2, new=True) elif mnemonic == "PER": # 22f yield Cycle(m.prog(1), False, True, False) yield Cycle(m.prog(2), False, True, False) yield io(m.prog(2)) yield from push(2, new=True) elif mnemonic == "RTI": # 22g; (7) no PBR pull in emulation mode yield io(m.prog(1)) yield io(m.prog(1)) yield from pull(3 if m.e else 4) elif mnemonic == "RTS": # 22h yield io(m.prog(1)) yield io(m.prog(1)) yield from pull(2) yield io(m.s) elif mnemonic == "RTL": # 22i yield io(m.prog(1)) yield io(m.prog(1)) yield from pull(3, new=True) elif mnemonic in ("BRK", "COP"): # 22j; (7) no PBR push in emulation mode yield Cycle(m.prog(1), False, True, False) yield from push(3 if m.e else 4) if m.e: vector = 0xFFFE if mnemonic == "BRK" else 0xFFF4 else: vector = 0xFFE6 if mnemonic == "BRK" else 0xFFE4 yield Cycle(vector, True, False, False, vpb=True) yield Cycle(vector + 1, True, False, False, vpb=True) else: raise ValueError(mnemonic)