raz / commit 489d8810

commit
489d88109fc91f2ae7f3b2acbc375ccdf98ae62d
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
6d1c7219
src/A64.raz: arm64's machine code, X64's twin; test/a64

PLAN.md 5, step 4. The encoder Gen.arm64 will use (constants as
Apple's assembler makes them, the ALU, loads and stores, branches
within a procedure, LSE atomics, reals) and the assembler of code
procedures, in Arm's syntax: bl p, b p, adr xN, v (adrp and add).
Chunk gains the fixups fxBranch26, fxPage21 and fxPageOff12, which
Link patches from step 6. test/a64 checks 428 words and 20 relocations
against Apple's cc and objdump, expect.sh making the expectation on
the Mac. x86-64's output is unchanged; the fixpoint holds.

patch · log

11 files changed, +3090 -12

PLAN.md (history) modified +13 -2

@@ -220,8 +220,19 @@
220220 3. Done. `Gen.raz` to `Gen.x86_64.raz`, `Elf.raz` to `Exe.linux.raz` (the
221221 unit `Exe`), `Host.raz` to `Host.linux.raz`, `src/cross.sh`: what
222222 Linux's compiler makes unchanged, byte for byte.
223-4. `A64.raz`, its encoder checked against `llvm-mc`'s bytes.
224-5. `Gen.arm64.raz`, in pieces: values and operations; jumps and
223+4. Done. `A64.raz`: arm64's encoder, jumps within a procedure, and
224+ the assembler in Arm's syntax (`bl p`, `b p`, `adr xN, v` for names),
225+ checked against Apple's assembler (clang's, `llvm-mc`'s bytes) by
226+ `test/a64`; Chunk's arm64 fixup kinds, `fxBranch26`, `fxPage21` and
227+ `fxPageOff12`, and `Scan.setBang` for a pre-index's `!`. Left for
228+ later: `Link`'s patching of those kinds comes with step 6; no
229+ compiler imports `A64` until step 5's `Gen.arm64.raz`, and
230+ `Chunk.beginChunk` still pads code with x86's `int3`, which arm64's
231+ Gen will want as `brk`.
232+5. `Gen.arm64.raz`, in pieces, each run on the Mac (owner, 2026-11-15):
233+ first a bare `Exe.darwin.raz` (a signed Mach-O over libSystem, no line
234+ numbers) and an `Rt` that only exits, built by the staged cross
235+ compiler in the container; then values and operations; jumps and
225236 checks; calls and frames; reals; atomics, deferred statements, the
226237 entry point.
227238 6. `Exe.darwin.raz` and `Link`'s rebases, its line numbers for lldb;

doc/compiler.md (history) modified +118 -6

