207 lines
23 KiB
Swift
207 lines
23 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
||
import Foundation
|
||
|
||
struct AssemblyReferenceLesson {
|
||
let id: String
|
||
let name: String
|
||
let predict: String
|
||
let observation: String
|
||
let assumptions: String
|
||
let body: String
|
||
var hd = false
|
||
|
||
var source: String {
|
||
"; " + name + "\n; " + assumptions + "\n; " + predict + "\n org $3f00\n" + body + "\n end start\n"
|
||
}
|
||
var testedScope: String {
|
||
hd ? "Assembled for HD6309. Debugger outcomes checked in emulation and native modes. MC6809 assembly rejection checked." :
|
||
"Assembled for both targets. Debugger outcomes checked on MC6809 and in HD6309 emulation and native modes."
|
||
}
|
||
var request: AssemblyReferenceExampleRequest { .init(title: name, source: source, target6309: hd) }
|
||
|
||
static let all: [Self] = [
|
||
.init(id: "cell", name: "First Program — Change a Screen Cell",
|
||
predict: "After the load, what is in A? At which step does the display change?",
|
||
observation: "A becomes $8F on the first step. The next step writes $8F to the upper-left cell, the same store as POKE &H0400,&H8F.",
|
||
assumptions: "Disk BASIC 32-column text screen at $0400. No ROM calls, direct-page operands or subroutine stack use.",
|
||
body: "start lda #$8f\n sta $0400\nhold bra hold"),
|
||
.init(id: "count", name: "Count and branch",
|
||
predict: "How many times will BNE jump back after starting B at three?",
|
||
observation: "BNE jumps twice. On the third decrement B is zero, Z sets, and the branch falls through to hold.",
|
||
assumptions: "Observe B, Z and PC. No display, ROM calls, direct-page operands or subroutine stack use.",
|
||
body: "start ldb #3\nagain decb\n bne again\nhold bra hold"),
|
||
.init(id: "call", name: "Pass a value to a subroutine",
|
||
predict: "Where does RTS return, and what value does the caller receive?",
|
||
observation: "JSR saves the address of the store. INCA turns 7 into 8. RTS restores PC and S. The caller writes 8 at result.",
|
||
assumptions: "Uses writable RAM for a private stack below stacktop and an output byte at result. No ROM calls, direct-page operands or display assumptions.",
|
||
body: "start lds #stacktop\n lda #7\n jsr plusone\n sta result\nhold bra hold\nplusone inca\n rts\nresult fcb 0\n zmb 64\nstacktop equ *"),
|
||
.init(id: "page", name: "Draw on a hidden page",
|
||
predict: "Will storing $AA change the text screen or the PMODE preview at $1A00?",
|
||
observation: "In Graphics Preview select At Address, Mapped CPU, $1A00, PMODE 1, Set 0. The first byte supplies four color-index-2 pixels. The CPU writes through its current memory map. The video chip continues reading its selected buffer in physical RAM, so the text display stays as it was.",
|
||
assumptions: "Disk BASIC text display. Uses $1A00 as writable scratch RAM. No video mode change, ROM calls, direct-page operands or subroutine stack use.",
|
||
body: "start lda #$aa\n sta $1a00\nhold bra hold"),
|
||
.init(id: "signed", name: "Compare signed and unsigned",
|
||
predict: "Is $FF lower or higher than $01? Predict the next PC at BLT and BHI.",
|
||
observation: "CMPA leaves A at $FF and produces N=1, V=0, C=0, Z=0. BLT lands at signed and BHI lands at both. $FF is signed −1 and unsigned 255.",
|
||
assumptions: "Observe PC and CC only. No display, ROM calls, direct-page operands or subroutine stack use.",
|
||
body: "start lda #$ff\n cmpa #1\n blt signed\nmiss bra miss\nsigned bhi both\n bra miss\nboth bra both"),
|
||
.init(id: "word", name: "Split a word into E and F",
|
||
predict: "Which half of W will contain $12?",
|
||
observation: "Step LDW. W becomes $1234, E becomes $12 and F becomes $34. Z, N and V clear.",
|
||
assumptions: "HD6309, emulation or native mode. No display, ROM calls, direct-page operands or subroutine stack use.",
|
||
body: "start ldw #$1234\nhold bra hold", hd: true),
|
||
.init(id: "transfer", name: "Copy three bytes with TFM",
|
||
predict: "How far will X and Y advance when W starts at three?",
|
||
observation: "One debugger Step on TFM copies $A5, $5A, $42 to target. X and Y advance by three and W ends at zero. Inspect target in mapped memory.",
|
||
assumptions: "HD6309, either mode. Separate source and destination in RAM. No display, ROM calls, direct-page operands or subroutine stack use.",
|
||
body: "start ldx #table\n ldy #target\n ldw #3\n tfm x+,y+\nhold bra hold\ntable fcb $a5,$5a,$42\ntarget zmb 3", hd: true)
|
||
]
|
||
}
|
||
|
||
extension AssemblyReference {
|
||
static let bibliography = [
|
||
"Atkinson (2009)": "Darren Atkinson. Motorola 6809 and Hitachi 6309 Programmer’s Reference. 2009. Part I contains the instruction discussions, Part II the HD6309 mode and register notes.",
|
||
"Motorola (1981)": "Motorola, Inc. MC6809–MC6809E 8-Bit Microprocessor Programming Manual. M6809PM (AD), original issue March 1981, reprinted May 1983. Chapters 1–2 and Appendix A.",
|
||
"Burke (1993)": "Chris Burke. The 6309 Book: Inside the 6309 Microprocessor. Second edition. Burke & Burke, 1993.",
|
||
"Barden (1983)": "William Barden, Jr. TRS-80 Color Computer Assembly Language Programming. Radio Shack, 1983.",
|
||
"Tepolt (1987)": "Laurence A. Tepolt. Assembly Language Programming for the CoCo 3. TEPCO, 1987.",
|
||
"Astle": "William Astle and LWTools contributors. LW Tool Chain. Manual accompanying LWTools 4.25, chapter 3, LWASM.",
|
||
"VCC Plus": "VCC Plus. Native Debugger and Debugger Memory Tools. Project documentation and regression programs for Graphics Preview and whole-instruction TFM Step."
|
||
]
|
||
|
||
static func topics() -> [AssemblyReferenceEntry] {
|
||
var entries: [AssemblyReferenceEntry] = []
|
||
let motorola = "Motorola (1981), ch. 1", addressing = "Motorola (1981), ch. 2"
|
||
let dialect = "Astle, LWTools 4.25, ch. 3"
|
||
for (name, purpose, hd) in [
|
||
("A","Eight-bit accumulator. A forms the high byte of D.",false), ("B","Eight-bit accumulator. B forms the low byte of D.",false),
|
||
("D","Sixteen-bit accumulator built from A (high) and B (low). Writing D immediately changes both halves.",false),
|
||
("X","Sixteen-bit index register. Use X to address a table or traverse bytes.",false),
|
||
("Y","Sixteen-bit index register. X and Y can walk independent buffers.",false),
|
||
("U","Sixteen-bit user stack pointer, also available as an index register. PSHU and PULU use this stack.",false),
|
||
("S","Sixteen-bit hardware stack pointer. JSR, interrupts and PSHS use memory below S. Initialize a writable stack before making a standalone call.",false),
|
||
("PC","Program counter. Branches, jumps, calls and returns change the address of the next instruction.",false),
|
||
("DP","Direct-page register. Its byte supplies the upper address bits of a direct operand. LWASM SETDP describes your assumption during assembly.",false),
|
||
("E","Eight-bit accumulator and high byte of the HD6309 W register. CC.E is a separate flag.",true),
|
||
("F","Eight-bit accumulator and low byte of W. CC.F is the fast-interrupt mask.",true),
|
||
("W","Sixteen-bit accumulator combining E (high) and F (low). TFM uses W as a byte count.",true),
|
||
("Q","Thirty-two-bit accumulator. From most to least significant its bytes are A, B, E, F. D is the high word and W the low word.",true),
|
||
("V","Additional 16-bit HD6309 register used in register operations. CC.V is a separate overflow flag.",true),
|
||
("MD","Mode register. LDMD controls execution mode and FIRQ stacking. BITMD tests the latched illegal-instruction and division-by-zero status.",true)
|
||
] {
|
||
entries.append(.init(name, .registers, only6309: hd, operation: purpose, links: hd ? ["HD6309 modes"] : ["Condition codes"],
|
||
citations: [hd ? "Burke (1993), register file" : motorola]))
|
||
}
|
||
entries.append(.init("Condition codes", .registers, aliases: ["CC"], operation: "CC holds eight one-bit values. E marks an entire interrupt frame. F masks FIRQ, H is half carry, I masks IRQ. N is negative, Z zero, V signed overflow and C carry or borrow.",
|
||
detail: "Branch choices depend on how the previous instruction defined these bits. For example, Z=1 after CMP means equal; C=1 after CMP means unsigned lower. An undefined bit cannot support a portable decision.", links: ["BGE","BCC","CMPA"], citations: [motorola], terms: ["flags","carry","zero","loop"], example: "signed"))
|
||
for (name, meaning, links) in [
|
||
("CC.C","Carry or borrow. An unsigned addition sets C when the sum exceeds the register. A comparison sets C when the unsigned left operand is lower.",["BCS","ADCA"]),
|
||
("CC.V","Signed overflow. For example, adding one to $7F produces $80 in a byte and sets V.",["BVS","BGE"]),
|
||
("CC.Z","Zero. Many arithmetic and load instructions set Z when the result is zero. After a compare, BEQ uses Z to test equality.",["BEQ","BNE"]),
|
||
("CC.N","Negative. For operations that set N from the result, it copies the most significant bit. A signed comparison also needs V.",["BMI","BLT"]),
|
||
("CC.I","Interrupt request mask. Set I to mask IRQ. Clear I to permit IRQ when the external request is active.",["ANDCC","ORCC"]),
|
||
("CC.H","Half carry. An eight-bit addition places the carry from bit 3 here. DAA uses H to adjust a packed decimal result.",["DAA","ADDA"]),
|
||
("CC.F","Fast interrupt request mask. Set F to mask FIRQ. A saved CC value can restore the previous mask.",["ANDCC","RTI"]),
|
||
("CC.E","Entire state stacked. RTI checks E in the saved condition byte to choose between the short and full interrupt frames.",["RTI","SWI"])
|
||
] {
|
||
entries.append(.init(name, .registers, operation: meaning, links: links, citations: [motorola]))
|
||
}
|
||
entries.append(.init("HD6309 modes", .registers, only6309: true, operation: "The HD6309 starts in emulation mode. Many instructions take fewer cycles in native mode. LDMD #1 selects native mode with the ordinary short FIRQ frame. Mode selection is independent of the LWASM target.",
|
||
detail: "MD bit 0 selects native mode. Bit 1 selects full FIRQ stacking. A native full-state interrupt frame includes E and F; the mode on return must agree with the frame. Cycle counts also depend on indexed postbytes, branch outcomes and transfer lengths. In VCC Plus, Step completes a TFM instruction across its byte transfers.",
|
||
links: ["MD","LDMD","BITMD","TFM","RTI"], citations: ["Atkinson (2009), pp. 2, 120, 136, 144","Burke (1993), mode register","VCC Plus, Native Debugger, HD6309 Step"]))
|
||
for (name, operation, syntax, terms) in [
|
||
("Immediate","Use the following operand bytes as the value.", "LDA #$20", ["literal","#"]),
|
||
("Direct","Join DP with the 8-bit operand to make the memory address. With DP=$12, LDA <$34 reads $1234.","LDA <$34", ["direct page","<"]),
|
||
("Extended","Use the full 16-bit address in the instruction. LDA >$0400 reads a byte there.","LDA >$0400", [">","absolute"]),
|
||
("Indexed","Calculate an address from a register and an offset. LDA ,X+ reads at the original X then increments X by one. Use ,X++ for a two-byte advance. Indexed operands can also use A, B or D as signed offsets.","LDA ,X+ · LDD 2,S · LDA B,Y", [",X+",",X++","auto increment","offset"]),
|
||
("Indirect","Use square brackets to fetch a two-byte pointer at the intermediate address, then access the final address. Use a two-byte increment when walking a pointer table.","LDA [,X++] · JMP [$4000]", ["pointer","brackets"]),
|
||
("Relative","Add a signed displacement to PC after the operand. Branch targets are labels. Indexed PC-relative data references use PCR in LWASM.","BNE again · LDA table,PCR", ["relative","PCR","loop"]),
|
||
("Inherent","The opcode specifies the operation and its operands. INCA, for example, acts on A.","INCA", ["no operand"]),
|
||
("HD6309 indexed","E, F and W can supply offsets for X, Y, U or S. W also supports ,W, offset,W, ,W++ and ,--W, including their indirect forms.", "LDA E,X · LDA ,W++", ["W index",",W++"])
|
||
] {
|
||
entries.append(.init(name, .addressing, only6309: name.hasPrefix("HD"), syntax: syntax, operation: operation, detail: name == "Extended" ? "On the CoCo 3, the address in STA >$1A00 selects a byte through the CPU memory map. The MMU chooses the physical 8 KiB block and preserves the low 13 address bits. Use Mapped CPU in the debugger to inspect that store." : "", links: ["LDA"],
|
||
citations: (name == "Extended" ? ["Tepolt (1987), p. 20, fig. 3-4"] : []) + [name.hasPrefix("HD") ? "Atkinson (2009), p. 148" : addressing, dialect], terms: terms))
|
||
}
|
||
for (names, syntax, text) in [
|
||
("ORG","ORG address","Set the address of the following output. In DECB an origin determines where a data block loads."),
|
||
("FCB .BYTE .DB","FCB byte[,byte…]","Emit each expression as one byte. The listing shows data at the current location."),
|
||
("FDB .WORD .DW","FDB word[,word…]","Emit 16-bit words, high byte first."), ("FQB .4BYTE .QUAD","FQB value","Emit 32-bit quantities, high byte first."),
|
||
("FCC .ASCII .STR","FCC /text/","Emit character bytes between matching delimiters."),
|
||
("FCN FCZ .ASCIZ .STRZ","FCN /text/","Emit a string followed by a zero byte."),
|
||
("FCS .ASCIS .STRS","FCS /text/","Emit a string with the high bit set in its last character."),
|
||
("RMB .BLKB .DS .RS","RMB count","Advance the location counter by a number of bytes. Use ZMB when the load image must contain zeros."),
|
||
("RMD RMW","RMD count","Reserve 16-bit words."), ("RMQ","RMQ count","Reserve 32-bit values."),
|
||
("ZMB BSZ FZB","ZMB count","Emit the requested number of zero bytes."), ("ZMD","ZMD count","Emit zero-filled words."),
|
||
("ZMQ","ZMQ count","Emit zero-filled four-byte quantities."), ("EQU =","name EQU expression","Assign a fixed value to a symbol."),
|
||
("SET","name SET expression","Assign a symbol a value that later SET statements may change."),
|
||
("SETDP","SETDP page","Tell the assembler the assumed direct page. Guest software must establish the matching DP value."),
|
||
("END .END","END entry","Finish the assembly and specify the DECB execution address. END itself emits no machine instruction."),
|
||
("INCLUDE INCL LIB USE","INCLUDE filename","Read another source file at this location."),
|
||
("INCLUDEBIN","INCLUDEBIN filename","Copy bytes from a binary file into the assembly output."),
|
||
("ALIGN","ALIGN boundary","Advance to a boundary divisible by the supplied value."), ("FILL","FILL byte,count","Emit the given byte repeatedly."),
|
||
("SECTION SECT .AREA","SECTION name","Begin a section in an object module. The linker determines final placement."),
|
||
("ENDSECT ENDSECTION","ENDSECT","Finish the current object section."),
|
||
("EXTERN EXTERNAL IMPORT","name EXTERN","Declare a name defined in another object module."),
|
||
("EXPORT .GLOBL","EXPORT name","Expose a symbol to other object modules."),
|
||
("MACRO MACR","name MACRO","Begin defining a sequence of source lines for later expansion."), ("ENDM","ENDM","Finish a macro definition."),
|
||
("REORG","REORG","Restore the location associated with the previous ORG."),
|
||
("PHASE","PHASE expression","Give following code a different logical address for labels and expressions while retaining its output placement."),
|
||
("DEPHASE","DEPHASE","Resume the original address calculation after PHASE."),
|
||
("FDBS","FDBS word[,word…]","Emit 16-bit values low byte first, opposite to the processor’s normal word order."),
|
||
("INCLUDESTR","INCLUDESTR string","Treat the contents of the given string as additional assembler source."),
|
||
("EXTDEP","name EXTDEP","Mark an external symbol as a link dependency without emitting storage for it."),
|
||
("ERROR","ERROR message","Report an assembly error with the supplied text."),
|
||
("WARNING MSG","WARNING message","Report a warning with the supplied text."),
|
||
("IFEQ","IFEQ expression","Include the following block when the expression equals zero."),
|
||
("IFNE IF","IFNE expression","Include the block when the expression is nonzero."),
|
||
("IFLT","IFLT expression","Include the block when the expression is negative."),
|
||
("IFLE","IFLE expression","Include the block when the expression is zero or negative."),
|
||
("IFGT","IFGT expression","Include the block when the expression is positive."),
|
||
("IFGE","IFGE expression","Include the block when the expression is zero or positive."),
|
||
("IFDEF","IFDEF symbol","Test whether a symbol has already been defined."),
|
||
("IFNDEF","IFNDEF symbol","Test whether a symbol is still undefined."),
|
||
("IFPRAGMA IFOPT","IFPRAGMA option","Include a block according to the current pragma setting."),
|
||
("IFSTR","IFSTR comparison,arguments","Include a block according to the specified string comparison."),
|
||
("ELSE","ELSE","Select the alternate branch of a conditional assembly block."),
|
||
("ENDC ENDIF","ENDC","Close the current conditional assembly block."),
|
||
("IFP1","IFP1","Legacy pass-number conditional. LWASM warns that it cannot reproduce pass-one assembly semantics."),
|
||
("IFP2","IFP2","Legacy pass-number conditional. LWASM warns that it cannot reproduce pass-two assembly semantics."),
|
||
("STRUCT","name STRUCT","Begin a structure layout. Field labels describe offsets in its instances."),
|
||
("ENDS ENDSTRUCT","ENDS","Close a structure definition."),
|
||
("SETSTR","SETSTR name=string","Set an assembler string variable."),
|
||
("DTS","DTS","Emit a textual build timestamp. Its value changes with the host clock."),
|
||
("DTB","DTB","Emit six host-local date and time bytes."),
|
||
("*PRAGMAPUSH","*PRAGMAPUSH","Save pragma settings on the assembler’s pragma stack."),
|
||
("*PRAGMAPOP","*PRAGMAPOP","Restore saved pragma settings."),
|
||
("PRAGMA *PRAGMA **PRAGMA OPT","PRAGMA option","Change a LWASM dialect option. A target-changing pragma affects subsequent assembly.")
|
||
] {
|
||
let words = names.components(separatedBy: " ")
|
||
entries.append(.init(words[0], .directives, aliases: Array(words.dropFirst()), form: .directive, syntax: syntax, operation: text,
|
||
detail: "LWASM directive. Its effects take place during assembly.", links: ["END","ORG"].filter { $0 != words[0] },
|
||
citations: [dialect], example: ["ORG","FCB","END"].contains(words[0]) ? "call" : nil))
|
||
}
|
||
entries.append(.init("Assembler conveniences", .dialect, aliases: ["ASRQ","CLRQ","COMQ","LSLE","LSLF","LSLQ","LSRQ","NEGE","NEGF","NEGW","NEGQ","TSTQ"],
|
||
operation: "LWASM can expand convenience operations into several instructions when the corresponding pragma is active. The listing gives the actual expansion. A 6809 emulation of CLRD, for example, executes CLRA and CLRB separately.",
|
||
detail: "6809 expansions include ASLD, ASRD, CLRD, COMD, LSLD, LSRD, NEGD and TSTD. These names also identify real HD6309 operations. Additional 6309 convenience spellings include ASRQ, CLRQ, COMQ, LSLE, LSLF, LSLQ, LSRQ, NEGE, NEGF, NEGW, NEGQ and TSTQ. MC6800 compatibility is a separate optional dialect.",
|
||
links: ["CLRD","PRAGMA"], citations: [dialect]))
|
||
entries.append(.init("MC6800 compatibility", .dialect,
|
||
aliases: "ABA CBA CLC CLF CLI CLIF CLV CPX DES DEX DEY INS INX INY SBA SEC SEF SEI SEIF SEV TAB TAP TBA TPA TSX TXS WAI".components(separatedBy: " "),
|
||
operation: "These optional LWASM spellings expand to 6809 encodings with the 6800compat pragma. Expansion can require several instructions. Inspect the listing when stepping.", links: ["PRAGMA"], citations: [dialect]))
|
||
entries.append(.init("Compatibility directives", .dialect, aliases: ["NAM","PAG","PAGE","SPC","TTL",".BANK",".MODULE"],
|
||
operation: "LWASM accepts these listing and tool-compatibility directives without generating code.", links: ["FCB"], citations: [dialect]))
|
||
entries.append(.init("ASM-09 dialect", .dialect, aliases: ["IFC","IFNC","EXITM","EXIT"],
|
||
operation: "The ASM-09 compatibility dialect adds string equality and inequality conditionals and an early macro exit.", links: ["MACRO"], citations: [dialect]))
|
||
entries.append(.init("OS-9 output directives", .dialect, aliases: ["OS9","MOD","EMOD"],
|
||
operation: "OS9 encodes SWI2 followed by a service byte for OS-9 or object output. MOD and EMOD frame an OS-9 module. Assembly Development runs standalone Disk BASIC block images.", links: ["SWI2","END"], citations: [dialect]))
|
||
entries.append(.init("Undocumented and emulator opcodes", .dialect, aliases: ["HCF","RHF","RESET","HALT","BREAK","LOG"], operation: "LWASM lists HCF, RHF and RESET for certain 6809 encodings. Behavior outside the documented instruction set can differ by chip. BREAK and LOG are emulator extensions. VCC Plus’s Mac decoder also excludes the optional HALT/BREAK encodings.",
|
||
links: ["NOP"], citations: ["Atkinson (2009), p. 153",dialect,"VCC Plus, Native Debugger, disassembly"], terms: ["HCF","RHF","RESET","HALT","BREAK","LOG"]))
|
||
for lesson in AssemblyReferenceLesson.all {
|
||
entries.append(.init(lesson.name, .examples, only6309: lesson.hd, operation: lesson.predict,
|
||
detail: lesson.observation + "\n\n" + lesson.assumptions,
|
||
links: [lesson.id == "page" ? "Extended" : lesson.hd ? "W" : "LDA"], citations: (lesson.id == "page" ? ["Tepolt (1987), pp. 20 and 23, figs. 3-4 and 4-1"] : []) + [lesson.hd ? "Atkinson (2009), pp. 91, 136" : "Barden (1983), addressing and subroutines", lesson.id == "page" ? "VCC Plus, Debugger Memory Tools, hidden drawing page" : dialect],
|
||
example: lesson.id))
|
||
}
|
||
return entries
|
||
}
|
||
}
|