(* Gen: the code generator, for arm64 (Gen.arm64.raz; x86-64's is Gen.x86_64.raz, the suffix of the file choosing, doc/raz.md, 3). 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. It makes all that x86-64's does, in arm64's instructions, but SYSCALL, which is Linux's only: a program that uses it fails to compile (missing). The stack is kept in registers as on x86-64: the value at depth d, depth 0 being the bottom, is in x9 to x14, register d mod 6, all of them registers a call may change and that carry no argument, so that a call moves its arguments into x0 to x7 in any order. A value that needs a register a lower one holds spills that one to a frame slot. A constant, or an address in the frame or of a chunk, is only noted until something needs it in a register. A variable's value is loaded when it is pushed: no instruction of arm64 but a load or a store takes memory. A real, an F32 or an F64, is held as x86-64 holds it, in the registers that compute with reals: the value at depth d in v16 to v21, XRegs[d mod 6], d or s, so each depth has two registers, and owner doesn't tell them apart. They are a call's to change and carry no argument, as x9 to x14 are; v23 is Gen's scratch. A real constant is made in x15 and moved across (fmov), as arm64 has no instruction that holds any real. Registers outside the stack: x15 and x17, Gen's scratch, as rax and rcx are on x86-64; x16, the encoder's (A64); x0 to x3 for copying and slices, between calls, where they hold nothing; x8, which Apple's convention keeps for the address of a result in memory; x18, the system's, never touched; x19 to x23, a procedure's busiest variables (VarRegs), and d8 to d15, its busiest reals (XVarRegs), which a called procedure gives back as it found them; x29, the frame pointer, and x30, the return address. Calls use Apple's arm64 convention: the first eight integer arguments in x0 to x7, the first eight reals in v0 to v7, the rest on the machine's stack, results in x0 and x1, or d0, 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 but a call's stack arguments, for the call, and a deferred statement's return address: pushed is always 0. What x86-64 does by itself, and arm64 doesn't, the code does: it checks a division by zero, and the smallest value by -1 (divide), and gives the smallest I64 for a real out of range (realToInt). Depends on: Scan and Diag for errors, Sym for types, Chunk for code and data, A64 for instructions. Leaves out SYSCALL, which is Linux's only. *) module Gen; import Fmt, Diag, Scan, Sym, Chunk, A := A64; import SYSTEM; const Arch* = "arm64"; (* the target's machine, as a file's suffix says it *) 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, 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 *) Dst = 0; Src = 1; Tmp = 2; (* copying's *) XT = 23; (* Gen's scratch for a real *) type Kind* = (kWord, kLong, kF32, kF64); (* Where a variable is: its address is relative to the frame, to a chunk, to an address on the stack, or to one held in a frame slot *) Base* = (bFrame, bGlobal, bStack, bSlot, bReg, bPtr); Adr* = record base*: Base; chunk*: INT; (* bGlobal: the chunk; bSlot: the frame slot; bReg: the register; bPtr: the register that holds the address *) off*: I64; (* added to the address; for bReg, which word, 0 or 8 *) hi*: INT; (* bReg, a slice: the register of its length, the second word; chunk is that of its pointer *) end; (* The code made so far, to go back to for a second try at a body *) CodeMark* = record pc*, fixups*, lines*, said*, fails*, exit*: INT; end; (* For entryPoint: the address of chunk, put in the variable whose chunk is into before the program starts; or, for C's symbols, the address in chunk, the quadword the loader fills in *) Link* = record chunk*, into*: INT; end; CallInfo* = record sig*: ^Sym.Type; param*: ^Sym.Obj; (* the parameter the next argument is for *) obj*: ^Sym.Obj; (* the procedure called, if it has a name *) n*: INT; (* the arguments *) isF*: [64]BOOL; (* ... goes in a real's register *) pair*: [64]BOOL; (* ... is a slice's first word, the next its second *) target*: I64; (* the frame slot of a procedure value, if chunk < 0 *) chunk*: INT; (* else the procedure's chunk *) ext*: BOOL; (* C's: called through the chunk holding its address *) ret*: I64; (* set by call: the temporary a slice result is in *) end; const (* the registers a procedure keeps its busiest variables in, which a called procedure saves and gives back (Apple's x19 to x28); the trap report finds them where the prologue saved them *) VarRegs*: [5]INT = [19, 20, 21, 22, 23]; (* the registers the trap report can show a variable in: VarRegs; no parameter is kept where it arrives, so the last two are none *) ShownRegs*: [7]INT = [19, 20, 21, 22, 23, -1, -1]; (* the registers of real variables, d8 to d15, which a call keeps, numbered from XmmVar up so that they aren't taken for x8 to x15 *) XmmVar* = 32; XVarRegs*: [8]INT = [XmmVar + 8, XmmVar + 9, XmmVar + 10, XmmVar + 11, XmmVar + 12, XmmVar + 13, XmmVar + 14, XmmVar + 15]; (* a procedure's registers of variables, as bits: bit i is VarRegs[i], bit XBit + i XVarRegs[i] *) XBit* = 5; var rtFail*, argcChunk*, argvChunk*: INT; lost*: BOOL; (* never set here: no parameter is kept where it arrived *) depth*: INT; (* the values on the stack *) pushed*: INT; (* quadwords pushed on the machine's stack: always 0 *) codeChunk*: INT; (* the procedure or body being compiled, or -1 *) type (* where a value on the stack is *) Loc = (lConst, (* not loaded: val is the value *) lAdr, (* not loaded: the address of chunk, or of the frame if chunk is -1, plus val *) lReg, (* in its register *) lFrame); (* spilled: in the frame slot val *) Entry = record loc: Loc; val: I64; chunk: INT; (* lAdr: the chunk, or -1 for the frame *) k: Kind; end; (* A place in memory: off from register base, or, if chunk >= 0, off 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]; XRegs: [NumRegs]INT = [16, 17, 18, 19, 20, 21]; (* v16 to v21 *) (* the condition codes of the comparisons, from sEql: = # < <= > >= *) CcSigned: [6]INT = [A.ccEQ, A.ccNE, A.ccLT, A.ccLE, A.ccGT, A.ccGE]; CcUnsigned: [6]INT = [A.ccEQ, A.ccNE, A.ccLO, A.ccLS, A.ccHI, A.ccHS]; (* and of reals, after fcmp: an unordered pair, a NaN, sets C and V and not N or Z, so that only # holds, as IEEE wants; lt and le would hold, as they test N # V, so < is mi and <= ls *) CcReal: [6]INT = [A.ccEQ, A.ccNE, A.ccMI, A.ccLS, A.ccGT, A.ccGE]; (* sub sp, sp, #imm12 and the same shifted by 12: the prologue's two, whose immediates endProc patches *) SubSp = 0D10003FFH; SubSp12 = 0D14003FFH; var stack: [MaxStack]Entry; owner: [NumRegs]INT; (* the value in each register, or -1 *) frameTop, frameMax, permTop: I64; frameFix: INT; (* where the frame's two subs are *) paramTop: I64; (* the parameters' slots end here *) zeroTop: I64; (* the locals the prologue zeroes end here *) retSlot: I64; resType: ^Sym.Type; (* the procedure's result, or nil *) exitL: INT; (* parameters arriving in registers, x0 to x7 or, told by a negative number, -1 - n, v0 to v7, and a result's address in x8: where each is stored on entry *) inReg: [17]INT; inSlot: [17]I64; inSize: [17]INT; inObj: [17]^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 *) homes: [8]I64; (* the slots of the variables in XVarRegs *) frameAt: [3]I64; (* frameTop, frameMax, permTop after the declarations *) (* 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 won't make, SYSCALL, marks the procedure being compiled (Chunk.setMissing), which is an error if the program uses it, and the compile reads on: a module the program imports may hold what it never calls. The routine keeps the stack as the real one would. *) proc missing(msg: []const U8); begin if codeChunk >= 0 then Chunk.setMissing(codeChunk, msg, Scan.tokPos()); end; end; (* -S: the text of each instruction is kept, and list prints it *) proc setListing*(yes: BOOL); begin A.setListing(yes); end; proc list*(home: INT); begin A.list(home); end; (* A variable changed in place, x := x + e, is x86-64's; here it is loaded and stored as any other *) proc setInPlace*(r: INT); begin _ := r; end; proc kindOf*(t: ^Sym.Type): Kind; begin if t^.form = Sym.fReal then if t^.size = 4 then return kF32; end; return kF64; end; if t^.size > WordSize then return kLong; end; return kWord; end; (* The stack *) proc isReal(i: INT): BOOL; begin return stack[i].k in {kF32, kF64}; end; proc allocTemp*(size, align: I64): I64; forward; proc allocPerm*(size, align: I64): I64; forward; proc loaded(i: INT): INT; forward; (* The value i, in its register, goes to a frame slot: a real as 8 bytes, an F32 with what lies above it *) proc spill(i: INT); var s: I64; r: INT; begin r := loaded(i); s := allocTemp(8, 8); if isReal(i) then A.storeF(r, FP, INT(s), 8); else A.store(r, FP, INT(s), 8); end; stack[i].loc := lFrame; stack[i].val := s; owner[i mod NumRegs] := -1; end; (* Every value below depth d in a register, spilled, as a call may change them *) proc spillBelow(d: INT); var r: INT; begin for r := 0 to NumRegs - 1 do if (owner[r] >= 0) and (owner[r] < d) then spill(owner[r]); end; end; end; (* The register of value i, for it to hold: a lower value there is spilled *) proc claim(i: INT): INT; var r: INT; begin r := i mod NumRegs; if (owner[r] >= 0) and (owner[r] # i) then spill(owner[r]); end; owner[r] := i; return Regs[r]; end; (* The value i into register r, from wherever it is; it stays where it was, so r is a new copy. A real goes as its bits. *) proc valueTo(i, r: INT); begin match stack[i].loc of | lConst: A.movRI(r, stack[i].val); | lAdr: if stack[i].chunk >= 0 then A.addrChunk(r, stack[i].chunk, INT(stack[i].val)); else A.aluI(A.opAdd, r, FP, stack[i].val); end; | lReg: if isReal(i) then A.fmovRF(r, XRegs[i mod NumRegs], false); elsif Regs[i mod NumRegs] # r then A.movRR(r, Regs[i mod NumRegs]); end; | lFrame: A.load(r, FP, INT(stack[i].val), 8, false); end; end; (* The real i into register v, as valueTo does for an integer: a constant by its bits, made in x15, or the zero register's *) proc xValueTo(i, v: INT); begin match stack[i].loc of | lConst: if stack[i].val = 0 then A.fmovFR(v, ZR, false); else A.movRI(T, stack[i].val); A.fmovFR(v, T, false); end; | lReg: if XRegs[i mod NumRegs] # v then A.fop1(A.fMov, v, XRegs[i mod NumRegs], false); end; | else: A.loadF(v, FP, INT(stack[i].val), 8); (* lFrame *) end; end; (* The value i, in its register, of its kind *) proc loaded(i: INT): INT; var r: INT; begin if stack[i].loc # lReg then r := claim(i); if isReal(i) then xValueTo(i, XRegs[i mod NumRegs]); else valueTo(i, r); end; stack[i].loc := lReg; end; if isReal(i) then return XRegs[i mod NumRegs]; end; return Regs[i mod NumRegs]; end; proc top: INT; begin if depth = 0 then Diag.fatal("internal error: the stack is empty"); end; return loaded(depth - 1); end; (* A value on the stack's top; at its last place the compile ends, as on x86-64 *) proc newEntry(k: Kind; loc: Loc; v: I64); begin if depth > LEN(stack) - 1 then _ := Scan.mark(Diag.say("more than {} values waiting in one expression", [Fmt.int(MaxStack)])); Diag.finish(); return; end; stack[depth].k := k; stack[depth].loc := loc; stack[depth].val := v; stack[depth].chunk := -1; INC(depth); end; (* The register a new value on top is computed in, and a real's *) proc target: INT; begin return claim(depth); end; proc xTarget: INT; begin _ := claim(depth); return XRegs[depth mod NumRegs]; end; (* The value just computed in target goes on top *) proc computed(k: Kind); begin newEntry(k, lReg, 0); end; (* drop emits no code, and the dropped value's register holds it until the next push claims it, which place and operands rely on *) proc drop*; begin DEC(depth); if owner[depth mod NumRegs] = depth then owner[depth mod NumRegs] := -1; end; end; proc popTo(r: INT); begin valueTo(depth - 1, r); drop(); end; proc topConst: (BOOL, I64); begin return stack[depth - 1].loc = lConst, stack[depth - 1].val; end; proc resetStack*(d, p: INT); var r: INT; begin depth := d; pushed := p; for r := 0 to NumRegs - 1 do owner[r] := -1; end; end; (* A constant; a real's v is its bits, an F64's or, in the low 32, an F32's *) proc pushConst*(k: Kind; v: I64); begin newEntry(k, lConst, v); end; (* The register of the word at a, a variable in registers: the pointer's (off 0) or, for a slice, the length's (off 8) *) proc regAt(a: Adr): INT; begin if a.off = 0 then return a.chunk; end; return a.hi; end; (* The memory a names. An address on the stack is popped, and is in its register still; one in a slot is loaded into r. *) proc place(a: Adr; r: INT): Mem; var m: Mem; begin m.chunk := -1; m.off := a.off; match a.base of | bFrame: m.base := FP; | bGlobal: m.chunk := a.chunk; | bStack: if (stack[depth - 1].loc = lAdr) and (stack[depth - 1].chunk >= 0) then m.chunk := stack[depth - 1].chunk; m.off := m.off + stack[depth - 1].val; elsif stack[depth - 1].loc = lAdr then m.base := FP; m.off := m.off + stack[depth - 1].val; else m.base := loaded(depth - 1); end; drop(); | bPtr: m.base := a.chunk; | bSlot: A.load(r, FP, a.chunk, 8, false); m.base := r; | bReg: Diag.fatal("internal error: a register has no address"); end; return m; end; (* Register r loaded from m, or stored there, size bytes *) proc loadMem(r: INT; m: Mem; size: INT; signed: BOOL); begin if m.chunk >= 0 then A.loadChunk(r, m.chunk, INT(m.off), size, signed); else A.load(r, m.base, INT(m.off), size, signed); end; end; proc storeMem(r: INT; m: Mem; size: INT); begin if m.chunk >= 0 then A.storeChunk(r, m.chunk, INT(m.off), size); else A.store(r, m.base, INT(m.off), size); end; end; (* A real's register v loaded from m, or stored there if not load *) proc realMem(v: INT; m: Mem; size: INT; load: BOOL); begin if (m.chunk >= 0) and load then A.loadChunkF(v, m.chunk, INT(m.off), size); elsif m.chunk >= 0 then A.storeChunkF(v, m.chunk, INT(m.off), size); elsif load then A.loadF(v, m.base, INT(m.off), size); else A.storeF(v, m.base, INT(m.off), size); end; end; (* Register r := the address m *) proc adrTo(r: INT; m: Mem); begin if m.chunk >= 0 then A.addrChunk(r, m.chunk, INT(m.off)); elsif (m.off # 0) or (m.base # r) then A.aluI(A.opAdd, r, m.base, m.off); end; end; (* The address a names, on top of the stack *) proc pushAdr*(a: Adr); var m: Mem; r: INT; begin if (a.base = bStack) and (a.off = 0) then return; end; (* it is on top already *) if a.base in {bFrame, bGlobal} then newEntry(kWord, lAdr, a.off); if a.base = bGlobal then stack[depth - 1].chunk := a.chunk; end; return; end; (* With the address on the stack, place pops it first, so that target may take its register; else target comes first, for place to load a slot's pointer into *) if a.base = bStack then m := place(a, U); r := target(); else r := target(); m := place(a, r); end; adrTo(r, m); computed(kWord); end; proc pushVar*(a: Adr; size: INT; signed: BOOL; k: Kind); var m: Mem; r: INT; fl: BOOL; begin fl := k in {kF32, kF64}; if (a.base = bReg) and fl then A.fop1(A.fMov, xTarget(), regAt(a) - XmmVar, false); elsif a.base = bReg then A.movRR(target(), regAt(a)); else if a.base = bStack then m := place(a, U); r := target(); else r := target(); m := place(a, r); end; if fl then realMem(xTarget(), m, size, true); else loadMem(r, m, size, signed); end; end; computed(k); end; proc pushProc*(c: INT; ext: BOOL); var r: INT; begin r := target(); if ext then A.loadChunk(r, c, 0, 8, false); else A.addrChunk(r, c, 0); end; computed(kWord); end; (* Pops a value into the variable at a; an address on the stack is under the value. A zero is stored from the zero register, and a real constant as its bits. A real variable in a register is written through to its slot, as on x86-64, where the trap report finds it. *) proc popVar*(a: Adr; size: INT); var r: INT; v: I64; c, fl: BOOL; begin if (a.base = bReg) and isReal(depth - 1) then r := regAt(a) - XmmVar; xValueTo(depth - 1, r); drop(); A.storeF(r, FP, INT(homes[r - 8]), 8); return; end; if a.base = bReg then popTo(regAt(a)); return; end; c, v := topConst(); fl := not c and isReal(depth - 1); if c and (v = 0) then r := ZR; elsif c then r := T; A.movRI(T, v); else r := loaded(depth - 1); end; drop(); if fl then realMem(r, place(a, U), size, false); else storeMem(r, place(a, U), size); end; end; (* The two values on top, of one kind, change places, each loaded in its register *) proc swap*; var e: Entry; x, y: INT; begin x := loaded(depth - 2); y := loaded(depth - 1); if isReal(depth - 1) then A.fop1(A.fMov, XT, x, false); A.fop1(A.fMov, x, y, false); A.fop1(A.fMov, y, XT, false); else A.movRR(T, x); A.movRR(x, y); A.movRR(y, T); end; e := stack[depth - 2]; stack[depth - 2] := stack[depth - 1]; stack[depth - 1] := e; end; (* Copying, by loads and stores of 8, 4, 2 and 1 bytes, from [x1] to [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 size := wordLoop(size, true); o := 0; while o < size do n := 8; while n > size - o do n := n div 2; end; A.load(Tmp, Src, INT(o), INT(n), false); A.store(Tmp, Dst, INT(o), INT(n)); INC(o, n); end; end; proc zeroBytes(size: I64); var o, n: I64; begin size := wordLoop(size, false); o := 0; while o < size do n := 8; while n > size - o do n := n div 2; end; A.store(ZR, Dst, INT(o), INT(n)); INC(o, n); end; end; (* Pops a source's address, and a destination's under it, and copies size bytes to off bytes past the destination *) proc copyBlock*(size, off: I64); begin popTo(Src); popTo(Dst); if off # 0 then A.aluI(A.opAdd, Dst, Dst, off); end; copyBytes(size); end; (* Pops a source's address, and copies size bytes to a: for a slice in registers, its two words into them *) proc copyTo*(a: Adr; size: I64); begin popTo(Src); if a.base = bReg then A.load(a.chunk, Src, 0, 8, false); A.load(a.hi, Src, 8, 8, false); return; end; adrTo(Dst, place(a, Dst)); copyBytes(size); end; proc zeroVar*(a: Adr; size: I64); begin adrTo(Dst, place(a, Dst)); 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: its own, or U for a constant; the left one stays, in its register, which is returned with y *) proc operands: (INT, INT); var v: I64; c: BOOL; y: INT; begin c, v := topConst(); if c then A.movRI(U, v); y := U; else y := loaded(depth - 1); end; drop(); return top(), y; end; (* The operation of two registers of +, -, &, | and xor *) proc aluOf(sy: Scan.Sym): INT; begin match sy of | sPlus: return A.opAdd; | sMinus: return A.opSub; | sAmp: return A.opAnd; | sBar: return A.opOrr; | else: return A.opEor; 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 reals on top, the left op the right, in the left's register: fadd d16, d16, d17 *) proc realOp(sy: Scan.Sym; k: Kind); var x, y, o: INT; begin match sy of | sPlus: o := A.fAdd; | sMinus: o := A.fSub; | sTimes: o := A.fMul; | else: o := A.fDiv; end; y := loaded(depth - 1); drop(); x := top(); A.fop(o, x, x, y, k = kF32); 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 modulo the width, as x86-64's code takes it. *) proc op*(sy: Scan.Sym; k: Kind; size: INT; signed: BOOL); var v: I64; r, y, bits, sh: INT; c, alu: BOOL; begin if k in {kF32, kF64} then realOp(sy, k); return; 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 *) if (alu and (sy # Scan.sMinus) or (sy = Scan.sTimes)) and (stack[depth - 2].loc = lConst) and (stack[depth - 1].loc # lConst) then swap(); end; if sy = Scan.sShl then sh := A.shLsl; elsif signed then sh := A.shAsr; else sh := A.shLsr; end; c, v := topConst(); if c and alu then drop(); r := top(); A.aluI(aluOf(sy), r, r, v); elsif c and ((sy = Scan.sShl) or (sy = Scan.sShr)) then drop(); r := top(); A.shiftI(sh, r, r, INT(v & I64(bits - 1)), 8); else r, y := operands(); if alu then 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); end; end; if bits < 64 then A.extend(r, r, size, signed); end; stack[depth - 1].k := k; end; (* ROL, if left, or ROR of the integer of size bytes under the count on top, at its own width, the count taken modulo it, a negative one as a shift's is (Gen.x86_64.raz says more). arm64 rotates only right, by ror, and only 32 or 64 bits: a left rotation is a right one by minus the count, and a U8 or a U16 is first repeated through 32 bits, so that what leaves its low end comes back at its top, as a rotation of 32 bits by any count rotates each of the copies alike. ROL(x, n) of a U8: and x9, x9, #0FFH ; repeated: 000000AB to ABABABAB orr x9, x9, x9, lsl #8 orr x9, x9, x9, lsl #16 neg x17, x10 ; left by n is right by -n ror w9, w9, w17 ; the count modulo 32, so modulo 8 too and x9, x9, #0FFH A constant count is rotated by as ror x9, x9, #k, none if 0. As on x86-64, a rotation of 32 bits leaves the upper ones zero; a narrow one here leaves them zero too, where x86-64 leaves them as they were, which differs only for a signed integer. *) proc rotate*(left: BOOL; size: INT); var c: BOOL; v: I64; r, y, w, sz: INT; begin w := size * 8; sz := 4; if size = 8 then sz := 8; end; c, v := topConst(); v := v & I64(w - 1); if left then v := (I64(w) - v) & I64(w - 1); end; if c then drop(); r := top(); if v = 0 then stack[depth - 1].k := kWord; return; end; else r, y := operands(); if left then A.neg(U, y); y := U; end; end; if w < 32 then A.aluI(A.opAnd, r, r, (I64(1) shl w) - 1); A.aluShift(A.opOrr, r, r, r, A.shLsl, w); if w = 8 then A.aluShift(A.opOrr, r, r, r, A.shLsl, 16); end; end; if c then A.shiftI(A.shRor, r, r, INT(v), sz); else A.shift(A.shRor, r, r, y, sz); end; if w < 32 then A.aluI(A.opAnd, r, r, (I64(1) shl w) - 1); end; stack[depth - 1].k := kWord; end; (* CLZ, if leading, or CTZ of the unsigned integer of size bytes on top (report section 6.1), whose bits above its width are zero. clz counts the leading zeros of 32 or 64 bits, the whole width for 0; of a U8 or a U16, those of 32 less the 24 or 16 above it. CTZ is clz of the bits reversed (rbit), and of a U8 or a U16 a one bit set just above its width first, so that 0 counts the width: CLZ, a U8 CTZ, a U8 clz w9, w9 orr x9, x9, #100H sub x9, x9, #24 rbit w9, w9 clz w9, w9 *) proc countZeros*(leading: BOOL; size: INT); var r, w, sz: INT; begin r := top(); w := size * 8; sz := 4; if size = 8 then sz := 8; end; if not leading and (w < 32) then A.aluI(A.opOrr, r, r, I64(1) shl w); end; if not leading then A.rbit(r, r, sz); end; A.clz(r, r, sz); if leading and (w < 32) then A.aluI(A.opSub, r, r, 32 - w); end; stack[depth - 1].k := kWord; end; (* POPCOUNT of the integer or set on top (report section 6.1), by the vector instructions every arm64 has, as C's compilers make it: cnt counts the ones in each of the eight bytes, and addv adds them: fmov d23, x9 cnt v23.8b, v23.8b addv b23, v23.8b fmov x9, d23 *) proc popCount*; var r: INT; begin r := top(); A.fmovFR(XT, r, false); A.cnt(XT, XT); A.addv(XT, XT); A.fmovRF(r, XT, false); stack[depth - 1].k := kWord; end; (* ABS of the real, or the signed integer, on top. A real's sign bit is cleared, fabs, a NaN's too, as x86-64 clears it. An integer is 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 r := top(); if k in {kF32, kF64} then A.fop1(A.fAbs, r, r, k = kF32); return; end; 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. Two reals are compared by fcmp, and the BOOL is made in the left's integer register: fcmp d16, d17; cset x9, mi for < (CcReal) *) proc compare*(sy: Scan.Sym; k: Kind; signed: BOOL); var r, x, y, i: INT; begin i := INT(sy) - INT(Scan.sEql); if k in {kF32, kF64} then y := loaded(depth - 1); drop(); x := top(); drop(); r := target(); A.fcmp(x, y, k = kF32); A.cset(CcReal[i], r); computed(kWord); return; end; r, y := operands(); A.cmp(r, y); if signed then A.cset(CcSigned[i], r); else A.cset(CcUnsigned[i], r); end; stack[depth - 1].k := kWord; end; (* -x; of a real, its sign bit flipped, fneg, as x86-64 flips it *) proc neg*(k: Kind; size: INT; signed: BOOL); var r: INT; begin r := top(); if k in {kF32, kF64} then A.fop1(A.fNeg, r, r, k = kF32); return; end; A.neg(r, r); if size < 8 then A.extend(r, r, size, signed); end; end; proc complement*(size: INT; signed: BOOL); var r: INT; begin r := top(); A.mvn(r, r); if size < 8 then A.extend(r, r, size, signed); end; end; proc notBool*; var r: INT; begin r := top(); A.aluI(A.opEor, r, r, 1); end; (* The integer on top, brought to size bytes *) proc narrow*(size: INT; signed: BOOL); var r: INT; begin r := top(); if size < 8 then A.extend(r, r, size, signed); end; stack[depth - 1].k := kWord; end; (* The integer on top, as a real of kind k, in its real register: scvtf of the 64 bits, or ucvtf if big, a U64 that may be above high(I64), which x86-64 halves and doubles to the same value *) proc intToReal*(k: Kind; big: BOOL); var r: INT; begin r := top(); A.scvtf(XRegs[(depth - 1) mod NumRegs], r, k = kF32, not big); stack[depth - 1].k := k; end; (* The real of kind k on top, toward zero, as an I64 (report 6.1, the table of conversions); out of an I64's range, or a NaN, it is the smallest I64, as x86-64's cvttsd2si gives. fcvtzs gives the nearest I64 instead, and 0 for a NaN, so the result is mended: a NaN is unordered with itself, which sets V, and only the largest I64, which no real converts to exactly, overflows when 1 is added, setting V: fcvtzs x9, d16 mov x15, #8000000000000000H fcmp d16, d16 csel x9, x15, x9, vs ; a NaN cmn x9, #1 csel x9, x15, x9, vs ; too big Too small is the smallest already. *) proc realToInt*(k: Kind); var x, r: INT; begin x := top(); r := Regs[(depth - 1) mod NumRegs]; A.fcvtz(r, x, k = kF32, true); A.movRI(T, MIN(I64)); A.fcmp(x, x, k = kF32); A.csel(A.csSel, A.ccVS, r, T, r); A.cmpI(r, -1); A.csel(A.csSel, A.ccVS, r, T, r); stack[depth - 1].k := kWord; end; (* The real of kind k on top, as the other kind: fcvt, which rounds to the nearest as x86-64's cvtsd2ss does *) proc realToReal*(k: Kind); var x: INT; begin x := top(); A.fcvt(x, x, k = kF64); if k = kF32 then stack[depth - 1].k := kF64; else stack[depth - 1].k := kF32; end; 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 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; (* An error points at its message's length, an 8-byte word, with the text after it; nil is no error. Pops one, and makes the slice of its message at tmp, empty for nil. *) proc errorText*(tmp: I64); var L: INT; begin popTo(T); A.movRI(U, 0); L := NoLabel; A.cbz(false, T, L); A.load(U, T, 0, 8, false); A.aluI(A.opAdd, T, T, 8); A.fixLink(L); A.store(T, FP, INT(tmp), 8); A.store(U, FP, INT(tmp) + 8, 8); end; (* INC or DEC of the variable whose address is under the step on top; its store cuts a narrow one to its width *) proc incDec*(size: INT; signed, dec: BOOL); var r, y, o: INT; begin if dec then o := A.opSub; else o := A.opAdd; end; r, y := operands(); drop(); A.load(T, r, 0, size, signed); A.alu(o, T, T, y); A.store(T, r, 0, size); end; (* INC or DEC of the variable in register r, by the value on top *) proc incDecReg*(r, size: INT; signed, dec: BOOL); var c: BOOL; v: I64; o: INT; begin if dec then o := A.opSub; else o := A.opAdd; end; c, v := topConst(); if c then A.aluI(o, r, r, v); else A.alu(o, r, r, loaded(depth - 1)); end; drop(); if size < 8 then A.extend(r, r, size, signed); end; end; (* NEW's memory, at the address on top, size bytes zeroed unless the address is nil (the allocator had no room): cbz x9, L; then zeroBytes from x0 *) proc zeroNew*(size: I64); var L, r: INT; begin r := top(); L := NoLabel; A.cbz(false, r, L); A.movRR(Dst, r); zeroBytes(size); A.fixLink(L); 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 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 missing("SYSTEM.SYSCALL is Linux's only: call the C library"); for i := 1 to n do drop(); end; _ := target(); computed(kWord); end; (* A barrier for every processor, dmb ish *) proc fence*; begin A.dmb(); end; (* Jumps. A label is the chain of the jumps to it, until it is placed (A64). *) proc jump*(var L: INT); begin A.jmp(L); end; (* Pops a BOOL, and jumps if it is when *) proc jumpIf*(var L: INT; when: BOOL); var r: INT; begin r := loaded(depth - 1); drop(); A.cbz(when, r, L); end; (* Pops two integers, and jumps if the left op the right *) proc jumpCmp*(sy: Scan.Sym; signed: BOOL; var L: INT); var r, y, i: INT; begin i := INT(sy) - INT(Scan.sEql); r, y := operands(); drop(); A.cmp(r, y); if signed then A.jcc(CcSigned[i], L); else A.jcc(CcUnsigned[i], L); end; end; (* jumpCmp out of an expression: the values under the two compared are spilled first, so that they are where the code after the landing place expects them, whichever way it came (Gen.x86_64.raz says more) *) proc jumpOut*(sy: Scan.Sym; signed: BOOL; var L: INT); begin spillBelow(depth - 2); jumpCmp(sy, signed, L); end; (* The two values on top, compared, as a BOOL: true unless notOp holds; fj and tj, the chains of and, or and not, land on the 0 and the 1 *) proc condValue*(notOp: Scan.Sym; signed: BOOL; fj, tj: INT); var r, e: INT; begin jumpOut(notOp, signed, fj); A.fixLink(tj); r := target(); A.movRI(r, 1); e := NoLabel; A.jmp(e); A.fixLink(fj); A.movRI(r, 0); A.fixLink(e); computed(kWord); end; proc jumpBack*(top: INT); begin A.jmpBack(top); end; proc fix*(L: INT); begin 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 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 code at target *) proc tableEntry*(table, target: INT); begin Chunk.put4(target - table); end; (* A loop's start is aligned on x86-64, for its fetches; here it isn't *) proc alignLoop*; begin end; proc joinJumps*(L1, L2: INT): INT; begin return A.joinLinks(L1, L2); end; proc fixTo*(L, top: INT); begin A.fixLinkTo(L, top); end; (* 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 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 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 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 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, else through x3, free between calls as x0 to x2 are *) proc mulI(r: INT; v: I64); var n: INT; begin n := 0; while (I64(1) shl n) < v do INC(n); end; if (I64(1) shl n) = v then if n > 0 then A.shiftI(A.shLsl, r, r, n, 8); end; else A.movRI(3, v); A.mul(r, r, 3); end; end; (* 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. 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, ml: Mem; r, len: INT; begin 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 loadMem(U, m, 8, false); A.alu(A.opAdd, T, T, U); end; r := target(); A.movRR(r, T); computed(kWord); end; (* Pops an index, and a pointer under it, and makes the address of the element it picks *) proc indexPtr*(size: I64); begin mulI(top(), size); op(Scan.sPlus, kWord, 8, false); end; (* Pops an index, checked before, and makes the address of the element it picks of the array at a *) proc indexArray*(a: Adr; size: I64); begin mulI(top(), size); pushAdr(a); op(Scan.sPlus, kWord, 8, false); end; (* 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. 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, ml: Mem; len: INT; begin popTo(Tmp); (* hi *) popTo(Src); (* lo *) 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); A.alu(A.opAdd, U, U, Src); 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 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; (* FILL: every element of the slice in the frame at dOff, of size bytes each, set to the value on top if the element is a scalar, or else to the size bytes at the address on top; n is how many elements there are if that is known, as of an array, else -1 (Gen.x86_64.raz says more). A constant zero into an array is its bytes zeroed (zeroBytes). A scalar, a real's bits as an integer's, goes into x15, and is stored into each element, by a store each into an array of FewFills elements or fewer, else by a loop: ldr x0, [x29, #dOff] ldr x2, [x29, #dOff + 8] cbz x2, out top: str w15, [x0], #4 ; a U32 subs x2, x2, #1 b.ne top out: Any other element is copied into d[0], and from there forward, from d[0] on to d[1] on, as copySlice copies, by words if it is 8 bytes or more, else by bytes: each is read after it is written, size bytes before, so d[0] repeats through the rest. ... ; d[0] := x, as for a copy, from x1 ldr x1, [x29, #dOff] add x0, x1, #size ldr x2, [x29, #dOff + 8] sub x2, x2, #1 ... ; times size: the bytes of d[1..n] ... ; copyRun(8), copyRun(1) *) const FewFills = 16; proc fillSlice*(dOff, size, n: I64; scalar: BOOL); var c: BOOL; v, i: I64; out, top: INT; begin c, v := topConst(); out := NoLabel; if scalar and c and (v = 0) and (n >= 0) then drop(); A.load(Dst, FP, INT(dOff), 8, false); zeroBytes(n * size); elsif scalar and (n >= 0) and (n <= FewFills) then popTo(T); A.load(Dst, FP, INT(dOff), 8, false); for i := 0 to n - 1 do A.store(T, Dst, INT(i * size), INT(size)); end; elsif scalar then popTo(T); A.load(Dst, FP, INT(dOff), 8, false); A.load(Tmp, FP, INT(dOff) + 8, 8, false); A.cbz(false, Tmp, out); top := Chunk.pc; A.storeIdx(T, Dst, INT(size), INT(size), A.mPost); A.aluI(A.opSubs, Tmp, Tmp, 1); A.jccBack(A.ccNE, top); else popTo(Src); A.load(Dst, FP, INT(dOff), 8, false); A.load(Tmp, FP, INT(dOff) + 8, 8, false); A.cbz(false, Tmp, out); copyBytes(size); A.load(Src, FP, INT(dOff), 8, false); A.aluI(A.opAdd, Dst, Src, size); A.load(Tmp, FP, INT(dOff) + 8, 8, false); A.aluI(A.opSub, Tmp, Tmp, 1); mulI(Tmp, size); if size >= 8 then copyRun(8, false); end; copyRun(1, false); end; A.fixLink(out); end; (* 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 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); A.alu(A.opAdd, U, U, Src); 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, or a real into the next of v0 to v7, 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, 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, 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. Each takes 8 bytes, a real as its bits, but a C procedure's own parameter of an integer, BOOL, enumeration, set or real, which takes its size, at a multiple of it, as Apple packs them: an I32 then an I64 go at sp and sp + 8, an I32 then an I16 at sp and sp + 4. 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, or d0, 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; q: ^Sym.Obj; i, ni, nf, first, own, r: INT; area: I64; onStack: [64]BOOL; at, size: [64]INT; (* where on the stack, and how wide *) begin first := depth - c.n; spillBelow(first); res := c.sig^.base; c.ret := 0; 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); end; own := c.n; if c.sig^.variadic then own := paramWords(c.sig); end; ni := 0; nf := 0; area := 0; q := c.sig^.fields; (* the parameter of argument i, while there is one *) for i := 0 to c.n - 1 do size[i] := 8; if c.ext and (q # nil) and not q^.isVar and (q^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fReal}) then size[i] := INT(q^.typ^.size); end; if (q # nil) and not c.pair[i] then q := q^.next; end; if i >= own then onStack[i] := true; elsif c.isF[i] then onStack[i] := nf = 8; 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 area := Sym.alignUp(area, size[i]); at[i] := INT(area); INC(area, size[i]); elsif c.isF[i] then INC(nf); else INC(ni); end; end; area := Sym.alignUp(area, 16); if area > 0 then A.aluI(A.opSub, SP, SP, area); end; ni := 0; nf := 0; for i := 0 to c.n - 1 do if onStack[i] then valueTo(first + i, T); A.store(T, SP, at[i], size[i]); elsif c.isF[i] then xValueTo(first + i, nf); INC(nf); 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); A.callR(U); elsif c.chunk >= 0 then A.callChunk(c.chunk); else 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); A.store(1, FP, INT(c.ret) + 8, 8); elsif Sym.inTwoRegs(res) then A.movRR(target(), 0); computed(kWord); A.movRR(target(), 1); computed(kWord); elsif (c.ret = 0) and (res^.form = Sym.fReal) then A.fop1(A.fMov, xTarget(), 0, false); computed(kindOf(res)); elsif c.ret = 0 then (* C leaves the bits above a narrow result as they fall *) r := target(); A.movRR(r, 0); if res^.form = Sym.fBool then A.extend(r, r, 1, false); elsif (res^.form = Sym.fInt) and (res^.size < 8) then A.extend(r, r, INT(res^.size), res^.signed); end; computed(kindOf(res)); end; end; end; (* Frames: a slot of size bytes, its offset from x29, negative. A temporary is released at the end of its statement; allocPerm's lasts the procedure. *) proc allocTemp*(size, align: I64): I64; begin if align < 1 then align := 1; end; frameTop := Sym.alignUp(frameTop + size, align); if frameTop > frameMax then frameMax := frameTop; end; return -frameTop; end; proc allocPerm*(size, align: I64): I64; var s: I64; begin s := allocTemp(size, align); permTop := frameTop; return s; end; proc tempMark*: I64; begin return frameTop; end; proc releaseTemps*(m: I64); begin if m < permTop then m := permTop; end; frameTop := m; end; proc keepTemps*; begin frameTop := frameMax; permTop := frameMax; end; (* The parameters' places: each in a frame slot of its own, stored there 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). A real comes in the next of v0 to v7, and the ninth on, as call puts them, on the stack. 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, nf, k, w: INT; stackOff: I64; f: BOOL; begin frameTop := 0; frameMax := 0; permTop := 0; resetStack(0, 0); exitL := NoLabel; numIn := 0; lost := false; resType := sig^.base; procParams := params; regMask := 0; if (resType # nil) and Sym.behindPointer(resType) then retSlot := allocPerm(8, 8); inReg[0] := 8; inSlot[0] := retSlot; inSize[0] := 8; inObj[0] := nil; numIn := 1; end; ni := 0; nf := 0; stackOff := 16; p := params; while p # nil do p^.ind := p^.isVar or (Sym.isAggregate(p^.typ) and (p^.typ^.form # Sym.fSlice)); f := (p^.typ^.form = Sym.fReal) and not p^.isVar; k := 1; if (p^.typ^.form = Sym.fSlice) and not p^.isVar then k := 2; end; if f and (nf < 8) then p^.val := allocPerm(8, 8); inReg[numIn] := -1 - nf; inSlot[numIn] := p^.val; inSize[numIn] := 8; inObj[numIn] := p; INC(numIn); INC(nf); k := 0; elsif f or (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; inSize[numIn] := 8; if not p^.ind and (p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet}) then inSize[numIn] := INT(p^.typ^.size); end; INC(numIn); INC(ni); end; p := p^.next; end; paramTop := frameTop; end; (* The frame as beginProc left it, with the parameters' slots only *) proc resetLocals*; begin frameTop := paramTop; frameMax := paramTop; permTop := paramTop; end; (* No parameter is kept where it arrived, as x86-64 keeps one in rdi or rsi: each is stored on entry, or moved to its register variable *) proc keepArrived*(o: ^Sym.Obj); begin _ := o; end; proc keptIn*(o: ^Sym.Obj): BOOL; begin _ := o; return false; end; (* The locals in memory have their slots: the prologue zeroes those. The registers of variables in mask are saved next, a quadword each, in slots that need no zeroing; the frame as it then stands is where a second try at the body starts. *) proc useRegs*(mask: INT); var i, k: INT; begin zeroTop := permTop; regMask := mask; k := 0; for i := 0 to XBit + 7 do if (mask & (1 shl i)) # 0 then INC(k); end; end; if k > 0 then saveAt := allocPerm(8 * k, 8); end; frameAt[0] := frameTop; frameAt[1] := frameMax; frameAt[2] := permTop; end; (* The registers of variables in regMask, saved from saveAt on, a quadword each, x19 to x23 first, then d8 to d15, of which a called procedure keeps the low 64 bits, and so must give them back; and each zeroed, as a variable starts at zero. Or, if back, restored. *) proc saveRegs(back: BOOL); var i, n, r: INT; begin n := 0; for i := 0 to XBit + 7 do if (regMask & (1 shl i)) # 0 then if i < XBit then r := VarRegs[i]; if back then A.load(r, FP, INT(saveAt) + 8 * n, 8, false); else A.store(r, FP, INT(saveAt) + 8 * n, 8); A.movRI(r, 0); end; else r := XVarRegs[i - XBit] - XmmVar; if back then A.loadF(r, FP, INT(saveAt) + 8 * n, 8); else A.storeF(r, FP, INT(saveAt) + 8 * n, 8); A.fmovFR(r, ZR, false); end; end; INC(n); end; end; end; (* The variable in register r of XVarRegs has a slot of 8 bytes at slot, which popVar writes as it writes r *) proc xHome*(r: INT; slot: I64); begin homes[r - XVarRegs[0]] := slot; end; proc markCode*(var m: CodeMark); begin m.pc := Chunk.pc; m.fixups := Chunk.numFixups; m.lines := Chunk.numLines; m.said := A.saidCount(); m.fails := numFails; m.exit := exitL; end; (* The code made since m taken back; the frame is left as it is *) proc rewind*(m: CodeMark); begin Chunk.rewindTo(m.pc, m.fixups, m.lines); A.unsay(m.said); numFails := m.fails; exitL := m.exit; end; (* For a second try at the body: the code as it was at m, and the frame as useRegs found it *) proc redo*(m: CodeMark); 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; (* The prologue, for the procedure's first line: the frame record, x29 and x30, pushed, and x29 made to point at it; sp lowered by the frame's size, known only at endProc, which patches it into the two subs, of its bits from 12 up and of its low 12 (so a frame is less than 16 MB); the locals in memory zeroed, from the parameters' slots down to zeroTop, by a store each of the zero register up to 16, else by a loop; the registers of variables saved and zeroed; and the 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; p: ^Sym.Obj; begin Chunk.beginChunk(c); codeChunk := c; Chunk.noteLine(line, 1); (* a declaration starts a line *) A.stp(FP, LR, SP, -16, A.mPre); A.movRR(FP, SP); frameFix := Chunk.pc; A.say("sub sp, sp, frame, lsl #12"); Chunk.put4(SubSp12); A.say("sub sp, sp, frame"); Chunk.put4(SubSp); n := (Sym.alignUp(zeroTop, 8) - paramTop) div 8; if n <= 16 then for i := 1 to INT(n) do A.store(ZR, FP, INT(-paramTop) - 8 * i, 8); end; elsif n > 0 then A.aluI(A.opSub, T, FP, paramTop + 8 * n); A.movRI(U, n); loop := Chunk.pc; A.storeIdx(ZR, T, 8, 8, A.mPost); A.aluI(A.opSubs, U, U, 1); A.jccBack(A.ccNE, loop); end; Chunk.setSaves(c, regMask & ((1 shl XBit) - 1), INT(saveAt)); saveRegs(false); for i := 0 to numIn - 1 do if inReg[i] < 0 then (* a real, from v0 to v7 *) A.storeF(-1 - inReg[i], FP, INT(inSlot[i]), 8); if inObj[i]^.reg # 0 then A.fop1(A.fMov, inObj[i]^.reg - XmmVar, -1 - inReg[i], false); end; elsif (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]); if inSize[i] < 8 then A.extend(r, r, inSize[i], inObj[i]^.typ^.signed); end; else 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 = Sym.fReal) then A.loadF(p^.reg - XmmVar, FP, INT(p^.val), INT(p^.typ^.size)); elsif 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; begin 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; fl: BOOL; begin r := top(); fl := isReal(depth - 1); drop(); A.load(U, FP, INT(retSlot), 8, false); if fl then A.storeF(r, U, INT(off), size); else A.store(r, U, INT(off), size); end; end; (* Pops an address, and copies size bytes from it to the result, off bytes into it *) proc copyResult*(off, size: I64); begin 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, or d0; two words, the two values on top, in x0 and x1; one in memory is there already *) proc returnJump*; begin if (resType # nil) and (resType^.form = Sym.fReal) then xValueTo(depth - 1, 0); drop(); elsif (resType # nil) and not Sym.behindPointer(resType) then if Sym.inTwoRegs(resType) then popTo(1); end; popTo(0); end; A.jmp(exitL); end; (* try, where the error isn't nil, first makes the machine's stack even on x86-64; here nothing is pushed, so sp is as the prologue left it *) proc tryAlign*; 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 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 its register r, which is returned, and, if it isn't nil, returned from the procedure by tryReturnFrom *) proc tryTest*(var ok: INT): INT; var r: INT; begin r := loaded(depth - 1); jumpIf(ok, false); return r; end; proc tryReturnFrom*(r: INT); begin returnError(r); end; (* The end of the procedure in chunk c: the code that returns, and the frame's size, known only now, patched into its prologue. If it is open, running off its end, it returns zeros. *) proc endProc*(c: INT; open: BOOL): ERROR; var n: I64; begin codeChunk := -1; if (depth # 0) or (pushed # 0) then Diag.fatal("internal error: stack depth"); end; 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; A.fmovFR(0, ZR, false); else A.dropJumpTo(exitL); end; A.fixLink(exitL); saveRegs(true); 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)); Chunk.put4At(frameFix + 4, SubSp | INT((n & 0FFFH) shl 10)); if A.listing then A.restate(frameFix, Diag.say("sub sp, sp, #{}, lsl #12", [Fmt.int(INT(n shr 12))])); A.restate(frameFix + 4, Diag.say("sub sp, sp, #{}", [Fmt.int(INT(n & 0FFFH))])); end; Chunk.endChunk(c); 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 A.jmp(L); at := Chunk.pc; A.storeIdx(LR, SP, -16, 8, A.mPre); return at, pushed; end; proc deferEnd*(L, saved: INT); begin keepTemps(); A.loadIdx(LR, SP, 16, 8, A.mPost); A.ret(); A.fixLink(L); pushed := saved; end; proc runDefer*(at: INT); begin A.callBack(at); end; (* The entry point, main, and its chunk. macOS starts every program in dyld, the dynamic loader, which binds its C symbols and calls the procedure LC_MAIN names as C's main(argc, argv): this one. It saves argc, an int (so its upper half is undefined until extended), and argv; gives the library C's symbols it needs (cLinks: Rt's cExit) and Rt the addresses it is given (links); runs every used module's body, then main; and ends with Rt.exit, its status main's or 0. The frame record it pushes links to dyld's, where a trace ends. Every program reaches the kernel through libSystem, so dynamic is always so; bare, for a machine with no system, isn't a Mac's. *) proc entryPoint*(dynamic, bare: BOOL; first: ^Sym.Module; mainObj: ^Sym.Obj; cLinks: []Link; numCLinks, exitProc: INT; links: []Link; numLinks: INT): INT; var entry, i: INT; m: ^Sym.Module; begin if bare or not dynamic then Diag.fatal("a program for macOS runs over libSystem: Rt must use C, and -bare is not for it"); end; entry := Chunk.newChunk(Chunk.secText, -1, internStr("main")); Chunk.beginChunk(entry); A.stp(FP, LR, SP, -16, A.mPre); A.movRR(FP, SP); A.extend(0, 0, 4, true); A.storeChunk(0, argcChunk, 0, 8); A.storeChunk(1, argvChunk, 0, 8); for i := 0 to numCLinks - 1 do A.loadChunk(0, cLinks[i].chunk, 0, 8, false); A.storeChunk(0, cLinks[i].into, 0, 8); end; for i := 0 to numLinks - 1 do A.addrChunk(0, links[i].chunk, 0); A.storeChunk(0, links[i].into, 0, 8); end; m := first; while m # nil do if m^.used and (m^.body >= 0) then A.callChunk(m^.body); end; m := m^.next; end; if mainObj # nil then A.callChunk(mainObj^.chunk); end; if (mainObj = nil) or (mainObj^.typ^.base = nil) then A.movRI(0, 0); end; 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; (* A code procedure: its instructions, read by the assembler (A64), are the whole of chunk c *) proc codeProc*(c: INT; constExpr: A.ConstFn; nameFn: A.NameFn): ERROR; begin Chunk.beginChunk(c); try A.assemble(constExpr, nameFn); Chunk.endChunk(c); return nil; end; (* Whether the code procedure in chunk c is a square root of d0, or of s0 if single, in itself, then ret, as Math.sqrt is, which a call of it does in place (realInPlace), as on x86-64: its first word, or 0. *) const FsqrtD = 1E61C000H; FsqrtS = 1E21C000H; Ret = 0D65F03C0H; proc oneRealOp*(c: INT; single: BOOL): INT; var s, i, w, want: INT; words: [2]INT; begin s := Chunk.chunks[c].start; if (Chunk.chunks[c].size # 8) or (Chunk.chunks[c].numFix # 0) then return 0; end; for w := 0 to 1 do words[w] := 0; for i := 3 to 0 by -1 do words[w] := words[w] shl 8 | INT(Chunk.text[s + 4 * w + i]); end; end; want := FsqrtD; if single then want := FsqrtS; end; if (words[0] = want) and (words[1] = Ret) then return want; end; return 0; end; (* The square root of oneRealOp on the real on top, in its register: Math.sqrt(d2) is fsqrt d16, d16, with no call *) proc realInPlace*(op: INT); var x: INT; begin x := top(); A.fop1(A.fSqrt, x, x, op = FsqrtS); 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; resetStack(0, 0); rtFail := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr("fail")); argcChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argc")); Chunk.setBss(argcChunk, 8, 8); argvChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argv")); Chunk.setBss(argvChunk, 8, 8); end Gen.