raz / commit c126e150

commit
c126e150268ebf36439d3ec4c7e2743a692478b6
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
6089fb3b
Better code from the same one pass

Three of Wirth's ways, no register allocator:
- A comparison of integers is an mCond item until something wants it:
  if and while jump on it (cmp, jcc), not on a BOOL made by setcc,
  movzx and test; and and or carry its jumps as chains (fj, tj), so
  (a < b) and (c < d) is two compares and two jumps, and not is the
  other comparison.
- An address in the frame or of a chunk is noted (lAdr) as a constant
  is: a field through it is one operand, and a constant or an address
  goes straight to its argument register (PopArg, LoadArg), not
  through a frame slot.
- A constant is stored, added or taken away in memory itself (x64's
  StoreI, AluMI): DEC(n) is sub qword [rbp - 8], 1.
The tools and examples: text 557,411 bytes to 518,579 (-7.0%);
Pretty over 348k lines 1,663 ms to 1,405 (-15.5%), Doc 488 to 454.
JumpKeep and FixKeep go. 8,066 lines of code; bench 1.07M lines/s.

patch · log

5 files changed, +327 -110

doc/compiler.md (history) modified +32 -19

@@ -1,6 +1,6 @@
11 # Reading the raz compiler
22
3-The compiler is eleven files of Free Pascal, under 7,900 lines of code.
3+The compiler is eleven files of Free Pascal, under 8,100 lines of code.
44 This guide walks through them in the order they are best read: from the
55 characters of a source file to the bytes of an executable. It assumes
66 you know the language from `doc/raz.md`, and enough x86-64 to read a
@@ -12,9 +12,9 @@
1212 | `src/scan.pas` | 886 | 747 | Symbols, literals, comments, positions |
1313 | `src/sym.pas` | 615 | 510 | Types, objects, scopes, layout |
1414 | `src/chunk.pas` | 298 | 232 | The compiled program: chunks, fixups, line notes |
15-| `src/x64.pas` | 1,039 | 870 | The instruction encoder, jumps within a procedure, the assembler |
16-| `src/gen.pas` | 1,332 | 1,039 | The stack machine, for x86-64: values, operations, checks, calls, frames |
17-| `src/item.pas` | 1,342 | 1,118 | Items: types, constants, variables, operators, conversions, calls |
15+| `src/x64.pas` | 1,094 | 916 | The instruction encoder, jumps within a procedure, the assembler |
16+| `src/gen.pas` | 1,428 | 1,118 | The stack machine, for x86-64: values, operations, checks, calls, frames |
17+| `src/item.pas` | 1,400 | 1,168 | Items: types, constants, variables, operators, conversions, calls |
1818 | `src/parse.pas` | 2,771 | 2,459 | Declarations, statements, expressions, built-ins, recovery, warnings |
1919 | `src/link.pas` | 243 | 188 | Tree shaking, layout, patching, the places |
2020 | `src/elf.pas` | 435 | 352 | Static and dynamic ELF, symbol table, line numbers |
@@ -43,8 +43,10 @@
4343
4444 On x86-64 the stack lives in registers, as in Wirth's compilers: the
4545 value at depth `d` is in register `d`, of `r8` to `r11`, and a constant
46-is only noted, until something needs it in a register, so that it can
47-be an instruction's operand. Which register a value goes in is settled
46+or an address in the frame or of a chunk is only noted, until something
47+needs it in a register, so that it can be an instruction's operand. A
48+comparison, too, waits as a condition, so that `if` and `while` jump
49+on it directly. Which register a value goes in is settled
4850 by its depth, so there is no register allocator, and every access the
4951 program writes is one instruction, in the order written. That is also
5052 why `VOLATILE` costs the compiler nothing: it never does anything
@@ -272,8 +274,8 @@
272274 the conversions between integers and reals, `CompareSeq` (of two
273275 slices), and copying: `CopyBlock`, `CopyTo`, `ZeroVar`;
274276 - jumps: `Jump`, `JumpIf` (on a `BOOL`), `JumpCmp` (on two integers),
275- `JumpKeep` and `FixKeep` for `and` and `or`, `Fix` where the label
276- is;
277+ `JumpOut` (`JumpCmp` from within an expression) and `CondValue` for
278+ `and` and `or`, `Fix` where the label is, and `JoinJumps`;
277279 - checks: `CheckIndex`, `CheckEnum`, and `IndexSlice`, `Slice` and
278280 `SlicePtr`, which check as they make their address or slice;
279281 - calls (`Call`), frames (`BeginProc`, `EnterBody`, `ReturnJump`,
@@ -289,19 +291,22 @@
289291 address first, so that a variable is read or written with one
290292 instruction.
291293
292-The stack: `stack` notes where each value is, a constant (`lConst`),
293-in its register (`lReg`) or in a frame slot (`lFrame`); `owner` which
294+The stack: `stack` notes where each value is, a constant (`lConst`), an
295+address not yet computed (`lAdr`, `AdrMem`'s operand), in its register
296+(`lReg`) or in a frame slot (`lFrame`); `owner` which
294297 value each register holds. The value at depth `d` belongs in
295298 `Regs[d mod 4]`, `r8` to `r11`: `rax`, `rdx` and `rcx`, which division
296299 and shifts need, and `rsi` and `rdi`, which copying needs, aren't among
297300 them. `Claim` gives a value its register, and `Spill`s a deeper one
298301 that holds it, when an expression is deeper than the registers;
299-`Loaded` brings a value into its register, from its constant or its
300-slot; `Top` is `Loaded` for the value on top, and `Target` the
302+`Loaded` brings a value into its register, from its constant, address
303+or slot; `Place` uses a noted address as the operand itself, and
304+`PopVar` and `IncDec` an operand of memory and a constant, so `DEC(n)`
305+is `sub qword [rbp - 8], 1`; `Top` is `Loaded` for the value on top, and `Target` the
301306 register a new one is computed in. Before a call every value in a
302307 register is spilled (`SpillBelow`), since the call may change them, and
303-so are the values under `and`'s and `or`'s left operand, which both
304-ways to its label must find in the same place. `pushed` counts what
308+so are the values under a comparison that jumps out of an expression
309+(`JumpOut`), which both ways to its label must find in the same place. `pushed` counts what
305310 is on the machine's stack, which a call must align: the return
306311 address, in a deferred statement. `Op` takes a
307312 constant on the right as it is, and a power of two on the right of
@@ -329,9 +334,11 @@
329334 own `gen.pas`: `Rt.fail` stops for a nil pointer, a division by zero
330335 and a stack overflow as the signals would.
331336
332-Calls: the arguments are in frame slots by the time `Call` runs, one
333-each, computed left to right; only then are they loaded into the
334-registers System V wants, and the stack aligned for the call. A record
337+Calls: the arguments wait for `Call`, computed left to right: a
338+constant or a noted address as itself, anything else in a frame slot
339+(`PopArg`), so that computing a later one can't disturb it; only then
340+are they loaded into the registers System V wants (`LoadArg`), and the
341+stack aligned for the call. A record
335342 passed by value goes as the address of a copy; one returned comes back
336343 through a hidden pointer in `rdi`, as C's structs do, and so do several
337344 results (`ResultTo`, `CopyResult`).
@@ -353,6 +360,10 @@
353360 - `mVar`: a variable, at `base`, `chunk` and `off`, which `AdrOf`
354361 makes a `TAdr` for gen;
355362 - `mStack`: a value on gen's stack;
363+- `mCond`: a condition, as Wirth's compilers keep one: two integers on
364+ gen's stack, compared by `rel` once something wants the result, and
365+ the jumps of `and` and `or` that land where it is false (`fj`) or
366+ true (`tj`); `CondJump` makes it a jump, `Value` a `BOOL`;
356367 - `mProc`, `mType`, `mStr`, and a few more the parser needs.
357368
358369 An item also carries `pos`, the stretch of source it came from, which
@@ -369,8 +380,10 @@
369380
370381 Expressions: `Op1` is called when the parser has seen an operator and
371382 its left operand, `Op2` when it has the right one. `Op1` pushes the
372-left operand, unless it is a constant (or, for `and` and `or`, has gen
373-jump past the right one). `Op2` checks the types, folds constants
383+left operand, unless it is a constant; for `and` and `or` it makes the
384+left one a condition (`MakeCond`) and jumps past the right one, which
385+`Op2` joins to it: `(a < b) and (c < d)` in an `if` is two compares
386+and two jumps, as `not` of a condition is the other comparison. `Op2` checks the types, folds constants
374387 (`FoldInt`, `FoldReal`), and otherwise pushes the right operand and has
375388 gen do the operation; a constant on the left goes on after the right,
376389 and the two `Swap`. A set's operations are operations on its bits

src/gen.pas modified +126 -30

@@ -11,12 +11,15 @@
1111
1212 The stack is kept in registers, as in Wirth's compilers: the value at
1313 depth d in r8 to r11, register d mod 4, a deeper one's register taken
14- by spilling the shallower value it held to the frame. A constant is only noted until something
14+ by spilling the shallower value it held to the frame. A constant, or
15+ an address in the frame or of a chunk, is only noted until something
1516 needs it in a register, so that it can be an instruction's operand.
1617
1718 Calls use the System V convention. Arguments are computed left to
1819 right into frame slots, then loaded into registers just before the
19- call, so that computing one argument can't disturb another. A record,
20+ call, so that computing one argument can't disturb another; a
21+ constant or an address, which nothing can disturb, goes straight to
22+ its register. A record,
2023 array, slice or variant passed by value goes as the address of a copy
2124 the caller makes; one returned goes through a hidden pointer, as C's
2225 structs do, and so do several results.
@@ -60,12 +63,18 @@
6063 off: int64; { added to the address }
6164 end;
6265
66+ { How an argument waits for its call: in a frame slot, or noted, as a
67+ constant or as the address of the frame or a chunk plus an offset }
68+ TArgHow = (argSlot, argConst, argAdr);
69+
6370 TCall = record
6471 sig: PType;
6572 param: PObj; { the parameter the next argument is for }
6673 obj: PObj; { the procedure called, if it has a name }
6774 n: longint; { the arguments }
68- slots: array[0..63] of int64; { each one's frame slot }
75+ slots: array[0..63] of int64; { each one's frame slot, constant or offset }
76+ how: array[0..63] of TArgHow;
77+ adrChunk: array[0..63] of longint; { argAdr: the chunk, or -1 for the frame }
6978 isF: array[0..63] of boolean; { ... goes in an xmm register }
7079 target: int64; { the frame slot of a procedure value, if chunk < 0 }
7180 chunk: longint; { else the procedure's chunk }
@@ -114,12 +123,13 @@
114123
115124 procedure Jump(var L: longint);
116125 procedure JumpIf(var L: longint; when: boolean);
117-procedure JumpKeep(var L: longint; when: boolean);
118-procedure FixKeep(L: longint);
119126 procedure JumpCmp(op: TSym; signed: boolean; var L: longint);
127+procedure JumpOut(op: TSym; signed: boolean; var L: longint);
128+procedure CondValue(notOp: TSym; signed: boolean; fj, tj: longint);
120129 procedure JumpBack(top: longint);
121130 procedure Fix(L: longint);
122131 procedure FixTo(L, top: longint);
132+function JoinJumps(L1, L2: longint): longint;
123133
124134 procedure CheckIndex(n: int64; const p: TPos);
125135 procedure CheckEnum(n: int64; name: longint; const p: TPos);
@@ -128,6 +138,7 @@
128138 procedure Slice(const a: TAdr; isArray: boolean; n, size, tmp: int64; checked: boolean; const p: TPos);
129139 procedure SlicePtr(size, tmp: int64; checked: boolean; const p: TPos);
130140
141+procedure PopArg(var c: TCall);
131142 procedure Call(var c: TCall);
132143
133144 function AllocTemp(size, align: int64): int64;
@@ -154,12 +165,15 @@
154165 type
155166 { where a value on the stack is }
156167 TLoc = (lConst, { not loaded: val is the value }
168+ lAdr, { not loaded: the address of chunk, or of the frame
169+ if chunk is -1, plus val }
157170 lReg, { in its register }
158171 lFrame); { spilled: in the frame slot val }
159172
160173 TEntry = record
161174 loc: TLoc;
162175 val: int64;
176+ chunk: longint;
163177 k: TKind;
164178 end;
165179
@@ -235,6 +249,13 @@
235249 Claim := Regs[r];
236250 end;
237251
252+{ The memory at the noted address i, plus off }
253+function AdrMem(i: longint; off: int64): TMem;
254+begin
255+ if stack[i].chunk < 0 then AdrMem := Mem(RBP, stack[i].val + off)
256+ else AdrMem := MemRip(stack[i].chunk, stack[i].val + off);
257+end;
258+
238259 { The value i, in its register }
239260 function Loaded(i: longint): longint;
240261 var r: longint;
@@ -242,6 +263,7 @@
242263 if stack[i].loc <> lReg then begin
243264 r := Claim(i);
244265 if stack[i].loc = lConst then MovRI(r, stack[i].val)
266+ else if stack[i].loc = lAdr then Lea(r, AdrMem(i, 0))
245267 else Load(r, Mem(RBP, stack[i].val), 8, false);
246268 stack[i].loc := lReg;
247269 end;
@@ -260,6 +282,7 @@
260282 stack[depth].k := k;
261283 stack[depth].loc := loc;
262284 stack[depth].val := v;
285+ stack[depth].chunk := -1;
263286 inc(depth);
264287 end;
265288
@@ -301,6 +324,11 @@
301324 NewEntry(k, lConst, v);
302325 end;
303326
327+function Fits32(v: int64): boolean;
328+begin
329+ Fits32 := (v >= low(longint)) and (v <= high(longint));
330+end;
331+
304332 { The memory a names. An address on the stack is popped, and is in its
305333 register still; one in a slot is loaded into r. }
306334 function Place(const a: TAdr; r: longint): TMem;
@@ -309,7 +337,15 @@
309337 case a.base of
310338 bFrame: Place := Mem(RBP, a.off);
311339 bGlobal: Place := MemRip(a.chunk, a.off);
312- bStack: begin ra := Top; Drop; Place := Mem(ra, a.off) end;
340+ bStack:
341+ if stack[depth - 1].loc = lAdr then begin
342+ Place := AdrMem(depth - 1, a.off);
343+ Drop;
344+ end else begin
345+ ra := Top;
346+ Drop;
347+ Place := Mem(ra, a.off)
348+ end;
313349 else
314350 Load(r, Mem(RBP, a.chunk), 8, false);
315351 Place := Mem(r, a.off);
@@ -320,6 +356,11 @@
320356 var m: TMem; r: longint;
321357 begin
322358 if (a.base = bStack) and (a.off = 0) then exit;
359+ if a.base in [bFrame, bGlobal] then begin
360+ NewEntry(kWord, lAdr, a.off);
361+ if a.base = bGlobal then stack[depth - 1].chunk := a.chunk;
362+ exit;
363+ end;
323364 if a.base = bStack then begin m := Place(a, -1); r := Target end
324365 else begin r := Target; m := Place(a, r) end;
325366 Lea(r, m);
@@ -349,6 +390,11 @@
349390 procedure PopVar(const a: TAdr; size: longint);
350391 var r: longint; v: int64;
351392 begin
393+ if TopConst(v) and Fits32(v) then begin
394+ Drop;
395+ StoreI(Place(a, RCX), v, size);
396+ exit;
397+ end;
352398 if TopConst(v) then begin r := RAX; MovRI(RAX, v) end
353399 else r := Top;
354400 Drop;
@@ -440,11 +486,6 @@
440486 Log2 := n;
441487 end;
442488
443-function Fits32(v: int64): boolean;
444-begin
445- Fits32 := (v >= low(longint)) and (v <= high(longint));
446-end;
447-
448489 { r compared with v, through rdx if v needs more than 32 bits }
449490 procedure CmpI(r: longint; v: int64);
450491 begin
@@ -728,8 +769,15 @@
728769 { Pops a step and an integer variable's address, and adds the step to
729770 it, or takes it away. }
730771 procedure IncDec(size: longint; signed, dec: boolean);
731-var r, y: longint;
772+var r, y, op: longint; v: int64; a: TAdr;
732773 begin
774+ if TopConst(v) and Fits32(v) then begin
775+ Drop;
776+ a.base := bStack; a.off := 0;
777+ if dec then op := aluSub else op := aluAdd;
778+ AluMI(op, Place(a, RCX), v, size);
779+ exit;
780+ end;
733781 r := Operands(y);
734782 Drop;
735783 Load(RAX, Mem(r, 0), size, signed);
@@ -779,6 +827,7 @@
779827 for i := 0 to n - 1 do
780828 with stack[depth - n + i] do
781829 if loc = lConst then MovRI(SysRegs[i], val)
830+ else if loc = lAdr then Lea(SysRegs[i], AdrMem(depth - n + i, 0))
782831 else Load(SysRegs[i], Mem(RBP, val), 8, false);
783832 for i := 1 to n do Drop;
784833 x64.Syscall;
@@ -808,22 +857,6 @@
808857 if when then Jcc(ccNE, L) else Jcc(ccE, L);
809858 end;
810859
811-{ For and and or: jumps if the BOOL on top is when, keeping it, in its
812- register, for where the jump goes; drops it if not. The values under
813- it are spilled first, so that both ways find them in the same place. }
814-procedure JumpKeep(var L: longint; when: boolean);
815-begin
816- SpillBelow(depth - 1);
817- JumpIf(L, when);
818-end;
819-
820-{ Where JumpKeep went: the BOOL on top is there, as it was there. }
821-procedure FixKeep(L: longint);
822-begin
823- Top;
824- FixLink(L);
825-end;
826-
827860 { Pops two integers, and jumps if the left op the right }
828861 procedure JumpCmp(op: TSym; signed: boolean; var L: longint);
829862 const
@@ -835,8 +868,34 @@
835868 else begin r := Operands(y); Alu(aluCmp, r, y) end;
836869 Drop;
837870 if signed then Jcc(CcSigned[op], L) else Jcc(CcUnsigned[op], L);
871+end;
872+
873+{ JumpCmp out of an expression, past code that may spill: the values
874+ under the two compared are spilled first, so that they are where the
875+ code after the landing place expects them, whichever way it came. }
876+procedure JumpOut(op: TSym; signed: boolean; var L: longint);
877+begin
878+ SpillBelow(depth - 2);
879+ JumpCmp(op, signed, L);
838880 end;
839881
882+{ The comparison of the two values on top, unless notOp holds, as a
883+ BOOL; jumps on its false path (fj) and its true one (tj) land as well }
884+procedure CondValue(notOp: TSym; signed: boolean; fj, tj: longint);
885+var r, e: longint;
886+begin
887+ JumpOut(notOp, signed, fj);
888+ FixLink(tj);
889+ r := Target;
890+ MovRI(r, 1);
891+ e := NoLabel;
892+ Jmp(e);
893+ FixLink(fj);
894+ MovRI(r, 0);
895+ FixLink(e);
896+ Computed(kWord);
897+end;
898+
840899 procedure JumpBack(top: longint);
841900 begin
842901 JmpBack(top);
@@ -847,6 +906,11 @@
847906 FixLink(L);
848907 end;
849908
909+function JoinJumps(L1, L2: longint): longint;
910+begin
911+ JoinJumps := JoinLinks(L1, L2);
912+end;
913+
850914 procedure FixTo(L, top: longint);
851915 begin
852916 FixLinkTo(L, top);
@@ -996,6 +1060,38 @@
9961060 { The call c, its arguments already in their frame slots: they go to
9971061 registers or the stack, the procedure is called, and its result, if
9981062 any, is pushed on the value stack. }
1063+{ The value on top is argument c.n of c, which waits for the call: a
1064+ constant or an address is noted, a real or anything else goes to a
1065+ frame slot. }
1066+procedure PopArg(var c: TCall);
1067+var i: longint;
1068+begin
1069+ i := depth - 1;
1070+ c.how[c.n] := argSlot;
1071+ if not c.isF[c.n] and (stack[i].loc = lConst) then c.how[c.n] := argConst
1072+ else if stack[i].loc = lAdr then c.how[c.n] := argAdr;
1073+ if c.how[c.n] = argSlot then begin
1074+ c.slots[c.n] := AllocTemp(8, 8);
1075+ Store(Mem(RBP, c.slots[c.n]), Top, 8);
1076+ end else begin
1077+ c.slots[c.n] := stack[i].val;
1078+ c.adrChunk[c.n] := stack[i].chunk;
1079+ end;
1080+ Drop;
1081+end;
1082+
1083+{ Argument i of c into register r }
1084+procedure LoadArg(const c: TCall; i, r: longint);
1085+begin
1086+ case c.how[i] of
1087+ argConst: MovRI(r, c.slots[i]);
1088+ argAdr:
1089+ if c.adrChunk[i] < 0 then Lea(r, Mem(RBP, c.slots[i]))
1090+ else Lea(r, MemRip(c.adrChunk[i], c.slots[i]));
1091+ else Load(r, Mem(RBP, c.slots[i]), 8, false);
1092+ end;
1093+end;
1094+
9991095 procedure Call(var c: TCall);
10001096 var
10011097 res: PType; i, ni, nf, k, pad, r: longint;
@@ -1023,7 +1119,7 @@
10231119 if pad <> 0 then AluI(aluSub, RSP, 8);
10241120 for i := c.n - 1 downto 0 do
10251121 if onStack[i] then begin
1026- Load(RAX, Mem(RBP, c.slots[i]), 8, false);
1122+ LoadArg(c, i, RAX);
10271123 Push(RAX);
10281124 end;
10291125 ni := 0; nf := 0;
@@ -1031,7 +1127,7 @@
10311127 for i := 0 to c.n - 1 do
10321128 if not onStack[i] then
10331129 if c.isF[i] then begin MovsdXM(nf, Mem(RBP, c.slots[i])); inc(nf) end
1034- else begin Load(IntRegs[ni], Mem(RBP, c.slots[i]), 8, false); inc(ni) end;
1130+ else begin LoadArg(c, i, IntRegs[ni]); inc(ni) end;
10351131 { a procedure taking ... is told in al how many xmm registers it got }
10361132 if c.sig^.variadic then MovRI(RAX, nf);
10371133 if c.ext then CallM(MemRip(c.chunk, 0))

src/item.pas modified +78 -20

@@ -20,11 +20,17 @@
2020 uses scan, diag, sym, chunk, gen;
2121
2222 type
23- TMode = (mConst, mVar, mStack, mProc, mType, mStr, mBuiltin, mCase, mNone);
23+ TMode = (mConst, mVar, mStack, mProc, mType, mStr, mBuiltin, mCase, mNone, mCond);
2424
2525 TItem = record
2626 mode: TMode;
2727 typ: PType;
28+ rel: TSym; { mCond: the comparison of the two integers on
29+ the stack, not yet made, as Wirth's compilers
30+ keep a condition }
31+ relSigned: boolean;
32+ fj, tj: longint; { mCond: the jumps taken where it is false, and
33+ where it is true, to land past it }
2834 val: int64; { mConst: the value, an F64's bits; mStr: its length }
2935 base: TBase; { mVar: what the address is relative to }
3036 chunk: longint; { mVar with bGlobal, mStr: the chunk; bSlot: the slot }
@@ -110,6 +116,10 @@
110116
111117 implementation
112118
119+const
120+ { the comparison that holds when op doesn't, for integers }
121+ Negated: array[sEql..sGeq] of TSym = (sNeq, sEql, sGeq, sGtr, sLeq, sLss);
122+
113123 var
114124 result: PType; { the result of the procedure being compiled, or nil }
115125
@@ -313,6 +323,12 @@
313323 procedure Value(var x: TItem);
314324 var f: single;
315325 begin
326+ if x.mode = mCond then begin
327+ if (x.fj = NoLabel) and (x.tj = NoLabel) then Compare(x.rel, kWord, x.relSigned)
328+ else CondValue(Negated[x.rel], x.relSigned, x.fj, x.tj);
329+ x.mode := mStack;
330+ exit;
331+ end;
316332 if x.typ^.form = fReal then UsesReals(x.pos);
317333 NilTest(x);
318334 case x.mode of
@@ -350,7 +366,9 @@
350366
351367 { x isn't wanted: what it has on the stack is dropped }
352368 procedure Discard(const x: TItem);
369+var y: TItem;
353370 begin
371+ if x.mode = mCond then begin y := x; Value(y); Drop; exit end;
354372 if (x.mode = mStack) or ((x.mode = mVar) and (x.base = bStack)) then Drop;
355373 end;
356374
@@ -428,6 +446,7 @@
428446 procedure Coerce(var x: TItem; t: PType);
429447 var s: PType; tmp: int64;
430448 begin
449+ if x.mode = mCond then Value(x);
431450 s := x.typ;
432451 if x.mode = mStr then begin
433452 if (t^.form = fSlice) and (t^.base = tU8) then begin
@@ -625,10 +644,15 @@
625644 end;
626645
627646 procedure NotOp(var x: TItem);
647+var L: longint;
628648 begin
629649 if IsInt(x.typ) then MarkHelp(x.pos, '"not" needs a BOOL, found ' + What(x), 'the bits of an integer flip with ~');
630650 if x.typ^.form <> fBool then MarkAt(x.pos, '"not" needs a BOOL, found ' + What(x));
631651 if x.mode = mConst then x.val := 1 - x.val
652+ else if x.mode = mCond then begin
653+ x.rel := Negated[x.rel];
654+ L := x.fj; x.fj := x.tj; x.tj := L;
655+ end
632656 else begin Value(x); NotBool end;
633657 end;
634658
@@ -668,15 +692,34 @@
668692 end;
669693 end;
670694
695+{ x, a BOOL, as a condition: a value compared with 0 if it isn't one }
696+procedure MakeCond(var x: TItem);
697+begin
698+ if x.mode = mCond then exit;
699+ Value(x);
700+ PushConst(kWord, 0);
701+ x.mode := mCond;
702+ x.rel := sNeq;
703+ x.relSigned := false;
704+ x.fj := NoLabel;
705+ x.tj := NoLabel;
706+end;
707+
671708 procedure Op1(op: TSym; var x: TItem; var L: longint);
672-var tmp: TItem;
673709 begin
674710 L := NoLabel;
675711 if (op in [sAnd, sOr]) and (x.typ^.form = fBool) then begin
676- tmp := x;
677- Value(tmp);
678- if x.mode <> mConst then x := tmp;
679- JumpKeep(L, op = sOr);
712+ if x.mode = mConst then exit; { folded by Op2 }
713+ MakeCond(x);
714+ if op = sAnd then begin
715+ JumpOut(Negated[x.rel], x.relSigned, x.fj);
716+ Fix(x.tj);
717+ x.tj := NoLabel;
718+ end else begin
719+ JumpOut(x.rel, x.relSigned, x.tj);
720+ Fix(x.fj);
721+ x.fj := NoLabel;
722+ end;
680723 end else if (op in [sEql, sNeq]) and IsSeq(x.typ) then
681724 SeqSlice(x)
682725 else if (op = sPlus) and (x.mode = mStr) then
@@ -848,13 +891,18 @@
848891 if xt^.form <> fBool then WrongLogic(op, x);
849892 if yt^.form <> fBool then WrongLogic(op, y);
850893 if (x.mode = mConst) and (y.mode = mConst) then begin
851- Fix(L);
852894 if op = sAnd then x.val := x.val and y.val else x.val := x.val or y.val;
853- exit;
895+ end else if x.mode = mConst then begin
896+ { true and y, false or y: y; else x, y computed and dropped }
897+ if (x.val = 1) = (op = sAnd) then x := y
898+ else Discard(y);
899+ end else begin
900+ MakeCond(y);
901+ if op = sAnd then begin x.fj := JoinJumps(x.fj, y.fj); x.tj := y.tj end
902+ else begin x.tj := JoinJumps(x.tj, y.tj); x.fj := y.fj end;
903+ x.rel := y.rel;
904+ x.relSigned := y.relSigned;
854905 end;
855- Value(y);
856- FixKeep(L);
857- x.mode := mStack; x.typ := tBool;
858906 exit;
859907 end;
860908
@@ -964,8 +1012,15 @@
9641012 if op in Rel then Compare(op, KindOf(t), false) else gen.Op(op, KindOf(t), 8, false)
9651013 end else if t^.form = fSet then
9661014 SetOp(op)
967- else if op in Rel then
968- Compare(op, kWord, Signed(t))
1015+ else if op in Rel then begin
1016+ x.mode := mCond;
1017+ x.rel := op;
1018+ x.relSigned := Signed(t);
1019+ x.fj := NoLabel;
1020+ x.tj := NoLabel;
1021+ x.typ := tBool;
1022+ exit;
1023+ end
9691024 else if isPtr then begin
9701025 if t <> tInt then ScaleBy(scale);
9711026 gen.Op(op, kWord, 8, false);
@@ -1087,7 +1142,8 @@
10871142 else if IsF32(a.typ) then MarkAt(a.pos, 'an F32 goes to ... as F64(x)')
10881143 else if not IsScalar(a.typ) then MarkAt(a.pos, 'only a single value goes to ...');
10891144 c.isF[c.n] := a.typ^.form = fReal;
1090- c.slots[c.n] := ToSlot(a);
1145+ Value(a);
1146+ PopArg(c);
10911147 inc(c.n);
10921148 exit;
10931149 end;
@@ -1101,19 +1157,15 @@
11011157 if not Same(a.typ, p^.typ) then Mismatch(a, 'a var parameter needs exactly ' + TypeName(p^.typ) + ', found ' + What(a));
11021158 if a.vol then MarkAt(a.pos, 'can''t pass through a volatile pointer to a var parameter');
11031159 Address(a);
1104- s := AllocTemp(8, 8);
1105- PopVar(FrameAdr(s), 8);
11061160 end else if IsAggregate(p^.typ) then begin
11071161 Coerce(a, p^.typ);
11081162 if a.isVar or a.vol or (a.base <> bFrame) then CopyToTemp(a);
11091163 Address(a);
1110- s := AllocTemp(8, 8);
1111- PopVar(FrameAdr(s), 8);
11121164 end else begin
11131165 Coerce(a, p^.typ);
1114- s := ToSlot(a);
1166+ Value(a);
11151167 end;
1116- c.slots[c.n] := s;
1168+ PopArg(c);
11171169 inc(c.n);
11181170 c.param := p^.next;
11191171 end;
@@ -1241,6 +1293,12 @@
12411293 procedure CondJump(var x: TItem; var L: longint);
12421294 begin
12431295 if x.typ^.form <> fBool then MarkAt(x.pos, 'a condition is a BOOL, found ' + What(x));
1296+ if x.mode = mCond then begin
1297+ JumpCmp(Negated[x.rel], x.relSigned, L);
1298+ L := JoinJumps(L, x.fj);
1299+ Fix(x.tj);
1300+ exit;
1301+ end;
12441302 Value(x);
12451303 JumpIf(L, false);
12461304 end;

src/x64.pas modified +58 -3

@@ -60,6 +60,8 @@
6060 procedure Alu(op, dst, src: longint);
6161 procedure AluI(op, r: longint; v: longint);
6262 procedure AluM(op, r: longint; const m: TMem);
63+procedure AluMI(op: longint; m: TMem; v, size: longint);
64+procedure StoreI(m: TMem; v, size: longint);
6365 procedure Imul(dst, src: longint);
6466 procedure ImulI(r: longint; v: longint);
6567 procedure Shift(op, r: longint);
@@ -103,6 +105,7 @@
103105 procedure JccBack(cc, target: longint);
104106 procedure FixLink(L: longint);
105107 procedure FixLinkTo(L, target: longint);
108+function JoinLinks(L1, L2: longint): longint;
106109
107110 type
108111 TConstFn = function: int64;
@@ -195,9 +198,9 @@
195198 Put1(reg shl 3 or 5);
196199 { mod 00 with r/m 101 is rip + disp32. The displacement counts
197200 from the end of the instruction, and the fixup takes it to end
198- with these four bytes: no rip operand has an immediate after it,
199- since only the compiler's loads, stores, lea and call make one
200- (the assembler can't name a chunk). }
201+ with these four bytes: an instruction with an immediate after
202+ them, AluMI's or StoreI's, takes the immediate's size off disp
203+ first (the assembler can't name a chunk). }
201204 AddFixup(pc, m.chunk, m.disp);
202205 Put4(0);
203206 exit;
@@ -316,6 +319,44 @@
316319 OpR(0, true, $89, src, dst);
317320 end;
318321
322+{ The immediate of n bytes that ends an instruction }
323+procedure PutImm(v, n: longint);
324+begin
325+ if n = 4 then Put4(v)
326+ else begin
327+ Put1(v and $FF);
328+ if n = 2 then Put1((v shr 8) and $FF);
329+ end;
330+end;
331+
332+{ op [m], v, on size bytes; v fits in them, or in 32 bits for 8 }
333+procedure AluMI(op: longint; m: TMem; v, size: longint);
334+var n: longint;
335+begin
336+ if listing then Say(AluNames[op] + ' ' + MN(m, size) + ', ' + IntStr(v));
337+ if (size = 1) or (v >= -128) and (v <= 127) then n := 1
338+ else if size = 2 then n := 2
339+ else n := 4;
340+ if m.base = RIP then dec(m.disp, n);
341+ if size = 1 then OpM(0, false, $80, op, m)
342+ else if n = 1 then OpM(ord(size = 2) * $66, size = 8, $83, op, m)
343+ else OpM(ord(size = 2) * $66, size = 8, $81, op, m);
344+ PutImm(v, n);
345+end;
346+
347+{ mov [m], v, of size bytes; v fits in them, or in 32 bits for 8 }
348+procedure StoreI(m: TMem; v, size: longint);
349+var n: longint;
350+begin
351+ if listing then Say('mov ' + MN(m, size) + ', ' + IntStr(v));
352+ n := size;
353+ if n > 4 then n := 4;
354+ if m.base = RIP then dec(m.disp, n);
355+ if size = 1 then OpM(0, false, $C6, 0, m)
356+ else OpM(ord(size = 2) * $66, size = 8, $C7, 0, m);
357+ PutImm(v, n);
358+end;
359+
319360 procedure MovRI(r: longint; v: int64);
320361 begin
321362 if not listing then
@@ -646,6 +687,20 @@
646687 procedure FixLink(L: longint);
647688 begin
648689 FixLinkTo(L, pc);
690+end;
691+
692+{ The jumps of chains L1 and L2, as one chain: each jump's field holds
693+ the next one's place until it is fixed, the last NoLabel }
694+function JoinLinks(L1, L2: longint): longint;
695+var L: longint;
696+begin
697+ if L2 = NoLabel then exit(L1);
698+ if L1 <> NoLabel then begin
699+ L := L2;
700+ while Get4At(L) <> NoLabel do L := Get4At(L);
701+ Put4At(L, L1);
702+ end;
703+ JoinLinks := L2;
649704 end;
650705
651706

test/list/Listing.expect (history) modified +33 -38

@@ -31,43 +31,38 @@
3131 11 xor eax, eax
3232 13 mov [rbp - 8], rax
3333 20 for i := 1 to 3 do
34- 17 mov rax, 1
35- 22 mov [rbp - 8], rax
36- 26 mov rax, 3
37- 31 mov [rbp - 16], rax
38- 35 mov r8, [rbp - 8]
39- 39 mov r9, [rbp - 16]
40- 43 cmp r8, r9
41- 46 jg 173
34+ 17 mov qword [rbp - 8], 1
35+ 25 mov qword [rbp - 16], 3
36+ 33 mov r8, [rbp - 8]
37+ 37 mov r9, [rbp - 16]
38+ 41 cmp r8, r9
39+ 44 jg 160
4240 21 if i # 2 then total := add(total, twice(i)); end;
43- 52 mov r8, [rbp - 8]
44- 56 cmp r8, 2
45- 60 setne r8b
46- 64 movzx r8d, r8b
47- 68 test r8, r8
48- 71 je 135
49- 77 mov r8, [Listing.total]
50- 84 mov [rbp - 24], r8
51- 88 mov r8, [rbp - 8]
52- 92 mov [rbp - 32], r8
53- 96 mov rdi, [rbp - 32]
54- 100 call Listing.twice
55- 105 mov r8, rax
56- 108 mov [rbp - 40], r8
57- 112 mov rdi, [rbp - 24]
58- 116 mov rsi, [rbp - 40]
59- 120 call Listing.add
60- 125 mov r8, rax
61- 128 mov [Listing.total], r8
62- 135 mov r8, [rbp - 16]
63- 139 mov r9, [rbp - 8]
64- 143 sub r8, r9
65- 146 cmp r8, 1
66- 150 jb 173
67- 156 mov r8, [rbp - 8]
68- 160 add r8, 1
69- 164 mov [rbp - 8], r8
70- 168 jmp 35
41+ 50 mov r8, [rbp - 8]
42+ 54 cmp r8, 2
43+ 58 je 122
44+ 64 mov r8, [Listing.total]
45+ 71 mov [rbp - 24], r8
46+ 75 mov r8, [rbp - 8]
47+ 79 mov [rbp - 32], r8
48+ 83 mov rdi, [rbp - 32]
49+ 87 call Listing.twice
50+ 92 mov r8, rax
51+ 95 mov [rbp - 40], r8
52+ 99 mov rdi, [rbp - 24]
53+ 103 mov rsi, [rbp - 40]
54+ 107 call Listing.add
55+ 112 mov r8, rax
56+ 115 mov [Listing.total], r8
57+ 122 mov r8, [rbp - 16]
58+ 126 mov r9, [rbp - 8]
59+ 130 sub r8, r9
60+ 133 cmp r8, 1
61+ 137 jb 160
62+ 143 mov r8, [rbp - 8]
63+ 147 add r8, 1
64+ 151 mov [rbp - 8], r8
65+ 155 jmp 33
7166 23 end main;
72- 173 leave
73- 174 ret
67+ 160 leave
68+ 161 ret