From 11681e72f338c3b044a354ff995d62599011d717 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 12 Oct 2026 15:08:41 +0100 Subject: [PATCH] Conditions as jumps v0.7.0 step 4. "if c then break; end" is one jump out of the loop where c holds (ThenPart, LoneBreak, CondJumpTrue), not a jump over a jump, when no deferred statement waits; a branch of an if that ends gets no jump past the others; a return that ends a procedure no longer jumps to the next instruction (DropJumpTo, TakeBack moving the line notes with it), and the zeros for running off the end are made only where it can be run off. A compare with zero is test; a BOOL is tested where it is. labelAt, set and never read, goes. rat: within noise (505 -> 504 ms), text -0.7%; a search loop that leaves by break 28% faster (74 -> 53 ms). conform/run/Breaks. --- diff --git a/conform/run/Breaks.expect b/conform/run/Breaks.expect new file mode 100644 index 0000000..ac3ccae --- /dev/null +++ b/conform/run/Breaks.expect @@ -0,0 +1,4 @@ +10 +113 +5 +3 diff --git a/conform/run/Breaks.raz b/conform/run/Breaks.raz new file mode 100644 index 0000000..56b93db --- /dev/null +++ b/conform/run/Breaks.raz @@ -0,0 +1,22 @@ +module Breaks; + +(* Leaving loops by break: on conditions of and and or, before elsif + and else, and with a deferred statement to run on the way out. *) +import Out; +var log: INT; +proc note; begin INC(log); end; +proc main*; +var i, s: INT; b: BOOL; +begin + for i := 0 to 100 do if i > 3 and i # 4 then break; end; s := s + i; end; + Out.int(s); Out.ln; (* 0+1+2+3+4 = 10 *) + s := 0; + for i := 0 to 100 do if i = 7 or i * i > 30 then break; elsif i = 2 then s := s + 100; else s := s + i; end; end; + Out.int(s); Out.ln; (* 0+1+100+3+4+5 = 113 *) + s := 0; i := 0; + while true do b := i = 5; if b then break; end; INC(i); end; + Out.int(i); Out.ln; (* 5 *) + for i := 0 to 3 do defer note; if i = 2 then break; end; end; + Out.int(log); Out.ln; (* 3 *) +end; +end Breaks. diff --git a/doc/compiler.md b/doc/compiler.md index 4f49da3..005bbbe 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -11,11 +11,11 @@ | `src/diag.pas` | 310 | 229 | Messages: positions, source excerpts, colour, counts | | `src/scan.pas` | 886 | 747 | Symbols, literals, comments, positions | | `src/sym.pas` | 643 | 527 | Types, objects, scopes, layout | -| `src/chunk.pas` | 302 | 234 | The compiled program: chunks, fixups, line notes | -| `src/x64.pas` | 1,113 | 930 | The instruction encoder, jumps within a procedure, the assembler | -| `src/gen.pas` | 1,650 | 1,282 | The stack machine, for x86-64: values, operations, checks, calls, frames | -| `src/item.pas` | 1,478 | 1,234 | Items: types, constants, variables, operators, conversions, calls | -| `src/parse.pas` | 2,927 | 2,588 | Declarations, statements, expressions, built-ins, recovery, warnings | +| `src/chunk.pas` | 318 | 246 | The compiled program: chunks, fixups, line notes | +| `src/x64.pas` | 1,125 | 936 | The instruction encoder, jumps within a procedure, the assembler | +| `src/gen.pas` | 1,653 | 1,284 | The stack machine, for x86-64: values, operations, checks, calls, frames | +| `src/item.pas` | 1,493 | 1,247 | Items: types, constants, variables, operators, conversions, calls | +| `src/parse.pas` | 2,957 | 2,609 | 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 | @@ -263,6 +263,10 @@ the position of the one before (`Jmp`, `Jcc`); `FixLink` walks the chain and patches each once the label's position is known. This is the trick from Wirth's compilers, and it means a label is one integer. +`DropJumpTo` takes back a `jmp` just made to a label about to be +placed after it, so a `return` that ends a procedure doesn't jump to +the next instruction; the line notes made after it move back with it +(`TakeBack`, in `chunk.pas`). ## gen.pas: the stack machine @@ -475,7 +479,10 @@ Then statements: `Statement` makes each one a recovery point (below) and `OneStatement` dispatches; `IfStatement`, `WhileStatement`, `ForStatement` and `MatchStatement` emit their jumps -with gen's labels. The blank is a symbol of its own, `sBlank`, so +with gen's labels. A branch of an `if` that ends, in `return` or +`break` (`ends`), gets no jump past the others; and `if c then break; +end` is one jump out of the loop where `c` holds (`ThenPart`, +`LoneBreak`, `CondJumpTrue`), not a jump past a jump. The blank is a symbol of its own, `sBlank`, so no declaration or expression takes it: `_ := e` loads a single value and drops it, and `MultiAssign` skips the results it stands for. A `match` on an integer reads each arm's diff --git a/src/chunk.pas b/src/chunk.pas index 71054df..91b6dff 100644 --- a/src/chunk.pas +++ b/src/chunk.pas @@ -106,6 +106,7 @@ procedure Put8(v: int64); procedure Put4At(at, v: longint); function Get4At(at: longint): longint; +procedure TakeBack(n: longint); implementation @@ -142,6 +143,21 @@ function Get4At(at: longint): longint; begin Get4At := PLongint(@code^[at])^; +end; + +{ The last n bytes of code taken back. A line noted past the new end + now starts there, in place of one noted there before, as NoteLine + would have it. } +procedure TakeBack(n: longint); +begin + dec(pc, n); + if (numLines > 0) and (lines^[numLines - 1].at > pc) then begin + lines^[numLines - 1].at := pc; + if (numLines > 1) and (lines^[numLines - 2].at = pc) then begin + lines^[numLines - 2] := lines^[numLines - 1]; + dec(numLines); + end; + end; end; procedure Put8(v: int64); diff --git a/src/gen.pas b/src/gen.pas index 49388d8..7b8b10f 100644 --- a/src/gen.pas +++ b/src/gen.pas @@ -161,7 +161,7 @@ procedure ResultTo(off: int64; size: longint); procedure CopyResult(off, size: int64); procedure ReturnJump; -procedure EndProc(c: longint); +procedure EndProc(c: longint; open: boolean); function DeferBegin(var L, saved: longint): longint; procedure DeferEnd(L, saved: longint); procedure RunDefer(at: longint); @@ -548,10 +548,12 @@ Log2 := n; end; -{ r compared with v, through rdx if v needs more than 32 bits } +{ r compared with v, through rdx if v needs more than 32 bits; with + zero by test, which sets the flags as cmp would and is shorter } procedure CmpI(r: longint; v: int64); begin - if Fits32(v) then AluI(aluCmp, r, v) + if v = 0 then TestRR(r, r) + else if Fits32(v) then AluI(aluCmp, r, v) else begin MovRI(RDX, v); Alu(aluCmp, r, RDX) end; end; @@ -924,7 +926,7 @@ procedure JumpIf(var L: longint; when: boolean); var r: longint; begin - r := Top; + r := Peek(depth - 1); Drop; TestRR(r, r); if when then Jcc(ccNE, L) else Jcc(ccE, L); @@ -1499,14 +1501,14 @@ 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. } -procedure EndProc(c: longint); + frame's size, known only now, patched into its prologue. If it is + open, running off its end, it returns zeros. } +procedure EndProc(c: longint; open: boolean); var n: int64; i: longint; begin codeChunk := -1; if (depth <> 0) or (pushed <> 0) then Fatal('internal error: stack depth'); - { running off the end returns zeros } - if resType <> nil then + if open then if BehindPointer(resType) then begin Load(RDI, Mem(RBP, retSlot), 8, false); MovRI(RCX, resType^.size); @@ -1517,7 +1519,8 @@ MovRI(RAX, 0); if InTwoRegs(resType) then MovRI(RDX, 0); MovqXR(0, RAX); - end; + end + else DropJumpTo(exitL); FixLink(exitL); n := 0; for i := 0 to 4 do diff --git a/src/item.pas b/src/item.pas index f49d4d3..8805216 100644 --- a/src/item.pas +++ b/src/item.pas @@ -100,6 +100,7 @@ procedure MatchTag(p: int64; tag: int64; var L: longint; isEnum: boolean); procedure MatchRange(p, lo, hi: int64; var body: longint); procedure CondJump(var x: TItem; var L: longint); +procedure CondJumpTrue(var x: TItem; var L: longint); procedure SliceOf(var x: TItem; t: PType; len: int64); procedure TempItem(var x: TItem; t: PType; off: int64); @@ -1352,6 +1353,20 @@ end; Value(x); JumpIf(L, false); +end; + +{ As CondJump, but the jump is taken where the condition holds } +procedure CondJumpTrue(var x: TItem; var L: longint); +begin + if x.typ^.form <> fBool then MarkAt(x.pos, 'a condition is a BOOL, found ' + What(x)); + if x.mode = mCond then begin + JumpCmp(x.rel, x.relSigned, L); + L := JoinJumps(L, x.tj); + Fix(x.fj); + exit; + end; + Value(x); + JumpIf(L, true); end; { Procedures } diff --git a/src/parse.pas b/src/parse.pas index ce093bb..300af58 100644 --- a/src/parse.pas +++ b/src/parse.pas @@ -1216,30 +1216,60 @@ for i := numDefers - 1 downto base do RunDefer(defers[i]); end; +{ Whether what follows "then" is a lone "break;", with no deferred + statement to run on the way out of the loop } +function LoneBreak: boolean; +var st: TScanState; +begin + LoneBreak := false; + if (tok <> sBreak) or (curLoop = nil) or (numDefers <> curLoop^.base) then exit; + SaveScan(st); + Next; + if tok = sSemicolon then begin + Next; + LoneBreak := tok in [sEnd, sElsif, sElse]; + end; + RestoreScan(st); +end; + +{ The condition x of if or elsif, and the statements it guards, which + L skips when it is false. "if c then break; end" is one jump out of + the loop when c holds, not one past a jump out. } +procedure ThenPart(var x: TItem; var L: longint); +begin + Expect(sThen); + L := NoLabel; + if LoneBreak then begin + NoteLine(CurLine, CurCol); + CondJumpTrue(x, curLoop^.brk); + Next; Next; { break; } + ends := true; + end else begin + CondJump(x, L); + Statements; + end; +end; + +{ A branch that ends, in return or break, needs no jump past the + others. } procedure IfStatement(const start: TPos; ind: longint); var x: TItem; L, endL: longint; all: boolean; begin Next; Expression(x, nil); - Expect(sThen); - L := NoLabel; - CondJump(x, L); - Statements; + ThenPart(x, L); all := ends; endL := NoLabel; while tok = sElsif do begin - Jump(endL); + if not ends then Jump(endL); Fix(L); Next; Expression(x, nil); - Expect(sThen); - L := NoLabel; - CondJump(x, L); - Statements; + ThenPart(x, L); all := all and ends; end; if tok = sElse then begin - Jump(endL); + if not ends then Jump(endL); Fix(L); Next; if tok = sIf then elseIf := true; @@ -1950,7 +1980,7 @@ PlaceLocals(params, before); RestoreScan(st); until false; - EndProc(p^.chunk); + EndProc(p^.chunk, p^.openEnd); { its parameters and variables, for the trap report } if before = nil then o := curModule^.locals else o := before^.link; q := params; @@ -2655,7 +2685,7 @@ Statements; NoteLine(CurLine, CurCol); Expect(sEnd); - EndProc(body); + EndProc(body, false); end; end else Expect(sEnd); if (tok <> sIdent) or (id <> n) then EndMissing(MissingPos, 'expected ' + NameOf(n) + ', found ' + Found); diff --git a/src/x64.pas b/src/x64.pas index 05d8beb..3adaad5 100644 --- a/src/x64.pas +++ b/src/x64.pas @@ -44,7 +44,6 @@ end; var - labelAt: longint; { the last place a jump was made to land } listing: boolean; { -S: each instruction's text is kept, for List } function Here: TMem; @@ -106,6 +105,7 @@ procedure JmpBack(target: longint); procedure JccBack(cc, target: longint); procedure FixLink(L: longint); +procedure DropJumpTo(var L: longint); procedure FixLinkTo(L, target: longint); function JoinLinks(L1, L2: longint): longint; @@ -695,7 +695,6 @@ procedure FixLinkTo(L, target: longint); var next: longint; begin - if L <> NoLabel then labelAt := target; while L <> NoLabel do begin next := Get4At(L); Put4At(L, target - (L + 4)); @@ -706,6 +705,19 @@ procedure FixLink(L: longint); begin FixLinkTo(L, pc); +end; + +{ If the last instruction made is a jmp to L, it is taken back, since L + is to be placed just after it: a return at the end of a procedure + needn't jump to the code that returns. The caller must place L next, + before anything can have noted where the jmp ended. A jcc's field + follows the bytes 0F 8x, never E9. } +procedure DropJumpTo(var L: longint); +begin + if (L = NoLabel) or (L <> pc - 4) or (code^[L - 1] <> $E9) then exit; + L := Get4At(L); + TakeBack(5); + if listing and (numSaid > 0) and (said[numSaid - 1].at = pc) then dec(numSaid); end; { The jumps of chains L1 and L2, as one chain: each jump's field holds diff --git a/test/list/Listing.expect b/test/list/Listing.expect index 283b535..8139459 100644 --- a/test/list/Listing.expect +++ b/test/list/Listing.expect @@ -16,12 +16,9 @@ 27 shl r9, 1 31 add r8, r9 34 mov rax, r8 - 37 jmp 49 15 end add; - 42 xor eax, eax - 44 movq xmm0, rax - 49 leave - 50 ret + 37 leave + 38 ret Listing.main: 17 proc main*;