// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! The 65816, as its own processor rather than as an option on the 6502. //! //! Nothing here is shared with `cpu.zig`, and that is the point. The two could //! have been one core generic over its width, and the cost of that would have //! been paid by the five 8-bit processors: a runtime branch on the width flags //! in the operand path of a core that is the hot loop, and — worse — a memory //! interface addressed by something wider than sixty-four kilobytes. Today a //! `u16` against a 65536-byte array means an address that is out of range is //! not a bug to be caught but a program that will not compile. Widening that //! for the sake of a sixth processor would trade a guarantee the compiler //! gives for free against masks and assertions at run time, on every machine //! in the project, for the benefit of the one that needs the room. //! //! So they sit side by side. What is genuinely common — the clock, and the //! decimal arithmetic, neither of which knows what an address is — is shared; //! everything shaped by the width of an address is written twice, on purpose. //! The other half of that bargain is that work here cannot regress the twelve //! and a half million corpus cases the 8-bit core passes. //! //! **The core is complete.** The registers, the flags, the stack, the program //! counter, the addressing modes and the table builder are here, and so is //! every one of the 256 instructions — the 65816 has no undefined encodings. //! All of it passes the SingleStepTests corpus (`zig build corpus16`): five //! million cases, native mode and emulation mode, matching cycle for cycle and //! bus line for bus line. What is not here is a machine to put it in; nothing //! in the models above holds a 65816 yet, so the corpus is what exercises it. const std = @import("std"); const addressing_modes = @import("cpu16/addressing_modes.zig"); const flags = @import("cpu16/flags.zig"); const memory16 = @import("memory16.zig"); const opcodes = @import("cpu16/opcodes.zig"); const program_counter = @import("cpu16/program_counter.zig"); const registers = @import("cpu16/registers.zig"); const stack = @import("cpu16/stack.zig"); pub const Errors = error{ Break, IllegalOpcode, IllegalOperation, IllegalAddressingMode, IllegalValue, }; /// How the dispatch table is built, which is the open question this core has /// to answer and the reason both answers are buildable. /// /// On the 6502 an opcode settles everything: which instruction, which /// addressing mode, how many bytes and how many cycles, all of it known before /// the machine runs. On the 65816 it does not. The same encoding is two bytes /// and two cycles or three and three depending on M and X, and those are /// runtime state that any REP or SEP can change. /// /// `branch` asks the flags inside the instruction, which is the obvious way /// and costs a test and a branch on every width-dependent instruction. /// `tables` builds one dispatch table per combination of the two flags and /// keeps a pointer to the one in force, changing it only when a flag changes, /// which makes the width comptime again — the whole instruction body /// specialises, as the 8-bit core's does — at the cost of four times the table /// and four times the code. /// /// The pointer is the point. An earlier version indexed by the widths on every /// fetch and lost badly, because that put arithmetic on the path of every /// instruction including the ones that do not care about a width, to save a /// branch on the ones that do. Selecting once per change and dereferencing /// thereafter is the version worth measuring. /// /// **`branch` is the answer, and `tables` is kept so the question can be asked /// again.** `zig build bench16` runs both, in one process, over a fixed stream /// of the implemented instructions, and the answer turned on how often a /// program changes its widths (best of three, four million instructions, on an /// eight core Ryzen 5800X): /// /// | a width change every | branch | tables | | /// | --- | --- | --- | --- | /// | instruction | 143.5 M/s | 52.4 M/s | branch 2.74× | /// | 4 instructions | 92.0 M/s | 71.2 M/s | branch 1.29× | /// | 32 instructions | 88.4 M/s | 86.7 M/s | branch 1.02× | /// | never | 93.4 M/s | 96.2 M/s | tables 1.03× | /// /// So the table strategy wins only in the limit where the widths never move at /// all, and then by three per cent, while it loses by nearly three to one when /// they move constantly. Real 65816 code sits at the wrong end of that for it: /// a routine that reaches for `REP #$30` and `SEP #$20` around a piece of work /// changes width every few instructions, not every few thousand. /// /// The reason is not the branch predictor, which does fine — it is that the /// table strategy multiplies the hot code by four. Every instruction body /// exists in four specialisations, and when the widths move about, all four /// copies are live at once. The branch it saves is one well-predicted test /// against a flag already in a register; the cache pressure it buys is not /// nearly so cheap. Which is the opposite of what I expected before measuring, /// and the reason for measuring. pub const Dispatch = enum { branch, tables }; pub const Options = struct { dispatch: Dispatch = .branch, }; /// A 65816 with nothing built around it: a clock that only counts, and the /// whole sixteen megabytes as plain RAM. This is what the tests run against. pub const Bare = Chip(.{}, @import("clock.zig").FakeClock, memory16.Flat(.{})); /// The same, dispatched through one table per width rather than by asking the /// flags inside each instruction. Both are kept so the two can be measured /// against each other rather than argued about. pub const BareTables = Chip(.{ .dispatch = .tables }, @import("clock.zig").FakeClock, memory16.Flat(.{})); /// The same, keeping a record of what went past on the bus, which is what the /// corpus needs and nothing else does. pub const BareLogged = Chip(.{}, @import("clock.zig").FakeClock, memory16.Flat(.{ .bus_log = true })); /// A 65816, parameterised over the clock it counts cycles against and the /// memory it sees. /// /// The memory is a function from the processor type to the model, rather than /// the model itself, because a model needs to name the processor it belongs to /// and the processor is not a type yet at that point. Same arrangement as the /// 8-bit core, and for the same reason. pub fn Chip( comptime options: Options, comptime Clock: type, comptime MemoryModel: fn (type) type, ) type { return struct { const Self = @This(); /// How this one's table is built. See `Dispatch`. pub const dispatch = options.dispatch; /// The two width flags, when they are known at comptime. An /// instruction is handed these as null under `.branch`, meaning ask /// the flags, or with both settled under `.tables`. pub const Widths = struct { /// The accumulator is eight bits. m: bool, /// The index registers are eight bits. x: bool, }; /// Where an instruction's operand is. Twenty-five ways of saying it, /// against the 6502's thirteen. pub const AddressingModes = addressing_modes.Modes; /// Where the processor looks for the address to carry on from when /// something interrupts the ordinary run of instructions. /// /// There are two sets, because there are two machines. In emulation /// mode the vectors are the 6502's, at the top of bank zero, which is /// what lets a 65816 be dropped into a machine that was built for the /// older part. In native mode they move, and there are more of them, /// since BRK and IRQ stop sharing and COP gets one of its own. pub const vector = struct { /// The vectors a 6502 would recognise. pub const emulation = struct { pub const cop: u24 = 0xfff4; pub const abort: u24 = 0xfff8; pub const nmi: u24 = 0xfffa; pub const reset: u24 = 0xfffc; /// IRQ and BRK together, as on the 6502: which one it was is /// what the break flag in the pushed status is for. pub const irq: u24 = 0xfffe; }; /// And the ones only this processor has. pub const native = struct { pub const cop: u24 = 0xffe4; pub const brk: u24 = 0xffe6; pub const abort: u24 = 0xffe8; pub const nmi: u24 = 0xffea; pub const irq: u24 = 0xffee; }; }; pub const Opcodes = opcodes.Opcodes(Self); pub const Memory = MemoryModel(Self); pub const Flags = flags.Flags(Self); pub const Registers = registers.Registers(Self); /// The interrupt request line. Level triggered, as on the 6502. irq: bool = false, /// The non-maskable interrupt line. Edge triggered. nmi: bool = false, /// Whether the memory lock is being held down, which it is across the /// three cycles of a read-modify-write and at no other time. It is an /// output like the width lines, so everything watching the bus sees /// it, and the recordings check it. locked: bool = false, /// Whether the processor has been told to wait, by WAI. waiting: bool = false, /// And whether it has been stopped, by STP, which nothing but a reset /// undoes. stopped: bool = false, /// The table in force, under `.tables`: the one for the widths as they /// stand. Kept rather than worked out, and changed only when a width /// flag does. dispatch_table: if (options.dispatch == .tables) *const [256]?Opcodes.Data else void, clock: Clock, flags: Flags, registers: Registers, program_counter: program_counter.ProgramCounter(Self), addressing_modes: addressing_modes.AddressingModes(Self), stack: stack.Stack(Self), memory: Memory, /// Brings up every part of the processor in place. Does not fetch the /// reset vector; call reset for that. /// /// Unlike the 8-bit core this takes an allocator, because sixteen /// megabytes of memory cannot live inside the struct. pub fn init(self: *Self, gpa: std.mem.Allocator, clock_speed: ?u128) !void { self.irq = false; self.nmi = false; self.locked = false; self.waiting = false; self.stopped = false; self.clock.init(clock_speed); self.addressing_modes.init(); try self.memory.init(gpa); self.program_counter.init(); self.registers.init(); self.stack.init(); self.flags.init(); self.selectTable(); } /// Points at the table for the widths as they now stand. Called by the /// flags whenever one of the two changes, and nothing else has any /// reason to. pub fn selectTable(self: *Self) void { if (comptime dispatch == .tables) self.dispatch_table = Opcodes.tableFor(self.flags.isSet(.M), self.flags.isSet(.X)); } /// Gives the memory back. Unlike the 8-bit core's, this one does /// something, so a caller that forgets to defer it leaks sixteen /// megabytes. pub fn deinit(self: *Self) void { self.memory.deinit(); } /// Does what the reset line does. A 65816 comes up in emulation mode /// in bank zero, which is why a machine built around one can run /// software that has never heard of it. pub fn reset(self: *Self) void { self.memory.reset(); self.stopped = false; self.waiting = false; self.registers.reset(); self.flags.reset(); self.stack.reset(); self.program_counter.reset(); } /// Which way in. Two of these are instructions and the rest are lines /// on the package, and past the first cycle or two they do the same /// thing: the way back and the flags onto the stack, interrupts /// disabled, decimal cleared, and off through a vector in bank zero. pub const Interrupt = enum { brk, cop, irq, nmi, abort }; /// Answers one. /// /// Natively the program bank is pushed too, and the vectors are /// different ones, because natively BRK and IRQ stop sharing and COP /// gets a vector of its own. Either way the handler is entered in bank /// zero, which is why an operating system's handlers live there. pub fn interrupt(self: *Self, comptime which: Interrupt) void { const software = which == .brk or which == .cop; // A hardware interrupt has no opcode and no signature byte to // fetch, so it spends two cycles of its own where those would have // been. A software one has already paid for them. if (!software) { self.program_counter.internal(); self.program_counter.internal(); } const emulating = self.flags.emulation; if (!emulating) self.stack.push(u8, .page_one, self.registers.program_bank); self.stack.push(u16, .page_one, self.program_counter.value); // Emulating, bit four of the pushed status is the 6502's break // flag: set when an instruction asked for this and clear when a // line did, which is the only way a handler can tell them apart // when they share a vector. Natively that bit is the index width // and means nothing of the sort, so it is pushed as it stands. const status = self.flags.dump(); self.stack.push(u8, .page_one, if (emulating and !software) status & ~@as(u8, 0x10) else status); self.flags.set(.I); self.flags.clear(.D); self.registers.program_bank = 0; const at: u24 = if (emulating) switch (which) { .brk, .irq => vector.emulation.irq, .cop => vector.emulation.cop, .nmi => vector.emulation.nmi, .abort => vector.emulation.abort, } else switch (which) { .brk => vector.native.brk, .cop => vector.native.cop, .irq => vector.native.irq, .nmi => vector.native.nmi, .abort => vector.native.abort, }; const low: u16 = self.memory.read(at, .vector); const high: u16 = self.memory.read(at +% 1, .vector); self.program_counter.jump(high << 8 | low); } /// Runs one instruction, or answers an interrupt if one is waiting. /// /// A processor looks at its interrupt lines between instructions, not /// during one — except that a block move is a great many instructions /// and so can be interrupted part way through a move, which is the /// whole reason it is built the way it is. pub fn executeInstruction(self: *Self) error{ IllegalOpcode, Break, Jam }!void { // A stopped processor is not driving the bus at all, and only a // reset starts it again. if (self.stopped) { self.memory.letGo(); return; } // A waiting one is the same until something interrupts it. If // interrupts are enabled it goes to the handler below; if they are // not it simply carries on, which is the useful half of WAI. if (self.waiting) { if (!self.irq and !self.nmi) { self.memory.letGo(); return; } self.waiting = false; } // Emulating, the stack pointer is pulled back into page one // before each instruction rather than after every access: what a // 16-bit push does to it in between is the pointer's own business. self.stack.normalize(); if (self.nmi) { self.nmi = false; self.interrupt(.nmi); return; } if (self.irq and self.flags.isClear(.I)) { self.interrupt(.irq); return; } const opcode = self.program_counter.opcode(); const entry = switch (comptime dispatch) { .branch => &Opcodes.table[opcode], .tables => &self.dispatch_table[opcode], }; const data = if (entry.* == null) return error.IllegalOpcode else &entry.*.?; try data.func(self); } }; } test "the parts come up and go away again" { var cpu: Bare = undefined; try cpu.init(std.testing.allocator, null); defer cpu.deinit(); try std.testing.expect(cpu.flags.emulation); try std.testing.expectEqual(@as(u16, 0x01ff), cpu.stack.get()); } test "XCE is the whole of what makes this processor different" { var cpu: Bare = undefined; try cpu.init(std.testing.allocator, null); defer cpu.deinit(); // CLC, XCE: the two instructions every 65816 program starts with. try cpu.memory.loadProgram(0x000200, &[_]u8{ 0x18, 0xfb }); cpu.program_counter.jump(0x0200); cpu.stack.set(0x6646); // Emulating, so the stack is in page one whatever it was set to. try std.testing.expectEqual(@as(u16, 0x0146), cpu.stack.get()); try cpu.executeInstruction(); try cpu.executeInstruction(); // Native now, and the carry came back holding what the emulation line // used to hold. try std.testing.expect(!cpu.flags.emulation); try std.testing.expect(cpu.flags.isSet(.C)); try std.testing.expectEqual(@as(u64, 4), cpu.clock.cycles); // And going back the other way pulls the stack into page one again. try cpu.memory.loadProgram(0x000202, &[_]u8{0xfb}); cpu.stack.set(0x6646); try std.testing.expectEqual(@as(u16, 0x6646), cpu.stack.get()); try cpu.executeInstruction(); try std.testing.expect(cpu.flags.emulation); try std.testing.expectEqual(@as(u16, 0x0146), cpu.stack.get()); } test "an immediate load is as wide as the flags say" { var cpu: Bare = undefined; try cpu.init(std.testing.allocator, null); defer cpu.deinit(); cpu.flags.setEmulation(false); // The corpus case a9 n 1: an eight-bit accumulator, so two bytes and two // cycles, and the high half of A is left holding what it held. cpu.flags.set(.M); cpu.registers.set(.A, 0x1ec9); try cpu.memory.loadProgram(0x000200, &[_]u8{ 0xa9, 0xfb }); cpu.program_counter.jump(0x0200); try cpu.executeInstruction(); try std.testing.expectEqual(@as(u16, 0x1efb), cpu.registers.get(.A)); try std.testing.expectEqual(@as(u16, 0x0202), cpu.program_counter.value); try std.testing.expectEqual(@as(u64, 2), cpu.clock.cycles); // And a9 n 2: sixteen bits, so three bytes and three cycles. cpu.flags.clear(.M); cpu.registers.set(.A, 0x65b0); try cpu.memory.loadProgram(0x000210, &[_]u8{ 0xa9, 0x06, 0xb3 }); cpu.program_counter.jump(0x0210); const before = cpu.clock.cycles; try cpu.executeInstruction(); try std.testing.expectEqual(@as(u16, 0xb306), cpu.registers.get(.A)); try std.testing.expectEqual(@as(u16, 0x0213), cpu.program_counter.value); try std.testing.expectEqual(@as(u64, 3), cpu.clock.cycles - before); } test "REP and SEP cannot widen a processor that is emulating" { var cpu: Bare = undefined; try cpu.init(std.testing.allocator, null); defer cpu.deinit(); // REP #$30 asks for both widths at once, which is the usual way to ask. try cpu.memory.loadProgram(0x000200, &[_]u8{ 0xc2, 0x30 }); cpu.program_counter.jump(0x0200); try cpu.executeInstruction(); try std.testing.expect(cpu.flags.isSet(.M)); try std.testing.expect(cpu.flags.isSet(.X)); // Native, and it is granted. cpu.flags.setEmulation(false); cpu.program_counter.jump(0x0200); try cpu.executeInstruction(); try std.testing.expect(cpu.flags.isClear(.M)); try std.testing.expect(cpu.flags.isClear(.X)); } test "a pointer at the top of the direct page does not wrap inside it" { // The 6502 wrapped a zero page pointer inside the zero page, and the // natural guess is that the 65816 keeps that while it is emulating. It // does not: the pointer counts on into the next page. The recordings said // so three times over, each on a single rare case, which is why this is // written down here as well. var cpu: Bare = undefined; try cpu.init(std.testing.allocator, null); defer cpu.deinit(); // D at $1200, so the direct page is $1200-$12ff, and LDA ($ff),Y. cpu.registers.direct = 0x1200; cpu.registers.data_bank = 0x7e; cpu.registers.set(.Y, 0x0004); try cpu.memory.loadProgram(0x000200, &[_]u8{ 0xb1, 0xff }); // The pointer's low half at the top of the page and its high half in the // next one, not back at the bottom of this one. cpu.memory.poke(0x0012ff, 0x34); cpu.memory.poke(0x001300, 0x12); // What the 6502's wrap would have picked up, left here to be ignored. cpu.memory.poke(0x001200, 0xff); cpu.memory.poke(0x7e1238, 0x5a); cpu.program_counter.jump(0x0200); try cpu.executeInstruction(); // $1234 + 4, in the data bank. try std.testing.expectEqual(@as(u16, 0x005a), cpu.registers.get(.A)); } test "a long pointer at the same place does not wrap" { // The three-byte pointer is this processor's own, so there is no older // machine's behaviour to reproduce and it counts straight on. This one the // recordings did settle, on a single case out of twenty thousand. var cpu: Bare = undefined; try cpu.init(std.testing.allocator, null); defer cpu.deinit(); cpu.registers.direct = 0x1200; try cpu.memory.loadProgram(0x000200, &[_]u8{ 0xa7, 0xff }); cpu.memory.poke(0x0012ff, 0x34); cpu.memory.poke(0x001300, 0x12); cpu.memory.poke(0x001301, 0x7e); cpu.memory.poke(0x001200, 0xff); cpu.memory.poke(0x7e1234, 0x5a); cpu.program_counter.jump(0x0200); try cpu.executeInstruction(); try std.testing.expectEqual(@as(u16, 0x005a), cpu.registers.get(.A)); } test "an interrupt line is answered between instructions" { // Nothing in the corpus can check this: an interrupt is a line going low, // not an instruction, so there is no encoding to record twenty thousand // cases of. What the recordings did settle is the sequence itself, through // BRK and COP, and a hardware interrupt is that sequence with two cycles // of its own in place of the opcode and the signature byte. var cpu: Bare = undefined; try cpu.init(std.testing.allocator, null); defer cpu.deinit(); cpu.flags.setEmulation(false); cpu.registers.program_bank = 0x12; cpu.stack.set(0x01ff); try cpu.memory.loadProgram(0x120200, &[_]u8{ 0xea, 0xea }); // The native IRQ vector. try cpu.memory.loadProgram(0x00ffee, &[_]u8{ 0x00, 0x40 }); cpu.program_counter.jump(0x0200); cpu.flags.clear(.I); // Nothing is asking, so the instruction runs. try cpu.executeInstruction(); try std.testing.expectEqual(@as(u16, 0x0201), cpu.program_counter.value); cpu.irq = true; try cpu.executeInstruction(); try std.testing.expectEqual(@as(u16, 0x4000), cpu.program_counter.value); // The handler is entered in bank zero whatever bank was interrupted, and // with interrupts disabled so that it is not interrupted itself. try std.testing.expectEqual(@as(u8, 0x00), cpu.registers.program_bank); try std.testing.expect(cpu.flags.isSet(.I)); // The bank that was interrupted is on the stack, which is what natively // makes RTI able to come back to it. try std.testing.expectEqual(@as(u8, 0x12), cpu.memory.peek(0x0001ff)); } test "the interrupt disable masks a request but not a non-maskable one" { var cpu: Bare = undefined; try cpu.init(std.testing.allocator, null); defer cpu.deinit(); cpu.flags.setEmulation(false); try cpu.memory.loadProgram(0x000200, &[_]u8{ 0xea, 0xea, 0xea }); try cpu.memory.loadProgram(0x00ffee, &[_]u8{ 0x00, 0x40 }); // IRQ try cpu.memory.loadProgram(0x00ffea, &[_]u8{ 0x00, 0x50 }); // NMI cpu.program_counter.jump(0x0200); cpu.flags.set(.I); // Asked, and refused. cpu.irq = true; try cpu.executeInstruction(); try std.testing.expectEqual(@as(u16, 0x0201), cpu.program_counter.value); // The other line is not the disable's to refuse, and answering it is what // clears it: it is an edge rather than a level. cpu.nmi = true; try cpu.executeInstruction(); try std.testing.expectEqual(@as(u16, 0x5000), cpu.program_counter.value); try std.testing.expect(!cpu.nmi); } test "the break bit tells a handler which kind of interrupt this was" { // Emulating, BRK and IRQ share a vector, so the only way a handler can // tell them apart is bit four of the status it finds on the stack. Set // means an instruction asked; clear means a line did. Natively that bit is // the index width and the two have vectors of their own instead. var cpu: Bare = undefined; try cpu.init(std.testing.allocator, null); defer cpu.deinit(); try cpu.memory.loadProgram(0x000200, &[_]u8{ 0x00, 0x00 }); try cpu.memory.loadProgram(0x00fffe, &[_]u8{ 0x00, 0x40 }); cpu.program_counter.jump(0x0200); cpu.stack.set(0x01ff); cpu.flags.clear(.I); try cpu.executeInstruction(); try std.testing.expectEqual(@as(u8, 0x10), cpu.memory.peek(0x0001fd) & 0x10); cpu.program_counter.jump(0x0200); cpu.stack.set(0x01ff); cpu.flags.clear(.I); cpu.irq = true; try cpu.executeInstruction(); try std.testing.expectEqual(@as(u8, 0x00), cpu.memory.peek(0x0001fd) & 0x10); } test "a waiting processor lets go of the bus until something interrupts it" { var cpu: BareLogged = undefined; try cpu.init(std.testing.allocator, null); defer cpu.deinit(); cpu.flags.setEmulation(false); try cpu.memory.loadProgram(0x000200, &[_]u8{ 0xcb, 0xea }); cpu.program_counter.jump(0x0200); cpu.flags.set(.I); try cpu.executeInstruction(); try std.testing.expect(cpu.waiting); // Four cycles, the last of them with nothing on the bus at all. try std.testing.expectEqual(@as(u64, 4), cpu.clock.cycles); try std.testing.expect(!cpu.memory.bus.entries[3].cycle.transfers()); // Still nothing asking, so it stays where it is and keeps off the bus. try cpu.executeInstruction(); try std.testing.expect(cpu.waiting); // A request wakes it even though interrupts are disabled — and because // they are, what it does next is simply the following instruction. cpu.irq = true; try cpu.executeInstruction(); try std.testing.expect(!cpu.waiting); try std.testing.expectEqual(@as(u16, 0x0202), cpu.program_counter.value); } test "only a reset starts a stopped processor again" { var cpu: Bare = undefined; try cpu.init(std.testing.allocator, null); defer cpu.deinit(); try cpu.memory.loadProgram(0x000200, &[_]u8{0xdb}); try cpu.memory.loadProgram(0x00fffc, &[_]u8{ 0x00, 0x30 }); cpu.program_counter.jump(0x0200); try cpu.executeInstruction(); try std.testing.expect(cpu.stopped); cpu.irq = true; cpu.nmi = true; for (0..10) |_| try cpu.executeInstruction(); try std.testing.expect(cpu.stopped); cpu.reset(); try std.testing.expect(!cpu.stopped); try std.testing.expectEqual(@as(u16, 0x3000), cpu.program_counter.value); }