Motorola 68000, MC68020, MC68030 and MC68040 CPU cores in Swift, as a Swift package (library
M68K). It contains no machine-specific code: a machine supplies its memory map
through the M68KBus protocol and drives the CPU one instruction at a time.
Used by:
- MacMiga, an Amiga 500 emulator for
macOS (
MC68000). - MacClassic, a Macintosh Classic
(
MC68000) and experimental Quadra 700 (MC68040) emulator.
Swift 6 (tools version 6.0), macOS 13 or later.
dependencies: [
.package(url: "https://github.com/AgentiLoop/M68K.git", from: "1.1.0")
],
targets: [
.target(name: "MyMachine", dependencies: [.product(name: "M68K", package: "M68K")])
]import M68K
struct RAM: M68KBus {
var bytes = [UInt8](repeating: 0, count: 0x10000)
func readByte(at address: UInt32) throws -> UInt8 { bytes[Int(address & 0xFFFF)] }
mutating func writeByte(_ value: UInt8, at address: UInt32) throws { bytes[Int(address & 0xFFFF)] = value }
// readWord/readLong/writeWord/writeLong likewise (big-endian)
}
var bus = RAM()
var cpu = MC68000()
try cpu.reset(memory: &bus) // SSP from 0, PC from 4
let clocks = try cpu.step(memory: &bus) // one instruction, its time in CPU clocksM68KBusis the protocol a machine implements for its memory map: big-endianreadByte/Word/Long(at:)andwriteByte/Word/Long(_:at:), all throwing, andresetDevices(), which the RESET instruction calls (it does nothing unless the machine implements it).MC68000is a value type holding only CPU state.reset(memory:)loads SSP and PC from addresses 0 and 4,step(memory:)executes one instruction andinterrupt(level:memory:)presents an autovectored interrupt; each takes the bus asinout. The machine resets its own devices and decides when to interrupt.stepreturns the CPU clocks the instruction took (see "Instruction timing"), and 0 while the CPU is stopped. An accepted interrupt takesMC68000.interruptClocks, 44. The machine advances its own hardware by those amounts.- After RESET the CPU executes the opcode it had already fetched, as a 68000's prefetch does, even if the reset changed what is at that address.
- The CPU checks word and long accesses for odd addresses itself, so a bus
needs no alignment rule. An error thrown by the bus stops
stepwith the CPU's registers unchanged, unless it conforms toM68KAccessFault: that is the machine's bus error (/BERR) and takes vector 2 with the 68000's 14-byte frame (cpu.stopsOnBusError = truerethrows it instead). The frame is written with the registers as they were before the instruction. interrupt(level:vector:memory:)takes the vector number a device supplies in the acknowledge cycle; without one the interrupt is autovectored. The machine passes 24 for a spurious interrupt.- CLR, Scc and MOVE from SR read a memory operand before they write it, as the 68000 does; a device register sees both accesses.
- The members are
@inlinable, so a release build of the client compiles the CPU specialized for its bus type. M68KBus.acknowledgeBreakpoint(_:)models a CPU-space BKPT acknowledgement, separate from memory reads and forwarded through the MMU bus. Its defaultnilresponse takes the illegal-instruction exception. MC68020/MC68030 pass the encoded number (0–7) and execute a returned opcode using extensions from the original instruction stream, without patching code memory. MC68040 passes zero, ignores the response and takes the illegal-instruction exception; MC68000 does not call the hook. A replacement BKPT throwsrecursiveBreakpointNotImplementedrather than attempting nested acknowledgement. This is functional behavior, not bus-cycle timing. References: Motorola M68000PM, BKPT, page 4-53; MC68040UM section 7.5.2, page 7-35 (NXP-hosted manuals). Seven breakpoint tests cover replacement execution, tracing, exceptions, model differences and MMU forwarding; all 223 tests passed.
Not implemented in MC68000: the prefetch queue and the placement in time of
bus cycles inside an instruction. The 68010 has no core.
MC68040 is a functional (untimed) 68040 core with the same reset, step
and interrupt shape; step returns no clock count. An interrupt taken with
the M bit set leaves its frame on the master stack and a throwaway frame on
the interrupt stack, and RTE returns through both. Invalid RTE frame formats take
format-error vector 14 with a format-$0 frame below the untouched invalid frame,
saving the address of RTE. Tests cover invalid format codes, ISP/MSP, trace suppression,
handler repair/retry and host bus-fault rollback. This completes missing behavior of
an existing instruction, not a new opcode. Reference: NXP-hosted MC68040UM sections
8.2.7, 8.4.1, 8.4.5 and 8.4.6 (pages 8-11, 8-21, 8-23 and 8-28). Format $4 belongs
to derivatives, not MC68040. ExecutionError.stackFrameNotImplemented is retained
for source compatibility but is no longer thrown for invalid RTE formats. The 228
package tests passed after this change. MC68040() throws
CPUError.unsupportedInstruction and CPUError.addressError to the host for
an unassigned opcode and an odd instruction address; with
stopsOnIllegalInstruction and stopsOnAddressError set to false it takes
the illegal instruction, line F and address error exceptions instead. It covers the integer
instruction set including 68020+ addressing, bit fields, MOVEC, MOVE16,
CINV/CPUSH, trace exceptions, the MMU (transparent translation registers,
4/8 KB page tables, PTEST, PFLUSH) with access-error format $7 frames, and an
FPU (FMOVE in every format including packed decimal, FMOVECR, arithmetic, FSGLMUL/FSGLDIV,
FSQRT, FMOD/FREM, FSCALE, FGETEXP/FGETMAN, FINT/FINTRZ, compare, FBcc, FScc, FDBcc, FTRAPcc,
FSAVE/FRESTORE idle/null frames, and the transcendental functions). A real 68040 traps
the transcendental and packed-decimal instructions, and denormalized or unnormalized
operands, to Motorola's FPSP; this core computes them itself. Transcendental results
are rounded from a 128-bit working value and tested against correctly rounded
references, but are not claimed to match the FPSP bit for bit. Enabled FPU exception
traps are not delivered to the guest: step throws FPUError.enabledException.
A bus reports /TEA by throwing an error conforming to M68KAccessFault.
The format $7 SSW sets ATC for a translation fault and leaves it clear for a bus
error, and its TM names the space that faulted, so a MOVES through SFC/DFC into
user space reports user data while S is set (MC68040UM 8.4.6.2, Table 3-2). SIZE
is always byte; a bus error reports the privilege level in SR and the address the
bus put in its fault. MOVES function codes 0, 3, 4 and 7 now bypass the ATC,
transparent translation and page tables (MC68040UM 3.2.5, page 3-22, Table 3-2).
Function codes 1/2 and 5/6 retain user/supervisor data translation. The operand
selection is restored on success and thrown errors; extension words and effective
address indirection remain in the current space. The new selectFunctionCode
bus hook defaults to the existing privilege-only hook for compatibility, and the
MC68030 wrapper retains its existing behavior. External TT/TM signal routing and
alternate-space bus-error SSW fields are not implemented by this change.
MovesAlternateSpaceTests.swift covers all eight codes, byte/word/long transfers,
reads/writes, step/run, warm ATC entries, descriptor history, protected TTR bypass
and restoration after errors. The first regression recorded 132 issues before
the fix; all 249 package tests pass afterward.
See the doc comments in Sources/M68K/MC68040*.swift for exact limits.
MC68020 and MC68030 run the MC68040 integer core as the earlier processors,
with the same reset, step, run and interrupt; they are untimed too.
var cpu = MC68030(coprocessor: .mc68882) // .none (the default), .mc68881 or .mc68882
try cpu.reset(memory: &bus)
try cpu.step(memory: &bus)What they do differently from the 68040:
-
MOVEC has SFC, DFC, CACR, USP, VBR, CAAR, MSP and ISP; any other control register is an illegal instruction. CACR keeps E and F on the MC68020 and WA, DBE, FD, ED, IBE, FI and EI on the MC68030, which is how system software tells the three apart. No cache is modelled.
-
The floating-point instructions belong to the coprocessor. Without one they take the line F exception; with one they are the FPU described above, and FSAVE/FRESTORE use a null frame or an idle frame of 28 bytes (MC68881) or 60 bytes (MC68882). The 68040's MOVE16, CINV/CPUSH, PFLUSH and PTEST are line F.
-
A bus error (
M68KAccessFault) or a translation fault takes vector 2 with the 92-byte format $B frame: SR, the faulted instruction's address, a data-fault SSW and the fault address, the internal state zero. RTE from it runs the instruction again; a handler that completes the bus cycle itself and expects the instruction to continue is not served. RTE also accepts formats $1, $2, $9 and $A. -
MC68030has the on-chip MMU: PMOVE (TC, CRP, SRP, TT0, TT1, MMUSR) with the MMU configuration exception, PFLUSH/PFLUSHA, PLOAD, PTEST, table searches as TC describes them (function code level, TIA–TID, short and long descriptors, limits, early termination, indirect descriptors, U/M/WP/S) and the two transparent translation registers. The bus does not tell instruction fetches from data accesses, so function code lookups use the data space.MC68020has no MMU (no MC68851). -
An unassigned opcode takes the illegal instruction exception, an unassigned $Fxxx opcode line F, and an instruction at an odd address the address error exception with the bus-error frame;
stopsOnIllegalInstructionandstopsOnAddressErrorturn these into thrown errors. The 68040's single- and double-rounding FPU forms (FSADD, FDMOVE, …) are line F.
The instructions the MC68020 introduced that the core lacked are there for all
three models: TRAPcc, PACK, UNPK, CMP2, CHK2, CAS, CAS2 and MOVES (which selects
the supervisor's or the user's translation by SFC/DFC); BKPT is an illegal
instruction. MC68020 CALLM/RTM support type-$00 modules with option 000
(arguments on the current stack), including the module frame, register/CCR
restoration, argument removal and change-of-flow tracing. Invalid option/type
fields take format error vector 14. Type-$01 access-control modules and option
100 throw MC68040.ExecutionError.moduleControlNotImplemented; external
CPU-space access-control hardware is not simulated. CALLM/RTM remain illegal
on MC68030/MC68040. Reference: MC68020UM sections 9.7–9.8.
Not implemented in the 32-bit cores: instruction timing, the caches, enabled
floating-point exception traps (step throws FPUError.enabledException),
continuing an instruction after a bus error (RTE runs it again), the MC68851,
and the CALLM/RTM configurations noted above. A double bus fault halts a real processor; here its error is
thrown to the host: a bus error while a bus-error frame is written, and an
address error whose own vector is odd.
M68KClock is a CPU clock frequency with the conversions a machine needs to run
a core at its original speed, and constants for frequencies that Macintosh,
Amiga, NeXT, Atari, Sharp and Sega machines and arcade boards used (.mhz7_8336,
.mhz7_09379, .mhz7_15909, .mhz7_670454, .mhz12, .mhz15_6672, .mhz25,
.mhz33, .mhz40, …; M68KClock(megahertz:) for any other).
let clock = M68KClock.mhz7_15909 // Amiga, NTSC
var budget = clock.clocks(inSeconds: 1.0 / 60) // CPU clocks in one frame
while budget > 0 { budget -= try cpu.step(memory: &bus) } // MC68000.step returns clocks
// The untimed cores take an instruction count; the average clocks per instruction
// is the machine's figure for its processor, caches and memory.
let count = M68KClock.mhz25.instructions(inSeconds: 1.0 / 60, clocksPerInstruction: 2)
try cpu030.run(memory: &bus, instructions: count, executed: &executed)swift testM68KOpcodeSweep executes all 65,536 first words on one model, each with 96
candidate extension words. It lists the opcodes the core leaves unassigned, meaning
every attempt throws CPUError.unsupportedInstruction. Given a table68k file, it
also prints the opcodes that the table lists for that CPU but the core leaves
unassigned. A table68k file is an opcode table in text form, one instruction bit
pattern a line with the CPU level it needs; none is part of this repository.
swift run -c release M68KOpcodeSweep --cpu 68040 path/to/table68kResult on December 3, 2026, against one such table:
| CPU | Unassigned opcodes | Listed in the table but unassigned |
|---|---|---|
| MC68000 | 11,526 | 0 |
| MC68020 + 68881 | 9,985 | 0 |
| MC68030 + 68882 | 10,029 | 0 |
| MC68040 | 13,528 | 0 |
Some extension-word rejections are below the sweep's resolution, for example a nonzero effective-address field on an FPU register-to-register operation, or MOVE16 reserved bits. The sweep does not check them.
The package has a second program, M68KSingleStep, which runs the core against
the two sets of the SingleStepTests project. A test is one instruction with the
registers and memory before and after, and the number of clocks it takes.
| Set | Files | Tests | Made with |
|---|---|---|---|
github.com/SingleStepTests/680x0, folder 68000/v1 |
124 .json.gz (about 190 MB) |
1,000,060 | a reference emulator |
github.com/SingleStepTests/m68000, folder v1 |
127 .json.bin (about 130 MB) |
317,500 | "the microcoded core in MAME", in its README's words |
Neither is in this repository, and neither was measured on a 68000.
swift run -c release M68KSingleStep 68000/v1
swift run -c release M68KSingleStep m68000/v1
swift run -c release M68KSingleStep --show 5 68000/v1/ASR.b.json.gzA test passes when all registers, SR, PC and every listed byte of memory match
and nothing else was written. The bus cycles and the prefetch queue are not
compared; the core models neither. The clocks are compared and counted apart;
they do not make a test fail. --show N lists the first N failures of each
file, --address-errors lists those among the address-error tests, --clocks
lists the tests whose time differs, and --only TEXT runs the tests whose name
contains TEXT. The second set records as PC the address of the next prefetch;
the program subtracts 4 to get the address of the next instruction.
Result on November 25, 2026:
| 680x0 set | m68000 set | |
|---|---|---|
| Tests without an address error | 821,973 | 261,894 |
| of those, passing | 813,220 | 260,338 |
| of those, failing | 8,753 | 1,556 |
| of those, with a different time | 2,601 | 0 |
| Tests with an address error | 178,087 | 55,606 |
| of those, matching exactly | 54,524 | 24,061 |
| of those, matching except inside the exception frame | 63,120 | 16,251 |
| of those, differing elsewhere too | 60,443 | 15,294 |
The two sets disagree with each other, so no core can pass both. Where they disagree M68K follows Motorola's manuals, and where the manuals call a result undefined or give no figure, the m68000 set, because its generator works at the level of the 68000's microcode.
The 8,753 failures against the 680x0 set:
- 3,736 are ASR by a register count larger than the operand's width, on a negative operand. That set expects C and X clear; M68K sets them, because every bit shifted out is a copy of the sign bit (Programmer's Reference Manual, ASR: "The carry bit receives the last bit shifted out of the operand"). The m68000 set expects the same as M68K.
- 4,693 are DIVU and DIVS with an overflow. N and Z are documented as undefined; that set leaves them as they were, the m68000 set has N set and Z clear, and so does M68K.
- 321 are CHK without a trap and with N set beforehand. N is documented as undefined; that set leaves it, the m68000 set clears it, and so does M68K.
- 2 are ASL.B tests whose expected result changes all 32 bits of the register, which a byte shift cannot do.
- 1 is that set's only division by zero, a DIVU. Its expected stacked PC is the instruction's own address; M68K stacks the next instruction's, as it does for CHK, where the set agrees. The m68000 set has no division by zero.
The 2,601 different times against the 680x0 set: 731 are ADDQ.L and SUBQ.L to an address register (6 clocks there; 8 in the User's Manual's table 8-5, the m68000 set and M68K), 1,265 are DIVS whose overflow shows only after the division (16 or 18 there, plus the operand), and 605 are CHK traps (40 there, 38 in the m68000 set, when the register is negative and bound − register overflows 16 bits).
The 1,556 failures against the m68000 set:
- 1,230 are STOP in supervisor mode and differ only in PC: the set's value is 4 lower than its convention gives for every other instruction, which I take to mean that a stopped 68000 has not fetched ahead. M68K's PC is the address after STOP's two words.
- 326 are LINK A7. That set pushes A7 as it was before the instruction; M68K and the 680x0 set push A7 − 4, the value after the decrement, which is the order the Programmer's Reference Manual gives ("SP – 4 → SP; An → (SP)"). Not resolved.
The address-error tests that differ outside the frame do so in what the faulting
instruction had already changed, for example An after -(An) and SR. Inside
the frame, in the seven files of the 680x0 set I looked at, the difference is
the stacked PC. The time of an address error is a flat 50 clocks in M68K; in
the m68000 set's TST.W, CLR.L, ADD.L and MOVEM.W files it is 58 to 72, longer by
the time the instruction had already run, so most of those times differ
(133,714 and 48,739 tests). The address-error handling was not changed in this
round.
Running the sets found these faults, now fixed and covered by unit tests:
- ABCD could stop the emulator with a Swift arithmetic trap for some operands that are not valid BCD (the ABCD file ended with signal 5 before the fix), and SBCD and NBCD gave different results from the sets for such operands (7,052 tests).
- CHK took its exception with An as it was before
(An)+or-(An). - A division by zero left N, Z, V and C as they were in the stacked SR; they are
now clear, as the 680x0 set's one such test expects. It also keeps An as
(An)+or-(An)left it, which is by analogy with CHK: neither set has a test of that. - A jump to an odd address took its address error one step late, and JSR had pushed the return address by then.
- The address-error frame held only 24 bits of the access address and none of the opcode bits in its first word.
- A division that overflowed left N and Z as they were.
step returns the time of each instruction in CPU clocks. The figures are
those of tables 8-1 to 8-14 of the MC68000 User's Manual: 4 clocks for each bus
cycle of an operand or extension word, and the instruction's own time on top.
In four places both test sets have a different figure from the printed table,
and M68K uses theirs:
| Instruction | Table | Both sets and M68K |
|---|---|---|
| ADDQ.W to an address register | 4 | 8 |
| ANDI.L to a data register | 14 | 16 |
| TAS on memory | 14 + operand | 10 + operand |
| BTST with an immediate operand | 8 | 10 |
Where the time depends on the data it is computed from the data:
- shifts and rotates take 2 clocks per bit;
- BCHG, BSET and BCLR on a data register take 2 clocks less for a bit below 16;
- MULU takes 38 clocks and 2 for each 1 in the source, MULS 38 and 2 for each change between neighbouring bits of the source with a 0 appended below it;
- DIVU takes 10 clocks on overflow and 76 to 136 otherwise, DIVS 16 or 18 on an overflow seen at once and 120 to 156 otherwise (the table gives only the maxima, 140 and 158). The rule is Jorge Cwik's description of the 68000's division as I remember it, not taken from a source in front of me; it gives the m68000 set's time in all 3,064 of its DIVU and DIVS tests without an address error;
- MOVEM takes 4 clocks per word moved;
- a trap takes 34 clocks, a division by zero 38 and CHK 38 or 40 plus the operand, an interrupt 44 and an address error 50.
All 261,894 tests of the m68000 set without an address error have the time M68K returns, and 819,372 of the 821,973 of the 680x0 set (the other 2,601 are listed above). What is not modelled: where inside an instruction each bus cycle falls, the time of an address error beyond the flat 50 clocks, and wait states, which belong to the machine.
The package's tests, 89 of them, use no machine-specific code. Most run on
TestBus, a memory map made for them: 2 MiB of RAM at $000000, 256 KiB of
read-only ROM at $FC0000, and a hole in between where every access throws.
Nine more tests run on a 64 KiB RAM bus (reset, a program with a loop and a
subroutine, STOP ended by an interrupt, the address-error frame, illegal and
TRAP vectors, the RESET instruction: the device reset, the kept prefetch,
privilege, and an interrupt discarding the prefetch, and trace: after an
ordinary instruction, not after the one that sets T or an illegal instruction,
after TRAP, and ending STOP). Seven tests check the time of about 125
instructions. MacMiga tests the CPU's use in the Amiga machine (interrupts,
STOP, and power-on and reset through the ROM overlay) in its own test target.
Sources/M68K/MC68000.swift implements D0–D7, A0–A7, banked
user/supervisor stack pointers, status bits, and external reset-vector loading.
The supported instructions are MOVE.B/W/L, MOVEA.W/L, LEA, PEA, JMP, JSR,
MOVEQ, ADD/ADDA/ADDQ/ADDI/ADDX, SUB/SUBA/SUBQ/SUBI/SUBX, CMP/CMPA/CMPI/CMPM,
NEG/NEGX/CLR/NOT/TST/TAS, AND/OR/EOR and their immediate forms (including to
CCR/SR), BTST/BCHG/BCLR/BSET, ASL/ASR/LSL/LSR/ROL/ROR/ROXL/ROXR (register and
memory), MULU/MULS/DIVU/DIVS, SWAP, EXT, EXG, MOVEM, MOVE to/from SR and CCR,
MOVE USP, LINK/UNLK, Scc, DBcc, Bcc/BRA/BSR, RTS, RTR, RTE, TRAP, TRAPV, RESET
(resets the devices on the bus), STOP, NOP, ABCD/SBCD/NBCD (for operands that are not valid BCD, and for the
undocumented N and V, the results are those of the single-step test set; see
"Single-step tests"), CHK.W (trap 6 if the register is negative or above the
bound; N set for a negative register and clear otherwise, Z/V/C cleared) and
MOVEP.W/.L. This completes the 68000 instruction set;
unassigned encodings and invalid addressing modes take the illegal-instruction
exception (vector 4, stacked PC = the opcode's address), as on hardware. Setting
cpu.stopsOnIllegalInstruction = true makes step throw
CPUError.unsupportedInstruction instead, which the decoder tests use.
MOVE supports register direct,
indirect, postincrement, predecrement, displacement, brief indexed, absolute,
PC-relative source, and immediate source addressing. LEA, JMP, and JSR accept
only control addressing modes and preserve condition codes. ADD and SUB set
X, N, Z, V, and C; address-register destinations (ADDA/SUBA and ADDQ/SUBQ to
An) use all 32 bits and leave flags unchanged. ADDX/SUBX/NEGX only clear Z.
Compares set N, Z, V, and C and leave X unchanged; CMPA compares all 32 bits
with a sign-extended word source. DBcc decrements only
the low word of Dn and leaves flags unchanged.
DIVU/DIVS overflow leaves the register unchanged, sets V and N and clears C and
Z (N and Z are documented as undefined; these are the m68000 test set's
values). A division by zero stacks SR with N, Z, V and
C clear. CHK and the divisions take their exception after (An)+ or -(An)
has changed An.
Branches support byte and word displacements. Unsupported opcodes throw an
opcode/address diagnostic.
Exceptions: TRAP #n, TRAPV, privilege violation, divide by zero, ILLEGAL, line A, line F, and MOVEC (68010+, executed by system software to detect the CPU) are processed the 68000 way: SR and the return PC are pushed on the supervisor stack and the CPU jumps through the vector table.
Autovectored interrupts (interrupt(level:memory:)) are accepted at level 7 or
above the SR mask: SR and PC are stacked, the mask is raised and STOP ends.
Level 7 is treated as level-sensitive (real hardware: edge-triggered).
Each instruction is executed in one step and its time is returned (see
"Instruction timing"); the bus cycles inside it are not placed in time. The
prefetch is absent. Trace: an instruction that starts with SR's T bit set is
followed by the trace exception (vector 9, 34 clocks, the next instruction's
address stacked); it also follows TRAP, TRAPV, CHK and a division by zero, and
ends STOP, but not an illegal instruction, line A/F, a privilege violation or an
address error. cpu.stopsBeforeTrace = true leaves it out, as the single-step
test sets record their results. A word or long access to an odd address takes the address-error
exception: vector 3 with the 14-byte group 0 frame (access type and function
code, with the opcode's upper 11 bits above them; all 32 bits of the access
address; opcode; SR; PC). A jump, branch or return to an odd address takes it
in the same step, as the 68000 fetches from the target before the instruction
ends; JSR pushes no return address in that case. The stacked PC is the branch's
address + 2 for Bcc, BRA and BSR, the odd address for other fetch faults,
otherwise the instruction address + 2 (hardware
stacks 2–10 bytes past it). Both were needed by a cracked Amiga disk of Super
Cars (1990), which still runs Rob Northen's Copylock code: it decrypts itself
one instruction at a time from the trace handler, then branches to an odd
address on purpose and adds up its own code as far as the stacked PC to find
where to go on. A fault while writing that frame stops emulation instead of
halting the CPU. Setting cpu.stopsOnAddressError = true throws
CPUError.addressError instead, as the fault-preservation tests do. The core
has no bus-error exception: an error thrown by the bus is rethrown from step.
M68K is released under the MIT License; see LICENSE.