From 46597e23432a6e82504fd8cd3c9b36c0b421289a Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 12 Oct 2026 14:07:50 +0100 Subject: [PATCH] Register variables A procedure keeps its busiest single values, up to five, in rbx and r12 to r15, which calls leave alone. ChooseRegs reads the body ahead and counts uses, a use in a loop 4, in two 16, leaving out what ADR takes; a variable whose address is wanted after all, by a var parameter, is put back in memory and the body compiled again (MarkCode, Redo). The prologue saves the registers after the variables, zeroes them and takes the parameters' values; the epilogue restores them. A variable in one is noted on the stack (lHeld) and read in place where only read (Peek): i < n is cmp rbx, r12, and an argument mov rdi, rbx. The trap report: each procedure's record in the places says which it saved and where; Rt carries the five registers out frame by frame (liveRegs, restore). Budget raised to 8,500 by the owner's word. rat on 26 MB of terminal output: 953 ms to 740 (-22%); Pretty 1,405 to 1,174 (-16%), Doc 454 to 393, a counting loop 997 to 700; the code is the same size. 8,283 lines of code; bench 962k lines/s. --- diff --git a/CLAUDE.md b/CLAUDE.md index bfb9334..afb341b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -55,7 +55,8 @@ `Luis <42945842+ldiaz94@users.noreply.github.com>`, unsigned (`--no-gpg-sign`), no attribution trailer. Push to `main`. No pull requests unless asked. -- Budget: a soft limit of 8,000 lines of code (blank and comment lines +- Budget: a soft limit of 8,500 lines of code (raised from 8,000 by + the owner's word, for register variables; blank and comment lines not counted), with the compiler documented and commented throughout, most of all where it is obscure or needs a compiler writer's knowledge; at least 400,000 lines of raz a second. diff --git a/doc/compiler.md b/doc/compiler.md index 77bf31b..ae77bd6 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -1,6 +1,6 @@ # Reading the raz compiler -The compiler is eleven files of Free Pascal, under 8,100 lines of code. +The compiler is eleven files of Free Pascal, under 8,300 lines of code. This guide walks through them in the order they are best read: from the characters of a source file to the bytes of an executable. It assumes you know the language from `doc/raz.md`, and enough x86-64 to read a @@ -10,13 +10,13 @@ |---|---|---|---| | `src/diag.pas` | 310 | 229 | Messages: positions, source excerpts, colour, counts | | `src/scan.pas` | 886 | 747 | Symbols, literals, comments, positions | -| `src/sym.pas` | 615 | 510 | Types, objects, scopes, layout | -| `src/chunk.pas` | 298 | 232 | The compiled program: chunks, fixups, line notes | -| `src/x64.pas` | 1,094 | 916 | The instruction encoder, jumps within a procedure, the assembler | -| `src/gen.pas` | 1,428 | 1,118 | The stack machine, for x86-64: values, operations, checks, calls, frames | -| `src/item.pas` | 1,400 | 1,168 | Items: types, constants, variables, operators, conversions, calls | -| `src/parse.pas` | 2,771 | 2,459 | Declarations, statements, expressions, built-ins, recovery, warnings | -| `src/link.pas` | 243 | 188 | Tree shaking, layout, patching, the places | +| `src/sym.pas` | 616 | 511 | Types, objects, scopes, layout | +| `src/chunk.pas` | 300 | 234 | The compiled program: chunks, fixups, line notes | +| `src/x64.pas` | 1,108 | 926 | The instruction encoder, jumps within a procedure, the assembler | +| `src/gen.pas` | 1,536 | 1,203 | The stack machine, for x86-64: values, operations, checks, calls, frames | +| `src/item.pas` | 1,412 | 1,178 | Items: types, constants, variables, operators, conversions, calls | +| `src/parse.pas` | 2,895 | 2,566 | Declarations, statements, expressions, built-ins, recovery, warnings | +| `src/link.pas` | 247 | 190 | Tree shaking, layout, patching, the places | | `src/elf.pas` | 435 | 352 | Static and dynamic ELF, symbol table, line numbers | | `src/raz.pas` | 197 | 147 | The command line | @@ -47,10 +47,12 @@ needs it in a register, so that it can be an instruction's operand. A comparison, too, waits as a condition, so that `if` and `while` jump on it directly. Which register a value goes in is settled -by its depth, so there is no register allocator, and every access the -program writes is one instruction, in the order written. That is also -why `VOLATILE` costs the compiler nothing: it never does anything -clever to begin with. +by its depth, so there is no register allocator for values, and every +access the program writes is one instruction, in the order written. +That is also why `VOLATILE` costs the compiler nothing: it never does +anything clever to begin with. A procedure's busiest variables, up to +five, live in the registers that calls leave alone (`rbx` and `r12` to +`r15`), where nothing but their own assignments can change them. The output is a set of *chunks*: one for each procedure, each module variable, each string. Code refers to other chunks through *fixups*, @@ -351,6 +353,17 @@ scratch space comes from `AllocTemp` and is given back by `ReleaseTemps`; `AllocPerm` reserves space for the whole procedure. +Register variables: the parser chooses them (`ChooseRegs`, below) and +tells gen (`UseRegs`): the registers, as bits of `VarRegs`, and the +slots they are saved in, a quadword each after the variables. The +prologue saves them, zeroes them, and takes a parameter's value from +where it came; the epilogue restores them. A variable in one is an +item at `bReg`: `PushVar` notes it (`lHeld`) rather than copying it, +`Peek` reads it in place where the value is only read, so `i < n` is +`cmp rbx, r12`, and `PopVar` and `IncDecReg` write it. Rt finds the +values for the trap report from the saves: each procedure's record in +the places says which it saved, and where (`saveMask`, `saveAt`). + ## item.pas: items An operand is an *item* (`TItem`), as in Wirth's compilers. Its `mode` @@ -520,6 +533,18 @@ parses its own arguments, since `SIZE` takes a type and `INC` a variable. +**Register variables.** One pass can't know whether a variable's +address will be taken before its code is made, so `ChooseRegs` reads +the body ahead, as `InstancesFor` does, and counts each variable's +uses: 1 for each, 4 in a loop, 16 in two; one `ADR` takes is out. The +five busiest used at least three times get registers (`o^.reg`). An +address wanted after all, by a `var` parameter, say, comes to +`Address` (`item.pas`), which puts the variable back in memory and +sets `demoted`: `Body` then throws the procedure's code away +(`MarkCode`, `Redo`) and compiles its statements again. Its notes for +the trap report are made after, by `VarKind`, which marks a variable +in a register with the register's number. + ## link.pas: tree shaking and layout `MarkLive` starts from the entry chunk and follows fixups, marking each @@ -634,6 +659,9 @@ with no `break`. So is a call standing on its own that drops a result (`drops`, kept by `OneStatement` and told by `Dropped`); `_ := f(x)` drops one on purpose. `-Werror` makes each an error. +- **Registers for variables.** Up to five of a procedure's single + values, not reals, whose address is never taken, live in `rbx` and + `r12` to `r15`; the trap report shows them as it shows the others. - **Several results** come back through a hidden pointer to the caller's slots; a code procedure returns two in rax and rdx. - **Reals.** A real constant is held as an F64. An `F32` in a register diff --git a/lib/Rt.raz b/lib/Rt.raz index 8072da1..8ac99f5 100644 --- a/lib/Rt.raz +++ b/lib/Rt.raz @@ -35,12 +35,13 @@ file whose path is at path in the names *) Place = record at, line, col, path: U32; end; (* A procedure, from address start to stop, called name, and its - count variables from first on *) - Proc = record start, stop, name, first, count: U32; end; + count variables from first on; it saves the registers of its + variables, bits of regs, a quadword each from saveAt in its frame *) + Proc = record start, stop, name, first, count, saves: U32; saveAt: I32; end; (* A variable of a procedure, at off from its frame, shown by kind: 1 a signed integer, 2 an unsigned one, 3 a BOOL, 4 an address, 5 a real; plus its size times 16, and 256 if the frame holds its - address *) + address, or 512 times 1 + i if it is in register i of regs *) Local = record name: U32; off: I32; kind: U32; end; (* What rt_sigaction and sigaltstack take *) Action = record @@ -61,6 +62,9 @@ The linker makes them. *) places: ^INT; line: [256]U8; (* the message being made *) + (* rbx, r12, r13, r14 and r15 in the frame being told of, where the + compiler keeps a procedure's busiest variables *) + regs: [5]UINT; lineLen: INT; act: Action; alt: Stack; @@ -159,7 +163,7 @@ (* The paths and names, after the places, procedures and variables *) proc names: ^U8; begin - return ^U8(places + 5) + 16 * places[0] + 20 * places[3] + 12 * places[4]; + return ^U8(places + 5) + 16 * places[0] + 28 * places[3] + 12 * places[4]; end; (* Puts where the code at address a comes from, as file:line:col: and @@ -251,6 +255,7 @@ var a: ^U8; w: ^UINT; h: ^U16; s: ^U32; f: ^F32; d: ^F64; v: UINT; bits: INT; begin a := ^U8(bp) + INT(l^.off); + if l^.kind shr 9 # 0 then a := ^U8(ADR(regs[INT(l^.kind shr 9) - 1])); end; w := ^UINT(a); if l^.kind & 256 # 0 then a := ^U8(w^); w := ^UINT(a); end; h := ^U16(a); s := ^U32(a); f := ^F32(a); d := ^F64(a); @@ -285,14 +290,60 @@ return 1; end; +(* rbx, r12, r13, r14 and r15, into p[0] to p[4] *) +proc liveRegs(p: ^UINT); +code + mov [rdi], rbx; + mov [rdi + 8], r12; + mov [rdi + 16], r13; + mov [rdi + 24], r14; + mov [rdi + 32], r15; + ret; +end liveRegs; + +(* An address in the code of the procedure that calls it *) +proc here: UINT; +code + mov rax, [rsp]; + ret; +end here; + +(* regs as the caller of p's frame at bp left them, where p saved them *) +proc restore(p: ^Proc; bp: UINT); +var i, j: INT; q: ^UINT; +begin + if p = nil then return; end; + j := 0; + for i := 0 to 4 do + if p^.saves shr i & 1 # 0 then + q := ^UINT(^U8(bp) + INT(p^.saveAt) + 8 * j); + regs[i] := q^; + INC(j); + end; + end; +end; + (* Says the calls under way, a line each, from the one at address ip whose frame is at bp: where each is, and its variables, unless vars is false for the first. At most 20 lines; a frame that isn't the program's ends them. Calls of one procedure from one place, as in a recursion that overflowed the stack, are told once, and counted. *) proc calls(ip, bp: UINT; vars: BOOL); -var p, last: ^Proc; l: ^Local; i, n, same: INT; q: ^UINT; lastIp: UINT; +var p, last: ^Proc; l: ^Local; i, n, same: INT; q: ^UINT; lastIp, x, xip: UINT; saved: BOOL; begin + (* the registers as they are, then as each frame from this one out + to bp's found them *) + liveRegs(ADR(regs[0])); + x := framePtr(); + xip := here(); + while (x # bp) and (x & 7 = 0) and (x # 0) do + restore(procAt(xip), x); + q := ^UINT(x); + if q[0] <= x then break; end; + xip := q[1] - 1; + x := q[0]; + end; + saved := vars; (* not in a prologue: the frame has saved them *) n := 0; same := 0; last := nil; @@ -311,7 +362,7 @@ putStr(names() + INT(p^.name)); put(" at "); where(ip); - l := ^Local(^U8(places + 5) + 16 * places[0] + 20 * places[3]) + INT(p^.first); + l := ^Local(^U8(places + 5) + 16 * places[0] + 28 * places[3]) + INT(p^.first); if not vars or (p^.count = 0) then DEC(lineLen, 2); end; (* where's ": " *) for i := 0 to INT(p^.count) - 1 do if vars then @@ -325,6 +376,8 @@ INC(n); vars := true; end; + if saved then restore(p, bp); end; + saved := true; q := ^UINT(bp); if (bp & 7 # 0) or (q[0] <= bp) then break; end; ip := q[1] - 1; (* the call, by its return address *) diff --git a/src/chunk.pas b/src/chunk.pas index 8e191fa..993889f 100644 --- a/src/chunk.pas +++ b/src/chunk.pas @@ -35,6 +35,8 @@ ext: boolean; { bss: the address of a C symbol, its name } reals: boolean; { code: computes with reals, first at realsAt } realsAt: TPos; + saveMask: longint; { code: the registers of variables it saves, as bits of gen's VarRegs } + saveAt: longint; { ... at this offset from the frame, one quadword each } end; { A place in the source whose code starts at a place in text: for diff --git a/src/gen.pas b/src/gen.pas index 4b2cf0f..28fedea 100644 --- a/src/gen.pas +++ b/src/gen.pas @@ -56,16 +56,19 @@ { 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 } - TBase = (bFrame, bGlobal, bStack, bSlot); + TBase = (bFrame, bGlobal, bStack, bSlot, bReg); TAdr = record base: TBase; - chunk: longint; { bGlobal: the chunk; bSlot: the frame slot } + chunk: longint; { bGlobal: the chunk; bSlot: the frame slot; bReg: the register } off: int64; { added to the address } end; { How an argument waits for its call: in a frame slot, or noted, as a constant or as the address of the frame or a chunk plus an offset } - TArgHow = (argSlot, argConst, argAdr); + TArgHow = (argSlot, argConst, argAdr, argHeld); + + { The code made so far, to go back to for a second try at a body } + TCodeMark = record pc, fixups, lines, said: longint; end; TCall = record sig: PType; @@ -83,6 +86,12 @@ ret: int64; { set by Call: the temporary an aggregate result is in } end; +const + { the registers a procedure keeps its busiest variables in: System V's + callee-saved ones, so they live through calls; a procedure saves + those it uses, and Rt finds them there for the trap report } + VarRegs: array[0..4] of longint = (RBX, R12, R13, R14, R15); + var rtFail, argcChunk, argvChunk: longint; depth: longint; { the values on the stack } @@ -116,6 +125,7 @@ procedure CompareSeq(a, b: int64; shift: longint; eq: boolean); procedure ErrorText(tmp: int64); procedure IncDec(size: longint; signed, dec: boolean); +procedure IncDecReg(r, size: longint; signed, dec: boolean); procedure ZeroNew(size: int64); procedure Atomic(which: longint); procedure SysCall(n: longint); @@ -148,6 +158,9 @@ procedure KeepTemps; procedure BeginProc(sig: PType; params: PObj); +procedure UseRegs(mask: longint; at: int64); +procedure MarkCode(var m: TCodeMark); +procedure Redo(const m: TCodeMark); procedure EnterBody(c, line: longint); procedure ResultTo(off: int64; size: longint); procedure CopyResult(off, size: int64); @@ -165,6 +178,8 @@ type { where a value on the stack is } TLoc = (lConst, { not loaded: val is the value } + lHeld, { not loaded: in register val, a variable's own, + which nothing in an expression can change } lAdr, { not loaded: the address of chunk, or of the frame if chunk is -1, plus val } lReg, { in its register } @@ -198,7 +213,12 @@ inReg: array[0..13] of longint; inSlot: array[0..13] of int64; inSize: array[0..13] of longint; + inObj: array[0..13] of PObj; numIn: longint; + procParams: PObj; { the parameters, for EnterBody } + regMask: longint; { the registers of variables, as bits of VarRegs } + saveAt: int64; { where they are saved, a quadword each } + frameAt: array[0..2] of int64; { frameTop, frameMax, permTop after the declarations } function KindOf(t: PType): TKind; begin @@ -263,11 +283,19 @@ if stack[i].loc <> lReg then begin r := Claim(i); if stack[i].loc = lConst then MovRI(r, stack[i].val) + else if stack[i].loc = lHeld then MovRR(r, stack[i].val) else if stack[i].loc = lAdr then Lea(r, AdrMem(i, 0)) else Load(r, Mem(RBP, stack[i].val), 8, false); stack[i].loc := lReg; end; Loaded := RegOf(i); +end; + +{ The register value i is in, only to be read: a variable's own, or + its register } +function Peek(i: longint): longint; +begin + if stack[i].loc = lHeld then Peek := stack[i].val else Peek := Loaded(i); end; function Top: longint; @@ -334,6 +362,7 @@ function Place(const a: TAdr; r: longint): TMem; var ra: longint; begin + if a.base = bReg then Fatal('internal error: a register has no address'); case a.base of bFrame: Place := Mem(RBP, a.off); bGlobal: Place := MemRip(a.chunk, a.off); @@ -342,7 +371,7 @@ Place := AdrMem(depth - 1, a.off); Drop; end else begin - ra := Top; + ra := Peek(depth - 1); Drop; Place := Mem(ra, a.off) end; @@ -370,6 +399,10 @@ procedure PushVar(const a: TAdr; size: longint; signed: boolean; k: TKind); var m: TMem; r: longint; begin + if a.base = bReg then begin + NewEntry(k, lHeld, a.chunk); + exit; + end; if a.base = bStack then begin m := Place(a, -1); r := Target end else begin r := Target; m := Place(a, r) end; Load(r, m, size, signed); @@ -390,13 +423,18 @@ procedure PopVar(const a: TAdr; size: longint); var r: longint; v: int64; begin + if a.base = bReg then begin + if TopConst(v) then MovRI(a.chunk, v) else MovRR(a.chunk, Peek(depth - 1)); + Drop; + exit; + end; if TopConst(v) and Fits32(v) then begin Drop; StoreI(Place(a, RCX), v, size); exit; end; if TopConst(v) then begin r := RAX; MovRI(RAX, v) end - else r := Top; + else r := Peek(depth - 1); Drop; Store(Place(a, RCX), r, size); end; @@ -533,7 +571,7 @@ function Operands(var y: longint): longint; var v: int64; begin - if TopConst(v) then begin MovRI(RCX, v); y := RCX end else y := Top; + if TopConst(v) then begin MovRI(RCX, v); y := RCX end else y := Peek(depth - 1); Drop; Operands := Top; end; @@ -785,6 +823,18 @@ Store(Mem(r, 0), RAX, size); end; +{ INC or DEC of the variable in register r, by the value on top; a + narrow one wraps at its width } +procedure IncDecReg(r, size: longint; signed, dec: boolean); +var y, op: longint; v: int64; +begin + if dec then op := aluSub else op := aluAdd; + if TopConst(v) and Fits32(v) then AluI(op, r, v) + else begin y := Top; Alu(op, r, y) end; + Drop; + if size < 8 then Extend(r, size, signed); +end; + { The pointer on top, which NEW got, to size zero bytes unless nil } procedure ZeroNew(size: int64); var L, r: longint; @@ -827,6 +877,7 @@ for i := 0 to n - 1 do with stack[depth - n + i] do if loc = lConst then MovRI(SysRegs[i], val) + else if loc = lHeld then MovRR(SysRegs[i], val) else if loc = lAdr then Lea(SysRegs[i], AdrMem(depth - n + i, 0)) else Load(SysRegs[i], Mem(RBP, val), 8, false); for i := 1 to n do Drop; @@ -864,8 +915,9 @@ CcUnsigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccB, ccBE, ccA, ccAE); var r, y: longint; v: int64; begin - if TopConst(v) then begin Drop; r := Top; CmpI(r, v) end - else begin r := Operands(y); Alu(aluCmp, r, y) end; + { a comparison changes neither: a variable's register will do } + if TopConst(v) then begin Drop; r := Peek(depth - 1); CmpI(r, v) end + else begin y := Peek(depth - 1); Drop; r := Peek(depth - 1); Alu(aluCmp, r, y) end; Drop; if signed then Jcc(CcSigned[op], L) else Jcc(CcUnsigned[op], L); end; @@ -1069,7 +1121,8 @@ i := depth - 1; c.how[c.n] := argSlot; if not c.isF[c.n] and (stack[i].loc = lConst) then c.how[c.n] := argConst - else if stack[i].loc = lAdr then c.how[c.n] := argAdr; + else if stack[i].loc = lAdr then c.how[c.n] := argAdr + else if stack[i].loc = lHeld then c.how[c.n] := argHeld; if c.how[c.n] = argSlot then begin c.slots[c.n] := AllocTemp(8, 8); Store(Mem(RBP, c.slots[c.n]), Top, 8); @@ -1085,6 +1138,7 @@ begin case c.how[i] of argConst: MovRI(r, c.slots[i]); + argHeld: MovRR(r, c.slots[i]); argAdr: if c.adrChunk[i] < 0 then Lea(r, Mem(RBP, c.slots[i])) else Lea(r, MemRip(c.adrChunk[i], c.slots[i])); @@ -1202,10 +1256,12 @@ exitL := NoLabel; numIn := 0; resType := sig^.base; + procParams := params; + regMask := 0; ni := 0; nf := 0; stackOff := 16; if (resType <> nil) and IsAggregate(resType) then begin retSlot := AllocPerm(8, 8); - inReg[0] := RDI; inSlot[0] := retSlot; inSize[0] := 8; + inReg[0] := RDI; inSlot[0] := retSlot; inSize[0] := 8; inObj[0] := nil; numIn := 1; ni := 1; end; p := params; @@ -1217,6 +1273,7 @@ if f then begin inReg[numIn] := -1 - nf; inc(nf) end else begin inReg[numIn] := IntRegs[ni]; inc(ni) end; inSlot[numIn] := p^.val; + inObj[numIn] := p; if p^.ind then inSize[numIn] := 8 else if p^.typ^.form in [fInt, fBool, fEnum, fSet, fReal] then inSize[numIn] := p^.typ^.size else inSize[numIn] := 8; @@ -1230,12 +1287,35 @@ paramTop := frameTop; end; +{ The procedure keeps variables in the registers of mask, saved at at; + the frame as it stands is where a second try at its body starts. } +procedure UseRegs(mask: longint; at: int64); +begin + regMask := mask; + saveAt := at; + frameAt[0] := frameTop; frameAt[1] := frameMax; frameAt[2] := permTop; +end; + +procedure MarkCode(var m: TCodeMark); +begin + m.pc := pc; m.fixups := numFixups; m.lines := numLines; m.said := SaidCount; +end; + +{ For a second try at the body: the code as it was at m, and the frame + as UseRegs found it } +procedure Redo(const m: TCodeMark); +begin + pc := m.pc; numFixups := m.fixups; numLines := m.lines; Unsay(m.said); + frameTop := frameAt[0]; frameMax := frameAt[1]; permTop := frameAt[2]; + exitL := NoLabel; +end; + { The prologue, which is for the procedure's first line. Only the locals are zeroed: the parameters are stored over their slots next, and every temporary is written before it is read. The locals are all declared by now, below the parameters' slots. } procedure EnterBody(c, line: longint); -var i, top: longint; n: int64; +var i, top: longint; n: int64; p: PObj; begin BeginChunk(c); codeChunk := c; @@ -1257,9 +1337,31 @@ AluI(aluAdd, R10, 1); JccBack(ccNE, top); end; + { the registers of variables: saved, as a variable starts at zero, + a parameter taken from where it came } + chunks^[c].saveMask := regMask; + chunks^[c].saveAt := saveAt; + n := 0; + for i := 0 to 4 do + if regMask and (1 shl i) <> 0 then begin + Store(Mem(RBP, saveAt + 8 * n), VarRegs[i], 8); + MovRI(VarRegs[i], 0); + inc(n); + end; for i := 0 to numIn - 1 do if inReg[i] < 0 then MovsdMX(Mem(RBP, inSlot[i]), -1 - inReg[i]) - else Store(Mem(RBP, inSlot[i]), inReg[i], inSize[i]); + else if (inObj[i] <> nil) and (inObj[i]^.reg <> 0) then begin + MovRR(inObj[i]^.reg, inReg[i]); + if inSize[i] < 8 then Extend(inObj[i]^.reg, inSize[i], inObj[i]^.typ^.signed); + end else Store(Mem(RBP, inSlot[i]), inReg[i], inSize[i]); + p := procParams; + while p <> nil do begin + if (p^.reg <> 0) and (p^.val > 0) then + if p^.typ^.form in [fInt, fBool, fEnum, fSet] then + Load(p^.reg, Mem(RBP, p^.val), p^.typ^.size, p^.typ^.signed) + else Load(p^.reg, Mem(RBP, p^.val), 8, false); + p := p^.next; + end; end; { Pops one of several results, a value of size bytes, into its place @@ -1300,7 +1402,7 @@ { The end of the procedure in chunk c: the code that returns, and the frame's size, known only now, patched into its prologue. } procedure EndProc(c: longint); -var n: int64; +var n: int64; i: longint; begin codeChunk := -1; if (depth <> 0) or (pushed <> 0) then Fatal('internal error: stack depth'); @@ -1317,6 +1419,12 @@ MovqXR(0, RAX); end; FixLink(exitL); + n := 0; + for i := 0 to 4 do + if regMask and (1 shl i) <> 0 then begin + Load(VarRegs[i], Mem(RBP, saveAt + 8 * n), 8, false); + inc(n); + end; Leave; Ret; n := AlignUp(frameMax, 16); diff --git a/src/item.pas b/src/item.pas index e34dea2..a4cb205 100644 --- a/src/item.pas +++ b/src/item.pas @@ -47,6 +47,7 @@ end; var + demoted: boolean; { Address wanted a register variable's address } checks: boolean; { the module's index and slice checks are made: it doesn't say check off } @@ -258,6 +259,8 @@ x.base := bGlobal; x.chunk := o^.chunk end else if o^.ind then begin x.base := bSlot; x.chunk := o^.val; x.off := o^.off; + end else if o^.reg <> 0 then begin + x.base := bReg; x.chunk := o^.reg end else begin x.base := bFrame; x.off := o^.val end; @@ -357,6 +360,14 @@ procedure Address(var x: TItem); begin NilTest(x); + if (x.mode = mVar) and (x.base = bReg) then begin + { its address is wanted after all: the procedure is compiled again + with the variable in memory; till then, this code is thrown away } + x.obj^.reg := 0; + demoted := true; + x.base := bFrame; + x.off := x.obj^.val; + end; if x.mode = mStr then PushAdr(GlobalAdr(x.chunk)) else if x.mode = mVar then begin PushAdr(AdrOf(x)); @@ -1370,7 +1381,8 @@ begin CoerceExact(k, v.typ, ''); Value(k); - gen.IncDec(ScalarSize(v.typ), v.typ^.signed, dec); + if v.base = bReg then IncDecReg(v.chunk, ScalarSize(v.typ), v.typ^.signed, dec) + else gen.IncDec(ScalarSize(v.typ), v.typ^.signed, dec); end; { An error is the address of its length, followed by its message. } diff --git a/src/link.pas b/src/link.pas index d262e00..a5bef05 100644 --- a/src/link.pas +++ b/src/link.pas @@ -92,10 +92,12 @@ text starts and stops, the procedures' and their variables' (I64s); for each place in live code its address, line, column and the offset of its file's path (U32s); for each live procedure where it starts and - stops, the offset of its name, its first variable and how many it has - (U32s); for each variable the offset of its name, its place in the - frame and its kind, as parse.pas's VarKind (U32s); then the paths and - names, each ending in a zero byte. They are in no order, since Rt + stops, the offset of its name, its first variable and how many it + has, and the registers of variables it saves, as bits of gen's + VarRegs, and the frame offset they are saved at (U32s); for each + variable the offset of its name, its place in the frame and its + kind, as parse.pas's VarKind (U32s); then the paths and names, each + ending in a zero byte. They are in no order, since Rt looks at them only as the program stops. } procedure MakePlaces(start, stop: int64); var @@ -141,7 +143,7 @@ for v := first^[c] to first^[c] + count^[c] - 1 do k := k + length(NameOf(varNotes[v].name)) + 1; nv := nv + count^[c]; end; - buf := GetMem(40 + 16 * n + 20 * np + 12 * nv + k); + buf := GetMem(40 + 16 * n + 28 * np + 12 * nv + k); PInt64(@buf^[0])^ := n; PInt64(@buf^[8])^ := start; PInt64(@buf^[16])^ := stop; @@ -159,7 +161,7 @@ at := at + 16; end; { the pool of paths and names starts at k } - k := 40 + 16 * n + 20 * np + 12 * nv; + k := 40 + 16 * n + 28 * np + 12 * nv; names := k; { the paths first, at the offsets offs gave the places: Name puts each in the pool, and also writes its offset at at, which a path @@ -178,7 +180,9 @@ Name(ChunkName(c)); PLongint(@buf^[at])^ := v; PLongint(@buf^[at + 4])^ := count^[c]; - at := at + 8; + PLongint(@buf^[at + 8])^ := chunks^[c].saveMask; + PLongint(@buf^[at + 12])^ := chunks^[c].saveAt; + at := at + 16; v := v + count^[c]; end; for c := 0 to numChunks - 1 do diff --git a/src/parse.pas b/src/parse.pas index 89cfd2c..e8ec1f4 100644 --- a/src/parse.pas +++ b/src/parse.pas @@ -81,7 +81,7 @@ curResult: PType; { the result type of the procedure being compiled } inExtern: boolean; { reading an extern's signature: ... allowed } tArgv, tBodySig: PType; - nameRt, nameFail, nameMain, nameBody, nameStatic, nameCheck, nameOff: longint; + nameRt, nameFail, nameMain, nameBody, nameStatic, nameCheck, nameOff, nameAdr: longint; declaring: array[0..63] of longint; { the names the declaration being read declares } numDeclaring: longint; skipped: boolean; { the last statement had an error and was skipped } @@ -830,7 +830,7 @@ NotReadOnly(x); if (x.mode <> mVar) or not x.isVar or (x.typ^.form <> fInt) then MarkAt(x.pos, IncOrDec(which) + ' needs an integer variable'); - Address(x); + if x.base <> bReg then Address(x); if tok = sComma then begin Next; Expression(y, x.typ); @@ -1741,10 +1741,10 @@ { How Rt shows a variable of o's type in the trap report: 1 a signed integer, 2 an unsigned one, 3 a BOOL, 4 an address, 5 a real; plus - its size times 16, and 256 if the frame holds its address; 0 if it - isn't shown. } + its size times 16, and 256 if the frame holds its address, or 512 + times 1 + i if it is in register VarRegs[i]; 0 if it isn't shown. } function VarKind(o: PObj): longint; -var k: longint; +var k, i: longint; begin case o^.typ^.form of fInt: k := 2 - ord(o^.typ^.signed); @@ -1755,10 +1755,121 @@ else exit(0); end; VarKind := k + o^.typ^.size * 16 + ord(o^.ind) * 256; + for i := 0 to 4 do + if o^.reg = VarRegs[i] then VarKind := k + o^.typ^.size * 16 + (i + 1) * 512; end; +{ Whether variable o could live in a register: a single value, not + a real, that isn't C's } +function RegFit(o: PObj): boolean; +begin + RegFit := (o^.cls = oVar) and not o^.ind and not o^.ext + and ((o^.typ^.form in [fInt, fBool, fEnum, fPtr, fProc, fError]) + or (o^.typ^.form = fSet) and (o^.typ^.size <= 8)); +end; + +{ Puts the busiest variables of the procedure, whose parameters are + params and whose locals follow before, in registers: read ahead from + its "begin" to its end, a use counts 1, in a loop 4, in two 16, and + a variable ADR is taken of can't have one. A register costs a save + and a restore, so a variable used less than three times keeps its + place in memory. The registers are saved after the variables. } +procedure ChooseRegs(params, before: PObj); +var + cand: array[0..63] of PObj; weight: array[0..63] of longint; + isLoop: array[0..255] of boolean; + n, i, k, d, loops, mask, best: longint; o: PObj; st: TScanState; afterDot, wasSkipping: boolean; + + function Find(name: longint): longint; + var j: longint; + begin + for j := 0 to n - 1 do if cand[j]^.name = name then exit(j); + Find := -1; + end; + + procedure Add(o: PObj); + begin + if RegFit(o) and (n <= High(cand)) then begin cand[n] := o; weight[n] := 0; inc(n) end; + end; + +begin + n := 0; + o := params; + while o <> nil do begin Add(o); o := o^.next end; + if before = nil then o := curModule^.locals else o := before^.link; + while o <> nil do begin Add(o); o := o^.link end; + mask := 0; + if n > 0 then begin + SaveScan(st); + wasSkipping := skipping; + skipping := true; { its slips are told when it is compiled } + d := 0; loops := 0; afterDot := false; + repeat + case tok of + sBegin, sIf, sMatch, sWhile, sFor, sRepeat: + if d < High(isLoop) then begin + inc(d); + isLoop[d] := tok in [sWhile, sFor, sRepeat]; + if isLoop[d] then inc(loops); + end; + sEnd, sUntil: begin + if isLoop[d] then dec(loops); + dec(d); + end; + sIdent: + if id = nameAdr then begin + Next; + if tok = sLparen then Next; + if (tok = sIdent) and (Find(id) >= 0) then weight[Find(id)] := low(longint) div 2; + end else if not afterDot and (Find(id) >= 0) then begin + k := Find(id); + if loops > 2 then inc(weight[k], 64) else inc(weight[k], 1 shl (2 * loops)); + end; + end; + afterDot := tok = sPeriod; + if (d > 0) and (tok <> sEof) then Next; + until (d = 0) or (tok = sEof); + RestoreScan(st); + skipping := wasSkipping; + for k := 0 to 4 do begin + best := -1; + for i := 0 to n - 1 do + if (cand[i]^.reg = 0) and (weight[i] >= 3) and ((best < 0) or (weight[i] > weight[best])) then best := i; + if best < 0 then break; + cand[best]^.reg := VarRegs[k]; + mask := mask or (1 shl k); + end; + end; + k := 0; + for i := 0 to 4 do if mask and (1 shl i) <> 0 then inc(k); + if k = 0 then UseRegs(0, 0) + else UseRegs(mask, AllocPerm(8 * k, 8)); +end; + +{ The registers the variables of the procedure are in, as ChooseRegs's + mask } +function RegsOf(params, before: PObj): longint; +var o: PObj; m, k: longint; +begin + m := 0; + o := params; + while o <> nil do begin + for k := 0 to 4 do if o^.reg = VarRegs[k] then m := m or (1 shl k); + o := o^.next; + end; + if before = nil then o := curModule^.locals else o := before^.link; + while o <> nil do begin + if o^.cls = oVar then + for k := 0 to 4 do if o^.reg = VarRegs[k] then m := m or (1 shl k); + o := o^.link; + end; + RegsOf := m; +end; + procedure Body(p: PObj; sig: PType; line: longint); -var q, params, last, o, before: PObj; old: PType; +var + q, params, last, o, before: PObj; old: PType; st: TScanState; + mark: TCodeMark; drops0, errs: longint; begin OpenScope(NewScope); params := nil; last := nil; @@ -1784,6 +1895,28 @@ curProc := p; before := curModule^.lastLocal; Declarations(false); + ChooseRegs(params, before); + { the body, made again if a variable in a register must be in memory } + SaveScan(st); + MarkCode(mark); drops0 := numDrops; errs := errors; + old := curResult; + repeat + demoted := false; + Expect(sBegin); + curResult := sig^.base; + EnterBody(p^.chunk, line); + stray := false; elseIf := false; deferSlot := 0; + Statements; + p^.openEnd := (curResult <> nil) and not ends; + NoteLine(CurLine, CurCol); + Expect(sEnd); + if not demoted or (errors <> errs) then break; + numDrops := drops0; + Redo(mark); + UseRegs(RegsOf(params, before), chunks^[p^.chunk].saveAt); + RestoreScan(st); + until false; + EndProc(p^.chunk); { its parameters and variables, for the trap report } if before = nil then o := curModule^.locals else o := before^.link; q := params; @@ -1795,16 +1928,6 @@ if (o^.cls = oVar) and (VarKind(o) <> 0) then NoteVar(p^.chunk, o^.name, o^.val, VarKind(o)); o := o^.link; end; - Expect(sBegin); - old := curResult; - curResult := sig^.base; - EnterBody(p^.chunk, line); - stray := false; elseIf := false; - Statements; - p^.openEnd := (curResult <> nil) and not ends; - NoteLine(CurLine, CurCol); - Expect(sEnd); - EndProc(p^.chunk); curResult := old; curProc := nil; CloseScope; @@ -2758,6 +2881,7 @@ nameRt := Name('Rt'); nameFail := Name('fail'); nameMain := Name('main'); + nameAdr := Name('ADR'); nameBody := Name('body'); nameStatic := Name('static'); nameCheck := Name('check'); diff --git a/src/sym.pas b/src/sym.pas index 6214105..b43285a 100644 --- a/src/sym.pas +++ b/src/sym.pas @@ -72,6 +72,7 @@ fwd: boolean; { oProc: declared forward, no body yet } isCode: boolean; { oProc: a code procedure } openEnd: boolean; { oProc: has results, and may reach its end } + reg: longint; { oVar: the register it lives in, or 0 if in memory } ext: boolean; { oProc, oVar: C's, reached through its chunk, which holds its address } fields: PObj; { oCase: its fields } diff --git a/src/x64.pas b/src/x64.pas index bc7ce70..01a87c1 100644 --- a/src/x64.pas +++ b/src/x64.pas @@ -18,7 +18,7 @@ const RAX = 0; RCX = 1; RDX = 2; RBX = 3; RSP = 4; RBP = 5; RSI = 6; RDI = 7; - R8 = 8; R9 = 9; R10 = 10; R11 = 11; + R8 = 8; R9 = 9; R10 = 10; R11 = 11; R12 = 12; R13 = 13; R14 = 14; R15 = 15; RIP = -1; { a base meaning rip-relative, to a chunk } NoIndex = -1; @@ -125,6 +125,8 @@ procedure Assemble(constExpr: TConstFn); procedure Say(const s: shortstring); +function SaidCount: longint; +procedure Unsay(n: longint); procedure Restate(at: longint; const s: shortstring); procedure List(module: longint); @@ -244,6 +246,18 @@ var said: ^TSaid; numSaid, saidCap: longint; + +{ How many instructions the listing has, and back to n of them, for + code made again } +function SaidCount: longint; +begin + SaidCount := numSaid; +end; + +procedure Unsay(n: longint); +begin + numSaid := n; +end; procedure SayAt(at: longint; const s: shortstring); begin diff --git a/test/list/Listing.expect b/test/list/Listing.expect index 42f11da..8b68ed6 100644 --- a/test/list/Listing.expect +++ b/test/list/Listing.expect @@ -30,39 +30,38 @@ 4 sub rsp, 48 11 xor eax, eax 13 mov [rbp - 8], rax + 17 mov [rbp - 16], rax + 21 mov [rbp - 16], rbx + 25 xor ebx, ebx 20 for i := 1 to 3 do - 17 mov qword [rbp - 8], 1 - 25 mov qword [rbp - 16], 3 - 33 mov r8, [rbp - 8] - 37 mov r9, [rbp - 16] - 41 cmp r8, r9 - 44 jg 160 + 27 mov rbx, 1 + 32 mov qword [rbp - 24], 3 + 40 mov r9, [rbp - 24] + 44 cmp rbx, r9 + 47 jg 144 21 if i # 2 then total := add(total, twice(i)); end; - 50 mov r8, [rbp - 8] - 54 cmp r8, 2 - 58 je 122 - 64 mov r8, [Listing.total] - 71 mov [rbp - 24], r8 - 75 mov r8, [rbp - 8] - 79 mov [rbp - 32], r8 - 83 mov rdi, [rbp - 32] - 87 call Listing.twice - 92 mov r8, rax - 95 mov [rbp - 40], r8 - 99 mov rdi, [rbp - 24] - 103 mov rsi, [rbp - 40] - 107 call Listing.add - 112 mov r8, rax - 115 mov [Listing.total], r8 - 122 mov r8, [rbp - 16] - 126 mov r9, [rbp - 8] - 130 sub r8, r9 - 133 cmp r8, 1 - 137 jb 160 - 143 mov r8, [rbp - 8] - 147 add r8, 1 - 151 mov [rbp - 8], r8 - 155 jmp 33 + 53 cmp rbx, 2 + 57 je 112 + 63 mov r8, [Listing.total] + 70 mov [rbp - 32], r8 + 74 mov rdi, rbx + 77 call Listing.twice + 82 mov r8, rax + 85 mov [rbp - 40], r8 + 89 mov rdi, [rbp - 32] + 93 mov rsi, [rbp - 40] + 97 call Listing.add + 102 mov r8, rax + 105 mov [Listing.total], r8 + 112 mov r8, [rbp - 24] + 116 sub r8, rbx + 119 cmp r8, 1 + 123 jb 144 + 129 mov r8, rbx + 132 add r8, 1 + 136 mov rbx, r8 + 139 jmp 40 23 end main; - 160 leave - 161 ret + 144 mov rbx, [rbp - 16] + 148 leave + 149 ret diff --git a/test/run/ThreadOverflow.stderr b/test/run/ThreadOverflow.stderr index c3884f5..016b284 100644 --- a/test/run/ThreadOverflow.stderr +++ b/test/run/ThreadOverflow.stderr @@ -1,6 +1,6 @@ test/run/ThreadOverflow.raz:6:1: stopped by a stack overflow in ThreadOverflow.down at test/run/ThreadOverflow.raz:6:1 - in ThreadOverflow.down at test/run/ThreadOverflow.raz:10:5: n = 1926 - and 1926 more the same + in ThreadOverflow.down at test/run/ThreadOverflow.raz:10:5: n = 1871 + and 1871 more the same in ThreadOverflow.work at test/run/ThreadOverflow.raz:15:5: _arg = nil in Thread.run at lib/Thread.linux-x86_64.raz:80:5: arg = 0x?, t = 0x?