raz / commit ae086c9a

commit
ae086c9a5573670420299eb72353fc306c9a7f49
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
513d996e
Seed: match on an integer or an enumeration by a jump table

The arms come first and Dispatch after them: a table for four labels
or more close together (JumpTable in gen: rip-relative, no relocations),
else the chain of compares, each jumping back to its arm.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

patch · log

8 files changed, +226 -32

doc/compiler.md (history) modified +9 -3

@@ -1017,9 +1017,15 @@
10171017 no declaration or expression takes it: `_ := e` loads a single value
10181018 and drops it, and `MultiAssign` skips the results it stands for. A
10191019 `match` on an integer reads each arm's
1020-labels in `IntArm`, which refuses a value in two of them, and tests them
1021-one after another with `MatchRange`: compares and branches, no jump
1022-table. `Defer` is worth reading: a deferred statement
1020+labels in `IntArm`, which refuses a value in two of them. The arms
1021+come first and the test after them: the match starts with a jump to
1022+`Dispatch`, placed after the last arm, since a jump table can only be
1023+made once every arm's place is known (an enumeration's arms are
1024+picked the same way; a variant's, by its tag, arm by arm).
1025+`Dispatch` makes a jump table (gen's `JumpTable`, whose comment shows
1026+the code) for four labels or more that lie close together, else
1027+compares and branches one label after another with `MatchRange`, each
1028+jumping back to its arm. `Defer` is worth reading: a deferred statement
10231029 is compiled where it stands, as a little subroutine of the procedure
10241030 that the code jumps over (gen's `DeferBegin` and `DeferEnd`), and
10251031 `RunDefers` emits a call to it at every way out of its statement list:

self/README.md modified +5 -4

@@ -47,7 +47,8 @@
4747 comparison `a[0..n] = b[0..n]` (97 ms), a 256-entry table for the
4848 bytes of a name (84), and one for the symbols that are a byte each
4949 (75). What is left for the code generator, which would help every
50- module: a `match` on an integer is a chain of compares, each loading
51- the selector from the frame and jumping over a `jmp` (`je L1; jmp L2`),
52- where FPC makes a jump table; and the slice comparison is slower than
53- the loop it stands for.
50+ module: the slice comparison is slower than the loop it stands for.
51+ (The seed's `match` on an integer was a chain of compares, each
52+ loading the selector from the frame and jumping over a `jmp`, where
53+ FPC makes a jump table; now it makes one too, and the seed's `Scan`
54+ runs on it.)

src/gen.pas modified +47 -0

@@ -171,6 +171,8 @@
171171 procedure JumpOut(op: TSym; signed: boolean; var L: longint);
172172 procedure CondValue(notOp: TSym; signed: boolean; fj, tj: longint);
173173 procedure JumpBack(top: longint);
174+function JumpTable(slot, lo: int64; n, elseAt: longint; var endL: longint): longint;
175+procedure TableEntry(table, target: longint);
174176 procedure AlignLoop;
175177 procedure Fix(L: longint);
176178 procedure FixTo(L, top: longint);
@@ -1344,6 +1346,51 @@
13441346 procedure Fix(L: longint);
13451347 begin
13461348 FixLink(L);
1349+end;
1350+
1351+{ A jump table, for a match on the integer in frame slot slot, whose
1352+ labels run from lo up for n values. The selector less lo, compared
1353+ unsigned (so below lo is above n too), is out of the table if it
1354+ isn't below n, and goes to the else arm at elseAt, or, if there is
1355+ none, to endL, the end of the match. Else it indexes a table of
1356+ 4-byte offsets, each from the start of the lea, that follows the
1357+ jump, and the code jumps to its start plus the entry:
1358+
1359+ mov rax, [slot]
1360+ sub rax, lo
1361+ cmp rax, n - 1
1362+ ja else
1363+ lea rcx, [rip + start] start: this very lea
1364+ movsxd rax, [rcx + rax*4 + 17]
1365+ add rax, rcx
1366+ jmp rax
1367+ table: .long arm0 - start, arm1 - start, ...
1368+
1369+ The four instructions after the compare are 7, 5, 3 and 2 bytes, so
1370+ the table is 17 bytes on, which JumpTable checks. It returns start;
1371+ the caller then makes the n entries with TableEntry. }
1372+function JumpTable(slot, lo: int64; n, elseAt: longint; var endL: longint): longint;
1373+const TableAt = 17;
1374+var start: longint;
1375+begin
1376+ Load(RAX, Mem(RBP, slot), 8, false);
1377+ if lo <> 0 then AluI(aluSub, RAX, lo);
1378+ AluI(aluCmp, RAX, n - 1);
1379+ if elseAt <> NoLabel then JccBack(ccA, elseAt) else Jcc(ccA, endL);
1380+ start := pc;
1381+ Lea(RCX, Here);
1382+ Load(RAX, MemIdx(RCX, RAX, 4, TableAt), 4, true);
1383+ Alu(aluAdd, RAX, RCX);
1384+ JmpR(RAX);
1385+ if pc <> start + TableAt then Fatal('internal error: the jump table is not where it was said');
1386+ JumpTable := start;
1387+end;
1388+
1389+{ The next entry of the table that JumpTable started at table: the
1390+ code at target }
1391+procedure TableEntry(table, target: longint);
1392+begin
1393+ Put4(target - table);
13471394 end;
13481395
13491396 procedure AlignLoop;

src/item.pas modified +5 -8

@@ -100,7 +100,7 @@
100100 procedure Construct(var x: TItem; c: PObj);
101101 procedure SetField(const x: TItem; f: PObj; var a: TItem);
102102 function MatchBegin(var x: TItem): int64;
103-procedure MatchTag(p: int64; tag: int64; var L: longint; isEnum: boolean);
103+procedure MatchTag(p: int64; tag: int64; var L: longint);
104104 procedure MatchRange(p, lo, hi: int64; var body: longint);
105105 procedure CondJump(var x: TItem; var L: longint);
106106 procedure CondJumpTrue(var x: TItem; var L: longint);
@@ -1316,16 +1316,13 @@
13161316 MatchBegin := p;
13171317 end;
13181318
1319-{ To L unless the tag of the variant whose address is in slot p, or the
1320- enumeration in it, is tag }
1321-procedure MatchTag(p: int64; tag: int64; var L: longint; isEnum: boolean);
1319+{ To L unless the tag of the variant whose address is in slot p is tag }
1320+procedure MatchTag(p: int64; tag: int64; var L: longint);
13221321 var a: TAdr;
13231322 begin
13241323 PushVar(FrameAdr(p), 8, false, kWord);
1325- if not isEnum then begin
1326- a.base := bStack; a.chunk := -1; a.off := 0;
1327- PushVar(a, 8, false, kWord);
1328- end;
1324+ a.base := bStack; a.chunk := -1; a.off := 0;
1325+ PushVar(a, 8, false, kWord);
13291326 PushConst(kWord, tag);
13301327 JumpCmp(sNeq, false, L);
13311328 end;

src/parse.pas modified +74 -17

@@ -1506,7 +1506,8 @@
15061506
15071507 type
15081508 TLabels = record
1509- lo, hi: array[0..1023] of int64; { the ranges of the arms so far }
1509+ lo, hi: array[0..1023] of int64; { the ranges of the labels so far }
1510+ at: array[0..1023] of longint; { where the arm of each starts }
15101511 n: longint;
15111512 end;
15121513
@@ -1516,14 +1517,15 @@
15161517 if unsign then Below := qword(a) < qword(b) else Below := a < b;
15171518 end;
15181519
1519-{ An arm of a match on an integer of type t, held in slot p: its labels,
1520- each a constant or a range, none overlapping another (report section
1521- 7.4), then its statements. }
1522-procedure IntArm(t: PType; p: int64; var ls: TLabels; var endL: longint);
1523-var lo, hi: TItem; L, body, i: longint; u: boolean; start: TPos;
1520+{ An arm of a match on an integer of type t: its labels, each a
1521+ constant or a range, none overlapping another (report section 7.4),
1522+ then its statements. No code tests the labels here; Dispatch does,
1523+ after the last arm, for which each label notes where its arm starts. }
1524+procedure IntArm(t: PType; var ls: TLabels; var endL: longint);
1525+var lo, hi: TItem; first, i: longint; u: boolean; start: TPos;
15241526 begin
15251527 u := not t^.signed;
1526- body := NoLabel;
1528+ first := ls.n;
15271529 repeat
15281530 start := TokPos;
15291531 Expression(lo, t);
@@ -1544,23 +1546,62 @@
15441546 if ls.n > High(ls.lo) then MarkAt(SpanFrom(start), 'more than ' + IntStr(High(ls.lo) + 1) + ' labels in one match');
15451547 ls.lo[ls.n] := lo.val; ls.hi[ls.n] := hi.val;
15461548 inc(ls.n);
1547- MatchRange(p, lo.val, hi.val, body);
15481549 if tok <> sComma then break;
15491550 Next;
15501551 until false;
1551- L := NoLabel;
1552- Jump(L);
1553- Fix(body);
15541552 Expect(sColon);
1553+ for i := first to ls.n - 1 do ls.at[i] := pc;
15551554 Statements;
15561555 Jump(endL);
1557- Fix(L);
1556+end;
1557+
1558+const
1559+ MinTable = 4; { fewer labels are tested one by one }
1560+ TableDensity = 8; { a table has at most this many entries to a label }
1561+
1562+{ The code that picks the arm, after the last one, which the match's
1563+ start jumped to: label by label, as a chain of compares each to its
1564+ arm; or, for four or more labels not far apart, a jump table (JumpTable),
1565+ which takes the same few instructions for any of them. It is here and
1566+ not before the arms, since a table can only be made once every arm's
1567+ place is known; an arm is entered by a jump back to it. elseAt is where
1568+ the else arm starts, or NoLabel. }
1569+procedure Dispatch(t: PType; p: int64; const ls: TLabels; elseAt: longint; var endL: longint);
1570+var
1571+ lo, hi: int64; i, start: longint; v: int64; u: boolean; body: longint;
1572+ entry: array[0..1023] of longint;
1573+begin
1574+ u := (t^.form = fInt) and not t^.signed;
1575+ lo := 0; hi := 0;
1576+ if ls.n > 0 then begin
1577+ lo := ls.lo[0]; hi := ls.hi[0];
1578+ for i := 1 to ls.n - 1 do begin
1579+ if Below(ls.lo[i], lo, u) then lo := ls.lo[i];
1580+ if Below(hi, ls.hi[i], u) then hi := ls.hi[i];
1581+ end;
1582+ end;
1583+ if (ls.n >= MinTable) and (lo >= low(longint)) and (lo <= high(longint))
1584+ and (qword(hi - lo) < qword(TableDensity) * ls.n) and (hi - lo <= High(entry)) then begin
1585+ start := JumpTable(p, lo, hi - lo + 1, elseAt, endL);
1586+ for v := 0 to hi - lo do
1587+ if elseAt <> NoLabel then entry[v] := elseAt else entry[v] := start;
1588+ for i := 0 to ls.n - 1 do
1589+ for v := ls.lo[i] - lo to ls.hi[i] - lo do entry[v] := ls.at[i];
1590+ for v := 0 to hi - lo do TableEntry(start, entry[v]);
1591+ exit;
1592+ end;
1593+ for i := 0 to ls.n - 1 do begin
1594+ body := NoLabel;
1595+ MatchRange(p, ls.lo[i], ls.hi[i], body);
1596+ FixTo(body, ls.at[i]);
1597+ end;
1598+ if elseAt <> NoLabel then JumpBack(elseAt);
15581599 end;
15591600
15601601 procedure MatchStatement(const start: TPos; ind: longint);
15611602 var
1562- x: TItem; t: PType; c, f, o: PObj; p: int64; L, endL, n: longint;
1563- seen: array[0..255] of boolean; hasElse, all: boolean; endAt: TPos; ls: TLabels;
1603+ x: TItem; t: PType; c, f, o: PObj; p: int64; L, endL, n, disp, elseAt: longint;
1604+ seen: array[0..255] of boolean; hasElse, all, byValue: boolean; endAt: TPos; ls: TLabels;
15641605 begin
15651606 Next;
15661607 Expression(x, nil);
@@ -1573,16 +1614,24 @@
15731614 all := true;
15741615 endL := NoLabel;
15751616 ls.n := 0;
1617+ { an integer or an enumeration is matched by its value, and the arms
1618+ are picked by Dispatch, after them; a variant by its tag, arm by arm }
1619+ byValue := t^.form in [fInt, fEnum];
1620+ disp := NoLabel;
1621+ elseAt := NoLabel;
1622+ if byValue then Jump(disp);
15761623 while tok = sBar do begin
15771624 Next;
15781625 if hasElse then Mark('else must be the last arm');
15791626 if tok = sElse then begin
15801627 Next;
15811628 Expect(sColon);
1629+ elseAt := pc;
15821630 Statements;
1631+ if byValue then Jump(endL);
15831632 hasElse := true;
15841633 end else if t^.form = fInt then
1585- IntArm(t, p, ls, endL)
1634+ IntArm(t, ls, endL)
15861635 else begin
15871636 if tok <> sIdent then Expected('a case');
15881637 c := t^.fields;
@@ -1592,7 +1641,10 @@
15921641 if c^.val <= High(seen) then seen[c^.val] := true;
15931642 Next;
15941643 L := NoLabel;
1595- MatchTag(p, c^.val, L, t^.form = fEnum);
1644+ if t^.form = fEnum then begin
1645+ ls.lo[ls.n] := c^.val; ls.hi[ls.n] := c^.val;
1646+ inc(ls.n);
1647+ end else MatchTag(p, c^.val, L);
15961648 OpenScope(NewScope);
15971649 if tok = sLparen then begin
15981650 Next;
@@ -1615,10 +1667,11 @@
16151667 Expect(sRparen);
16161668 end;
16171669 Expect(sColon);
1670+ if t^.form = fEnum then ls.at[ls.n - 1] := pc;
16181671 Statements;
16191672 CloseScope;
16201673 Jump(endL);
1621- Fix(L);
1674+ if t^.form <> fEnum then Fix(L);
16221675 end;
16231676 all := all and ends;
16241677 end;
@@ -1633,6 +1686,10 @@
16331686 if (c^.val > High(seen)) or not seen[c^.val] then MarkAt(endAt, 'no arm for ' + NameOf(c^.name));
16341687 c := c^.next;
16351688 end;
1689+ end;
1690+ if byValue then begin
1691+ Fix(disp);
1692+ Dispatch(t, p, ls, elseAt, endL);
16361693 end;
16371694 Fix(endL);
16381695 end;

src/x64.pas modified +7 -0

@@ -75,6 +75,7 @@
7575 procedure CallChunk(c: longint);
7676 procedure CallBack(target: longint);
7777 procedure CallR(r: longint);
78+procedure JmpR(r: longint);
7879 procedure CallM(const m: TMem);
7980 procedure Ret;
8081 procedure Leave;
@@ -554,6 +555,12 @@
554555 begin
555556 if listing then Say('call ' + RN(r));
556557 OpR(0, false, $FF, 2, r);
558+end;
559+
560+procedure JmpR(r: longint);
561+begin
562+ if listing then Say('jmp ' + RN(r));
563+ OpR(0, false, $FF, 4, r);
557564 end;
558565
559566 procedure CallM(const m: TMem);

test/run/MatchTable.expect (history) added +4 -0

@@ -0,0 +1,4 @@
1+-1 -1 -1 -1 10 20 20 -1 30 30 30 -1 40 -1 -1
2+0 1 2 3 4 0
3+0140
4+1234567

test/run/MatchTable.raz (history) added +75 -0

@@ -0,0 +1,75 @@
1+module MatchTable;
2+import Out;
3+
4+type
5+ Day = (mon, tue, wed, thu, fri, sat, sun);
6+
7+(* dense, with a hole and a range: a jump table *)
8+proc dense(n: I64): I64;
9+begin
10+ match n of
11+ | 1: return 10;
12+ | 2, 3: return 20;
13+ | 5..7: return 30;
14+ | 9: return 40;
15+ | else: return -1;
16+ end;
17+end;
18+
19+(* negative labels *)
20+proc signed(n: I64): I64;
21+begin
22+ match n of
23+ | -2: return 1;
24+ | -1: return 2;
25+ | 0: return 3;
26+ | 1: return 4;
27+ | else: return 0;
28+ end;
29+end;
30+
31+(* unsigned, at the top of the range *)
32+proc top(n: U64): I64;
33+begin
34+ match n of
35+ | 0FFFFFFFFFFFFFFFCH: return 1;
36+ | 0FFFFFFFFFFFFFFFDH: return 2;
37+ | 0FFFFFFFFFFFFFFFEH: return 3;
38+ | 0FFFFFFFFFFFFFFFFH: return 4;
39+ | else: return 0;
40+ end;
41+end;
42+
43+proc kind(d: Day): I64;
44+var r: I64;
45+begin
46+ r := 0;
47+ match d of
48+ | mon: r := 1;
49+ | tue: r := 2;
50+ | wed: r := 3;
51+ | thu: r := 4;
52+ | fri: r := 5;
53+ | sat: r := 6;
54+ | sun: r := 7;
55+ end;
56+ return r;
57+end;
58+
59+proc main*;
60+var i: I64; d: Day;
61+begin
62+ for i := -3 to 11 do
63+ Out.int(dense(i)); Out.str(" ");
64+ end;
65+ Out.ln;
66+ for i := -3 to 2 do
67+ Out.int(signed(i)); Out.str(" ");
68+ end;
69+ Out.ln;
70+ Out.int(top(0FFFFFFFFFFFFFFFBH)); Out.int(top(0FFFFFFFFFFFFFFFCH));
71+ Out.int(top(0FFFFFFFFFFFFFFFFH)); Out.int(top(0)); Out.ln;
72+ for d := mon to sun do Out.int(kind(d)); end;
73+ Out.ln;
74+end;
75+end MatchTable.