// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! Which way the 65816 should dispatch, measured rather than argued about. //! //! On the 6502 an opcode settles everything 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. There are two //! ways to live with that. Ask the flags inside the instruction, which costs a //! test and a branch on every width-dependent one. Or build one dispatch table //! per combination of the two flags and pick between them when the opcode is //! fetched, 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. //! //! Both are built into this one program and run back to back in the same //! process, so the comparison cannot be spoiled by a different build, a //! different machine or a different moment. //! //! The program they run is a fixed stream of the implemented instructions, //! laid out so that it is exactly parseable: no immediate operands except the //! masks of the REP and SEP that flip the widths, because an immediate is the //! one operand whose length depends on the very flags being changed, and a //! stream that cannot be laid out in advance is a stream where the two //! candidates might execute different work. Everything else has a fixed //! length, so the program counter always lands on an opcode and both //! candidates do exactly the same thing. //! //! The stores that could write anywhere are left out — the long ones, and the //! ones through a long pointer — because their target bank comes out of the //! operand or out of memory rather than from the data bank register, and a //! benchmark that overwrites its own program is measuring something else. Every //! other store is here; they land in bank zero or in the data bank, and the //! program is in a bank of its own. const std = @import("std"); const zig65 = @import("zig65"); /// Where the program lives. Nothing in the mix can write here: the data bank /// register is set elsewhere and never changes, since the instructions that /// would change it are not implemented yet. const program_bank: u8 = 0x01; /// Where the stores go. const data_bank: u8 = 0x02; /// One entry in the mix: an opcode and how many operand bytes follow it. const Shape = struct { opcode: u8, operands: u8 }; /// Every implemented encoding whose length does not depend on a width flag, /// less the stores that could reach the program bank. const mix = [_]Shape{ // Loads, across every mode they have. .{ .opcode = 0xa5, .operands = 1 }, // LDA dp .{ .opcode = 0xb5, .operands = 1 }, // LDA dp,X .{ .opcode = 0xad, .operands = 2 }, // LDA abs .{ .opcode = 0xbd, .operands = 2 }, // LDA abs,X .{ .opcode = 0xb9, .operands = 2 }, // LDA abs,Y .{ .opcode = 0xaf, .operands = 3 }, // LDA long .{ .opcode = 0xbf, .operands = 3 }, // LDA long,X .{ .opcode = 0xb2, .operands = 1 }, // LDA (dp) .{ .opcode = 0xb1, .operands = 1 }, // LDA (dp),Y .{ .opcode = 0xa1, .operands = 1 }, // LDA (dp,X) .{ .opcode = 0xa7, .operands = 1 }, // LDA [dp] .{ .opcode = 0xb7, .operands = 1 }, // LDA [dp],Y .{ .opcode = 0xa3, .operands = 1 }, // LDA sr .{ .opcode = 0xb3, .operands = 1 }, // LDA (sr),Y .{ .opcode = 0xa6, .operands = 1 }, // LDX dp .{ .opcode = 0xb6, .operands = 1 }, // LDX dp,Y .{ .opcode = 0xae, .operands = 2 }, // LDX abs .{ .opcode = 0xbe, .operands = 2 }, // LDX abs,Y .{ .opcode = 0xa4, .operands = 1 }, // LDY dp .{ .opcode = 0xb4, .operands = 1 }, // LDY dp,X .{ .opcode = 0xac, .operands = 2 }, // LDY abs .{ .opcode = 0xbc, .operands = 2 }, // LDY abs,X // Stores whose bank is the data bank or bank zero. .{ .opcode = 0x85, .operands = 1 }, // STA dp .{ .opcode = 0x95, .operands = 1 }, // STA dp,X .{ .opcode = 0x8d, .operands = 2 }, // STA abs .{ .opcode = 0x9d, .operands = 2 }, // STA abs,X .{ .opcode = 0x99, .operands = 2 }, // STA abs,Y .{ .opcode = 0x92, .operands = 1 }, // STA (dp) .{ .opcode = 0x91, .operands = 1 }, // STA (dp),Y .{ .opcode = 0x81, .operands = 1 }, // STA (dp,X) .{ .opcode = 0x83, .operands = 1 }, // STA sr .{ .opcode = 0x93, .operands = 1 }, // STA (sr),Y .{ .opcode = 0x86, .operands = 1 }, // STX dp .{ .opcode = 0x96, .operands = 1 }, // STX dp,Y .{ .opcode = 0x8e, .operands = 2 }, // STX abs .{ .opcode = 0x84, .operands = 1 }, // STY dp .{ .opcode = 0x94, .operands = 1 }, // STY dp,X .{ .opcode = 0x8c, .operands = 2 }, // STY abs .{ .opcode = 0x64, .operands = 1 }, // STZ dp .{ .opcode = 0x74, .operands = 1 }, // STZ dp,X .{ .opcode = 0x9c, .operands = 2 }, // STZ abs .{ .opcode = 0x9e, .operands = 2 }, // STZ abs,X // And the ones that touch no memory at all, which are the cheapest // instructions there are and so the ones where a dispatch difference // shows most plainly. .{ .opcode = 0x18, .operands = 0 }, // CLC .{ .opcode = 0x38, .operands = 0 }, // SEC .{ .opcode = 0xb8, .operands = 0 }, // CLV .{ .opcode = 0xea, .operands = 0 }, // NOP }; /// One instruction in thirty-two changes the widths, which is far more often /// than real code does — a program usually picks a width and keeps it for a /// stretch. Erring this way is deliberate: it is the case that punishes the /// table strategy hardest, since every change is a different table and a cold /// one. const default_width_change_every = 32; /// Lays out the program. Exactly 65536 bytes, so the program counter's wrap at /// the end of the bank lands on the first opcode again. fn layOut(program: *[65536]u8, seed: u64, width_change_every: usize) void { var prng: std.Random.DefaultPrng = .init(seed); const random = prng.random(); var at: usize = 0; var since_change: usize = 0; while (true) { // A width change, or an instruction from the mix. const shape: Shape = if (since_change >= width_change_every) blk: { since_change = 0; break :blk .{ .opcode = if (random.boolean()) 0xc2 else 0xe2, .operands = 1 }; } else mix[random.uintLessThan(usize, mix.len)]; if (at + 1 + shape.operands > program.len) break; program[at] = shape.opcode; at += 1; for (0..shape.operands) |i| { // The mask for REP and SEP names both width flags; everything else // takes whatever it is given. program[at + i] = if (shape.opcode == 0xc2 or shape.opcode == 0xe2) 0x30 else random.int(u8); } at += shape.operands; since_change += 1; } // Pad to the end with the one-byte instruction, so the wrap is clean. @memset(program[at..], 0xea); } /// Runs the program and gives back how long it took, in nanoseconds. fn measure( comptime CPU: type, io: std.Io, gpa: std.mem.Allocator, program: *const [65536]u8, instructions: usize, ) !u64 { var cpu: CPU = undefined; try cpu.init(gpa, null); defer cpu.deinit(); try cpu.memory.loadProgram(@as(u24, program_bank) << 16, program); // Native mode, since that is the half of the machine this question is // about: emulating, the widths never change and there is nothing to // choose between. cpu.flags.setEmulation(false); cpu.registers.program_bank = program_bank; cpu.registers.data_bank = data_bank; cpu.registers.direct = 0x0000; cpu.registers.set(.X, 0x1234); cpu.registers.set(.Y, 0x5678); cpu.stack.set(0x01ff); cpu.program_counter.jump(0x0000); const started = std.Io.Timestamp.now(io, .awake); for (0..instructions) |_| { cpu.executeInstruction() catch |err| switch (err) { error.IllegalOpcode => unreachable, // the layout cannot produce one else => return err, }; } const ended = std.Io.Timestamp.now(io, .awake); // Kept so the optimiser cannot decide none of this was needed. std.mem.doNotOptimizeAway(cpu.registers.get(.A)); std.mem.doNotOptimizeAway(cpu.clock.read()); return @intCast(started.durationTo(ended).nanoseconds); } pub fn main(init: std.process.Init) !void { const io = init.io; var debug_allocator: std.heap.DebugAllocator(.{}) = .init; defer _ = debug_allocator.deinit(); const gpa = std.heap.smp_allocator; _ = &debug_allocator; var args: std.process.Args.Iterator = .init(init.minimal.args); _ = args.skip(); const instructions: usize = if (args.next()) |text| try std.fmt.parseInt(usize, text, 10) else 20_000_000; const rounds: usize = if (args.next()) |text| try std.fmt.parseInt(usize, text, 10) else 5; // How often the widths change, which is the one thing the two strategies // should differ on: the more often, the worse a branch predictor should do // and the better a table should look. const width_change_every: usize = if (args.next()) |text| try std.fmt.parseInt(usize, text, 10) else default_width_change_every; var program: [65536]u8 = undefined; layOut(&program, 0x5eed_65816, width_change_every); const Branch = zig65.cpu16.Bare; const Tables = zig65.cpu16.BareTables; std.debug.print( "{d} instructions, {d} rounds, a width change every {d}, alternating\n\n", .{ instructions, rounds, width_change_every }, ); var best_branch: u64 = std.math.maxInt(u64); var best_tables: u64 = std.math.maxInt(u64); for (0..rounds) |round| { // Alternating rather than one after the other, so that anything that // drifts during the run — the governor, another process, the cache — // lands on both rather than on whichever went second. const branch = try measure(Branch, io, gpa, &program, instructions); const tables = try measure(Tables, io, gpa, &program, instructions); best_branch = @min(best_branch, branch); best_tables = @min(best_tables, tables); std.debug.print( " round {d}: branch {d: >7.1} ms tables {d: >7.1} ms\n", .{ round + 1, @as(f64, @floatFromInt(branch)) / 1e6, @as(f64, @floatFromInt(tables)) / 1e6 }, ); } const per = struct { fn second(ns: u64, count: usize) f64 { return @as(f64, @floatFromInt(count)) / (@as(f64, @floatFromInt(ns)) / 1e9); } }.second; std.debug.print("\nbest of {d}:\n", .{rounds}); std.debug.print( " branch {d: >8.1} ms {d: >6.1} million instructions a second\n", .{ @as(f64, @floatFromInt(best_branch)) / 1e6, per(best_branch, instructions) / 1e6 }, ); std.debug.print( " tables {d: >8.1} ms {d: >6.1} million instructions a second\n", .{ @as(f64, @floatFromInt(best_tables)) / 1e6, per(best_tables, instructions) / 1e6 }, ); const ratio = @as(f64, @floatFromInt(best_branch)) / @as(f64, @floatFromInt(best_tables)); if (ratio > 1) std.debug.print("\n tables is {d:.2}x faster\n", .{ratio}) else std.debug.print("\n branch is {d:.2}x faster\n", .{1 / ratio}); // What the second strategy costs in room, which is the other half of the // trade and does not show up in a stopwatch. std.debug.print( "\n dispatch table: {d} bytes for one, {d} for four\n", .{ @sizeOf(@TypeOf(Branch.Opcodes.table)), @sizeOf(@TypeOf(Tables.Opcodes.tables)) }, ); }