1 Commits
r3 .. r4
Author SHA1 Message Date
brad ArantandClaude Opus 5.5 fa4752fd7a Assembler in GNU as syntax, objdump-style disassembly, UCASE$ and LCASE$
The monitor's assembler takes GNU as directives (.org, .equ, .byte, .half,
.word, .ascii, .string, .space, .align, .balign ...), # comments, 0x/0b
numbers, '\n' constants, . for the current address, << >> ^ ~, %hi/%lo and
the FP CSR short forms; the old ORG/DB/EQU/0FFH forms remain as aliases. The
disassembler prints lower case and 0x hex as objdump does. The monitor is
built with -msave-restore and puts .rodata first, to fit its ROM.
BASIC gains UCASE$ and LCASE$. Manual, README and tests updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 18:14:19 -08:00
16 changed files with 7921 additions and 7615 deletions

No files matched your search

+5 -3
View File
@@ -17,7 +17,7 @@ RISC-V processor written from scratch in Verilog:
- **Software**: Dartmouth-style BASIC with graphics, sound and files, - **Software**: Dartmouth-style BASIC with graphics, sound and files,
`DO … LOOP`, block `IF … ELSE … END IF` and `SELECT CASE`, and scientific `DO … LOOP`, block `IF … ELSE … END IF` and `SELECT CASE`, and scientific
functions (inverse and hyperbolic trigonometry in radians or degrees, functions (inverse and hyperbolic trigonometry in radians or degrees,
`LOG10`, `ROUND`, `MOD`, `FACT` …); a `LOG10`, `ROUND`, `MOD`, `FACT` …), and `UCASE$`/`LCASE$`; a
machine-code monitor with a RISC-V disassembler and assembler, and five machine-code monitor with a RISC-V disassembler and assembler, and five
original games. original games.
@@ -164,7 +164,9 @@ All in C (plus a little assembly), compiled with GCC:
newlib's bring in its stdio and malloc. newlib's bring in its stdio and malloc.
- `monitor/` — the machine-code monitor: memory, registers (integer and - `monitor/` — the machine-code monitor: memory, registers (integer and
floating point), step, breakpoints, a RISC-V disassembler and a two-pass floating point), step, breakpoints, a RISC-V disassembler and a two-pass
assembler, Intel HEX in and out. assembler that both use GNU as syntax (`.org`, `.word`, `.string`,
`%hi`/`%lo`, `#` comments; the disassembly reads like `objdump`'s), Intel
HEX in and out.
- `games/` — The Iron Keep, Bastion Raid, Star Warden, Star Swarm and Crystal - `games/` — The Iron Keep, Bastion Raid, Star Warden, Star Swarm and Crystal
Cavern; they load at A200h (`CALL 41472`). Cavern; they load at A200h (`CALL 41472`).
@@ -199,7 +201,7 @@ the configuration flash.
| `scripts/fputest.sh` | `rtl/rv32_fpu.v` against `tools/f32.py`, an exact model of RISC-V's single precision (itself checked against the PC's FPU), on random vectors: every F instruction, every rounding mode, special values, subnormals and near-cancellations | | `scripts/fputest.sh` | `rtl/rv32_fpu.v` against `tools/f32.py`, an exact model of RISC-V's single precision (itself checked against the PC's FPU), on random vectors: every F instruction, every rounding mode, special values, subnormals and near-cancellations |
| `scripts/cputest.sh` | the official [riscv-tests](https://github.com/riscv-software-src/riscv-tests) (`rv32ui`, `rv32um`, `rv32uf`, `rv32mi`, fetched into `third_party/`) and `tests/` (interrupts, the NMI and single step) on `rv32_cpu.v` in xsim, with random wait states on the data bus. Two riscv-tests don't apply: `ma_data` expects misaligned loads and stores to work (here they trap, as the spec allows) and `pmpaddr` needs PMP. | | `scripts/cputest.sh` | the official [riscv-tests](https://github.com/riscv-software-src/riscv-tests) (`rv32ui`, `rv32um`, `rv32uf`, `rv32mi`, fetched into `third_party/`) and `tests/` (interrupts, the NMI and single step) on `rv32_cpu.v` in xsim, with random wait states on the data bus. Two riscv-tests don't apply: `ma_data` expects misaligned loads and stores to work (here they trap, as the spec allows) and `pmpaddr` needs PMP. |
| `scripts/sim.sh` | the whole design in xsim: the terminal, BASIC, both graphics modes, sprites, scrolling, flash files, the monitor (step, breakpoint, Pause, memory files, the assembler, Intel HEX), 3 Mbaud. `scripts/sim.sh quick` skips the terminal and the monitor; `wide` checks the 132 × 64 start-up. | | `scripts/sim.sh` | the whole design in xsim: the terminal, BASIC, both graphics modes, sprites, scrolling, flash files, the monitor (step, breakpoint, Pause, memory files, the assembler, Intel HEX), 3 Mbaud. `scripts/sim.sh quick` skips the terminal and the monitor; `wide` checks the 132 × 64 start-up. |
| `monitor/test-disasm.py`, `test-asm.py` | the disassembler against GNU objdump on thousands of random instructions, and the assembler against GNU as | | `monitor/test-disasm.py`, `test-asm.py` | the disassembler against GNU objdump on thousands of random instructions, and the assembler against GNU as, byte for byte, on a program in GNU syntax and one in the assembler's older spellings |
| `basic/test-*.py`, `games/*/test-*.py` | BASIC's line editor, RENUM, string arrays, block structures, graphics modes and maths functions (bit for bit against Python's `math`), and each game, on `tools/rv32emu.py` (a Python RV32IMF emulator of the machine; `tools/boardemu.py` models the game hardware). They need `pyte` and Pillow. | | `basic/test-*.py`, `games/*/test-*.py` | BASIC's line editor, RENUM, string arrays, block structures, graphics modes and maths functions (bit for bit against Python's `math`), and each game, on `tools/rv32emu.py` (a Python RV32IMF emulator of the machine; `tools/boardemu.py` models the game hardware). They need `pyte` and Pillow. |
| `bench/` | the processor alone with 64 KB of RAM, for timing | | `bench/` | the processor alone with 64 KB of RAM, for timing |
BIN
View File
Binary file not shown.
+11 -3
View File
@@ -198,7 +198,7 @@ enum {
T_DO, T_LOOP, T_WHILE, T_UNTIL, T_EXIT, T_ELSE, T_SELECT, T_CASE, T_DO, T_LOOP, T_WHILE, T_UNTIL, T_EXIT, T_ELSE, T_SELECT, T_CASE,
T_OPTION, T_PI, T_ANGLE, T_DEG, T_RAD, T_ASIN, T_ACOS, T_SEC, T_CSC, T_COT, T_OPTION, T_PI, T_ANGLE, T_DEG, T_RAD, T_ASIN, T_ACOS, T_SEC, T_CSC, T_COT,
T_SINH, T_COSH, T_TANH, T_ASINH, T_ACOSH, T_ATANH, T_LOG10, T_LOG2, T_CEIL, T_SINH, T_COSH, T_TANH, T_ASINH, T_ACOSH, T_ATANH, T_LOG10, T_LOG2, T_CEIL,
T_IP, T_FP, T_ROUND, T_TRUNCATE, T_MOD, T_MIN, T_MAX, T_FACT, T_LAST T_IP, T_FP, T_ROUND, T_TRUNCATE, T_MOD, T_MIN, T_MAX, T_FACT, T_UCASES, T_LCASES, T_LAST
}; };
_Static_assert(T_LAST <= 0x100, "too many keywords for a byte"); _Static_assert(T_LAST <= 0x100, "too many keywords for a byte");
@@ -213,7 +213,7 @@ static const char *const kw[] = {
"DO", "LOOP", "WHILE", "UNTIL", "EXIT", "ELSE", "SELECT", "CASE", "DO", "LOOP", "WHILE", "UNTIL", "EXIT", "ELSE", "SELECT", "CASE",
"OPTION", "PI", "ANGLE", "DEG", "RAD", "ASIN", "ACOS", "SEC", "CSC", "COT", "OPTION", "PI", "ANGLE", "DEG", "RAD", "ASIN", "ACOS", "SEC", "CSC", "COT",
"SINH", "COSH", "TANH", "ASINH", "ACOSH", "ATANH", "LOG10", "LOG2", "CEIL", "SINH", "COSH", "TANH", "ASINH", "ACOSH", "ATANH", "LOG10", "LOG2", "CEIL",
"IP", "FP", "ROUND", "TRUNCATE", "MOD", "MIN", "MAX", "FACT" "IP", "FP", "ROUND", "TRUNCATE", "MOD", "MIN", "MAX", "FACT", "UCASE$", "LCASE$"
}; };
/* ----------------------------------------------------------------- memory */ /* ----------------------------------------------------------------- memory */
@@ -684,7 +684,7 @@ static u8 is_str_start(void)
{ {
u8 c = peekc(); u8 c = peekc();
if (c == '"' || c == T_CHRS || c == T_STRS || c == T_LEFTS || c == T_RIGHTS || c == T_MIDS || if (c == '"' || c == T_CHRS || c == T_STRS || c == T_LEFTS || c == T_RIGHTS || c == T_MIDS ||
c == T_DATES) c == T_DATES || c == T_UCASES || c == T_LCASES)
return 1; return 1;
return is_alpha(c) && tp[1] == '$'; return is_alpha(c) && tp[1] == '$';
} }
@@ -1107,6 +1107,14 @@ static void str_prim(char *out)
out[0] = to_int(expr()); out[0] = to_int(expr());
out[1] = 0; out[1] = 0;
break; break;
case T_UCASES: /* only A-Z and a-z change */
case T_LCASES: {
char *p;
sexpr(out);
for (p = out; *p; p++)
if (c == T_UCASES ? *p >= 'a' && *p <= 'z' : *p >= 'A' && *p <= 'Z') *p ^= 32;
break;
}
case T_STRS: { case T_STRS: {
float v = expr(); float v = expr();
out[0] = ' '; out[0] = ' ';
+1158 -1158
View File
File diff suppressed because it is too large. Load diff
+18 -1
View File
@@ -18,9 +18,11 @@ def main():
b = te.Basic() b = te.Basic()
errors = 0 errors = 0
def check(what, ok): def check(what, ok, out=""):
nonlocal errors nonlocal errors
print(("PASS " if ok else "FAIL ") + what) print(("PASS " if ok else "FAIL ") + what)
if not ok and out:
print(out)
errors += not ok errors += not ok
def run(prog): def run(prog):
@@ -64,6 +66,21 @@ def main():
b.type(b"A, B" + CR) b.type(b"A, B" + CR)
check("LINE INPUT into an element", "<A, B>" in "\n".join(l.rstrip() for l in b.screen_text().display)) check("LINE INPUT into an element", "<A, B>" in "\n".join(l.rstrip() for l in b.screen_text().display))
out = run('''
10 A$ = "Hello, World! 123"
20 PRINT UCASE$(A$); "|"; LCASE$(A$); "|"; LCASE$(UCASE$("mIxEd"))
30 B$ = CHR$(64) + CHR$(91) + CHR$(96) + CHR$(123) + CHR$(224)
40 PRINT (UCASE$(B$) = B$); (LCASE$(B$) = B$); LEN(UCASE$("")); ASC(LCASE$("Z"))
50 DIM N$(1): N$(1) = "abc": PRINT UCASE$(N$(1) + "d")
''')
check("UCASE$ and LCASE$", "HELLO, WORLD! 123|hello, world! 123|mixed" in out, out)
check("only A-Z and a-z change", "-1 -1 0 122" in out, out)
check("UCASE$ of an expression", "ABCD" in out, out)
b.type(b"LIST 20" + CR)
check("LIST spells UCASE$ and LCASE$",
'20 PRINT UCASE$(A$); "|"; LCASE$(A$); "|"; LCASE$(UCASE$("mIxEd"))' in
"\n".join(l.rstrip() for l in b.screen_text().display))
out = run('10 DIM Q$(2): Q$(3) = "X"') out = run('10 DIM Q$(2): Q$(3) = "X"')
check("subscript out of range", "SUBSCRIPT" in out.upper()) check("subscript out of range", "SUBSCRIPT" in out.upper())
out = run('10 DIM Z$(300)') out = run('10 DIM Z$(300)')
+105 -67
View File
@@ -550,6 +550,20 @@ ACOS(-1) = 180 20! = 2.4329E+18
| `LEFT$(A$, N)` | First *N* characters | | `LEFT$(A$, N)` | First *N* characters |
| `RIGHT$(A$, N)` | Last *N* characters | | `RIGHT$(A$, N)` | Last *N* characters |
| `MID$(A$, S [, N])` | *N* characters (or the rest) starting at position *S* (from 1) | | `MID$(A$, S [, N])` | *N* characters (or the rest) starting at position *S* (from 1) |
| `UCASE$(A$)` | The string in capitals: only `a`–`z` change |
| `LCASE$(A$)` | The string in small letters: only `A`–`Z` change |
BASIC turns what you type into capitals outside quotes, but text that comes
from `INPUT`, a file or `CHR$` keeps its case. `UCASE$` is the way to compare
an answer whatever case it was typed in, `IF UCASE$(A$) = "YES" THEN …`, and
the two together tidy a name:
```
10 INPUT "YOUR NAME"; N$
20 PRINT "HELLO, "; UCASE$(LEFT$(N$, 1)); LCASE$(MID$(N$, 2))
```
typed `aDA LOVELACE`, prints `HELLO, Ada lovelace`.
### Machine and screen ### Machine and screen
@@ -992,9 +1006,9 @@ graphics come back exactly as they were.
T1 00000000 T2 00000000 S0 00013FB0 S1 0000A01E A0 00000000 A1 00012000 T1 00000000 T2 00000000 S0 00013FB0 S1 0000A01E A0 00000000 A1 00012000
... ...
ADDR WORD INSTRUCTION STACK ADDR WORD INSTRUCTION STACK
>*12000 04100513 LI A0,65 13F70 00000000 >*12000 04100513 li a0,65 13F70 00000000
12004 F0A000A3 SB A0,-255(ZERO) 13F74 0000A01E 12004 F0A000A3 sb a0,-255(zero) 13F74 0000A01E
12008 00008067 RET ... 12008 00008067 ret ...
MEMORY MEMORY
12000 13 05 10 04 A3 00 A0 F0-67 80 00 00 00 00 00 00 ....g........... 12000 13 05 10 04 A3 00 A0 F0-67 80 00 00 00 00 00 00 ....g...........
``` ```
@@ -1007,7 +1021,8 @@ graphics come back exactly as they were.
### Commands ### Commands
Type a command on the bottom line and press Enter. Numbers are in hex. Type a command on the bottom line and press Enter. Numbers are in hex, with
or without `0x`.
| Command | Does | | Command | Does |
|---|---| |---|---|
@@ -1024,7 +1039,7 @@ Type a command on the bottom line and press Enter. Numbers are in hex.
| `F` | Show the float registers F0–F31 and FCSR, as bit patterns, in the memory window (`M` brings the memory back) | | `F` | Show the float registers F0–F31 and FCSR, as bit patterns, in the memory window (`M` brings the memory back) |
| `SAVE "NAME" start end` | Save memory *start* to *end* (inclusive) to a file in flash | | `SAVE "NAME" start end` | Save memory *start* to *end* (inclusive) to a file in flash |
| `LOAD "NAME"` | Load a memory file back to where it was saved from | | `LOAD "NAME"` | Load a memory file back to where it was saved from |
| `LOAD "NAME" addr` | Load it at *addr* instead (0A000h or above) | | `LOAD "NAME" addr` | Load it at *addr* instead (A000 or above) |
| `DIR` | List the files in flash in the memory window (`M` brings the memory back) | | `DIR` | List the files in flash in the memory window (`M` brings the memory back) |
| `ASM "NAME"` | Assemble a source file into memory (see the assembler, below) | | `ASM "NAME"` | Assemble a source file into memory (see the assembler, below) |
| `A addr` | Assemble lines as you type them, from *addr*; an empty line ends | | `A addr` | Assemble lines as you type them, from *addr*; an empty line ends |
@@ -1043,9 +1058,11 @@ Type a command on the bottom line and press Enter. Numbers are in hex.
- **The float registers** are saved and put back like the others, while the - **The float registers** are saved and put back like the others, while the
FPU is on (`mstatus.FS`, which BASIC turns on); `F` says when it is off. FPU is on (`mstatus.FS`, which BASIC turns on); `F` says when it is off.
- **The disassembler** shows every RV32IMF instruction and the CSR and system - **The disassembler** shows every RV32IMF instruction and the CSR and system
instructions, using the usual short forms where they apply (`LI`, `MV`, `J`, instructions the way GNU `objdump` does: in lower case, with the usual
`RET`, `BEQZ`, `CSRR` and so on), with hex numbers like `1F0H` and `0A200H`; short forms where they apply (`li`, `mv`, `j`, `ret`, `beqz`, `csrr` and so
anything else is shown as `DW` and its value. on), hex numbers like `0x1f0`, and the float registers by their ABI names
(`fa0`, `ft1`). Anything else is shown as `.word` and its value. What it
shows, the assembler reads back.
### A machine-code example ### A machine-code example
@@ -1056,8 +1073,8 @@ RUN
MONITOR MONITOR
``` ```
The `POKE`s put `LI A0,65 : SB A0,-255(ZERO) : RET` at 12000h; it prints an The `POKE`s put `li a0,65`, `sb a0,-255(zero)` and `ret` at 0x12000; it
`A` (port 1 is at -255 from address 0). In the monitor, `B 12000` then `X`. prints an `A` (port 1 is at -255 from address 0). In the monitor, `B 12000` then `X`.
Back in BASIC, `CALL 73728` stops at the breakpoint. Press Enter to step Back in BASIC, `CALL 73728` stops at the breakpoint. Press Enter to step
through each instruction, or `X` to let it finish. through each instruction, or `X` to let it finish.
@@ -1066,89 +1083,110 @@ through each instruction, or `X` to let it finish.
The monitor can assemble RISC-V source code into memory, either a whole file The monitor can assemble RISC-V source code into memory, either a whole file
or one line at a time. or one line at a time.
**Writing source.** Type it into BASIC as numbered lines, just like a **Writing source.** The assembler reads the GNU assembler's RISC-V syntax,
program, and save it. BASIC doesn't run it; it just keeps the lines. The as in the RISC-V manuals and `gcc -S` output. Type the source into BASIC as
assembler ignores the line numbers, and uses them in its error messages. numbered lines, just like a program, and save it. BASIC doesn't run it; it
just keeps the lines. The assembler ignores the line numbers, and uses them
in its error messages.
``` ```
NEW NEW
10 ; PRINT A MESSAGE 10 # print a message
20 ORG 12000H 20 .org 0x12000
30 START: LA A1,MSG 30 start: la a1, msg
40 LOOP: LBU A0,0(A1) 40 loop: lbu a0, 0(a1)
50 BEQZ A0,DONE 50 beqz a0, done
60 WAIT: LBU T0,-256(ZERO) ; CAN THE SCREEN TAKE A CHARACTER? 60 wait: lbu t0, -256(zero) # can the screen take a character?
70 ANDI T0,T0,2 70 andi t0, t0, 2
80 BEQZ T0,WAIT 80 beqz t0, wait
90 SB A0,-255(ZERO) 90 sb a0, -255(zero)
100 ADDI A1,A1,1 100 addi a1, a1, 1
110 J LOOP 110 j loop
120 DONE: RET 120 done: ret
130 MSG: DB "HELLO FROM ASSEMBLY",13,10,0 130 msg: .string "Hello from assembly\r\n"
SAVE "HELLO" SAVE "HELLO"
``` ```
A text file sent from the PC with `tools/send-bas.py` works the same way, as A text file sent from the PC with `tools/send-bas.py` works the same way, as
long as each line starts with a number. long as each line starts with a number.
BASIC stores what you type in capitals, except inside double quotes, so
`LIST` shows `30 START: LA A1, MSG`. The assembler doesn't mind either way,
but a character constant changes: `'a'` becomes `'A'`. BASIC also drops the
spaces after the line number, so a label needs its colon. And BASIC knows
nothing of `\"`, so a string can't contain a double quote; use `.byte 34`.
**Assembling.** `MONITOR`, then `ASM "HELLO"`. The monitor says **Assembling.** `MONITOR`, then `ASM "HELLO"`. The monitor says
`ASSEMBLED 12000-12041` and shows the code; errors are listed in the memory `ASSEMBLED 12000-12041` and shows the code; errors are listed in the memory
window with their line numbers. Back in BASIC (`X`), `CALL 73728` runs it. window with their line numbers. Back in BASIC (`X`), `CALL 73728` runs it.
Or set a breakpoint first and step through it. Or set a breakpoint first and step through it.
**One line at a time.** `A 12100` starts the line assembler at 12100h: type **One line at a time.** `A 12100` starts the line assembler at 0x12100: type
an instruction, press Enter, and it is assembled and shown, then the next an instruction, press Enter, and it is assembled and shown, then the next
address is offered. An empty line ends. Labels from the last `ASM` can be used. address is offered. An empty line ends. Labels from the last `ASM` can be used.
**Syntax**: as the disassembler shows it. **Syntax**: GNU as's, which is also what the disassembler shows.
| | | | | |
|---|---| |---|---|
| Labels | `NAME:` before an instruction, up to 8 letters and digits; `NAME EQU value` for constants | | Labels | `name:` before an instruction, or on a line of its own; letters, digits, `_` and `.`, of which the first 8 count |
| Numbers | `123`, `0FFH`, `$FF`, `0x1F`, `1010B`, `'A'`; `$` alone is the current address | | Constants | `.equ name, value`, `.set name, value` or `name = value` |
| Expressions | `+ - * / & |` and brackets: `LI A0,END-START`, `LI A1,'Z'-1` | | Numbers | `123`, `0x1f`, `0b1010`, `'A'`, `'\n'`; `.` is the current address |
| Registers | `X0`–`X31` or `ZERO RA SP GP TP T0`–`T6 S0`–`S11 FP A0`–`A7` | | Expressions | <code>+ - * / &amp; &#124; ^ &lt;&lt; &gt;&gt; ~</code> and brackets: `li a0, end - start`, `li a1, 'Z' - 1`; `%hi(x)` and `%lo(x)` split an address for `lui` and `addi`, or a load or store: `lui a5, %hi(table)` then `lw a0, %lo(table)(a5)` |
| Memory operands | *offset*`(`*register*`)`: `LW A0,8(SP)`, `SB A0,-255(ZERO)`, `LBU T0,(A1)` | | Registers | `x0`–`x31` or `zero ra sp gp tp t0`–`t6 s0`–`s11 fp a0`–`a7` |
| CSRs | by name (`MSTATUS`, `MEPC`, `MCAUSE`, `CYCLE`, `TIME`, `INSTRET`, …) or number | | Memory operands | *offset*`(`*register*`)`: `lw a0, 8(sp)`, `sb a0, -255(zero)`, `lbu t0, (a1)` |
| `ORG addr` | assemble from *addr* (12000h if there is no `ORG`) | | CSRs | by name (`mstatus`, `mepc`, `mcause`, `cycle`, `time`, `instret`, …) or number |
| `DB` / `DEFB` / `DEFM` | bytes and `"strings"`: `DB "HI",13,10,0` | | `.org addr` | assemble from *addr* (0x12000 if there is no `.org`) |
| `DH` | 16-bit halfwords, low byte first | | `.byte` | bytes: `.byte 13, 10, 'A'` |
| `DW` / `DEFW` | 32-bit words, low byte first | | `.half` / `.short` | 16-bit halfwords, low byte first |
| `DS n` / `DEFS n` | skip *n* bytes | | `.word` / `.long` | 32-bit words, low byte first: `.word start, 0x12345678` |
| `ALIGN n` | skip to a multiple of *n* (instructions must be on a multiple of 4) | | `.ascii "text"` | the characters of the text; `\n`, `\r`, `\t`, `\0`, `\\` and `\"` stand for a line feed, return, tab, 0, `\` and `"` |
| `END` | stop here | | `.string "text"` / `.asciz "text"` | the same with a 0 after it |
| `;` | comment to the end of the line | | `.space n` / `.skip n` / `.zero n` | *n* bytes of 0, or of *fill* with `.space n, fill` |
| `.align n` / `.p2align n` | to a multiple of 2*ⁿ*: `.align 2` for a word. The gap is filled with zeros up to a word, then `nop`s, so code can run through it; `.align n, fill` fills it with *fill* |
| `.balign n` | to a multiple of *n* bytes |
| `.end` | stop here |
| `.text`, `.data`, `.section`, `.globl`, `.global`, `.option`, `.type` | accepted and ignored, so code written for GNU as needn't be changed |
| `#` or `;` | comment to the end of the line |
- **Instructions:** all of RV32I and M, `CSRRW`…`CSRRCI`, `ECALL`, `EBREAK`, The assembler of earlier versions used other spellings, and sources written
`MRET`, `MNRET`, `WFI`, `FENCE`, `FENCE.I`, and the short forms `NOP`, `LI`, for it still assemble: `ORG`, `NAME EQU value`, `DB`/`DEFB`/`DEFM` (with
`LA`, `MV`, `NOT`, `NEG`, `SEQZ`, `SNEZ`, `SLTZ`, `SGTZ`, `J`, `JR`, `JAL` strings taken as they are, no escapes), `DH`, `DW`/`DEFW`, `DS n`/`DEFS n`
*target* (saving RA), `JALR` *register*, `RET`, `CALL`, `BEQZ`, `BNEZ`, (skip *n* bytes), `ALIGN n` (to a multiple of *n*), `END`, numbers like
`BLEZ`, `BGEZ`, `BLTZ`, `BGTZ`, `BGT`, `BLE`, `BGTU`, `BLEU`, `CSRR`, `CSRW`, `0FFH`, `$FF` and `1010B`, and `$` for the current address.
`CSRS`, `CSRC`, `CSRWI`, `CSRSI`, `CSRCI`.
- **Floating point:** `FLW`, `FSW`, `FADD.S`, `FSUB.S`, `FMUL.S`, `FDIV.S`, - **Instructions:** all of RV32I and M, `csrrw`…`csrrci`, `ecall`, `ebreak`,
`FSQRT.S`, `FMADD.S`, `FMSUB.S`, `FNMSUB.S`, `FNMADD.S`, `FMIN.S`, `FMAX.S`, `mret`, `mnret`, `wfi`, `fence`, `fence.i`, and the short forms `nop`, `li`,
`FSGNJ.S`, `FSGNJN.S`, `FSGNJX.S` (and `FMV.S`, `FNEG.S`, `FABS.S`), `FEQ.S`, `la`, `mv`, `not`, `neg`, `seqz`, `snez`, `sltz`, `sgtz`, `j`, `jr`, `jal`
`FLT.S`, `FLE.S`, `FCVT.W.S`, `FCVT.WU.S`, `FCVT.S.W`, `FCVT.S.WU`, `FMV.X.W`, *target* (saving `ra`), `jalr` *register*, `ret`, `call`, `beqz`, `bnez`,
`FMV.W.X`, `FCLASS.S`. Float registers are `F0`–`F31` or `FT0`–`FT11`, `blez`, `bgez`, `bltz`, `bgtz`, `bgt`, `ble`, `bgtu`, `bleu`, `csrr`,
`FS0`–`FS11`, `FA0`–`FA7`; a rounding mode (`RNE`, `RTZ`, `RDN`, `RUP`, `RMM`) `csrw`, `csrs`, `csrc`, `csrwi`, `csrsi`, `csrci`.
may follow the operands, `FADD.S FA0,FA1,FA2,RTZ`, and without one the - **Floating point:** `flw`, `fsw`, `fadd.s`, `fsub.s`, `fmul.s`, `fdiv.s`,
instruction uses FCSR's (round to nearest unless changed). CSRs `FFLAGS`, `fsqrt.s`, `fmadd.s`, `fmsub.s`, `fnmsub.s`, `fnmadd.s`, `fmin.s`, `fmax.s`,
`FRM` and `FCSR`. `fsgnj.s`, `fsgnjn.s`, `fsgnjx.s` (and `fmv.s`, `fneg.s`, `fabs.s`),
- **`LI`** is one instruction (`ADDI`) for a value from −2048 to 2047 that is `feq.s`, `flt.s`, `fle.s`, `fcvt.w.s`, `fcvt.wu.s`, `fcvt.s.w`, `fcvt.s.wu`,
known by then, otherwise two (`LUI`, `ADDI`); **`LA`** is always two `fmv.x.w`, `fmv.w.x`, `fclass.s`. Float registers are `f0`–`f31` or
(`AUIPC`, `ADDI`); **`CALL`** is `JAL RA`, which reaches 1 MB either way. `ft0`–`ft11`, `fs0`–`fs11`, `fa0`–`fa7`; a rounding mode (`rne`, `rtz`,
- **Where code can go:** RAM from 0A000h up. 12000h–12FFFh is the safe place, `rdn`, `rup`, `rmm`) may follow the operands, `fadd.s fa0, fa1, fa2, rtz`,
since BASIC doesn't use it. and without one the instruction uses FCSR's (round to nearest unless
changed). CSRs `fflags`, `frm` and `fcsr`, and the short forms `frcsr`,
`fscsr`, `frrm`, `fsrm`, `frflags`, `fsflags`.
- **`li`** is one instruction (`addi`) for a value from −2048 to 2047 that is
known by then, `lui` alone for one whose low 12 bits are 0, otherwise two
(`lui`, `addi`); **`la`** is always two (`auipc`, `addi`). **`call`** is
`jal ra`, which reaches 1 MB either way (GNU as makes it `auipc` and
`jalr`, 8 bytes, to reach anywhere).
- **Where code can go:** RAM from 0xA000 up. 0x12000–0x12FFF is the safe
place, since BASIC doesn't use it.
- **Labels:** up to 200. - **Labels:** up to 200.
- **Typing source into BASIC:** BASIC turns lower case to upper case (except
inside double quotes), so `'a'` becomes `'A'`. Indentation after the line
number isn't kept, so labels need their colon.
**Errors:** `UNKNOWN INSTRUCTION`, `BAD REGISTER`, `MISSING OPERAND`, `TOO **Errors:** `UNKNOWN INSTRUCTION`, `BAD REGISTER`, `MISSING OPERAND`, `TOO
MANY OPERANDS`, `OFFSET(REGISTER)`, `UNDEFINED LABEL`, `DUPLICATE LABEL`, MANY OPERANDS`, `OFFSET(REGISTER)`, `UNDEFINED LABEL`, `DUPLICATE LABEL`,
`VALUE OUT OF RANGE` (an immediate, offset or `LUI` value that doesn't fit), `VALUE OUT OF RANGE` (an immediate, offset or `lui` value that doesn't fit),
`BRANCH TOO FAR` (beyond ±4 KB), `JUMP TOO FAR` (beyond ±1 MB), `NOT ON A `BRANCH TOO FAR` (beyond ±4 KB), `JUMP TOO FAR` (beyond ±1 MB), `NOT ON A
WORD: USE ALIGN 4`, `CAN'T WRITE THERE`, `BAD NUMBER`, `BAD EXPRESSION`. WORD: USE .ALIGN 2`, `CAN'T WRITE THERE`, `BAD NUMBER`, `BAD EXPRESSION`,
`BAD STRING` (`.ascii` or `.string` without a string), `ALIGN TO A POWER OF
2`, `EQU NEEDS A NAME`.
### How it works ### How it works
Binary file not shown.
+167 -55
View File
@@ -1,26 +1,37 @@
/* RISC-V assembler for the monitor (included by monitor.c). /* RISC-V assembler for the monitor (included by monitor.c).
* *
* The syntax the disassembler prints. A line is * GNU as syntax, as the disassembler prints it. A line is
* [line number] [label:] [instruction or directive] [; comment] * [line number] [label:] [instruction or directive] [# comment]
* (the line number is there when the source was typed into BASIC). Numbers: * (the line number is there when the source was typed into BASIC; ; also
* 123, 0FFH, $FF, 0x1F, 1010B, 'A'; $ alone is the current address. * starts a comment). Case doesn't matter: lines are upper-cased outside
* Expressions use + - * / & | and parentheses. Registers are X0-X31 or their * quotes before they are read. Numbers: 123, 0x1F, 0b1010, 'A', '\n'; . is
* ABI names (ZERO RA SP GP TP T0-T6 S0-S11 FP A0-A7); memory operands are * the current address. Expressions use + - * / & | ^ << >> ~ and parentheses,
* offset(register). CSRs by name (MSTATUS, MEPC, CYCLE...) or number. * and %hi(x) and %lo(x), the LUI/AUIPC and ADDI parts of x. Registers are
* x0-x31 or their ABI names (zero ra sp gp tp t0-t6 s0-s11 fp a0-a7); memory
* operands are offset(register). CSRs by name (mstatus, mepc, cycle...) or
* number.
* *
* Instructions: RV32I and M, CSRRW..CSRRCI, ECALL EBREAK MRET MNRET WFI FENCE * Instructions: RV32I and M, csrrw..csrrci, ecall ebreak mret mnret wfi fence
* FENCE.I, and the usual short forms: NOP LI LA MV NOT NEG SEQZ SNEZ SLTZ SGTZ * fence.i, and the usual short forms: nop li la mv not neg seqz snez sltz sgtz
* J JR JAL target RET CALL BEQZ BNEZ BLEZ BGEZ BLTZ BGTZ BGT BLE BGTU BLEU CSRR * j jr jal target ret call beqz bnez blez bgez bltz bgtz bgt ble bgtu bleu
* CSRW CSRS CSRC CSRWI CSRSI CSRCI. * csrr csrw csrs csrc csrwi csrsi csrci.
* F: FLW FSW FMADD.S FMSUB.S FNMSUB.S FNMADD.S FADD.S FSUB.S FMUL.S FDIV.S * F: flw fsw fmadd.s fmsub.s fnmsub.s fnmadd.s fadd.s fsub.s fmul.s fdiv.s
* FSQRT.S FSGNJ.S FSGNJN.S FSGNJX.S FMIN.S FMAX.S FEQ.S FLT.S FLE.S FCVT.W.S * fsqrt.s fsgnj.s fsgnjn.s fsgnjx.s fmin.s fmax.s feq.s flt.s fle.s fcvt.w.s
* FCVT.WU.S FCVT.S.W FCVT.S.WU FMV.X.W FMV.W.X FCLASS.S and FMV.S FNEG.S * fcvt.wu.s fcvt.s.w fcvt.s.wu fmv.x.w fmv.w.x fclass.s and fmv.s fneg.s
* FABS.S; float registers F0-F31 or FT0-FT11 FS0-FS11 FA0-FA7; a rounding * fabs.s; float registers f0-f31 or ft0-ft11 fs0-fs11 fa0-fa7; a rounding
* mode (RNE RTZ RDN RUP RMM DYN) may follow the operands, DYN if not. LI is one instruction for a constant of * mode (rne rtz rdn rup rmm dyn) may follow the operands, dyn if not. li is
* -2048..2047 known by then, else LUI and ADDI; LA is AUIPC and ADDI. * one instruction for a constant of -2048..2047 known by then, else lui and
* Directives: ORG, EQU (NAME EQU value), DB/DEFB/DEFM (numbers and "strings"), * addi; la is auipc and addi.
* DH (16 bits), DW/DEFW (32 bits), DS/DEFS n, ALIGN n, END. Instructions must * Directives: .org, .equ/.set name, value (or name = value), .byte, .half
* be on a 4-byte boundary. Labels are up to 8 characters. * (.short .2byte), .word (.long .4byte), .ascii, .string/.asciz (a 0 after
* each string; \n \r \t \0 \\ \" escapes), .space/.skip/.zero n, .align n
* and .p2align n (to 2^n), .balign n (to n), .end; .text .data .section .globl
* .global .option and .type are accepted and ignored. Instructions must be on
* a 4-byte boundary. Labels are up to 8 characters (more are allowed; the
* first 8 count).
* The older forms still work: ORG, NAME EQU value, DB/DEFB/DEFM (no escapes),
* DH, DW/DEFW, DS/DEFS n, ALIGN n (to n), END; numbers 0FFH, $FF, 1010B; $
* for the current address.
*/ */
#define MAXSYM 200 #define MAXSYM 200
struct sym { char name[8]; u32 val; u16 line; }; struct sym { char name[8]; u32 val; u16 line; };
@@ -42,6 +53,28 @@ static void a_sp(void) { while (*ap == ' ' || *ap == '\t') ap++; }
static u8 a_alpha(char c) { return (c >= 'A' && c <= 'Z') || c == '_' || c == '.'; } static u8 a_alpha(char c) { return (c >= 'A' && c <= 'Z') || c == '_' || c == '.'; }
static u8 a_alnum(char c) { return a_alpha(c) || (c >= '0' && c <= '9'); } static u8 a_alnum(char c) { return a_alpha(c) || (c >= '0' && c <= '9'); }
/* the length of the character constant at p ('A' or '\N'), 0 if none */
static u8 a_chlen(const char *p)
{
if (p[0] != '\'') return 0;
if (p[1] == '\\' && p[2] && p[3] == '\'') return 4;
if (p[1] && p[2] == '\'') return 3;
return 0;
}
/* the character an escape stands for: \N \R \T \0 \E, else itself */
static u8 a_esc(char c)
{
switch (c) {
case 'n': case 'N': return 10;
case 'r': case 'R': return 13;
case 't': case 'T': return 9;
case '0': return 0;
case 'e': case 'E': return 27;
}
return c;
}
static void a_emit(u8 b) static void a_emit(u8 b)
{ {
if (a_pass == 2) { if (a_pass == 2) {
@@ -85,15 +118,19 @@ static void a_name(char *n)
/* ---------------------------------------------------------- expressions */ /* ---------------------------------------------------------- expressions */
static u32 a_expr(void); static u32 a_expr(void);
/* the LUI/AUIPC part and the ADDI part of a 32-bit value */
static u32 hi20(u32 v) { return (v + 0x800) >> 12 & 0xFFFFF; }
static i32 lo12(u32 v) { return sx(v, 12); }
static u32 a_number(void) static u32 a_number(void)
{ {
const char *s = ap; const char *s = ap;
u32 v = 0; u32 v = 0;
u8 base = 10, n = 0; u8 base = 10, n = 0;
while (a_alnum(s[n])) n++;
if (s[0] == '0' && s[1] == 'X') { base = 16; s += 2; } if (s[0] == '0' && s[1] == 'X') { base = 16; s += 2; }
else if (s[0] == '0' && s[1] == 'B' && s[n - 1] != 'H') { base = 2; s += 2; }
else { else {
while (a_alnum(s[n])) n++;
if (s[n - 1] == 'H') base = 16; if (s[n - 1] == 'H') base = 16;
else if (s[n - 1] == 'B') { else if (s[n - 1] == 'B') {
u8 k; u8 k;
@@ -104,7 +141,7 @@ static u32 a_number(void)
for (; a_alnum(*s); s++) { for (; a_alnum(*s); s++) {
char c = *s; char c = *s;
u8 d = c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : 99; u8 d = c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : 99;
if ((c == 'H' && base == 16) || (c == 'B' && base == 2 && !a_alnum(s[1]))) { s++; break; } if ((c == 'H' && base == 16 && !a_alnum(s[1])) || (c == 'B' && base == 2 && !a_alnum(s[1]))) { s++; break; }
if (d >= base) { a_fail("BAD NUMBER"); break; } if (d >= base) { a_fail("BAD NUMBER"); break; }
v = v * base + d; v = v * base + d;
} }
@@ -118,6 +155,15 @@ static u32 a_factor(void)
a_sp(); a_sp();
if (*ap == '-') { ap++; return -a_factor(); } if (*ap == '-') { ap++; return -a_factor(); }
if (*ap == '+') { ap++; return a_factor(); } if (*ap == '+') { ap++; return a_factor(); }
if (*ap == '~') { ap++; return ~a_factor(); }
if (*ap == '%') { /* %HI(x), %LO(x) */
u8 hi = !strncmp(ap + 1, "HI(", 3);
if (!hi && strncmp(ap + 1, "LO(", 3)) { a_fail("BAD EXPRESSION"); return 0; }
ap += 3;
v = a_factor();
return hi ? hi20(v) : (u32)lo12(v);
}
if (*ap == '.' && !a_alnum(ap[1])) { ap++; return a_pc; }
if (*ap == '(') { if (*ap == '(') {
ap++; ap++;
v = a_expr(); v = a_expr();
@@ -125,7 +171,8 @@ static u32 a_factor(void)
if (*ap == ')') ap++; else a_fail("MISSING )"); if (*ap == ')') ap++; else a_fail("MISSING )");
return v; return v;
} }
if (*ap == '\'' && ap[1] && ap[2] == '\'') { v = (u8)ap[1]; ap += 3; return v; } if (a_chlen(ap) == 4) { v = a_esc(ap[2]); ap += 4; return v; }
if (a_chlen(ap) == 3) { v = (u8)ap[1]; ap += 3; return v; }
if (*ap == '$') { if (*ap == '$') {
ap++; ap++;
if ((*ap >= '0' && *ap <= '9') || (*ap >= 'A' && *ap <= 'F')) { if ((*ap >= '0' && *ap <= '9') || (*ap >= 'A' && *ap <= 'F')) {
@@ -174,6 +221,9 @@ static u32 a_expr(void)
else if (*ap == '-') { ap++; v -= a_term(); } else if (*ap == '-') { ap++; v -= a_term(); }
else if (*ap == '&') { ap++; v &= a_term(); } else if (*ap == '&') { ap++; v &= a_term(); }
else if (*ap == '|') { ap++; v |= a_term(); } else if (*ap == '|') { ap++; v |= a_term(); }
else if (*ap == '^') { ap++; v ^= a_term(); }
else if (*ap == '<' && ap[1] == '<') { ap += 2; v <<= a_term(); }
else if (*ap == '>' && ap[1] == '>') { ap += 2; v >>= a_term(); }
else return v; else return v;
} }
} }
@@ -192,7 +242,8 @@ static void a_split(void)
const char *s = ap; const char *s = ap;
u8 d = 0, q = 0, len; u8 d = 0, q = 0, len;
while (*ap && (d || q || *ap != ',')) { while (*ap && (d || q || *ap != ',')) {
if (*ap == '\'' && !q && ap[1] && ap[2] == '\'') ap += 2; if (!q && a_chlen(ap)) ap += a_chlen(ap) - 1;
else if (q && *ap == '\\' && ap[1]) ap++;
else if (*ap == '"') q = !q; else if (*ap == '"') q = !q;
else if (*ap == '(') d++; else if (*ap == '(') d++;
else if (*ap == ')' && d) d--; else if (*ap == ')' && d) d--;
@@ -315,9 +366,6 @@ static u32 enc_u(u32 base, u8 rd, u32 imm)
if (a_pass == 2 && imm > 0xFFFFF) a_fail("VALUE OUT OF RANGE"); if (a_pass == 2 && imm > 0xFFFFF) a_fail("VALUE OUT OF RANGE");
return base | rd << 7 | (imm & 0xFFFFF) << 12; return base | rd << 7 | (imm & 0xFFFFF) << 12;
} }
/* the LUI/AUIPC part and the ADDI part of a 32-bit value */
static u32 hi20(u32 v) { return (v + 0x800) >> 12 & 0xFFFFF; }
static i32 lo12(u32 v) { return sx(v, 12); }
/* ----------------------------------------------------------------- F */ /* ----------------------------------------------------------------- F */
static void a_need(u8 n); static void a_need(u8 n);
@@ -385,7 +433,7 @@ static void a_finstr(const struct fins *t)
u32 b = t->base; u32 b = t->base;
i32 off; i32 off;
u8 r, s; u8 r, s;
if (a_pc & 3) { a_fail("NOT ON A WORD: USE ALIGN 4"); return; } if (a_pc & 3) { a_fail("NOT ON A WORD: USE .ALIGN 2"); return; }
switch (t->f) { switch (t->f) {
case G_LD: a_need(2); r = a_freg(0); s = a_mem(1, &off); a_emit32(enc_i(b, r, s, off)); return; case G_LD: a_need(2); r = a_freg(0); s = a_mem(1, &off); a_emit32(enc_i(b, r, s, off)); return;
case G_ST: a_need(2); r = a_freg(0); s = a_mem(1, &off); a_emit32(enc_s(b, s, r, off)); return; case G_ST: a_need(2); r = a_freg(0); s = a_mem(1, &off); a_emit32(enc_s(b, s, r, off)); return;
@@ -413,7 +461,7 @@ static void a_finstr(const struct fins *t)
enum { enum {
F_R, F_I, F_SH, F_LD, F_ST, F_B, F_U, F_JAL, F_JALR, F_CSR, F_CSRI, F_FIX, F_R, F_I, F_SH, F_LD, F_ST, F_B, F_U, F_JAL, F_JALR, F_CSR, F_CSRI, F_FIX,
P_LI, P_LA, P_MV, P_NOT, P_NEG, P_SEQZ, P_SNEZ, P_SLTZ, P_SGTZ, P_J, P_JR, P_RET, P_LI, P_LA, P_MV, P_NOT, P_NEG, P_SEQZ, P_SNEZ, P_SLTZ, P_SGTZ, P_J, P_JR, P_RET,
P_CALL, P_BZ, P_BZS, P_BSW, P_CSRR, P_CSRW, P_CSRWI P_CALL, P_BZ, P_BZS, P_BSW, P_CSRR, P_CSRW, P_CSRWI, P_FR, P_FS
}; };
struct ins { char name[8]; u8 f; u32 base; }; struct ins { char name[8]; u8 f; u32 base; };
static const struct ins itab[] = { static const struct ins itab[] = {
@@ -450,6 +498,9 @@ static const struct ins itab[] = {
{ "CSRR", P_CSRR, 0 }, { "CSRW", P_CSRW, 0x00001073 }, { "CSRS", P_CSRW, 0x00002073 }, { "CSRR", P_CSRR, 0 }, { "CSRW", P_CSRW, 0x00001073 }, { "CSRS", P_CSRW, 0x00002073 },
{ "CSRC", P_CSRW, 0x00003073 }, { "CSRWI", P_CSRWI, 0x00005073 }, { "CSRC", P_CSRW, 0x00003073 }, { "CSRWI", P_CSRWI, 0x00005073 },
{ "CSRSI", P_CSRWI, 0x00006073 }, { "CSRCI", P_CSRWI, 0x00007073 }, { "CSRSI", P_CSRWI, 0x00006073 }, { "CSRCI", P_CSRWI, 0x00007073 },
/* the float CSRs: read (CSRR), and write ([rd,] rs: CSRRW) */
{ "FRFLAGS", P_FR, 0x00102073 }, { "FRRM", P_FR, 0x00202073 }, { "FRCSR", P_FR, 0x00302073 },
{ "FSFLAGS", P_FS, 0x00101073 }, { "FSRM", P_FS, 0x00201073 }, { "FSCSR", P_FS, 0x00301073 },
}; };
#define NINS (sizeof itab / sizeof itab[0]) #define NINS (sizeof itab / sizeof itab[0])
@@ -460,7 +511,7 @@ static void a_instr(const struct ins *t)
u32 b = t->base, v; u32 b = t->base, v;
i32 off; i32 off;
u8 rd, rs; u8 rd, rs;
if (a_pc & 3) { a_fail("NOT ON A WORD: USE ALIGN 4"); return; } if (a_pc & 3) { a_fail("NOT ON A WORD: USE .ALIGN 2"); return; }
switch (t->f) { switch (t->f) {
case F_R: a_need(3); a_emit32(enc_r(b, a_reg(0), a_reg(1), a_reg(2))); return; case F_R: a_need(3); a_emit32(enc_r(b, a_reg(0), a_reg(1), a_reg(2))); return;
case F_I: a_need(3); a_emit32(enc_i(b, a_reg(0), a_reg(1), (i32)a_imm(2))); return; case F_I: a_need(3); a_emit32(enc_i(b, a_reg(0), a_reg(1), (i32)a_imm(2))); return;
@@ -496,6 +547,8 @@ static void a_instr(const struct ins *t)
v = a_imm(1); v = a_imm(1);
if (!a_undef && !a_fwd && (i32)v >= -2048 && (i32)v <= 2047) { if (!a_undef && !a_fwd && (i32)v >= -2048 && (i32)v <= 2047) {
a_emit32(enc_i(0x13, rd, 0, (i32)v)); a_emit32(enc_i(0x13, rd, 0, (i32)v));
} else if (!a_undef && !a_fwd && !(v & 0xFFF)) {
a_emit32(enc_u(0x37, rd, v >> 12)); /* LUI alone, as GNU as does */
} else { } else {
a_emit32(enc_u(0x37, rd, hi20(v))); a_emit32(enc_u(0x37, rd, hi20(v)));
a_emit32(enc_i(0x13, rd, rd, lo12(v))); a_emit32(enc_i(0x13, rd, rd, lo12(v)));
@@ -524,6 +577,10 @@ static void a_instr(const struct ins *t)
case P_BSW: a_need(3); rs = a_reg(0); a_emit32(enc_b(b, a_reg(1), rs, a_imm(2))); return; case P_BSW: a_need(3); rs = a_reg(0); a_emit32(enc_b(b, a_reg(1), rs, a_imm(2))); return;
case P_CSRR: a_need(2); a_emit32(0x2073 | a_reg(0) << 7 | (u32)a_csr(1) << 20); return; case P_CSRR: a_need(2); a_emit32(0x2073 | a_reg(0) << 7 | (u32)a_csr(1) << 20); return;
case P_CSRW: a_need(2); a_emit32(b | a_reg(1) << 15 | (u32)a_csr(0) << 20); return; case P_CSRW: a_need(2); a_emit32(b | a_reg(1) << 15 | (u32)a_csr(0) << 20); return;
case P_FR: a_need(1); a_emit32(b | a_reg(0) << 7); return;
case P_FS:
if (a_nops == 1) { a_emit32(b | a_reg(0) << 15); return; }
a_need(2); a_emit32(b | a_reg(0) << 7 | a_reg(1) << 15); return;
case P_CSRWI: case P_CSRWI:
a_need(2); a_need(2);
v = a_imm(1); v = a_imm(1);
@@ -533,15 +590,24 @@ static void a_instr(const struct ins *t)
} }
} }
/* DB/DH/DW items: numbers and (for DB) strings */ /* data items: numbers, and for bytes "strings". str: 1 strings with
static void a_data(u8 size) escapes (.ascii), 2 the same with a 0 after each (.string); 0 DB's, kept
as they are. */
static void a_data(u8 size, u8 str)
{ {
for (;;) { for (;;) {
a_sp(); a_sp();
if (*ap == '"' && size == 1) { if (*ap == '"' && size == 1) {
ap++; ap++;
while (*ap && *ap != '"') a_emit(*ap++); while (*ap && *ap != '"') {
if (str && *ap == '\\' && ap[1]) { a_emit(a_esc(ap[1])); ap += 2; }
else a_emit(*ap++);
}
if (*ap) ap++; if (*ap) ap++;
if (str == 2) a_emit(0);
} else if (str) {
a_fail("BAD STRING");
return;
} else { } else {
u32 v = a_expr(); u32 v = a_expr();
u8 k; u8 k;
@@ -556,20 +622,37 @@ static void a_data(u8 size)
static u8 is_w(const char *w, const char *s) { return !strncmp(w, s, 8); } static u8 is_w(const char *w, const char *s) { return !strncmp(w, s, 8); }
/* directives, and the old names that mean the same */
enum { D_EQU = 1, D_SET, D_ORG, D_END, D_DB, D_ASCII, D_STRING, D_DH, D_DW, D_DS, D_SPACE,
D_ALIGN, D_P2ALIGN, D_IGNORE };
static const struct { char n[8]; u8 d; } dtab[] = {
{ "EQU", D_EQU }, { ".EQU", D_SET }, { ".SET", D_SET }, { "ORG", D_ORG }, { ".ORG", D_ORG },
{ "END", D_END }, { ".END", D_END }, { "DB", D_DB }, { "DEFB", D_DB }, { "DEFM", D_DB },
{ ".BYTE", D_DB }, { ".ASCII", D_ASCII }, { ".STRING", D_STRING }, { ".ASCIZ", D_STRING },
{ "DH", D_DH }, { ".HALF", D_DH }, { ".SHORT", D_DH }, { ".2BYTE", D_DH }, { "DW", D_DW },
{ "DEFW", D_DW }, { ".WORD", D_DW }, { ".LONG", D_DW }, { ".4BYTE", D_DW }, { "DS", D_DS },
{ "DEFS", D_DS }, { ".SPACE", D_SPACE }, { ".SKIP", D_SPACE }, { ".ZERO", D_SPACE },
{ "ALIGN", D_ALIGN }, { ".BALIGN", D_ALIGN }, { ".ALIGN", D_P2ALIGN }, { ".P2ALIGN", D_P2ALIGN },
{ ".TEXT", D_IGNORE }, { ".DATA", D_IGNORE }, { ".SECTION", D_IGNORE }, { ".GLOBL", D_IGNORE },
{ ".GLOBAL", D_IGNORE }, { ".OPTION", D_IGNORE }, { ".TYPE", D_IGNORE }, { "", 0 }
};
/* Assemble one source line (uppercase except in quotes). */ /* Assemble one source line (uppercase except in quotes). */
static void a_line(char *s) static void a_line(char *s)
{ {
char w[8], lab[8], fm[12]; char w[8], lab[8], fm[12];
const char *mn; const char *mn;
u8 has_lab = 0, q = 0; u8 has_lab = 0, q = 0, d;
u16 m; u16 m;
u32 n, f;
char *c; char *c;
a_err = 0; a_err = 0;
/* cut the comment */ /* cut the comment */
for (c = s; *c; c++) { for (c = s; *c; c++) {
if (*c == '"') q = !q; if (q && *c == '\\' && c[1]) c++;
else if (*c == '\'' && !q && c[1] && c[2] == '\'') c += 2; else if (*c == '"') q = !q;
else if (*c == ';' && !q) { *c = 0; break; } else if (!q && a_chlen(c)) c += a_chlen(c) - 1;
else if ((*c == ';' || *c == '#') && !q) { *c = 0; break; }
} }
ap = s; ap = s;
a_sp(); a_sp();
@@ -593,30 +676,58 @@ static void a_line(char *s)
mn = ap; mn = ap;
a_name(w); a_name(w);
a_sp(); a_sp();
} else if (!strncmp(ap, "EQU", 3) && !a_alnum(ap[3])) { } else if ((!strncmp(ap, "EQU", 3) && !a_alnum(ap[3])) || (*ap == '=' && w[0] != '.')) {
memcpy(lab, w, 8); has_lab = 1; memcpy(lab, w, 8); has_lab = 1; /* NAME EQU value, NAME = value */
ap += *ap == '=' ? 1 : 3;
memcpy(w, "EQU\0\0\0\0\0", 8); memcpy(w, "EQU\0\0\0\0\0", 8);
ap += 3;
} }
if (is_w(w, "EQU")) { for (m = 0; dtab[m].d && !is_w(w, dtab[m].n); m++);
u32 v = a_expr(); d = dtab[m].d;
if (d == D_SET) { /* .EQU NAME, value */
if (!a_alpha(*ap)) { a_fail("EQU NEEDS A NAME"); return; }
a_name(lab); has_lab = 1;
a_sp();
if (*ap == ',') ap++;
d = D_EQU;
}
if (d == D_EQU) {
n = a_expr();
if (!has_lab) a_fail("EQU NEEDS A NAME"); if (!has_lab) a_fail("EQU NEEDS A NAME");
else if (a_undef && a_pass == 1) a_fail("EQU BEFORE ITS VALUE"); else if (a_undef && a_pass == 1) a_fail("EQU BEFORE ITS VALUE");
else sym_def(lab, v); else sym_def(lab, n);
return; return;
} }
if (has_lab) sym_def(lab, a_pc); if (has_lab) sym_def(lab, a_pc);
if (is_w(w, "ORG")) { a_pc = a_expr(); return; } switch (d) {
if (is_w(w, "END")) { a_end = 1; return; } case D_ORG: a_pc = a_expr(); return;
if (is_w(w, "DB") || is_w(w, "DEFB") || is_w(w, "DEFM")) { a_data(1); return; } case D_END: a_end = 1; return;
if (is_w(w, "DH")) { a_data(2); return; } case D_DB: a_data(1, 0); return;
if (is_w(w, "DW") || is_w(w, "DEFW")) { a_data(4); return; } case D_ASCII: a_data(1, 1); return;
if (is_w(w, "DS") || is_w(w, "DEFS")) { a_pc += a_expr(); return; } case D_STRING: a_data(1, 2); return;
if (is_w(w, "ALIGN")) { case D_DH: a_data(2, 0); return;
u32 n = a_expr(); case D_DW: a_data(4, 0); return;
if (!n || (n & (n - 1))) a_fail("ALIGN TO A POWER OF 2"); case D_DS: a_pc += a_expr(); return;
else while (a_pc & (n - 1)) a_emit(0); case D_SPACE: /* n [, fill] */
n = a_expr(); f = 0;
a_sp();
if (*ap == ',') { ap++; f = a_expr(); }
while (n--) a_emit(f);
return; return;
case D_ALIGN: case D_P2ALIGN:
n = a_expr();
if (d == D_P2ALIGN) n = n < 32 ? 1u << n : 0; /* .ALIGN, .P2ALIGN: to 2^n */
a_sp();
if (!n || (n & (n - 1))) a_fail("ALIGN TO A POWER OF 2");
else if (*ap == ',') { /* n, fill */
ap++;
f = a_expr();
while (a_pc & (n - 1)) a_emit(f);
} else { /* zeros to a word, then NOPs */
while (a_pc & (n - 1) & 3) a_emit(0);
while (a_pc & (n - 1)) a_emit32(0x13);
}
return;
case D_IGNORE: return;
} }
/* F instructions, whose names can be longer than 8 */ /* F instructions, whose names can be longer than 8 */
for (m = 0; m < 11 && a_alnum(mn[m]); m++) fm[m] = mn[m]; for (m = 0; m < 11 && a_alnum(mn[m]); m++) fm[m] = mn[m];
@@ -641,8 +752,9 @@ static void a_upper(char *s)
{ {
u8 q = 0; u8 q = 0;
for (; *s; s++) { for (; *s; s++) {
if (*s == '"') q = !q; if (q && *s == '\\' && s[1]) s++;
else if (*s == '\'' && !q && s[1] && s[2] == '\'') s += 2; else if (*s == '"') q = !q;
else if (!q && a_chlen(s)) s += a_chlen(s) - 1;
else if (!q && *s >= 'a' && *s <= 'z') *s -= 32; else if (!q && *s >= 'a' && *s <= 'z') *s -= 32;
if (*s == '\t') *s = ' '; if (*s == '\t') *s = ' ';
} }
+2 -1
View File
@@ -5,7 +5,8 @@ set -e
cd "$(dirname "$0")" cd "$(dirname "$0")"
source ../scripts/rv_env.sh source ../scripts/rv_env.sh
mkdir -p out mkdir -p out
CFLAGS="$RV_ARCH -Os -ffunction-sections -fdata-sections -fno-common -Wall -I../include" # -msave-restore: shared register saving, 2 KB smaller (the ROM is 32 KB)
CFLAGS="$RV_ARCH -Os -msave-restore -ffunction-sections -fdata-sections -fno-common -Wall -I../include"
${RV_PREFIX}gcc $CFLAGS -c -o out/crt0.o crt0.S ${RV_PREFIX}gcc $CFLAGS -c -o out/crt0.o crt0.S
${RV_PREFIX}gcc $CFLAGS -c -o out/monitor.o monitor.c ${RV_PREFIX}gcc $CFLAGS -c -o out/monitor.o monitor.c
${RV_PREFIX}gcc $CFLAGS -c -o out/string.o ../lib/string.c ${RV_PREFIX}gcc $CFLAGS -c -o out/string.o ../lib/string.c
Binary file not shown.
+27 -7
View File
@@ -80,14 +80,13 @@ static void s_udec(u32 v)
s_str(q); s_str(q);
} }
static void s_dec(i32 v) { if (v < 0) { s_ch('-'); v = -v; } s_udec((u32)v); } static void s_dec(i32 v) { if (v < 0) { s_ch('-'); v = -v; } s_udec((u32)v); }
/* assembler style: 1F0H, 0A200H (a leading 0 when it starts with a letter) */ /* GNU style: 0x1f0 (disasm() lower-cases it) */
static void s_lit(u32 v) static void s_lit(u32 v)
{ {
u8 n = 1; u8 n = 1;
while (n < 8 && v >> (4 * n)) n++; while (n < 8 && v >> (4 * n)) n++;
if ((v >> (4 * (n - 1)) & 15) >= 10) s_ch('0'); s_str("0X");
s_hex(v, n); s_hex(v, n);
s_ch('H');
} }
/* ---------------------------------------------------------- disassembler */ /* ---------------------------------------------------------- disassembler */
@@ -129,7 +128,17 @@ static const char *const csrin[8] = { 0, "CSRRW", "CSRRS", "CSRRC", 0, "CSRRWI",
/* F: registers F0-F31, the rounding mode after the operands unless DYN */ /* F: registers F0-F31, the rounding mode after the operands unless DYN */
static const char *const rmn[8] = { "RNE", "RTZ", "RDN", "RUP", "RMM", 0, 0, "DYN" }; static const char *const rmn[8] = { "RNE", "RTZ", "RDN", "RUP", "RMM", 0, 0, "DYN" };
static void s_freg(u8 r) { s_ch('F'); s_udec(r); } /* float registers by their ABI names, as objdump shows them: ft0-7 fs0-1
fa0-7 fs2-11 ft8-11 */
static void s_freg(u8 r)
{
s_ch('F');
if (r < 8) { s_ch('T'); s_udec(r); }
else if (r < 10) { s_ch('S'); s_udec(r - 8); }
else if (r < 18) { s_ch('A'); s_udec(r - 10); }
else if (r < 28) { s_ch('S'); s_udec(r - 16); }
else { s_ch('T'); s_udec(r - 20); }
}
static void s_rm(u8 m) { if (m != 7) { s_c(); s_str(rmn[m]); } } static void s_rm(u8 m) { if (m != 7) { s_c(); s_str(rmn[m]); } }
/* An F instruction (not FLW/FSW); 0 if it isn't one */ /* An F instruction (not FLW/FSW); 0 if it isn't one */
@@ -194,8 +203,8 @@ static u8 dis_f(u32 w)
return 0; return 0;
} }
/* One instruction at a into line (at lp); returns its length, 4. */ /* One instruction at a into line (at lp), in capitals; returns its length, 4. */
static u8 disasm(u32 a) static u8 dis_up(u32 a)
{ {
u32 w = rd32(a); u32 w = rd32(a);
u8 op = w & 0x7F, rd = w >> 7 & 31, f3 = w >> 12 & 7, rs1 = w >> 15 & 31, rs2 = w >> 20 & 31; u8 op = w & 0x7F, rd = w >> 7 & 31, f3 = w >> 12 & 7, rs1 = w >> 15 & 31, rs2 = w >> 20 & 31;
@@ -306,10 +315,20 @@ static u8 disasm(u32 a)
return 4; return 4;
} }
} }
s_mn("DW"); s_lit(w); s_mn(".WORD"); s_lit(w);
return 4; return 4;
} }
/* One instruction at a into line (at lp), in lower case as GNU tools show
it; returns its length, 4. */
static u8 disasm(u32 a)
{
char *s = lp;
u8 n = dis_up(a);
for (; s < lp; s++) if (*s >= 'A' && *s <= 'Z') *s += 32;
return n;
}
#ifndef __riscv #ifndef __riscv
#include "asm.c" #include "asm.c"
@@ -580,6 +599,7 @@ static u8 get_hex(u32 *v)
u8 n = 0; u8 n = 0;
skip_sp(); skip_sp();
*v = 0; *v = 0;
if (cp[0] == '0' && (cp[1] == 'X' || cp[1] == 'x') && is_hex(cp[2])) cp += 2; /* 0x is optional */
while (is_hex(*cp)) { while (is_hex(*cp)) {
*v = *v << 4 | (*cp <= '9' ? *cp - '0' : *cp - 'A' + 10); *v = *v << 4 | (*cp <= '9' ? *cp - '0' : *cp - 'A' + 10);
cp++; n++; cp++; n++;
+5 -1
View File
@@ -11,8 +11,12 @@ SECTIONS
{ {
.text : { .text : {
KEEP(*(.text.start)) KEEP(*(.text.start))
*(.text .text.*) /* the constants before the code: they are reached by LUI and ADDI,
and relaxation must never take them for gp-relative data, which
it would if the code (larger before relaxing) pushed them past
28000h */
*(.rodata .rodata.* .srodata .srodata.*) *(.rodata .rodata.* .srodata .srodata.*)
*(.text .text.*)
. = ALIGN(4); . = ALIGN(4);
} > ROM } > ROM
.data : ALIGN(4) { .data : ALIGN(4) {
+6285 -6285
View File
File diff suppressed because it is too large. Load diff
+117 -22
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Assemble a test program with the monitor's assembler (out/monitor-host) """Assemble test programs with the monitor's assembler (out/monitor-host)
and with GNU as, and check the bytes are the same. and with GNU as, and check the bytes are the same: one in GNU syntax, given
to both as it is, and one in the older forms the monitor still takes.
python3 test-asm.py python3 test-asm.py
""" """
@@ -12,7 +13,72 @@ import tempfile
HERE = os.path.dirname(os.path.abspath(__file__)) HERE = os.path.dirname(os.path.abspath(__file__))
# the monitor's syntax; to_gnu() below turns it into GNU as's # GNU syntax: both assemblers read this text (GNU as without the .org)
GNU_SRC = r"""
.org 0x12000
.text
.option norvc
.globl _start
.equ count, 10
.set mask, 0b1010 << 4 | 1 # 161
width = (count * 3) ^ ~0xf # mixed operators
big = 0x12345
_start: la a1, message # auipc and addi
li a2, count
li a3, 0x12000 # lui alone
li a4, 0x12345 # lui and addi
li a5, -1
li t0, mask
li t1, width & 0x7ff
lui a6, %hi(big)
addi a6, a6, %lo(big)
lui a7, %hi(table)
lw a7, %lo(table)(a7)
sw zero, %lo(table)(a7)
print_char:
lbu a0, 0(a1)
beqz a0, finish
wait: lbu t0, -256(zero)
andi t0, t0, 2
beqz t0, wait
sb a0, -255(zero)
addi a1, a1, 1
j print_char
finish: li a0, '\n'
li a1, 'Z' - 1
csrr a2, mstatus
csrw mscratch, a2
csrrs a3, cycle, zero
frrm a4
fadd.s fa0, fa1, fa2, rtz
fmadd.s ft0, ft1, ft2, ft3
flw fs0, 4(sp)
fsw ft11, -8(sp)
fcvt.w.s t2, fa0, rtz
jal print_char
jalr t0
ret
.align 4 # NOPs from a word
message:
.string "hello, \"world\"\n", "two"
.ascii "tab\there"
.asciz "back\\slash"
.p2align 2, 0 # GNU leaves bytes unaligned without a fill
table: .word _start, finish, . - _start, 0x12345678
.long -1
.4byte 'A'
.half 1234, 0xffff
.short 7
.2byte -2
.byte 1, 2, 0x7f, 'X', '\t' # (GNU reads '\0' as '0')
.space 3, 0xaa
.zero 2
.skip 1
.balign 8
.byte 0xee
"""
# the older forms; to_gnu() below turns them into GNU as's
SRC = r""" SRC = r"""
ORG 12000H ORG 12000H
COUNT EQU 10 COUNT EQU 10
@@ -130,36 +196,65 @@ def to_gnu(src):
return "\n".join(out) + "\n" return "\n".join(out) + "\n"
def main(): def assemble_gnu(pre, text, tmp):
pre = subprocess.run(["bash", "-c", "source %s/../scripts/rv_env.sh; echo $RV_PREFIX" % HERE], open(os.path.join(tmp, "t.s"), "w").write(text)
capture_output=True, text=True).stdout.strip()
ours = subprocess.run([os.path.join(HERE, "out", "monitor-host"), "asmbin"], input=SRC,
capture_output=True, text=True).stdout.strip()
if not re.fullmatch(r"[0-9A-F]{5} [0-9A-F]+", ours):
print("FAIL the monitor's assembler: " + ours)
sys.exit(1)
start, ours = ours.split()
tmp = tempfile.mkdtemp()
open(os.path.join(tmp, "t.s"), "w").write(to_gnu(SRC))
subprocess.run([pre + "as", "-march=rv32imf_zicsr_zifencei", "-mno-relax", "-o", os.path.join(tmp, "t.o"), subprocess.run([pre + "as", "-march=rv32imf_zicsr_zifencei", "-mno-relax", "-o", os.path.join(tmp, "t.o"),
os.path.join(tmp, "t.s")], check=True) os.path.join(tmp, "t.s")], check=True)
subprocess.run([pre + "ld", "-m", "elf32lriscv", "--no-relax", "-e", "0x12000", "-Ttext=0x12000", "-o", os.path.join(tmp, "t.elf"), subprocess.run([pre + "ld", "-m", "elf32lriscv", "--no-relax", "-e", "0x12000", "-Ttext=0x12000", "-o",
os.path.join(tmp, "t.o")], check=True) os.path.join(tmp, "t.elf"), os.path.join(tmp, "t.o")], check=True)
subprocess.run([pre + "objcopy", "-O", "binary", os.path.join(tmp, "t.elf"), os.path.join(tmp, "t.bin")], subprocess.run([pre + "objcopy", "-O", "binary", os.path.join(tmp, "t.elf"), os.path.join(tmp, "t.bin")],
check=True) check=True)
gnu = open(os.path.join(tmp, "t.bin"), "rb").read().hex().upper() return open(os.path.join(tmp, "t.bin"), "rb").read().hex().upper()
# GNU pads the section's end to a word
if len(gnu) > len(ours) and set(gnu[len(ours):]) <= {"0"}:
def compare(what, src, gnu_text, pre):
ours = subprocess.run([os.path.join(HERE, "out", "monitor-host"), "asmbin"], input=src,
capture_output=True, text=True).stdout.strip()
if not re.fullmatch(r"[0-9A-F]{5} [0-9A-F]+", ours):
print("FAIL %s: the monitor's assembler says %s" % (what, ours))
return False
start, ours = ours.split()
gnu = assemble_gnu(pre, gnu_text, tempfile.mkdtemp())
if 0 < len(gnu) - len(ours) < 32: # GNU pads the section's end to 16 bytes
gnu = gnu[:len(ours)] gnu = gnu[:len(ours)]
ok = start == "12000" and ours == gnu ok = start == "12000" and ours == gnu
if not ok: if not ok:
for i in range(0, max(len(ours), len(gnu)), 8): for i in range(0, max(len(ours), len(gnu)), 8):
if ours[i:i + 8] != gnu[i:i + 8]: if ours[i:i + 8] != gnu[i:i + 8]:
print("first difference at %05X: monitor %s, GNU %s" % (0x12000 + i // 2, ours[i:i + 8], gnu[i:i + 8])) print("first difference at %05X: monitor %s, GNU %s" % (0x12000 + i // 2, ours[i:i + 8],
gnu[i:i + 8]))
break break
print("lengths: monitor %d bytes, GNU %d" % (len(ours) // 2, len(gnu) // 2)) print("lengths: monitor %d bytes, GNU %d" % (len(ours) // 2, len(gnu) // 2))
print(("PASS" if ok else "FAIL") + " %d bytes from 12000h the same as GNU as" % (len(ours) // 2)) print(("PASS" if ok else "FAIL") + " %s: %d bytes from 12000h the same as GNU as" % (what, len(ours) // 2))
sys.exit(0 if ok else 1) return ok
def host(cmd, text):
return subprocess.run([os.path.join(HERE, "out", "monitor-host"), cmd], input=text,
capture_output=True, text=True).stdout
def main():
pre = subprocess.run(["bash", "-c", "source %s/../scripts/rv_env.sh; echo $RV_PREFIX" % HERE],
capture_output=True, text=True).stdout.strip()
ok = compare("GNU syntax", GNU_SRC, GNU_SRC.replace(".org 0x12000", ""), pre)
ok &= compare("the older forms", SRC, to_gnu(SRC), pre)
# the same lines as BASIC stores them, in capitals outside double quotes
# (BASIC knows nothing of \" in a string, so that line is left out), and
# with ; comments
plain = "\n".join(l for l in GNU_SRC.splitlines() if '\\"' not in l)
upper = re.sub(r'("[^"]*")|[a-z]', lambda m: m.group(1) or m.group(0).upper(), plain)
upper = upper.replace("#", ";")
want = host("asmbin", plain)
same = host("asmbin", upper) == want and "ERROR" not in want
print(("PASS" if same else "FAIL") + " the same in capitals, with ; comments")
ok &= same
# errors
errs = {".align 33": "ALIGN", ".equ 5": "NAME", "li a0, %mid(5)": "BAD EXPRESSION",
".ascii 5": "BAD STRING", "lw a0, 0(q9)": "REGISTER", ".byte 0b102": "BAD NUMBER"}
bad = [k for k, v in errs.items() if v not in host("asm", k + "\n")]
print(("PASS" if not bad else "FAIL %s" % bad) + " errors")
sys.exit(0 if ok and not bad else 1)
if __name__ == "__main__": if __name__ == "__main__":
+9 -2
View File
@@ -124,7 +124,14 @@ FCSR_ALIAS = {"FRCSR": ("FCSR", "R"), "FRRM": ("FRM", "R"), "FRFLAGS": ("FFLAGS"
"FSRMI": ("FRM", "I"), "FSFLAGSI": ("FFLAGS", "I")} "FSRMI": ("FRM", "I"), "FSFLAGSI": ("FFLAGS", "I")}
FABI = ["FT%d" % i for i in range(8)] + ["FS0", "FS1"] + ["FA%d" % i for i in range(8)] + \
["FS%d" % i for i in range(2, 12)] + ["FT%d" % i for i in range(8, 12)]
def same(gnu_mn, gnu_ops, our): def same(gnu_mn, gnu_ops, our):
# ours is in lower case, with float registers by ABI name: objdump -M
# numeric's f0-f31
our = re.sub(r"\bF[TSA]\d+\b", lambda q: "F%d" % FABI.index(q.group(0)), our.upper())
m = our.split(None, 1) m = our.split(None, 1)
mn = m[0] mn = m[0]
ops = [o.strip() for o in m[1].split(",")] if len(m) > 1 else [] ops = [o.strip() for o in m[1].split(",")] if len(m) > 1 else []
@@ -145,7 +152,7 @@ def same(gnu_mn, gnu_ops, our):
gnu_mn, gnu_ops = "CSRW" + kind, [csr] + gnu_ops gnu_mn, gnu_ops = "CSRW" + kind, [csr] + gnu_ops
gnu_ops = [str(CSRN[o]) if o in CSRN else o for o in gnu_ops] gnu_ops = [str(CSRN[o]) if o in CSRN else o for o in gnu_ops]
ops = [str(CSRN[o]) if o in CSRN else o for o in ops] ops = [str(CSRN[o]) if o in CSRN else o for o in ops]
alias = {"FENCE.I": "FENCE.I", "UNIMP": "DW"} alias = {"FENCE.I": "FENCE.I", "UNIMP": ".WORD"}
if alias.get(gnu_mn, gnu_mn) != mn: if alias.get(gnu_mn, gnu_mn) != mn:
return False return False
# objdump writes "fence iorw,iorw" # objdump writes "fence iorw,iorw"
@@ -208,7 +215,7 @@ def main():
print("DIS %08X: objdump '%s', monitor '%s'" % (w, g, o)) print("DIS %08X: objdump '%s', monitor '%s'" % (w, g, o))
# round trip through the monitor's assembler, one instruction at 1000h each # round trip through the monitor's assembler, one instruction at 1000h each
bad_asm = 0 bad_asm = 0
back = subprocess.run([HOST, "asm"], input="".join("ORG 1000H\n%s\n" % o for o in ours), back = subprocess.run([HOST, "asm"], input="".join(".org 0x1000\n%s\n" % o for o in ours),
capture_output=True, text=True).stdout.splitlines() capture_output=True, text=True).stdout.splitlines()
for w, o, b in zip(ws, ours, back): for w, o, b in zip(ws, ours, back):
want = 0x0FF0000F if (w & 0x707F) == 0x0F else w want = 0x0FF0000F if (w & 0x707F) == 0x0F else w
+12 -10
View File
@@ -208,6 +208,7 @@ module tb_terminal;
ch = cellraw(rr, cc); ch = cellraw(rr, cc);
if (go && ch >= "0" && ch <= "9") hex_at = hex_at * 16 + (ch - "0"); if (go && ch >= "0" && ch <= "9") hex_at = hex_at * 16 + (ch - "0");
else if (go && ch >= "A" && ch <= "F") hex_at = hex_at * 16 + (ch - "A" + 10); else if (go && ch >= "A" && ch <= "F") hex_at = hex_at * 16 + (ch - "A" + 10);
else if (go && ch >= "a" && ch <= "f") hex_at = hex_at * 16 + (ch - "a" + 10);
else go = 0; else go = 0;
end end
end end
@@ -559,7 +560,7 @@ module tb_terminal;
pc_a = screen_pc(0); pc_a = screen_pc(0);
wait_at(9, 0, ">"); wait_at(9, 0, ">");
jp_txt = {cellraw(9, 19), cellraw(9, 20)}; jp_txt = {cellraw(9, 19), cellraw(9, 20)};
jp_to = hex_at(9, 21); jp_to = hex_at(9, 23); // "j 0x54a4"
dump_screen; dump_screen;
// the float registers, in place of the memory window, and setting one // the float registers, in place of the memory window, and setting one
uart_str("F\015"); uart_str("F\015");
@@ -573,9 +574,9 @@ module tb_terminal;
wait_at(0, 50, "STOPPED BY STEP"); wait_at(0, 50, "STOPPED BY STEP");
wait_at(29, 0, "> "); wait_at(29, 0, "> ");
pc_b = screen_pc(0); pc_b = screen_pc(0);
// MONITOR stops on a J (to the end of BASIC's statement routine): one // MONITOR stops on a j (to the end of BASIC's statement routine): one
// step must land exactly on its target // step must land exactly on its target
if (jp_txt == "J " && pc_b == jp_to) $display("PASS step: PC %h -> %h", pc_a, pc_b); if (jp_txt == "j " && pc_b == jp_to) $display("PASS step: PC %h -> %h", pc_a, pc_b);
else begin $display("FAIL step: PC %h -> %h, wanted %h (%0s)", pc_a, pc_b, jp_to, jp_txt); errors = errors + 1; end else begin $display("FAIL step: PC %h -> %h, wanted %h (%0s)", pc_a, pc_b, jp_to, jp_txt); errors = errors + 1; end
// a breakpoint where the step stopped (the end of BASIC's statement // a breakpoint where the step stopped (the end of BASIC's statement
// routine), hit again by OUT; leaving from it steps off it first // routine), hit again by OUT; leaving from it steps off it first
@@ -632,16 +633,17 @@ module tb_terminal;
wait_row(0, " 72 73"); wait_row(0, " 72 73");
// ---- the assembler: source typed into BASIC, saved, assembled by the monitor // ---- the assembler: source typed into BASIC, saved, assembled by the monitor
uart_str({"NEW\01510 ORG 12000H\01520 START: LA A1,MSG\01530 LOOP: LBU A0,0(A1)\015", // GNU as syntax, typed in lower case (BASIC stores it in capitals)
"40 BEQZ A0,DONE\01550 WAIT: LBU T0,-256(ZERO)\01560 ANDI T0,T0,2\015"}); uart_str({"NEW\01510 .org 0x12000\01520 start: la a1, msg\01530 loop: lbu a0, 0(a1)\015",
uart_str({"70 BEQZ T0,WAIT\01580 SB A0,-255(ZERO)\01590 ADDI A1,A1,1\015100 J LOOP\015", "40 beqz a0, done\01550 wait: lbu t0, -256(zero)\01560 andi t0, t0, 2\015"});
"110 DONE: RET\015"}); uart_str({"70 beqz t0, wait\01580 sb a0, -255(zero)\01590 addi a1, a1, 1\015100 j loop\015",
uart_str({"120 MSG: DB \"ASM OK\",0 ; THE MESSAGE\015SAVE \"HELLO\"\015MONITOR\015"}); "110 done: ret\015"});
uart_str({"120 msg: .string \"ASM OK\" # the message\015SAVE \"HELLO\"\015MONITOR\015"});
wait_at(29, 0, "> "); wait_at(29, 0, "> ");
uart_str("ASM \"HELLO\"\015"); uart_str("ASM \"HELLO\"\015");
wait_at(29, 40, "ASSEMBLED 12000-12032"); wait_at(29, 40, "ASSEMBLED 12000-12032");
uart_str("A 12100\015LI A0,66\015\015"); uart_str("A 12100\015LI A0,'B'\015\015"); // the line assembler, in capitals
wait_at(9, 2, "12100 04200513 LI A0,66"); wait_at(9, 2, "12100 04200513 li a0,66");
// an Intel HEX record above 64K (an extended address first) and the end record // an Intel HEX record above 64K (an extended address first) and the end record
uart_str(":020000040001F9\015:03210000AABBCCAB\015:00000001FF\015"); uart_str(":020000040001F9\015:03210000AABBCCAB\015:00000001FF\015");
wait_at(29, 40, "HEX LOADED 12100-12102"); wait_at(29, 40, "HEX LOADED 12100-12102");