From 6d4487fbe2e3e0c6213e719b1f1d28e0880fafa6 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:42:28 +0000 Subject: [PATCH] Gen.arm64: division and the checks, calls in full, try and defer, atomics, COPY PLAN.md 5, step 5b. Division and mod check zero and the smallest value by -1, as arm64 doesn't trap; every check Gen.x86_64 makes reaches Rt.fail by stubs that pass the place. Arguments past x7, results through x8, Apple's variadic C calls, try, deferred statements, return f(x) of several results, jump tables, compareSeq; and the atomics and COPY, which Lock and Sys need. Rt.darwin-arm64 tells a failed check and a fault as Linux does. mac-check runs conform/run too: 91 of 111 pass on the Mac, the rest waiting on reals, FILL, CLZ and ROL (5c). x86-64's output is unchanged for 202 programs; the fixpoint holds. --- diff --git a/PLAN.md b/PLAN.md index cb5dbed..a3508e7 100644 --- a/PLAN.md +++ b/PLAN.md @@ -247,12 +247,23 @@ exit, one procedure at exit, fail and stop by `write`. As the interface check of `Rt` reads `Rt.raz`, and so compiles `Sys` over C, also `lib/CAbi.darwin-arm64.raz`, from `tools/cabi.c` on the Mac, and a - code procedure skipped in a file read only for its interface. Left of - step 5: division and its check, the other checks and their stubs for - `Rt.fail`, the reals, arguments and results past the registers or in - memory (`x8`), Apple's variadic calls, `try`, deferred statements, - atomics and system calls, `COPY`, `FILL`, `NEW`'s zeroing, the bit - counts and rotations, copies past 256 bytes. + code procedure skipped in a file read only for its interface. + + 5b, done: division and its checks (by zero, the smallest by -1, in + every width), the checks of indexes, slices, views and enumerations + with their stubs for `Rt.fail`, arguments past x7 on the stack, + results in memory through x8, Apple's variadic calls, `try`, deferred + statements, jump tables, `compareSeq`, copies past 256 bytes, `ABS` + of an integer; and, since `Out` needs them, the atomics and `COPY`. + `SYSTEM.SYSCALL` is an error on the Mac, Linux's only (report 6.8). + `lib/Rt.darwin-arm64.raz` says what failed with its values, by its + address, runs 32 procedures at exit, and tells a nil pointer or + procedure and a stack overflow by a handler of SIGSEGV and SIGBUS. + `make mac-check` runs conform/run too and counts it: 91 of 111 pass, + the others needing reals (13), `FILL` (4, `Heap`'s among them), + `CLZ`, `ROL`, or `SYSCALL` (`SystemImport`, Linux's only). Left of + step 5 (5c): the reals, `FILL`, `NEW`'s zeroing, the counts of bits + and the rotations. 6. `Exe.darwin.raz`'s line numbers for lldb (its rebases came with 5a); `Host.darwin.raz`. 7. The library: `CAbi`, `Sys`, `Rt`, `Thread`, `Bytes`, `Math`, `Str`. diff --git a/doc/compiler.md b/doc/compiler.md index 9b9fe83..4239580 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -1,6 +1,6 @@ # Reading the raz compiler -The compiler is fifteen files of raz, about 16,100 lines of code (the +The compiler is fifteen files of raz, about 16,400 lines of code (the budget is 18,000); three of them, `A64.raz`, `Gen.arm64.raz` and `Exe.darwin.raz`, are the Mac's back end, begun (`PLAN.md` 5), built only into a compiler for `darwin-arm64` (`src/cross.sh`). It is its own compiler: a release of it, the one @@ -25,7 +25,7 @@ | `src/X64.raz` | 1,771 | 1,450 | The instruction encoder, jumps within a procedure, the assembler | | `src/A64.raz` | 1,843 | 1,365 | The same for arm64: the encoder, jumps, the assembler | | `src/Gen.x86_64.raz` | 2,861 | 1,999 | The stack machine, for x86-64: values, operations, checks, calls, frames | -| `src/Gen.arm64.raz` | 1,468 | 1,107 | The same for arm64, begun: frames, values, operations, jumps, calls | +| `src/Gen.arm64.raz` | 1,993 | 1,398 | The same for arm64, begun: frames, values, operations, checks, calls | | `src/Item.raz` | 2,553 | 2,051 | Items: types, constants, variables, operators, conversions, calls | | `src/Parse.raz` | 4,948 | 4,198 | Declarations, statements, expressions, built-ins, recovery, warnings | | `src/Link.raz` | 481 | 365 | Tree shaking, layout, patching, the places | @@ -1716,10 +1716,13 @@ answers every call `Gen.x86_64.raz` answers, with the same parameters, as the interface check holds the two files to (report, 3), and makes frames, constants, the values of variables and their stores, the -integer operations but division, comparisons and jumps, elements and -slices unchecked, calls with integer arguments in registers, C's -calls, code procedures (`A64.assemble`) and the entry point. `Gen.Arch` -is `"arm64"`. +integer operations, division with its checks, comparisons and jumps, +jump tables, elements and slices and their checks, calls with integer +arguments in registers and on the stack, results in memory, C's calls +and Apple's variadic ones, `try`, deferred statements, the atomics, +`COPY`, code procedures (`A64.assemble`) and the entry point; not yet +the reals, `FILL`, `NEW`'s zeroing, the counts of bits and the +rotations (step 5c). `Gen.Arch` is `"arm64"`. *Not yet.* What it can't make yet isn't refused at once, since a library module holds much that a program never calls: the C library's @@ -1737,6 +1740,8 @@ doesn't compiles. `beginProc` comes before its chunk is begun, so its notes wait for `enterBody` (`pending`). A routine not yet made reads into `_` the parameters it doesn't use yet, so that none is warned of. +`SYSTEM.SYSCALL`, which the report gives only on Linux (6.8), is noted +the same way, with a message of its own, and stays so. *The stack* is x86-64's, kept as plainly as it can be: the value at depth d is in `Regs[d mod 6]`, x9 to x14, which a call may change and @@ -1785,13 +1790,51 @@ numbered from `XmmVar`, 32, above every x register, which `Parse` tells apart by it). -*Calls* move each argument into x0 to x7; a single result comes back in -x0, two words in x0 and x1, and a narrow result of C's is extended, as -C leaves the upper bits as they fall. C's procedure is called through -the quadword the loader fills in, `adrp x16` of its page, `ldr x17, -[x16, ...]` and `blr x17`; a procedure value from its slot, `blr x17` -too. +*Calls* move each argument into x0 to x7, a slice's two words into two +of them or both onto the stack. The arguments past the registers go on +the machine's stack, 8 bytes each, the first at sp, in an area that sp +is lowered by for the call alone and that keeps it a multiple of 16; +the callee finds them above its frame record, at x29 + 16 on, as x86's +finds them above rbp. A C procedure that ends in `...` takes what comes +past its own parameters on the stack, registers free or not, as +Apple's convention has it (C's own parameters past x7 narrower than 8 +bytes, which Apple packs, raz doesn't make). A single result comes back +in x0, two words in x0 and x1, and a narrow result of C's is extended, +as C leaves the upper bits as they fall; a result in memory, a record +or several results, goes to the caller's temporary, whose address the +caller puts in x8 and the callee keeps in a slot (`retSlot`) for +`resultTo`, `copyResult` and `try`'s `returnError`. C's procedure is +called through the quadword the loader fills in, `adrp x16` of its +page, `ldr x17, [x16, ...]` and `blr x17`; a procedure value from its +slot, `blr x17` too. A deferred statement is a subroutine of its +procedure, called by `bl`, as on x86-64; since its own calls would +change x30, it keeps x30 on the machine's stack, 16 bytes, for its +`ret`. +*Checks* are x86-64's (`check`, `endFails`): a branch, not taken when +the check holds, to code at the procedure's end that puts `Rt.fail`'s +values in x1, x2 (a slice's b), x3 (the length) and x5 (an +enumeration's name) and calls a stub of its kind, `check0` to `check7`, +which `entryPoint` makes: `sub x4, x30, #4`, the place of the check's +`bl`; the kind in x0; x6 and x7, the registers x86's trap report shows, +zero; and `bl Rt.fail`. A slice in memory has its length loaded into x3 +first, where the failing code finds it. Two things x86 catches and +arm64 doesn't are checked as they are made: a division by zero, and +the smallest value of a signed type divided by -1, which `sdiv` takes +without a fault (`divide`), both stopping the program as `Rt.fail`'s +kind 5, a division fault, as SIGFPE does on Linux. What the Mac does +catch, `Rt`'s handler tells: a nil pointer within page zero, 4 GB +(`NilPage`), a call to nil, and a stack overflow at the guard page, +each a SIGSEGV or SIGBUS, on a stack of its own (`lib/Rt.darwin-arm64.raz`). + +The rest is x86's, in arm64's instructions, each shown in its +routine's comment: `copyBytes` and `zeroBytes` past 256 bytes by a loop +of words; `compareSeq` a byte at a time; `jumpTable`'s table of words +after a `br`, found by `adr`; the atomics by the LSE instructions, +`casal`, `swpal` and `ldaddal`; `COPY` (`copySlice`) by words, then +bytes, back from the ends when the destination starts inside the +source; `ABS` by `cneg`. + *The entry point* (`entryPoint`) is the C `main` that dyld calls: it pushes a frame record, which links to dyld's, saves argc, an `int` it extends to 64 bits, and argv, gives `Rt` C's `exit` in `cExit` and the @@ -2570,7 +2613,8 @@ compiler for the Mac this way, in the linux/amd64 container, and `make mac-check` (`test/mac.sh`), on an Apple Silicon Mac, has it compile `test/mac`'s programs there and runs each here, natively, against its -`X.expect` and `X.status`. The host changes nothing of the target: +`X.expect` and `X.status`; then conform/run's, which are counted, not +failures yet, those that fail listed in `build/mac/conform.fail`. The host changes nothing of the target: a program for another system still needs that system's `Sys` and `Rt`, and for a kernel the options `-bare`, `-s` and `-base`. diff --git a/lib/Rt.darwin-arm64.raz b/lib/Rt.darwin-arm64.raz index bda5d05..b2ce13e 100644 --- a/lib/Rt.darwin-arm64.raz +++ b/lib/Rt.darwin-arm64.raz @@ -1,53 +1,76 @@ -(* The run time, for macOS on arm64: for now the least a program needs - to end, with lib/Rt.raz's interface, which every file of Rt keeps. - The compiler finds exit, fail and cExit by these names. exit runs - the procedure atExit registered, then ends the program by C's exit, - which the entry point gives cExit, as every program on a Mac reaches - the kernel through libSystem; fail and stop say what failed and end - it with status 2. It leaves out what lib/Rt.raz does on Linux, which - PLAN.md 5's step 7 brings here: more than one procedure at exit, the - places a failure is told by, the signals' handlers, the trace of - calls and the profiler; place, trace and startProfile do nothing. *) +(* The run time, for macOS on arm64, with lib/Rt.raz's interface, which + every file of Rt keeps. The compiler finds exit, fail and cExit by + these names. exit runs the procedures atExit registered, then ends + the program by C's exit, which the entry point gives cExit, as every + program on a Mac reaches the kernel through libSystem; fail says + what failed, with its values, and stop its message, and they end it + with status 2; and a fault the machine catches, a nil pointer or + procedure or a stack overflow, is told by a handler, on a stack of + its own, as on Linux, and ends it so too. A failure is told by its + address, as on Linux in a program built with raz -s: the places, the + calls under way and the profiler are what PLAN.md 5's step 7 brings + here; place, trace and startProfile do nothing yet. *) module Rt; import SYSTEM; const Full*: ERROR = "too many procedures to run at exit"; (* atExit's *) - Failed = "raz: a check failed\n"; + MaxAtExit = 32; + Digits = "0123456789abcdef"; + (* the signals a fault raises, and sigaction's flags SA_ONSTACK, + SA_RESETHAND and SA_SIGINFO, as macOS's has them *) + SigIll = 4; SigTrap = 5; SigFpe = 8; SigBus = 10; SigSegv = 11; + Flags = 1H + 4H + 40H; + Low = 100000000H; (* page zero: no address below this is ever mapped *) +type + (* What sigaction and sigaltstack take, as macOS lays them out *) + Action = record handler: proc(sig: I32; info, ctx: ^U8); mask, flags: I32; end; + Stack = record sp: ^U8; size: INT; flags: I32; end; + extern proc write(fd: I32; buf: ^U8; n: UINT): INT; +extern proc sigaction(sig: I32; act, old: ^U8): I32; +extern proc sigaltstack(ss, old: ^U8): I32; var - atExitProc: proc; (* the procedure atExit registered, or nil *) + atExits: [MaxAtExit]proc; + numAtExit: INT; ending: INT; (* the status exit was given, once it has been *) cExit: proc(status: I32); (* C's exit, set first thing *) placer: proc(a: UINT); (* place, set first thing, or nil under raz -s *) profiler: proc; (* startProfile, set first thing, or nil *) + line: [256]U8; (* the message being made *) + lineLen: INT; + act: Action; + alt: Stack; + altStack: [65536]U8; (* where the handler runs, even when the stack is full *) -(* Registers p to run when the program ends by exit: one, for now *) +(* Registers p to run when the program ends by exit *) proc atExit*(p: proc): ERROR; begin - if atExitProc # nil then return Full; end; - atExitProc := p; + if numAtExit = MaxAtExit then return Full; end; + atExits[numAtExit] := p; + INC(numAtExit); return nil; end; -(* The status exit was given, while the procedure atExit registered - runs; 0 before *) +(* The status exit was given, while the procedures atExit registered + run; 0 before *) proc exitStatus*: INT; begin return ending; end; -(* Runs the procedure atExit registered, taken off first so that it - runs once, then ends the program with status *) +(* Runs the procedures registered with atExit, the last first, each + taken off first so that it runs once, then ends the program with + status *) proc exit*(status: INT); var p: proc; begin ending := status; - if atExitProc # nil then - p := atExitProc; - atExitProc := nil; + while numAtExit > 0 do + DEC(numAtExit); + p := atExits[numAtExit]; p(); end; cExit(I32(status)); @@ -62,6 +85,72 @@ exit(2); end; +(* Messages, made in line, as lib/Rt.raz makes them, one byte kept for + the line feed, and written by say in one piece *) +proc put(s: []const U8); +var i: INT; +begin + for i := 0 to LEN(s) - 1 do + if lineLen < LEN(line) - 1 then + line[lineLen] := s[i]; + INC(lineLen); + end; + end; +end; + +(* The digits from the last, a negative n's from its negative + remainders, so that the lowest INT comes out too *) +proc putInt(n: INT); +var buf: [20]U8; i: INT; neg: BOOL; +begin + neg := n < 0; + i := 20; + repeat + DEC(i); + if neg then buf[i] := U8(-(n mod 10)) + '0'; else buf[i] := U8(n mod 10) + '0'; end; + n := n div 10; + until n = 0; + if neg then put("-"); end; + put(buf[i..20]); +end; + +proc putHex(u: UINT); +var buf: [16]U8; i: INT; +begin + i := 16; + repeat + DEC(i); + buf[i] := Digits[INT(u & 15)]; + u := u shr 4; + until u = 0; + put("0x"); + put(buf[i..16]); +end; + +proc putStr(s: ^U8); +var n: INT; +begin + n := 0; + while s[n] # 0 do INC(n); end; + put(s[0..n]); +end; + +proc say; +begin + line[lineLen] := '\n'; + _ := write(2, SYSTEM.PTR(line), UINT(lineLen + 1)); + lineLen := 0; +end; + +(* Puts where the code at address a is: its address, for now *) +proc where(a: UINT); +begin + if placer # nil then placer(a); end; + put("at "); + putHex(a); + put(": "); +end; + (* Where the code at address a comes from: not told yet *) proc place*(a: UINT); begin @@ -73,13 +162,60 @@ begin end; -(* A check failed: the compiler's code calls this with what failed, - its values and where, none of which it tells yet *) +(* A check failed in the code at address at: says where, and what + failed, as lib/Rt.raz's fail, whose comment says what each kind is, + then ends the program by exit with status 2. The registers that + x86-64's trap report shows are none here. *) proc fail*(what, a, b, len: INT; at: UINT; name: ^U8; rdi, rsi: UINT); begin - _ := what; _ := a; _ := b; _ := len; _ := name; _ := rdi; _ := rsi; - if placer # nil then placer(at); end; - _ := write(2, SYSTEM.PTR(Failed), LEN(Failed)); + _ := rdi; _ := rsi; + where(at); + if what = 4 then put("stopped by a nil pointer"); + elsif what = 5 then put("stopped by a division fault"); + elsif what = 6 then put("stopped by a stack overflow"); + elsif what = 0 then put("index "); putInt(a); + elsif what = 7 then + put("a view at index "); putInt(a); + put(" runs past a length of "); putInt(len); + elsif (what = 1) or (what = 3) then + put("slice "); putInt(a); put(".."); putInt(b); + if what = 3 then put(" runs backwards"); end; + else + putInt(a); put(" isn't a position of "); putStr(name); + end; + if what < 2 then put(" is out of range for a length of "); putInt(len); end; + say; + exit(2); +end; + +(* A fault stops the program: says where it was and why on standard + error, then ends it by exit with status 2, as a failed check does. + info and ctx are the kernel's siginfo and ucontext: the address that + faulted is at 24 in siginfo, and the registers at uc_mcontext, a + pointer at 48 in ucontext, past 16 bytes of the exception's state: + x0 to x28, then fp, lr, sp and pc. *) +proc onSignal(sig: I32; info, ctx: ^U8); +var adr, sp, pc: UINT; q: ^UINT; why: []const U8; +begin + q := ^UINT(info + 24); + adr := q^; + q := ^UINT(ctx + 48); + q := ^UINT(q^ + 16); + sp := q[31]; + pc := q[32]; + if sig = SigFpe then why := "a division fault"; + elsif pc < Low then + why := "a nil procedure"; + pc := q[30] - 4; (* the call, by its return address in lr *) + elsif adr < Low then why := "a nil pointer"; + elsif adr - sp + 100000H < 200000H then why := "a stack overflow"; (* within a megabyte of sp *) + elsif (sig = SigIll) or (sig = SigTrap) then why := "a trap"; + else why := "a bad address"; + end; + where(pc); + put("stopped by "); + put(why); + say; exit(2); end; @@ -90,4 +226,12 @@ begin _ := profiler; (* started here when RAZ_PROFILE is set, by step 7's Rt *) + alt := {sp: SYSTEM.ADR(altStack[0]), size: LEN(altStack)}; + _ := sigaltstack(^U8(SYSTEM.ADR(alt)), nil); + act := {handler: onSignal, flags: Flags}; + _ := sigaction(SigSegv, ^U8(SYSTEM.ADR(act)), nil); + _ := sigaction(SigBus, ^U8(SYSTEM.ADR(act)), nil); + _ := sigaction(SigFpe, ^U8(SYSTEM.ADR(act)), nil); + _ := sigaction(SigIll, ^U8(SYSTEM.ADR(act)), nil); + _ := sigaction(SigTrap, ^U8(SYSTEM.ADR(act)), nil); end Rt. diff --git a/src/Gen.arm64.raz b/src/Gen.arm64.raz index cfa2158..f867943 100644 --- a/src/Gen.arm64.raz +++ b/src/Gen.arm64.raz @@ -4,13 +4,14 @@ The same stack machine as x86-64's, with the same calls, which Item and Parse make: they push constants, addresses and the values of variables, operate on the values on top, store them and jump on - them. This one is begun: what it makes so far is frames, constants, - the values of variables and their stores, the integer operations but - division, comparisons and jumps, elements and slices unchecked, - calls of procedures with integer arguments in registers, C's through - the quadword the loader fills in, code procedures and the program's - entry point. What else is - asked is noted as "not yet on arm64" (notYet), and a program that + them. What it makes so far is frames, constants, the values of + variables and their stores, the integer operations, comparisons and + jumps, jump tables, elements and slices and their checks, calls with + integer arguments in registers and on the stack, C's through the + quadword the loader fills in, results in memory, try, deferred + statements, the atomics, COPY, code procedures and the program's + entry point. What else + is asked is noted as "not yet on arm64" (notYet), and a program that uses it fails to compile rather than run wrong; PLAN.md 5 says the pieces still to come. @@ -33,17 +34,20 @@ pointer, and x30, the return address. Calls use Apple's arm64 convention: the first eight integer arguments - in x0 to x7, results in x0 and x1, sp a multiple of 16 always, a + in x0 to x7, the rest on the machine's stack, results in x0 and x1, + or in memory at the address in x8, sp a multiple of 16 always, a frame record of x29 and x30 that x29 points at, so that the chain of frames can be followed. A frame is made whole by the prologue, so - nothing is pushed in a body: sp stays where the prologue put it, and - pushed is always 0. + nothing is pushed in a body but a call's stack arguments, for the + call, and a deferred statement's return address: pushed is always 0. + What x86-64 catches by itself, and arm64 doesn't, the code checks: a + division by zero, and the smallest value by -1 (divide). + Depends on: Scan and Diag for errors, Sym for types, Chunk for code and data, A64 for instructions. - Leaves out, for now: reals, division, checks, COPY and FILL, - arguments and parameters on the machine's stack, results in memory, - try, deferred statements, atomics and system calls. *) + Leaves out, for now: reals, FILL, NEW's zeroing, the counts of bits + and the rotations; and SYSCALL, which is Linux's only. *) module Gen; import Fmt, Diag, Scan, Sym, Chunk, A := A64; import SYSTEM; @@ -53,9 +57,11 @@ NoLabel* = -1; WordSize* = 8; (* the size of an address, and of INT *) (* What the machine catches by itself: a load or store within - NilPage bytes of address 0 (the Mac's page zero is 4 GB; this is - Linux's figure until Rt tells the Mac's faults) *) - NilPage* = 4096; + NilPage bytes of address 0, in the Mac's page zero of 4 GB, which + Rt's handler tells as a nil pointer; and a call to nil, and a + stack overflow at the guard page under the stack. A division by + zero it doesn't catch: op checks for it. *) + NilPage* = 100000000H; FP = A.FP; LR = A.LR; SP = A.SP; ZR = A.ZR; T = 15; U = 17; (* Gen's scratch *) @@ -140,8 +146,18 @@ into that chunk, reached by adrp (A64.loadChunk) *) Mem = record base, chunk: INT; off: I64; end; + (* a check of the procedure, whose failure endFails makes: what + failed, a's register, the length's (or -1 for the constant n), + the enumeration's name, and the place *) + Fail = record + L, what, ra, lenReg, name: INT; + n: I64; + path, line, col: INT; + end; + const MaxStack = 1024; (* values waiting in one expression *) + StubNames: [8][]const U8 = ["check0", "check1", "check2", "check3", "check4", "check5", "check6", "check7"]; NumRegs = 6; Regs: [NumRegs]INT = [9, 10, 11, 12, 13, 14]; (* the condition codes of the comparisons, from sEql: = # < <= > >= *) @@ -161,17 +177,24 @@ retSlot: I64; resType: ^Sym.Type; (* the procedure's result, or nil *) exitL: INT; - (* parameters arriving in registers: where each is stored on entry *) - inReg: [8]INT; - inSlot: [8]I64; - inSize: [8]INT; - inObj: [8]^Sym.Obj; + (* parameters arriving in registers, x0 to x7, and a result's address + in x8: where each is stored on entry *) + inReg: [9]INT; + inSlot: [9]I64; + inSize: [9]INT; + inObj: [9]^Sym.Obj; numIn: INT; + procParams: ^Sym.Obj; (* the parameters, for enterBody *) regMask: INT; (* the registers of variables, as bits (XBit) *) saveAt: I64; (* where they are saved, a quadword each *) frameAt: [3]I64; (* frameTop, frameMax, permTop after the declarations *) pending: []const U8; (* what beginProc found not yet made, for enterBody's chunk *) pendingAt: Diag.Pos; + (* the stubs that a failed check calls, one for each kind of failure, + made by entryPoint for those used; and the procedure's checks *) + failStubs: [8]INT; + fails: [4096]Fail; + numFails: INT; (* What this Gen can't make yet marks the procedure being compiled (Chunk.setMissing), which is an error if the program uses it, and the @@ -179,21 +202,21 @@ calls, as Sys does. So each routine not yet made keeps the stack as the real one would, and makes what code it likes, never run; it reads into _ the parameters it doesn't use yet, so that none is - warned of. *) -proc notYetAt(what: []const U8; p: Diag.Pos); + warned of. What this Gen will never make, SYSCALL, is marked so too, + with its own message. *) +proc missing(msg: []const U8); begin if codeChunk >= 0 then - Chunk.setMissing(codeChunk, Diag.say("not yet on arm64: {}", [Fmt.str(what)]), p); + Chunk.setMissing(codeChunk, msg, Scan.tokPos()); elsif LEN(pending) = 0 then (* beginProc's, before enterBody names the chunk *) - pending := Diag.say("not yet on arm64: {}", [Fmt.str(what)]); - pendingAt := p; + pending := msg; + pendingAt := Scan.tokPos(); end; end; -(* The same, at the place being read *) proc notYet(what: []const U8); begin - notYetAt(what, Scan.tokPos()); + missing(Diag.say("not yet on arm64: {}", [Fmt.str(what)])); end; (* -S: the text of each instruction is kept, and list prints it *) @@ -499,14 +522,40 @@ end; (* Copying, by loads and stores of 8, 4, 2 and 1 bytes, from [x1] to - [x0], through x2 *) + [x0], through x2. Past MaxMoves bytes the words go by a loop, which + moves x0 and x1 on, counting down in x3, and the last few bytes + after it as before: + mov x3, #words + top: ldr x2, [x1], #8 + str x2, [x0], #8 + subs x3, x3, #1 + b.ne top + ... ; the size mod 8 bytes left, from [x1] to [x0] + + zeroBytes is the same, storing the zero register. *) + const MaxMoves = 256; +(* The loop's head and tail, of the words of size bytes, by store and + load if load; returns what is left after the words *) +proc wordLoop(size: I64; load: BOOL): I64; +var top: INT; +begin + if size <= MaxMoves then return size; end; + A.movRI(3, size div 8); + top := Chunk.pc; + if load then A.loadIdx(Tmp, Src, 8, 8, A.mPost); A.storeIdx(Tmp, Dst, 8, 8, A.mPost); + else A.storeIdx(ZR, Dst, 8, 8, A.mPost); end; + A.aluI(A.opSubs, 3, 3, 1); + A.jccBack(A.ccNE, top); + return size mod 8; +end; + proc copyBytes(size: I64); var o, n: I64; begin - if size > MaxMoves then notYet("a copy of more than 256 bytes"); return; end; + size := wordLoop(size, true); o := 0; while o < size do n := 8; @@ -520,7 +569,7 @@ proc zeroBytes(size: I64); var o, n: I64; begin - if size > MaxMoves then notYet("zeroing more than 256 bytes"); return; end; + size := wordLoop(size, false); o := 0; while o < size do n := 8; @@ -560,6 +609,71 @@ zeroBytes(size); end; +(* Checks *) + +(* The name s, interned *) +proc internStr(s: []const U8): INT; +begin + return Scan.intern(SYSTEM.PTR(s), LEN(s)); +end; + +(* The program goes on if the condition cc holds, and otherwise stops + in Rt.fail(what, a, b, len, at, name), as on x86-64, whose check says + what each is (Gen.x86_64.raz). Here a is in register ra and b, where + there is one, in x2; len is in register lenReg, or the constant n if + lenReg is -1. The failing code is out of the way, at the procedure's + end (endFails), so that a check that holds is a branch not taken; it + has p for its place, worked out now. *) +proc check(cc, what: INT; p: Diag.Pos; ra, lenReg: INT; n: I64; name: INT); +var f: INT; +begin + if numFails > LEN(fails) - 1 then + _ := Scan.mark(Diag.say("more than {} checks in one procedure", [Fmt.int(LEN(fails))])); + return; + end; + f := numFails; + fails[f].L := NoLabel; + A.jcc(A.invert(cc), fails[f].L); + fails[f].what := what; + fails[f].ra := ra; + fails[f].lenReg := lenReg; + fails[f].n := n; + fails[f].name := name; + fails[f].path := Chunk.curFilePath(); + fails[f].line, fails[f].col := Scan.lineCol(p.a); + INC(numFails); +end; + +(* The failures of the procedure's checks: each puts Rt.fail's values in + the registers it takes them in, x3 first, since a is never there, + then x1 and x5, and calls the stub for its kind, which adds what + failed and where (entryPoint): + + mov x3, x10 ; the length, or mov x3, #n + mov x1, x15 ; a + adrp x5, name; add x5 ... ; an enumeration's name + bl check0 *) +proc endFails; +var i, path: INT; f: Fail; +begin + path := Chunk.curFilePath(); + for i := 0 to numFails - 1 do + f := fails[i]; + A.fixLink(f.L); + Chunk.setCurFile(f.path); + Chunk.noteLine(f.line, f.col); + Chunk.setCurFile(path); + if f.lenReg < 0 then A.movRI(3, f.n); elsif f.lenReg # 3 then A.movRR(3, f.lenReg); end; + if f.ra # 1 then A.movRR(1, f.ra); end; + if f.name >= 0 then A.addrChunk(5, f.name, 0); end; + if failStubs[f.what] < 0 then + failStubs[f.what] := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr(StubNames[f.what])); + end; + A.callChunk(failStubs[f.what]); + end; + numFails := 0; +end; + (* Operations *) (* The right operand of the two values on top, popped, in register y: @@ -586,6 +700,46 @@ end; end; +(* r div y, or r mod y, of bits bits, signed or not, y being the + constant v if c. x86's idiv stops the program for a division by + zero, and for the smallest value divided by -1, which overflows; the + report binds both (6.1), and arm64's sdiv and udiv give a value for + each, so the code checks first, as Rt.fail's kind 5, a division + fault. The smallest value is that of the type's width, for a narrow + one, an I32's -2^31, sign-extended in 64 bits. Of an I64: + + cmp x17, #0 + b.eq fail ; by zero + cmn x17, #1 + b.ne L + mov x15, #8000000000000000H + cmp x9, x15 + b.eq fail ; the smallest by -1 + L: sdiv x15, x9, x17 + mov x9, x15 ; div; for mod, msub x9, x15, x17, x9 + + msub is x9 - x15 * x17, what is left. A constant divisor other than + 0 needs no first check, and other than -1 no second. *) +proc divide(sy: Scan.Sym; r, y, bits: INT; signed, c: BOOL; v: I64); +var L: INT; +begin + if not c or (v = 0) then + A.cmpI(y, 0); + check(A.ccNE, 5, Scan.tokPos(), r, -1, 0, -1); + end; + if signed and (not c or (v = -1)) then + L := NoLabel; + A.cmpI(y, -1); + A.jcc(A.ccNE, L); + A.movRI(T, I64(-1) shl (bits - 1)); + A.cmp(r, T); + check(A.ccNE, 5, Scan.tokPos(), r, -1, 0, -1); + A.fixLink(L); + end; + A.divide(signed, T, r, y); + if sy = Scan.sDiv then A.movRR(r, T); else A.madd(r, T, y, r, true); end; +end; + (* The two values on top, the left op the right, an integer of size bytes, signed or not, computed in 64 bits and brought back to its width, which is how a narrow integer wraps. A shift's count is taken @@ -594,7 +748,6 @@ var v: I64; r, y, bits, sh: INT; c, alu: BOOL; begin if k in {kF32, kF64} then notYet("reals"); end; - if (sy = Scan.sDiv) or (sy = Scan.sMod) then notYet("div and mod"); end; bits := size * 8; alu := (sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor); (* a constant goes right, where it can be an immediate *) @@ -616,6 +769,8 @@ A.alu(aluOf(sy), r, r, y); elsif sy = Scan.sTimes then A.mul(r, r, y); + elsif (sy = Scan.sDiv) or (sy = Scan.sMod) then + divide(sy, r, y, bits, signed, c, v); else (* sShl, sShr: the machine takes the count modulo 64 *) if bits < 64 then A.aluI(A.opAnd, U, y, bits - 1); y := U; end; A.shift(sh, r, r, y, 8); @@ -643,10 +798,21 @@ notYet("POPCOUNT"); end; +(* ABS of the signed integer on top: negated if negative, and cut back + to its width, so that the smallest value gives itself, as -x does + (Gen.x86_64.raz says more): + + cmp x9, #0 + cneg x9, x9, lt ; csneg x9, x9, x9, ge + sxtw x9, w9 ; an I32 *) proc abs*(k: Kind; size: INT); +var r: INT; begin - _ := k; _ := size; - notYet("ABS"); + if k in {kF32, kF64} then notYet("reals"); end; + r := top(); + A.cmpI(r, 0); + A.csel(A.csNeg, A.ccGE, r, r, r); + if size < 8 then A.extend(r, r, size, true); end; end; (* The two values on top, compared: a BOOL, 1 or 0 *) @@ -714,11 +880,48 @@ stack[depth - 1].k := k; end; +(* Whether the slices in the frame at a and b (the offsets of their + pointers, the lengths 8 bytes on) are equal (or not, if not eq): the + lengths, then the bytes, len shl shift of them, a byte at a time. The + flags say equal or not, where the loop leaves it: + + ldr x2, [x29, #b + 8] + ldr x15, [x29, #a + 8] + cmp x2, x15 + b.ne out ; the lengths differ + ldr x1, [x29, #b] + ldr x0, [x29, #a] + lsl x2, x2, #shift + top: cmp x2, #0 + b.eq out ; no bytes left: equal + ldrb w15, [x0], #1 + ldrb w17, [x1], #1 + sub x2, x2, #1 + cmp x15, x17 + b.eq top + out: cset x9, eq ; or ne *) proc compareSeq*(a, b: I64; shift: INT; eq: BOOL); +var r, out, loop: INT; begin - _ := a; _ := b; _ := shift; _ := eq; - notYet("comparing slices"); - _ := target(); + r := target(); + out := NoLabel; + A.load(Tmp, FP, INT(b) + 8, 8, false); + A.load(T, FP, INT(a) + 8, 8, false); + A.cmp(Tmp, T); + A.jcc(A.ccNE, out); + A.load(Src, FP, INT(b), 8, false); + A.load(Dst, FP, INT(a), 8, false); + if shift > 0 then A.shiftI(A.shLsl, Tmp, Tmp, shift, 8); end; + loop := Chunk.pc; + A.cmpI(Tmp, 0); + A.jcc(A.ccEQ, out); + A.loadIdx(T, Dst, 1, 1, A.mPost); + A.loadIdx(U, Src, 1, 1, A.mPost); + A.aluI(A.opSub, Tmp, Tmp, 1); + A.cmp(T, U); + A.jccBack(A.ccEQ, loop); + A.fixLink(out); + if eq then A.cset(A.ccEQ, r); else A.cset(A.ccNE, r); end; computed(kWord); end; @@ -768,19 +971,39 @@ _ := size; notYet("NEW"); end; + +(* CAS(v, old, new), XCHG(v, x) or XADD(v, x), from the stack, v's + address under the rest: the result where the address was. By the + LSE instructions every Apple processor has, each with acquire and + release, as x86's lock does: casal stores new if [v] holds old, + leaving what [v] held where old was, which says whether it did: + + mov x17, x15 ; old + casal x17, x10, [x9] ; x10, new + cmp x17, x15 + cset x9, eq + swpal and ldaddal leave what [v] held in x17, the result. *) proc atomic*(which: INT); +var r, n: INT; begin - notYet("CAS, XCHG and XADD"); - if which = Sym.bCas then drop(); end; - drop(); + if which = Sym.bCas then n := top(); drop(); end; + popTo(T); + r := top(); + match which of + | Sym.bCas: A.movRR(U, T); A.casal(U, n, r, 8); A.cmp(U, T); A.cset(A.ccEQ, r); + | Sym.bXchg: A.swpal(T, U, r, 8); A.movRR(r, U); + | else: A.ldaddal(T, U, r, 8); A.movRR(r, U); + end; stack[depth - 1].k := kWord; end; +(* SYSTEM.SYSCALL is Linux's only (report 6.8): macOS has no stable + system calls, and a program calls the C library there *) proc sysCall*(n: INT); var i: INT; begin - notYet("SYSCALL"); + missing("SYSTEM.SYSCALL is Linux's only: call the C library"); for i := 1 to n do drop(); end; _ := target(); computed(kWord); @@ -856,14 +1079,45 @@ A.fixLink(L); end; +(* A jump table, for a match on the integer in frame slot slot, whose + labels run from lo up for n values. The selector less lo, compared + unsigned (so below lo is above n too), is out of the table if it + isn't below n, and goes to the else arm at elseAt, or, if there is + none, to endL, the end of the match. Else it picks a word of the + table that follows the jump, an offset from the table's start, which + adr finds four instructions on: + + ldr x15, [x29, #slot] + sub x15, x15, #lo + cmp x15, #n - 1 + b.hi else + adr x17, table + ldrsw x15, [x17, x15, lsl #2] + add x15, x17, x15 + br x15 + table: .word arm0 - table, arm1 - table, ... + + It returns the table's start; the caller then makes the n entries + with tableEntry. *) proc jumpTable*(slot, lo: I64; n, elseAt: INT; var endL: INT): INT; +const TableAt = 16; +var start: INT; begin - _ := slot; _ := lo; _ := n; _ := elseAt; _ := endL; - notYet("a jump table"); - return Chunk.pc; + A.load(T, FP, INT(slot), 8, false); + if lo # 0 then A.aluI(A.opSub, T, T, lo); end; + A.cmpI(T, n - 1); + if elseAt # NoLabel then A.jccBack(A.ccHI, elseAt); else A.jcc(A.ccHI, endL); end; + start := Chunk.pc + TableAt; + A.adr(U, TableAt); + A.loadR(T, U, T, 4, true, true); + A.alu(A.opAdd, T, U, T); + A.jmpR(T); + if Chunk.pc # start then Diag.fatal("internal error: the jump table is not where it was said"); end; + return start; end; -(* The next entry of the table that jumpTable started at table *) +(* The next entry of the table that jumpTable started at table: the + code at target *) proc tableEntry*(table, target: INT); begin Chunk.put4(target - table); @@ -884,30 +1138,55 @@ A.fixLinkTo(L, top); end; -(* Checks, and what checks as it goes *) +(* Checks, and what checks as it goes, as on x86-64, whose comments + say more; a comparison is unsigned, so that a negative index is a + huge one *) +(* The index on top is below n *) proc checkIndex*(n: I64; p: Diag.Pos); +var r: INT; begin - _ := n; - notYetAt("checks", p); + r := top(); + A.cmpI(r, n); + check(A.ccLO, 0, p, r, -1, n, -1); end; +(* The index on top is where a view starts in an array of n elements, + below below *) proc checkView*(n, below: I64; p: Diag.Pos); +var r: INT; begin - _ := n; _ := below; - notYetAt("checks", p); + r := top(); + A.cmpI(r, below); + check(A.ccLO, 7, p, r, -1, n, -1); end; +(* The integer on top is a position of an enumeration of n names *) proc checkEnum*(n: I64; name: INT; p: Diag.Pos); +var r: INT; begin - _ := n; _ := name; - notYetAt("checks", p); + r := top(); + A.cmpI(r, n); + check(A.ccLO, 2, p, r, -1, n, name); end; +(* The address on top, to be used reach bytes past, isn't nil, unless + the machine would stop it, within page zero *) proc checkNil*(reach: I64; p: Diag.Pos); +var r: INT; +begin + if reach <= NilPage then return; end; + r := top(); + A.cmpI(r, 0); + check(A.ccNE, 4, p, r, -1, 0, -1); +end; + +(* What a failed index check is: an index past the length (0), or a + view that runs past it (7) when it needs room elements more *) +proc kindOfIndex(room: I64): INT; begin - _ := reach; - notYetAt("checks", p); + if room > 0 then return 7; end; + return 0; end; (* r times v, an element's size: by a shift where v is a power of two, @@ -927,17 +1206,42 @@ (* Pops an index, and the address of the slice at a if it is on the stack, and makes the address of the element it picks: the slice's - pointer plus the index times size *) + pointer plus the index times size. The index is checked against the + length, in its register or loaded into x3; a view, which needs room + elements after the one indexed, against the length less the index, + which can't wrap once the index is below it: + + ldr x3, [x29, #-24] ; the length + cmp x15, x3 + b.hs fail + sub x2, x3, x15 + cmp x2, #room + b.ls fail *) proc indexSlice*(a: Adr; size, room: I64; checked: BOOL; p: Diag.Pos); -var m: Mem; r: INT; +var m, ml: Mem; r, len: INT; begin - if checked or (room > 0) then notYetAt("checks", p); end; popTo(T); + if a.base = bReg then + len := a.hi; + else + m := place(a, U); + ml := m; ml.off := ml.off + 8; + len := 3; + if checked then loadMem(len, ml, 8, false); end; + end; + if checked then + A.cmp(T, len); + check(A.ccLO, kindOfIndex(room), p, T, len, 0, -1); + if room > 0 then + A.alu(A.opSub, Tmp, len, T); + A.cmpI(Tmp, room); + check(A.ccHI, 7, p, T, len, 0, -1); + end; + end; mulI(T, size); if a.base = bReg then A.alu(A.opAdd, T, T, a.chunk); else - m := place(a, U); loadMem(U, m, 8, false); A.alu(A.opAdd, T, T, U); end; @@ -966,20 +1270,32 @@ (* Pops hi and lo, and the address of the array or slice at a if it is on the stack, and makes the slice lo..hi of it, of elements of size bytes, in the frame at tmp: its pointer, the start plus lo times size, - and its length, hi - lo *) + and its length, hi - lo. The array has n elements. Two checks, both + unsigned, so that a negative bound fails too: hi against the length, + then lo against hi; lo is in x1 and hi in x2, as Rt.fail takes a and + b. *) proc slice*(a: Adr; isArray: BOOL; n, size, tmp: I64; checked: BOOL; p: Diag.Pos); -var m: Mem; +var m, ml: Mem; len: INT; begin - _ := n; - if checked then notYetAt("checks", p); end; popTo(Tmp); (* hi *) popTo(Src); (* lo *) - if a.base = bReg then - A.movRR(U, a.chunk); - else - m := place(a, U); - if isArray then adrTo(U, m); else loadMem(U, m, 8, false); end; + if a.base # bReg then m := place(a, U); end; + if checked then + if isArray then + len := -1; + A.cmpI(Tmp, n); + else + len := a.hi; + if a.base # bReg then len := 3; ml := m; ml.off := ml.off + 8; loadMem(len, ml, 8, false); end; + A.cmp(Tmp, len); + end; + check(A.ccLS, 1, p, Src, len, n, -1); + A.cmp(Src, Tmp); + check(A.ccLS, 1, p, Src, len, n, -1); end; + if a.base = bReg then A.movRR(U, a.chunk); + elsif isArray then adrTo(U, m); + else loadMem(U, m, 8, false); end; A.alu(A.opSub, Tmp, Tmp, Src); A.store(Tmp, FP, INT(tmp) + 8, 8); mulI(Src, size); @@ -987,10 +1303,79 @@ A.store(U, FP, INT(tmp), 8); end; +(* The x2 bytes from [x1] to [x0], n at a time while x2 holds n or more, + through x15: forward, moving x1 and x0 on after each, or back, from + the ends, moving them down first *) +proc copyRun(n: INT; back: BOOL); +var top, out: INT; +begin + top := Chunk.pc; + out := NoLabel; + A.cmpI(Tmp, n); + A.jcc(A.ccLO, out); + if back then + A.loadIdx(T, Src, -n, n, A.mPre); A.storeIdx(T, Dst, -n, n, A.mPre); + else + A.loadIdx(T, Src, n, n, A.mPost); A.storeIdx(T, Dst, n, n, A.mPost); + end; + A.aluI(A.opSub, Tmp, Tmp, n); + A.jmpBack(top); + A.fixLink(out); +end; + +(* COPY: the elements of the slice in the frame at sOff, of size bytes + each, to the start of the one at dOff, which must be at least as long + (the source may be shorter): slice 0..LEN(s) of d, checked. They go + by words, then the last few bytes one by one, forward; but back, from + the ends, when the destination starts inside the source, so that an + overlap comes out right (report 6.8): + + ldr x2, [x29, #sOff + 8] + ldr x3, [x29, #dOff + 8] + cmp x2, x3 + b.hi fail ; the source longer than the destination + ldr x1, [x29, #sOff] + ldr x0, [x29, #dOff] + cmp x0, x1 + b.ls fwd ; the destination not above: forward + add x15, x1, x2 + cmp x0, x15 + b.hs fwd ; nor inside the source + add x1, x1, x2 ; back, from the ends + add x0, x0, x2 + ... ; copyRun(8, back), copyRun(1, back) + b out + fwd: ... ; copyRun(8), copyRun(1) + out: *) proc copySlice*(dOff, sOff, size: I64; checked: BOOL; p: Diag.Pos); +var fwd, out: INT; begin - _ := dOff; _ := sOff; _ := size; _ := checked; - notYetAt("COPY", p); + A.load(Tmp, FP, INT(sOff) + 8, 8, false); + if checked then + A.load(3, FP, INT(dOff) + 8, 8, false); + A.movRI(Src, 0); (* a, the slice's start *) + A.cmp(Tmp, 3); + check(A.ccLS, 1, p, Src, 3, 0, -1); + end; + mulI(Tmp, size); + A.load(Src, FP, INT(sOff), 8, false); + A.load(Dst, FP, INT(dOff), 8, false); + fwd := NoLabel; + A.cmp(Dst, Src); + A.jcc(A.ccLS, fwd); + A.alu(A.opAdd, T, Src, Tmp); + A.cmp(Dst, T); + A.jcc(A.ccHS, fwd); + A.alu(A.opAdd, Src, Src, Tmp); + A.alu(A.opAdd, Dst, Dst, Tmp); + copyRun(8, true); + copyRun(1, true); + out := NoLabel; + A.jmp(out); + A.fixLink(fwd); + copyRun(8, false); + copyRun(1, false); + A.fixLink(out); end; proc fillSlice*(dOff, size, n: I64; scalar: BOOL); @@ -1000,13 +1385,17 @@ drop(); end; -(* Pops hi, lo and a pointer, and makes the slice p[lo..hi] at tmp *) +(* Pops hi, lo and a pointer, and makes the slice p[lo..hi] at tmp. Its + bounds can't be known, but it can't run backwards. *) proc slicePtr*(size, tmp: I64; checked: BOOL; p: Diag.Pos); begin - if checked then notYetAt("checks", p); end; popTo(Tmp); (* hi *) popTo(Src); (* lo *) popTo(U); (* the pointer *) + if checked then + A.cmp(Src, Tmp); + check(A.ccLE, 3, p, Src, -1, 0, -1); + end; A.alu(A.opSub, Tmp, Tmp, Src); A.store(Tmp, FP, INT(tmp) + 8, 8); mulI(Src, size); @@ -1014,36 +1403,74 @@ A.store(U, FP, INT(tmp), 8); end; +(* The words the parameters of procedure type sig take: two for a + slice passed by value, one for anything else *) +proc paramWords(sig: ^Sym.Type): INT; +var q: ^Sym.Obj; n: INT; +begin + n := 0; + q := sig^.fields; + while q # nil do + if (q^.typ^.form = Sym.fSlice) and not q^.isVar then INC(n, 2); else INC(n); end; + q := q^.next; + end; + return n; +end; + (* Calls. The arguments are the c.n values on top, each moved into the next of x0 to x7 just before the call; the values under them are spilled first, as the call may change their registers. As the stack's registers carry no argument, the moves may go in any order. A slice - goes as its two words, a record by value as the address of a copy - (Item makes it). A single result comes back in x0, two words in x0 - and x1: a slice is stored in the temporary c.ret, two results pushed - as two values. *) + goes as its two words, both in registers or both on the stack, a + record by value as the address of a copy (Item makes it). The + arguments past the registers go on the machine's stack, 8 bytes + each, the first at sp, in an area sp is lowered by for the call, a + multiple of 16; and so do those past a C procedure's own parameters + where it ends in ..., in registers or not, as Apple's convention has + it (where a C procedure's own parameters past x7 narrower than 8 + bytes would be packed, which raz doesn't do). A result in memory, a + record, an array or several results, goes to the caller's temporary + c.ret, its address in x8. A single result comes back in x0, two words + in x0 and x1: a slice is stored in c.ret, two results pushed as two + values. *) proc call*(var c: CallInfo); -var res: ^Sym.Type; i, ni, first, r: INT; +var res: ^Sym.Type; i, ni, k, first, own, r: INT; area: I64; onStack: [64]BOOL; begin first := depth - c.n; spillBelow(first); res := c.sig^.base; c.ret := 0; - if c.sig^.variadic then notYet("a call of a C procedure that takes ..."); end; - if (res # nil) and (Sym.holdsArray(res) or Sym.behindPointer(res)) then - notYet("a result in memory"); - c.ret := allocPerm(res^.size, res^.align); - elsif (res # nil) and (res^.form = Sym.fSlice) then + if (res # nil) and Sym.holdsArray(res) then + c.ret := allocPerm(res^.size, res^.align); (* kept, as on x86-64 (report 8) *) + elsif (res # nil) and (Sym.behindPointer(res) or (res^.form = Sym.fSlice)) then c.ret := allocTemp(res^.size, res^.align); elsif (res # nil) and (res^.form = Sym.fReal) then notYet("reals"); end; - ni := 0; + own := c.n; + if c.sig^.variadic then own := paramWords(c.sig); end; + ni := 0; k := 0; for i := 0 to c.n - 1 do if c.isF[i] then notYet("reals"); end; - if ni < 8 then valueTo(first + i, ni); else notYet("an argument past x7"); end; - INC(ni); + if i >= own then onStack[i] := true; + elsif (i > 0) and c.pair[i - 1] then onStack[i] := onStack[i - 1]; + else onStack[i] := ni + 1 + INT(c.pair[i]) > 8; end; + if onStack[i] then INC(k); else INC(ni); end; end; + area := Sym.alignUp(8 * k, 16); + if area > 0 then A.aluI(A.opSub, SP, SP, area); end; + k := 0; ni := 0; + for i := 0 to c.n - 1 do + if onStack[i] then + valueTo(first + i, T); + A.store(T, SP, 8 * k, 8); + INC(k); + else + valueTo(first + i, ni); + INC(ni); + end; + end; + if (c.ret # 0) and Sym.behindPointer(res) then A.aluI(A.opAdd, 8, FP, c.ret); end; for i := 1 to c.n do drop(); end; if c.ext then A.loadChunk(U, c.chunk, 0, 8, false); @@ -1054,6 +1481,7 @@ A.load(U, FP, INT(c.target), 8, false); A.callR(U); end; + if area > 0 then A.aluI(A.opAdd, SP, SP, area); end; if res # nil then if res^.form = Sym.fSlice then A.store(0, FP, INT(c.ret), 8); @@ -1109,10 +1537,12 @@ end; (* The parameters' places: each in a frame slot of its own, stored there - from its register on entry. A var parameter, and a record or array - passed by value, holds an address (ind). *) + from its register on entry, or above the frame where the caller put + it, past the frame record (call). A var parameter, and a record or + array passed by value, holds an address (ind). The address of a + result in memory arrives in x8, and is kept in retSlot. *) proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj); -var p: ^Sym.Obj; ni, k, w: INT; +var p: ^Sym.Obj; ni, k, w: INT; stackOff: I64; begin frameTop := 0; frameMax := 0; permTop := 0; resetStack(0, 0); @@ -1120,21 +1550,30 @@ numIn := 0; lost := false; resType := sig^.base; + procParams := params; regMask := 0; if (resType # nil) and Sym.behindPointer(resType) then - notYet("a result in memory"); retSlot := allocPerm(8, 8); + inReg[0] := 8; inSlot[0] := retSlot; inSize[0] := 8; inObj[0] := nil; + numIn := 1; end; ni := 0; + stackOff := 16; p := params; while p # nil do p^.ind := p^.isVar or (Sym.isAggregate(p^.typ) and (p^.typ^.form # Sym.fSlice)); k := 1; if (p^.typ^.form = Sym.fSlice) and not p^.isVar then k := 2; end; - p^.val := allocPerm(8 * k, 8); - if (p^.typ^.form = Sym.fReal) and not p^.isVar or (ni + k > 8) then - notYet("a real parameter, or one past x7"); + if (p^.typ^.form = Sym.fReal) and not p^.isVar then + notYet("a real parameter"); + p^.val := allocPerm(8, 8); k := 0; + elsif ni + k > 8 then (* on the stack, as call puts it *) + p^.val := stackOff; + INC(stackOff, 8 * k); + k := 0; + else + p^.val := allocPerm(8 * k, 8); end; for w := 0 to k - 1 do (* a slice's two words, in two slots *) inReg[numIn] := ni; inSlot[numIn] := p^.val + I64(8 * w); inObj[numIn] := p; @@ -1191,7 +1630,7 @@ proc markCode*(var m: CodeMark); begin m.pc := Chunk.pc; m.fixups := Chunk.numFixups; m.lines := Chunk.numLines; m.said := A.saidCount(); - m.fails := 0; m.exit := exitL; + m.fails := numFails; m.exit := exitL; end; (* The code made since m taken back; the frame is left as it is *) @@ -1199,6 +1638,7 @@ begin Chunk.rewindTo(m.pc, m.fixups, m.lines); A.unsay(m.said); + numFails := m.fails; exitL := m.exit; end; @@ -1208,6 +1648,7 @@ begin Chunk.rewindTo(m.pc, m.fixups, m.lines); A.unsay(m.said); + numFails := 0; frameTop := frameAt[0]; frameMax := frameAt[1]; permTop := frameAt[2]; exitL := NoLabel; end; @@ -1222,7 +1663,7 @@ parameters stored from their registers to their slots, or moved to their registers. *) proc enterBody*(c, line: INT); -var i, loop, r: INT; n: I64; +var i, loop, r: INT; n: I64; p: ^Sym.Obj; begin Chunk.beginChunk(c); codeChunk := c; @@ -1255,7 +1696,7 @@ end; end; for i := 0 to numIn - 1 do - if inObj[i]^.reg # 0 then + if (inObj[i] # nil) and (inObj[i]^.reg # 0) then r := inObj[i]^.reg; if inSlot[i] # inObj[i]^.val then r := inObj[i]^.reg2; end; A.movRR(r, inReg[i]); @@ -1264,6 +1705,21 @@ A.store(inReg[i], FP, INT(inSlot[i]), inSize[i]); end; end; + (* a register variable's parameter that came on the stack, above the + frame (val > 0), is loaded from there: one passed by its address + (ind) is the address, 8 bytes, whatever its type *) + p := procParams; + while p # nil do + if (p^.reg # 0) and (p^.val > 0) then + if not p^.ind and (p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet}) then + A.load(p^.reg, FP, INT(p^.val), INT(p^.typ^.size), p^.typ^.signed); + else + A.load(p^.reg, FP, INT(p^.val), 8, false); + if not p^.ind and (p^.typ^.form = Sym.fSlice) then A.load(p^.reg2, FP, INT(p^.val) + 8, 8, false); end; + end; + end; + p := p^.next; + end; end; proc resultSlot*: I64; @@ -1271,27 +1727,32 @@ return retSlot; end; +(* Pops one of several results, a value of size bytes, into its place + off bytes into the caller's, at the address that came in x8 *) proc resultTo*(off: I64; size: INT); +var r: INT; begin - _ := off; _ := size; - notYet("a result in memory"); + r := top(); drop(); + A.load(U, FP, INT(retSlot), 8, false); + A.store(r, U, INT(off), size); end; +(* Pops an address, and copies size bytes from it to the result, off + bytes into it *) proc copyResult*(off, size: I64); begin - _ := off; _ := size; - notYet("a result in memory"); - drop(); + popTo(Src); + A.load(Dst, FP, INT(retSlot), 8, false); + if off # 0 then A.aluI(A.opAdd, Dst, Dst, off); end; + copyBytes(size); end; (* return: the result, a value on top, goes in x0; two words, the two - values on top, in x0 and x1 *) + values on top, in x0 and x1; one in memory is there already *) proc returnJump*; begin - if (resType # nil) and Sym.behindPointer(resType) then - A.load(0, FP, INT(retSlot), 8, false); (* not yet made: marked by beginProc *) - elsif resType # nil then + if (resType # nil) and not Sym.behindPointer(resType) then if Sym.inTwoRegs(resType) then popTo(1); end; popTo(0); end; @@ -1304,10 +1765,35 @@ begin end; +(* The procedure returns the error in register r, and a zero for each + of its other results; r isn't x0, x1 or x2, which this uses. *) +proc returnError(r: INT); +var f: ^Sym.Obj; +begin + if Sym.behindPointer(resType) then + A.load(Dst, FP, INT(retSlot), 8, false); + zeroBytes(resType^.size); + f := resType^.fields; + while f^.next # nil do f := f^.next; end; + A.load(Dst, FP, INT(retSlot), 8, false); + A.store(r, Dst, INT(f^.val), 8); + elsif Sym.inTwoRegs(resType) then + A.movRR(1, r); + A.movRI(0, 0); + else + A.movRR(0, r); + end; + A.jmp(exitL); +end; + +(* The rest of what try does where the error isn't nil: the procedure + returns the error in the frame slot. Only code is made: the stack of + values is left as it is, for the code that follows, where the error + is nil. *) proc tryReturn*(slot: I64); begin - _ := slot; - notYet("try"); + A.load(U, FP, INT(slot), 8, false); + returnError(U); end; (* try, with no deferred statement to run: the error on top is tested in @@ -1323,8 +1809,7 @@ proc tryReturnFrom*(r: INT); begin - _ := r; - notYet("try"); + returnError(r); end; (* The end of the procedure in chunk c: the code that returns, and the @@ -1335,7 +1820,10 @@ begin codeChunk := -1; if (depth # 0) or (pushed # 0) then Diag.fatal("internal error: stack depth"); end; - if open then + if open and Sym.behindPointer(resType) then + A.load(Dst, FP, INT(retSlot), 8, false); + zeroBytes(resType^.size); + elsif open then A.movRI(0, 0); if Sym.inTwoRegs(resType) then A.movRI(1, 0); end; else @@ -1352,6 +1840,7 @@ A.movRR(SP, FP); A.ldp(FP, LR, SP, 16, A.mPost); A.ret(); + endFails(); n := Sym.alignUp(frameMax, 16); if n >= 1000000H then return Scan.mark("frame too big: 16 MB or more"); end; Chunk.put4At(frameFix, SubSp12 | INT((n shr 12) shl 10)); @@ -1364,29 +1853,40 @@ return nil; end; +(* A deferred statement is compiled where it stands, as a subroutine of + its procedure that the code jumps over, in the procedure's own frame + (the same x29), so that it sees all its variables; deferBegin gives + its address and what pushed was. bl, which runs it, leaves its return + address in x30, which its own calls would change: so it keeps x30 on + the machine's stack, 16 bytes, so that sp stays a multiple of 16: + + b over + at: str x30, [sp, #-16]! + ... ; the statement + ldr x30, [sp], #16 + ret + over: *) proc deferBegin*(var L: INT): (INT, INT); +var at: INT; begin - _ := L; - notYet("defer"); - return Chunk.pc, pushed; + A.jmp(L); + at := Chunk.pc; + A.storeIdx(LR, SP, -16, 8, A.mPre); + return at, pushed; end; proc deferEnd*(L, saved: INT); begin - _ := L; _ := saved; keepTemps(); + A.loadIdx(LR, SP, 16, 8, A.mPost); + A.ret(); + A.fixLink(L); + pushed := saved; end; proc runDefer*(at: INT); begin - _ := at; - notYet("defer"); -end; - -(* The name s, interned *) -proc internStr(s: []const U8): INT; -begin - return Scan.intern(SYSTEM.PTR(s), LEN(s)); + A.callBack(at); end; (* The entry point, main, and its chunk. macOS starts every program in @@ -1428,6 +1928,29 @@ A.callChunk(exitProc); A.brk(1); (* exit never returns: trap if it does *) Chunk.endChunk(entry); + (* Rt.fail, for the failures of each kind, given a, b, len and name + by the check's code (endFails), which called the stub by bl: the + place is that bl's, 4 bytes before the return address. Rt.fail's + last two arguments, the registers x86-64's trap report shows, are + none here. + + sub x4, x30, #4 + mov x0, #kind + mov x6, #0 + mov x7, #0 + bl Rt.fail *) + for i := 0 to LEN(failStubs) - 1 do + if failStubs[i] >= 0 then + Chunk.beginChunk(failStubs[i]); + A.aluI(A.opSub, 4, LR, 4); + A.movRI(0, i); + A.movRI(6, 0); + A.movRI(7, 0); + A.callChunk(rtFail); + A.brk(1); + Chunk.endChunk(failStubs[i]); + end; + end; return entry; end; @@ -1455,7 +1978,9 @@ notYet("reals"); end; +var i: INT; begin + for i := 0 to LEN(failStubs) - 1 do failStubs[i] := -1; end; Chunk.setPad(0D4200020H); (* brk #1, a trap, between procedures *) codeChunk := -1; pending := ""; diff --git a/test/mac.sh b/test/mac.sh index ea6fd56..e7e46aa 100755 --- a/test/mac.sh +++ b/test/mac.sh @@ -6,6 +6,10 @@ # compared, as test/check.sh compares a test's: # X.expect its standard output (optional; empty if missing) # X.status its exit status (optional; 0 if missing) +# Then conform/run's programs the same way, into build/mac/conform, +# with their arguments (X.args): until the port is whole some fail, +# which are counted and listed in build/mac/conform.fail, not failures +# of the run. # # test/mac.sh build in the container: the cross compiler, then the programs # test/mac.sh run on the Mac: each program, run with a timeout @@ -23,6 +27,12 @@ for f in test/mac/*.raz; do name=$(basename $f .raz) build/cross/darwin-arm64/raz -o $out/$name $f 2>$out/$name.cerr || true + done + mkdir -p $out/conform + for f in conform/run/*.raz; do + name=$(basename $f .raz) + build/cross/darwin-arm64/raz -I conform/run/mods -o $out/conform/$name $f \ + 2>$out/conform/$name.cerr || true done ;; run) @@ -48,6 +58,36 @@ fi done echo "$pass passed, $fail failed" + # conform/run, counted: why each fails goes to conform.fail + c=$out/conform + cpass=0 + cfail=0 + : > $c.fail + for f in conform/run/*.raz; do + name=$(basename $f .raz) + want=0 + [ -f conform/run/$name.status ] && want=$(cat conform/run/$name.status) + if [ ! -x $c/$name ]; then + echo "$name: doesn't compile: $(grep -m1 error $c/$name.cerr)" >> $c.fail + cfail=$((cfail + 1)); continue + fi + set -- + if [ -f conform/run/$name.args ]; then + while IFS= read -r a; do set -- "$@" "$a"; done < conform/run/$name.args + fi + status=0 + perl -e 'alarm 10; exec @ARGV' ./$c/$name "$@" > $c/$name.out 2>$c/$name.err || status=$? + if [ $status != $want ]; then + echo "$name: status $status, not $want: $(head -1 $c/$name.err)" >> $c.fail + cfail=$((cfail + 1)) + elif ! cmp -s $c/$name.out conform/run/$name.expect; then + echo "$name: output differs" >> $c.fail + cfail=$((cfail + 1)) + else + cpass=$((cpass + 1)) + fi + done + echo "conform/run: $cpass of $((cpass + cfail)) passed; the others in $c.fail" [ $fail = 0 ] ;; *) diff --git a/test/mac/Calls.expect b/test/mac/Calls.expect new file mode 100644 index 0000000..cf80562 --- /dev/null +++ b/test/mac/Calls.expect @@ -0,0 +1,8 @@ +385 +-178672 +120 +1605 +1926 +86 +42 +42 and 1234567890123 -5 diff --git a/test/mac/Calls.raz b/test/mac/Calls.raz new file mode 100644 index 0000000..9799605 --- /dev/null +++ b/test/mac/Calls.raz @@ -0,0 +1,76 @@ +(* Calls past the registers (PLAN.md 5, 5b): arguments past x7 on the + machine's stack, a slice among them; a record and several results + through x8; two results in x0 and x1; a procedure value; C's printf, + whose arguments past its own go on the stack; and copies past 256 + bytes. *) +module Calls; +import Out; +import SYSTEM; + +extern proc printf(fmt: ^U8; ...): I32; +extern proc fflush(f: ^U8): I32; + +type + Big = record a: [40]INT; n: INT; end; + +proc ten(a, b, c, d, e, f, g, h, i, j: INT): INT; +begin + return a + 2 * b + 3 * c + 4 * d + 5 * e + 6 * f + 7 * g + 8 * h + 9 * i + 10 * j; +end; + +(* the slice takes x7 and the stack's first word, or both on the stack *) +proc late(a, b, c, d, e, f, g: INT; s: []const U8; n: I8): INT; +begin + return a + b + c + d + e + f + g + LEN(s) * 100 + INT(s[1]) * 1000 + INT(n) * 100000; +end; + +proc big(n: INT): Big; +var r: Big; i: INT; +begin + for i := 0 to 39 do r.a[i] := i * n; end; + r.n := n; + return r; +end; + +proc three(x: INT): (INT, INT, INT); +begin + return x, x * 2, x * 3; +end; + +proc passOn(x: INT): (INT, INT, INT); +begin + return three(x + 1); +end; + +proc two(x: INT): (INT, INT); +begin + return x + 1, x - 1; +end; + +proc twice(x: INT): INT; +begin + return 2 * x; +end; + +proc main*; +var b, c: Big; p, q, r: INT; f: proc(x: INT): INT; +begin + Out.int(ten(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); Out.ln(); + Out.int(late(1, 2, 3, 4, 5, 6, 7, "xyz", -3)); Out.ln(); + b := big(3); + c := b; + Out.int(c.a[39] + c.n); Out.ln(); + p, q, r := three(5); + Out.int(p + q * 10 + r * 100); Out.ln(); + p, q, r := passOn(5); + Out.int(p + q * 10 + r * 100); Out.ln(); + p, q := two(7); + Out.int(p * 10 + q); Out.ln(); + f := twice; + Out.int(f(21)); Out.ln(); + Out.flush(); + _ := printf("%d %s %ld %d\n", 42, "and", 1234567890123, -5); + _ := fflush(nil); +end; + +end Calls. diff --git a/test/mac/DivNarrow.expect b/test/mac/DivNarrow.expect new file mode 100644 index 0000000..90be1f3 --- /dev/null +++ b/test/mac/DivNarrow.expect @@ -0,0 +1 @@ +before diff --git a/test/mac/DivNarrow.raz b/test/mac/DivNarrow.raz new file mode 100644 index 0000000..b12a8d3 --- /dev/null +++ b/test/mac/DivNarrow.raz @@ -0,0 +1,16 @@ +(* The smallest I16 divided by -1 stops the program, as an I64's does: + arm64's sdiv wouldn't, so the code checks *) +module DivNarrow; +import Out; + +proc main*; +var a, b: I16; +begin + a := -32767 - 1; + b := -1; + Out.str("before\n"); + Out.int(I64(a div b)); + Out.ln(); +end; + +end DivNarrow. diff --git a/test/mac/DivNarrow.status b/test/mac/DivNarrow.status new file mode 100644 index 0000000..0cfbf08 --- /dev/null +++ b/test/mac/DivNarrow.status @@ -0,0 +1 @@ +2 diff --git a/test/mac/DivZero.expect b/test/mac/DivZero.expect new file mode 100644 index 0000000..90be1f3 --- /dev/null +++ b/test/mac/DivZero.expect @@ -0,0 +1 @@ +before diff --git a/test/mac/DivZero.raz b/test/mac/DivZero.raz new file mode 100644 index 0000000..4285eeb --- /dev/null +++ b/test/mac/DivZero.raz @@ -0,0 +1,14 @@ +(* A U8 divided by zero, in mod, stops the program *) +module DivZero; +import Out; + +proc main*; +var a, b: U8; +begin + a := 7; + Out.str("before\n"); + Out.int(I64(a mod b)); + Out.ln(); +end; + +end DivZero. diff --git a/test/mac/DivZero.status b/test/mac/DivZero.status new file mode 100644 index 0000000..0cfbf08 --- /dev/null +++ b/test/mac/DivZero.status @@ -0,0 +1 @@ +2 diff --git a/test/mac/Divide.expect b/test/mac/Divide.expect new file mode 100644 index 0000000..b4f43f1 --- /dev/null +++ b/test/mac/Divide.expect @@ -0,0 +1,9 @@ +-3 -2 -4 -1 17 +-1073741823 -1 -2147483 +16383 -1 +-42 -1 127 +35 5 15 10 +1333333333 1 +many one two three or four three or four five many seven many +[halve]5 +[halve]odd diff --git a/test/mac/Divide.raz b/test/mac/Divide.raz new file mode 100644 index 0000000..98a6a83 --- /dev/null +++ b/test/mac/Divide.raz @@ -0,0 +1,61 @@ +(* Division and mod in every width, signed and unsigned, by constants + and variables, and a jump table, deferred statements and try *) +module Divide; +import Out; + +const Odd: ERROR = "odd"; + +proc show(n: I64); +begin + Out.int(n); Out.str(" "); +end; + +proc even(n: INT): ERROR; +begin + if n mod 2 # 0 then return Odd; end; + return nil; +end; + +proc halve(n: INT): (INT, ERROR); +begin + defer Out.str("[halve]"); + try even(n); + return n div 2, nil; +end; + +proc name(n: INT): []const U8; +begin + match n of + | 1: return "one"; + | 2: return "two"; + | 3, 4: return "three or four"; + | 5: return "five"; + | 7: return "seven"; + | else: return "many"; + end; +end; + +proc main*; +var a, b: I64; c, d: I32; e, f: I16; g, h: I8; u, v: U8; w, x: U32; m, k: INT; err: ERROR; +begin + a := -17; b := 5; + show(a div b); show(a mod b); show(a div 4); show(a mod 4); show(a div (-1)); Out.ln(); + c := -2147483647; d := 2; + show(I64(c div d)); show(I64(c mod d)); show(I64(c div 1000)); Out.ln(); + e := -32767; f := -2; + show(I64(e div f)); show(I64(e mod f)); Out.ln(); + g := -127; h := 3; + show(I64(g div h)); show(I64(g mod h)); show(I64(g div (-1))); Out.ln(); + u := 250; v := 7; + show(I64(u div v)); show(I64(u mod v)); show(I64(u div 16)); show(I64(u mod 16)); Out.ln(); + w := 4000000000; x := 3; + show(I64(w div x)); show(I64(w mod x)); Out.ln(); + for m := 0 to 8 do Out.str(name(m)); Out.str(" "); end; + Out.ln(); + k, err := halve(10); show(k); Out.ln(); + k, err := halve(7); + if err = Odd then Out.str("odd"); end; + Out.ln(); +end; + +end Divide.