@@ -1,7 +1,8 @@
11 # Reading the raz compiler
22
3-The compiler is twelve files of raz, about 13,200 lines of code (the
4-budget is 18,000). It is its own compiler: a release of it, the one
3+The compiler is thirteen files of raz, about 14,600 lines of code (the
4+budget is 18,000); one of them, `A64.raz`, arm64's encoder, waits for
5+the back end that will use it (`PLAN.md` 5). It is its own compiler: a release of it, the one
56 `BOOT` names, builds `src/`, and `make fixpoint` checks that what it
67 makes makes itself again, byte for byte. Each release was built by the
78 one before it, back to v0.19.0, which the Pascal compiler it was ported
@@ -17,10 +18,11 @@
1718 | File | Lines | Code | What |
1819 |---|---|---|---|
1920 | `src/Diag.raz` | 479 | 363 | Messages: positions, source excerpts, colour, counts |
20-| `src/Scan.raz` | 1,267 | 1,040 | Symbols, literals, comments, positions |
21+| `src/Scan.raz` | 1,279 | 1,048 | Symbols, literals, comments, positions |
2122 | `src/Sym.raz` | 866 | 689 | Types, objects, scopes, layout |
22-| `src/Chunk.raz` | 364 | 280 | The compiled program: chunks, fixups, line notes |
23+| `src/Chunk.raz` | 389 | 288 | The compiled program: chunks, fixups, line notes |
2324 | `src/X64.raz` | 1,777 | 1,450 | The instruction encoder, jumps within a procedure, the assembler |
25+| `src/A64.raz` | 1,848 | 1,365 | The same for arm64, not yet imported: the encoder, jumps, the assembler |
2426 | `src/Gen.x86_64.raz` | 2,860 | 1,998 | The stack machine, for x86-64: values, operations, checks, calls, frames |
2527 | `src/Item.raz` | 2,553 | 2,051 | Items: types, constants, variables, operators, conversions, calls |
2628 | `src/Parse.raz` | 4,938 | 4,191 | Declarations, statements, expressions, built-ins, recovery, warnings |
@@ -51,7 +53,7 @@
5153 each with the kind of the value (a word, a 64-bit integer, an `F32`,
5254 an `F64`). `Gen` is the only one that knows x86-64; a port to
5355 another machine is a new `Gen`, with an encoder of its own in place
54-of `X64.raz`. Likewise `Exe` is the only one that knows the executable's
56+of `X64.raz`, as `A64.raz` is arm64's. Likewise `Exe` is the only one that knows the executable's
5557 format, and `Host` the host's services. Each is a unit with a file per
5658 target, which the suffixes of the report's section 3 choose
5759 (`Gen.x86_64.raz`, `Exe.linux.raz`, `Host.linux.raz`); `Gen.Arch` and
@@ -1146,7 +1148,14 @@
11461148
11471149 A *fixup* (`Fixup`) is a 32-bit field in the code that will hold the
11481150 distance to another chunk: a call's target, or a rip-relative address.
1149-`addFixup` records one; `Link.raz` fills them in. A constant's addresses
1151+`addFixup` records one; `Link.raz` fills them in. arm64's fixups
1152+(`addKindFixup`) are fields of an instruction, of a kind each
1153+(`FixKind`): `fxBranch26`, a `bl`'s or `b`'s distance in words;
1154+`fxPage21`, an `adrp`'s distance in pages of 4 KB; `fxPageOff12`, an
1155+address's place in its page, in an `add` or, divided by the size the
1156+instruction reads, a load's or store's offset; as the Mach-O relocations
1157+of the same names. `Link.raz` patches only x86-64's yet; arm64's come
1158+with the Mac's executable. A constant's addresses
11501159 are *data fixups*, `addDataFixup`'s: 64-bit fields in rodata that will
11511160 hold a chunk's address itself, since the executable is loaded where the
11521161 linker placed it. `noteLine` records which line and column of the source
@@ -1267,6 +1276,106 @@
12671276 the next instruction; the line notes made after it move back with it
12681277 (`takeBack`, in `Chunk.raz`).
12691278
1279+## A64.raz: arm64's machine code
1280+
1281+X64's twin, for arm64: what `Gen.arm64.raz` will call, and the
1282+assembler of a code procedure on the Mac. No compiler imports it yet;
1283+`test/a64` checks every routine against Apple's assembler.
1284+
1285+Every instruction is one word of 32 bits, which `emit` writes. A
1286+routine builds the word from its fields with shifts and ors, and its
1287+comment draws the fields as Arm's manual does, most significant first:
1288+`sf op S 100010 sh imm12 Rn Rd` for add with an immediate. Registers
1289+are numbers: x0 to x30, and 31, which an instruction reads as sp or as
1290+the zero register by its kind (`SP` and `ZR` are both 31, and each
1291+routine says which it takes); the reals' v0 to v31, with a size, s, d
1292+or q. x18 is Apple's and never named; x16 is the encoder's own: a
1293+routine given an immediate or an offset its instruction can't hold
1294+builds it in x16 first, so Gen needn't know the limits.
1295+
1296+The routines, by family: `movRI` makes a constant as Apple's assembler
1297+would, a `movz` or `movn` when one halfword of 16 bits differs from
1298+zeros or ones, an `orr` of a logical immediate (`bitmask`, a run of
1299+ones rotated and repeated), else a `movz` or `movn` and a `movk` for
1300+each other halfword; `movRR`, `alu`, `aluShift`, `aluI` (an add of 12
1301+bits, of 12 bits shifted by 12, two adds below 2^24, else through x16;
1302+a negative one the opposite operation), `cmp`, `cmpI`, `neg`, `mvn`;
1303+`shift`, `shiftI` (every shift by a constant is a `ubfm`, `sbfm` or
1304+`extr`), `field`, `extend`; `mul`, `madd`, `mulHigh`, `divide`, `clz`,
1305+`rbit`, `csel`, `cset`; `load`, `store`, `loadR`, `storeR`, `loadIdx`,
1306+`storeIdx`, `loadF`, `storeF` (one routine, `ldst`, from bits that tell
1307+size, register file and operation: a scaled offset, else unscaled, else
1308+through x16), `ldp`, `stp`; the LSE atomics `ldaddal`, `swpal` and
1309+`casal`, and `dmb`, `svc`, `brk`, `align`; for reals `fop`, `fop1`,
1310+`fcvt`, `fcmp`, `scvtf`, `fcvtz`, `fmovFR` and `fmovRF`. Two things
1311+x86 does and arm64 doesn't are Gen's to mend, as their comments say:
1312+`sdiv` by zero gives 0, and `fcvtzs` saturates where x86 gives the
1313+smallest `I64`.
1314+
1315+*Other chunks.* macOS loads a program anywhere, so every address is
1316+made from the code's own: `addrChunk` is `adrp` of the chunk's page and
1317+`add` of its place in it, each with a fixup (`Chunk.raz`); `loadChunk`
1318+and `storeChunk`, and their reals' twins, put the page in x16 and the
1319+place in the load's offset, which the linker divides by the size it
1320+reads in the instruction; when the chunk's alignment doesn't make the
1321+place a multiple of the size, the address is made whole first. A C
1322+symbol's quadword is read so. `callChunk` and `jmpChunk` are `bl` and
1323+`b` with a fixup, within 128 MB.
1324+
1325+*Jumps within a procedure* are chains, as in X64, but the field that
1326+links a jump to the one before holds that one's place in words from the
1327+procedure's chunk, plus one, 0 ending the chain, since the fields are
1328+narrow: 26 bits in `b`, 19 in `b.cond`, `cbz` and `cbnz` (1 MB either
1329+way), 14 in `tbz` and `tbnz` (32 KB). A procedure of more than 1 MB of
1330+code, a quarter of a million instructions, is an error, rather than
1331+every conditional jump two instructions for a procedure no one writes.
1332+Gen's `tbz`, which a long procedure would outrun, is the opposite `tbz`
1333+over a `b`, two instructions that reach as far as `b`; the assembler's
1334+is one, in a code procedure that is never that long. `fixLink`,
1335+`fixLinkTo`, `dropJumpTo` and `joinLinks` are X64's.
1336+
1337+*The assembler*, `assemble`, has X64's interface: the parser's
1338+`ConstFn` and `NameFn`, labels found first (`findLabels`), and the
1339+listing. It reads Arm's syntax, destination first: `add x0, x1, #16`,
1340+`ldr w2, [x0, #4]`, `ldr x1, [x2, x3, lsl #3]`, `stp x29, x30, [sp,
1341+#-16]!`, `ldr x0, [sp], #16`, `b.ne loop`, `csel x0, x1, x2, lt`,
1342+`dmb ish`. The `#` is raz's "not equal", read and passed over, and may
1343+be left out; numbers are raz's, `10H` and not `0x10`; `!` is a slip for
1344+`not` elsewhere, and a symbol of its own while `assemble` runs
1345+(`Scan.setBang`). A procedure or a module variable stands for its
1346+address as in X64, in three places, written as Arm writes them:
1347+
1348+ bl triple 94000000 fxBranch26 to triple
1349+ b AsmNamed.twice 14000000 fxBranch26 to AsmNamed.twice
1350+ adr x9, total adrp x9; add x9 fxPage21 and fxPageOff12 to total
1351+
1352+`adr x9, total` is two instructions, `adrp` and `add`, since a variable
1353+may lie beyond `adr`'s 1 MB: it is the plain form of an address, as `lea
1354+r9, [total]` is on x86. The instructions are those of the routines
1355+above in all their forms, of x or w registers, and `movz`, `movk`,
1356+`movn`, `cmn`, `tst`, `bic`, `orn`, `eor`, `csinc`, `csinv`, `csneg`,
1357+`csetm`, `sxtb` to `uxth`, `ubfm`, `sbfm`, `ubfx`, `sbfx`, `rev`, every
1358+`ldr`, `str`, `ldur` and `stur` of a size, `ldp` and `stp` of w, x, s, d
1359+and q, `ldaxr` and `stlxr`, `dsb`, `isb`, `nop`, `yield`, `br`, `blr`,
1360+`ret` of a register, `cbz`, `cbnz`, `tbz`, `tbnz`, `fmax` and `fmin`,
1361+enough for the library's code procedures as they will be on the Mac;
1362+`db` gives bytes and `dd` words for any other. The assembler checks
1363+what it reads: a register where its instruction takes one of its width,
1364+sp only where sp goes, an immediate in its field's range; where Gen's
1365+routines would go through x16, the assembler says it can't.
1366+
1367+The listing is X64's: each routine says its instruction, as the
1368+assembler would read it, and a jump to a label says `->`, which `list`
1369+makes its target's offset from the jump's field.
1370+
1371+`test/a64` is its test, run by `make check`: `Encode.raz`, compiled
1372+with `-I src`, assembles `Asm.txt` and calls every routine, and prints
1373+each word in hex and each fixup; `expect.sh`, on an arm64 Mac, makes
1374+`Encode.expect` from `Asm.txt` in Apple's syntax and `Api.s`, the
1375+calls' instructions a line each, with `cc -c -arch arm64` and `objdump`:
1376+428 words and 20 relocations, the farthest jumps among them, across a
1377+megabyte of `nop`.
1378+
12701379 ## Gen.raz: the stack machine
12711380
12721381 This is the only unit that knows the machine. The calls it answers:
@@ -2920,6 +3029,9 @@
29203029 - **An instruction:** a routine in `X64.raz` built on `opM` or `opR`,
29213030 its encoding checked against `objdump -d` once, and a program in
29223031 `conform/` or `test/` that uses it.
3032+ In `A64.raz`, a routine that builds its word, and a line in
3033+ `test/a64` (`Encode.raz` and `Api.s`, or `Asm.txt`), whose
3034+ `expect.sh` checks it against Apple's assembler.
29233035 - **A machine:** a new `Gen.ARCH.raz`, answering the same calls, and an
29243036 encoder and assembler for it in place of `X64.raz`; and `Exe.OS.raz` if
29253037 the system's executable differs.

src/A64.raz (history) added +1848 -0

@@ -0,0 +1,1848 @@
1+(* A64: machine code for arm64, X64's twin.
2+
3+ The encoder writes arm64's instructions into the text of Chunk, each
4+ one word of 32 bits, least significant byte first. Registers are
5+ numbered as the hardware numbers them: x0 to x30, and 31, which is sp
6+ in some places and the zero register, xzr, in others, as each
7+ instruction says (SP and ZR below are both 31; a routine's comment
8+ says which it means). The reals' registers, v0 to v31, have numbers
9+ of their own, 0 to 31, and a size: s for an F32, d for an F64, q for
10+ 16 bytes. Jumps within a procedure are patched here, as soon as their
11+ target is known; calls and addresses of other chunks are fixups,
12+ patched by Link.
13+
14+ Apple's arm64 convention is the target's: x18 is the system's and
15+ never touched, x29 is the frame pointer, x30 the link register, sp
16+ is kept a multiple of 16. x16 (IP0) is this encoder's own scratch
17+ register: a routine given an immediate or an offset too big for its
18+ instruction builds it in x16 first, so Gen keeps nothing there.
19+
20+ Each encoding's comment gives its fields, most significant first, as
21+ Arm's reference manual draws them: `sf 0 0 100010 sh imm12 Rn Rd` is
22+ add (immediate), sf the bit for 64 bits, then constant bits, then the
23+ fields, Rd in the low five bits. Every encoding was checked against
24+ Apple's assembler; test/a64 checks them all again.
25+
26+ Depends on: Scan, for errors and the assembler's symbols; Diag, for
27+ positions and text; Chunk, for the code buffer and fixups.
28+ Leaves out: choosing instructions; that is Gen (Gen.arm64.raz, to
29+ come). Only what Gen and the library's code procedures need is here;
30+ `db` and `dd` give any other instruction. *)
31+module A64;
32+import Out, Fmt, Str, Diag, Scan, Chunk;
33+import SYSTEM;
34+
35+const
36+ FP* = 29; LR* = 30;
37+ SP* = 31; ZR* = 31; (* the same number: the instruction tells which *)
38+ X16* = 16; X17* = 17; (* IP0 and IP1, the scratch registers; X16 is the encoder's *)
39+
40+ (* condition codes, as b.cond and csel take them; cc xor 1 is the
41+ opposite of cc (invert) *)
42+ ccEQ* = 0; ccNE* = 1; ccHS* = 2; ccLO* = 3; ccMI* = 4; ccPL* = 5; ccVS* = 6; ccVC* = 7;
43+ ccHI* = 8; ccLS* = 9; ccGE* = 10; ccLT* = 11; ccGT* = 12; ccLE* = 13; ccAL* = 14;
44+
45+ (* the operations of two registers, alu's op: AluBits gives each its bits *)
46+ opAdd* = 0; opAdds* = 1; opSub* = 2; opSubs* = 3;
47+ opAnd* = 4; opOrr* = 5; opEor* = 6; opAnds* = 7; opBic* = 8; opOrn* = 9;
48+
49+ (* shifts: of a register operand, and lsl, lsr, asr and ror themselves *)
50+ shLsl* = 0; shLsr* = 1; shAsr* = 2; shRor* = 3;
51+
52+ (* csel's op: rd := rn if the condition holds, else rm, rm + 1, ~rm or -rm *)
53+ csSel* = 0; csInc* = 1; csInv* = 2; csNeg* = 3;
54+
55+ (* the addressing of ldp, stp and the indexed loads, bits 23 and 24 of
56+ a pair: [rn, #off]; [rn, #off]!, rn changed first; [rn], #off, after *)
57+ mPost* = 1; mOff* = 2; mPre* = 3;
58+
59+ (* reals: fop's op (the opcode field of two sources) and fop1's (of one) *)
60+ fMul* = 0; fDiv* = 1; fAdd* = 2; fSub* = 3; fMax* = 4; fMin* = 5;
61+ fMov* = 0; fAbs* = 1; fNeg* = 2; fSqrt* = 3;
62+
63+ NoLabel* = -1;
64+
65+ AluBits: [10]INT = [0B000000H, 2B000000H, 4B000000H, 6B000000H,
66+ 0A000000H, 2A000000H, 4A000000H, 6A000000H, 0A200000H, 2A200000H];
67+ AluNames: [10][]const U8 = ["add", "adds", "sub", "subs", "and", "orr", "eor", "ands", "bic", "orn"];
68+ ShiftNames: [4][]const U8 = ["lsl", "lsr", "asr", "ror"];
69+ CselBits: [4]INT = [1A800000H, 1A800400H, 5A800000H, 5A800400H];
70+ CselNames: [4][]const U8 = ["csel", "csinc", "csinv", "csneg"];
71+ CondNames*: [16][]const U8 = ["eq", "ne", "hs", "lo", "mi", "pl", "vs", "vc",
72+ "hi", "ls", "ge", "lt", "gt", "le", "al", "nv"];
73+ FopNames: [6][]const U8 = ["fmul", "fdiv", "fadd", "fsub", "fmax", "fmin"];
74+ Fop1Names: [4][]const U8 = ["fmov", "fabs", "fneg", "fsqrt"];
75+ Nop = 0D503201FH;
76+
77+type
78+ (* The parser's reader of an integer constant in a code procedure: a
79+ whole expression, or, when whole is false, a single factor *)
80+ ConstFn* = proc(whole: BOOL): (I64, ERROR);
81+
82+ (* The parser's reader of a name that stands for an address: a
83+ procedure or a module variable. Its chunk, the name read; or -1,
84+ nothing read, if the name is anything else *)
85+ NameFn* = proc: (INT, ERROR);
86+
87+ (* The text of the instruction that starts at at, for the listing *)
88+ Said = record
89+ at: INT;
90+ text: []const U8;
91+ end;
92+
93+var
94+ listing*: BOOL; (* -S: each instruction's text is kept, for list *)
95+ said: ^Said;
96+ numSaid, saidCap: INT;
97+ labelAt: INT; (* where a jump was last fixed to the place it was at *)
98+
99+(* The listing, as X64's *)
100+
101+proc setListing*(yes: BOOL);
102+begin
103+ listing := yes;
104+end;
105+
106+proc saidCount*: INT;
107+begin
108+ return numSaid;
109+end;
110+
111+proc unsay*(n: INT);
112+begin
113+ numSaid := n;
114+end;
115+
116+proc sayAt*(at: INT; s: []const U8);
117+begin
118+ if not listing then return; end;
119+ if numSaid = saidCap then
120+ said := ^Said(Scan.regrab(^U8(said), numSaid * SIZE(Said), (saidCap * 2 + 1024) * SIZE(Said)));
121+ saidCap := saidCap * 2 + 1024;
122+ end;
123+ said[numSaid].at := at;
124+ said[numSaid].text := s;
125+ INC(numSaid);
126+end;
127+
128+proc say*(s: []const U8);
129+begin
130+ sayAt(Chunk.pc, s);
131+end;
132+
133+proc restate*(at: INT; s: []const U8);
134+var i: INT;
135+begin
136+ i := numSaid - 1;
137+ while (i >= 0) and (said[i].at # at) do DEC(i); end;
138+ if i >= 0 then said[i].text := s; end;
139+end;
140+
141+(* "op a, b, c": an instruction's text, from its operands' *)
142+proc sayOps(op: []const U8; ops: []const []const U8);
143+var s: []const U8; i: INT;
144+begin
145+ s := op;
146+ for i := 0 to LEN(ops) - 1 do
147+ if i = 0 then s := Diag.say("{} {}", [Fmt.str(s), Fmt.str(ops[i])]);
148+ else s := Diag.say("{}, {}", [Fmt.str(s), Fmt.str(ops[i])]); end;
149+ end;
150+ say(s);
151+end;
152+
153+(* 1 for true *)
154+proc bit(f: BOOL): INT;
155+begin
156+ if f then return 1; end;
157+ return 0;
158+end;
159+
160+(* log2 of a size of 1, 2, 4, 8 or 16 bytes *)
161+proc scaleOf(size: INT): INT;
162+var s: INT;
163+begin
164+ s := 0;
165+ while (1 shl s) < size do INC(s); end;
166+ return s;
167+end;
168+
169+(* Register r's name: x or w by sf, 31 sp if sp, else the zero register *)
170+proc reg(r, sf: INT; sp: BOOL): []const U8;
171+const Pfx: [2][]const U8 = ["w", "x"];
172+begin
173+ if (r = 31) and sp and (sf = 1) then return "sp"; end;
174+ if (r = 31) and sp then return "wsp"; end;
175+ if r = 31 then return Diag.say("{}zr", [Fmt.str(Pfx[sf])]); end;
176+ return Diag.say("{}{}", [Fmt.str(Pfx[sf]), Fmt.int(r)]);
177+end;
178+
179+proc x(r: INT): []const U8;
180+begin
181+ return reg(r, 1, false);
182+end;
183+
184+proc xsp(r: INT): []const U8;
185+begin
186+ return reg(r, 1, true);
187+end;
188+
189+(* A real's register, by its size: s, d or q *)
190+proc vreg(v, size: INT): []const U8;
191+const Pfx: [5][]const U8 = ["b", "h", "s", "d", "q"];
192+begin
193+ return Diag.say("{}{}", [Fmt.str(Pfx[scaleOf(size)]), Fmt.int(v)]);
194+end;
195+
196+proc imm(v: I64): []const U8;
197+begin
198+ return Diag.say("#{}", [Fmt.int(v)]);
199+end;
200+
201+(* [rn, #off], or [rn, #off]! and [rn], #off by mode *)
202+proc memText(rn, off, mode: INT): []const U8;
203+begin
204+ if mode = mPre then return Diag.say("[{}, #{}]!", [Fmt.str(xsp(rn)), Fmt.int(off)]); end;
205+ if mode = mPost then return Diag.say("[{}], #{}", [Fmt.str(xsp(rn)), Fmt.int(off)]); end;
206+ return Diag.say("[{}, #{}]", [Fmt.str(xsp(rn)), Fmt.int(off)]);
207+end;
208+
209+proc emit(insn: INT);
210+begin
211+ Chunk.put4(insn);
212+end;
213+
214+proc invert*(cc: INT): INT;
215+begin
216+ return cc xor 1;
217+end;
218+
219+(* Immediates and moves *)
220+
221+(* v as a logical instruction's immediate, its fields N:immr:imms, or -1
222+ if it can't be one. Such an immediate is an element of 2, 4, 8, 16, 32
223+ or 64 bits repeated across the register, the element a run of ones
224+ rotated: N says 64 bits, imms holds the element's size and the run's
225+ length less one (imms 0xxxxx for 32 bits, 10xxxx for 16, ... 11110x
226+ for 2), and immr the rotation right. Of 32 bits (sf 0) the low half is
227+ taken, and seen as repeated. *)
228+proc bitmask*(v: I64; sf: INT): INT;
229+var u, elem, pat, m, rot: U64; e, ones, r: INT;
230+begin
231+ u := U64(v);
232+ if sf = 0 then u := (u & 0FFFFFFFFH) | ((u & 0FFFFFFFFH) shl 32); end;
233+ if (u = 0) or (u = MAX(U64)) then return -1; end;
234+ (* the smallest element: u is made of halves alike while turning it
235+ round by half its element changes nothing *)
236+ e := 64;
237+ while (e > 2) and (ROR(u, e div 2) = u) do e := e div 2; end;
238+ if e = 64 then m := MAX(U64); else m := (U64(1) shl e) - 1; end;
239+ elem := u & m;
240+ ones := POPCOUNT(elem);
241+ pat := (U64(1) shl ones) - 1;
242+ for r := 0 to e - 1 do
243+ rot := ((pat shr r) | (pat shl ((e - r) & 63))) & m;
244+ if rot = elem then
245+ return (bit(e = 64) shl 12) | (r shl 6) | ((~(e * 2 - 1)) & 3FH) | (ones - 1);
246+ end;
247+ end;
248+ return -1;
249+end;
250+
251+(* movn, movz or movk (opc 0, 2, 3): sf opc 100101 hw imm16 Rd, imm16
252+ shifted left by 16 * hw; movn writes its inverse, movk keeps the rest *)
253+proc movWide(sf, opc, rd, imm16, hw: INT);
254+const Names: [4][]const U8 = ["movn", "", "movz", "movk"];
255+begin
256+ if listing then sayOps(Names[opc], [reg(rd, sf, false), imm(imm16 & 0FFFFH), Diag.say("lsl #{}", [Fmt.int(hw * 16)])]); end;
257+ emit((sf shl 31) | (opc shl 29) | 12800000H | (hw shl 21) | ((imm16 & 0FFFFH) shl 5) | rd);
258+end;
259+
260+(* A logical instruction with an immediate, enc as bitmask gives it:
261+ sf opc 100100 N immr imms Rn Rd, opc 00 and, 01 orr, 10 eor, 11 ands.
262+ Rd is sp (but for ands), Rn the zero register. *)
263+proc logicImm(sf, op, rd, rn, enc: INT; v: I64);
264+begin
265+ if listing then sayOps(AluNames[op], [reg(rd, sf, op # opAnds), reg(rn, sf, false), imm(v)]); end;
266+ emit((sf shl 31) | (AluBits[op] + 08000000H) | (enc shl 10) | (rn shl 5) | rd);
267+end;
268+
269+(* rd := v, of 64 bits (sf 1) or 32, in as few instructions as it
270+ takes: movz #0 or movn #0 for all zeros or all ones; a single movz
271+ when v is one halfword of 16 bits and zeros, a movn when it is one
272+ halfword and ones, an orr of the zero register when it is a logical
273+ immediate; else a movz (or movn, if more of its halfwords are ones)
274+ of the first halfword that isn't all zeros (ones), and a movk for
275+ each other such halfword. Apple's assembler chooses the same. *)
276+proc movImm(sf, rd: INT; v: I64);
277+var n, zeros, ones, i, h, first, enc: INT;
278+begin
279+ n := 2 + 2 * sf;
280+ if sf = 0 then v := v & 0FFFFFFFFH; end;
281+ zeros := 0; ones := 0;
282+ for i := 0 to n - 1 do
283+ h := INT((v shr (16 * i)) & 0FFFFH);
284+ if h = 0 then INC(zeros); elsif h = 0FFFFH then INC(ones); end;
285+ end;
286+ if (zeros = n) or (ones = n) then
287+ movWide(sf, 2 * bit(zeros = n), rd, 0, 0);
288+ return;
289+ end;
290+ enc := bitmask(v, sf);
291+ if (zeros < n - 1) and (ones < n - 1) and (enc >= 0) then
292+ logicImm(sf, opOrr, rd, ZR, enc, v);
293+ return;
294+ end;
295+ first := -1;
296+ for i := 0 to n - 1 do
297+ h := INT((v shr (16 * i)) & 0FFFFH);
298+ if (zeros >= ones) and (h # 0) or (zeros < ones) and (h # 0FFFFH) then
299+ if first >= 0 then movWide(sf, 3, rd, h, i);
300+ elsif zeros >= ones then movWide(sf, 2, rd, h, i);
301+ else movWide(sf, 0, rd, ~h, i); end;
302+ first := i;
303+ end;
304+ end;
305+end;
306+
307+proc movRI*(rd: INT; v: I64);
308+begin
309+ movImm(1, rd, v);
310+end;
311+
312+(* Add, subtract and the logical operations *)
313+
314+(* add, adds, sub or subs with an immediate of 12 bits, shifted left by
315+ 12 if sh: sf op S 100010 sh imm12 Rn Rd. Rn is sp; so is Rd, but for
316+ adds and subs, whose Rd 31 is the zero register (cmp, cmn). *)
317+proc addImm(sf, op, rd, rn, imm12, sh: INT);
318+begin
319+ if listing then sayOps(AluNames[op], [reg(rd, sf, (op & 1) = 0), reg(rn, sf, true), imm(imm12), Diag.say("lsl #{}", [Fmt.int(12 * sh)])]); end;
320+ emit((sf shl 31) | (AluBits[op] + 06000000H) | (sh shl 22) | (imm12 shl 10) | (rn shl 5) | rd);
321+end;
322+
323+(* op of two registers, rm shifted by n: sf op S 01011 shift 0 Rm imm6 Rn
324+ Rd for add and sub, sf opc 01010 shift N Rm imm6 Rn Rd for the logical
325+ ones (N 1 for bic and orn, which invert rm). 31 is the zero register. *)
326+proc aluShifted(sf, op, rd, rn, rm, sh, n: INT);
327+begin
328+ if listing then sayOps(AluNames[op], [reg(rd, sf, false), reg(rn, sf, false), reg(rm, sf, false), Diag.say("{} #{}", [Fmt.str(ShiftNames[sh]), Fmt.int(n)])]); end;
329+ emit((sf shl 31) | AluBits[op] | (sh shl 22) | (rm shl 16) | (n shl 10) | (rn shl 5) | rd);
330+end;
331+
332+(* add or sub of a register extended, here only uxtx (uxtw for 32
333+ bits), shifted left by n up to 4: sf op S 01011 00 1 Rm option imm3
334+ Rn Rd. The form that takes sp, as Rn, and as Rd but for adds and subs *)
335+proc addExt(sf, op, rd, rn, rm, n: INT);
336+begin
337+ if listing then sayOps(AluNames[op], [reg(rd, sf, (op & 1) = 0), reg(rn, sf, true), reg(rm, sf, false), Diag.say("uxtx #{}", [Fmt.int(n)])]); end;
338+ emit((sf shl 31) | AluBits[op] | 200000H | (rm shl 16) | ((2 + sf) shl 13) | (n shl 10) | (rn shl 5) | rd);
339+end;
340+
341+(* rd := rn op rm, of 64 bits; 31 is the zero register, so tst a, b is
342+ alu(opAnds, ZR, a, b) *)
343+proc alu*(op, rd, rn, rm: INT);
344+begin
345+ aluShifted(1, op, rd, rn, rm, shLsl, 0);
346+end;
347+
348+(* rd := rn op (rm shifted by n), as an element's address, rn + rm lsl 3 *)
349+proc aluShift*(op, rd, rn, rm, sh, n: INT);
350+begin
351+ aluShifted(1, op, rd, rn, rm, sh, n);
352+end;
353+
354+(* rd := rn op v, of 64 bits. For add and sub, rn and rd may be sp:
355+ v in 12 bits, or 12 bits shifted by 12, is one instruction, a
356+ negative v the opposite one; below 2^24, without flags, two; else v
357+ is built in x16 and added as a register. For the logical operations,
358+ v as an immediate if it can be one, else built in x16. *)
359+proc aluI*(op, rd, rn: INT; v: I64);
360+var enc: INT;
361+begin
362+ if op <= opSubs then
363+ if (v < 0) and (v > MIN(I64)) then v := -v; op := op xor 2; end;
364+ if (v >= 0) and (v < 1000H) then
365+ addImm(1, op, rd, rn, INT(v), 0);
366+ elsif (v > 0) and (v < 1000000H) and ((v & 0FFFH) = 0) then
367+ addImm(1, op, rd, rn, INT(v shr 12), 1);
368+ elsif (v > 0) and (v < 1000000H) and ((op & 1) = 0) then
369+ addImm(1, op, rd, rn, INT(v shr 12), 1);
370+ addImm(1, op, rd, rd, INT(v & 0FFFH), 0);
371+ else
372+ movRI(X16, v);
373+ addExt(1, op, rd, rn, X16, 0);
374+ end;
375+ return;
376+ end;
377+ enc := bitmask(v, 1);
378+ if (enc >= 0) and (op <= opAnds) then
379+ logicImm(1, op, rd, rn, enc, v);
380+ else
381+ movRI(X16, v);
382+ aluShifted(1, op, rd, rn, X16, shLsl, 0);
383+ end;
384+end;
385+
386+(* rd := rn, by orr of the zero register; by add of 0 when either is sp *)
387+proc movRR*(rd, rn: INT);
388+begin
389+ if (rd = SP) or (rn = SP) then addImm(1, opAdd, rd, rn, 0, 0); else aluShifted(1, opOrr, rd, ZR, rn, shLsl, 0); end;
390+end;
391+
392+(* the flags of rn - rm; and of rn - v, where rn 31 is sp *)
393+proc cmp*(rn, rm: INT);
394+begin
395+ aluShifted(1, opSubs, ZR, rn, rm, shLsl, 0);
396+end;
397+
398+proc cmpI*(rn: INT; v: I64);
399+begin
400+ aluI(opSubs, ZR, rn, v);
401+end;
402+
403+(* neg: sub from the zero register; mvn: orn of it *)
404+proc neg*(rd, rm: INT);
405+begin
406+ aluShifted(1, opSub, rd, ZR, rm, shLsl, 0);
407+end;
408+
409+proc mvn*(rd, rm: INT);
410+begin
411+ aluShifted(1, opOrn, rd, ZR, rm, shLsl, 0);
412+end;
413+
414+(* Shifts and bit fields *)
415+
416+(* sbfm, bfm or ubfm (opc 0, 1, 2): sf opc 100110 N immr imms Rn Rd, N
417+ as sf. The bits imms down to immr of rn, or, if imms < immr, the low
418+ imms + 1 bits put at width - immr; the rest of rd is the sign, kept,
419+ or zeros. Every shift by a constant, extension and field is one. *)
420+proc bitfield(sf, opc, rd, rn, immr, imms: INT);
421+const Names: [3][]const U8 = ["sbfm", "bfm", "ubfm"];
422+begin
423+ if listing then sayOps(Names[opc], [reg(rd, sf, false), reg(rn, sf, false), imm(immr), imm(imms)]); end;
424+ emit((sf shl 31) | (opc shl 29) | 13000000H | (sf shl 22) | (immr shl 16) | (imms shl 10) | (rn shl 5) | rd);
425+end;
426+
427+(* A shift by n, 0 to the width less one, of size 4 or 8 bytes: lsl is
428+ ubfm by width - n of the low width - 1 - n bits, lsr ubfm and asr
429+ sbfm of the bits from n up, ror extr of rn and rn from bit n:
430+ sf 00 100111 N 0 Rm imms Rn Rd *)
431+proc shiftI*(op, rd, rn, n, size: INT);
432+var sf, w: INT;
433+begin
434+ sf := bit(size = 8); w := 32 + 32 * sf;
435+ match op of
436+ | shLsl: bitfield(sf, 2, rd, rn, (w - n) & (w - 1), w - 1 - n);
437+ | shLsr: bitfield(sf, 2, rd, rn, n, w - 1);
438+ | shAsr: bitfield(sf, 0, rd, rn, n, w - 1);
439+ | else:
440+ if listing then sayOps("ror", [reg(rd, sf, false), reg(rn, sf, false), imm(n)]); end;
441+ emit((sf shl 31) | 13800000H | (sf shl 22) | (rn shl 16) | (n shl 10) | (rn shl 5) | rd);
442+ end;
443+end;
444+
445+(* rd := the width bits of rn from bit lsb, as ubfx, or sbfx if signed:
446+ ubfm or sbfm of the bits lsb + width - 1 down to lsb *)
447+proc field*(signed: BOOL; rd, rn, lsb, width: INT);
448+begin
449+ bitfield(1, 2 - 2 * bit(signed), rd, rn, lsb, lsb + width - 1);
450+end;
451+
452+(* rd := the low size bytes of rn, brought to 64 bits by their sign or
453+ zeros: sxtb, sxth, sxtw (sbfm, 64 bits); uxtb and uxth (ubfm, 32 bits,
454+ which zeroes the upper half), mov wd, wn for 4 *)
455+proc extend*(rd, rn, size: INT; signed: BOOL);
456+begin
457+ if signed then
458+ bitfield(1, 0, rd, rn, 0, size * 8 - 1);
459+ elsif size < 4 then
460+ bitfield(0, 2, rd, rn, 0, size * 8 - 1);
461+ else
462+ aluShifted(0, opOrr, rd, ZR, rn, shLsl, 0);
463+ end;
464+end;
465+
466+(* The instructions of only registers, each its bits and n registers,
467+ Rd, Rn, Rm and Ra, in their places; a field an instruction hasn't is
468+ 0, or set in its bits:
469+ madd, msub sf 00 11011 000 Rm o0 Ra Rn Rd rd := ra + rn * rm, ra - rn * rm
470+ smulh, umulh 1 00 11011 U10 Rm 0 11111 Rn Rd the high 64 bits of the product
471+ sdiv, udiv sf 0 0 11010110 Rm 00001 o1 Rn Rd
472+ lslv ... rorv sf 0 0 11010110 Rm 0010 op2 Rn Rd by rm, modulo the width
473+ clz, rbit, rev sf 1 0 11010110 00000 0000 opc Rn Rd
474+ A division by zero gives 0, and the smallest value by -1 itself: Gen
475+ checks for both. *)
476+proc regOp(name: []const U8; n, sf, bits, rd, rn, rm, ra: INT);
477+var t: [4][]const U8;
478+begin
479+ if listing then
480+ t := [reg(rd, sf, false), reg(rn, sf, false), reg(rm, sf, false), reg(ra, sf, false)];
481+ sayOps(name, t[0..n]);
482+ end;
483+ emit((sf shl 31) | bits | (rm shl 16) | (ra shl 10) | (rn shl 5) | rd);
484+end;
485+
486+proc mul*(rd, rn, rm: INT);
487+begin
488+ regOp("mul", 3, 1, 1B007C00H, rd, rn, rm, 0);
489+end;
490+
491+(* rd := ra + rn * rm, or ra - rn * rm if sub *)
492+proc madd*(rd, rn, rm, ra: INT; sub: BOOL);
493+const Names: [2][]const U8 = ["madd", "msub"];
494+begin
495+ regOp(Names[bit(sub)], 4, 1, 1B000000H | (bit(sub) shl 15), rd, rn, rm, ra);
496+end;
497+
498+proc mulHigh*(signed: BOOL; rd, rn, rm: INT);
499+const Names: [2][]const U8 = ["umulh", "smulh"];
500+begin
501+ regOp(Names[bit(signed)], 3, 1, 1B407C00H | (bit(not signed) shl 23), rd, rn, rm, 0);
502+end;
503+
504+proc divide*(signed: BOOL; rd, rn, rm: INT);
505+const Names: [2][]const U8 = ["udiv", "sdiv"];
506+begin
507+ regOp(Names[bit(signed)], 3, 1, 1AC00800H | (bit(signed) shl 10), rd, rn, rm, 0);
508+end;
509+
510+(* lsl, lsr, asr or ror of size 4 or 8 bytes, by rm *)
511+proc shift*(op, rd, rn, rm, size: INT);
512+begin
513+ regOp(ShiftNames[op], 3, bit(size = 8), 1AC02000H | (op shl 10), rd, rn, rm, 0);
514+end;
515+
516+(* the leading zeros of rn, of size 4 or 8 bytes: 64 for 0; and rn's
517+ bits in the opposite order, of which clz counts trailing zeros *)
518+proc clz*(rd, rn, size: INT);
519+begin
520+ regOp("clz", 2, bit(size = 8), 5AC01000H, rd, rn, 0, 0);
521+end;
522+
523+proc rbit*(rd, rn, size: INT);
524+begin
525+ regOp("rbit", 2, bit(size = 8), 5AC00000H, rd, rn, 0, 0);
526+end;
527+
528+(* csel, csinc, csinv or csneg (op), on condition cc:
529+ sf op 0 11010100 Rm cond 0 o2 Rn Rd *)
530+proc condSel(sf, op, cc, rd, rn, rm: INT);
531+begin
532+ if listing then sayOps(CselNames[op], [reg(rd, sf, false), reg(rn, sf, false), reg(rm, sf, false), CondNames[cc]]); end;
533+ emit((sf shl 31) | CselBits[op] | (rm shl 16) | (cc shl 12) | (rn shl 5) | rd);
534+end;
535+
536+proc csel*(op, cc, rd, rn, rm: INT);
537+begin
538+ condSel(1, op, cc, rd, rn, rm);
539+end;
540+
541+(* rd := 1 if cc holds, else 0: cset, csinc of the zero register on the
542+ opposite condition *)
543+proc cset*(cc, rd: INT);
544+begin
545+ condSel(1, csInc, invert(cc), rd, ZR, ZR);
546+end;
547+
548+(* Loads and stores. ldst and its kin make them all from the bits that
549+ tell size, register file and operation, (size << 30 | V << 26 | opc
550+ << 22), and the form:
551+ unsigned offset size 111 V 01 opc imm12 Rn Rt, imm12 = off / size
552+ unscaled size 111 V 00 opc 0 imm9 00 Rn Rt (ldur, stur)
553+ post-index size 111 V 00 opc 0 imm9 01 Rn Rt
554+ pre-index size 111 V 00 opc 0 imm9 11 Rn Rt
555+ register size 111 V 00 opc 1 Rm option S 10 Rn Rt
556+ Rn 31 is sp; Rt 31 is the zero register. *)
557+
558+(* The bits of a load (or store) of size bytes; signed sign-extends to
559+ 64 bits (to 32 if sf is 0), fp is a real's register. For an integer
560+ opc is 00 store, 01 load, 10 load signed to x, 11 load signed to w;
561+ for a real the same but q, 16 bytes, which is size 00 and opc 1x. *)
562+proc ldstBits(size: INT; load, signed, fp: BOOL; sf: INT): INT;
563+begin
564+ if fp and (size = 16) then return 04000000H | ((2 + bit(load)) shl 22); end;
565+ if fp then return (scaleOf(size) shl 30) | 04000000H | (bit(load) shl 22); end;
566+ if signed and (size < 8) then return (scaleOf(size) shl 30) | ((3 - sf) shl 22); end;
567+ return (scaleOf(size) shl 30) | (bit(load) shl 22);
568+end;
569+
570+(* The size of the load or store with these bits, 16 for q *)
571+proc sizeOf(bits: INT): INT;
572+begin
573+ if (bits & 04800000H) = 04800000H then return 16; end;
574+ return 1 shl INT(bits shr 30);
575+end;
576+
577+(* The text of a load or store, its name from its bits (ldrsh, sturb,
578+ ...), its register's and its address m *)
579+proc sayLdst(bits, rt: INT; unscaled: BOOL; m: []const U8);
580+const Sizes: [4][]const U8 = ["b", "h", "w", ""];
581+var opc: INT; s, r: []const U8;
582+begin
583+ opc := (bits shr 22) & 3;
584+ if (opc & 1) = 0 then s := "str"; else s := "ldr"; end;
585+ if unscaled then s := Diag.say("{}ur", [Fmt.str(s[0..2])]); end;
586+ if (bits & 04000000H) # 0 then
587+ r := vreg(rt, sizeOf(bits));
588+ else
589+ r := reg(rt, bit((opc = 2) or (bits shr 30 = 3)), false);
590+ if opc >= 2 then s := Diag.say("{}s", [Fmt.str(s)]); end;
591+ if (opc >= 2) or (bits shr 30 < 2) then s := Diag.say("{}{}", [Fmt.str(s), Fmt.str(Sizes[bits shr 30])]); end;
592+ end;
593+ sayOps(s, [r, m]);
594+end;
595+
596+(* rt at [rn, rm], or [rn, rm, lsl #scale] if scaled: option 011, S *)
597+proc ldstReg(bits, rt, rn, rm: INT; scaled: BOOL);
598+begin
599+ if listing then sayLdst(bits, rt, false, Diag.say("[{}, {}, lsl #{}]", [Fmt.str(xsp(rn)), Fmt.str(x(rm)), Fmt.int(bit(scaled) * scaleOf(sizeOf(bits)))])); end;
600+ emit(38206800H | bits | (rm shl 16) | (bit(scaled) shl 12) | (rn shl 5) | rt);
601+end;
602+
603+(* rt at [rn, #off]: by its unsigned offset if off is a multiple of the
604+ size below 4096 of them, else unscaled if off is in -256 to 255; else
605+ off is built in x16 for the register form *)
606+proc ldst(bits, rt, rn, off: INT);
607+var sc: INT;
608+begin
609+ sc := scaleOf(sizeOf(bits));
610+ if (off >= 0) and ((off & ((1 shl sc) - 1)) = 0) and ((off shr sc) < 4096) then
611+ if listing then sayLdst(bits, rt, false, memText(rn, off, mOff)); end;
612+ emit(39000000H | bits | ((off shr sc) shl 10) | (rn shl 5) | rt);
613+ elsif (off >= -256) and (off <= 255) then
614+ if listing then sayLdst(bits, rt, true, memText(rn, off, mOff)); end;
615+ emit(38000000H | bits | ((off & 1FFH) shl 12) | (rn shl 5) | rt);
616+ else
617+ movRI(X16, off);
618+ ldstReg(bits, rt, rn, X16, false);
619+ end;
620+end;
621+
622+(* rt at [rn, #off]!, rn changed first, or [rn], #off, after; off in
623+ -256 to 255 *)
624+proc ldstIdx(bits, rt, rn, off, mode: INT);
625+begin
626+ if (off < -256) or (off > 255) then _ := Scan.mark("an index beyond -256 to 255"); end;
627+ if listing then sayLdst(bits, rt, false, memText(rn, off, mode)); end;
628+ emit(38000000H | bits | ((off & 1FFH) shl 12) | ((2 * bit(mode = mPre) + 1) shl 10) | (rn shl 5) | rt);
629+end;
630+
631+(* rt := the size bytes at [rn, #off], 1, 2, 4 or 8, by their sign or
632+ zeros; and the store *)
633+proc load*(rt, rn, off, size: INT; signed: BOOL);
634+begin
635+ ldst(ldstBits(size, true, signed, false, 1), rt, rn, off);
636+end;
637+
638+proc store*(rt, rn, off, size: INT);
639+begin
640+ ldst(ldstBits(size, false, false, false, 1), rt, rn, off);
641+end;
642+
643+(* [rn + rm], or [rn + rm * size] if scaled *)
644+proc loadR*(rt, rn, rm, size: INT; signed, scaled: BOOL);
645+begin
646+ ldstReg(ldstBits(size, true, signed, false, 1), rt, rn, rm, scaled);
647+end;
648+
649+proc storeR*(rt, rn, rm, size: INT; scaled: BOOL);
650+begin
651+ ldstReg(ldstBits(size, false, false, false, 1), rt, rn, rm, scaled);
652+end;
653+
654+(* with rn changed, mPre or mPost, as a push is str x0, [sp, #-16]! *)
655+proc loadIdx*(rt, rn, off, size, mode: INT);
656+begin
657+ ldstIdx(ldstBits(size, true, false, false, 1), rt, rn, off, mode);
658+end;
659+
660+proc storeIdx*(rt, rn, off, size, mode: INT);
661+begin
662+ ldstIdx(ldstBits(size, false, false, false, 1), rt, rn, off, mode);
663+end;
664+
665+(* A real's register, of size 4, 8 or 16 *)
666+proc loadF*(vt, rn, off, size: INT);
667+begin
668+ ldst(ldstBits(size, true, false, true, 1), vt, rn, off);
669+end;
670+
671+proc storeF*(vt, rn, off, size: INT);
672+begin
673+ ldst(ldstBits(size, false, false, true, 1), vt, rn, off);
674+end;
675+
676+(* ldp and stp: two registers at [rn, #off], off a multiple of the size
677+ in -64 to 63 of them: opc 101 V mode L imm7 Rt2 Rn Rt, opc 00 for w or
678+ s, 10 for x, 01 for d, 10 for q *)
679+proc pair(load, fp: BOOL; size, rt, rt2, rn, off, mode: INT);
680+const Names: [2][]const U8 = ["stp", "ldp"];
681+var opc: INT;
682+begin
683+ if fp then opc := scaleOf(size) - 2; else opc := 2 * bit(size = 8); end;
684+ if ((off & (size - 1)) # 0) or (off < -64 * size) or (off > 63 * size) then
685+ _ := Scan.mark("a pair's offset beyond -64 to 63 of its size");
686+ end;
687+ if listing then sayOps(Names[bit(load)], [x(rt), x(rt2), memText(rn, off, mode)]); end;
688+ emit((opc shl 30) | 28000000H | (bit(fp) shl 26) | (mode shl 23) | (bit(load) shl 22)
689+ | (((off div size) & 7FH) shl 15) | (rt2 shl 10) | (rn shl 5) | rt);
690+end;
691+
692+proc ldp*(rt, rt2, rn, off, mode: INT);
693+begin
694+ pair(true, false, 8, rt, rt2, rn, off, mode);
695+end;
696+
697+proc stp*(rt, rt2, rn, off, mode: INT);
698+begin
699+ pair(false, false, 8, rt, rt2, rn, off, mode);
700+end;
701+
702+(* Atomics, by the LSE instructions every Apple processor has, of size 4
703+ or 8 bytes, each with acquire and release, so sequentially consistent:
704+ ldaddal rs, rt, [rn] size 111 0 00 1 1 1 Rs 0 000 00 Rn Rt: rt := [rn], [rn] += rs
705+ swpal rs, rt, [rn] size 111 0 00 1 1 1 Rs 1 000 00 Rn Rt: rt := [rn], [rn] := rs
706+ casal rs, rt, [rn] size 001000 1 1 1 Rs 1 11111 Rn Rt: if [rn] = rs, [rn] := rt; rs := old [rn]
707+ The assembler knows the exclusive pair too, for a loop of its own:
708+ ldaxr rt, [rn] size 001000 0 1 0 11111 1 11111 Rn Rt
709+ stlxr ws, rt, [rn] size 001000 0 0 0 Rs 1 11111 Rn Rt, ws 0 if it stored *)
710+const
711+ AtomNames: [5][]const U8 = ["ldaddal", "swpal", "casal", "ldaxr", "stlxr"];
712+ AtomBits: [5]INT = [38E00000H, 38E08000H, 08E0FC00H, 085FFC00H, 0800FC00H];
713+
714+proc atomic(op, size, rs, rt, rn: INT);
715+begin
716+ if listing then sayOps(AtomNames[op], [reg(rs, bit(size = 8), false), reg(rt, bit(size = 8), false), memText(rn, 0, mOff)]); end;
717+ emit(80000000H | (bit(size = 8) shl 30) | AtomBits[op] | (rs shl 16) | (rn shl 5) | rt);
718+end;
719+
720+proc ldaddal*(rs, rt, rn, size: INT);
721+begin
722+ atomic(0, size, rs, rt, rn);
723+end;
724+
725+proc swpal*(rs, rt, rn, size: INT);
726+begin
727+ atomic(1, size, rs, rt, rn);
728+end;
729+
730+proc casal*(rs, rt, rn, size: INT);
731+begin
732+ atomic(2, size, rs, rt, rn);
733+end;
734+
735+(* The rest of the system's: a barrier, the inner shareable domain's,
736+ which is every processor's (dmb ish, 1101010100 0 00 011 0011 CRm 1 01
737+ 11111, CRm 1011); a call of the system, svc #imm; a trap, brk #imm *)
738+proc dmb*;
739+begin
740+ if listing then say("dmb ish"); end;
741+ emit(0D5033BBFH);
742+end;
743+
744+proc svc*(n: INT);
745+begin
746+ if listing then sayOps("svc", [imm(n)]); end;
747+ emit(0D4000001H | ((n & 0FFFFH) shl 5));
748+end;
749+
750+proc brk*(n: INT);
751+begin
752+ if listing then sayOps("brk", [imm(n)]); end;
753+ emit(0D4200000H | ((n & 0FFFFH) shl 5));
754+end;
755+
756+(* Code made up to a multiple of n bytes with nop *)
757+proc align*(n: INT);
758+begin
759+ while Chunk.pc mod n # 0 do
760+ if listing then say("nop"); end;
761+ emit(Nop);
762+ end;
763+end;
764+
765+(* Reals: type 00 is single, an F32, 01 double *)
766+
767+(* fmul, fdiv, fadd, fsub, fmax and fmin, vd := vn op vm:
768+ 0 0 0 11110 type 1 Rm opcode 10 Rn Rd *)
769+proc fop*(op, vd, vn, vm: INT; single: BOOL);
770+var s: INT;
771+begin
772+ s := 8 - 4 * bit(single);
773+ if listing then sayOps(FopNames[op], [vreg(vd, s), vreg(vn, s), vreg(vm, s)]); end;
774+ emit(1E200800H | (bit(not single) shl 22) | (vm shl 16) | (op shl 12) | (vn shl 5) | vd);
775+end;
776+
777+(* fmov, fabs, fneg and fsqrt, of one register:
778+ 0 0 0 11110 type 1 opcode 10000 Rn Rd *)
779+proc fop1*(op, vd, vn: INT; single: BOOL);
780+var s: INT;
781+begin
782+ s := 8 - 4 * bit(single);
783+ if listing then sayOps(Fop1Names[op], [vreg(vd, s), vreg(vn, s)]); end;
784+ emit(1E204000H | (bit(not single) shl 22) | (op shl 15) | (vn shl 5) | vd);
785+end;
786+
787+(* vd := vn converted, to an F32 if toSingle, else to an F64: fop1's form
788+ with opcode 0001, then the type made, 00 single or 01 double *)
789+proc fcvt*(vd, vn: INT; toSingle: BOOL);
790+begin
791+ if listing then sayOps("fcvt", [vreg(vd, 8 - 4 * bit(toSingle)), vreg(vn, 4 + 4 * bit(toSingle))]); end;
792+ emit(1E204000H | (bit(toSingle) shl 22) | ((5 - bit(toSingle)) shl 15) | (vn shl 5) | vd);
793+end;
794+
795+(* fcmp vn, vm, or vn with 0.0 if vm < 0: the flags as an unsigned
796+ compare sets them, but for unordered (a NaN), which is C and V:
797+ 0 0 0 11110 type 1 Rm 00 1000 Rn 0 opc 000, opc 01 for 0.0 *)
798+proc fcmp*(vn, vm: INT; single: BOOL);
799+var s: INT;
800+begin
801+ s := 8 - 4 * bit(single);
802+ if vm < 0 then
803+ if listing then sayOps("fcmp", [vreg(vn, s), "#0.0"]); end;
804+ emit(1E202008H | (bit(not single) shl 22) | (vn shl 5));
805+ else
806+ if listing then sayOps("fcmp", [vreg(vn, s), vreg(vm, s)]); end;
807+ emit(1E202000H | (bit(not single) shl 22) | (vm shl 16) | (vn shl 5));
808+ end;
809+end;
810+
811+(* Between the register files: sf 0 0 11110 type 1 rmode opcode 000000
812+ Rn Rd, the real of size 4 or 8 bytes, to it if toFp. rmode 00 opcode
813+ 010 scvtf, 011 ucvtf, 110 fmov to a general register, 111 fmov from
814+ one; rmode 11 opcode 000 fcvtzs, 001 fcvtzu, which round toward zero *)
815+proc fconv(name: []const U8; sf, size, rmode, opcode, rd, rn: INT; toFp: BOOL);
816+begin
817+ if listing and toFp then sayOps(name, [vreg(rd, size), reg(rn, sf, false)]); end;
818+ if listing and not toFp then sayOps(name, [reg(rd, sf, false), vreg(rn, size)]); end;
819+ emit((sf shl 31) | 1E200000H | (bit(size = 8) shl 22) | (rmode shl 19) | (opcode shl 16) | (rn shl 5) | rd);
820+end;
821+
822+(* vd := the 64-bit integer in rn, signed or not, as a real *)
823+proc scvtf*(vd, rn: INT; single, signed: BOOL);
824+const Names: [2][]const U8 = ["ucvtf", "scvtf"];
825+begin
826+ fconv(Names[bit(signed)], 1, 8 - 4 * bit(single), 0, 3 - bit(signed), vd, rn, true);
827+end;
828+
829+(* rd := vn toward zero as a 64-bit integer; out of range it is the
830+ nearest, and a NaN 0, where x86 gives the smallest I64: Gen mends it *)
831+proc fcvtz*(rd, vn: INT; single, signed: BOOL);
832+const Names: [2][]const U8 = ["fcvtzu", "fcvtzs"];
833+begin
834+ fconv(Names[bit(signed)], 1, 8 - 4 * bit(single), 3, bit(not signed), rd, vn, false);
835+end;
836+
837+(* The bits of a real between the files: s and w, d and x *)
838+proc fmovFR*(vd, rn: INT; single: BOOL);
839+begin
840+ fconv("fmov", bit(not single), 8 - 4 * bit(single), 0, 7, vd, rn, true);
841+end;
842+
843+proc fmovRF*(rd, vn: INT; single: BOOL);
844+begin
845+ fconv("fmov", bit(not single), 8 - 4 * bit(single), 0, 6, rd, vn, false);
846+end;
847+
848+(* Addresses, and references to other chunks *)
849+
850+(* rd := the address of this instruction plus off, within 1 MB (adr),
851+ or its page of 4 KB plus off pages (adrp): op immlo 10000 immhi Rd *)
852+proc adrOp(page, rd, off: INT);
853+begin
854+ emit((page shl 31) | 10000000H | ((off & 3) shl 29) | (((off shr 2) & 7FFFFH) shl 5) | rd);
855+end;
856+
857+proc adr*(rd, off: INT);
858+begin
859+ if listing then sayOps("adr", [x(rd), Diag.say(". + {}", [Fmt.int(off)])]); end;
860+ adrOp(0, rd, off);
861+end;
862+
863+(* adrp rd with a fixup to the page of chunk c plus addend *)
864+proc adrpChunk(rd, c, addend: INT);
865+begin
866+ if listing then sayOps("adrp", [x(rd), Diag.say("{}@PAGE", [Fmt.str(Chunk.chunkName(c))])]); end;
867+ Chunk.addKindFixup(Chunk.pc, c, addend, Chunk.fxPage21);
868+ adrOp(1, rd, 0);
869+end;
870+
871+(* rd := the address of chunk c plus addend, wherever the linker puts
872+ it, since macOS loads a program anywhere: adrp of its page, then add
873+ of its place in the page, each with its fixup *)
874+proc addrChunk*(rd, c, addend: INT);
875+begin
876+ adrpChunk(rd, c, addend);
877+ if listing then sayOps("add", [x(rd), x(rd), Diag.say("{}@PAGEOFF", [Fmt.str(Chunk.chunkName(c))])]); end;
878+ Chunk.addKindFixup(Chunk.pc, c, addend, Chunk.fxPageOff12);
879+ emit(91000000H | (rd shl 5) | rd);
880+end;
881+
882+(* A load or store of the bits ldstBits gives at chunk c plus addend:
883+ adrp x16, then the load's or store's unsigned offset is the place in
884+ the page, divided by the size, which the linker reads from the
885+ instruction, as Apple's linker does for ARM64_RELOC_PAGEOFF12. That
886+ offset must then be a multiple of the size: when the chunk's
887+ alignment doesn't make it one, the address is made whole first. As a
888+ C symbol's quadword is read: loadChunk(rt, externChunk(name), 0, 8). *)
889+proc chunkMem(bits, rt, c, addend: INT);
890+begin
891+ if ((addend & (sizeOf(bits) - 1)) # 0) or (Chunk.chunks[c].align < sizeOf(bits)) then
892+ addrChunk(X16, c, addend);
893+ ldst(bits, rt, X16, 0);
894+ return;
895+ end;
896+ adrpChunk(X16, c, addend);
897+ if listing then sayLdst(bits, rt, false, Diag.say("[x16, {}@PAGEOFF]", [Fmt.str(Chunk.chunkName(c))])); end;
898+ Chunk.addKindFixup(Chunk.pc, c, addend, Chunk.fxPageOff12);
899+ emit(39000000H | bits | (X16 shl 5) | rt);
900+end;
901+
902+proc loadChunk*(rt, c, addend, size: INT; signed: BOOL);
903+begin
904+ chunkMem(ldstBits(size, true, signed, false, 1), rt, c, addend);
905+end;
906+
907+proc storeChunk*(rt, c, addend, size: INT);
908+begin
909+ chunkMem(ldstBits(size, false, false, false, 1), rt, c, addend);
910+end;
911+
912+proc loadChunkF*(vt, c, addend, size: INT);
913+begin
914+ chunkMem(ldstBits(size, true, false, true, 1), vt, c, addend);
915+end;
916+
917+proc storeChunkF*(vt, c, addend, size: INT);
918+begin
919+ chunkMem(ldstBits(size, false, false, true, 1), vt, c, addend);
920+end;
921+
922+(* bl or b to the start of chunk c, a fixup: 1 00101 imm26 for bl, 0
923+ 00101 for b, imm26 the distance in words, within 128 MB *)
924+proc branchChunk(call: BOOL; c: INT);
925+const Names: [2][]const U8 = ["b", "bl"];
926+begin
927+ if listing then sayOps(Names[bit(call)], [Chunk.chunkName(c)]); end;
928+ Chunk.addKindFixup(Chunk.pc, c, 0, Chunk.fxBranch26);
929+ emit(14000000H | (bit(call) shl 31));
930+end;
931+
932+proc callChunk*(c: INT);
933+begin
934+ branchChunk(true, c);
935+end;
936+
937+(* a tail call *)
938+proc jmpChunk*(c: INT);
939+begin
940+ branchChunk(false, c);
941+end;
942+
943+(* bl to target, a place in text already written *)
944+proc callBack*(target: INT);
945+begin
946+ if listing then say("bl ->"); end;
947+ emit(94000000H | (((target - Chunk.pc) div 4) & 3FFFFFFH));
948+end;
949+
950+(* blr, br and ret, to the address in rn:
951+ 1101011 0 0 opc 11111 000000 Rn 00000, opc 01 blr, 00 br, 10 ret *)
952+proc callR*(rn: INT);
953+begin
954+ if listing then sayOps("blr", [x(rn)]); end;
955+ emit(0D63F0000H | (rn shl 5));
956+end;
957+
958+proc jmpR*(rn: INT);
959+begin
960+ if listing then sayOps("br", [x(rn)]); end;
961+ emit(0D61F0000H | (rn shl 5));
962+end;
963+
964+proc ret*;
965+begin
966+ if listing then say("ret"); end;
967+ emit(0D65F03C0H);
968+end;
969+
970+(* Jumps within a procedure. A label not yet placed is the chain of the
971+ jumps to it, as in X64, each jump's offset field holding the place
972+ of the one before, in words from the start of the procedure's chunk,
973+ plus one: 0 ends the chain. Placing the label walks the chain and
974+ puts each jump's distance in its field. The fields are of three
975+ widths:
976+ b, bl 0 00101 imm26 within 128 MB
977+ b.cond 0101010 0 imm19 0 cond within 1 MB
978+ cbz, cbnz sf 011010 op imm19 Rt within 1 MB
979+ tbz, tbnz b5 011011 op b40 imm14 Rt within 32 KB
980+ A b.cond or a cbz reaches 1 MB, a procedure of a quarter of a million
981+ instructions; past that the compile ends with an error, rather than
982+ make every conditional jump two instructions for a procedure no one
983+ writes. A tbz reaches only 32 KB, which a long procedure passes: so
984+ Gen's tbz is the opposite tbz over a b, which reaches as far as any b
985+ (tbz below); only the assembler's tbz is one instruction, in a code
986+ procedure that is never that long. *)
987+
988+(* Where the offset field of the branch insn is, its lowest bit and its
989+ width *)
990+proc fieldOf(insn: INT): (INT, INT);
991+begin
992+ if (insn & 7C000000H) = 14000000H then return 0, 26; end;
993+ if (insn & 7E000000H) = 36000000H then return 5, 14; end;
994+ return 5, 19;
995+end;
996+
997+(* The jump before the one at L on its chain, from the link in its field *)
998+proc before(L: INT): INT;
999+var insn, lo, w, prev: INT;
1000+begin
1001+ insn := Chunk.get4At(L) & 0FFFFFFFFH;
1002+ lo, w := fieldOf(insn);
1003+ prev := (insn shr lo) & ((1 shl w) - 1);
1004+ if prev = 0 then return NoLabel; end;
1005+ return Chunk.chunks[Chunk.curChunk].start + (prev - 1) * 4;
1006+end;
1007+
1008+(* insn with its field set: to the distance d in words if back, else to
1009+ the link to the jump at d, or to none if d is NoLabel; either must fit *)
1010+proc withField(insn, d: INT; back: BOOL): INT;
1011+var lo, w: INT;
1012+begin
1013+ lo, w := fieldOf(insn);
1014+ if not back and (d = NoLabel) then
1015+ d := 0;
1016+ elsif not back then
1017+ d := (d - Chunk.chunks[Chunk.curChunk].start) div 4 + 1;
1018+ end;
1019+ if back and ((d < -(1 shl (w - 1))) or (d >= (1 shl (w - 1)))) or not back and (d >= (1 shl w)) then
1020+ _ := Scan.mark("a jump within a procedure beyond what its instruction reaches (b.cond and cbz: 1 MB)");
1021+ end;
1022+ return (insn & ~(((1 shl w) - 1) shl lo)) | ((d & ((1 shl w) - 1)) shl lo);
1023+end;
1024+
1025+(* insn, a branch to L: back to the place L if back, else on L's chain;
1026+ the chain's new first jump *)
1027+proc branch(insn, L: INT; back: BOOL): INT;
1028+begin
1029+ if back then emit(withField(insn, (L - Chunk.pc) div 4, true)); return L; end;
1030+ emit(withField(insn, L, false));
1031+ return Chunk.pc - 4;
1032+end;
1033+
1034+proc jmp*(var L: INT);
1035+begin
1036+ if listing then say("b ->"); end;
1037+ L := branch(14000000H, L, false);
1038+end;
1039+
1040+proc jcc*(cc: INT; var L: INT);
1041+begin
1042+ if listing then say(Diag.say("b.{} ->", [Fmt.str(CondNames[cc])])); end;
1043+ L := branch(54000000H | cc, L, false);
1044+end;
1045+
1046+(* to L if the 64 bits of r are zero (cbz), or not (cbnz) *)
1047+proc cbz*(nonzero: BOOL; r: INT; var L: INT);
1048+const Names: [2][]const U8 = ["cbz", "cbnz"];
1049+begin
1050+ if listing then sayOps(Names[bit(nonzero)], [x(r), "->"]); end;
1051+ L := branch(0B4000000H | (bit(nonzero) shl 24) | r, L, false);
1052+end;
1053+
1054+(* to L if bit b of r is zero (tbz) or one (tbnz): the opposite test
1055+ over the next instruction, a b to L: b5 011011 op b40 imm14 Rt, b's
1056+ number split as b5 and b40, imm14 2 *)
1057+proc tbz*(nonzero: BOOL; r, b: INT; var L: INT);
1058+const Names: [2][]const U8 = ["tbnz", "tbz"];
1059+begin
1060+ if listing then sayOps(Names[bit(nonzero)], [x(r), imm(b), ". + 8"]); end;
1061+ emit(36000000H | (bit(not nonzero) shl 24) | ((b shr 5) shl 31) | ((b & 31) shl 19) | (2 shl 5) | r);
1062+ jmp(L);
1063+end;
1064+
1065+proc jmpBack*(target: INT);
1066+begin
1067+ if listing then say("b ->"); end;
1068+ _ := branch(14000000H, target, true);
1069+end;
1070+
1071+proc jccBack*(cc, target: INT);
1072+begin
1073+ if listing then say(Diag.say("b.{} ->", [Fmt.str(CondNames[cc])])); end;
1074+ _ := branch(54000000H | cc, target, true);
1075+end;
1076+
1077+proc fixLinkTo*(L, target: INT);
1078+var next: INT;
1079+begin
1080+ while L # NoLabel do
1081+ next := before(L);
1082+ Chunk.put4At(L, withField(Chunk.get4At(L) & 0FFFFFFFFH, (target - L) div 4, true));
1083+ L := next;
1084+ end;
1085+end;
1086+
1087+proc fixLink*(L: INT);
1088+begin
1089+ if L # NoLabel then labelAt := Chunk.pc; end;
1090+ fixLinkTo(L, Chunk.pc);
1091+end;
1092+
1093+(* If the last instruction made is a b to L, it is taken back, as in
1094+ X64: L is that b when it is the last word and an unconditional b
1095+ (000101 in the top bits), and no jump was fixed to just after it.
1096+ L becomes the jump before it on the chain. *)
1097+proc dropJumpTo*(var L: INT);
1098+begin
1099+ if (L = NoLabel) or (L # Chunk.pc - 4) or (labelAt = Chunk.pc) or ((Chunk.get4At(L) & 0FC000000H) # 14000000H) then return; end;
1100+ L := before(L);
1101+ Chunk.takeBack(4);
1102+ if listing and (numSaid > 0) and (said[numSaid - 1].at = Chunk.pc) then DEC(numSaid); end;
1103+end;
1104+
1105+(* The jumps of chains L1 and L2, as one chain: the last of L2's links to
1106+ L1's first *)
1107+proc joinLinks*(L1, L2: INT): INT;
1108+var L: INT;
1109+begin
1110+ if L2 = NoLabel then return L1; end;
1111+ if L1 # NoLabel then
1112+ L := L2;
1113+ while before(L) # NoLabel do L := before(L); end;
1114+ Chunk.put4At(L, withField(Chunk.get4At(L) & 0FFFFFFFFH, L1, false));
1115+ end;
1116+ return L2;
1117+end;
1118+
1119+(* The assembler, for code procedures: arm64 in Arm's syntax, as its
1120+ reference manual writes it, destination first (report, appendix A):
1121+ `add x0, x1, #16;`, `ldr w2, [x0, #4];`, `stp x29, x30, [sp, #-16]!;`,
1122+ `b.ne loop;`. The # before an immediate may be left out; numbers are
1123+ raz's, 10H and not 0x10, and a constant of the module stands where a
1124+ number does. A procedure or a module variable stands for its address
1125+ in `bl p`, `b p` and `adr xN, v`, the last made as adrp and add, two
1126+ instructions, since the variable may lie beyond adr's 1 MB. It reads
1127+ instructions with the scanner up to end, as X64's assembler does, and
1128+ encodes them with the routines above, the listing off: an immediate
1129+ or offset out of an instruction's range is an error here, where Gen's
1130+ routines build it in x16. *)
1131+
1132+const
1133+ NameOnly = "a procedure or a variable stands for its address only in bl p, b p and adr r, v";
1134+
1135+type
1136+ OpKind = (oReg, oFp, oImm, oMem, oShift, oName, oLabel, oWord);
1137+ Operand = record
1138+ kind: OpKind;
1139+ r, sf: INT; (* oReg: the register, and 1 for x, 0 for w; oFp, oMem: the register *)
1140+ sp: BOOL; (* oReg: 31 written sp or wsp, not xzr or wzr *)
1141+ size: INT; (* oFp: 4, 8 or 16 *)
1142+ v: I64; (* oImm; oShift: the amount; oMem: the offset, or the index's shift *)
1143+ sh: INT; (* oShift: lsl, lsr, asr or ror *)
1144+ index, mode: INT; (* oMem: an index register or -1, mOff, mPre or mPost *)
1145+ scaled: BOOL; (* oMem: the index shifted by lsl *)
1146+ c: INT; (* oName: the chunk; oLabel: the label *)
1147+ w: []const U8; (* oWord: a condition or a barrier's option *)
1148+ at: Diag.Pos;
1149+ end;
1150+
1151+var
1152+ (* the labels of the procedure *)
1153+ lnames, lplaces, lchains: [64]INT;
1154+ lusedAt: [64]Diag.Pos;
1155+ numLabels: INT;
1156+ (* the instruction being assembled *)
1157+ aw: []const U8;
1158+ ao: [6]Operand;
1159+ an, acc: INT; (* how many operands; b.cond's condition *)
1160+ aat: Diag.Pos;
1161+
1162+proc asmWord: []const U8;
1163+begin
1164+ if Scan.tok = Scan.sIdent then return Scan.nameOf(Scan.id); end;
1165+ if Scan.tok = Scan.sAnd then return "and"; end;
1166+ return "";
1167+end;
1168+
1169+(* The number w spells from its second letter, one or two digits, below
1170+ lim; else -1 *)
1171+proc numberIn(w: []const U8; lim: INT): INT;
1172+var i, n: INT;
1173+begin
1174+ if (LEN(w) < 2) or (LEN(w) > 3) then return -1; end;
1175+ n := 0;
1176+ for i := 1 to LEN(w) - 1 do
1177+ if (w[i] < '0') or (w[i] > '9') then return -1; end;
1178+ n := n * 10 + INT(w[i] - '0');
1179+ end;
1180+ if n >= lim then return -1; end;
1181+ return n;
1182+end;
1183+
1184+(* Whether w names a general register, x0 to x30, w0 to w30, sp, wsp,
1185+ xzr, wzr, fp or lr, or a real's, s, d or q and 0 to 31: o is set if so *)
1186+proc isReg(w: []const U8; var o: Operand): BOOL;
1187+begin
1188+ o.kind := oReg; o.sf := 1;
1189+ if LEN(w) < 2 then
1190+ return false;
1191+ elsif (w = "sp") or (w = "xzr") or (w = "wsp") or (w = "wzr") then
1192+ o.r := 31; o.sf := bit(w[0] # 'w'); o.sp := (w = "sp") or (w = "wsp");
1193+ elsif (w = "fp") or (w = "lr") then
1194+ o.r := 29 + bit(w = "lr");
1195+ elsif ((w[0] = 'x') or (w[0] = 'w')) and (numberIn(w, 31) >= 0) then
1196+ o.r := numberIn(w, 31); o.sf := bit(w[0] = 'x');
1197+ elsif ((w[0] = 's') or (w[0] = 'd') or (w[0] = 'q')) and (numberIn(w, 32) >= 0) then
1198+ o.kind := oFp; o.r := numberIn(w, 32); o.sf := 0;
1199+ if w[0] = 's' then o.size := 4; elsif w[0] = 'd' then o.size := 8; else o.size := 16; end;
1200+ else
1201+ return false;
1202+ end;
1203+ return true;
1204+end;
1205+
1206+proc wordIndex(w: []const U8; list: []const []const U8): INT;
1207+var i: INT;
1208+begin
1209+ for i := 0 to LEN(list) - 1 do
1210+ if list[i] = w then return i; end;
1211+ end;
1212+ return -1;
1213+end;
1214+
1215+(* The condition w names, cs and cc as hs and lo; -1 if none *)
1216+proc cond(w: []const U8): INT;
1217+begin
1218+ if w = "cs" then return ccHS; end;
1219+ if w = "cc" then return ccLO; end;
1220+ return wordIndex(w, CondNames);
1221+end;
1222+
1223+proc labelIndex(n: INT): INT;
1224+var i: INT;
1225+begin
1226+ for i := 0 to numLabels - 1 do
1227+ if lnames[i] = n then return i; end;
1228+ end;
1229+ return -1;
1230+end;
1231+
1232+proc lab(n: INT): (INT, ERROR);
1233+var i: INT;
1234+begin
1235+ i := labelIndex(n);
1236+ if i >= 0 then return i, nil; end;
1237+ if numLabels > 63 then return 0, Scan.mark("more than 64 labels"); end;
1238+ lnames[numLabels] := n; lplaces[numLabels] := -1; lchains[numLabels] := NoLabel;
1239+ lusedAt[numLabels] := Scan.tokPos();
1240+ INC(numLabels);
1241+ return numLabels - 1, nil;
1242+end;
1243+
1244+(* Every label, entered before an instruction is read, as in X64 *)
1245+proc findLabels;
1246+var st: Scan.State; wasQuiet, start: BOOL; w: []const U8;
1247+begin
1248+ Scan.saveScan(st);
1249+ wasQuiet := Diag.quiet;
1250+ Diag.setQuiet(true);
1251+ start := true;
1252+ while (Scan.tok # Scan.sEnd) and (Scan.tok # Scan.sEof) do
1253+ w := "";
1254+ if start then w := asmWord(); end;
1255+ start := Scan.tok = Scan.sSemicolon;
1256+ Scan.next;
1257+ if (LEN(w) > 0) and (Scan.tok = Scan.sColon) and (numLabels < 64) then
1258+ _, _ := lab(Scan.intern(SYSTEM.PTR(w), LEN(w)));
1259+ start := true;
1260+ Scan.next;
1261+ end;
1262+ end;
1263+ Diag.setQuiet(wasQuiet);
1264+ Scan.restoreScan(st);
1265+end;
1266+
1267+(* An immediate, with or without its #: # is raz's "not equal" *)
1268+proc immediate(constExpr: ConstFn): (I64, ERROR);
1269+begin
1270+ if Scan.tok = Scan.sNeq then Scan.next; end;
1271+ return constExpr(true);
1272+end;
1273+
1274+(* [xn], [xn, #off], [xn, xm], [xn, xm, lsl #s], then ! for pre-index,
1275+ or , #off after for post-index *)
1276+proc memory(var o: Operand; constExpr: ConstFn): ERROR;
1277+var b: Operand; st: Scan.State;
1278+begin
1279+ Scan.next;
1280+ o.kind := oMem; o.index := -1; o.mode := mOff;
1281+ if not isReg(asmWord(), b) or (b.kind # oReg) or (b.sf = 0) or ((b.r = 31) and not b.sp) then
1282+ return Scan.mark("expected a memory operand, [xn, #offset] or [xn, xm]");
1283+ end;
1284+ o.r := b.r;
1285+ Scan.next;
1286+ if Scan.tok = Scan.sComma then
1287+ Scan.next;
1288+ if isReg(asmWord(), b) then
1289+ if (b.kind # oReg) or (b.sf = 0) or (b.r = 31) then return Scan.mark("expected an index register, x0 to x30"); end;
1290+ o.index := b.r;
1291+ Scan.next;
1292+ if Scan.tok = Scan.sComma then
1293+ Scan.next;
1294+ if asmWord() # "lsl" then return Scan.mark("expected lsl"); end;
1295+ Scan.next;
1296+ o.scaled := true;
1297+ end;
1298+ end;
1299+ if (o.index < 0) or o.scaled then o.v := try immediate(constExpr); end;
1300+ end;
1301+ if Scan.tok # Scan.sRbrak then return Scan.mark("expected \"]\""); end;
1302+ Scan.next;
1303+ if Scan.tok = Scan.sNot then
1304+ o.mode := mPre;
1305+ Scan.next;
1306+ elsif (Scan.tok = Scan.sComma) and (o.v = 0) and (o.index < 0) then
1307+ Scan.saveScan(st);
1308+ Scan.next;
1309+ if (Scan.tok = Scan.sNeq) or (Scan.tok = Scan.sInt) or (Scan.tok = Scan.sMinus) then
1310+ o.mode := mPost;
1311+ o.v := try immediate(constExpr);
1312+ else
1313+ Scan.restoreScan(st);
1314+ end;
1315+ end;
1316+ return nil;
1317+end;
1318+
1319+(* An operand: a register, a memory operand, a shift (lsl #12), an
1320+ immediate; a label, where target is set (a jump's last operand),
1321+ entered if new, which assemble finds undefined; a name, a procedure or
1322+ a variable, by nameFn; or, where word is set, a condition or a
1323+ barrier's option. *)
1324+proc operand(var o: Operand; target, word: BOOL; constExpr: ConstFn; nameFn: NameFn): ERROR;
1325+var w: []const U8; k: INT;
1326+begin
1327+ o := {};
1328+ w := asmWord();
1329+ o.at := Scan.tokPos();
1330+ if Scan.tok = Scan.sLbrak then
1331+ try memory(o, constExpr);
1332+ elsif isReg(w, o) then
1333+ Scan.next;
1334+ elsif wordIndex(w, ShiftNames) >= 0 then
1335+ o.kind := oShift; o.sh := wordIndex(w, ShiftNames);
1336+ Scan.next;
1337+ o.v := try immediate(constExpr);
1338+ elsif word and (Scan.tok = Scan.sIdent) then
1339+ o.kind := oWord; o.w := w;
1340+ Scan.next;
1341+ else
1342+ o.c := -1;
1343+ k := -1;
1344+ if Scan.tok = Scan.sIdent then
1345+ k := labelIndex(Scan.id);
1346+ if (k >= 0) and not target then return Scan.mark(Diag.say("label {} is only for a jump", [Fmt.str(w)])); end;
1347+ if k < 0 then o.c := try nameFn(); end;
1348+ end;
1349+ if (k >= 0) or target and (o.c < 0) and (Scan.tok = Scan.sIdent) then
1350+ o.kind := oLabel;
1351+ o.c := try lab(Scan.id);
1352+ Scan.next;
1353+ elsif o.c >= 0 then
1354+ o.kind := oName;
1355+ else
1356+ o.kind := oImm;
1357+ o.v := try immediate(constExpr);
1358+ end;
1359+ end;
1360+ return nil;
1361+end;
1362+
1363+proc bad: ERROR;
1364+begin
1365+ return Scan.markAt(aat, Diag.say("can't assemble {} with these operands", [Fmt.str(aw)]));
1366+end;
1367+
1368+(* Whether the operands are kinds, one letter each: r a general
1369+ register, f a real's, i an immediate, m memory, s a shift, n a name,
1370+ l a label, w a word; and as many *)
1371+proc are(kinds: []const U8): BOOL;
1372+const Letters = "rfimsnlw";
1373+var i: INT;
1374+begin
1375+ if an # LEN(kinds) then return false; end;
1376+ for i := 0 to an - 1 do
1377+ if Letters[INT(ao[i].kind)] # kinds[i] then return false; end;
1378+ end;
1379+ return true;
1380+end;
1381+
1382+(* Whether the n operands from first are general registers of the
1383+ width of operand 0, none of them written sp *)
1384+proc regs(first, n: INT): BOOL;
1385+var i: INT;
1386+begin
1387+ for i := first to first + n - 1 do
1388+ if (i >= an) or (ao[i].kind # oReg) or (ao[i].sf # ao[0].sf) or ao[i].sp then return false; end;
1389+ end;
1390+ return true;
1391+end;
1392+
1393+proc fits(v, lo, hi: I64): BOOL;
1394+begin
1395+ return (v >= lo) and (v <= hi);
1396+end;
1397+
1398+(* The zero register, of operand 0's width, put in as operand i: mov is
1399+ orr of it, neg sub from it, cmp subs to it *)
1400+proc insertZR(i: INT);
1401+var j, sf: INT;
1402+begin
1403+ sf := ao[0].sf;
1404+ for j := an to i + 1 by -1 do ao[j] := ao[j - 1]; end;
1405+ ao[i] := {}; ao[i].kind := oReg; ao[i].r := ZR; ao[i].sf := sf;
1406+ INC(an);
1407+end;
1408+
1409+(* a branch to label k: back if it is placed, else on its chain *)
1410+proc toLabel(insn, k: INT);
1411+begin
1412+ if lplaces[k] >= 0 then
1413+ _ := branch(insn, lplaces[k], true);
1414+ else
1415+ lchains[k] := branch(insn, lchains[k], false);
1416+ end;
1417+end;
1418+
1419+(* The shift that is operand i, if there is one, the last: its kind and
1420+ amount, or lsl 0; false if it isn't a shift within the width *)
1421+proc shiftAt(i: INT; var sh, n: INT): BOOL;
1422+begin
1423+ sh := shLsl; n := 0;
1424+ if an = i then return true; end;
1425+ if (an # i + 1) or (ao[i].kind # oShift) or not fits(ao[i].v, 0, 31 + 32 * ao[0].sf) then return false; end;
1426+ sh := ao[i].sh; n := INT(ao[i].v);
1427+ return true;
1428+end;
1429+
1430+(* add, adds, sub, subs, and, orr, eor, ands, bic and orn, op, of
1431+ operands 0, 1 and 2: of an immediate, 12 bits with lsl #12 or
1432+ negative for the opposite operation, or a logical immediate; or of a
1433+ register, shifted, or extended where sp is one *)
1434+proc alu3(op: INT): ERROR;
1435+var sh, n, enc: INT; v: I64; d: Operand;
1436+begin
1437+ d := ao[0];
1438+ if (d.kind # oReg) or (an < 3) or (ao[1].kind # oReg) or (ao[1].sf # d.sf) or ao[1].sp and (op > opSubs) then return bad(); end;
1439+ if ao[2].kind = oImm then
1440+ v := ao[2].v;
1441+ if op > opSubs then
1442+ enc := bitmask(v, d.sf);
1443+ if (an # 3) or (op > opAnds) or (enc < 0) or (d.sf = 0) and not fits(v, -80000000H, 0FFFFFFFFH)
1444+ or (d.r = 31) and (d.sp = (op = opAnds)) then return bad(); end;
1445+ logicImm(d.sf, op, d.r, ao[1].r, enc, v);
1446+ return nil;
1447+ end;
1448+ if not shiftAt(3, sh, n) or (sh # shLsl) or (n # 0) and (n # 12) then return bad(); end;
1449+ if (v < 0) and (n = 0) then v := -v; op := op xor 2; end;
1450+ if not fits(v, 0, 4095) or (d.r = 31) and (d.sp = ((op & 1) = 1)) or (ao[1].r = 31) and not ao[1].sp then return bad(); end;
1451+ addImm(d.sf, op, d.r, ao[1].r, INT(v), n div 12);
1452+ return nil;
1453+ end;
1454+ if not regs(2, 1) or not shiftAt(3, sh, n) then return bad(); end;
1455+ if (op <= opSubs) and (d.sp or ao[1].sp) then
1456+ if (sh # shLsl) or (n > 4) or (d.r = 31) and (d.sp = ((op & 1) = 1)) then return bad(); end;
1457+ addExt(d.sf, op, d.r, ao[1].r, ao[2].r, n);
1458+ elsif d.sp or (sh = shRor) and (op <= opSubs) then
1459+ return bad();
1460+ else
1461+ aluShifted(d.sf, op, d.r, ao[1].r, ao[2].r, sh, n);
1462+ end;
1463+ return nil;
1464+end;
1465+
1466+(* ldr, str and their kin: the size from the name's end (b, h, sb, sh,
1467+ sw) or from the register; ldur and stur, and an offset that can't
1468+ be scaled, are unscaled *)
1469+proc loadStore(): ERROR;
1470+var name, sfx: []const U8; size, sf, bits, sc: INT; load, signed, fp, unscaled: BOOL; m: Operand;
1471+begin
1472+ unscaled := aw[2] = 'u';
1473+ name := aw;
1474+ if unscaled then name := Diag.say("{}{}", [Fmt.str(aw[0..2]), Fmt.str(aw[3..LEN(aw)])]); end;
1475+ load := name[0] = 'l';
1476+ sfx := name[3..LEN(name)];
1477+ if not are("rm") and not are("fm") then return bad(); end;
1478+ m := ao[1];
1479+ fp := ao[0].kind = oFp;
1480+ sf := ao[0].sf;
1481+ signed := (LEN(sfx) = 2) and (sfx[0] = 's');
1482+ if fp and (LEN(sfx) = 0) then size := ao[0].size;
1483+ elsif sfx = "" then size := 4 + 4 * sf;
1484+ elsif (sfx = "b") or (sfx = "sb") then size := 1;
1485+ elsif (sfx = "h") or (sfx = "sh") then size := 2;
1486+ elsif sfx = "sw" then size := 4;
1487+ else return bad();
1488+ end;
1489+ if fp and (LEN(sfx) # 0) or signed and not load or (sfx = "sw") and (sf = 0) or (LEN(sfx) = 1) and (sf = 1) or ao[0].sp then return bad(); end;
1490+ bits := ldstBits(size, load, signed, fp, sf);
1491+ sc := scaleOf(size);
1492+ if (m.mode # mOff) or unscaled then
1493+ if (m.index >= 0) or (m.mode # mOff) and unscaled or not fits(m.v, -256, 255) then return bad(); end;
1494+ if m.mode # mOff then ldstIdx(bits, ao[0].r, m.r, INT(m.v), m.mode);
1495+ else emit(38000000H | bits | (INT(m.v & 1FFH) shl 12) | (m.r shl 5) | ao[0].r); end;
1496+ elsif m.index >= 0 then
1497+ if m.scaled and (m.v # sc) and (m.v # 0) then return bad(); end;
1498+ ldstReg(bits, ao[0].r, m.r, m.index, m.scaled and (m.v = sc));
1499+ elsif fits(m.v, 0, 4095 shl sc) and ((m.v & ((1 shl sc) - 1)) = 0) or fits(m.v, -256, 255) then
1500+ ldst(bits, ao[0].r, m.r, INT(m.v));
1501+ else
1502+ return bad();
1503+ end;
1504+ return nil;
1505+end;
1506+
1507+const
1508+ (* the aliases of alu3's operations with the zero register put in:
1509+ cmp and cmn as subs and adds to it, tst ands to it, neg sub from
1510+ it, mvn orn of it *)
1511+ Aliases: [5][]const U8 = ["cmp", "cmn", "tst", "neg", "mvn"];
1512+ AliasOps: [5]INT = [opSubs, opAdds, opAnds, opSub, opOrn];
1513+ (* the instructions of only registers, regOp's: their bits and how
1514+ many registers *)
1515+ RegNames: [14][]const U8 = ["mul", "madd", "msub", "smulh", "umulh", "sdiv", "udiv",
1516+ "lsl", "lsr", "asr", "ror", "clz", "rbit", "rev"];
1517+ RegBits: [14]INT = [1B007C00H, 1B000000H, 1B008000H, 9B407C00H, 9BC07C00H, 1AC00C00H, 1AC00800H,
1518+ 1AC02000H, 1AC02400H, 1AC02800H, 1AC02C00H, 5AC01000H, 5AC00000H, 5AC00800H];
1519+ RegCount: [14]INT = [3, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2];
1520+ Extends: [5][]const U8 = ["sxtb", "sxth", "sxtw", "uxtb", "uxth"];
1521+ Barriers: [6][]const U8 = ["sy", "ish", "ishld", "ishst", "osh", "nsh"];
1522+ BarrierCodes: [6]INT = [15, 11, 9, 10, 3, 7];
1523+ (* the instructions of no operands *)
1524+ Plain: [4][]const U8 = ["nop", "yield", "isb", "ret"];
1525+ PlainBits: [4]INT = [0D503201FH, 0D503203FH, 0D5033FDFH, 0D65F03C0H];
1526+ (* between the register files, as fconv takes them: rmode * 8 +
1527+ opcode; the first two into a real's register *)
1528+ Convs: [4][]const U8 = ["scvtf", "ucvtf", "fcvtzs", "fcvtzu"];
1529+ ConvCodes: [4]INT = [02H, 03H, 18H, 19H];
1530+
1531+(* The instruction aw with its operands, in ao and an *)
1532+proc instruction(): ERROR;
1533+var k, sf, size, bits, g, f: INT; d: Operand; v: I64;
1534+begin
1535+ d := ao[0];
1536+ sf := d.sf;
1537+ if wordIndex(aw, Aliases) >= 0 then
1538+ insertZR(bit(wordIndex(aw, Aliases) >= 3));
1539+ return alu3(AliasOps[wordIndex(aw, Aliases)]);
1540+ elsif wordIndex(aw, AluNames) >= 0 then
1541+ return alu3(wordIndex(aw, AluNames));
1542+ elsif aw = "mov" then
1543+ (* movImm's choice for an immediate; add #0 with sp, else orr *)
1544+ if are("ri") and not d.sp and ((sf = 1) or fits(ao[1].v, -80000000H, 0FFFFFFFFH)) then
1545+ movImm(sf, d.r, ao[1].v);
1546+ return nil;
1547+ elsif are("rr") and (d.sp or ao[1].sp) then
1548+ ao[2] := {}; ao[2].kind := oImm; an := 3;
1549+ return alu3(opAdd);
1550+ end;
1551+ insertZR(1);
1552+ return alu3(opOrr);
1553+ elsif (aw = "movz") or (aw = "movk") or (aw = "movn") then
1554+ k := 0;
1555+ if (an = 3) and (ao[2].kind = oShift) and (ao[2].sh = shLsl) and ((ao[2].v & 15) = 0) and fits(ao[2].v, 0, 16 + 32 * sf) then
1556+ k := INT(ao[2].v) div 16;
1557+ DEC(an);
1558+ end;
1559+ if not are("ri") or d.sp or not fits(ao[1].v, 0, 0FFFFH) then return bad(); end;
1560+ movWide(sf, wordIndex(aw, ["movn", "", "movz", "movk"]), d.r, INT(ao[1].v), k);
1561+ elsif (wordIndex(aw, ShiftNames) >= 0) and are("rri") then
1562+ if not regs(1, 1) or not fits(ao[2].v, 0, 31 + 32 * sf) then return bad(); end;
1563+ shiftI(wordIndex(aw, ShiftNames), d.r, ao[1].r, INT(ao[2].v), 4 + 4 * sf);
1564+ elsif wordIndex(aw, RegNames) >= 0 then
1565+ (* smulh and umulh are of x only; rev's opc is 11 for x, 10 for w *)
1566+ k := wordIndex(aw, RegNames);
1567+ if (an # RegCount[k]) or not regs(0, an) or ((k = 3) or (k = 4)) and (sf = 0) then return bad(); end;
1568+ bits := RegBits[k];
1569+ if aw = "rev" then bits := bits | (sf shl 10); end;
1570+ while an < 4 do ao[an].r := 0; INC(an); end;
1571+ regOp(aw, RegCount[k], sf, bits & 7FFFFFFFH, d.r, ao[1].r, ao[2].r, ao[3].r);
1572+ elsif wordIndex(aw, CselNames) >= 0 then
1573+ if (an # 4) or not regs(0, 3) or (ao[3].kind # oWord) or (cond(ao[3].w) < 0) then return bad(); end;
1574+ condSel(sf, wordIndex(aw, CselNames), cond(ao[3].w), d.r, ao[1].r, ao[2].r);
1575+ elsif (aw = "cset") or (aw = "csetm") then
1576+ (* csinc and csinv of the zero register on the opposite condition *)
1577+ if (an # 2) or not regs(0, 1) or (ao[1].kind # oWord) or (cond(ao[1].w) < 0) then return bad(); end;
1578+ condSel(sf, csInc + bit(aw = "csetm"), invert(cond(ao[1].w)), d.r, ZR, ZR);
1579+ elsif wordIndex(aw, Extends) >= 0 then
1580+ k := wordIndex(aw, Extends);
1581+ if (an # 2) or (d.kind # oReg) or d.sp or (ao[1].kind # oReg) or (ao[1].sf # 0) or ao[1].sp
1582+ or (k >= 3) and (sf = 1) or (k = 2) and (sf = 0) then return bad(); end;
1583+ bitfield(sf, 2 * bit(k >= 3), d.r, ao[1].r, 0, 8 * (1 shl (k mod 3)) - 1);
1584+ elsif (aw = "ubfm") or (aw = "sbfm") or (aw = "ubfx") or (aw = "sbfx") then
1585+ if (an # 4) or not regs(0, 2) or (ao[2].kind # oImm) or (ao[3].kind # oImm) then return bad(); end;
1586+ v := ao[3].v;
1587+ if aw[3] = 'x' then v := ao[2].v + v - 1; end; (* ubfx's width, as ubfm's last bit *)
1588+ if not fits(ao[2].v, 0, 31 + 32 * sf) or not fits(v, 0, 31 + 32 * sf) then return bad(); end;
1589+ bitfield(sf, 2 * bit(aw[0] = 'u'), d.r, ao[1].r, INT(ao[2].v), INT(v));
1590+ elsif Str.hasPrefix(aw, "ldr") or Str.hasPrefix(aw, "str") or Str.hasPrefix(aw, "ldur") or Str.hasPrefix(aw, "stur") then
1591+ return loadStore();
1592+ elsif (aw = "ldp") or (aw = "stp") then
1593+ if not are("rrm") and not are("ffm") then return bad(); end;
1594+ size := 4 + 4 * sf;
1595+ if d.kind = oFp then size := d.size; end;
1596+ if (ao[1].sf # sf) or (ao[1].size # d.size) or d.sp or ao[1].sp or (ao[2].index >= 0)
1597+ or ((ao[2].v & (size - 1)) # 0) or not fits(ao[2].v, -64 * size, 63 * size) then return bad(); end;
1598+ pair(aw[0] = 'l', d.kind = oFp, size, d.r, ao[1].r, ao[2].r, INT(ao[2].v), ao[2].mode);
1599+ elsif wordIndex(aw, AtomNames) >= 0 then
1600+ (* ldaxr has no rs, which is 31 in its bits; stlxr's is a w *)
1601+ k := wordIndex(aw, AtomNames);
1602+ if aw = "ldaxr" then insertZR(0); end;
1603+ if not are("rrm") or ao[0].sp or ao[1].sp or (ao[2].index >= 0) or (ao[2].v # 0) or (ao[2].mode # mOff)
1604+ or (k < 3) and (ao[1].sf # sf) or (k = 4) and (sf = 1) then return bad(); end;
1605+ atomic(k, 4 + 4 * ao[1].sf, ao[0].r, ao[1].r, ao[2].r);
1606+ elsif aw = "adr" then
1607+ if not are("rn") or (sf = 0) or d.sp then return bad(); end;
1608+ addrChunk(d.r, ao[1].c, 0);
1609+ elsif ((aw = "b") or (aw = "bl")) and are("n") then
1610+ branchChunk(aw = "bl", d.c);
1611+ elsif (aw = "b") and are("l") then
1612+ toLabel(14000000H, d.c);
1613+ elsif (aw = "b.") and are("l") then
1614+ toLabel(54000000H | acc, d.c);
1615+ elsif ((aw = "cbz") or (aw = "cbnz")) and are("rl") and not d.sp then
1616+ toLabel((sf shl 31) | 34000000H | (bit(aw = "cbnz") shl 24) | d.r, ao[1].c);
1617+ elsif ((aw = "tbz") or (aw = "tbnz")) and are("ril") and not d.sp and fits(ao[1].v, 0, 31 + 32 * sf) then
1618+ k := INT(ao[1].v);
1619+ toLabel(36000000H | (bit(aw = "tbnz") shl 24) | ((k shr 5) shl 31) | ((k & 31) shl 19) | d.r, ao[2].c);
1620+ elsif (aw = "br") or (aw = "blr") or (aw = "ret") and (an = 1) then
1621+ (* opc in bits 21 and 22: 00 br, 01 blr, 10 ret *)
1622+ if not are("r") or (sf = 0) or d.sp then return bad(); end;
1623+ emit(0D61F0000H | (wordIndex(aw, ["br", "blr", "ret"]) shl 21) | (d.r shl 5));
1624+ elsif (aw = "svc") or (aw = "brk") then
1625+ if not are("i") or not fits(d.v, 0, 0FFFFH) then return bad(); end;
1626+ if aw = "svc" then svc(INT(d.v)); else brk(INT(d.v)); end;
1627+ elsif (aw = "dmb") or (aw = "dsb") then
1628+ if not are("w") or (wordIndex(d.w, Barriers) < 0) then return bad(); end;
1629+ emit(0D503309FH | (bit(aw = "dmb") shl 5) | (BarrierCodes[wordIndex(d.w, Barriers)] shl 8));
1630+ elsif wordIndex(aw, Plain) >= 0 then
1631+ if an # 0 then return bad(); end;
1632+ emit(PlainBits[wordIndex(aw, Plain)]);
1633+ elsif wordIndex(aw, FopNames) >= 0 then
1634+ if not are("fff") or (d.size = 16) or (ao[1].size # d.size) or (ao[2].size # d.size) then return bad(); end;
1635+ fop(wordIndex(aw, FopNames), d.r, ao[1].r, ao[2].r, d.size = 4);
1636+ elsif (wordIndex(aw, Fop1Names) >= 0) and are("ff") and (d.size # 16) and (ao[1].size = d.size) then
1637+ fop1(wordIndex(aw, Fop1Names), d.r, ao[1].r, d.size = 4);
1638+ elsif (aw = "fmov") and are("fr") and (d.size = 4 + 4 * ao[1].sf) and not ao[1].sp then
1639+ fmovFR(d.r, ao[1].r, d.size = 4);
1640+ elsif (aw = "fmov") and are("rf") and (ao[1].size = 4 + 4 * sf) and not d.sp then
1641+ fmovRF(d.r, ao[1].r, ao[1].size = 4);
1642+ elsif (aw = "fcmp") and are("ff") and (ao[1].size = d.size) and (d.size # 16) then
1643+ fcmp(d.r, ao[1].r, d.size = 4);
1644+ elsif (aw = "fcmp") and are("fi") and (ao[1].v = 0) and (d.size # 16) then
1645+ fcmp(d.r, -1, d.size = 4);
1646+ elsif (aw = "fcvt") and are("ff") and (d.size + ao[1].size = 12) then
1647+ fcvt(d.r, ao[1].r, d.size = 4);
1648+ elsif wordIndex(aw, Convs) >= 0 then
1649+ (* scvtf and ucvtf from operand g, a general register, into f, a
1650+ real's; fcvtzs and fcvtzu the other way *)
1651+ k := wordIndex(aw, Convs);
1652+ g := bit(k < 2); f := 1 - g;
1653+ if (ao[g].kind # oReg) or (ao[f].kind # oFp) or (an # 2) or ao[g].sp or (ao[f].size = 16) then return bad(); end;
1654+ fconv(aw, ao[g].sf, ao[f].size, ConvCodes[k] shr 3, ConvCodes[k] & 7, d.r, ao[1].r, k < 2);
1655+ else
1656+ return Scan.markAt(aat, Diag.say("unknown instruction {}", [Fmt.str(aw)]));
1657+ end;
1658+ return nil;
1659+end;
1660+
1661+(* Which operand of instruction w is a jump's target, which may be a
1662+ label: -1 if none *)
1663+proc targetOf(w: []const U8): INT;
1664+begin
1665+ if (w = "b") or (w = "bl") or (w = "b.") then return 0; end;
1666+ if (w = "cbz") or (w = "cbnz") then return 1; end;
1667+ if (w = "tbz") or (w = "tbnz") then return 2; end;
1668+ return -1;
1669+end;
1670+
1671+(* Whether operand i of instruction w is a word: a condition or a
1672+ barrier's option *)
1673+proc wordAt(w: []const U8; i: INT): BOOL;
1674+begin
1675+ return (wordIndex(w, CselNames) >= 0) and (i = 3) or ((w = "cset") or (w = "csetm")) and (i = 1)
1676+ or ((w = "dmb") or (w = "dsb")) and (i = 0);
1677+end;
1678+
1679+(* db's bytes or dd's words, each a constant *)
1680+proc data(constExpr: ConstFn): ERROR;
1681+var v: I64; start: Diag.Pos; n: INT;
1682+begin
1683+ n := 1 + 3 * bit(aw = "dd");
1684+ repeat
1685+ start := Scan.tokPos();
1686+ v := try constExpr(true);
1687+ if (v < -(I64(1) shl (8 * n - 1))) or (v >= I64(1) shl (8 * n)) then
1688+ return Scan.markAt(Scan.spanFrom(start), Diag.say("{} doesn't fit in {} bits", [Fmt.int(v), Fmt.int(8 * n)]));
1689+ end;
1690+ if n = 1 then Chunk.put1(INT(v & 0FFH)); else Chunk.put4(INT(v & 0FFFFFFFFH)); end;
1691+ if Scan.tok # Scan.sComma then break; end;
1692+ Scan.next;
1693+ until false;
1694+ return nil;
1695+end;
1696+
1697+(* One instruction or label *)
1698+proc statement(constExpr: ConstFn; nameFn: NameFn): ERROR;
1699+var i, k, first: INT; wasListing: BOOL;
1700+begin
1701+ aat := Scan.tokPos();
1702+ aw := asmWord();
1703+ if LEN(aw) = 0 then return Scan.mark("expected an instruction"); end;
1704+ Scan.next;
1705+ if Scan.tok = Scan.sColon then
1706+ sayAt(Chunk.pc, Diag.say("{}:", [Fmt.str(aw)]));
1707+ k := try lab(Scan.intern(SYSTEM.PTR(aw), LEN(aw)));
1708+ if lplaces[k] >= 0 then
1709+ return Scan.markAt(aat, Diag.say("label {} is defined twice", [Fmt.str(aw)]));
1710+ end;
1711+ lplaces[k] := Chunk.pc;
1712+ fixLink(lchains[k]);
1713+ Scan.next;
1714+ return nil;
1715+ end;
1716+ if (aw = "b") and (Scan.tok = Scan.sPeriod) then
1717+ (* b.cond: the condition, after the period *)
1718+ Scan.next;
1719+ acc := cond(asmWord());
1720+ if acc < 0 then return Scan.mark("expected a condition, as eq of b.eq"); end;
1721+ aw := "b.";
1722+ Scan.next;
1723+ end;
1724+ first := Chunk.pc;
1725+ wasListing := listing;
1726+ listing := false; (* the instruction is said as it is written *)
1727+ if (aw = "db") or (aw = "dd") then
1728+ try data(constExpr);
1729+ else
1730+ an := 0;
1731+ if Scan.tok # Scan.sSemicolon then
1732+ repeat
1733+ if an > 3 then return Scan.mark("too many operands"); end;
1734+ try operand(ao[an], an = targetOf(aw), wordAt(aw, an), constExpr, nameFn);
1735+ INC(an);
1736+ if Scan.tok # Scan.sComma then break; end;
1737+ Scan.next;
1738+ until false;
1739+ end;
1740+ (* a name stands only in bl p, b p and adr r, v *)
1741+ for i := 0 to an - 1 do
1742+ if (ao[i].kind = oName) and not ((i = 0) and ((aw = "b") or (aw = "bl")) or (i = 1) and (aw = "adr")) then
1743+ return Scan.markAt(ao[i].at, NameOnly);
1744+ end;
1745+ end;
1746+ try instruction();
1747+ end;
1748+ if Scan.tok # Scan.sSemicolon then return Scan.mark("expected \";\""); end;
1749+ listing := wasListing;
1750+ sayAt(first, Diag.source(Scan.spanFrom(aat)));
1751+ Scan.next;
1752+ return nil;
1753+end;
1754+
1755+(* A code procedure's instructions, up to end. ! of a pre-index is a
1756+ symbol of its own meanwhile (Scan.setBang), where elsewhere it is a
1757+ slip for not. *)
1758+proc assemble*(constExpr: ConstFn; nameFn: NameFn): ERROR;
1759+var k: INT;
1760+begin
1761+ Scan.setBang(true);
1762+ defer Scan.setBang(false);
1763+ numLabels := 0;
1764+ findLabels();
1765+ while (Scan.tok # Scan.sEnd) and (Scan.tok # Scan.sEof) do
1766+ if Scan.tok = Scan.sSemicolon then
1767+ Scan.next;
1768+ else
1769+ try statement(constExpr, nameFn);
1770+ end;
1771+ end;
1772+ for k := 0 to numLabels - 1 do
1773+ if lplaces[k] < 0 then
1774+ return Scan.markAt(lusedAt[k], Diag.say("label {} isn't defined", [Fmt.str(Scan.nameOf(lnames[k]))]));
1775+ end;
1776+ end;
1777+ return nil;
1778+end;
1779+
1780+(* n, in decimal, at least w wide *)
1781+proc padded(n, w: INT);
1782+var s: []const U8; i: INT;
1783+begin
1784+ s := Diag.say("{}", [Fmt.int(n)]);
1785+ for i := LEN(s) to w - 1 do Out.str(" "); end;
1786+ Out.str(s);
1787+end;
1788+
1789+(* The listing, raz -S, as X64's: a jump within the procedure, said with
1790+ -> for its target, says where to by its offset, read from its field *)
1791+proc list*(home: INT);
1792+var order: ^INT; n, i, j, k, c, t, line, insn, lo, w, d: INT; text: []const U8;
1793+begin
1794+ order := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT)));
1795+ n := 0;
1796+ for c := 0 to Chunk.numChunks - 1 do
1797+ if Chunk.chunks[c].live and (Chunk.chunks[c].sec = Chunk.secText) and (Chunk.chunks[c].home = home) then
1798+ i := n;
1799+ while (i > 0) and (Chunk.chunks[order[i - 1]].start > Chunk.chunks[c].start) do
1800+ order[i] := order[i - 1];
1801+ DEC(i);
1802+ end;
1803+ order[i] := c;
1804+ INC(n);
1805+ end;
1806+ end;
1807+ i := 0; j := 0;
1808+ for k := 0 to n - 1 do
1809+ c := order[k];
1810+ Out.ln;
1811+ Out.str(Chunk.chunkName(c)); Out.str(":\n");
1812+ line := -1;
1813+ while (i < numSaid) and (said[i].at < Chunk.chunks[c].start) do INC(i); end;
1814+ while (i < numSaid) and (said[i].at < Chunk.chunks[c].start + Chunk.chunks[c].size) do
1815+ while (j < Chunk.numLines) and (Chunk.lines[j].at <= said[i].at) do
1816+ if (Chunk.lines[j].chunk = c) and (Chunk.lines[j].line # line) then
1817+ line := Chunk.lines[j].line;
1818+ padded(line, 6);
1819+ Out.str(" ");
1820+ Out.str(Diag.lineText(Scan.nameOf(Chunk.lines[j].path), line));
1821+ Out.ln;
1822+ end;
1823+ INC(j);
1824+ end;
1825+ text := said[i].text;
1826+ t := said[i].at;
1827+ if (LEN(text) > 2) and (text[LEN(text) - 2..LEN(text)] = "->") then
1828+ insn := Chunk.get4At(t) & 0FFFFFFFFH;
1829+ lo, w := fieldOf(insn);
1830+ d := (insn shr lo) & ((1 shl w) - 1);
1831+ if d >= (1 shl (w - 1)) then d := d - (1 shl w); end;
1832+ text := Diag.say("{}{}", [Fmt.str(text[0..LEN(text) - 2]), Fmt.int(t + 4 * d - Chunk.chunks[c].start)]);
1833+ end;
1834+ padded(t - Chunk.chunks[c].start, 14);
1835+ Out.str(" ");
1836+ Out.str(text);
1837+ Out.ln;
1838+ INC(i);
1839+ end;
1840+ end;
1841+end;
1842+
1843+begin
1844+ listing := false;
1845+ numSaid := 0;
1846+ saidCap := 0;
1847+ said := nil;
1848+end A64.

src/Chunk.raz (history) modified +27 -2

@@ -9,10 +9,10 @@
99 point on is for.
1010
1111 Nothing here depends on the machine: text is bytes, written by the
12- encoder for the target (X64).
12+ encoder for the target (X64, or A64 for arm64).
1313
1414 Depends on: Scan, for names and memory; Diag, for positions.
15- Leaves out: the instructions; that is X64.
15+ Leaves out: the instructions; that is X64 or A64.
1616
1717 Exported variables can't be set from outside, so the setters at the
1818 end do what the seed's other units do to these. *)
@@ -52,12 +52,29 @@
5252 kind*: INT; (* how Rt shows it: see Link *)
5353 end;
5454
55+ (* How a fixup's field is patched. fxRel32 is x86-64's: 32 bits, the
56+ distance from the field's end, or with abs the address itself. The
57+ others are arm64's (A64), each a field of the instruction at at,
58+ as the Mach-O relocations of the same names:
59+ fxBranch26 b or bl: the distance in words, in imm26
60+ fxPage21 adrp: the distance in 4 KB pages from the
61+ instruction's page, in immhi:immlo
62+ fxPageOff12 add, or a load or store's unsigned offset: the
63+ address's place in its page, in imm12, divided
64+ by the size a load or store reads from its own
65+ bits (31 and 30, or 16 for a q register), as
66+ ARM64_RELOC_PAGEOFF12 is
67+ Link patches only fxRel32 yet: arm64's come with Exe.darwin.raz
68+ (PLAN.md 5, step 6). *)
69+ FixKind* = (fxRel32, fxBranch26, fxPage21, fxPageOff12);
70+
5571 Fixup* = record
5672 at*: INT; (* the 32-bit field, as an offset in text; in
5773 dataFixups, the 64-bit one, from its chunk's start *)
5874 chunk*: INT; (* the chunk it refers to *)
5975 addend*: INT; (* added to the chunk's address *)
6076 abs*: BOOL; (* text: the address itself, not from the field's end *)
77+ kind*: FixKind; (* text: how the field is patched *)
6178 end;
6279
6380 var
@@ -249,7 +266,15 @@
249266 fixups[numFixups].chunk := chunk;
250267 fixups[numFixups].addend := addend;
251268 fixups[numFixups].abs := false;
269+ fixups[numFixups].kind := fxRel32;
252270 INC(numFixups);
271+end;
272+
273+(* The same, of an arm64 kind: the instruction at at *)
274+proc addKindFixup*(at, chunk, addend: INT; kind: FixKind);
275+begin
276+ addFixup(at, chunk, addend);
277+ fixups[numFixups - 1].kind := kind;
253278 end;
254279
255280 (* The same, for X64.memAbs: the field holds the address itself *)

src/Scan.raz (history) modified +13 -1

@@ -89,6 +89,10 @@
8989 error, so slips in it aren't reported again. *)
9090 skipping*: BOOL;
9191
92+ (* In arm64's code procedure, ! is a symbol, sNot, of a pre-index, as
93+ in [sp, #-16]!, not a slip for not (A64.assemble) *)
94+ bang: BOOL;
95+
9296 atCursor*: INT; (* the name the symbol at the cursor has *)
9397 prefix*: []const U8; (* what is typed of the name at the cursor *)
9498 word*: []const U8; (* the whole name at the cursor, as raz -q def asks of it *)
@@ -122,6 +126,11 @@
122126 skipping := yes;
123127 end;
124128
129+proc setBang*(yes: BOOL);
130+begin
131+ bang := yes;
132+end;
133+
125134 (* The bytes of the string just read, without the zero after them *)
126135 proc strBytes*: []const U8;
127136 begin
@@ -1232,7 +1241,10 @@
12321241 tok := sBar;
12331242 end;
12341243 | '!':
1235- if cur.buf[cur.pos + 1] = '=' then
1244+ if bang then
1245+ INC(cur.pos);
1246+ tok := sNot;
1247+ elsif cur.buf[cur.pos + 1] = '=' then
12361248 slip(2, sNeq, "\"not equal\" is written #, not !=");
12371249 else
12381250 slip(1, sNot, "\"not\" is written not, not !");

test/a64/Api.s (history) added +209 -0

@@ -0,0 +1,209 @@
1+// Encode.raz's calls of A64, one line each in its order, in Apple's
2+// syntax: the instructions each call must make. expect.sh assembles it.
3+// moves
4+movz x0, #0
5+movz x1, #0x1234
6+movz x2, #0x1234, lsl #16
7+movn x3, #0
8+movn x4, #1, lsl #16
9+orr x5, xzr, #0x00ff00ff00ff00ff
10+movz x6, #0xdef0 ; movk x6, #0x9abc, lsl #16 ; movk x6, #0x5678, lsl #32 ; movk x6, #0x1234, lsl #48
11+movn x7, #0xa987 ; movk x7, #0x1234, lsl #32
12+orr x8, xzr, #0x100000001
13+orr x9, xzr, #0x5555555555555555
14+movz x10, #0x8000, lsl #48
15+movn x11, #0x8000, lsl #48
16+orr x12, xzr, #0xffffffff
17+movz x13, #0xabcd ; movk x13, #0xffff, lsl #32
18+orr x0, xzr, x1
19+add sp, x29, #0
20+add x29, sp, #0
21+// two registers
22+add x0, x1, x2
23+adds x3, x4, x5
24+sub x6, x7, x8
25+subs x9, x10, x11
26+and x12, x13, x14
27+orr x15, x16, x17
28+eor x19, x20, x21
29+ands x22, x23, x24
30+bic x25, x26, x27
31+orn x28, x29, x30
32+add x0, x1, x2, lsl #3
33+sub x3, x4, x5, asr #63
34+orr x6, x7, x8, ror #1
35+// immediates
36+add x0, x1, #4095
37+add x0, x1, #1, lsl #12
38+add sp, sp, #16
39+sub sp, sp, #0x123, lsl #12
40+sub x0, x1, #8
41+sub x2, x3, #0x12, lsl #12 ; sub x2, x2, #0x345
42+movz x16, #0x4567 ; movk x16, #0x123, lsl #16 ; add x4, sp, x16, uxtx
43+movz x16, #0x2345 ; movk x16, #0x1, lsl #16 ; adds x5, x6, x16, uxtx
44+and x0, x1, #0xff
45+orr sp, x1, #0xf0
46+movz x16, #0x1234 ; eor x2, x3, x16
47+subs xzr, x0, x1
48+cmp sp, #32
49+cmn x2, #5
50+movz x16, #0x1001 ; movk x16, #0x100, lsl #16 ; subs xzr, x3, x16, uxtx
51+tst x4, x5
52+tst x6, #1
53+tst x7, #0x8000000000000000
54+neg x0, x1
55+mvn x2, x3
56+// shifts and fields
57+lsl x0, x1, x2
58+lsr x3, x4, x5
59+asr x6, x7, x8
60+ror x9, x10, x11
61+lsl w3, w4, w5
62+lsl x0, x1, #3
63+lsr x0, x1, #63
64+asr x2, x3, #1
65+ror x4, x5, #7
66+lsl w6, w7, #31
67+ror w8, w9, #16
68+ubfm x0, x1, #0, #63
69+ubfx x0, x1, #8, #8
70+sbfx x2, x3, #0, #32
71+sxtb x0, w1
72+sxth x2, w3
73+sxtw x4, w5
74+uxtb w6, w7
75+uxth w8, w9
76+mov w10, w11
77+// multiply, divide, select, count
78+mul x0, x1, x2
79+madd x3, x4, x5, x6
80+msub x7, x8, x9, x10
81+smulh x0, x1, x2
82+umulh x3, x4, x5
83+sdiv x3, x4, x5
84+udiv x6, x7, x8
85+csel x0, x1, x2, eq
86+csinc x3, x4, x5, ne
87+csneg x6, x7, x8, lt
88+cset x9, gt
89+clz x0, x1
90+clz w2, w3
91+rbit x4, x5
92+// loads and stores
93+ldr x0, [x1]
94+ldr x0, [x1, #32760]
95+movz x16, #0x8000 ; ldr x2, [x3, x16]
96+ldur x4, [x5, #-8]
97+ldur x4, [x5, #-256]
98+ldur x6, [x7, #3]
99+ldrb w8, [x9, #4095]
100+ldrsb x10, [x11, #4]
101+ldrh w12, [x13, #8190]
102+ldrsh x14, [x15, #6]
103+ldr w0, [sp, #16380]
104+ldrsw x1, [x2, #4]
105+ldursb x3, [x4, #-1]
106+str x0, [x1, #8]
107+str w2, [sp]
108+sturh w3, [x4, #1]
109+strb w5, [x6, #4095]
110+str xzr, [x7]
111+ldr x0, [x1, x2, lsl #3]
112+ldrsb x3, [x4, x5]
113+ldr w6, [x7, x8, lsl #2]
114+strh w9, [x10, x11, lsl #1]
115+str x12, [x13, x14]
116+ldr x0, [sp], #16
117+str x1, [sp, #-16]!
118+str w2, [x3, #-256]!
119+ldrb w4, [x5], #255
120+ldr d0, [x1, #8]
121+ldr s2, [x3, #4]
122+ldr q4, [x5, #32]
123+str q6, [sp, #65520]
124+stur d7, [x8, #-4]
125+str s9, [x10]
126+stp x29, x30, [sp, #-16]!
127+ldp x29, x30, [sp], #16
128+stp x19, x20, [sp, #504]
129+ldp x21, x22, [x1, #-512]
130+// atomics and the system's
131+ldaddal x1, x0, [x2]
132+ldaddal w3, w4, [x5]
133+swpal x6, x7, [x8]
134+swpal w9, w10, [x11]
135+casal x12, x13, [x14]
136+casal w15, w16, [x17]
137+dmb ish
138+svc #0x80
139+svc #0
140+brk #1
141+brk #0xf000
142+// reals
143+fmul d0, d1, d2
144+fdiv d0, d1, d2
145+fadd d0, d1, d2
146+fsub d0, d1, d2
147+fmax d0, d1, d2
148+fmin d0, d1, d2
149+fadd s3, s4, s5
150+fmov d0, d1
151+fabs d0, d1
152+fneg d0, d1
153+fsqrt d0, d1
154+fsqrt s6, s7
155+fcvt d0, s1
156+fcvt s2, d3
157+fcmp d0, d1
158+fcmp s2, s3
159+fcmp d4, #0.0
160+fcmp s5, #0.0
161+scvtf d0, x1
162+scvtf s2, x3
163+ucvtf d4, x5
164+fcvtzs x0, d1
165+fcvtzu x2, s3
166+fmov d0, x1
167+fmov s2, w3
168+fmov x4, d5
169+fmov w6, s7
170+// addresses, calls
171+adr x0, .
172+adr x1, .-4
173+adr x2, .+1048572
174+adrp x0, _glob@PAGE ; add x0, x0, _glob@PAGEOFF
175+adrp x16, _glob@PAGE ; ldr x1, [x16, _glob@PAGEOFF]
176+adrp x16, _glob@PAGE ; str w2, [x16, _glob@PAGEOFF]
177+adrp x16, _glob@PAGE ; ldr d3, [x16, _glob@PAGEOFF]
178+adrp x16, _glob@PAGE ; str s4, [x16, _glob@PAGEOFF]
179+adrp x16, _byte@PAGE ; add x16, x16, _byte@PAGEOFF ; ldr x5, [x16]
180+bl _proc1
181+b _proc1
182+bl Lstart
183+blr x5
184+br x6
185+ret
186+// jumps within the procedure
187+b.eq L1
188+cbz x3, L1
189+cbnz x4, L1
190+tbnz x5, #3, .+8 ; b L1
191+tbz x6, #40, .+8 ; b L1
192+b L1
193+L1:
194+Ltop:
195+orr x0, xzr, x1
196+b.ne Ltop
197+b Ltop
198+b L2
199+b.lo L2
200+b L2
201+L2:
202+orr x1, xzr, x2
203+.p2align 4
204+// the farthest
205+b.ne Lfar
206+cbz x1, Lfar
207+.p2align 20
208+Lfar:
209+b.eq Lstart

test/a64/Asm.txt (history) added +58 -0

@@ -0,0 +1,58 @@
1+(* A64's assembler on a code procedure's instructions, from just after
2+ proc ... code, to end. expect.sh turns it into Apple's syntax. *)
3+Lat:
4+mov x0, x1; mov sp, x29; mov x29, sp; mov w2, w3; mov x4, 1234H; mov w5, -1;
5+mov x6, 0FFFF0000H; mov x7, -2; mov x8, #00FF00FF00FF00FFH;
6+movz x8, 0FFFFH, lsl 48; movk w9, 1, lsl 16; movn x10, 5; movz w11, #7;
7+add x0, x1, #16; add x0, x1, 1, lsl 12; add sp, sp, #32; sub sp, sp, #4095;
8+add x2, x3, -8; adds w4, w5, #1; cmp x6, #0; cmn w7, #3; cmp sp, #16;
9+add x8, x9, x10; add x11, x12, x13, lsl #2; sub w14, w15, w16, asr #31;
10+adds x17, x19, x20; subs x21, x22, x23, lsr #63; add sp, sp, x16;
11+add x0, sp, x1, lsl #3; cmp x1, x2; cmp w3, w4, lsl #4; cmn x5, x6;
12+neg x7, x8; neg w9, w10, lsl #2; mvn x11, x12; mvn w13, w14, ror #3;
13+and x0, x1, #0FFH; orr w2, w3, #0F0F0F0F0H; eor x4, x5, #5555555555555555H;
14+ands x6, x7, #1; tst x8, #8000000000000000H; tst w9, #0FFFFH;
15+and sp, x0, #-16; orr x10, x11, x12; eor w13, w14, w15, ror #8;
16+bic x16, x17, x19; orn w20, w21, w22, lsl #1; ands x23, x24, x25; tst x26, x27;
17+lsl x0, x1, x2; lsr w3, w4, w5; asr x6, x7, x8; ror w9, w10, w11;
18+lsl x0, x1, #12; lsr w2, w3, #31; asr x4, x5, #63; ror x6, x7, #1; ror w8, w9, #31;
19+mul x0, x1, x2; mul w3, w4, w5; madd x6, x7, x8, x9; msub w10, w11, w12, w13;
20+smulh x14, x15, x16; umulh x0, x1, x2; sdiv x3, x4, x5; udiv w6, w7, w8;
21+csel x0, x1, x2, eq; csinc w3, w4, w5, ne; csinv x6, x7, x8, hs;
22+csneg x9, x10, x11, lo; cset x12, mi; cset w13, ge; csetm x14, lt;
23+csel x15, x16, x17, cs; csel x0, x1, x2, cc; csel w3, wzr, w4, vs;
24+sxtb x0, w1; sxth w2, w3; sxtw x4, w5; uxtb w6, w7; uxth w8, w9;
25+ubfm x10, x11, #4, #7; sbfm w12, w13, #0, #15; ubfx x14, x15, #8, #16; sbfx x16, x17, #3, #61;
26+clz x0, x1; clz w2, w3; rbit x4, x5; rev x6, x7; rev w8, w9;
27+ldr x0, [x1]; ldr x2, [x3, #8]; ldr x4, [sp, #32760]; ldr w5, [x6, #16380];
28+ldrb w7, [x8, #4095]; ldrh w9, [x10, #2]; ldrsb x11, [x12, #1]; ldrsb w13, [x14];
29+ldrsh x15, [x16, #6]; ldrsh w17, [x19]; ldrsw x20, [x21, #4]; ldr x22, [x23, #-8];
30+ldr x24, [x25, #3]; ldur x26, [x27, #8]; ldurb w0, [x1, #-1]; ldursw x2, [x3, #-256];
31+ldr x4, [x5, x6]; ldr x7, [x8, x9, lsl #3]; ldrb w10, [x11, x12];
32+ldrh w13, [x14, x15, lsl #1]; ldr w16, [x17, x19, lsl #2];
33+ldr x0, [sp], #16; ldr x1, [x2, #-8]!; ldrb w3, [x4], #1; ldrsw x5, [x6, #255]!;
34+ldr d0, [x1, #8]; ldr s2, [x3]; ldr q4, [x5, #16]; ldr d6, [x7, x8, lsl #3]; ldur q9, [x10, #-16];
35+str x0, [x1]; str w2, [sp, #4]; strb w3, [x4, #4095]; strh w5, [x6, #8190];
36+str x7, [sp, #-16]!; str x8, [x9], #8; stur w10, [x11, #-4]; sturb w12, [x13, #255];
37+str x14, [x15, x16, lsl #3]; str xzr, [x17]; str d0, [sp, #8]; str s1, [x2, #-4]; str q3, [x4, #65520];
38+ldp x29, x30, [sp], #16; stp x29, x30, [sp, #-16]!; stp x19, x20, [sp, #504];
39+ldp w0, w1, [x2, #-256]; ldp x3, x4, [x5]; stp d8, d9, [sp, #-512]!;
40+ldp q0, q1, [x0, #1008]; stp s2, s3, [x1], #-256;
41+ldaddal x0, x1, [x2]; ldaddal w3, w4, [sp]; swpal x5, x6, [x7]; swpal w8, w9, [x10];
42+casal x11, x12, [x13]; casal w14, w15, [x16]; ldaxr x0, [x1]; ldaxr w2, [x3];
43+stlxr w4, x5, [x6]; stlxr w7, w8, [x9];
44+dmb ish; dmb sy; dsb ish; isb; nop; yield; svc #80H; svc 0; brk #1; brk 0F000H;
45+fmov d0, d1; fmov s2, s3; fmov d4, x5; fmov s6, w7; fmov x8, d9; fmov w10, s11;
46+fadd d0, d1, d2; fsub s3, s4, s5; fmul d6, d7, d8; fdiv s9, s10, s11;
47+fmax d12, d13, d14; fmin s15, s16, s17; fsqrt d0, d0; fsqrt s1, s2; fneg d3, d4; fabs s5, s6;
48+fcmp d0, d1; fcmp s2, s3; fcmp d4, #0; fcvt d0, s1; fcvt s2, d3;
49+scvtf d0, x1; scvtf s2, w3; ucvtf d4, w5; ucvtf s6, x7;
50+fcvtzs x0, d1; fcvtzs w2, s3; fcvtzu x4, s5; fcvtzu w6, d7;
51+Lloop:
52+cbz x0, Ldone; cbnz w1, Lloop; tbz x2, #3, Ldone; tbnz w3, #31, Lloop; tbz x4, #63, Ldone;
53+b.eq Lloop; b.ne Ldone; b.cs Lloop; b.hs Ldone; b.lo Lloop; b.al Ldone;
54+b Lloop; b Ldone; bl proc1; b proc1; adr x0, glob; adr x5, proc1;
55+br x1; blr x2; ret; ret x3;
56+Ldone:
57+db 1, 2, 3, 4; dd 0D503201FH, 12345678H, -1;
58+end

test/a64/Encode.expect (history) added +452 -0

@@ -0,0 +1,452 @@
1+aa0103e0
2+910003bf
3+910003fd
4+2a0303e2
5+d2824684
6+12800005
7+d2bfffe6
8+92800027
9+b2009fe8
10+d2ffffe8
11+72a00029
12+928000aa
13+528000eb
14+91004020
15+91400420
16+910083ff
17+d13fffff
18+d1002062
19+310004a4
20+f10000df
21+31000cff
22+f10043ff
23+8b0a0128
24+8b0d098b
25+4b907dee
26+ab140271
27+eb57fed5
28+8b3063ff
29+8b216fe0
30+eb02003f
31+6b04107f
32+ab0600bf
33+cb0803e7
34+4b0a0be9
35+aa2c03eb
36+2aee0fed
37+92401c20
38+3204cc62
39+d200f0a4
40+f24000e6
41+f241011f
42+72003d3f
43+927cec1f
44+aa0c016a
45+4acf21cd
46+8a330230
47+2a3606b4
48+ea190317
49+ea1b035f
50+9ac22020
51+1ac52483
52+9ac828e6
53+1acb2d49
54+d374cc20
55+531f7c62
56+937ffca4
57+93c704e6
58+13897d28
59+9b027c20
60+1b057c83
61+9b0824e6
62+1b0cb56a
63+9b507dee
64+9bc27c20
65+9ac50c83
66+1ac808e6
67+9a820020
68+1a851483
69+da8820e6
70+da8b3549
71+9a9f57ec
72+1a9fb7ed
73+da9fa3ee
74+9a91220f
75+9a823020
76+1a8463e3
77+93401c20
78+13003c62
79+93407ca4
80+53001ce6
81+53003d28
82+d3441d6a
83+13003dac
84+d3485dee
85+9343fe30
86+dac01020
87+5ac01062
88+dac000a4
89+dac00ce6
90+5ac00928
91+f9400020
92+f9400462
93+f97fffe4
94+b97ffcc5
95+397ffd07
96+79400549
97+3980058b
98+39c001cd
99+79800e0f
100+79c00271
101+b98006b4
102+f85f82f6
103+f8403338
104+f840837a
105+385ff020
106+b8900062
107+f86668a4
108+f8697907
109+386c696a
110+786f79cd
111+b8737a30
112+f84107e0
113+f85f8c41
114+38401483
115+b88ffcc5
116+fd400420
117+bd400062
118+3dc004a4
119+fc6878e6
120+3cdf0149
121+f9000020
122+b90007e2
123+393ffc83
124+793ffcc5
125+f81f0fe7
126+f8008528
127+b81fc16a
128+380ff1ac
129+f83079ee
130+f900023f
131+fd0007e0
132+bc1fc041
133+3dbffc83
134+a8c17bfd
135+a9bf7bfd
136+a91fd3f3
137+29600440
138+a94010a3
139+6da027e8
140+ad5f8400
141+2ca00c22
142+f8e00041
143+b8e303e4
144+f8e580e6
145+b8e88149
146+c8ebfdac
147+88eefe0f
148+c85ffc20
149+885ffc62
150+c804fcc5
151+8807fd28
152+d5033bbf
153+d5033fbf
154+d5033b9f
155+d5033fdf
156+nop * 1
157+d503203f
158+d4001001
159+d4000001
160+d4200020
161+d43e0000
162+1e604020
163+1e204062
164+9e6700a4
165+1e2700e6
166+9e660128
167+1e26016a
168+1e622820
169+1e253883
170+1e6808e6
171+1e2b1949
172+1e6e49ac
173+1e315a0f
174+1e61c000
175+1e21c041
176+1e614083
177+1e20c0c5
178+1e612000
179+1e232040
180+1e602088
181+1e22c020
182+1e624062
183+9e620020
184+1e220062
185+1e6300a4
186+9e2300e6
187+9e780020
188+1e380062
189+9e3900a4
190+1e7900e6
191+b40002e0
192+35ffffe1
193+361802a2
194+37ffffa3
195+b6f80264
196+54ffff60
197+54000221
198+54ffff22
199+540001e2
200+54fffee3
201+540001ae
202+17fffff5
203+1400000b
204+94000000
205+14000000
206+90000000
207+91000000
208+90000005
209+910000a5
210+d61f0020
211+d63f0040
212+d65f03c0
213+d65f0060
214+04030201
215+nop * 1
216+12345678
217+ffffffff
218+d2800000
219+d2824681
220+d2a24682
221+92800003
222+92a00024
223+b2009fe5
224+d29bde06
225+f2b35786
226+f2cacf06
227+f2e24686
228+929530e7
229+f2c24687
230+b20003e8
231+b200f3e9
232+d2f0000a
233+92f0000b
234+b2407fec
235+d29579ad
236+f2dfffed
237+aa0103e0
238+910003bf
239+910003fd
240+8b020020
241+ab050083
242+cb0800e6
243+eb0b0149
244+8a0e01ac
245+aa11020f
246+ca150293
247+ea1802f6
248+8a3b0359
249+aa3e03bc
250+8b020c20
251+cb85fc83
252+aac804e6
253+913ffc20
254+91400420
255+910043ff
256+d1448fff
257+d1002020
258+d1404862
259+d10d1442
260+d288acf0
261+f2a02470
262+8b3063e4
263+d28468b0
264+f2a00030
265+ab3060c5
266+92401c20
267+b27c0c3f
268+d2824690
269+ca100062
270+eb01001f
271+f10083ff
272+b100145f
273+d2820030
274+f2a02010
275+eb30607f
276+ea05009f
277+f24000df
278+f24100ff
279+cb0103e0
280+aa2303e2
281+9ac22020
282+9ac52483
283+9ac828e6
284+9acb2d49
285+1ac52083
286+d37df020
287+d37ffc20
288+9341fc62
289+93c51ca4
290+530100e6
291+13894128
292+d340fc20
293+d3483c20
294+93407c62
295+93401c20
296+93403c62
297+93407ca4
298+53001ce6
299+53003d28
300+2a0b03ea
301+9b027c20
302+9b051883
303+9b09a907
304+9b427c20
305+9bc57c83
306+9ac50c83
307+9ac808e6
308+9a820020
309+9a851483
310+da88b4e6
311+9a9fd7e9
312+dac01020
313+5ac01062
314+dac000a4
315+f9400020
316+f97ffc20
317+d2900010
318+f8706862
319+f85f80a4
320+f85000a4
321+f84030e6
322+397ffd28
323+3980116a
324+797ffdac
325+79800dee
326+b97fffe0
327+b9800441
328+389ff083
329+f9000420
330+b90003e2
331+78001083
332+393ffcc5
333+f90000ff
334+f8627820
335+38a56883
336+b86878e6
337+782b7949
338+f82e69ac
339+f84107e0
340+f81f0fe1
341+b8100c62
342+384ff4a4
343+fd400420
344+bd400462
345+3dc008a4
346+3dbfffe6
347+fc1fc107
348+bd000149
349+a9bf7bfd
350+a8c17bfd
351+a91fd3f3
352+a9605835
353+f8e10040
354+b8e300a4
355+f8e68107
356+b8e9816a
357+c8ecfdcd
358+88effe30
359+d5033bbf
360+d4001001
361+d4000001
362+d4200020
363+d43e0000
364+1e620820
365+1e621820
366+1e622820
367+1e623820
368+1e624820
369+1e625820
370+1e252883
371+1e604020
372+1e60c020
373+1e614020
374+1e61c020
375+1e21c0e6
376+1e22c020
377+1e624062
378+1e612000
379+1e232040
380+1e602088
381+1e2020a8
382+9e620020
383+9e220062
384+9e6300a4
385+9e780020
386+9e390062
387+9e670020
388+1e270062
389+9e6600a4
390+1e2600e6
391+10000000
392+10ffffe1
393+107fffe2
394+90000000
395+91000000
396+90000010
397+f9400201
398+90000010
399+b9000202
400+90000010
401+fd400203
402+90000010
403+bd000204
404+90000010
405+91000210
406+f9400205
407+94000000
408+14000000
409+97fffe68
410+d63f00a0
411+d61f00c0
412+d65f03c0
413+54000100
414+b40000e3
415+b50000c4
416+37180045
417+14000004
418+b6400046
419+14000002
420+14000001
421+aa0103e0
422+54ffffe1
423+17fffffe
424+14000003
425+54000043
426+14000001
427+aa0203e1
428+nop * 1
429+547fca81
430+b47fca61
431+nop * 261714
432+54800000
433+reloc 000000000000032c ARM64_RELOC_BRANCH26 _proc1
434+reloc 0000000000000330 ARM64_RELOC_BRANCH26 _proc1
435+reloc 0000000000000334 ARM64_RELOC_PAGE21 _glob
436+reloc 0000000000000338 ARM64_RELOC_PAGEOFF12 _glob
437+reloc 000000000000033c ARM64_RELOC_PAGE21 _proc1
438+reloc 0000000000000340 ARM64_RELOC_PAGEOFF12 _proc1
439+reloc 0000000000000624 ARM64_RELOC_PAGE21 _glob
440+reloc 0000000000000628 ARM64_RELOC_PAGEOFF12 _glob
441+reloc 000000000000062c ARM64_RELOC_PAGE21 _glob
442+reloc 0000000000000630 ARM64_RELOC_PAGEOFF12 _glob
443+reloc 0000000000000634 ARM64_RELOC_PAGE21 _glob
444+reloc 0000000000000638 ARM64_RELOC_PAGEOFF12 _glob
445+reloc 000000000000063c ARM64_RELOC_PAGE21 _glob
446+reloc 0000000000000640 ARM64_RELOC_PAGEOFF12 _glob
447+reloc 0000000000000644 ARM64_RELOC_PAGE21 _glob
448+reloc 0000000000000648 ARM64_RELOC_PAGEOFF12 _glob
449+reloc 000000000000064c ARM64_RELOC_PAGE21 _byte
450+reloc 0000000000000650 ARM64_RELOC_PAGEOFF12 _byte
451+reloc 0000000000000658 ARM64_RELOC_BRANCH26 _proc1
452+reloc 000000000000065c ARM64_RELOC_BRANCH26 _proc1

test/a64/Encode.raz (history) added +306 -0

@@ -0,0 +1,306 @@
1+(* A64's encodings, checked against Apple's assembler: its assembler on
2+ Asm.txt, then every routine of its interface (api), into one
3+ procedure's chunk, which is printed a word to a line in hex (a run of
4+ nop as one line), then the fixups. Api.s holds the same instructions
5+ as api's calls, a line for each, and expect.sh makes Encode.expect
6+ from Asm.txt and it with cc and objdump on an arm64 Mac. The
7+ assembler goes first, at the chunk's start, as a code procedure is:
8+ a tbz's link, the place of the jump before it on its label's chain,
9+ counts from there in 14 bits. The interface's last jumps are the
10+ farthest b.cond and cbz reach, 1 MB. test/check.sh compiles this with
11+ -I src, as A64 isn't in the compiler yet. *)
12+module Encode;
13+import Fmt, Diag, Scan, Chunk, A := A64;
14+import SYSTEM;
15+
16+var
17+ body, proc1, glob, byte: INT; (* chunks: the code, and three it names *)
18+
19+(* The calls, in Api.s's order *)
20+proc api;
21+var L, L2, top: INT;
22+begin
23+ (* moves *)
24+ A.movRI(0, 0);
25+ A.movRI(1, 1234H);
26+ A.movRI(2, 12340000H);
27+ A.movRI(3, -1);
28+ A.movRI(4, -10001H);
29+ A.movRI(5, 00FF00FF00FF00FFH);
30+ A.movRI(6, 123456789ABCDEF0H);
31+ A.movRI(7, I64(0FFFF1234FFFF5678H));
32+ A.movRI(8, 100000001H);
33+ A.movRI(9, 5555555555555555H);
34+ A.movRI(10, I64(8000000000000000H));
35+ A.movRI(11, 7FFFFFFFFFFFFFFFH);
36+ A.movRI(12, 0FFFFFFFFH);
37+ A.movRI(13, 0FFFF0000ABCDH);
38+ A.movRR(0, 1);
39+ A.movRR(A.SP, A.FP);
40+ A.movRR(A.FP, A.SP);
41+ (* two registers *)
42+ A.alu(A.opAdd, 0, 1, 2);
43+ A.alu(A.opAdds, 3, 4, 5);
44+ A.alu(A.opSub, 6, 7, 8);
45+ A.alu(A.opSubs, 9, 10, 11);
46+ A.alu(A.opAnd, 12, 13, 14);
47+ A.alu(A.opOrr, 15, 16, 17);
48+ A.alu(A.opEor, 19, 20, 21);
49+ A.alu(A.opAnds, 22, 23, 24);
50+ A.alu(A.opBic, 25, 26, 27);
51+ A.alu(A.opOrn, 28, 29, 30);
52+ A.aluShift(A.opAdd, 0, 1, 2, A.shLsl, 3);
53+ A.aluShift(A.opSub, 3, 4, 5, A.shAsr, 63);
54+ A.aluShift(A.opOrr, 6, 7, 8, A.shRor, 1);
55+ (* immediates *)
56+ A.aluI(A.opAdd, 0, 1, 4095);
57+ A.aluI(A.opAdd, 0, 1, 4096);
58+ A.aluI(A.opAdd, A.SP, A.SP, 16);
59+ A.aluI(A.opSub, A.SP, A.SP, 123000H);
60+ A.aluI(A.opAdd, 0, 1, -8);
61+ A.aluI(A.opSub, 2, 3, 12345H);
62+ A.aluI(A.opAdd, 4, A.SP, 1234567H);
63+ A.aluI(A.opAdds, 5, 6, 12345H);
64+ A.aluI(A.opAnd, 0, 1, 0FFH);
65+ A.aluI(A.opOrr, A.SP, 1, 0F0H);
66+ A.aluI(A.opEor, 2, 3, 1234H);
67+ A.cmp(0, 1);
68+ A.cmpI(A.SP, 32);
69+ A.cmpI(2, -5);
70+ A.cmpI(3, 1001001H);
71+ A.alu(A.opAnds, A.ZR, 4, 5);
72+ A.aluI(A.opAnds, A.ZR, 6, 1);
73+ A.aluI(A.opAnds, A.ZR, 7, I64(8000000000000000H));
74+ A.neg(0, 1);
75+ A.mvn(2, 3);
76+ (* shifts and fields *)
77+ A.shift(A.shLsl, 0, 1, 2, 8);
78+ A.shift(A.shLsr, 3, 4, 5, 8);
79+ A.shift(A.shAsr, 6, 7, 8, 8);
80+ A.shift(A.shRor, 9, 10, 11, 8);
81+ A.shift(A.shLsl, 3, 4, 5, 4);
82+ A.shiftI(A.shLsl, 0, 1, 3, 8);
83+ A.shiftI(A.shLsr, 0, 1, 63, 8);
84+ A.shiftI(A.shAsr, 2, 3, 1, 8);
85+ A.shiftI(A.shRor, 4, 5, 7, 8);
86+ A.shiftI(A.shLsl, 6, 7, 31, 4);
87+ A.shiftI(A.shRor, 8, 9, 16, 4);
88+ A.shiftI(A.shLsl, 0, 1, 0, 8);
89+ A.field(false, 0, 1, 8, 8);
90+ A.field(true, 2, 3, 0, 32);
91+ A.extend(0, 1, 1, true);
92+ A.extend(2, 3, 2, true);
93+ A.extend(4, 5, 4, true);
94+ A.extend(6, 7, 1, false);
95+ A.extend(8, 9, 2, false);
96+ A.extend(10, 11, 4, false);
97+ (* multiply, divide, select, count *)
98+ A.mul(0, 1, 2);
99+ A.madd(3, 4, 5, 6, false);
100+ A.madd(7, 8, 9, 10, true);
101+ A.mulHigh(true, 0, 1, 2);
102+ A.mulHigh(false, 3, 4, 5);
103+ A.divide(true, 3, 4, 5);
104+ A.divide(false, 6, 7, 8);
105+ A.csel(A.csSel, A.ccEQ, 0, 1, 2);
106+ A.csel(A.csInc, A.ccNE, 3, 4, 5);
107+ A.csel(A.csNeg, A.ccLT, 6, 7, 8);
108+ A.cset(A.ccGT, 9);
109+ A.clz(0, 1, 8);
110+ A.clz(2, 3, 4);
111+ A.rbit(4, 5, 8);
112+ (* loads and stores *)
113+ A.load(0, 1, 0, 8, false);
114+ A.load(0, 1, 32760, 8, false);
115+ A.load(2, 3, 32768, 8, false);
116+ A.load(4, 5, -8, 8, false);
117+ A.load(4, 5, -256, 8, false);
118+ A.load(6, 7, 3, 8, false);
119+ A.load(8, 9, 4095, 1, false);
120+ A.load(10, 11, 4, 1, true);
121+ A.load(12, 13, 8190, 2, false);
122+ A.load(14, 15, 6, 2, true);
123+ A.load(0, A.SP, 16380, 4, false);
124+ A.load(1, 2, 4, 4, true);
125+ A.load(3, 4, -1, 1, true);
126+ A.store(0, 1, 8, 8);
127+ A.store(2, A.SP, 0, 4);
128+ A.store(3, 4, 1, 2);
129+ A.store(5, 6, 4095, 1);
130+ A.store(A.ZR, 7, 0, 8);
131+ A.loadR(0, 1, 2, 8, false, true);
132+ A.loadR(3, 4, 5, 1, true, false);
133+ A.loadR(6, 7, 8, 4, false, true);
134+ A.storeR(9, 10, 11, 2, true);
135+ A.storeR(12, 13, 14, 8, false);
136+ A.loadIdx(0, A.SP, 16, 8, A.mPost);
137+ A.storeIdx(1, A.SP, -16, 8, A.mPre);
138+ A.storeIdx(2, 3, -256, 4, A.mPre);
139+ A.loadIdx(4, 5, 255, 1, A.mPost);
140+ A.loadF(0, 1, 8, 8);
141+ A.loadF(2, 3, 4, 4);
142+ A.loadF(4, 5, 32, 16);
143+ A.storeF(6, A.SP, 65520, 16);
144+ A.storeF(7, 8, -4, 8);
145+ A.storeF(9, 10, 0, 4);
146+ A.stp(A.FP, A.LR, A.SP, -16, A.mPre);
147+ A.ldp(A.FP, A.LR, A.SP, 16, A.mPost);
148+ A.stp(19, 20, A.SP, 504, A.mOff);
149+ A.ldp(21, 22, 1, -512, A.mOff);
150+ (* atomics and the system's *)
151+ A.ldaddal(1, 0, 2, 8);
152+ A.ldaddal(3, 4, 5, 4);
153+ A.swpal(6, 7, 8, 8);
154+ A.swpal(9, 10, 11, 4);
155+ A.casal(12, 13, 14, 8);
156+ A.casal(15, 16, 17, 4);
157+ A.dmb();
158+ A.svc(80H);
159+ A.svc(0);
160+ A.brk(1);
161+ A.brk(0F000H);
162+ (* reals *)
163+ A.fop(A.fMul, 0, 1, 2, false);
164+ A.fop(A.fDiv, 0, 1, 2, false);
165+ A.fop(A.fAdd, 0, 1, 2, false);
166+ A.fop(A.fSub, 0, 1, 2, false);
167+ A.fop(A.fMax, 0, 1, 2, false);
168+ A.fop(A.fMin, 0, 1, 2, false);
169+ A.fop(A.fAdd, 3, 4, 5, true);
170+ A.fop1(A.fMov, 0, 1, false);
171+ A.fop1(A.fAbs, 0, 1, false);
172+ A.fop1(A.fNeg, 0, 1, false);
173+ A.fop1(A.fSqrt, 0, 1, false);
174+ A.fop1(A.fSqrt, 6, 7, true);
175+ A.fcvt(0, 1, false);
176+ A.fcvt(2, 3, true);
177+ A.fcmp(0, 1, false);
178+ A.fcmp(2, 3, true);
179+ A.fcmp(4, -1, false);
180+ A.fcmp(5, -1, true);
181+ A.scvtf(0, 1, false, true);
182+ A.scvtf(2, 3, true, true);
183+ A.scvtf(4, 5, false, false);
184+ A.fcvtz(0, 1, false, true);
185+ A.fcvtz(2, 3, true, false);
186+ A.fmovFR(0, 1, false);
187+ A.fmovFR(2, 3, true);
188+ A.fmovRF(4, 5, false);
189+ A.fmovRF(6, 7, true);
190+ (* addresses, calls *)
191+ A.adr(0, 0);
192+ A.adr(1, -4);
193+ A.adr(2, 1048572);
194+ A.addrChunk(0, glob, 0);
195+ A.loadChunk(1, glob, 0, 8, false);
196+ A.storeChunk(2, glob, 0, 4);
197+ A.loadChunkF(3, glob, 0, 8);
198+ A.storeChunkF(4, glob, 0, 4);
199+ A.loadChunk(5, byte, 0, 8, false);
200+ A.callChunk(proc1);
201+ A.jmpChunk(proc1);
202+ A.callBack(0);
203+ A.callR(5);
204+ A.jmpR(6);
205+ A.ret();
206+ (* jumps within the procedure: forward on a chain, back *)
207+ L := A.NoLabel;
208+ A.jcc(A.ccEQ, L);
209+ A.cbz(false, 3, L);
210+ A.cbz(true, 4, L);
211+ A.tbz(false, 5, 3, L);
212+ A.tbz(true, 6, 40, L);
213+ A.jmp(L);
214+ A.fixLink(L);
215+ top := Chunk.pc;
216+ A.movRR(0, 1);
217+ A.jccBack(A.ccNE, top);
218+ A.jmpBack(top);
219+ L := A.NoLabel; L2 := A.NoLabel;
220+ A.jmp(L);
221+ A.jcc(A.ccLO, L2);
222+ A.jmp(L);
223+ A.fixLink(A.joinLinks(L, L2));
224+ L := A.NoLabel;
225+ A.movRR(1, 2);
226+ A.jmp(L);
227+ A.dropJumpTo(L);
228+ A.fixLink(L);
229+ A.align(16);
230+ (* the farthest: b.cond and cbz to 1 MB on, and b.cond 1 MB back *)
231+ L := A.NoLabel;
232+ A.jcc(A.ccNE, L);
233+ A.cbz(false, 1, L);
234+ A.align(100000H);
235+ A.fixLink(L);
236+ A.jccBack(A.ccEQ, 0);
237+end;
238+
239+(* The test's reader of a constant: a number, perhaps negative *)
240+proc konst(_whole: BOOL): (I64, ERROR);
241+var neg: BOOL; v: I64;
242+begin
243+ neg := Scan.tok = Scan.sMinus;
244+ if neg then Scan.next; end;
245+ if Scan.tok # Scan.sInt then return 0, Scan.mark("expected a number"); end;
246+ v := Scan.ival;
247+ Scan.next;
248+ if neg then return -v, nil; end;
249+ return v, nil;
250+end;
251+
252+(* and of a name: proc1 and glob *)
253+proc name: (INT, ERROR);
254+begin
255+ if Scan.nameOf(Scan.id) = "proc1" then Scan.next; return proc1, nil; end;
256+ if Scan.nameOf(Scan.id) = "glob" then Scan.next; return glob, nil; end;
257+ return -1, nil;
258+end;
259+
260+proc chunk(n: []const U8; sec: Chunk.Section): INT;
261+begin
262+ return Chunk.newChunk(sec, -1, Scan.intern(SYSTEM.PTR(n), LEN(n)));
263+end;
264+
265+const
266+ Kinds: [4][]const U8 = ["", "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21", "ARM64_RELOC_PAGEOFF12"];
267+ Nop = 0D503201FH;
268+
269+var
270+ err: ERROR;
271+ i, n, w: INT;
272+ why: []const U8;
273+
274+begin
275+ body := chunk("code", Chunk.secText);
276+ proc1 := chunk("proc1", Chunk.secText);
277+ glob := chunk("glob", Chunk.secBss);
278+ Chunk.setBss(glob, 8, 8);
279+ byte := chunk("byte", Chunk.secBss);
280+ Chunk.setBss(byte, 8, 1);
281+ Chunk.beginChunk(body);
282+ why := Scan.open("test/a64/Asm.txt");
283+ if LEN(why) > 0 then Fmt.print("test/a64/Asm.txt: {}\n", [Fmt.str(why)]); end;
284+ Scan.next;
285+ err := A.assemble(konst, name);
286+ if err # nil then Fmt.print("the assembler failed\n", []); end;
287+ api();
288+ Chunk.endChunk(body);
289+ i := 0;
290+ while i < Chunk.pc do
291+ w := Chunk.get4At(i) & 0FFFFFFFFH;
292+ n := 0;
293+ while (i < Chunk.pc) and (w = Nop) and ((Chunk.get4At(i) & 0FFFFFFFFH) = Nop) do INC(n); INC(i, 4); end;
294+ if n > 0 then
295+ Fmt.print("nop * {}\n", [Fmt.int(n)]);
296+ else
297+ Fmt.print("{08}\n", [Fmt.lowHex(U64(w))]);
298+ INC(i, 4);
299+ end;
300+ end;
301+ for i := 0 to Chunk.numFixups - 1 do
302+ Fmt.print("reloc {016} {} _{}\n", [Fmt.lowHex(U64(Chunk.fixups[i].at)),
303+ Fmt.str(Kinds[INT(Chunk.fixups[i].kind)]), Fmt.str(Scan.nameOf(Chunk.chunks[Chunk.fixups[i].chunk].name))]);
304+ end;
305+ Diag.finish;
306+end Encode.

test/a64/expect.sh (history) added +33 -0

@@ -0,0 +1,33 @@
1+#!/bin/sh
2+# Makes test/a64/Encode.expect, what Encode.raz must print, from Apple's
3+# assembler: Asm.txt, A64's assembler's part, turned into Apple's syntax
4+# (raz's comments dropped, 10H as 0x10, `adr x0, v` as the adrp and add
5+# it stands for, a name as its symbol, _v, db and dd as .byte and .long,
6+# and ; between instructions as a new line, since ; begins a comment
7+# there), then Api.s, the instructions of Encode.raz's calls of A64.
8+# Each word of the object's code, a run of nop as one line, then its
9+# relocations, sorted, as Encode.raz prints its fixups.
10+# Run on an arm64 Mac, from the repository's root: sh test/a64/expect.sh
11+set -e
12+d=test/a64
13+t=$(mktemp -d)
14+trap 'rm -rf "$t"' EXIT
15+{
16+ echo Lstart:
17+ sed -E -e '/^\(\*/,/\*\)/d' -e '/^end$/d' \
18+ -e 's/([0-9][0-9A-F]*)H/0x\1/g' \
19+ -e 's/adr (x[0-9]+), (glob|proc1)/adrp \1, _\2@PAGE; add \1, \1, _\2@PAGEOFF/g' \
20+ -e 's/(b|bl) proc1/\1 _proc1/g' \
21+ -e 's/(fcmp [ds][0-9]+, #0);/\1.0;/g' \
22+ -e 's/^db /.byte /; s/; dd /; .long /' $d/Asm.txt
23+ cat $d/Api.s
24+} | tr ';' '\n' > $t/all.s
25+cc -c -arch arm64 $t/all.s -o $t/all.o
26+objdump -d $t/all.o | awk '
27+ /^ *[0-9a-f]+:/ {
28+ if ($2 == "d503201f") { nops++; next }
29+ if (nops) { print "nop * " nops; nops = 0 }
30+ print $2
31+ }
32+ END { if (nops) print "nop * " nops }' > $d/Encode.expect
33+objdump -r $t/all.o | awk '/ARM64_RELOC/ { print "reloc", $1, $2, $3 }' | sort >> $d/Encode.expect

test/check.sh (history) modified +13 -1

@@ -16,7 +16,8 @@
1616 # the compiler's own version in a library's note written as N); there
1717 # X.args holds the compiler's options. The examples, test/libc, the
1818 # tools and the library's tests are compiled with -Werror, so warnings
19-# fail them. Then the version, tools/Doc.raz, the report's examples,
19+# fail them. test/a64/Encode.raz checks arm64's encoder, src/A64.raz,
20+# against Apple's assembler. Then the version, tools/Doc.raz, the report's examples,
2021 # the tutorial's, tools/Pretty.raz, and the library's own tests.
2122
2223 raz=./raz
@@ -101,6 +102,17 @@
101102 libc=' -libc musl'
102103 for f in test/libc/*.raz; do run test/libc $(basename $f .raz); done
103104 libc=
105+fi
106+
107+# A64, arm64's encoder, which no compiler for this target imports: its
108+# test is compiled with src/ for its modules, and prints what Apple's
109+# assembler makes of the same instructions (test/a64/expect.sh)
110+if $raz -Werror -I src -I build/src -o $out/Encode test/a64/Encode.raz 2>$out/Encode.cerr &&
111+ $out/Encode > $out/Encode.out 2>&1 && cmp -s $out/Encode.out test/a64/Encode.expect; then
112+ pass=$((pass + 1))
113+else
114+ echo "FAIL test/a64/Encode"; cat $out/Encode.cerr; diff $out/Encode.out test/a64/Encode.expect | head -10
115+ fail=$((fail + 1))
104116 fi
105117
106118 # raz run: a static program and one over C, from memory, with their