From a2ea2c5ef486d6adae4cc99c84c922951072c486 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sat, 17 Oct 2026 09:24:06 +0000 Subject: [PATCH] v0.19.0 builds src/; the Pascal seed goes BOOT names the release that builds the compiler, v0.19.0, and its tarball's SHA-256; src/boot.sh fetches it into build/boot/ (curl, or gh's REST API for a private repository), checks the sum and puts its raz there with today's lib/ beside it. The fixpoint starts from it, and make prev-bench, which replaces seed-bench, fails if this compiler is a tenth slower than it. seed/ and the Pascal tests of the units below the parser (make tests) go; CI needs no fpc, only a token for boot.sh. --- diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 97dd57c..98dc9d5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,8 +24,12 @@ ref: ${{ inputs.tag || github.ref }} fetch-depth: 0 # git describe needs the tags # musl and musl-tools: test/libc over musl, and cabi with musl-gcc - - run: sudo apt-get update && sudo apt-get install -y fp-compiler musl musl-tools + - run: sudo apt-get update && sudo apt-get install -y musl musl-tools + # src/boot.sh fetches the release BOOT names, by gh where the + # repository is private - run: make check + env: + GH_TOKEN: ${{ github.token }} - run: make alpine - name: release if: env.TAG != '' diff --git a/BOOT b/BOOT new file mode 100644 index 0000000..427fa9d --- /dev/null +++ b/BOOT @@ -0,0 +1 @@ +v0.19.0 217448cb6521c76a28d71499d70a5dfdebc2dbcbc81d6d41ed9d9590005772ed diff --git a/Makefile b/Makefile index cad4c6d..6a20acd 100644 --- a/Makefile +++ b/Makefile @@ -1,19 +1,15 @@ # Builds the compiler, raz, from src/ into the repository's root; the -# library it needs is lib/, beside it. The seed, the Pascal compiler in -# seed/, builds it: fpc makes the seed in build/seed/ (with lib/ beside -# it, as every raz has), and the seed compiles src/. The one module -# the build makes, Version, holds what git says the version is. - -FPC = fpc -FPCFLAGS = -O2 -Mobjfpc -Sh- -vew -FUbuild +# library it needs is lib/, beside it. The previous release builds it: +# BOOT names that release and its tarball's SHA-256, and src/boot.sh +# puts its raz in build/boot/, with this lib/ beside it (as every raz +# has its library), so that src/ is built against today's library. The +# one module the build makes, Version, holds what git says the version is. -raz: build/seed/raz src/*.raz build/src/Version.raz - build/seed/raz -Werror -I src -I build/src -o raz src/Raz.raz +raz: build/boot/raz src/*.raz build/src/Version.raz + build/boot/raz -Werror -I src -I build/src -o raz src/Raz.raz -build/seed/raz: seed/*.pas build/version.inc | build - mkdir -p build/seed - $(FPC) $(FPCFLAGS) -Fibuild -FEbuild/seed -obuild/seed/raz seed/raz.pas - ln -sfn ../../lib build/seed/lib +build/boot/raz: BOOT src/boot.sh | build + src/boot.sh build/src/Version.raz: build/version.inc | build mkdir -p build/src @@ -27,16 +23,6 @@ FORCE: -units: seed/*.pas | build - for u in diag scan sym chunk x64 link elf; do $(FPC) $(FPCFLAGS) seed/$$u.pas || exit 1; done - -# tests of the parts below the parser, built from test/ -tests: units - $(FPC) $(FPCFLAGS) -Fuseed -obuild/scantest test/scantest.pas - $(FPC) $(FPCFLAGS) -Fuseed -obuild/enctest test/enctest.pas - $(FPC) $(FPCFLAGS) -Fuseed -obuild/handtest test/handtest.pas - build/handtest build/hand && build/hand; test $$? = 42 - build: mkdir -p build @@ -47,12 +33,13 @@ check: raz build/raz-lib.3 test/check.sh -# the scanner's and the compiler's speed against the seed's -seed-bench: raz | build +# the compiler's speed against the previous release's, BOOT's, on the +# same program: fails if this one is more than a tenth slower +prev-bench: raz | build src/bench.sh -# the seed builds src/, that builds src/, that builds it again: the -# last two must be the same file; check and bench then run on it +# the previous release builds src/, that builds src/, that builds it +# again: the last two must be the same file; check and bench then run on it fixpoint: raz | build src/fixpoint.sh @@ -185,4 +172,4 @@ site: raz pdf python3 site/build.py -.PHONY: units tests seed-bench fixpoint check gdb bench kernels stress alpine fmt loc man pdf dist site clean install uninstall +.PHONY: prev-bench fixpoint check gdb bench kernels stress alpine fmt loc man pdf dist site clean install uninstall diff --git a/seed/chunk.pas b/seed/chunk.pas deleted file mode 100644 index 91b6dff..0000000 --- a/seed/chunk.pas +++ /dev/null @@ -1,318 +0,0 @@ -{ chunk.pas: the compiled program, before it is linked. - - The code of a program is a set of chunks: one per procedure, module - variable and string. A chunk's bytes go in one of three sections: - text (code), rodata (strings and other constants), bss (variables, - which are all zero). A reference from code to another chunk (a call, - or an address) is a fixup, patched once the linker has placed every - chunk. Line notes say which place in the source the code from each - point on is for. - - Nothing here depends on the machine: text is bytes, written by the - encoder for the target (x64.pas). - - Depends on: scan, for errors. - Leaves out: the instructions; that is x64.pas. } - -unit chunk; - -{$mode objfpc}{$H-} - -interface - -uses scan, diag; - -type - TSection = (secText, secRodata, secBss); - - TChunk = record - sec: TSection; - start, size, align: longint; { in its section's buffer } - firstFix, numFix: longint; { its fixups: text's in fixups, rodata's in dataFixups } - module, name: longint; { for the symbol table; -1 if none } - adr: int64; { its address, set by the linker } - live: boolean; { reached from the entry point } - 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 - gdb, and for Rt to say where a failed check or a signal was } - TLine = record - at, chunk: longint; { the place in text, and its chunk } - path, line, col: longint; { the file's path, interned, the line and column } - end; - - { A variable of a procedure, for the trap report: Rt shows it, by - kind, from its place in the frame } - TVarNote = record - chunk, name: longint; - off: longint; { from the frame pointer } - kind: longint; { how Rt shows it: see link.pas } - end; - - TFixup = record - at: longint; { the 32-bit field, as an offset in text; in - dataFixups, the 64-bit one, from its chunk's start } - chunk: longint; { the chunk it refers to } - addend: longint; { added to the chunk's address } - end; - - PChunks = ^TChunkArray; - TChunkArray = array[0..MaxInt div SizeOf(TChunk) - 1] of TChunk; - PLines = ^TLineArray; - TLineArray = array[0..MaxInt div SizeOf(TLine) - 1] of TLine; - PFixups = ^TFixupArray; - TFixupArray = array[0..MaxInt div SizeOf(TFixup) - 1] of TFixup; - -var - code: PBytes; { text } - pc: longint; { its length } - rodata: PBytes; - rolen: longint; - chunks: PChunks; - numChunks: longint; - fixups: PFixups; - numFixups: longint; - { Addresses in read-only data, as in an array constant of strings: - each 8 bytes, the chunk's absolute address, since the executable - is loaded where the linker placed it } - dataFixups: PFixups; - numDataFixups: longint; - lines: PLines; - numLines: longint; - curFile: longint; { the file being compiled, for NoteLine } - curChunk: longint; { the chunk of code being written } - varNotes: ^TVarNote; - numVarNotes: longint; - -function NewChunk(sec: TSection; module, name: longint): longint; -procedure BeginChunk(c: longint); -procedure EndChunk(c: longint); -procedure SetData(c: longint; p: PBytes; n, align: longint); -procedure SetBss(c: longint; size, align: longint); -function ExternChunk(name: longint): longint; -procedure NoteLine(line, col: longint); -procedure AddFixup(at, chunk, addend: longint); -procedure AddDataFixup(c, at, chunk, addend: longint); -procedure NoteVar(chunk, name, off, kind: longint); -function ChunkName(c: longint): shortstring; - -procedure Put1(b: longint); -procedure Put4(v: longint); -procedure Put8(v: int64); -procedure Put4At(at, v: longint); -function Get4At(at: longint): longint; -procedure TakeBack(n: longint); - -implementation - -var - codeCap, roCap, chunkCap, fixCap, lineCap: longint; - -procedure Room(n: longint); -begin - if pc + n > codeCap then begin - codeCap := codeCap * 2 + n; - code := ReAllocMem(code, codeCap); - end; -end; - -procedure Put1(b: longint); -begin - if pc + 16 > codeCap then Room(16); - code^[pc] := byte(b); - inc(pc); -end; - -procedure Put4(v: longint); -begin - if pc + 16 > codeCap then Room(16); - PLongint(@code^[pc])^ := v; - inc(pc, 4); -end; - -procedure Put4At(at, v: longint); -begin - PLongint(@code^[at])^ := v; -end; - -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); -begin - Put4(longint(v and $FFFFFFFF)); - Put4(longint(v shr 32)); -end; - -function NewChunk(sec: TSection; module, name: longint): longint; -begin - if numChunks = chunkCap then begin - chunkCap := chunkCap * 2; - chunks := ReAllocMem(chunks, chunkCap * SizeOf(TChunk)); - end; - FillChar(chunks^[numChunks], SizeOf(TChunk), 0); - chunks^[numChunks].sec := sec; - chunks^[numChunks].module := module; - chunks^[numChunks].name := name; - chunks^[numChunks].align := 1; - chunks^[numChunks].size := -1; { not yet defined } - NewChunk := numChunks; - inc(numChunks); -end; - -procedure BeginChunk(c: longint); -begin - { code is aligned to 32 bytes, the windows in which x86 fetches and - caches it, so that a procedure's loops sit in them the same way - whatever comes before: rat ran 5% slower at 16, by where its loops - fell. Padded with CC, x86's int3: a trap if it were ever run } - while pc and 31 <> 0 do Put1($CC); - curChunk := c; - chunks^[c].start := pc; - chunks^[c].align := 32; - chunks^[c].firstFix := numFixups; -end; - -procedure EndChunk(c: longint); -begin - chunks^[c].size := pc - chunks^[c].start; - chunks^[c].numFix := numFixups - chunks^[c].firstFix; -end; - -procedure SetData(c: longint; p: PBytes; n, align: longint); -begin - if rolen + n > roCap then begin - roCap := roCap * 2 + n; - rodata := ReAllocMem(rodata, roCap); - end; - Move(p^, rodata^[rolen], n); - chunks^[c].firstFix := numDataFixups; - chunks^[c].numFix := 0; - chunks^[c].start := rolen; - chunks^[c].size := n; - chunks^[c].align := align; - inc(rolen, n); -end; - -procedure SetBss(c: longint; size, align: longint); -begin - chunks^[c].size := size; - chunks^[c].align := align; -end; - -{ The code from here on is for line and column of the current file. A - place with no code of its own gives way to the next. } -procedure NoteLine(line, col: longint); -begin - if (numLines > 0) and (lines^[numLines - 1].at = pc) then dec(numLines); - if (numLines > 0) and (lines^[numLines - 1].chunk = curChunk) and (lines^[numLines - 1].line = line) - and (lines^[numLines - 1].col = col) and (lines^[numLines - 1].path = curFile) then exit; - if numLines = lineCap then begin - lineCap := lineCap * 2; - lines := ReAllocMem(lines, lineCap * SizeOf(TLine)); - end; - lines^[numLines].at := pc; - lines^[numLines].chunk := curChunk; - lines^[numLines].path := curFile; - lines^[numLines].line := line; - lines^[numLines].col := col; - inc(numLines); -end; - -{ The quadword that holds the address of C's symbol name, filled in - when the program starts; one for each name. } -function ExternChunk(name: longint): longint; -var c: longint; -begin - for c := 0 to numChunks - 1 do - if chunks^[c].ext and (chunks^[c].name = name) then exit(c); - c := NewChunk(secBss, -1, name); - SetBss(c, 8, 8); - chunks^[c].ext := true; - ExternChunk := c; -end; - -procedure AddFixup(at, chunk, addend: longint); -begin - if numFixups = fixCap then begin - fixCap := fixCap * 2; - fixups := ReAllocMem(fixups, fixCap * SizeOf(TFixup)); - end; - fixups^[numFixups].at := at; - fixups^[numFixups].chunk := chunk; - fixups^[numFixups].addend := addend; - inc(numFixups); -end; - -{ The address of chunk, plus addend, at offset at of rodata chunk c, - whose data is set: its fixups follow one another. } -procedure AddDataFixup(c, at, chunk, addend: longint); -begin - if numDataFixups and 255 = 0 then - dataFixups := ReAllocMem(dataFixups, (numDataFixups + 256) * SizeOf(TFixup)); - dataFixups^[numDataFixups].at := at; - dataFixups^[numDataFixups].chunk := chunk; - dataFixups^[numDataFixups].addend := addend; - inc(numDataFixups); - inc(chunks^[c].numFix); -end; - -procedure NoteVar(chunk, name, off, kind: longint); -begin - if numVarNotes and 255 = 0 then varNotes := ReAllocMem(varNotes, (numVarNotes + 256) * SizeOf(TVarNote)); - varNotes[numVarNotes].chunk := chunk; - varNotes[numVarNotes].name := name; - varNotes[numVarNotes].off := off; - varNotes[numVarNotes].kind := kind; - inc(numVarNotes); -end; - -{ The name of chunk c: its module's and its own, or literal and its - number for a literal } -function ChunkName(c: longint): shortstring; -begin - with chunks^[c] do - if name < 0 then ChunkName := 'literal' + IntStr(c) - else if module < 0 then ChunkName := NameOf(name) - else ChunkName := NameOf(module) + '.' + NameOf(name); -end; - -initialization - codeCap := 1 shl 20; - code := GetMem(codeCap); - pc := 0; - roCap := 1 shl 16; - rodata := GetMem(roCap); - rolen := 0; - chunkCap := 1 shl 10; - chunks := GetMem(chunkCap * SizeOf(TChunk)); - numChunks := 0; - fixCap := 1 shl 12; - fixups := GetMem(fixCap * SizeOf(TFixup)); - numFixups := 0; - lineCap := 1 shl 12; - lines := GetMem(lineCap * SizeOf(TLine)); - numLines := 0; -end. diff --git a/seed/diag.pas b/seed/diag.pas deleted file mode 100644 index 9480509..0000000 --- a/seed/diag.pas +++ /dev/null @@ -1,316 +0,0 @@ -{ diag.pas: messages. - - The one place the compiler's messages are made. A message is an - error or a warning at a position, which it shows as the file, line - and column, then the line of source with the position underlined; - notes, each at a position of its own, and help, a line of advice, - may follow it. Colour is used when standard error is a terminal and - NO_COLOR isn't set. diag keeps every source file it is given, so - that a note can show a line of a module compiled earlier. - - Depends on: BaseUnix and termio, to write and to ask about the - terminal. - Leaves out: wording. The callers say what is wrong; a message is at - most 255 characters, which every message so far keeps well within. } - -unit diag; - -{$mode objfpc}{$H-} - -interface - -type - { A stretch of a source file: bytes a up to but not including b. - a = b marks the place between two characters. } - TPos = record - f, a, b: longint; - end; - -const - MaxErrors = 20; - -var - errors, warnings: longint; - werror: boolean; { -Werror: a warning counts as an error } - { The construct being read uses a name already reported as not - declared: its errors follow from that one, and aren't shown. } - quiet: boolean; - -function AddFile(const path: shortstring; buf: PChar; len: longint): longint; -function ShownPath(const path: shortstring): shortstring; -function PathOf(f: longint): shortstring; -function LineOf(const p: TPos): longint; -function Join(const p, q: TPos): TPos; -function Source(const p: TPos): shortstring; -function LineText(const path: shortstring; line: longint): shortstring; -procedure Error(const p: TPos; const msg: shortstring); -procedure Warning(const p: TPos; const msg: shortstring); -procedure Note(const p: TPos; const msg: shortstring); -function IntStr(n: int64): shortstring; -procedure Help(const msg: shortstring); -procedure Fatal(const msg: shortstring); -procedure Finish; - -implementation - -uses BaseUnix, termio; - -type - TFile = record - path: shortstring; - buf: PChar; - len: longint; - end; - -var - files: ^TFile; { numFiles of them, in room for cap } - numFiles, cap: longint; - colour, colourKnown, cwdKnown: boolean; - cwd: shortstring; { the working directory and a /, or '' if unknown } - lastError: TPos; { where the last error was } - shown: boolean; { whether it was shown: its notes and help are only then } - -{ Paths are shown from the working directory where they are under it, - so messages read the same wherever the compiler or its library is. } -function ShownPath(const path: shortstring): shortstring; -var d: array[0..255] of char; -begin - if not cwdKnown then begin - if FpGetcwd(@d[0], SizeOf(d)) <> nil then cwd := StrPas(@d[0]) + '/'; - cwdKnown := true; - end; - if (cwd <> '') and (copy(path, 1, length(cwd)) = cwd) then ShownPath := copy(path, length(cwd) + 1, 255) - else ShownPath := path; -end; - -function AddFile(const path: shortstring; buf: PChar; len: longint): longint; -begin - if numFiles = cap then begin - cap := 2 * cap + 8; - ReallocMem(files, cap * SizeOf(TFile)); - end; - files[numFiles].path := ShownPath(path); - files[numFiles].buf := buf; - files[numFiles].len := len; - AddFile := numFiles; - inc(numFiles); -end; - -function PathOf(f: longint): shortstring; -begin - PathOf := files[f].path; -end; - -{ Writing } - -const - Bold = #27'[1m'; Red = #27'[1;31m'; Yellow = #27'[1;33m'; - Cyan = #27'[1;36m'; Green = #27'[1;32m'; Blue = #27'[1;34m'; - Plain = #27'[0m'; - -{ Whether NO_COLOR is set, to anything } -function NoColour: boolean; -var e: PPChar; -begin - e := envp; - while (e^ <> nil) and (CompareByte(e^^, PChar('NO_COLOR=')^, 9) <> 0) do inc(e); - NoColour := e^ <> nil; -end; - -{ s in colour c, when colour is on } -function Paint(const c, s: shortstring): shortstring; -begin - if not colourKnown then begin - colour := (IsATTY(2) = 1) and not NoColour; - colourKnown := true; - end; - if colour then Paint := c + s + Plain else Paint := s; -end; - -function IntStr(n: int64): shortstring; -var s: shortstring; -begin - Str(n, s); - IntStr := s; -end; - -{ Positions } - -{ The line of p, and the byte where it starts. Lines are counted from - the start of the file, which is slow only next to compiling it. } -procedure Locate(const p: TPos; out line, start: longint); -var i: longint; buf: PChar; -begin - buf := files[p.f].buf; - line := 1; start := 0; - for i := 0 to p.a - 1 do - if buf[i] = #10 then begin inc(line); start := i + 1 end; -end; - -function LineOf(const p: TPos): longint; -var line, start: longint; -begin - Locate(p, line, start); - LineOf := line; -end; - -{ Characters from byte i to byte j of buf: every byte but a UTF-8 - continuation byte. } -function Chars(buf: PChar; i, j: longint): longint; -var n: longint; -begin - n := 0; - for i := i to j - 1 do - if (byte(buf[i]) and $C0) <> $80 then inc(n); - Chars := n; -end; - -{ "file:line:col: kind: msg", then the line with p underlined. A tab - before p is copied into the underline, so that the two line up - whatever the terminal makes of tabs. } -{ A long line is shown cut to this many bytes around the place, its - cut ends marked ... } -const ShownBytes = 100; - -procedure Show(const p: TPos; const kind, kindColour, msg: shortstring); -var line, start, stop, lo, hi, i, n: longint; buf: PChar; num, gutter: shortstring; -begin - if p.f >= numFiles then begin - { about no place in a file, as for Rt, which the compiler imports - before it reads one } - writeln(StdErr, Paint(Bold, 'raz:'), ' ', Paint(kindColour, kind + ':'), ' ', Paint(Bold, msg)); - exit; - end; - Locate(p, line, start); - buf := files[p.f].buf; - writeln(StdErr, Paint(Bold, files[p.f].path + ':' + IntStr(line) + ':' - + IntStr(Chars(buf, start, p.a) + 1) + ':'), ' ', Paint(kindColour, kind + ':'), - ' ', Paint(Bold, msg)); - stop := start; - while (stop < files[p.f].len) and (buf[stop] <> #10) do inc(stop); - num := IntStr(line); - while length(num) < 5 do num := ' ' + num; - gutter := Paint(Blue, num + ' |'); - lo := start; hi := stop; - if hi - lo > ShownBytes then begin - if p.a - lo > ShownBytes div 2 then lo := p.a - ShownBytes div 2; - while (byte(buf[lo]) and $C0) = $80 do inc(lo); - if hi - lo > ShownBytes then hi := lo + ShownBytes; - while (hi < stop) and ((byte(buf[hi]) and $C0) = $80) do inc(hi); - end; - write(StdErr, gutter, ' '); - if lo > start then write(StdErr, '...'); - for i := lo to hi - 1 do write(StdErr, buf[i]); - if hi < stop then write(StdErr, '...'); - writeln(StdErr); - write(StdErr, Paint(Blue, ' |'), ' '); - if lo > start then write(StdErr, ' '); - for i := lo to p.a - 1 do - if buf[i] = #9 then write(StdErr, #9) - else if (byte(buf[i]) and $C0) <> $80 then write(StdErr, ' '); - if p.b < hi then n := Chars(buf, p.a, p.b) else n := Chars(buf, p.a, hi); - if n < 1 then n := 1; - writeln(StdErr, Paint(kindColour, StringOfChar('^', n))); -end; - -{ From the start of p to the end of q } -function Join(const p, q: TPos): TPos; -begin - Join := p; - Join.b := q.b; -end; - -{ The text at p, at most the 255 bytes a shortstring holds } -function Source(const p: TPos): shortstring; -var n: longint; -begin - n := p.b - p.a; - if n > 255 then n := 255; - SetLength(Source, n); - Move(files[p.f].buf[p.a], Source[1], n); -end; - -{ Messages } - -{ Line line of the file at path, as written } -function LineText(const path: shortstring; line: longint): shortstring; -var i, k, n: longint; s: shortstring; -begin - s := ''; - for i := 0 to numFiles - 1 do - if files[i].path = ShownPath(path) then begin - k := 0; n := 1; - while (n < line) and (k < files[i].len) do begin - if files[i].buf[k] = #10 then inc(n); - inc(k); - end; - while (k < files[i].len) and (files[i].buf[k] <> #10) and (length(s) < 255) do begin - s := s + files[i].buf[k]; - inc(k); - end; - break; - end; - LineText := s; -end; - -procedure Error(const p: TPos; const msg: shortstring); -begin - { a second error at one place follows from the first: when a symbol - ends a construct with an error, the one around it may stop there too } - shown := not quiet and not ((errors > 0) and (p.f = lastError.f) and (p.a = lastError.a)); - if not shown then exit; - lastError := p; - Show(p, 'error', Red, msg); - inc(errors); - if errors >= MaxErrors then begin - writeln(StdErr, 'raz: stopping after ', MaxErrors, ' errors'); - Halt(1); - end; -end; - -procedure Warning(const p: TPos; const msg: shortstring); -begin - if werror then Error(p, msg) - else begin - Show(p, 'warning', Yellow, msg); - shown := true; - inc(warnings); - end; -end; - -{ Notes and help follow an error or a warning, and are shown with it } -procedure Note(const p: TPos; const msg: shortstring); -begin - if shown then Show(p, 'note', Cyan, msg); -end; - -procedure Help(const msg: shortstring); -begin - if shown then writeln(StdErr, Paint(Green, 'help:'), ' ', msg); -end; - -{ An error with no place in the source, such as a file that can't be - read: it stops the compiler at once. } -procedure Fatal(const msg: shortstring); -begin - writeln(StdErr, 'raz: ', msg); - Halt(1); -end; - -function Count(n: longint; const what: shortstring): shortstring; -begin - if n = 1 then Count := '1 ' + what else Count := IntStr(n) + ' ' + what + 's'; -end; - -{ Says how many errors and warnings there were, and stops the compiler - if there were errors. } -procedure Finish; -begin - if (errors > 0) and (warnings > 0) then - writeln(StdErr, 'raz: ', Count(errors, 'error'), ', ', Count(warnings, 'warning')) - else if errors > 0 then writeln(StdErr, 'raz: ', Count(errors, 'error')) - else if warnings > 0 then writeln(StdErr, 'raz: ', Count(warnings, 'warning')); - if errors > 0 then Halt(1); -end; - -end. diff --git a/seed/elf.pas b/seed/elf.pas deleted file mode 100644 index 79b576f..0000000 --- a/seed/elf.pas +++ /dev/null @@ -1,373 +0,0 @@ -{ elf.pas: the executable file. - - Writes an ELF64 executable for x86-64 Linux: the ELF header, the - program headers, the linked text and rodata, and section headers - with a symbol table, so that objdump and gdb can name each procedure - and variable. For gdb's line numbers there is DWARF 4: a line table - (.debug_line), and the one compile unit that points to it - (.debug_info, .debug_abbrev). There are no types or variables. - - A program that uses C is linked dynamically, in the least way the - loader accepts: it names its loader and libraries, and each C symbol - it uses is a quadword the loader fills in with the symbol's address - (a GLOB_DAT relocation), which the code calls or reads through. - There is no PLT and no lazy binding, and the program exports nothing. - - Depends on: link for the images and addresses, chunk for the chunks, - scan for names and errors, BaseUnix to write the file. - Leaves out: position independent executables, symbol versions, the - rest of DWARF. } - -unit elf; - -{$mode objfpc}{$H-} - -interface - -uses scan, diag, chunk, link; - -var - needed: array[0..31] of longint; { the libraries to load, names interned } - numNeeded: longint; { none: a static program } - mainPath: shortstring; { the main module's file, for gdb } - stripped: boolean; { -s: no symbols and no line numbers; the sections are there, empty } - -procedure WriteElf(const path: shortstring; entry: longint); - -implementation - -uses BaseUnix; - -var - buf: PBytes; - len, cap: int64; - -procedure Room(n: int64); -begin - if len + n > cap then begin - cap := cap * 2 + n; - buf := ReAllocMem(buf, cap); - end; -end; - -procedure PutN(v: qword; n: longint); -var i: longint; -begin - Room(n); - for i := 0 to n - 1 do begin - buf^[len] := byte(v); - v := v shr 8; - inc(len); - end; -end; - -procedure PutBytes(p: PBytes; n: int64); -begin - Room(n); - if n > 0 then Move(p^, buf^[len], n); - len := len + n; -end; - -procedure PadTo(off: int64); -begin - while len < off do PutN(0, 1); -end; - -procedure Patch(at: int64; v: qword; n: longint); -var i: longint; -begin - for i := 0 to n - 1 do begin - buf^[at + i] := byte(v); - v := v shr 8; - end; -end; - -procedure Phdr(typ, flags: longint; off, adr, filesz, memsz, align: int64); -begin - PutN(typ, 4); - PutN(flags, 4); - PutN(off, 8); - PutN(adr, 8); - PutN(adr, 8); - PutN(filesz, 8); - PutN(memsz, 8); - PutN(align, 8); -end; - -const - { the section names, in .shstrtab; a section header names its own } - ShNames = #0'.text'#0'.rodata'#0'.bss'#0'.symtab'#0'.strtab'#0'.shstrtab'#0 + - '.dynamic'#0'.dynstr'#0'.dynsym'#0'.debug_line'#0'.debug_info'#0'.debug_abbrev'#0; - -{ A section header. Its name is given as a string and stored as its - offset in ShNames: the #0 before it, counted from 1, is that offset - counted from 0; the empty name, found nowhere, is 0. } -procedure Shdr(const name: shortstring; typ: longint; flags, adr, off, size: int64; lnk, info: longint; align, entsize: int64); -begin - PutN(Pos(#0 + name + #0, ShNames), 4); PutN(typ, 4); PutN(flags, 8); PutN(adr, 8); - PutN(off, 8); PutN(size, 8); PutN(lnk, 4); PutN(info, 4); - PutN(align, 8); PutN(entsize, 8); -end; - -procedure PutStr(const s: shortstring); -begin - PutBytes(@s[1], length(s)); - PutN(0, 1); -end; - -{ LEB128, unsigned } -procedure PutU(v: qword); -begin - while v >= $80 do begin - PutN(v and $7F or $80, 1); - v := v shr 7; - end; - PutN(v, 1); -end; - -{ The compile unit, which names the line table, and its abbreviation; - the table itself is in the places, in rodata (link.pas). Section - offsets go in off, sizes in size: line, info, abbrev. } -procedure PutDebug(var off, size: array of int64); -var cwd: array[0..255] of char; -begin - off[0] := chunks^[placesChunk].adr - roAdr + roOff + linesOff; - size[0] := linesSize; - off[1] := len; - PutN(0, 4); PutN(4, 2); PutN(0, 4); PutN(8, 1); { length, version, abbrev, address size } - PutU(1); - PutStr(mainPath); - if FpGetcwd(@cwd, SizeOf(cwd)) = nil then cwd[0] := #0; - PutStr(PChar(@cwd)); - PutStr('raz'); - PutN(0, 4); { the line table, at 0 } - PutN(Base + textOff, 8); PutN(textSize, 8); { the code, all of it } - Patch(off[1], len - off[1] - 4, 4); - size[1] := len - off[1]; - - off[2] := len; - PutU(1); PutU($11); PutN(0, 1); { 1: a compile unit, no children } - PutU($03); PutU($08); { name, a string } - PutU($1B); PutU($08); { comp_dir, a string } - PutU($25); PutU($08); { producer, a string } - PutU($10); PutU($17); { stmt_list, a section offset } - PutU($11); PutU($01); { low_pc, an address } - PutU($12); PutU($07); { high_pc, a length in 8 bytes } - PutN(0, 2); PutN(0, 1); - size[2] := len - off[2]; -end; - -const - Interp = '/lib64/ld-linux-x86-64.so.2'; - { program header types } - PtLoad = 1; PtDynamic = 2; PtInterp = 3; PtGnuStack = $6474E551; - -var - { in the room at the end of rodata: where each of the loader's - tables starts, from extraAdr } - symAt, relaAt, hashAt, strAt: int64; - nsym, strLen: longint; - -{ The sizes of the loader's tables: what LinkAll must leave room for. } -procedure SizeTables(var roExtra, dynSize: int64); -var c, i: longint; -begin - nsym := 1; - strLen := 1; - for i := 0 to numNeeded - 1 do strLen := strLen + length(NameOf(needed[i])) + 1; - for c := 0 to numChunks - 1 do - if chunks^[c].live and chunks^[c].ext then begin - inc(nsym); - strLen := strLen + length(NameOf(chunks^[c].name)) + 1; - end; - symAt := (length(Interp) + 1 + 7) div 8 * 8; - relaAt := symAt + nsym * 24; - hashAt := relaAt + (nsym - 1) * 24; - strAt := hashAt + 4 * (3 + nsym); - roExtra := strAt + strLen; - dynSize := (numNeeded + 10) * 16; -end; - -{ The loader's tables in the room at the end of rodata, which the - buffer already holds as zeros: the loader's name; the symbols, one - for each C symbol used; a GLOB_DAT relocation for each, at its - quadword; a hash table of one bucket; and their names. } -procedure PutTables; -var c, k, i, at, name: longint; -begin - len := extraAdr - roAdr + roOff; - PutStr(Interp); - PadTo(extraAdr - roAdr + roOff + symAt); - PutN(0, 24); - name := strLen; - for c := numChunks - 1 downto 0 do { names go last in the string table } - if chunks^[c].live and chunks^[c].ext then name := name - length(NameOf(chunks^[c].name)) - 1; - for c := 0 to numChunks - 1 do - if chunks^[c].live and chunks^[c].ext then begin - PutN(name, 4); PutN($10, 1); PutN(0, 1); PutN(0, 2); { global, undefined } - PutN(0, 8); PutN(0, 8); - name := name + length(NameOf(chunks^[c].name)) + 1; - end; - k := 1; - for c := 0 to numChunks - 1 do - if chunks^[c].live and chunks^[c].ext then begin - PutN(chunks^[c].adr, 8); - PutN(qword(k) shl 32 or 6, 8); { R_X86_64_GLOB_DAT } - PutN(0, 8); - inc(k); - end; - PutN(1, 4); PutN(nsym, 4); PutN(nsym - 1, 4); { the bucket chains every symbol } - PutN(0, 4); - for i := 1 to nsym - 1 do PutN(i - 1, 4); - PutN(0, 1); - for i := 0 to numNeeded - 1 do PutStr(NameOf(needed[i])); - for c := 0 to numChunks - 1 do - if chunks^[c].live and chunks^[c].ext then PutStr(NameOf(chunks^[c].name)); - len := roOff + roSize; - - { the dynamic table, at the start of the writable segment } - PadTo(bssOff); - at := 1; - for i := 0 to numNeeded - 1 do begin - PutN(1, 8); PutN(at, 8); { DT_NEEDED } - at := at + length(NameOf(needed[i])) + 1; - end; - PutN(4, 8); PutN(extraAdr + hashAt, 8); { DT_HASH } - PutN(5, 8); PutN(extraAdr + strAt, 8); { DT_STRTAB } - PutN(6, 8); PutN(extraAdr + symAt, 8); { DT_SYMTAB } - PutN(10, 8); PutN(strLen, 8); { DT_STRSZ } - PutN(11, 8); PutN(24, 8); { DT_SYMENT } - PutN(7, 8); PutN(extraAdr + relaAt, 8); { DT_RELA } - PutN(8, 8); PutN((nsym - 1) * 24, 8); { DT_RELASZ } - PutN(9, 8); PutN(24, 8); { DT_RELAENT } - PutN(21, 8); PutN(0, 8); { DT_DEBUG, for gdb } - PutN(0, 16); { DT_NULL } -end; - -procedure WriteElf(const path: shortstring; entry: longint); -var - nph, nsh, c, nsyms, fd: longint; - roExtra, dynSize, symOff, strOff, shstrOff, shOff, strsLen: int64; - dbgOff, dbgSize: array[0..2] of int64; - strs: PBytes; - s, p: shortstring; - sec: longint; - dynamic: boolean; -begin - cap := 1 shl 16; - buf := GetMem(cap); - len := 0; - dynamic := numNeeded > 0; - roExtra := 0; dynSize := 0; - if dynamic then SizeTables(roExtra, dynSize); - { room for the most program headers either kind of program has } - LinkAll(64 + 6 * 56, roExtra, dynSize); - if dynamic then nph := 6 - else begin - nph := 2; - if roSize > 0 then inc(nph); - if bssSize > 0 then inc(nph); - end; - - { ELF header } - PutN($464C457F, 4); { #127 'ELF' } - PutN(2, 1); PutN(1, 1); PutN(1, 1); PutN(0, 9); { 64-bit, little-endian, version 1 } - PutN(2, 2); { ET_EXEC } - PutN(62, 2); { EM_X86_64 } - PutN(1, 4); - PutN(chunks^[entry].adr, 8); - PutN(64, 8); { program headers follow } - PutN(0, 8); { section headers: patched below } - PutN(0, 4); - nsh := 10; - if dynamic then nsh := 13; - PutN(64, 2); PutN(56, 2); PutN(nph, 2); - PutN(64, 2); PutN(nsh, 2); PutN(6, 2); { .shstrtab is section 6 } - - { flags: 4 read, 5 read and run, 6 read and write } - if dynamic then Phdr(PtInterp, 4, extraAdr - roAdr + roOff, extraAdr, length(Interp) + 1, length(Interp) + 1, 1); - { the first segment maps the headers too, so text can follow them } - Phdr(PtLoad, 5, 0, Base, textOff + textSize, textOff + textSize, Page); - if roSize > 0 then Phdr(PtLoad, 4, roOff, roAdr, roSize, roSize, Page); - if dynamic then begin - Phdr(PtLoad, 6, bssOff, bssAdr, dynSize, bssSize, Page); - Phdr(PtDynamic, 6, bssOff, bssAdr, dynSize, dynSize, 8); - end else if bssSize > 0 then Phdr(PtLoad, 6, 0, bssAdr, 0, bssSize, Page); - Phdr(PtGnuStack, 6, 0, 0, 0, 0, 16); { a stack that can't run code } - - PadTo(textOff); - PutBytes(textImg, textSize); - PadTo(roOff); { even when empty, so that every section lies in the file } - PutBytes(roImg, roSize); - if dynamic then PutTables; - - { the symbol table: one local symbol for each named live chunk } - PadTo((len + 7) div 8 * 8); - symOff := len; - strs := GetMem(1 shl 16); - strsLen := 1; - strs^[0] := 0; - PutN(0, 24); - nsyms := 1; - for c := 0 to numChunks - 1 do - if not stripped and chunks^[c].live and (chunks^[c].name >= 0) and not chunks^[c].ext then begin - s := ChunkName(c); - if strsLen + length(s) + 1 > MemSize(strs) then strs := ReAllocMem(strs, strsLen * 2 + 256); - Move(s[1], strs^[strsLen], length(s)); - strs^[strsLen + length(s)] := 0; - case chunks^[c].sec of { the section's index in the headers below } - secText: sec := 1; - secRodata: sec := 2; - else sec := 3; - end; - PutN(strsLen, 4); - if sec = 1 then PutN(2, 1) else PutN(1, 1); { STT_FUNC, STT_OBJECT } - PutN(0, 1); - PutN(sec, 2); - PutN(chunks^[c].adr, 8); - PutN(chunks^[c].size, 8); - strsLen := strsLen + length(s) + 1; - inc(nsyms); - end; - strOff := len; - PutBytes(strs, strsLen); - shstrOff := len; - s := ShNames; - PutBytes(@s[1], length(s)); - if stripped or (placesChunk < 0) then begin - for c := 0 to 2 do begin dbgOff[c] := len; dbgSize[c] := 0 end; - end else PutDebug(dbgOff, dbgSize); - - PadTo((len + 7) div 8 * 8); - shOff := len; - Patch(40, shOff, 8); - { types: 1 PROGBITS, 2 SYMTAB, 3 STRTAB, 6 DYNAMIC, 8 NOBITS, 11 DYNSYM; - flags: 2 ALLOC, 3 WRITE+ALLOC, 6 ALLOC+EXECINSTR. A symbol table's - link is its string table's index: 5 .strtab, 8 .dynstr. The order - here is the index the code above relies on. } - Shdr('', 0, 0, 0, 0, 0, 0, 0, 0, 0); - Shdr('.text', 1, 6, Base + textOff, textOff, textSize, 0, 0, 16, 0); - Shdr('.rodata', 1, 2, roAdr, roOff, roSize, 0, 0, 16, 0); - Shdr('.bss', 8, 3, bssAdr + dynSize, roOff + roSize, bssSize - dynSize, 0, 0, 16, 0); - Shdr('.symtab', 2, 0, 0, symOff, nsyms * 24, 5, nsyms, 8, 24); - Shdr('.strtab', 3, 0, 0, strOff, strsLen, 0, 0, 1, 0); - Shdr('.shstrtab', 3, 0, 0, shstrOff, length(ShNames), 0, 0, 1, 0); - if dynamic then begin { the loader's tables, for readelf and objdump } - Shdr('.dynamic', 6, 3, bssAdr, bssOff, dynSize, 8, 0, 8, 16); - Shdr('.dynstr', 3, 2, extraAdr + strAt, extraAdr + strAt - roAdr + roOff, strLen, 0, 0, 1, 0); - Shdr('.dynsym', 11, 2, extraAdr + symAt, extraAdr + symAt - roAdr + roOff, nsym * 24, 8, 1, 8, 24); - end; - Shdr('.debug_line', 1, 0, 0, dbgOff[0], dbgSize[0], 0, 0, 1, 0); - Shdr('.debug_info', 1, 0, 0, dbgOff[1], dbgSize[1], 0, 0, 1, 0); - Shdr('.debug_abbrev', 1, 0, 0, dbgOff[2], dbgSize[2], 0, 0, 1, 0); - - p := path + #0; - fd := FpOpen(@p[1], O_WRONLY or O_CREAT or O_TRUNC, &755); - if fd < 0 then Fatal('can''t write ' + path); - if FpWrite(fd, buf^, len) <> len then Fatal('can''t write ' + path); - FpClose(fd); - FreeMem(strs); - FreeMem(buf); -end; - -end. diff --git a/seed/gen.pas b/seed/gen.pas deleted file mode 100644 index aeed68b..0000000 --- a/seed/gen.pas +++ /dev/null @@ -1,2322 +0,0 @@ -{ gen.pas: the code generator, for x86-64. - - item.pas and parse.pas drive a stack machine: they push constants, - addresses and the values of variables, operate on the values on top, - store them and jump on them. Every value has a kind: a word, which - is an integer as big as an address, a pointer, a BOOL, a set or a - narrower integer; a long, a 64-bit integer on a machine whose word is - smaller (never here); an F32; an F64. This unit makes the machine's - code for those calls, and nothing above it knows the machine: a port - is a new gen.pas, with an encoder of its own. - - The stack is kept in registers, as in Wirth's compilers (Niklaus - Wirth's Pascal and Oberon compilers): the value at depth d, depth 0 - being the bottom, is in r8 to r11, register d mod 4, or in xmm8 to - xmm11 if it is a real. A value that needs a register a lower one - holds spills that one: stores it in a frame slot, to free the - register. A constant, or an address in the - frame or of a chunk, is only noted until something needs it in a - register, so that it can be an instruction's operand. - - A slice is two words, a pointer and then a length. - - Calls use the System V convention, which x86-64 Linux has for C: - arguments in rdi, rsi, rdx, rcx, r8, r9 and xmm0 to xmm7, the rest on - the machine's stack; rbx, rbp and r12 to r15 are callee-saved, which - is to say a called procedure gives them back as it found them. The - arguments are computed left to right onto the stack of values, and - moved into their registers just before the call: a call in a later - argument spills the earlier ones, as any call spills the values under - it, so that it can't disturb them. A slice goes as its two words, as - System V passes a 16-byte struct of two integers; a record, array or - variant passed by value goes as the address of a copy the caller - makes. A slice, or two results that are single values, come back in - rax and rdx (InTwoRegs); any other record, or several results, comes - back in memory the caller provides, through a hidden pointer - (BehindPointer), where C would send a small struct back in registers. - - A procedure's frame holds its parameters, its variables, and the - temporaries of the statement running. The variables are zeroed on - entry. - - Depends on: scan and diag for errors, sym for types, chunk for code - and data, x64 for instructions. - Leaves out: what the program means, its types and their checks; that - is item.pas. } - -unit gen; - -{$mode objfpc}{$H-} - -interface - -uses scan, diag, sym, chunk, x64; - -const - NoLabel = -1; - WordSize = 8; { the size of an address, and of INT } - { What the machine catches by itself, which the code needn't test for - (report section 10): on x86-64 Linux, a division by zero, a stack - overflow (at the guard page under the stack), a call to nil, and - a load or store within NilPage bytes of address 0, which is never - mapped. } - NilPage = 4096; - -type - TKind = (kWord, kLong, kF32, kF64); - - { Where a variable is: its address is relative to the frame, to a - chunk, to an address on the stack, or to one held in a frame slot } - TBase = (bFrame, bGlobal, bStack, bSlot, bReg); - TAdr = record - base: TBase; - chunk: longint; { bGlobal: the chunk; bSlot: the frame slot; bReg: the register } - off: int64; { added to the address; for bReg, which word, 0 or 8 } - hi: longint; { bReg, a slice: the register of its length, the - second word; chunk is that of its pointer } - end; - - { The code made so far, to go back to for a second try at a body } - TCodeMark = record pc, fixups, lines, said, fails: longint; end; - - { For EntryPoint: the address of chunk, put in the variable whose - chunk is into before the program starts } - TLink = record chunk, into: longint; end; - - TCall = record - sig: PType; - param: PObj; { the parameter the next argument is for } - obj: PObj; { the procedure called, if it has a name } - n: longint; { the arguments } - isF: array[0..63] of boolean; { ... goes in an xmm register } - pair: array[0..63] of boolean; { ... is a slice's first word, the next its second } - target: int64; { the frame slot of a procedure value, if chunk < 0 } - chunk: longint; { else the procedure's chunk } - ext: boolean; { C's: called through the chunk holding its address } - ret: int64; { set by Call: the temporary a slice or a record 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 register variable); 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); - { the registers the trap report can show a variable in: VarRegs, then - rdi and rsi, where a procedure that calls nothing keeps the - parameters that arrive in them (KeptIn) } - ShownRegs: array[0..6] of longint = (RBX, R12, R13, R14, R15, RDI, RSI); - { the registers a procedure keeps its busiest reals in, xmm12 to - xmm15, numbered from XmmVar up so that they aren't taken for r12 to - r15 (RegAt). Each has a slot too, written as it is, where the trap - report finds it, and from which it is loaded again after a call, as - System V has no callee-saved xmm register (XHome). } - XmmVar = 16; - XVarRegs: array[0..3] of longint = (XmmVar + 12, XmmVar + 13, XmmVar + 14, XmmVar + 15); - { a procedure's registers of variables, as bits: bit i is VarRegs[i], - bit XBit + i XVarRegs[i] } - XBit = 5; - -var - rtFail, argcChunk, argvChunk: longint; - { the stubs that Check's code calls, one for each kind of failure, - made by EntryPoint for those used } - failStubs: array[0..5] of longint = (-1, -1, -1, -1, -1, -1); - lost: boolean; { a parameter kept where it arrived was wanted - for other work: the procedure is compiled again, - the parameter in memory } - inPlace: longint = -1; { the register of a variable that the statement - being compiled assigns, x := x + e, where the - value can be worked out in the variable's own - register, from its first push on (lInto) } - depth: longint; { the values on the stack } - pushed: longint; { quadwords pushed on the machine's stack } - codeChunk: longint = -1; { the procedure or body being compiled, or -1 } - -function KindOf(t: PType): TKind; - -procedure PushConst(k: TKind; v: int64); -procedure PushAdr(const a: TAdr); -procedure PushVar(const a: TAdr; size: longint; signed: boolean; k: TKind); -procedure PushProc(c: longint; ext: boolean); -procedure PopVar(const a: TAdr; size: longint); -procedure Drop; -procedure Swap; -procedure ResetStack(d, p: longint); - -procedure CopyBlock(size, off: int64); -procedure CopyTo(const a: TAdr; size: int64); -procedure ZeroVar(const a: TAdr; size: int64); - -procedure Op(op: TSym; k: TKind; size: longint; signed: boolean); -procedure Compare(op: TSym; k: TKind; signed: boolean); -procedure Neg(k: TKind; size: longint; signed: boolean); -procedure Complement(size: longint; signed: boolean); -procedure NotBool; -procedure Narrow(size: longint; signed: boolean); -procedure IntToReal(k: TKind; big: boolean); -procedure RealToInt(k: TKind); -procedure RealToReal(k: TKind); -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); -procedure Fence; - -procedure Jump(var L: longint); -procedure JumpIf(var L: longint; when: boolean); -procedure JumpCmp(op: TSym; signed: boolean; var L: longint); -procedure JumpOut(op: TSym; signed: boolean; var L: longint); -procedure CondValue(notOp: TSym; signed: boolean; fj, tj: longint); -procedure JumpBack(top: longint); -function JumpTable(slot, lo: int64; n, elseAt: longint; var endL: longint): longint; -procedure TableEntry(table, target: longint); -procedure AlignLoop; -procedure Fix(L: longint); -procedure FixTo(L, top: longint); -function JoinJumps(L1, L2: longint): longint; - -procedure CheckIndex(n: int64; const p: TPos); -procedure CheckEnum(n: int64; name: longint; const p: TPos); -procedure CheckNil(reach: int64; const p: TPos); -procedure IndexArray(const a: TAdr; size: int64); -procedure IndexSlice(const a: TAdr; size: int64; checked: boolean; const p: TPos); -procedure Slice(const a: TAdr; isArray: boolean; n, size, tmp: int64; checked: boolean; const p: TPos); -procedure SlicePtr(size, tmp: int64; checked: boolean; const p: TPos); -procedure CopySlice(dOff, sOff, size: int64; checked: boolean; const p: TPos); - -procedure Call(var c: TCall); - -function AllocTemp(size, align: int64): int64; -function AllocPerm(size, align: int64): int64; -function TempMark: int64; -procedure ReleaseTemps(m: int64); -procedure KeepTemps; - -procedure BeginProc(sig: PType; params: PObj); -procedure ResetLocals; -procedure KeepArrived(o: PObj); -function KeptIn(o: PObj): boolean; -procedure UseRegs(mask: longint); -procedure XHome(r: longint; slot: int64); -procedure MarkCode(var m: TCodeMark); -procedure Redo(const m: TCodeMark); -procedure Rewind(const m: TCodeMark); -procedure EnterBody(c, line: longint); -procedure ResultTo(off: int64; size: longint); -procedure CopyResult(off, size: int64); -procedure ReturnJump; -procedure TryAlign; -procedure TryReturn(slot: int64); -procedure EndProc(c: longint; open: boolean); -function DeferBegin(var L, saved: longint): longint; -procedure DeferEnd(L, saved: longint); -procedure RunDefer(at: longint); - -function EntryPoint(dynamic: boolean; first: PModule; main: PObj; cExit, exitProc: longint; const links: array of TLink; numLinks: longint): longint; -procedure CodeProc(c: longint; constExpr: TConstFn); - -implementation - -type - { where a value on the stack is } - TLoc = (lConst, { not loaded: val is the value } - lHeld, { not loaded: in register val, a register - variable's own (see VarRegs), read in place, which - nothing in an expression can change } - lAdr, { not loaded: the address of chunk, or of the frame - if chunk is -1, plus val } - lIdx, { not loaded: the address m, an element of an array - or of a slice in registers: the array's or the - pointer's register, or rbp, as the base, and the - index in a register variable's or the value's - own register (IndexSlice, IndexArray) } - lMem, { not loaded: the value of size bytes at m, in the - frame, a chunk, or at an address lAdr or lIdx - noted, read where it is used (PushVar) } - lInto, { in register val, a register variable's own, which - is what the value goes to (inPlace): so it is - changed in place } - lReg, { in its register } - lFrame); { spilled: in the frame slot val } - - TEntry = record - loc: TLoc; - val: int64; { lConst: the value; lHeld: the register; lAdr: the - offset; lFrame: the frame slot } - chunk: longint; { lAdr: the chunk, or -1 for the frame } - m: TMem; { lIdx, lMem } - size: longint; { lMem } - signed: boolean; { lMem } - k: TKind; - off: int64; { lHeld, lReg: a word, its register plus off, the - constant of x + 1 not yet added (Op), so that an - operand that uses it can take it as its - displacement: [r13 + r9 * 8 - 8] } - end; - -const - StubNames: array[0..5] of string[6] = ('check0', 'check1', 'check2', 'check3', 'check4', 'check5'); - { the registers of the stack: the value at depth d is in Regs[d mod - NumRegs]. rax, rdx and rcx, which division and shifts need, and rsi - and rdi, which copying needs, aren't among them. } - NumRegs = 4; - Regs: array[0..NumRegs - 1] of longint = (R8, R9, R10, R11); - XRegs: array[0..NumRegs - 1] of longint = (8, 9, 10, 11); { xmm8 to xmm11 } - IntRegs: array[0..5] of longint = (RDI, RSI, RDX, RCX, R8, R9); - -var - stack: array[0..255] of TEntry; - owner: array[0..NumRegs - 1] of longint; { the value in each register, or -1 } - frameTop, frameMax, permTop: int64; - frameFix: longint; { where the frame size is patched in } - paramTop: int64; { the parameters' slots end here } - zeroTop: int64; { the locals the prologue zeroes end here } - retSlot: int64; { holds the hidden result pointer } - resType: PType; { the procedure's result, or nil } - exitL: longint; - { parameters arriving in registers: where each is stored on entry } - 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 (XBit) } - kept: longint; { bit r: register r holds a parameter, as it arrived } - saveAt: int64; { where they are saved, a quadword each } - homes: array[0..3] of int64; { the slots of the variables in XVarRegs } - frameAt: array[0..2] of int64; { frameTop, frameMax, permTop after the declarations } - { the checks of the procedure, whose failures EndFails makes } - fails: array[0..4095] of record - L, what, ra, name, at: longint; - m: TMem; - n: int64; - end; - numFails: longint; - -function KindOf(t: PType): TKind; -begin - if t^.form = fReal then begin - if t^.size = 4 then KindOf := kF32 else KindOf := kF64 - end else if t^.size > WordSize then KindOf := kLong - else KindOf := kWord; -end; - -{ The stack, as in Wirth's compilers: the value at depth d is held in - register d mod NumRegs. A value, when a higher one wants its register, - and every value in a register when a call would clobber them, is - spilled to a frame slot, and loaded again where it is used. A constant - is only noted. - - Drop emits no code, and a dropped value's register still holds it - until the next push claims it: Place (for bStack), Operands, - IndexSlice and JumpCmp read a register after dropping its value. - - Registers outside the stack, free within one operation: rax, rcx and - rdx for arithmetic; rsi and rdi for copying; and, where the stack holds - nothing in them, r10 for the prologue's zeroing loop and r11 for a call - through a procedure value; xmm0 and xmm1 for reals. - - A real, an F32 or an F64, is held in xmm8 to xmm11 (XRegs), where the - machine computes with reals, the value at depth d in XRegs[d mod - NumRegs]: so each depth has two registers, and holds its value in the - one of its kind, which owner doesn't tell apart. The xmm registers - from xmm8 up carry no arguments, so that Call can move a real into - xmm0 to xmm7 without overwriting another still to go. } - -function Fits32(v: int64): boolean; -begin - Fits32 := (v >= low(longint)) and (v <= high(longint)); -end; - -{ The register of kind k for the value at depth i } -function RegIn(k: TKind; i: longint): longint; -begin - if k in [kF32, kF64] then RegIn := XRegs[i mod NumRegs] else RegIn := Regs[i mod NumRegs]; -end; - -function RegOf(i: longint): longint; -begin - RegOf := RegIn(stack[i].k, i); -end; - -function IsReal(i: longint): boolean; -begin - IsReal := stack[i].k in [kF32, kF64]; -end; - -{ A real constant, its bits v, as an operand: 8 bytes in read-only - data, as the machine has no instruction that holds one } -function RealConst(v: int64): TMem; -var c: longint; -begin - c := NewChunk(secRodata, -1, -1); - SetData(c, @v, 8, 8); - RealConst := MemRip(c, 0); -end; - -{ The real i into xmm register x, from wherever it is, as ValueTo does - for an integer register } -procedure XValueTo(i, x: longint); -var single: boolean; -begin - single := stack[i].k = kF32; - case stack[i].loc of - lConst: MovsXM(x, RealConst(stack[i].val), single); - lMem: MovsXM(x, stack[i].m, stack[i].size = 4); - lHeld, lInto: if stack[i].val <> x then MovX(x, stack[i].val); - lReg: if RegOf(i) <> x then MovX(x, RegOf(i)); - else MovsXM(x, Mem(RBP, stack[i].val), false); { spilled, as 8 bytes } - end; -end; - -function Loaded(i: longint): longint; forward; - -{ The value i, in a register, goes to a frame slot; one noted that - holds its register, as an index, is worked out in it first } -procedure Spill(i: longint); -var s: int64; -begin - if (stack[i].loc <> lReg) or (stack[i].off <> 0) then Loaded(i); - s := AllocTemp(8, 8); - if IsReal(i) then MovsMX(Mem(RBP, s), RegOf(i), false) - else Store(Mem(RBP, s), RegOf(i), 8); - stack[i].loc := lFrame; - stack[i].val := s; - owner[i mod NumRegs] := -1; -end; - -{ Each value below depth d read from memory now, as what comes next - may change it } -procedure ReadMems(d: longint); -var i: longint; -begin - for i := 0 to d - 1 do - if stack[i].loc = lMem then Loaded(i); -end; - -{ Every value below depth d in a register, spilled; one noted in memory - is read first, as a call may change it } -procedure SpillBelow(d: longint); -var r: longint; -begin - ReadMems(d); - for r := 0 to NumRegs - 1 do - if (owner[r] >= 0) and (owner[r] < d) then Spill(owner[r]); -end; - -{ The register of kind k of value i, for it to hold: a lower value at - its depth's registers is spilled. } -function Claim(i: longint; k: TKind): longint; -var r: longint; -begin - r := i mod NumRegs; - if (owner[r] >= 0) and (owner[r] <> i) then Spill(owner[r]); - owner[r] := i; - Claim := RegIn(k, i); -end; - -{ The memory at the noted address i, plus off } -function AdrMem(i: longint; off: int64): TMem; -begin - if stack[i].chunk < 0 then AdrMem := Mem(RBP, stack[i].val + off) - else AdrMem := MemRip(stack[i].chunk, stack[i].val + off); -end; - -{ The value i, in its register } -function Loaded(i: longint): longint; -var r: longint; -begin - if stack[i].loc = lInto then exit(stack[i].val); - if (stack[i].loc <> lReg) and IsReal(i) then begin - XValueTo(i, Claim(i, stack[i].k)); - stack[i].loc := lReg; - end else if stack[i].loc <> lReg then begin - r := Claim(i, kWord); - case stack[i].loc of - lConst: MovRI(r, stack[i].val); - lHeld: MovRR(r, stack[i].val); - lAdr: Lea(r, AdrMem(i, 0)); - lIdx: Lea(r, stack[i].m); - lMem: Load(r, stack[i].m, stack[i].size, stack[i].signed); - else Load(r, Mem(RBP, stack[i].val), 8, false); - end; - stack[i].loc := lReg; - end; - if stack[i].off <> 0 then begin - Lea(RegOf(i), Mem(RegOf(i), stack[i].off)); - stack[i].off := 0; - 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) and (stack[i].off = 0) then Peek := stack[i].val else Peek := Loaded(i); -end; - -{ The offset of value i, taken from it, for the caller to add or to - make a displacement of } -function TakeOff(i: longint): int64; -begin - TakeOff := stack[i].off; - stack[i].off := 0; -end; - -{ The word on top, in a register, has o added: noted, if o can be a - displacement, else added now } -procedure PutOff(o: int64); -begin - if Fits32(stack[depth - 1].off + o) then stack[depth - 1].off := stack[depth - 1].off + o - else begin - MovRI(RCX, o); - Alu(aluAdd, Loaded(depth - 1), RCX); - end; -end; - -function Top: longint; -begin - if depth = 0 then Fatal('internal error: the stack is empty'); - Top := Loaded(depth - 1); -end; - -procedure NewEntry(k: TKind; loc: TLoc; v: int64); -begin - if depth > High(stack) then Mark('the expression is too deep'); - stack[depth].k := k; - stack[depth].loc := loc; - stack[depth].val := v; - stack[depth].chunk := -1; - stack[depth].off := 0; - inc(depth); -end; - -{ An address, lIdx, or a value at it, lMem, noted as the operand m. Its - index may be in the register of the value just dropped, at this - depth: it is the new value's own, then. } -procedure NewMem(loc: TLoc; const m: TMem; k: TKind; size: longint; signed: boolean); -begin - NewEntry(k, loc, 0); - stack[depth - 1].m := m; - stack[depth - 1].size := size; - stack[depth - 1].signed := signed; - if m.index = Regs[(depth - 1) mod NumRegs] then owner[(depth - 1) mod NumRegs] := depth - 1; -end; - -{ The register a new value on top is to be computed in } -function Target: longint; -begin - Target := Claim(depth, kWord); -end; - -{ The xmm register a new real on top is to be computed in } -function XTarget: longint; -begin - XTarget := Claim(depth, kF64); -end; - -{ The value just computed in Target goes on top } -procedure Computed(k: TKind); -begin - NewEntry(k, lReg, 0); -end; - -procedure Drop; -begin - dec(depth); - if owner[depth mod NumRegs] = depth then owner[depth mod NumRegs] := -1; -end; - -{ rsi and rdi are about to be used for other work, as in copying: a - parameter kept in either must go to memory (lost). } -procedure ClobberArgs; -begin - if kept <> 0 then lost := true; -end; - -{ The value i into register r, from wherever it is: a constant or an - address is made there, a variable's register or the value's own - register copied, a spilled value loaded. Unlike Loaded, it leaves the - value where it was, so r is its only new copy. } -procedure ValueTo(i, r: longint); -begin - if IsReal(i) and (stack[i].loc in [lHeld, lInto]) then MovqRX(r, stack[i].val) - else case stack[i].loc of - lConst: MovRI(r, stack[i].val); - lHeld, lInto: MovRR(r, stack[i].val); - lAdr: Lea(r, AdrMem(i, 0)); - lIdx: Lea(r, stack[i].m); - lMem: Load(r, stack[i].m, stack[i].size, stack[i].signed); - lReg: - if IsReal(i) then MovqRX(r, RegOf(i)) - else if RegOf(i) <> r then MovRR(r, RegOf(i)); - else Load(r, Mem(RBP, stack[i].val), 8, false); - end; - if stack[i].off <> 0 then Lea(r, Mem(r, stack[i].off)); -end; - -{ The value on top, popped into register r } -procedure PopTo(r: longint); -begin - ValueTo(depth - 1, r); - Drop; -end; - -{ Whether the value on top is a constant, and if so, which } -function TopConst(var v: int64): boolean; -begin - TopConst := stack[depth - 1].loc = lConst; - v := stack[depth - 1].val; -end; - -procedure ResetStack(d, p: longint); -var r: longint; -begin - depth := d; - pushed := p; - for r := 0 to NumRegs - 1 do owner[r] := -1; -end; - -procedure PushConst(k: TKind; v: int64); -begin - NewEntry(k, lConst, v); -end; - -{ The register of the word at a, a variable in registers: the variable's - own, or for a slice its pointer's (off 0) or its length's (off 8) } -function RegAt(const a: TAdr): longint; -begin - if a.off = 0 then RegAt := a.chunk else RegAt := a.hi; - if RegAt >= XmmVar then RegAt := RegAt - XmmVar; { an xmm register, XVarRegs } -end; - -{ The memory a names. An address on the stack is popped, and is in its - register still; one in a slot is loaded into r. } -function Place(const a: TAdr; r: longint): TMem; -var ra: longint; o: int64; -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); - bStack: - if stack[depth - 1].loc = lAdr then begin - Place := AdrMem(depth - 1, a.off); - Drop; - end else if stack[depth - 1].loc = lIdx then begin - Place := stack[depth - 1].m; - Place.disp := Place.disp + a.off; - Drop; - end else begin - { an offset noted on the address is the operand's, as - p^.f + 8: [r8 + 8] } - if Fits32(a.off + stack[depth - 1].off) then o := TakeOff(depth - 1) else o := 0; - ra := Peek(depth - 1); - Drop; - Place := Mem(ra, a.off + o) - end; - else { bSlot: the address is in the frame slot a.chunk } - Load(r, Mem(RBP, a.chunk), 8, false); - Place := Mem(r, a.off); - end; -end; - -{ The address a names, on top of the stack } -procedure PushAdr(const a: TAdr); -var m: TMem; r: longint; -begin - if (a.base = bStack) and (a.off = 0) then exit; { it is on top already } - if a.base in [bFrame, bGlobal] then begin - NewEntry(kWord, lAdr, a.off); - if a.base = bGlobal then stack[depth - 1].chunk := a.chunk; - exit; - end; - { The order matters. With the address on the stack, Place pops it and - must come first, so that Target may reuse its register; otherwise - Target comes first, since Place may need r to load a slot's pointer. } - if a.base = bStack then begin m := Place(a, -1); r := Target end - else begin r := Target; m := Place(a, r) end; - Lea(r, m); - Computed(kWord); -end; - -procedure PushVar(const a: TAdr; size: longint; signed: boolean; k: TKind); -var m: TMem; r: longint; -begin - r := inPlace; - inPlace := -1; - if r >= XmmVar then r := r - XmmVar; - if (a.base = bReg) and (RegAt(a) = r) then begin - NewEntry(k, lInto, r); - exit; - end; - if a.base = bReg then begin - NewEntry(k, lHeld, RegAt(a)); - exit; - end; - { a variable in the frame or a chunk, or at an address only noted, is - only noted too: read where it is used, as an operand if it can be } - if (a.base in [bFrame, bGlobal]) or (a.base = bStack) and (stack[depth - 1].loc in [lAdr, lIdx]) then begin - m := Place(a, -1); - NewMem(lMem, m, k, size, signed); - exit; - end; - { in the order PushAdr explains } - if a.base = bStack then begin m := Place(a, -1); r := Target end - else begin r := Target; m := Place(a, r) end; - if k in [kF32, kF64] then MovsXM(XTarget, m, size = 4) - else Load(r, m, size, signed); - Computed(k); -end; - -procedure PushProc(c: longint; ext: boolean); -var r: longint; -begin - r := Target; - if ext then Load(r, MemRip(c, 0), 8, false) - else Lea(r, MemRip(c, 0)); - Computed(kWord); -end; - -{ The slot of the variable in xmm register x } -function HomeOf(x: longint): TMem; -begin - HomeOf := Mem(RBP, homes[x + XmmVar - XVarRegs[0]]); -end; - -{ Pops a value into the variable at a; an address on the stack is under - the value. } -procedure PopVar(const a: TAdr; size: longint); -var r: longint; v: int64; real: boolean; -begin - if (a.base = bReg) and IsReal(depth - 1) then begin - XValueTo(depth - 1, RegAt(a)); - Drop; - MovsMX(HomeOf(RegAt(a)), RegAt(a), false); { written through, as XHome says } - exit; - end; - if a.base = bReg then begin - if TopConst(v) then MovRI(RegAt(a), v) - else if Peek(depth - 1) <> RegAt(a) then MovRR(RegAt(a), Peek(depth - 1)); { else it is there, lInto } - 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 := Peek(depth - 1); - real := (stack[depth - 1].loc <> lConst) and IsReal(depth - 1); - Drop; - if real then MovsMX(Place(a, RCX), r, size = 4) - else Store(Place(a, RCX), r, size); -end; - -{ Register src to dst, an xmm register's if real } -procedure MovReg(real: boolean; dst, src: longint); -begin - if real then MovX(dst, src) else MovRR(dst, src); -end; - -{ The two values on top, of one kind, change places. } -procedure Swap; -var e: TEntry; x, y, t: longint; rx, ry, real: boolean; -begin - x := depth - 2; y := depth - 1; - { a value noted at an address that uses its register is worked out, - so that its register moves with it } - if stack[x].loc in [lIdx, lMem] then Loaded(x); - if stack[y].loc in [lIdx, lMem] then Loaded(y); - rx := stack[x].loc = lReg; - ry := stack[y].loc = lReg; - real := IsReal(y); - if real then t := 0 else t := RAX; { xmm0, or rax } - if rx and ry then begin - MovReg(real, t, RegOf(x)); - MovReg(real, RegOf(x), RegOf(y)); - MovReg(real, RegOf(y), t); - end else if rx then begin - owner[x mod NumRegs] := -1; - MovReg(real, Claim(y, stack[y].k), RegOf(x)); - end else if ry then begin - owner[y mod NumRegs] := -1; - MovReg(real, Claim(x, stack[x].k), RegOf(y)); - end; - e := stack[x]; stack[x] := stack[y]; stack[y] := e; -end; - -{ Copying } - -{ size bytes from [rsi] to [rdi], through rcx; rsi and rdi are left - as they fall. Up to 64 bytes, as a record or a small array mostly - is, they go as moves of 8, 4, 2 and 1 bytes: rep movsb takes some - twenty cycles to start, longer than the few moves take. } -procedure CopyBytes(size: int64); -var o, n: int64; -begin - if size > 64 then begin - MovRI(RCX, size); - RepMovsb; - exit; - end; - o := 0; - while o < size do begin - n := 8; - while n > size - o do n := n div 2; - Load(RCX, Mem(RSI, o), n, false); - Store(Mem(RDI, o), RCX, n); - Inc(o, n); - end; -end; - -{ Pops a source's address, and a destination's under it, and copies - size bytes to off bytes past the destination. } -procedure CopyBlock(size, off: int64); -begin - ClobberArgs; - PopTo(RSI); - PopTo(RDI); - if off <> 0 then Lea(RDI, Mem(RDI, off)); - CopyBytes(size); -end; - -{ Pops a source's address, and copies size bytes to a: for a slice in - registers, its two words into them. } -procedure CopyTo(const a: TAdr; size: int64); -begin - ClobberArgs; - PopTo(RSI); - if a.base = bReg then begin - Load(a.chunk, Mem(RSI, 0), 8, false); - Load(a.hi, Mem(RSI, 8), 8, false); - exit; - end; - Lea(RDI, Place(a, RDI)); - CopyBytes(size); -end; - -procedure ZeroVar(const a: TAdr; size: int64); -begin - ClobberArgs; - Lea(RDI, Place(a, RDI)); - MovRI(RCX, size); - MovRI(RAX, 0); - RepStosb; -end; - -{ Operations } - -{ n if v is 2^n, which is 0 for 1; -1 if v isn't a power of two } -function ExactLog2(v: int64): longint; -var n: longint; -begin - n := 0; - while (v > 1) and (v and 1 = 0) do begin v := v shr 1; inc(n) end; - if v <> 1 then n := -1; - ExactLog2 := n; -end; - -{ r times v, a size: by a shift where v is a power of two, as it - mostly is, since a shift takes one cycle and imul three } -procedure MulI(r: longint; v: int64); -begin - if ExactLog2(v) > 0 then ShiftI(shShl, r, ExactLog2(v)) - else if v <> 1 then ImulI(r, v); -end; - -{ 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 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; - -{ r div or mod 2^k, 1 <= k <= 62, with shifts: div truncates towards - zero, so a negative dividend first gets 2^k - 1 added (the bias). } -procedure DivPow2(op: TSym; r, k: longint; unsign: boolean); -begin - { unsigned: div shifts right; mod keeps the low k bits, by shifting - them up to the top and back down } - if unsign then begin - if op = sDiv then ShiftI(shShr, r, k) - else begin ShiftI(shShl, r, 64 - k); ShiftI(shShr, r, 64 - k) end; - exit; - end; - { signed: sar 63 makes the sign into all ones or all zeros, and shr - 64 - k keeps k of them, the bias 2^k - 1 or 0; with it added, sar k - rounds towards zero. The remainder is r less the quotient times 2^k. } - MovRR(RCX, r); - ShiftI(shSar, RCX, 63); - ShiftI(shShr, RCX, 64 - k); - Alu(aluAdd, RCX, r); - ShiftI(shSar, RCX, k); - if op = sDiv then MovRR(r, RCX) - else begin ShiftI(shShl, RCX, k); Alu(aluSub, r, RCX) end; -end; - -{ Before rax div y, of a signed type of bits < 64: its smallest value - divided by -1 overflows it, which must stop the program as it does for - an I64 (report section 6.1). idiv on the 64-bit values wouldn't fault, - so then rax is made the smallest I64, and it does. } -procedure DivTrap(bits, y: longint); -var L: longint; -begin - L := NoLabel; - CmpI(y, -1); - Jcc(ccNE, L); - CmpI(RAX, int64(-1) shl (bits - 1)); - Jcc(ccNE, L); - ShiftI(shShl, RAX, 64 - bits); - FixLink(L); -end; - -{ Whether the value on top is a word in memory that can be the right - operand of an instruction as it is: add r, [m] } -function TopInMem: boolean; -begin - TopInMem := (stack[depth - 1].loc = lMem) and (stack[depth - 1].size = 8); -end; - -{ The right operand of the two values on top, popped, in register y: - its own, or rcx for a constant; the left one stays, in its register, - which is returned. } -function Operands(var y: longint): longint; -var v: int64; -begin - if TopConst(v) then begin MovRI(RCX, v); y := RCX end else y := Peek(depth - 1); - Drop; - Operands := Top; -end; - -{ The two reals on top, the left op the right, worked out in the left's - xmm register. The right is taken from memory where it is, as a - constant, a variable or a spilled value is: mulsd xmm8, [rbp - 16]. } -procedure RealOp(op: TSym; k: TKind); -var f: boolean; c, x, y: longint; m: TMem; -begin - f := k = kF32; - case op of - sPlus: c := $58; { addsd, or addss for an F32 } - sMinus: c := $5C; { subsd, subss } - sTimes: c := $59; { mulsd, mulss } - else c := $5E; { divsd, divss } - end; - if stack[depth - 1].loc in [lConst, lMem, lFrame] then begin - case stack[depth - 1].loc of - lConst: m := RealConst(stack[depth - 1].val); - lMem: m := stack[depth - 1].m; - else m := Mem(RBP, stack[depth - 1].val); - end; - Drop; - SseM(c, Top, m, f); - end else begin - y := Peek(depth - 1); - Drop; - x := Top; - Sse(c, x, y, f); - end; -end; - -{ The group 1 operation of +, -, &, | and xor } -function AluOf(op: TSym): longint; -begin - case op of - sPlus: AluOf := aluAdd; - sMinus: AluOf := aluSub; - sAmp: AluOf := aluAnd; - sBar: AluOf := aluOr; - else AluOf := aluXor; - end; -end; - -{ The two values on top, the left op the right, an integer of size - bytes, signed or not, brought back to its width. } -procedure Op(op: TSym; k: TKind; size: longint; signed: boolean); -var v, o: int64; r, y, sh, bits: longint; c: boolean; m: TMem; -begin - if k in [kF32, kF64] then begin RealOp(op, k); exit end; - bits := size * 8; - { a constant on the left of an operation whose order doesn't matter - goes right, where it can be an immediate or a shift } - if (op in [sPlus, sTimes, sAmp, sBar, sXor]) and (stack[depth - 2].loc = lConst) - and (stack[depth - 1].loc <> lConst) then Swap; - c := TopConst(v); - { A word's offset (see TEntry) is carried through + and -, and - through * by a constant, as (x + a) * k is x * k + a * k: the - operation is done on the registers, the offsets worked out here, - and put on the result. x + 1 is only noted. A value changed in - place, lInto, has no offset. } - o := 0; - if (bits = 64) and (stack[depth - 2].loc <> lInto) - and ((op in [sPlus, sMinus]) or (op = sTimes) and c and Fits32(v)) then begin - o := TakeOff(depth - 2); - if op = sTimes then o := o * v - else if c and Fits32(v) then begin - if op = sPlus then o := o + v else o := o - v; - Drop; - if not (stack[depth - 1].loc in [lReg, lHeld]) then Top; - PutOff(o); - exit; - end - else if op = sPlus then o := o + TakeOff(depth - 1) - else o := o - TakeOff(depth - 1); - end; - sh := -1; - if c and (op in [sTimes, sDiv, sMod]) then sh := ExactLog2(v); - if c and (sh >= 1) then begin - Drop; - r := Top; - if op = sTimes then ShiftI(shShl, r, sh) else DivPow2(op, r, sh, not signed); - end else if c and Fits32(v) and (op in [sPlus, sMinus, sBar, sXor, sAmp, sTimes, sShl, sShr]) then begin - Drop; - r := Top; - case op of - sTimes: ImulI(r, v); - sShl: ShiftI(shShl, r, v and (bits - 1)); - sShr: if signed then ShiftI(shSar, r, v and (bits - 1)) else ShiftI(shShr, r, v and (bits - 1)); - else AluI(AluOf(op), r, v); - end; - end else if TopInMem and (op in [sPlus, sMinus, sAmp, sBar, sXor]) then begin - m := stack[depth - 1].m; - Drop; - r := Top; - AluM(AluOf(op), r, m); - end else begin - r := Operands(y); - case op of - sPlus, sMinus, sAmp, sBar, sXor: Alu(AluOf(op), r, y); - sTimes: Imul(r, y); - sDiv, sMod: begin - MovRR(RAX, r); - if not signed then begin MovRI(RDX, 0); Unary(6, y) end { div } - else begin - { only -1 can make the division overflow, so a constant - divisor other than -1 needs no check } - if (bits < 64) and (not c or (v = -1)) then DivTrap(bits, y); - Cqo; Unary(7, y) { idiv, of rdx:rax, which cqo made from rax } - end; - if op = sDiv then MovRR(r, RAX) else MovRR(r, RDX); - end; - sShl, sShr: begin - { the count modulo the width: the machine takes it modulo 64 } - if y <> RCX then MovRR(RCX, y); - if bits < 64 then AluI(aluAnd, RCX, bits - 1); - if op = sShl then Shift(shShl, r) - else if signed then Shift(shSar, r) else Shift(shShr, r); - end; - end; - end; - if bits < 64 then Extend(r, size, signed); - stack[depth - 1].k := k; - if o <> 0 then PutOff(o); -end; - -{ The left op the right of the two values on top, as a BOOL } -procedure Compare(op: TSym; k: TKind; signed: boolean); -const - CcSigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccL, ccLE, ccG, ccGE); - CcUnsigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccB, ccBE, ccA, ccAE); -var f: boolean; r, x, y: longint; v: int64; m: TMem; -begin - if k in [kF32, kF64] then begin - f := k = kF32; - y := Peek(depth - 1); - Drop; - x := Peek(depth - 1); - Drop; - r := Target; { the BOOL, in the left's integer register } - { ucomis sets the flags as an unsigned comparison would, but for an - unordered pair (a NaN) it sets zero, parity and carry all. So only - "above" can be tested straight: it is false for NaN, as every - comparison but <> must be. a < b is made b > a. = also asks for - no parity, as NaN = NaN sets the zero flag, and <> asks for - parity as well. } - case op of - sEql: begin Ucomis(x, y, f); SetCC(ccE, r); SetCC(ccNP, RCX); Alu(aluAnd, r, RCX) end; - sNeq: begin Ucomis(x, y, f); SetCC(ccNE, r); SetCC(ccP, RCX); Alu(aluOr, r, RCX) end; - sLss: begin Ucomis(y, x, f); SetCC(ccA, r) end; - sLeq: begin Ucomis(y, x, f); SetCC(ccAE, r) end; - sGtr: begin Ucomis(x, y, f); SetCC(ccA, r) end; - sGeq: begin Ucomis(x, y, f); SetCC(ccAE, r) end; - end; - Computed(kWord); - end else begin - if TopConst(v) then begin Drop; r := Top; CmpI(r, v) end - else if TopInMem then begin m := stack[depth - 1].m; Drop; r := Top; AluM(aluCmp, r, m) end - else begin r := Operands(y); Alu(aluCmp, r, y) end; - if signed then SetCC(CcSigned[op], r) else SetCC(CcUnsigned[op], r); - end; - stack[depth - 1].k := kWord; -end; - -{ A real is negated by flipping its sign bit, in rax } -procedure Neg(k: TKind; size: longint; signed: boolean); -var r: longint; -begin - r := Top; - case k of - kF32, kF64: begin - MovqRX(RAX, r); - if k = kF32 then Btc(RAX, 31) else Btc(RAX, 63); - MovqXR(r, RAX); - end; - else - Unary(3, r); { neg } - if size < 8 then Extend(r, size, signed); - end; -end; - -procedure Complement(size: longint; signed: boolean); -var r: longint; -begin - r := Top; - Unary(2, r); { not } - if size < 8 then Extend(r, size, signed); -end; - -procedure NotBool; -begin - AluI(aluXor, Top, 1); -end; - -{ The integer on top, brought to size bytes } -procedure Narrow(size: longint; signed: boolean); -var r: longint; -begin - r := Top; - if size < 8 then Extend(r, size, signed); - stack[depth - 1].k := kWord; -end; - -{ The integer on top, as a real of kind k; big if it may be a U64 above - high(I64), which the machine would take as negative } -procedure IntToReal(k: TKind; big: boolean); -var L1, L2, r, x: longint; f: boolean; -begin - f := k = kF32; - r := Top; - x := RegIn(k, depth - 1); { its xmm register } - if big then begin - { above high(I64): halve, keeping the low bit, and double } - L1 := NoLabel; L2 := NoLabel; - TestRR(r, r); - Jcc(ccS, L1); - Cvtsi2s(x, r, f); - Jmp(L2); - FixLink(L1); - MovRR(RCX, r); - ShiftI(shShr, RCX, 1); - AluI(aluAnd, r, 1); - Alu(aluOr, RCX, r); - Cvtsi2s(x, RCX, f); - Sse($58, x, x, f); { adds it to itself: doubles } - FixLink(L2); - end else Cvtsi2s(x, r, f); - stack[depth - 1].k := k; -end; - -{ The real of kind k on top, truncated to an integer } -procedure RealToInt(k: TKind); -var x: longint; -begin - x := Top; - Cvtts2si(RegIn(kWord, depth - 1), x, k = kF32); - stack[depth - 1].k := kWord; -end; - -{ The real of kind k on top, as the other kind } -procedure RealToReal(k: TKind); -var x: longint; -begin - x := Top; - Sse($5A, x, x, k = kF32); { cvtss2sd, or cvtsd2ss } - if k = kF32 then stack[depth - 1].k := kF64 else stack[depth - 1].k := kF32; -end; - -{ Whether the slices in the frame at a and b (the offsets of their - pointers, the lengths 8 bytes on) are equal (or not, if not eq): the - lengths, then the bytes, len shl shift of them, compared where the - comparison stands. } -procedure CompareSeq(a, b: int64; shift: longint; eq: boolean); -var differ, r: longint; -begin - ClobberArgs; - r := Target; - Load(RCX, Mem(RBP, b + 8), 8, false); - AluM(aluCmp, RCX, Mem(RBP, a + 8)); - differ := NoLabel; - Jcc(ccNE, differ); - Load(RSI, Mem(RBP, b), 8, false); - Load(RDI, Mem(RBP, a), 8, false); - if shift > 0 then ShiftI(shShl, RCX, shift); - { repe cmpsb with rcx = 0 leaves the flags alone, so make them say - equal first, which is right if there are no bytes } - Alu(aluCmp, RCX, RCX); - RepeCmpsb; - FixLink(differ); - if eq then SetCC(ccE, r) else SetCC(ccNE, r); - Computed(kWord); -end; - -{ An error points at its message's length, an 8-byte word, with the - text after it; nil is no error. Pops one, and makes the slice of its - message at tmp, empty for nil. } -procedure ErrorText(tmp: int64); -var L: longint; -begin - PopTo(RAX); - MovRI(RCX, 0); - L := NoLabel; - TestRR(RAX, RAX); - Jcc(ccE, L); - Load(RCX, Mem(RAX, 0), 8, false); - Lea(RAX, Mem(RAX, 8)); - FixLink(L); - Store(Mem(RBP, tmp), RAX, 8); - Store(Mem(RBP, tmp + 8), RCX, 8); -end; - -{ Pops a step and an integer variable's address, and adds the step to - it, or takes it away. } -procedure IncDec(size: longint; signed, dec: boolean); -var r, y, op: longint; v: int64; a: TAdr; -begin - if TopConst(v) and Fits32(v) then begin - Drop; - a.base := bStack; a.off := 0; - if dec then op := aluSub else op := aluAdd; - AluMI(op, Place(a, RCX), v, size); - exit; - end; - r := Operands(y); - Drop; - Load(RAX, Mem(r, 0), size, signed); - if dec then Alu(aluSub, RAX, y) else Alu(aluAdd, RAX, y); - 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; -begin - ClobberArgs; - r := Top; - L := NoLabel; - TestRR(r, r); - Jcc(ccE, L); - MovRR(RDI, r); - MovRI(RCX, size); - MovRI(RAX, 0); - RepStosb; - FixLink(L); -end; - -{ CAS(p, old, new), XCHG(p, v) or XADD(p, v), from the stack: the - result where p was } -procedure Atomic(which: longint); -var r, n: longint; -begin - ReadMems(depth - 2 - ord(which = bCas)); { what it writes may be one } - if which = bCas then begin n := Top; Drop end; - PopTo(RAX); { cmpxchg compares with rax, so CAS's old value goes there } - r := Top; - case which of - bCas: begin LockCmpxchg(Mem(r, 0), n); SetCC(ccE, r) end; - bXchg: begin Xchg(Mem(r, 0), RAX); MovRR(r, RAX) end; - bXadd: begin LockXadd(Mem(r, 0), RAX); MovRR(r, RAX) end; - end; - stack[depth - 1].k := kWord; -end; - -{ The system call and its arguments, n values on the stack. Linux takes - the number in rax and the arguments in rdi, rsi, rdx, r10, r8 and r9, - and the syscall instruction clobbers rcx and r11. Every value in a - register is spilled first, as r8 to r11 are the stack's registers, - and the arguments are loaded from their slots. } -procedure SysCall(n: longint); -const SysRegs: array[0..6] of longint = (RAX, RDI, RSI, RDX, R10, R8, R9); -var i: longint; -begin - ClobberArgs; - SpillBelow(depth); - for i := 0 to n - 1 do ValueTo(depth - n + i, SysRegs[i]); - for i := 1 to n do Drop; - x64.Syscall; - MovRR(Target, RAX); - Computed(kWord); -end; - -procedure Fence; -begin - Mfence; -end; - -{ Jumps. A label is the chain of the jumps to it, until it is placed. } - -procedure Jump(var L: longint); -begin - Jmp(L); -end; - -{ Pops a BOOL, and jumps if it is when } -procedure JumpIf(var L: longint; when: boolean); -var r: longint; -begin - r := Peek(depth - 1); - Drop; - TestRR(r, r); - if when then Jcc(ccNE, L) else Jcc(ccE, L); -end; - -{ Pops two integers, and jumps if the left op the right } -procedure JumpCmp(op: TSym; signed: boolean; var L: longint); -const - CcSigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccL, ccLE, ccG, ccGE); - CcUnsigned: array[sEql..sGeq] of longint = (ccE, ccNE, ccB, ccBE, ccA, ccAE); -var r, y: longint; v: int64; m: TMem; -begin - { 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 if TopInMem then begin m := stack[depth - 1].m; Drop; r := Peek(depth - 1); AluM(aluCmp, r, m) 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; - -{ JumpCmp out of an expression, past code that may spill: the values - under the two compared are spilled first, so that they are where the - code after the landing place expects them, whichever way it came. In - v + (a < b and f(x) = 0), a call to f spills v on the way through, so - v must be in its slot too where a < b jumps past the call. } -procedure JumpOut(op: TSym; signed: boolean; var L: longint); -begin - SpillBelow(depth - 2); - JumpCmp(op, signed, L); -end; - -{ The two values on top, compared, as a BOOL: true unless notOp, the - opposite comparison, holds. fj and tj are the chains of jumps, made - earlier by and, or and not, that are taken when the whole condition is - false and when it is true; they land here, on the 0 and the 1. } -procedure CondValue(notOp: TSym; signed: boolean; fj, tj: longint); -var r, e: longint; -begin - JumpOut(notOp, signed, fj); - FixLink(tj); - r := Target; - MovRI(r, 1); - e := NoLabel; - Jmp(e); - FixLink(fj); - MovRI(r, 0); - FixLink(e); - Computed(kWord); -end; - -{ JumpBack, Fix, FixTo and JoinJumps are gen's names for the encoder's, - so that a port can place jumps its own way. Fix(L) places label L here; - FixTo(L, top) makes every jump on chain L go to the earlier place top; - JoinJumps makes one chain of two. } -procedure JumpBack(top: longint); -begin - JmpBack(top); -end; - -procedure Fix(L: longint); -begin - FixLink(L); -end; - -{ A jump table, for a match on the integer in frame slot slot, whose - labels run from lo up for n values. The selector less lo, compared - unsigned (so below lo is above n too), is out of the table if it - isn't below n, and goes to the else arm at elseAt, or, if there is - none, to endL, the end of the match. Else it indexes a table of - 4-byte offsets, each from the start of the lea, that follows the - jump, and the code jumps to its start plus the entry: - - mov rax, [slot] - sub rax, lo - cmp rax, n - 1 - ja else - lea rcx, [rip + start] start: this very lea - movsxd rax, [rcx + rax*4 + 17] - add rax, rcx - jmp rax - table: .long arm0 - start, arm1 - start, ... - - The four instructions after the compare are 7, 5, 3 and 2 bytes, so - the table is 17 bytes on, which JumpTable checks. It returns start; - the caller then makes the n entries with TableEntry. } -function JumpTable(slot, lo: int64; n, elseAt: longint; var endL: longint): longint; -const TableAt = 17; -var start: longint; -begin - Load(RAX, Mem(RBP, slot), 8, false); - if lo <> 0 then AluI(aluSub, RAX, lo); - AluI(aluCmp, RAX, n - 1); - if elseAt <> NoLabel then JccBack(ccA, elseAt) else Jcc(ccA, endL); - start := pc; - Lea(RCX, Here); - Load(RAX, MemIdx(RCX, RAX, 4, TableAt), 4, true); - Alu(aluAdd, RAX, RCX); - JmpR(RAX); - if pc <> start + TableAt then Fatal('internal error: the jump table is not where it was said'); - JumpTable := start; -end; - -{ The next entry of the table that JumpTable started at table: the - code at target } -procedure TableEntry(table, target: longint); -begin - Put4(target - table); -end; - -procedure AlignLoop; -begin - Align(32); -end; - -function JoinJumps(L1, L2: longint): longint; -begin - JoinJumps := JoinLinks(L1, L2); -end; - -procedure FixTo(L, top: longint); -begin - FixLinkTo(L, top); -end; - -{ Checks } - -const - NoBase = -2; { a TMem that is no memory } - ARegister = -3; { a TMem that is no memory but a register, its index } - -{ The program goes on if the condition cc holds, and otherwise stops - in Rt.fail(what, a, b, len, at, name), which says what failed at p, - found by at, which a stub works out from where it was called; what is - an index a (0), a slice a..b (1), each for a length len, a position a - of the enumeration called name (2), a slice of a pointer a..b that - runs backwards (3), or a nil pointer (4). Rt.fail knows 5 and 6, a - division fault and a stack overflow, which this machine catches - itself, so no check here has them. The arguments go in rdi, rsi, rdx, - rcx, r8 and r9: a is in register ra, b in RDX; len is in memory at m, - or n if m.base is NoBase, or in register m.index if it is ARegister. - rdi and rsi are passed on as they were, since a parameter may be kept - in them, for the trap report to show: so a goes to the stub in rax. - The failing code is out of the way, at the - procedure's end (EndFails), so that a check that holds costs a jump - not taken; it has p for its place (at is p's offset in the source), - never returns, and may use any register once it has read what it - needs. } -procedure Check(cc, what: longint; const p: TPos; ra: longint; const m: TMem; n: int64; name: longint); -begin - if numFails > High(fails) then Mark('more than ' + IntStr(High(fails) + 1) + ' checks in one procedure'); - fails[numFails].L := NoLabel; - Jcc(cc xor 1, fails[numFails].L); { x86's conditions come in pairs, the other one its last bit flipped } - fails[numFails].what := what; - fails[numFails].ra := ra; - fails[numFails].m := m; - fails[numFails].n := n; - fails[numFails].name := name; - fails[numFails].at := p.a; - inc(numFails); -end; - -{ The failures of the procedure's checks: each gives Rt.fail its values - and the place of the offending expression, through a stub for its - kind, which takes the place from where it was called } -procedure EndFails; -var i, line, col: longint; -begin - for i := 0 to numFails - 1 do - with fails[i] do begin - FixLink(L); - LineCol(at, line, col); - NoteLine(line, col); - if ra <> RAX then MovRR(RAX, ra); - if m.base = NoBase then MovRI(RCX, n) - else if m.base = ARegister then MovRR(RCX, m.index) - else Load(RCX, m, 8, false); - if name >= 0 then Lea(R9, MemRip(name, 0)); - if failStubs[what] < 0 then failStubs[what] := NewChunk(secText, Intern('Rt', 2), Intern(@StubNames[what][1], 6)); - CallChunk(failStubs[what]); - end; - numFails := 0; -end; - -{ For Check: a length known here, not in memory } -function NoMem: TMem; -begin - NoMem := Mem(NoBase, 0); -end; - -{ For Check: a length in register r, a slice's in registers } -function InRegister(r: longint): TMem; -begin - InRegister := Mem(ARegister, 0); - InRegister.index := r; -end; - -{ The index on top is below n, unsigned } -procedure CheckIndex(n: int64; const p: TPos); -var r: longint; -begin - r := Peek(depth - 1); - CmpI(r, n); - Check(ccB, 0, p, r, NoMem, n, -1); -end; - -{ The integer on top is a position of an enumeration of n names } -procedure CheckEnum(n: int64; name: longint; const p: TPos); -var r: longint; -begin - r := Top; - CmpI(r, n); - Check(ccB, 2, p, r, NoMem, n, name); -end; - -{ The address on top, from a pointer, which is to be used reach bytes - past: the program stops if it is nil, unless the machine would stop - it, as for a reach within NilPage. } -procedure CheckNil(reach: int64; const p: TPos); -var r: longint; -begin - if reach <= NilPage then exit; - r := Top; - TestRR(r, r); - Check(ccNE, 4, p, r, NoMem, 0, -1); -end; - -{ The displacement disp of an element of size bytes, with the offset of - the index on top taken into it if it fits: s[k - 1] is [r13 + r9 * 8 - - 8] } -function IndexOff(size, disp: int64): int64; -begin - IndexOff := disp; - if Fits32(disp + stack[depth - 1].off * size) then IndexOff := disp + TakeOff(depth - 1) * size; -end; - -{ Pops an index, and the address of the slice at a if it is on the - stack, and pushes the address of its element of size bytes: the - index, checked against the length, times size, plus the pointer. - It is worked out in the index's own register, which then holds the - address; but if the slice's address is on the stack, under the - index, the element's register is the one that holds that, still - needed, so the work is done in rax. A slice in registers is - compared with and added to them; for an element of 1, 2, 4 or 8 - bytes, its address is only noted, as the operand [pointer + index * - size], to be read or written where it is used (lIdx). } -procedure IndexSlice(const a: TAdr; size: int64; checked: boolean; const p: TPos); -var m, ml: TMem; r: longint; inRax: boolean; o: int64; -begin - if (a.base = bReg) and (size in [1, 2, 4, 8]) then begin - o := 0; - if not checked then o := IndexOff(size, 0); - r := Peek(depth - 1); - if checked then begin - Alu(aluCmp, r, a.hi); - Check(ccB, 0, p, r, InRegister(a.hi), 0, -1); - end; - Drop; - NewMem(lIdx, MemIdx(a.chunk, r, size, o), kWord, 8, false); - exit; - end; - inRax := a.base = bStack; - if inRax then begin r := RAX; PopTo(RAX) end - else begin r := Top; Drop end; - if a.base = bReg then begin - if checked then begin - Alu(aluCmp, r, a.hi); - Check(ccB, 0, p, r, InRegister(a.hi), 0, -1); - end; - MulI(r, size); - Alu(aluAdd, r, a.chunk); - end else begin - m := Place(a, RCX); - ml := m; ml.disp := ml.disp + 8; - if checked then begin - AluM(aluCmp, r, ml); - Check(ccB, 0, p, r, ml, 0, -1); - end; - MulI(r, size); - AluM(aluAdd, r, m); - end; - if inRax then MovRR(Target, RAX) - else Claim(depth, kWord); { the index's register again, now for the address } - Computed(kWord); -end; - -{ Pops an index, checked, and makes the address of the element it - picks of the array at a. An element of 1, 2, - 4 or 8 bytes is only noted, as the operand [base + index * size] - (lIdx): an array in the frame has rbp as its base, and one in a - chunk, if the index is a variable's register, its address made in - the value's own register. Any other is added up. } -procedure IndexArray(const a: TAdr; size: int64); -var r, b: longint; o: int64; -begin - if (size in [1, 2, 4, 8]) and (a.base = bFrame) then begin - o := IndexOff(size, a.off); - r := Peek(depth - 1); - Drop; - NewMem(lIdx, MemIdx(RBP, r, size, o), kWord, 8, false); - end else if (size in [1, 2, 4, 8]) and (a.base = bGlobal) and (stack[depth - 1].loc = lHeld) then begin - o := IndexOff(size, 0); - r := Peek(depth - 1); - Drop; - b := Target; - Lea(b, MemRip(a.chunk, a.off)); - NewMem(lIdx, MemIdx(b, r, size, o), kWord, 8, false); - end else begin - MulI(Top, size); - PushAdr(a); - Op(sPlus, kWord, 8, false); - end; -end; - -{ Pops lo and hi, and the address of the array or slice at a if it is - on the stack, and makes the slice lo..hi of it, with elements of size - bytes, in the frame at tmp; the array has n elements. } -procedure Slice(const a: TAdr; isArray: boolean; n, size, tmp: int64; checked: boolean; const p: TPos); -var m, ml: TMem; -begin - PopTo(RDX); - PopTo(RCX); - if a.base = bSlot then ClobberArgs; { Place loads its slot into rdi } - if a.base = bReg then ml := InRegister(a.hi) { a slice in registers } - else begin - m := Place(a, RDI); - ml := m; ml.disp := ml.disp + 8; - end; - if checked then begin - { two checks, both unsigned, so that a negative bound fails too: - hi against the length, then lo against hi } - if isArray then begin CmpI(RDX, n); ml := NoMem end - else if a.base = bReg then Alu(aluCmp, RDX, a.hi) - else AluM(aluCmp, RDX, ml); - Check(ccBE, 1, p, RCX, ml, n, -1); - Alu(aluCmp, RCX, RDX); - Check(ccBE, 1, p, RCX, ml, n, -1); - end; - MovRR(RAX, RDX); - Alu(aluSub, RAX, RCX); - Store(Mem(RBP, tmp + 8), RAX, 8); - MulI(RCX, size); - if isArray then Lea(RAX, m) - else if a.base = bReg then MovRR(RAX, a.chunk) - else Load(RAX, m, 8, false); - Alu(aluAdd, RAX, RCX); - Store(Mem(RBP, tmp), RAX, 8); -end; - -{ COPY: the elements of the slice in the frame at sOff, of size bytes - each, to the start of the one at dOff, which must be at least as long - (the source may be shorter), as one block; backwards when the - destination is above the source, so that an overlap comes out right. } -procedure CopySlice(dOff, sOff, size: int64; checked: boolean; const p: TPos); -var ml: TMem; L, E: longint; -begin - ClobberArgs; - Load(RDX, Mem(RBP, sOff + 8), 8, false); - if checked then begin - ml := Mem(RBP, dOff + 8); - MovRI(RAX, 0); - AluM(aluCmp, RDX, ml); - Check(ccBE, 1, p, RAX, ml, 0, -1); - end; - MovRR(RCX, RDX); - MulI(RCX, size); - Load(RSI, Mem(RBP, sOff), 8, false); - Load(RDI, Mem(RBP, dOff), 8, false); - Alu(aluCmp, RDI, RSI); - L := NoLabel; - Jcc(ccBE, L); { the destination is not above: forwards, at L } - { backwards: std makes rep movsb run downward, so it starts at the - last byte of each } - Lea(RSI, MemIdx(RSI, RCX, 1, -1)); - Lea(RDI, MemIdx(RDI, RCX, 1, -1)); - Std; - RepMovsb; - Cld; - E := NoLabel; - Jmp(E); - FixLink(L); - RepMovsb; - FixLink(E); -end; - -{ Pops a pointer, lo and hi, and makes the slice p[lo..hi] at tmp. Its - bounds can't be known, but it can't run backwards. } -procedure SlicePtr(size, tmp: int64; checked: boolean; const p: TPos); -begin - ClobberArgs; - PopTo(RDX); - PopTo(RCX); - PopTo(RDI); - if checked then begin - Alu(aluCmp, RCX, RDX); - Check(ccLE, 3, p, RCX, NoMem, 0, -1); - end; - MovRR(RAX, RDX); - Alu(aluSub, RAX, RCX); - Store(Mem(RBP, tmp + 8), RAX, 8); - MulI(RCX, size); - Alu(aluAdd, RCX, RDI); - Store(Mem(RBP, tmp), RCX, 8); -end; - -{ Calls } - -{ The call c, its c.n arguments the values on top of the stack, in - registers, noted as constants or spilled. They go to registers or the - machine's stack, the procedure is called, and its result, if any, - comes back: one value is pushed, two results are pushed as two values, - a slice or a record is stored in the temporary c.ret. - - ni and nf count the integer and the real registers used so far, k the - arguments on the machine's stack, and pad is 1 when a padding quadword - is needed. } - -procedure Call(var c: TCall); -var - res: PType; i, ni, nf, k, pad, r, first: longint; - onStack: array[0..63] of boolean; late: array[4..5] of longint; -begin - { the arguments are the c.n values on top, where computing them left - them; the registers in use under them are saved around the call } - ClobberArgs; - first := depth - c.n; - SpillBelow(first); - res := c.sig^.base; - c.ret := 0; - ni := 0; nf := 0; - if (res <> nil) and (BehindPointer(res) or (res^.form = fSlice)) then begin - c.ret := AllocTemp(res^.size, res^.align); - if BehindPointer(res) then ni := 1; - end; - { the System V classes: each argument in the next free register of - its kind, or else on the stack } - k := 0; - for i := 0 to c.n - 1 do begin - if c.isF[i] then begin onStack[i] := nf >= 8; if nf < 8 then inc(nf) end - else begin - { a slice's words both go in registers, or both on the stack } - if (i > 0) and c.pair[i - 1] then onStack[i] := onStack[i - 1] - else if c.pair[i] then onStack[i] := ni > 4 - else onStack[i] := ni >= 6; - if not onStack[i] then inc(ni); - end; - if onStack[i] then inc(k); - end; - { System V wants rsp a multiple of 16 at the call. A procedure's body - has it so (push rbp, and a frame size that is a multiple of 16), so - a quadword of padding makes the count pushed since even. The stack - arguments go right to left, so that the first is at the lowest - address. } - pad := ord(odd(pushed + k)); - if pad <> 0 then AluI(aluSub, RSP, 8); - for i := c.n - 1 downto 0 do - if onStack[i] then begin - ValueTo(first + i, RAX); - Push(RAX); - end; - ni := 0; nf := 0; - late[4] := -1; late[5] := -1; - if (c.ret <> 0) and BehindPointer(res) then begin Lea(RDI, Mem(RBP, c.ret)); ni := 1 end; - { rdi, rsi, rdx, rcx and the xmm registers first; r8 and r9 last, as - they are stack registers and may hold arguments not yet moved: late - is the value for each. The fifth goes through rax, so that writing r8 - doesn't destroy a value still wanted for r9. } - for i := 0 to c.n - 1 do - if not onStack[i] then - if c.isF[i] then begin - XValueTo(first + i, nf); - inc(nf); - end else begin - if ni < 4 then ValueTo(first + i, IntRegs[ni]) else late[ni] := first + i; - inc(ni); - end; - if late[4] >= 0 then ValueTo(late[4], RAX); - if late[5] >= 0 then ValueTo(late[5], R9); - if late[4] >= 0 then MovRR(R8, RAX); - for i := 1 to c.n do Drop; - { a procedure taking ... is told in al how many xmm registers it got } - if c.sig^.variadic then MovRI(RAX, nf); - if c.ext then CallM(MemRip(c.chunk, 0)) - else if c.chunk >= 0 then CallChunk(c.chunk) - else begin - { r11 is scratch: caller-saved, carrying no argument, and free, - as the value stack was spilled above } - Load(R11, Mem(RBP, c.target), 8, false); - CallR(R11); - end; - if k + pad > 0 then AluI(aluAdd, RSP, 8 * (k + pad)); - { the variables in xmm registers, which the call may have changed, - from their slots } - for i := 0 to 3 do - if regMask and (1 shl (XBit + i)) <> 0 then MovsXM(XVarRegs[i] - XmmVar, Mem(RBP, homes[i]), false); - { the result: a slice in rax and rdx goes to the caller's temporary, - two results on the stack, the first under the second, and a single - value on top } - if res = nil then - { nothing comes back } - else if res^.form = fSlice then begin - Store(Mem(RBP, c.ret), RAX, 8); - Store(Mem(RBP, c.ret + 8), RDX, 8); - end else if InTwoRegs(res) then begin - MovRR(Target, RAX); Computed(kWord); - MovRR(Target, RDX); Computed(kWord); - end else if (c.ret = 0) and (res^.form = fReal) then begin - MovX(XTarget, 0); - Computed(KindOf(res)); - end else if c.ret = 0 then begin - r := Target; - MovRR(r, RAX); - if res^.form = fBool then Extend(r, 1, false) - else if (res^.form = fInt) and (res^.size < 8) then Extend(r, res^.size, res^.signed); - Computed(KindOf(res)); - end; -end; - -{ Frames } - -{ A slot of size bytes in the frame: its offset from rbp, negative, as - the frame grows down. A temporary is released at the end of its - statement (TempMark, ReleaseTemps); AllocPerm's lasts the procedure. } -function AllocTemp(size, align: int64): int64; -begin - if align < 1 then align := 1; - frameTop := AlignUp(frameTop + size, align); - if frameTop > frameMax then frameMax := frameTop; - AllocTemp := -frameTop; -end; - -function AllocPerm(size, align: int64): int64; -begin - AllocPerm := AllocTemp(size, align); - permTop := frameTop; -end; - -function TempMark: int64; -begin - TempMark := frameTop; -end; - -{ The slots allocated since the mark m are free again, but those - AllocPerm made stay } -procedure ReleaseTemps(m: int64); -begin - if m < permTop then m := permTop; - frameTop := m; -end; - -{ Every slot used so far stays reserved for the rest of the procedure: - a deferred statement's temporaries live until it runs. } -procedure KeepTemps; -begin - frameTop := frameMax; - permTop := frameMax; -end; - -{ The parameters' places: each in a frame slot of its own, stored there - from its register on entry, or above the frame where the caller - pushed it. A var parameter, and a record or array passed by value, - holds an address (ind). } -procedure BeginProc(sig: PType; params: PObj); -var p: PObj; ni, nf, k: longint; stackOff: int64; f: boolean; -begin - frameTop := 0; frameMax := 0; permTop := 0; - ResetStack(0, 0); - exitL := NoLabel; - numIn := 0; - lost := false; - kept := 0; - resType := sig^.base; - procParams := params; - regMask := 0; - ni := 0; nf := 0; stackOff := 16; { stackOff: above the saved rbp and the return address } - if (resType <> nil) and BehindPointer(resType) then begin - retSlot := AllocPerm(8, 8); - inReg[0] := RDI; inSlot[0] := retSlot; inSize[0] := 8; inObj[0] := nil; - numIn := 1; ni := 1; - end; - p := params; - while p <> nil do begin - p^.ind := p^.isVar or (IsAggregate(p^.typ) and (p^.typ^.form <> fSlice)); - f := (p^.typ^.form = fReal) and not p^.isVar; - if (p^.typ^.form = fSlice) and not p^.isVar then begin - { its two words, in two registers or both on the stack } - if ni <= 4 then begin - p^.val := AllocPerm(16, 8); - for k := 0 to 1 do begin - inReg[numIn] := IntRegs[ni]; inSlot[numIn] := p^.val + 8 * k; - inSize[numIn] := 8; inObj[numIn] := p; - inc(numIn); inc(ni); - end; - end else begin - p^.val := stackOff; - inc(stackOff, 16); - end; - end else if (f and (nf < 8)) or (not f and (ni < 6)) then begin - p^.val := AllocPerm(8, 8); - { a real's register, xmm nf, is told from an integer register by - a negative number (EnterBody decodes it) } - 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; - inc(numIn); - end else begin - p^.val := stackOff; - inc(stackOff, 8); - end; - p := p^.next; - end; - paramTop := frameTop; -end; - -{ The frame as BeginProc left it, with the parameters' slots only: the - locals are given theirs again once their registers are chosen. } -procedure ResetLocals; -begin - frameTop := paramTop; frameMax := paramTop; permTop := paramTop; -end; - -{ The register the word (0, or 1 for a slice's second) of parameter o - arrives in, or -1 if it comes on the stack or in an xmm register } -function ArrivesIn(o: PObj; word: longint): longint; -var i: longint; -begin - ArrivesIn := -1; - for i := 0 to numIn - 1 do - if (inObj[i] = o) and (inSlot[i] = o^.val + 8 * word) and (inReg[i] >= 0) then ArrivesIn := inReg[i]; -end; - -{ Parameter o, of a procedure that calls nothing, stays in the register - it arrives in if that is rdi or rsi, which only a call or a copy needs: - no register is saved for it, and nothing is moved. A slice stays only - if it has both. If the procedure turns out to copy after all, lost is - set, and it is compiled again with o in memory. } -procedure KeepArrived(o: PObj); -var r: longint; -begin - r := ArrivesIn(o, 0); - if o^.typ^.form = fSlice then begin - if (r = RDI) and (ArrivesIn(o, 1) = RSI) then begin o^.reg := RDI; o^.reg2 := RSI end; - end else if (r = RDI) or (r = RSI) then o^.reg := r; -end; - -{ Whether parameter o is kept where it arrived } -function KeptIn(o: PObj): boolean; -begin - KeptIn := (o^.reg = RDI) or (o^.reg = RSI); -end; - -{ The locals in memory have their slots: the prologue zeroes those and - nothing below. The procedure keeps variables in the registers of - mask, which are saved next, a quadword each, in slots that need no - zeroing; the frame as it then stands is where a second try at the - body starts. } -procedure UseRegs(mask: longint); -var i, k: longint; p: PObj; -begin - zeroTop := permTop; - regMask := mask; - { the parameters left in rdi and rsi, as they arrived } - kept := 0; - p := procParams; - while p <> nil do begin - if p^.reg in [RDI, RSI] then kept := kept or (1 shl p^.reg); - if p^.reg2 in [RDI, RSI] then kept := kept or (1 shl p^.reg2); - p := p^.next; - end; - k := 0; - for i := 0 to 4 do if mask and (1 shl i) <> 0 then inc(k); - if k > 0 then saveAt := AllocPerm(8 * k, 8); - frameAt[0] := frameTop; frameAt[1] := frameMax; frameAt[2] := permTop; -end; - -{ The variable in xmm register r of XVarRegs has a slot of 8 bytes at - slot, kept as it changes } -procedure XHome(r: longint; slot: int64); -begin - homes[r - XVarRegs[0]] := slot; -end; - -procedure MarkCode(var m: TCodeMark); -begin - m.pc := pc; m.fixups := numFixups; m.lines := numLines; m.said := SaidCount; - m.fails := numFails; -end; - -{ The code made since m taken back, as if it had never been made; the - frame is left as it is } -procedure Rewind(const m: TCodeMark); -begin - pc := m.pc; numFixups := m.fixups; numLines := m.lines; Unsay(m.said); - numFails := m.fails; -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); - numFails := 0; - lost := false; - 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 in memory are zeroed, from the parameters' slots down to - zeroTop: the parameters are stored over their slots next, the - registers of variables are zeroed in place, their save slots are - written before they are read, and so is every temporary. } -procedure EnterBody(c, line: longint); -var i, top, r: longint; n: int64; p: PObj; -begin - BeginChunk(c); - codeChunk := c; - NoteLine(line, 1); { a declaration starts a line } - Push(RBP); - MovRR(RBP, RSP); - Say('sub rsp, frame'); - { sub rsp, imm32: always the form with a 32-bit field, so that EndProc - can patch the frame's size in } - Put1($48); Put1($81); Put1($EC); - frameFix := pc; Put4(0); - n := (AlignUp(zeroTop, 8) - paramTop) div 8; - if n > 0 then MovRI(RAX, 0); - if n <= 4 then - for i := 1 to n do Store(Mem(RBP, -paramTop - 8 * i), RAX, 8) - else begin - { a quadword at a time: r10 runs from -n up to 0, and the store's - address is scaled by it } - MovRI(R10, -n); - top := pc; - Store(MemIdx(RBP, R10, 8, -paramTop), RAX, 8); - AluI(aluAdd, R10, 1); - JccBack(ccNE, top); - end; - { each register that holds a variable is saved, for the caller, and - zeroed, as a variable starts at zero } - chunks^[c].saveMask := regMask and (1 shl XBit - 1); - 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; - { and each xmm register that holds a variable, zeroed, as its slot - is: the caller keeps its own } - for i := 0 to 3 do - if regMask and (1 shl (XBit + i)) <> 0 then begin - MovRI(RAX, 0); - MovqXR(XVarRegs[i] - XmmVar, RAX); - end; - { the parameters that came in registers, to their slots or, for a - register variable, to its register: a slice's second word, the one - for the slot 8 bytes into its own, to its length's } - for i := 0 to numIn - 1 do - if inReg[i] < 0 then begin - MovsMX(Mem(RBP, inSlot[i]), -1 - inReg[i], false); - if inObj[i]^.reg <> 0 then MovX(inObj[i]^.reg - XmmVar, -1 - inReg[i]); - end - else if (inObj[i] <> nil) and (inObj[i]^.reg <> 0) then begin - r := inObj[i]^.reg; - if inSlot[i] <> inObj[i]^.val then r := inObj[i]^.reg2; - if r <> inReg[i] then MovRR(r, inReg[i]); { else it is kept where it is } - if inSize[i] < 8 then Extend(r, inSize[i], inObj[i]^.typ^.signed); - end else Store(Mem(RBP, inSlot[i]), inReg[i], inSize[i]); - { a register variable's parameter that came on the stack, above the - frame (val > 0), is loaded from there } - p := procParams; - while p <> nil do begin - if (p^.reg <> 0) and (p^.val > 0) then - if p^.typ^.form = fReal then MovsXM(p^.reg - XmmVar, Mem(RBP, p^.val), p^.typ^.size = 4) - else if p^.typ^.form in [fInt, fBool, fEnum, fSet] then - Load(p^.reg, Mem(RBP, p^.val), p^.typ^.size, p^.typ^.signed) - else begin - Load(p^.reg, Mem(RBP, p^.val), 8, false); - if p^.typ^.form = fSlice then Load(p^.reg2, Mem(RBP, p^.val + 8), 8, false); - end; - p := p^.next; - end; -end; - -{ Pops one of several results, a value of size bytes, into its place - off bytes into the caller's, behind the hidden pointer. } -procedure ResultTo(off: int64; size: longint); -var r: longint; real: boolean; -begin - r := Top; - real := IsReal(depth - 1); - Drop; - Load(RCX, Mem(RBP, retSlot), 8, false); - if real then MovsMX(Mem(RCX, off), r, size = 4) - else Store(Mem(RCX, off), r, size); -end; - -{ Pops an address, and copies size bytes from it to the result, off - bytes into it. } -procedure CopyResult(off, size: int64); -begin - ClobberArgs; - PopTo(RSI); - Load(RDI, Mem(RBP, retSlot), 8, false); - if off <> 0 then Lea(RDI, Mem(RDI, off)); - CopyBytes(size); -end; - -{ return: the result, a value on top, goes in rax or xmm0; two words, - the two values on top, in rax and rdx; one behind the hidden pointer - goes back with that pointer in rax. } -procedure ReturnJump; -begin - if resType <> nil then - if BehindPointer(resType) then Load(RAX, Mem(RBP, retSlot), 8, false) - else if InTwoRegs(resType) then begin - PopTo(RDX); - PopTo(RAX); - end else begin - if resType^.form = fReal then begin XValueTo(depth - 1, 0); Drop end - else PopTo(RAX); - end; - Jmp(exitL); -end; - -{ The first of what try does where the error isn't nil (the report, 7.8): - the machine's stack made even, as the deferred statements about to be - run expect to find it. try can stand among the arguments of another - call, where quadwords have been pushed. Nothing is lost: the frame is - above rsp, and the code returns through the frame pointer. } -procedure TryAlign; -begin - AluI(aluAnd, RSP, -16); -end; - -{ The rest of it: the procedure returns the error in the frame slot, and - a zero for each of its other results. Only code is made: no entry of - the stack of values is touched, since the code that follows is the - code for an error that is nil, with the stack as it was. } -procedure TryReturn(slot: int64); -var f: PObj; -begin - if BehindPointer(resType) then begin - Load(RDI, Mem(RBP, retSlot), 8, false); - MovRI(RCX, resType^.size); - MovRI(RAX, 0); - RepStosb; - f := resType^.fields; - while f^.next <> nil do f := f^.next; - Load(RCX, Mem(RBP, slot), 8, false); - Load(RDX, Mem(RBP, retSlot), 8, false); - Store(Mem(RDX, f^.val), RCX, 8); - Load(RAX, Mem(RBP, retSlot), 8, false); - end else if InTwoRegs(resType) then begin - Load(RDX, Mem(RBP, slot), 8, false); - MovRI(RAX, 0); - end else Load(RAX, Mem(RBP, slot), 8, false); - Jmp(exitL); -end; - -{ The end of the procedure in chunk c: the code that returns, and the - frame's size, known only now, patched into its prologue. If it is - open, running off its end, it returns zeros. } -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'); - if open then begin - if BehindPointer(resType) then begin - Load(RDI, Mem(RBP, retSlot), 8, false); - MovRI(RCX, resType^.size); - MovRI(RAX, 0); - RepStosb; - Load(RAX, Mem(RBP, retSlot), 8, false); - end else begin - 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 - if regMask and (1 shl i) <> 0 then begin - Load(VarRegs[i], Mem(RBP, saveAt + 8 * n), 8, false); - inc(n); - end; - Leave; - Ret; - EndFails; - n := AlignUp(frameMax, 16); - if n < 16 then n := 16; - if n > high(longint) then Mark('frame too big'); - Put4At(frameFix, n); - { the listing's text for the sub, which starts 3 bytes (REX.W, opcode, - ModRM) before its immediate } - Restate(frameFix - 3, 'sub rsp, ' + IntStr(n)); - EndChunk(c); -end; - -{ A deferred statement is compiled where it stands, as a subroutine of - its procedure that the code jumps over, in the procedure's own frame - (the same rbp), so that it sees all its variables; DeferBegin gives its address - and starts it, with the return address pushed. The stack is empty - where it is called, and where it begins. } -function DeferBegin(var L, saved: longint): longint; -begin - Jmp(L); - saved := pushed; - pushed := 1; - DeferBegin := pc; -end; - -procedure DeferEnd(L, saved: longint); -begin - KeepTemps; - Ret; - FixLink(L); - pushed := saved; -end; - -procedure RunDefer(at: longint); -begin - CallBack(at); -end; - -{ The entry point, _start, and its chunk: it saves argc and argv, and - the address of the places for Rt; runs every used module's body, then - main; and ends with Rt.exit, its status main's or 0. A dynamic program - starts as C's crt1 does, through __libc_start_main(main, argc, argv, - nil, nil, rtld_fini, stack_end), with rsp aligned; its main first - gives Rt C's exit, in cExit. - - dynamic: the program uses C. first: the first module, whose chain - gives the order of the bodies. main: the program's main procedure, or - nil. cExit and exitProc: the chunks of Rt's cExit and exit. The - first numLinks of links: the addresses Rt is given, of what the program has: the places, and - the profiler and calls; what it isn't given, nothing reaches, and the - linker leaves out. } -function EntryPoint(dynamic: boolean; first: PModule; main: PObj; cExit, exitProc: longint; const links: array of TLink; numLinks: longint): longint; -var entry, start, i: longint; m: PModule; -begin - entry := NewChunk(secText, -1, Intern('_start', 6)); - if dynamic then begin - start := NewChunk(secText, -1, Intern('main', 4)); - BeginChunk(entry); - { at the start rdx holds rtld_fini, from the dynamic loader, and the - stack argc, then argv } - MovRI(RBP, 0); { no frame above, where a trace stops } - MovRR(R9, RDX); { rtld_fini, the sixth argument } - Pop(RSI); { argc, the second } - MovRR(RDX, RSP); { argv, the third } - AluI(aluAnd, RSP, -16); - Push(RAX); { padding, so that the next push, the seventh } - Push(RSP); { argument, stack_end, leaves rsp aligned } - MovRI(R8, 0); { fini and init: none } - MovRI(RCX, 0); - Lea(RDI, MemRip(start, 0)); { main, the first argument } - CallM(MemRip(ExternChunk(Intern('__libc_start_main', 17)), 0)); - Ud2; { it never returns } - EndChunk(entry); - BeginChunk(start); - Push(RBP); { aligns the stack again } - Store(MemRip(argcChunk, 0), RDI, 8); - Store(MemRip(argvChunk, 0), RSI, 8); - Load(RAX, MemRip(ExternChunk(Intern('exit', 4)), 0), 8, false); - Store(MemRip(cExit, 0), RAX, 8); - end else begin - start := entry; - BeginChunk(entry); - Load(RAX, Mem(RSP, 0), 8, false); - Store(MemRip(argcChunk, 0), RAX, 8); - Lea(RAX, Mem(RSP, 8)); - Store(MemRip(argvChunk, 0), RAX, 8); - end; - for i := 0 to numLinks - 1 do begin - Lea(RAX, MemRip(links[i].chunk, 0)); - Store(MemRip(links[i].into, 0), RAX, 8); - end; - m := first; - while m <> nil do begin - if m^.used and (m^.body >= 0) then CallChunk(m^.body); - m := m^.next; - end; - if main <> nil then CallChunk(main^.chunk); - if (main <> nil) and (main^.typ^.base <> nil) then MovRR(RDI, RAX) else MovRI(RDI, 0); - CallChunk(exitProc); - Ud2; { exit never returns: trap if it does } - EndChunk(start); - { Rt.fail, for the failures of each kind: the place is where the - check's call is. The return address is the next instruction's, which - may belong to another line; one byte back is inside the call, so the - lookup finds the call's line. rsp is aligned for the call, as the - check's code may have pushed an odd number of quadwords. rdi and rsi - as the failing code had them go on the stack, as Rt.fail's last two - arguments, and a comes in rax (EndFails). } - for i := 0 to High(failStubs) do - if failStubs[i] >= 0 then begin - BeginChunk(failStubs[i]); - Load(R8, Mem(RSP, 0), 8, false); - AluI(aluSub, R8, 1); - AluI(aluAnd, RSP, -16); - Push(RSI); - Push(RDI); - MovRR(RSI, RAX); - MovRI(RDI, i); - CallChunk(rtFail); - Ud2; - EndChunk(failStubs[i]); - end; - EntryPoint := entry; -end; - -{ A code procedure: its instructions, read by the assembler (x64.pas), - are the whole of chunk c } -procedure CodeProc(c: longint; constExpr: TConstFn); -begin - BeginChunk(c); - Assemble(constExpr); - EndChunk(c); -end; - -initialization - ResetStack(0, 0); - rtFail := NewChunk(secText, Intern('Rt', 2), Intern('fail', 4)); - argcChunk := NewChunk(secBss, -1, Intern('argc', 4)); - SetBss(argcChunk, 8, 8); - argvChunk := NewChunk(secBss, -1, Intern('argv', 4)); - SetBss(argvChunk, 8, 8); -end. diff --git a/seed/item.pas b/seed/item.pas deleted file mode 100644 index e2afc4f..0000000 --- a/seed/item.pas +++ /dev/null @@ -1,1575 +0,0 @@ -{ item.pas: operands, their types, and what they mean. - - The parser describes each operand as an item (TItem), as in Wirth's - compilers: a constant, a variable at an address it can name, a value - on gen's stack, a procedure, a string. The routines here check the - items' types, fold constants, and have gen.pas make the code, as calls - of its stack machine; nothing here knows the machine. - - Depends on: scan for errors, sym for types, chunk for data, gen for - code. - Leaves out: the language's syntax, which is parse.pas; the machine, - which is gen.pas. } - -unit item; - -{$mode objfpc}{$H-} - -interface - -uses scan, diag, sym, chunk, gen; - -type - TMode = (mConst, mVar, mStack, mProc, mType, mStr, mBuiltin, mCase, mNone, mCond, - mWords); { two results of a call, on the stack, the first under the second } - - TItem = record - mode: TMode; - typ: PType; - rel: TSym; { mCond: the comparison of the two integers on - the stack, not yet made, as Wirth's compilers - keep a condition } - relSigned: boolean; - fj, tj: longint; { mCond: the chains of jumps already made that are - taken when the whole condition is false, and when - it is true, not yet given a place (and, or and - not make them); see gen's JumpOut } - val: int64; { mConst: the value, an F64's bits; mStr: its length } - base: TBase; { mVar: what the address is relative to } - chunk: longint; { mVar with bGlobal, mStr: the chunk; bSlot: the slot } - off: int64; { mVar: added to the base } - vol: boolean; { mVar: reached through ^VOLATILE } - isVar: boolean; { mVar: a variable of the program, not a temporary } - odd: boolean; { mVar: in a packed record, so maybe misaligned } - ro: boolean; { mVar: another module's exported variable, or part - of one, which only that module changes } - deref: boolean; { mVar: at an address from a pointer, which may be - nil and isn't tested yet (NilTest) } - obj: PObj; { mProc, mBuiltin, mCase; mVar: the variable named } - pos: TPos; { where it is in the source, for messages } - end; - -var - demoted: boolean; { Address wanted a register variable's address: its - procedure is compiled again, the variable in memory } - checks: boolean; { the module's index and slice checks are made: it - doesn't say check off } - -procedure MakeConst(var x: TItem; t: PType; v: int64); -function What(const x: TItem): shortstring; -procedure MakeReal(var x: TItem; r: double); -procedure MakeStr(var x: TItem); -procedure MakeItem(var x: TItem; o: PObj); -function RealOf(const x: TItem): double; -function FrameAdr(off: int64): TAdr; -function GlobalAdr(c: longint): TAdr; -function AdrOf(const x: TItem): TAdr; - -procedure UsesReals(const p: TPos); -procedure Value(var x: TItem); -procedure Address(var x: TItem); -procedure Discard(const x: TItem); -procedure NilTest(var x: TItem); -procedure Coerce(var x: TItem; t: PType); -procedure CoerceExact(var x: TItem; t: PType; const help: shortstring); -procedure NotReadOnly(const x: TItem); -procedure Assign(var dst, src: TItem); -procedure CopyToTemp(var x: TItem); -function ToSlot(var x: TItem): int64; - -procedure Deref(var x: TItem); -procedure Field(var x: TItem; f: PObj); -procedure IndexPrep(var x: TItem); -procedure Index(var x, y: TItem); -procedure SliceLo(var lo: TItem); -procedure Slice(var x, lo, hi: TItem); - -procedure Neg(var x: TItem); -procedure NotOp(var x: TItem); -procedure Complement(var x: TItem); -procedure Op1(op: TSym; var x: TItem; var L: longint); -procedure Op2(op: TSym; var x, y: TItem; L: longint); -function IsWord(t: PType): boolean; -procedure Convert(var x: TItem; t: PType); - -procedure BeginCall(var c: TCall; var x: TItem); -procedure PassArg(var c: TCall; var a: TItem); -procedure EndCall(var c: TCall; var x: TItem); - -procedure ZeroTemp(var x: TItem; t: PType); -procedure Construct(var x: TItem; c: PObj); -procedure SetField(const x: TItem; f: PObj; var a: TItem); -function MatchBegin(var x: TItem): int64; -procedure MatchTag(p: int64; tag: int64; var L: longint); -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); -function ScalarSize(t: PType): longint; -procedure ForStep(o: PObj; step: int64); -procedure ForCmp(o: PObj; const lim: TItem; op: TSym; var L: longint); -procedure ForNext(o: PObj; const lim: TItem; step: int64; var exitL: longint; top, body: longint); - -procedure BeginProc(sig: PType; params: PObj); -procedure ReturnValue(var x: TItem); -procedure ReturnField(f: PObj; var x: TItem); -procedure ReturnAll(var x: TItem); -procedure ReturnNone; -procedure Pin(var x: TItem); -procedure IncDec(var v, k: TItem; dec: boolean); -procedure CopyDest(var d: TItem); -procedure CopyFrom(var d, s: TItem); -procedure Msg(var x: TItem); -function ErrorChunk(var x: TItem; module, name: longint): longint; - -implementation - -const - { the comparison that holds when op doesn't, for integers } - Negated: array[sEql..sGeq] of TSym = (sNeq, sEql, sGeq, sGtr, sLeq, sLss); - -var - result: PType; { the result of the procedure being compiled, or nil } - -{ Items } - -procedure MakeConst(var x: TItem; t: PType; v: int64); -var p: TPos; -begin - p := x.pos; - FillChar(x, SizeOf(x), 0); - x.pos := p; - x.mode := mConst; - x.typ := t; - x.val := v; -end; - -{ A real constant: untyped, unless typed later. Its value is an F64, - which for an F32 is one an F32 can hold. } -procedure MakeReal(var x: TItem; r: double); -begin - MakeConst(x, tRConst, 0); - Move(r, x.val, 8); -end; - -function IsF32(t: PType): boolean; -begin - IsF32 := (t^.form = fReal) and (t^.size = 4); -end; - -{ Gives a real constant the real type t, rounded to it. } -procedure RealTo(var x: TItem; t: PType); -var r: double; -begin - r := RealOf(x); - if IsF32(t) then MakeReal(x, single(r)) else MakeReal(x, r); - x.typ := t; -end; - -function RealOf(const x: TItem): double; -var r: double; -begin - Move(x.val, r, 8); - RealOf := r; -end; - -{ The current string literal, as an item of its own chunk. } -procedure MakeStr(var x: TItem); -begin - FillChar(x, SizeOf(x), 0); - x.mode := mStr; - x.typ := tStr; - x.val := slen; - x.chunk := NewChunk(secRodata, -1, -1); - SetData(x.chunk, @sbuf, slen + 1, 1); -end; - -function FrameAdr(off: int64): TAdr; -begin - FrameAdr.base := bFrame; - FrameAdr.chunk := -1; - FrameAdr.off := off; - FrameAdr.hi := 0; -end; - -function GlobalAdr(c: longint): TAdr; -begin - GlobalAdr.base := bGlobal; - GlobalAdr.chunk := c; - GlobalAdr.off := 0; - GlobalAdr.hi := 0; -end; - -{ Where the variable x is, for gen; a slice in registers has two } -function AdrOf(const x: TItem): TAdr; -begin - AdrOf.base := x.base; - AdrOf.chunk := x.chunk; - AdrOf.off := x.off; - AdrOf.hi := 0; - if x.base = bReg then AdrOf.hi := x.obj^.reg2; -end; - -{ An item for "found ...": a constant without a type of its own as it - is written, so that "found 1.5" says what is wrong; else its type. } -function What(const x: TItem): shortstring; -begin - if (x.mode = mConst) and ((x.typ = tConst) or (x.typ = tRConst)) then What := Source(x.pos) - else What := TypeName(x.typ); -end; - -{ Two operands of different types. Numbers convert, so say how. } -procedure Mismatch(const x, y: TItem; xt, yt: PType); -var msg: shortstring; -begin - msg := TypeName(xt) + ' and ' + TypeName(yt) + ' are different types'; - if (IsInt(xt) or (xt^.form = fReal)) and (IsInt(yt) or (yt^.form = fReal)) - and (xt <> tConst) and (xt <> tRConst) then - MarkHelp(Join(x.pos, y.pos), msg, 'convert one to the other''s type, as in ' + TypeName(xt) + '(' + Source(y.pos) + ')') - else MarkAt(Join(x.pos, y.pos), msg); -end; - -{ An item that is not a value, by what it is. } -procedure NotValue(const x: TItem); -begin - case x.mode of - mType: MarkAt(x.pos, TypeName(x.typ) + ' is a type, not a value'); - mBuiltin: MarkAt(x.pos, NameOf(x.obj^.name) + ' is a built-in procedure, not a value'); - mCase: MarkAt(x.pos, NameOf(x.obj^.name) + ' is a case, not a value'); - mNone: - if x.obj <> nil then MarkAt(x.pos, NameOf(x.obj^.name) + ' returns nothing') - else MarkAt(x.pos, 'the procedure returns nothing'); - else MarkAt(x.pos, 'a string can''t be an operand'); - end; -end; - -procedure MakeItem(var x: TItem; o: PObj); -begin - FillChar(x, SizeOf(x), 0); - x.typ := o^.typ; - x.obj := o; - case o^.cls of - oConst: - if o^.typ = tStr then begin - x.mode := mStr; x.val := o^.val; x.chunk := o^.chunk - end else if o^.typ^.form in [fArray, fRecord] then begin - { an array or record constant: a variable in read-only data, not one of - the program's, so nothing can change it } - x.mode := mVar; x.base := bGlobal; x.chunk := o^.chunk - end else begin - x.mode := mConst; x.val := o^.val - end; - oVar: begin - x.mode := mVar; - x.ro := (o^.lev = 0) and (o^.module <> curModule); - x.isVar := not x.ro; - if o^.ext then begin - PushVar(GlobalAdr(o^.chunk), 8, false, kWord); - x.base := bStack; - end else if o^.lev = 0 then begin - 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; - end; - oProc: x.mode := mProc; - oType: x.mode := mType; - oBuiltin: x.mode := mBuiltin; - oCase: x.mode := mCase; - else Mark(NameOf(o^.name) + ' is not a value'); - end; -end; - -function ScalarSize(t: PType): longint; -begin - if t^.form in [fInt, fBool, fEnum, fSet, fReal] then ScalarSize := t^.size - else ScalarSize := 8; -end; - -{ The width an operation on t is brought back to, and whether signed } -function IntSize(t: PType): longint; -begin - if t^.form = fInt then IntSize := t^.size else IntSize := 8; -end; - -function Signed(t: PType): boolean; -begin - Signed := ((t^.form = fInt) and t^.signed) or (t^.form = fConst); -end; - -function Cut(v: int64; t: PType): int64; -begin - Cut := v; - if t^.form <> fInt then exit; - case t^.size of - 1: if t^.signed then Cut := shortint(v) else Cut := byte(v); - 2: if t^.signed then Cut := smallint(v) else Cut := word(v); - 4: if t^.signed then Cut := longint(v) else Cut := longword(v); - end; -end; - -{ Code computing with a real is noted on its chunk, at the first place, - for a target without reals (report 5.1) to refuse if the chunk turns - out to be used. A real moved whole, as a record's bytes are copied, - needs nothing the target lacks, and isn't noted. } -procedure UsesReals(const p: TPos); -begin - if (codeChunk >= 0) and not chunks^[codeChunk].reals then begin - chunks^[codeChunk].reals := true; - chunks^[codeChunk].realsAt := p; - end; -end; - -{ x, at an address from a pointer, is about to be used: gen tests the - address for nil where the machine wouldn't stop at it (report section - 10), from its offset to its end. } -procedure NilTest(var x: TItem); -begin - if (x.mode = mVar) and x.deref then CheckNil(x.off + x.typ^.size, x.pos); - x.deref := false; -end; - -{ x's value, on top of the stack } -procedure Value(var x: TItem); -var f: single; -begin - if x.mode = mCond then begin - if (x.fj = NoLabel) and (x.tj = NoLabel) then Compare(x.rel, kWord, x.relSigned) - else CondValue(Negated[x.rel], x.relSigned, x.fj, x.tj); - x.mode := mStack; - exit; - end; - if x.typ^.form = fReal then UsesReals(x.pos); - NilTest(x); - case x.mode of - mConst: - if (x.typ^.form = fError) and (x.val > 0) then PushAdr(GlobalAdr(x.val - 1)) - else if IsF32(x.typ) then begin - f := RealOf(x); - PushConst(kF32, PLongword(@f)^); - end else PushConst(KindOf(x.typ), x.val); - mVar: begin - if not IsScalar(x.typ) then MarkAt(x.pos, 'expected a single value, found ' + What(x)); - PushVar(AdrOf(x), ScalarSize(x.typ), (x.typ^.form = fInt) and x.typ^.signed, KindOf(x.typ)); - end; - mStack: ; - mProc: begin - if x.obj^.isCode and (x.obj^.typ^.base <> nil) and x.obj^.typ^.base^.tuple then - MarkAt(x.pos, 'a code procedure with two results can only be called'); - PushProc(x.obj^.chunk, x.obj^.ext); - end; - else NotValue(x); - end; - x.mode := mStack; -end; - -{ The address of the variable or string x, on top of the stack } -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; - x.obj^.reg2 := 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)); - x.base := bStack; x.off := 0; - end else MarkAt(x.pos, 'expected a variable'); -end; - -{ x isn't wanted: what it has on the stack is dropped } -procedure Discard(const x: TItem); -var y: TItem; -begin - if x.mode = mCond then begin y := x; Value(y); Drop; exit end; - if (x.mode = mStack) or ((x.mode = mVar) and (x.base = bStack)) then Drop; - if x.mode = mWords then begin Drop; Drop end; -end; - -{ Frames } - -procedure TempItem(var x: TItem; t: PType; off: int64); -var p: TPos; -begin - p := x.pos; - FillChar(x, SizeOf(x), 0); - x.pos := p; - x.mode := mVar; x.typ := t; x.base := bFrame; x.off := off; -end; - -function ToSlot(var x: TItem): int64; -var s: int64; -begin - Value(x); - s := AllocTemp(8, 8); - PopVar(FrameAdr(s), 8); - ToSlot := s; -end; - -{ Copying } - -{ x, copied to a temporary } -procedure CopyToTemp(var x: TItem); -var t: int64; f, g: PObj; a: TAdr; -begin - if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer'); - t := AllocTemp(x.typ^.size, x.typ^.align); - if (x.mode = mVar) and (x.base = bReg) then begin - { a slice in registers, which has no address: its words stored } - a := AdrOf(x); - PushVar(a, 8, false, kWord); - PopVar(FrameAdr(t), 8); - a.off := 8; - PushVar(a, 8, false, kWord); - PopVar(FrameAdr(t + 8), 8); - TempItem(x, x.typ, t); - exit; - end; - if x.mode = mWords then begin - { the second result is on top, so it is popped first } - f := x.typ^.fields; g := f^.next; - PopVar(FrameAdr(t + g^.val), ScalarSize(g^.typ)); - PopVar(FrameAdr(t + f^.val), ScalarSize(f^.typ)); - TempItem(x, x.typ, t); - exit; - end; - Address(x); - CopyTo(FrameAdr(t), x.typ^.size); - TempItem(x, x.typ, t); -end; - -{ A slice made from an address on the stack and a length. } -procedure SliceOf(var x: TItem; t: PType; len: int64); -var s: int64; -begin - s := AllocTemp(16, 8); - PopVar(FrameAdr(s), 8); - PushConst(kWord, len); - PopVar(FrameAdr(s + 8), 8); - TempItem(x, t, s); -end; - -{ An INT goes silently into an I64, and a UINT into a U64, losing - nothing on any target (report section 5.10). } -function Widens(s, t: PType): boolean; -begin - Widens := ((s = tInt) and Same(t, tI64)) or ((s = tUInt) and Same(t, tU64)); -end; - -{ Another module's exported variable can be read, not changed, nor - handed to anything that could change it (report section 3). } -procedure NotReadOnly(const x: TItem); -begin - if x.ro then MarkAt(x.pos, Source(x.pos) + ' is ' + NameOf(x.obj^.module^.name) + '''s, and can''t be changed outside it'); -end; - -var - passing: PObj; { the parameter the argument at passingAt goes to } - passingAt: TPos; - -{ An error in x's type; if x is an argument, a note at the parameter - it goes to. } -procedure Mismatch(const x: TItem; const msg: shortstring); -begin - Error(x.pos, msg); - if (passing <> nil) and (x.pos.f = passingAt.f) and (x.pos.a = passingAt.a) and (x.pos.b = passingAt.b) then - Note(passing^.pos, 'it goes to ' + NameOf(passing^.name) + ', declared here'); - Fail; -end; - -procedure Coerce(var x: TItem; t: PType); -var s: PType; tmp: int64; -begin - if x.mode = mCond then Value(x); - s := x.typ; - if x.mode = mStr then begin - if (t^.form = fSlice) and (t^.base = tU8) then begin - Address(x); SliceOf(x, t, x.val) - end else if (t^.form = fPtr) and (t^.base = tU8) then begin - Address(x); x.mode := mStack; x.typ := t - end else if (t^.form = fArray) and (t^.base = tU8) and (t^.len >= x.val) then begin - tmp := AllocTemp(t^.size, 1); - Address(x); - CopyTo(FrameAdr(tmp), x.val); - if t^.len > x.val then ZeroVar(FrameAdr(tmp + x.val), t^.len - x.val); - TempItem(x, t, tmp); - end else Mismatch(x, 'can''t use a string as ' + TypeName(t)); - exit; - end; - if x.mode in [mType, mBuiltin, mNone, mCase] then NotValue(x); - if Same(s, t) then exit; - if Widens(s, t) then x.typ := t { the same bits, on a 64-bit target } - else if (s = tRConst) and (t^.form = fReal) then RealTo(x, t) - else if (s^.form = fConst) and (t^.form = fInt) then begin - if (x.mode = mConst) and not Fits(x.val, t) then MarkAt(x.pos, IntStr(x.val) + ' doesn''t fit ' + TypeName(t)); - x.typ := t; - end else if (s^.form = fNil) and (t^.form in [fPtr, fProc, fError]) then - x.typ := t - else if (s^.form = fPtr) and (t^.form = fPtr) and t^.vol and not s^.vol - and Same(s^.base, t^.base) then - x.typ := t - else if (s^.form = fArray) and (t^.form = fSlice) and Same(s^.base, t^.base) then begin - NotReadOnly(x); - if x.vol then MarkAt(x.pos, 'can''t make a slice through a volatile pointer'); - if x.odd then MarkAt(x.pos, 'can''t make a slice of a field of a packed record'); - Address(x); - SliceOf(x, t, s^.len); - end else if (x.mode = mProc) and (t^.form <> fProc) and (s^.base = nil) then - MarkAt(x.pos, Source(x.pos) + ' is a procedure, and returns nothing') - else if (x.mode = mProc) and (t^.form <> fProc) then - MarkHelp(x.pos, 'can''t use ' + TypeName(s) + ' as ' + TypeName(t), 'to call it, write ' + Source(x.pos) + '()') - else - Mismatch(x, 'can''t use ' + TypeName(s) + ' as ' + TypeName(t)); -end; - -{ Coerce where the types must be the same, as in a for loop, INC and - several results, which don't widen an INT to an I64 (report sections - 5.10, 6.1 and 7.2); help, if not empty, says why. } -procedure CoerceExact(var x: TItem; t: PType; const help: shortstring); -var h: shortstring; -begin - if Widens(x.typ, t) then begin - h := help; - if h = '' then h := 'they don''t mix here: write ' + TypeName(t) + '(' + Source(x.pos) + ')'; - MarkHelp(x.pos, 'expected ' + TypeName(t) + ', found ' + What(x), h); - end; - Coerce(x, t); -end; - -{ dst := src. The address of dst, if it has to be computed, is on the - stack already, under src's. } -procedure Assign(var dst, src: TItem); -begin - Coerce(src, dst.typ); - if IsScalar(dst.typ) then begin - Value(src); - PopVar(AdrOf(dst), ScalarSize(dst.typ)); - end else begin - if dst.vol or src.vol then MarkAt(src.pos, 'can''t copy through a volatile pointer'); - if (src.mode = mVar) and (src.base = bReg) then CopyToTemp(src); { a slice in registers } - Address(src); - if dst.base = bStack then CopyBlock(dst.typ^.size, dst.off) - else CopyTo(AdrOf(dst), dst.typ^.size); - end; -end; - -{ t's name, ending in a zero byte, for Rt.fail } -function NameChunk(t: PType): longint; -var s: shortstring; c: longint; -begin - s := TypeName(t) + #0; - c := NewChunk(secRodata, -1, -1); - SetData(c, @s[1], length(s), 1); - NameChunk := c; -end; - -{ Selectors } - -procedure Deref(var x: TItem); -var t: PType; -begin - t := x.typ; - if t^.form <> fPtr then MarkAt(x.pos, 'expected a pointer, found ' + TypeName(t)); - if t^.base = nil then MarkAt(x.pos, TypeName(t) + ' points to a type never declared'); - Value(x); - x.mode := mVar; x.base := bStack; x.off := 0; x.deref := true; - x.typ := t^.base; x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false; -end; - -{ A field of a packed record, of more than one byte's alignment, may - sit anywhere; it is read and written, but has no address and no - volatile access, which a machine that can't reach a misaligned word - couldn't make one access (report section 5.5). } -procedure Field(var x: TItem; f: PObj); -begin - if x.typ^.packd and (f^.typ^.align > 1) then begin - if x.vol then MarkAt(x.pos, 'a field of a packed record can''t be volatile'); - x.odd := true; - end; - x.off := x.off + f^.val; - x.typ := f^.typ; -end; - -procedure IndexPrep(var x: TItem); -begin - NilTest(x); - if x.mode = mStr then Coerce(x, tBytes); - if (x.typ^.form = fPtr) and (x.typ^.base^.form = fArray) then - MarkAt(x.pos, 'a pointer to an array is indexed as p^[i]'); - if x.typ^.form = fPtr then Value(x) - else if not ((x.mode = mVar) and (x.typ^.form in [fArray, fSlice])) then - MarkAt(x.pos, 'expected an array, a slice or a pointer, found ' + What(x)); -end; - -{ The index on top, times the size of an element } -procedure ScaleBy(s: int64); -begin - if s <> 1 then begin - PushConst(kWord, s); - gen.Op(sTimes, kWord, 8, true); - end; -end; - -procedure Index(var x, y: TItem); -var t: PType; s: int64; -begin - t := x.typ; - s := t^.base^.size; - if not IsInt(y.typ) then MarkAt(y.pos, 'an index is an integer, found ' + What(y)); - if t^.form = fPtr then begin - Value(y); - ScaleBy(s); - gen.Op(sPlus, kWord, 8, false); - x.mode := mVar; x.base := bStack; x.off := 0; - x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false; - end else if (t^.form = fArray) and (y.mode = mConst) then begin - if (y.val < 0) or (y.val >= t^.len) then MarkAt(y.pos, 'index ' + IntStr(y.val) + ' is out of range for a length of ' + IntStr(t^.len)); - x.off := x.off + y.val * s; - end else if t^.form = fArray then begin - Value(y); - if checks then CheckIndex(t^.len, y.pos); - if x.base = bStack then begin ScaleBy(s); gen.Op(sPlus, kWord, 8, false) end - else begin IndexArray(AdrOf(x), s); x.off := 0 end; - x.base := bStack; - end else begin - Value(y); - IndexSlice(AdrOf(x), s, checks, y.pos); - x.base := bStack; x.off := 0; x.isVar := true; x.vol := false; x.ro := false; - end; - x.typ := t^.base; -end; - -procedure SliceLo(var lo: TItem); -begin - if not IsInt(lo.typ) then MarkAt(lo.pos, 'an index is an integer, found ' + What(lo)); - Value(lo); -end; - -procedure Slice(var x, lo, hi: TItem); -var t, st: PType; tmp: int64; -begin - t := x.typ; - if not IsInt(hi.typ) then MarkAt(hi.pos, 'an index is an integer, found ' + What(hi)); - if x.vol then MarkAt(x.pos, 'can''t make a slice through a volatile pointer'); - if x.odd then MarkAt(x.pos, 'can''t make a slice of a field of a packed record'); - if t^.form = fArray then NotReadOnly(x); - Value(hi); - tmp := AllocTemp(16, 8); - if t^.form = fPtr then SlicePtr(t^.base^.size, tmp, checks, lo.pos) - else gen.Slice(AdrOf(x), t^.form = fArray, t^.len, t^.base^.size, tmp, checks, lo.pos); - st := NewType(fSlice, 16, 8); - st^.base := t^.base; - TempItem(x, st, tmp); -end; - -{ Operators } - -procedure Neg(var x: TItem); -begin - if x.typ^.form = fReal then begin - if x.mode = mConst then x.val := x.val xor low(int64) - else begin Value(x); gen.Neg(KindOf(x.typ), 8, false) end; - end else if IsInt(x.typ) then begin - if (x.mode = mConst) and (x.typ^.form = fConst) and (x.val = low(int64)) then - MarkAt(x.pos, 'the constant is too big for I64') - else if x.mode = mConst then x.val := Cut(-x.val, x.typ) - else begin Value(x); gen.Neg(kWord, IntSize(x.typ), Signed(x.typ)) end; - end else MarkAt(x.pos, 'can''t negate ' + TypeName(x.typ)); -end; - -procedure NotOp(var x: TItem); -var L: longint; -begin - if IsInt(x.typ) then MarkHelp(x.pos, '"not" needs a BOOL, found ' + What(x), 'the bits of an integer flip with ~'); - if x.typ^.form <> fBool then MarkAt(x.pos, '"not" needs a BOOL, found ' + What(x)); - if x.mode = mConst then x.val := 1 - x.val - else if x.mode = mCond then begin - x.rel := Negated[x.rel]; - L := x.fj; x.fj := x.tj; x.tj := L; - end - else begin Value(x); NotBool end; -end; - -procedure Complement(var x: TItem); -begin - if x.typ^.form = fBool then MarkHelp(x.pos, '"~" needs an integer, found ' + What(x), 'a BOOL is negated with not'); - if not IsInt(x.typ) then MarkAt(x.pos, '"~" needs an integer, found ' + What(x)); - if x.mode = mConst then x.val := Cut(not x.val, x.typ) - else begin Value(x); gen.Complement(IntSize(x.typ), Signed(x.typ)) end; -end; - -{ Arrays, slices and strings, which = and # compare element by element } -function IsSeq(t: PType): boolean; -begin - IsSeq := t^.form in [fStr, fArray, fSlice]; -end; - -function ElemOf(t: PType): PType; -begin - if t^.form = fStr then ElemOf := tU8 else ElemOf := t^.base; -end; - -{ An array, slice or string as a slice in a temporary, for comparing. } -procedure SeqSlice(var x: TItem); -var t: PType; -begin - t := NewType(fSlice, 16, 8); - t^.base := ElemOf(x.typ); - if x.typ^.form = fSlice then begin - x.typ := t; CopyToTemp(x) - end else begin - if x.mode = mStr then begin Address(x); SliceOf(x, t, x.val) end - else begin - if x.vol then MarkAt(x.pos, 'can''t compare through a volatile pointer'); - Address(x); SliceOf(x, t, x.typ^.len) - end; - end; -end; - -{ x, a BOOL, as a condition: a value compared with 0 if it isn't one } -procedure MakeCond(var x: TItem); -begin - if x.mode = mCond then exit; - Value(x); - PushConst(kWord, 0); - x.mode := mCond; - x.rel := sNeq; - x.relSigned := false; - x.fj := NoLabel; - x.tj := NoLabel; -end; - -procedure Op1(op: TSym; var x: TItem; var L: longint); -begin - L := NoLabel; - if (op in [sAnd, sOr]) and (x.typ^.form = fBool) then begin - if x.mode = mConst then exit; { folded by Op2 } - MakeCond(x); - if op = sAnd then begin - JumpOut(Negated[x.rel], x.relSigned, x.fj); - Fix(x.tj); - x.tj := NoLabel; - end else begin - JumpOut(x.rel, x.relSigned, x.tj); - Fix(x.fj); - x.fj := NoLabel; - end; - end else if (op in [sEql, sNeq]) and IsSeq(x.typ) then - SeqSlice(x) - else if (op = sPlus) and (x.mode = mStr) then - { two string constants to be joined: nothing to compute } - else if (op = sPlus) and IsSeq(x.typ) then - MarkHelp(x.pos, '+ doesn''t join ' + What(x), 'strings are joined in a Buf: Buf.str(b, s)') - else if x.mode in [mType, mBuiltin, mNone, mCase, mStr] then - NotValue(x) - else if x.mode <> mConst then - Value(x); -end; - -function Log2(v: int64): longint; -var n: longint; -begin - n := 0; - while (v > 1) and (v and 1 = 0) do begin v := v shr 1; inc(n) end; - if v <> 1 then n := -1; - Log2 := n; -end; - -{ Whether a op b, for + - *, overflows an I64: an untyped constant - doesn't wrap, it is an error (report section 4). } -function Overflows(op: TSym; a, b: int64): boolean; -begin - case op of - sPlus: Overflows := ((b > 0) and (a > high(int64) - b)) or ((b < 0) and (a < low(int64) - b)); - sMinus: Overflows := ((b < 0) and (a > high(int64) + b)) or ((b > 0) and (a < low(int64) + b)); - sTimes: - if (a = 0) or (b = 0) then Overflows := false - else if a = -1 then Overflows := b = low(int64) - else if b = -1 then Overflows := a = low(int64) - else Overflows := (a * b) div b <> a; - else Overflows := false; - end; -end; - -{ A type's width in bits; an untyped constant's is an I64's } -function Bits(t: PType): longint; -begin - Bits := t^.size * 8; -end; - -function FoldInt(op: TSym; a, b: int64; t: PType; const p: TPos): int64; -var u: boolean; -begin - u := (t^.form = fInt) and not t^.signed; - if (t^.form = fConst) and Overflows(op, a, b) then MarkAt(p, 'the constant is too big for I64'); - case op of - sPlus: FoldInt := a + b; - sMinus: FoldInt := a - b; - sTimes: FoldInt := a * b; - sDiv, sMod: begin - if b = 0 then MarkAt(p, 'division by zero'); - if u then begin - if op = sDiv then FoldInt := int64(qword(a) div qword(b)) - else FoldInt := int64(qword(a) mod qword(b)); - end else if (b = -1) and (a = int64(-1) shl (Bits(t) - 1)) then MarkAt(p, 'division overflows') - else if op = sDiv then FoldInt := a div b - else FoldInt := a mod b; - end; - sAmp: FoldInt := a and b; - sBar: FoldInt := a or b; - sXor: FoldInt := a xor b; - sShl: FoldInt := a shl (b and (Bits(t) - 1)); - sShr: if u then FoldInt := int64(qword(a) shr (b and (Bits(t) - 1))) - else FoldInt := SarInt64(a, b and (Bits(t) - 1)); - sEql: FoldInt := ord(a = b); - sNeq: FoldInt := ord(a <> b); - sLss: if u then FoldInt := ord(qword(a) < qword(b)) else FoldInt := ord(a < b); - sLeq: if u then FoldInt := ord(qword(a) <= qword(b)) else FoldInt := ord(a <= b); - sGtr: if u then FoldInt := ord(qword(a) > qword(b)) else FoldInt := ord(a > b); - sGeq: if u then FoldInt := ord(qword(a) >= qword(b)) else FoldInt := ord(a >= b); - else MarkAt(p, 'bad operator'); FoldInt := 0; - end; -end; - -{ Folds x op y, of the real type t: an F32 rounded at each step, as - the machine would. } -function FoldReal(op: TSym; const x, y: TItem; t: PType; var r: TItem): boolean; -var a, b: double; -begin - a := RealOf(x); b := RealOf(y); - FoldReal := true; - case op of - sPlus: MakeReal(r, a + b); - sMinus: MakeReal(r, a - b); - sTimes: MakeReal(r, a * b); - sSlash: MakeReal(r, a / b); - sEql: MakeConst(r, tBool, ord(a = b)); - sNeq: MakeConst(r, tBool, ord(a <> b)); - sLss: MakeConst(r, tBool, ord(a < b)); - sLeq: MakeConst(r, tBool, ord(a <= b)); - sGtr: MakeConst(r, tBool, ord(a > b)); - sGeq: MakeConst(r, tBool, ord(a >= b)); - else FoldReal := false; - end; - if r.typ^.form = fReal then RealTo(r, t); -end; - -{ and, or and not are for BOOLs; &, |, xor and ~ for the bits of - integers: x is the wrong kind for op, and the message names the - operator it may have meant } -procedure WrongLogic(op: TSym; var x: TItem); -const Bits = 'the bits of integers take '; -begin - case op of - sAnd: if IsInt(x.typ) then MarkHelp(x.pos, '"and" needs BOOLs, found ' + What(x), Bits + '&'); - sOr: if IsInt(x.typ) then MarkHelp(x.pos, '"or" needs BOOLs, found ' + What(x), Bits + '|'); - sAmp: MarkHelp(x.pos, '"&" needs integers, found ' + What(x), 'BOOLs take and'); - sBar: MarkHelp(x.pos, '"|" needs integers, found ' + What(x), 'BOOLs take or'); - sXor: MarkHelp(x.pos, '"xor" needs integers, found ' + What(x), 'BOOLs that differ are #'); - end; - MarkAt(x.pos, SymText(op) + ' needs BOOLs, found ' + What(x)); -end; - -{ x + y, of two string constants: one string, in a chunk of its own - (report section 4) } -procedure JoinStr(var x, y: TItem); -var p: PBytes; c: longint; -begin - if y.mode <> mStr then MarkAt(y.pos, '"+" joins two strings, found ' + What(y)); - p := GetMem(x.val + y.val + 1); - Move(rodata^[chunks^[x.chunk].start], p^[0], x.val); - Move(rodata^[chunks^[y.chunk].start], p^[x.val], y.val + 1); - c := NewChunk(secRodata, -1, -1); - SetData(c, p, x.val + y.val + 1, 1); - FreeMem(p); - x.chunk := c; - x.val := x.val + y.val; -end; - -{ A set's operations, as operations on its bits: the two values on top } -procedure SetOp(op: TSym); -begin - case op of - sPlus: gen.Op(sBar, kWord, 8, false); - sTimes: gen.Op(sAmp, kWord, 8, false); - sMinus: begin gen.Complement(8, false); gen.Op(sAmp, kWord, 8, false) end; - sLeq, sGeq: begin - { x <= y has no bit of x outside y } - if op = sGeq then Swap; - gen.Complement(8, false); - gen.Op(sAmp, kWord, 8, false); - PushConst(kWord, 0); - Compare(sEql, kWord, false); - end; - sIn: begin - Swap; - gen.Op(sShr, kWord, 8, false); - PushConst(kWord, 1); - gen.Op(sAmp, kWord, 8, false); - end; - else Compare(op, kWord, false); - end; -end; - -procedure Op2(op: TSym; var x, y: TItem; L: longint); -const - Rel = [sEql, sNeq, sLss, sLeq, sGtr, sGeq]; -var - xt, yt, t, e: PType; r: TItem; scale: longint; isPtr: boolean; a, b: int64; -begin - xt := x.typ; yt := y.typ; - if y.mode in [mType, mBuiltin, mNone, mCase] then NotValue(y); - if (op = sPlus) and (x.mode = mStr) then begin JoinStr(x, y); exit end; - - if op in [sAnd, sOr] then begin - if xt^.form <> fBool then WrongLogic(op, x); - if yt^.form <> fBool then WrongLogic(op, y); - if (x.mode = mConst) and (y.mode = mConst) then begin - if op = sAnd then x.val := x.val and y.val else x.val := x.val or y.val; - end else if x.mode = mConst then begin - { true and y, false or y: y; else x, y computed and dropped } - if (x.val = 1) = (op = sAnd) then x := y - else Discard(y); - end else begin - MakeCond(y); - if op = sAnd then begin x.fj := JoinJumps(x.fj, y.fj); x.tj := y.tj end - else begin x.tj := JoinJumps(x.tj, y.tj); x.fj := y.fj end; - x.rel := y.rel; - x.relSigned := y.relSigned; - end; - exit; - end; - - if (op in [sAmp, sBar, sXor]) and (xt^.form = fBool) then WrongLogic(op, x); - if (op in [sAmp, sBar, sXor]) and (yt^.form = fBool) then WrongLogic(op, y); - - { the lengths, then the bytes, LEN * SIZE(T) of them: the elements - are of types whose bytes say all there is to their values } - if (op in [sEql, sNeq]) and IsSeq(xt) then begin - e := ElemOf(xt); - if not IsSeq(yt) then - MarkAt(Join(x.pos, y.pos), 'can''t compare an array with ' + TypeName(yt)) - else if not Same(e, ElemOf(yt)) then - MarkAt(Join(x.pos, y.pos), 'can''t compare an array of ' + TypeName(e) + ' with one of ' + TypeName(ElemOf(yt))); - if e^.form = fReal then - MarkHelp(Join(x.pos, y.pos), 'can''t compare arrays of reals with ' + SymText(op), - '-0.0 = 0.0 and a NaN equals nothing, though their bytes say otherwise: write a loop') - else if not (e^.form in [fInt, fBool, fEnum, fSet, fPtr]) then - MarkHelp(Join(x.pos, y.pos), 'can''t compare arrays of ' + TypeName(e) + ' with ' + SymText(op), 'write a loop'); - SeqSlice(y); - CompareSeq(x.off, y.off, Log2(e^.size), op = sEql); - MakeConst(x, tBool, 0); - x.mode := mStack; - exit; - end; - - { the type of the result, and the checks } - t := nil; scale := 1; isPtr := false; - if IsInt(xt) and IsInt(yt) then begin - if op = sSlash then MarkHelp(Join(x.pos, y.pos), '"/" divides reals, not integers', 'to divide integers, write ' + Source(x.pos) + ' div ' + Source(y.pos)); - if op in [sShl, sShr] then begin - if xt^.form = fConst then t := tConst else t := xt - end else if (xt^.form = fConst) and (yt^.form = fConst) then t := tConst - else if xt^.form = fConst then begin - if (x.mode = mConst) and not Fits(x.val, yt) then MarkAt(x.pos, IntStr(x.val) + ' doesn''t fit ' + TypeName(yt)); - t := yt - end else if yt^.form = fConst then begin - if (y.mode = mConst) and not Fits(y.val, xt) then MarkAt(y.pos, IntStr(y.val) + ' doesn''t fit ' + TypeName(xt)); - t := xt - end else if Same(xt, yt) then t := xt - else Mismatch(x, y, xt, yt); - if not (op in Rel + [sPlus, sMinus, sTimes, sDiv, sMod, sAmp, sBar, sXor, sShl, sShr]) then - MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(t)); - end else if (xt^.form = fReal) and (yt^.form = fReal) then begin - if not (op in Rel + [sPlus, sMinus, sTimes, sSlash]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); - if xt = tRConst then t := yt - else if (yt = tRConst) or Same(xt, yt) then t := xt - else Mismatch(x, y, xt, yt); - if (x.mode = mConst) and (x.typ <> t) then RealTo(x, t); - if (y.mode = mConst) and (y.typ <> t) then RealTo(y, t); - end else if (xt^.form = fBool) and (yt^.form = fBool) then begin - if not (op in [sEql, sNeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); - t := tBool; - end else if (xt^.form = fPtr) and IsInt(yt) and (op in [sPlus, sMinus]) then begin - t := xt; scale := xt^.base^.size; isPtr := true; - if y.mode = mConst then y.typ := tInt; - end else if (xt^.form = fPtr) and (yt^.form = fPtr) and (op = sMinus) then begin - if not Same(xt, yt) then Mismatch(x, y, xt, yt); - t := tInt; scale := xt^.base^.size; isPtr := true; - end else if (xt^.form in [fPtr, fProc, fNil, fError]) and (yt^.form in [fPtr, fProc, fNil, fError]) then begin - if not (op in Rel) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); - if (xt^.form in [fProc, fError]) or (yt^.form in [fProc, fError]) then - if not (op in [sEql, sNeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); - if (xt^.form <> fNil) and (yt^.form <> fNil) and not Same(xt, yt) then - if not ((xt^.form = fPtr) and (yt^.form = fPtr) and Same(xt^.base, yt^.base)) then - Mismatch(x, y, xt, yt); - t := tU64; - end else if (xt^.form = fEnum) and Same(xt, yt) then begin - if not (op in Rel) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); - t := xt; - end else if (xt^.form = fSet) and Same(xt, yt) then begin - if not (op in [sPlus, sTimes, sMinus, sEql, sNeq, sLeq, sGeq]) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); - t := xt; - end else if (op = sIn) and (yt^.form = fSet) and Same(xt, yt^.base) then - t := yt - else - Mismatch(x, y, xt, yt); - - { constants } - if (x.mode = mConst) and (y.mode = mConst) and not isPtr then begin - if t^.form = fReal then begin - if not FoldReal(op, x, y, t, r) then MarkAt(Join(x.pos, y.pos), SymText(op) + ' doesn''t apply to ' + TypeName(xt)); - x := r; - end else if t^.form = fSet then begin - a := x.val; b := y.val; - case op of - sPlus: MakeConst(x, t, a or b); - sTimes: MakeConst(x, t, a and b); - sMinus: MakeConst(x, t, a and not b); - sIn: MakeConst(x, tBool, (b shr a) and 1); - sLeq: MakeConst(x, tBool, ord(a and not b = 0)); - sGeq: MakeConst(x, tBool, ord(b and not a = 0)); - else MakeConst(x, tBool, ord((a = b) = (op = sEql))); - end; - end else if op in Rel then - MakeConst(x, tBool, FoldInt(op, x.val, y.val, t, Join(x.pos, y.pos))) - else - MakeConst(x, t, Cut(FoldInt(op, x.val, y.val, t, Join(x.pos, y.pos)), t)); - exit; - end; - - { x and y on the stack, x under y; a constant x goes on after y, and - is left on top where the order doesn't matter, as gen takes a - constant best on the right: 0.25 * e is mulsd xmm8, [0.25] } - Value(y); - if x.mode = mConst then begin - Value(x); - if not (op in [sPlus, sTimes, sAmp, sBar, sXor]) or isPtr then Swap; - end; - - if t^.form = fReal then begin - if op in Rel then Compare(op, KindOf(t), false) else gen.Op(op, KindOf(t), 8, false) - end else if t^.form = fSet then - SetOp(op) - else if op in Rel then begin - x.mode := mCond; - x.rel := op; - x.relSigned := Signed(t); - x.fj := NoLabel; - x.tj := NoLabel; - x.typ := tBool; - exit; - end - else if isPtr then begin - if t <> tInt then ScaleBy(scale); - gen.Op(op, kWord, 8, false); - if (t = tInt) and (scale <> 1) then begin - PushConst(kWord, scale); - gen.Op(sDiv, kWord, 8, true); - end; - end else - gen.Op(op, KindOf(t), IntSize(t), Signed(t)); - x.mode := mStack; - if op in Rel + [sIn] then x.typ := tBool else x.typ := t; -end; - -{ INT and UINT, the integers as big as an address, through which - integers and pointers convert (report section 6.7) } -function IsWord(t: PType): boolean; -begin - IsWord := Same(t, tInt) or Same(t, tUInt); -end; - -procedure Convert(var x: TItem; t: PType); -var s: PType; r: double; -begin - s := x.typ; - if x.mode in [mType, mBuiltin, mNone, mCase, mStr] then begin - if x.mode = mStr then MarkAt(x.pos, 'can''t convert a string'); - NotValue(x); - end; - if Same(s, t) then exit; - if (IsInt(s) or (s^.form in [fEnum, fSet])) and (t^.form = fInt) then begin - if x.mode = mConst then x.val := Cut(x.val, t) - else begin Value(x); Narrow(t^.size, t^.signed) end; - end else if IsInt(s) and (t^.form = fEnum) then begin - if x.mode = mConst then begin - if (x.val < 0) or (x.val >= t^.len) then MarkAt(x.pos, IntStr(x.val) + ' isn''t a position of ' + TypeName(t)) - end else begin Value(x); CheckEnum(t^.len, NameChunk(t), x.pos) end; - end else if IsInt(s) and (t^.form = fSet) then begin - if x.mode = mConst then begin - if t^.len < 64 then x.val := x.val and ((int64(1) shl t^.len) - 1) - end else begin - Value(x); - if t^.len < 64 then begin - PushConst(kWord, (int64(1) shl t^.len) - 1); - gen.Op(sAmp, kWord, 8, false); - end; - end; - end else if IsInt(s) and (t^.form = fReal) then begin - if x.mode = mConst then begin - if (s^.form = fInt) and not s^.signed then r := qword(x.val) else r := x.val; - MakeReal(x, r); - RealTo(x, t); - end else begin - Value(x); - IntToReal(KindOf(t), (s^.form = fInt) and not s^.signed and (s^.size = 8)); - end; - end else if (s^.form = fReal) and (t^.form = fReal) then begin - { F32 to F64, F64 to F32, or a real constant to either } - if x.mode = mConst then RealTo(x, t) - else begin Value(x); RealToReal(KindOf(s)) end; - end else if (s^.form = fReal) and (t^.form = fInt) then begin - if x.mode = mConst then begin - r := RealOf(x); - { NaN or out of range folds to low(int64), the "integer - indefinite" cvttsd2si gives at run time } - if (r <> r) or (r >= 9.2233720368547758e18) or (r < -9.2233720368547758e18) then - x.val := Cut(low(int64), t) - else x.val := Cut(trunc(r), t); - end else begin - Value(x); RealToInt(KindOf(s)); Narrow(t^.size, t^.signed) - end; - end else if (IsWord(s) or (s^.form in [fConst, fPtr, fProc, fNil])) and (t^.form in [fPtr, fProc]) then begin - if x.mode <> mConst then Value(x); - end else if (s^.form in [fPtr, fProc]) and IsWord(t) then - Value(x) - else - MarkAt(x.pos, 'can''t convert ' + TypeName(s) + ' to ' + TypeName(t)); - x.typ := t; -end; - -{ Calls } - -procedure BeginCall(var c: TCall; var x: TItem); -begin - if x.mode = mProc then begin - c.sig := x.obj^.typ; c.chunk := x.obj^.chunk; c.target := 0; - c.obj := x.obj; c.ext := x.obj^.ext; - end else begin - c.obj := nil; c.ext := false; - if x.typ^.form <> fProc then MarkAt(x.pos, 'expected a procedure, found ' + What(x)); - c.sig := x.typ; c.chunk := -1; - c.target := ToSlot(x); - end; - c.param := c.sig^.fields; - c.n := 0; -end; - -{ Too many arguments or too few, at p } -procedure WrongCount(var c: TCall; const p: TPos; const what: shortstring); -begin - if c.obj = nil then MarkAt(p, what); - Error(p, what + ': ' + NameOf(c.obj^.name) + ' takes ' + IntStr(c.sig^.len)); - if c.obj^.module <> nil then Note(c.obj^.pos, 'the signature is here'); - Fail; -end; - -{ Pushes the two words of x, a slice or two results (InTwoRegs), read - from memory now, so that what comes after can't change them. } -procedure PushWords(var x: TItem); -var adr: TAdr; f: PObj; -begin - if x.mode = mWords then exit; { there already } - { copied to a temporary unless its two words are in memory at a place - that a later argument can't change } - if (x.mode <> mVar) or x.vol or not (x.base in [bFrame, bGlobal, bSlot, bReg]) then CopyToTemp(x); - adr := AdrOf(x); - if x.typ^.form = fSlice then begin - PushVar(adr, 8, false, kWord); - inc(adr.off, 8); - PushVar(adr, 8, false, kWord); - end else begin - f := x.typ^.fields; - while f <> nil do begin - adr.off := AdrOf(x).off + f^.val; - PushVar(adr, ScalarSize(f^.typ), Signed(f^.typ), KindOf(f^.typ)); - f := f^.next; - end; - end; -end; - -procedure PassArg(var c: TCall; var a: TItem); -var p: PObj; -begin - p := c.param; - if c.n >= High(c.isF) then MarkAt(a.pos, 'too many arguments'); - if p = nil then begin - { past the parameters of a C procedure that ends in ...: a string - goes as a C string, an integer constant as an INT, a real - constant as an F64; C takes no F32 there } - if not c.sig^.variadic then WrongCount(c, a.pos, 'too many arguments'); - if a.mode = mStr then Coerce(a, tPtrU8) - else if a.typ^.form = fConst then Coerce(a, tInt) - else if a.typ = tRConst then Coerce(a, tReal) - else if IsF32(a.typ) then MarkAt(a.pos, 'an F32 goes to ... as F64(x)') - else if not IsScalar(a.typ) then MarkAt(a.pos, 'only a single value goes to ...'); - c.isF[c.n] := a.typ^.form = fReal; - c.pair[c.n] := false; - Value(a); - inc(c.n); - exit; - end; - c.isF[c.n] := (p^.typ^.form = fReal) and not p^.isVar; - passing := p; - passingAt := a.pos; - if p^.isVar then begin - NotReadOnly(a); - if (a.mode <> mVar) or not a.isVar then MarkAt(a.pos, 'a var parameter needs a variable'); - if a.odd then MarkAt(a.pos, 'a field of a packed record can''t be a var parameter'); - if not Same(a.typ, p^.typ) then Mismatch(a, 'a var parameter needs exactly ' + TypeName(p^.typ) + ', found ' + What(a)); - if a.vol then MarkAt(a.pos, 'can''t pass through a volatile pointer to a var parameter'); - Address(a); - end else if p^.typ^.form = fSlice then begin - Coerce(a, p^.typ); - PushWords(a); - c.pair[c.n] := true; - inc(c.n); - c.isF[c.n] := false; - end else if IsAggregate(p^.typ) then begin - Coerce(a, p^.typ); - if a.isVar or a.vol or (a.base <> bFrame) then CopyToTemp(a); - Address(a); - end else begin - Coerce(a, p^.typ); - Value(a); - end; - c.pair[c.n] := false; - inc(c.n); - c.param := p^.next; -end; - -{ The call c made, with x its result as an item: none; a temporary, for a - slice or a record; two results on gen's stack (mWords); else one value - on the stack. } -procedure EndCall(var c: TCall; var x: TItem); -var res: PType; -begin - if c.param <> nil then WrongCount(c, TokPos, 'too few arguments'); - Call(c); - res := c.sig^.base; - FillChar(x, SizeOf(x), 0); - if res = nil then begin - x.mode := mNone; x.typ := tNone; x.obj := c.obj - end else if c.ret <> 0 then - TempItem(x, res, c.ret) - else begin - x.mode := mStack; x.typ := res; - if res^.tuple then x.mode := mWords; - end; -end; - -{ Variants } - -{ A temporary of type t, all zero: for variants and record literals. } -procedure ZeroTemp(var x: TItem; t: PType); -var tmp: int64; -begin - tmp := AllocTemp(t^.size, t^.align); - ZeroVar(FrameAdr(tmp), t^.size); - TempItem(x, t, tmp); -end; - -procedure Construct(var x: TItem; c: PObj); -begin - ZeroTemp(x, c^.typ); - PushConst(kWord, c^.val); - PopVar(FrameAdr(x.off), 8); -end; - -procedure SetField(const x: TItem; f: PObj; var a: TItem); -begin - Coerce(a, f^.typ); - if IsScalar(f^.typ) then begin - Value(a); - PopVar(FrameAdr(x.off + f^.val), ScalarSize(f^.typ)); - end else begin - if a.vol then MarkAt(a.pos, 'can''t copy through a volatile pointer'); - Address(a); - CopyTo(FrameAdr(x.off + f^.val), f^.typ^.size); - end; -end; - -{ The slot match tests: a variant's address, or an enumeration's or an - integer's value. } -function MatchBegin(var x: TItem): int64; -var p: int64; -begin - if x.typ^.form in [fEnum, fInt] then exit(ToSlot(x)); - if (x.mode <> mVar) or (x.typ^.form <> fVariant) then MarkAt(x.pos, 'match needs a variant, an enumeration or an integer, found ' + What(x)); - if x.ro then CopyToTemp(x); { its arms' names stand for a copy's fields } - Address(x); - p := AllocTemp(8, 8); - PopVar(FrameAdr(p), 8); - MatchBegin := p; -end; - -{ To L unless the tag of the variant whose address is in slot p is tag } -procedure MatchTag(p: int64; tag: int64; var L: longint); -var a: TAdr; -begin - PushVar(FrameAdr(p), 8, false, kWord); - a.base := bStack; a.chunk := -1; a.off := 0; - PushVar(a, 8, false, kWord); - PushConst(kWord, tag); - JumpCmp(sNeq, false, L); -end; - -{ To body if the integer in slot p is from lo to hi: less its lo, it is - then at most hi - lo, compared unsigned, which holds for a signed type - or not, with no second jump. } -procedure MatchRange(p, lo, hi: int64; var body: longint); -begin - PushVar(FrameAdr(p), 8, false, kWord); - if lo = hi then begin - PushConst(kWord, lo); - JumpCmp(sEql, false, body); - exit; - end; - if lo <> 0 then begin - PushConst(kWord, lo); - gen.Op(sMinus, kWord, 8, false); - end; - PushConst(kWord, hi - lo); - JumpCmp(sLeq, false, body); -end; - -{ A for loop's variable o, stepped by step, wrapping as its type does } -procedure ForStep(o: PObj; step: int64); -var v, w: TItem; -begin - MakeItem(v, o); - if v.base = bReg then begin - { a variable in a register is stepped in it } - PushConst(kWord, step); - IncDecReg(v.chunk, IntSize(o^.typ), Signed(o^.typ), false); - exit; - end; - MakeItem(w, o); - Value(w); - PushConst(kWord, step); - gen.Op(sPlus, kWord, IntSize(o^.typ), Signed(o^.typ)); - Assign(v, w); -end; - -{ For a for loop: pushes the variable o and the limit lim, a constant or - the slot it was put in, and jumps to L if the one is op the other, as - the type of o compares } -procedure ForCmp(o: PObj; const lim: TItem; op: TSym; var L: longint); -var v, b: TItem; -begin - MakeItem(v, o); - Value(v); - b := lim; - Value(b); - JumpCmp(op, o^.typ^.signed, L); -end; - -{ The end of a round of a for loop, for a positive step s, as the report - has it: if v <= b and b - v < s, the loop ends; otherwise v becomes - v + s and the loop goes on while v <= b. Counting the distance left, - rather than comparing after the step, can't be fooled by v wrapping - around. A negative step is the same the other way round: Before, Past - and Within are indexed by up, whether the step is positive. - For a step of 1: v < b goes on to top, where v is stepped; v = b - ends; otherwise the body moved v past b. - For another step: v past b goes to past; else b - v (unsigned, as - v <= b) >= |step| goes on to top, and else the loop ends. - Past: v is stepped here and tested, going to body if within b. } -procedure ForNext(o: PObj; const lim: TItem; step: int64; var exitL: longint; top, body: longint); -const - Before: array[boolean] of TSym = (sGtr, sLss); { by a negative step, by a positive } - Past: array[boolean] of TSym = (sLss, sGtr); - Within: array[boolean] of TSym = (sGeq, sLeq); -var v, b: TItem; L, pastL: longint; up: boolean; -begin - up := step > 0; - L := NoLabel; - pastL := NoLabel; - if abs(step) = 1 then begin - ForCmp(o, lim, Before[up], L); - FixTo(L, top); - ForCmp(o, lim, sEql, exitL); - end else begin - ForCmp(o, lim, Past[up], pastL); - MakeItem(v, o); - b := lim; - if up then begin Value(b); Value(v) end - else begin Value(v); Value(b) end; - gen.Op(sMinus, kWord, 8, false); - PushConst(kWord, abs(step)); - JumpCmp(sGeq, false, L); - FixTo(L, top); - Jump(exitL); - end; - Fix(pastL); - ForStep(o, step); - L := NoLabel; - ForCmp(o, lim, Within[up], L); - FixTo(L, body); -end; - -{ Jumps to L if the condition x is false. The jumps waiting in x.fj join - L; those in x.tj are placed here, as x is true past this. } -procedure CondJump(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(Negated[x.rel], x.relSigned, L); - L := JoinJumps(L, x.fj); - Fix(x.tj); - exit; - end; - Value(x); - JumpIf(L, false); -end; - -{ As CondJump, but the jump to L is taken where the condition is true; - x.tj joins L and x.fj is placed here } -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 } - -procedure BeginProc(sig: PType; params: PObj); -begin - result := sig^.base; - gen.BeginProc(sig, params); -end; - -{ The result of return x: a value on top, a slice's two words on top, - or one copied behind the hidden pointer } -procedure ReturnValue(var x: TItem); -begin - if result = nil then MarkAt(x.pos, 'this procedure returns nothing'); - Coerce(x, result); - if InTwoRegs(result) then PushWords(x) - else if IsAggregate(result) then begin - if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer'); - Address(x); - CopyResult(0, result^.size); - end else Value(x); -end; - -{ One of several results: of two words, a value left on top for - ReturnJump to put in rax or rdx; else into its place behind the - hidden pointer. } -procedure ReturnField(f: PObj; var x: TItem); -begin - Coerce(x, f^.typ); - if InTwoRegs(result) then Value(x) - else if IsScalar(f^.typ) then begin - Value(x); - ResultTo(f^.val, ScalarSize(f^.typ)); - end else begin - if x.vol then MarkAt(x.pos, 'can''t copy through a volatile pointer'); - Address(x); - CopyResult(f^.val, f^.typ^.size); - end; -end; - -{ Several results at once, the call's that return f(x) passes on. } -procedure ReturnAll(var x: TItem); -begin - if InTwoRegs(result) then PushWords(x) - else begin - Address(x); - CopyResult(0, result^.size); - end; -end; - -procedure ReturnNone; -begin - if result <> nil then Mark('return needs a result of ' + TypeName(result)); - ReturnJump; -end; - -{ Keeps a variable's address in a frame slot, rather than on the stack, - while other code runs. } -procedure Pin(var x: TItem); -var s: int64; -begin - if (x.mode = mVar) and (x.base = bStack) then begin - Address(x); - s := AllocTemp(8, 8); - PopVar(FrameAdr(s), 8); - x.base := bSlot; - x.chunk := s; - end; -end; - -{ INC(v, k) or DEC: v's address is on the stack, from Address. } -procedure IncDec(var v, k: TItem; dec: boolean); -begin - CoerceExact(k, v.typ, ''); - Value(k); - 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; - -{ COPY(d, s): d, an array variable or a slice, as a slice in the frame, - before s is read } -procedure CopyDest(var d: TItem); -begin - if not IsSeq(d.typ) or (d.mode = mStr) or (d.typ^.form = fArray) and ((d.mode <> mVar) or not d.isVar) then - MarkAt(d.pos, 'COPY copies into an array variable or a slice, found ' + What(d)); - if d.typ^.form = fArray then NotReadOnly(d); - SeqSlice(d); -end; - -{ ... and the elements of s copied to its start } -procedure CopyFrom(var d, s: TItem); -begin - if not IsSeq(s.typ) or not Same(ElemOf(s.typ), d.typ^.base) then - MarkAt(s.pos, 'COPY copies elements of ' + TypeName(d.typ^.base) + ', found ' + What(s)); - SeqSlice(s); - CopySlice(d.off, s.off, d.typ^.base^.size, checks, s.pos); -end; - -{ An error is the address of its length, followed by its message. } -function ErrorChunk(var x: TItem; module, name: longint): longint; -var c: longint; p: PBytes; -begin - if x.mode <> mStr then MarkAt(x.pos, 'an error is made from a string'); - p := GetMem(x.val + 8); - PInt64(p)^ := x.val; - Move(rodata^[chunks^[x.chunk].start], p^[8], x.val); - c := NewChunk(secRodata, module, name); - SetData(c, p, x.val + 8, 8); - FreeMem(p); - ErrorChunk := c; -end; - -procedure Msg(var x: TItem); -var s: int64; -begin - Coerce(x, tError); - Value(x); - s := AllocTemp(16, 8); - ErrorText(s); - TempItem(x, tBytes, s); -end; - -end. diff --git a/seed/link.pas b/seed/link.pas deleted file mode 100644 index edf0611..0000000 --- a/seed/link.pas +++ /dev/null @@ -1,334 +0,0 @@ -{ link.pas: tree shaking, layout and patching. - - Starting from the entry chunk, marks every chunk the program can - reach through fixups; the rest is left out. Then gives each live - chunk its address and builds the images of text and rodata, with - every fixup patched. - - The file is laid out so that each section can be mapped as it lies: - text right after the headers, rodata on the next page, then a - writable page that starts with the table the dynamic loader reads - (none in a static program) and goes on as bss, in memory only. The - loader's other tables come at the end of rodata; elf.pas writes them - in the room left there. - - Depends on: chunk for chunks and fixups, scan for names and errors. - Leaves out: the file format; that is elf.pas. } - -unit link; - -{$mode objfpc}{$H-} - -interface - -uses scan, diag, chunk; - -const - Base = $400000; - Page = 4096; - -var - textOff, textSize: int64; { file offset and size of text, at Base + textOff } - roOff, roSize: int64; { rodata, the room for the loader's tables included } - roAdr: int64; { where rodata is loaded } - extraAdr: int64; { that room } - bssAdr, bssSize: int64; { the writable segment, the loader's table first } - bssOff: int64; { the file offset of that table } - textImg, roImg: PBytes; - placesChunk: longint = -1; { the rodata chunk of the places, made here } - linesOff, linesSize: int64; { the line table, in the places: .debug_line } - -procedure MarkLive(entry: longint); -procedure LinkAll(headerSize, roExtra, dynSize: int64); - -implementation - -{ Marks live each chunk reached from entry through the fixups. } -procedure MarkLive(entry: longint); -var stack: PLongs; sp, c, f, t: longint; fx: PFixups; -begin - stack := GetMem(numChunks * 4); - sp := 0; - chunks^[entry].live := true; - stack^[0] := entry; - sp := 1; - while sp > 0 do begin - dec(sp); - c := stack^[sp]; - if chunks^[c].size < 0 then Fatal(ChunkName(c) + ' is declared but never defined'); - { code and constants have fixups; variables start at zero, holding - no addresses } - case chunks^[c].sec of - secText: fx := fixups; - secRodata: fx := dataFixups; - else continue; - end; - for f := chunks^[c].firstFix to chunks^[c].firstFix + chunks^[c].numFix - 1 do begin - t := fx^[f].chunk; - if not chunks^[t].live then begin - chunks^[t].live := true; - stack^[sp] := t; - inc(sp); - end; - end; - end; - FreeMem(stack); -end; - -{ Gives the live chunks of one section their places, from start; - returns the end. } -function Place(sec: TSection; start: int64): int64; -var c: longint; a: int64; -begin - a := start; - for c := 0 to numChunks - 1 do - if chunks^[c].live and (chunks^[c].sec = sec) then begin - a := (a + chunks^[c].align - 1) div chunks^[c].align * chunks^[c].align; - chunks^[c].adr := a; - a := a + chunks^[c].size; - end; - Place := a; -end; - -{ The line table, DWARF 4's line program, which gdb reads as - .debug_line and Rt to say where code comes from: one sequence for - each live procedure with lines, a row for each place noted, its - address, file, line and column. A row whose address and line move a - little is one byte, a special opcode; the others are made of the - standard ones. Made in lp, lpLen bytes long. } -const - LineBase = -5; LineRange = 14; OpcodeBase = 13; { the special opcodes' } - -var - lp: PBytes; - lpLen, lpCap: longint; - -procedure PutB(v: int64); -begin - if lpLen = lpCap then begin - lpCap := lpCap * 2 + 256; - lp := ReAllocMem(lp, lpCap); - end; - lp^[lpLen] := byte(v); - inc(lpLen); -end; - -procedure PutN(v: int64; n: longint); -var i: longint; -begin - for i := 1 to n do begin PutB(v); v := v shr 8 end; -end; - -{ LEB128, unsigned and signed } -procedure PutU(v: int64); -begin - while v >= $80 do begin PutB(v and $7F or $80); v := v shr 7 end; - PutB(v); -end; - -procedure PutS(v: int64); -begin - while (v < -64) or (v >= 64) do begin PutB(v and $7F or $80); v := SarInt64(v, 7) end; - PutB(v and $7F); -end; - -{ The line program of the files paths, nfiles of them, numbered from - 1, as they are written in the table } -procedure MakeLines(paths: PLongs; nfiles: longint); -var i, f, c, cf, cl, cc, op: longint; at, da, dl: int64; s: shortstring; -begin - lpLen := 0; - PutN(0, 4); { unit_length, patched below } - PutN(4, 2); { version } - PutN(0, 4); { header_length, patched below } - PutB(1); PutB(1); { minimum_instruction_length, maximum_operations } - PutB(1); { default_is_stmt } - PutB(LineBase); PutB(LineRange); PutB(OpcodeBase); - for i := 1 to OpcodeBase - 1 do PutB(ord(i in [2, 3, 4, 5, 9, 12])); { their operands } - PutB(0); { no include directories } - for f := 0 to nfiles - 1 do begin - s := ShownPath(NameOf(paths^[f])); - for i := 1 to length(s) do PutB(ord(s[i])); - PutN(0, 4); { its end, directory, time, length } - end; - PutB(0); - PLongint(@lp^[6])^ := lpLen - 10; - i := 0; - while i < numLines do begin - c := lines^[i].chunk; - if not chunks^[c].live then begin inc(i); continue end; - PutB(0); PutU(9); PutB(2); { DW_LNE_set_address } - PutN(chunks^[c].adr + lines^[i].at - chunks^[c].start, 8); - at := lines^[i].at; cf := 1; cl := 1; cc := 0; - while (i < numLines) and (lines^[i].chunk = c) do begin - f := 1; - while paths^[f - 1] <> lines^[i].path do inc(f); - if f <> cf then begin PutB(4); PutU(f); cf := f end; { DW_LNS_set_file } - if lines^[i].col <> cc then begin PutB(5); PutU(lines^[i].col); cc := lines^[i].col end; { DW_LNS_set_column } - da := lines^[i].at - at; - dl := lines^[i].line - cl; - op := (dl - LineBase) + LineRange * da + OpcodeBase; - if (dl >= LineBase) and (dl < LineBase + LineRange) and (op <= 255) then PutB(op) { a special opcode: a row } - else begin - if da > 0 then begin PutB(2); PutU(da) end; { DW_LNS_advance_pc } - if dl <> 0 then begin PutB(3); PutS(dl) end; { DW_LNS_advance_line } - PutB(1); { DW_LNS_copy: a row } - end; - at := lines^[i].at; cl := lines^[i].line; - inc(i); - end; - PutB(2); PutU(chunks^[c].start + chunks^[c].size - at); - PutB(0); PutU(1); PutB(1); { DW_LNE_end_sequence } - end; - PLongint(@lp^[0])^ := lpLen - 4; -end; - -{ The places that Rt reads to say where a failed check or a signal - was, and what calls were under way: where the line table is in them, - where text starts and stops, the numbers of procedures and of their - variables (I64s); for each live procedure where it starts and 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 names, each ending in a zero - byte; then the line table (MakeLines), at linesOff. They are in no - order, since Rt looks at them only as the program stops. } -procedure MakePlaces(start, stop: int64); -var - files, first, count: PLongs; buf: PBytes; - i, f, nfiles, k, np, nv, c, v, at, names: longint; - - procedure Name(const s: shortstring); - begin - PLongint(@buf^[at])^ := names - k; - Move(s[1], buf^[names], length(s)); - buf^[names + length(s)] := 0; - names := names + length(s) + 1; - at := at + 4; - end; - -begin - files := GetMem(numLines * 4 + 4); - first := GetMem(numChunks * 4); - count := GetMem(numChunks * 4); - FillChar(count^, numChunks * 4, 0); - for v := numVarNotes - 1 downto 0 do begin - first^[varNotes[v].chunk] := v; - inc(count^[varNotes[v].chunk]); - end; - nfiles := 0; k := 0; np := 0; nv := 0; - for i := 0 to numLines - 1 do - if chunks^[lines^[i].chunk].live then begin - f := 0; - while (f < nfiles) and (files^[f] <> lines^[i].path) do inc(f); - if f = nfiles then begin - files^[f] := lines^[i].path; - inc(nfiles); - end; - end; - MakeLines(files, nfiles); - for c := 0 to numChunks - 1 do - if chunks^[c].live and (chunks^[c].sec = secText) and (chunks^[c].module >= 0) then begin - inc(np); - k := k + length(ChunkName(c)) + 1; - 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 + 28 * np + 12 * nv + k + lpLen); - { the pool of names starts at k, the line table after it } - k := 40 + 28 * np + 12 * nv; - names := k; - at := 40; - v := 0; - for c := 0 to numChunks - 1 do - if chunks^[c].live and (chunks^[c].sec = secText) and (chunks^[c].module >= 0) then begin - PLongint(@buf^[at])^ := chunks^[c].adr; - PLongint(@buf^[at + 4])^ := chunks^[c].adr + chunks^[c].size; - at := at + 8; - Name(ChunkName(c)); - PLongint(@buf^[at])^ := v; - PLongint(@buf^[at + 4])^ := count^[c]; - 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 - if chunks^[c].live and (chunks^[c].sec = secText) and (chunks^[c].module >= 0) then - for v := first^[c] to first^[c] + count^[c] - 1 do begin - Name(NameOf(varNotes[v].name)); - PLongint(@buf^[at])^ := varNotes[v].off; - PLongint(@buf^[at + 4])^ := varNotes[v].kind; - at := at + 8; - end; - linesOff := names; - linesSize := lpLen; - Move(lp^, buf^[names], lpLen); - PInt64(@buf^[0])^ := linesOff; - PInt64(@buf^[8])^ := start; - PInt64(@buf^[16])^ := stop; - PInt64(@buf^[24])^ := np; - PInt64(@buf^[32])^ := nv; - SetData(placesChunk, buf, names + lpLen, 8); - FreeMem(buf); FreeMem(files); FreeMem(first); FreeMem(count); -end; - -{ Places the live chunks, leaving roExtra bytes at the end of rodata - and dynSize at the start of the writable segment. The segments follow - each other in the file with no padding, and each is loaded a page - further from its file offset than the one before: rodata at Base + - Page + roOff, the writable segment at Base + 2 * Page + bssOff. So an - address and its offset agree within a page, as the loader needs, and - no two segments, with their different permissions, share a page. - The bss of a program without the loader's table has no bytes in the - file, and starts on a page of its own. } -procedure LinkAll(headerSize, roExtra, dynSize: int64); -var c, f, at: longint; e, p, v: int64; -begin - textOff := (headerSize + 31) div 32 * 32; { as each code chunk is } - e := Place(secText, Base + textOff); - textSize := e - (Base + textOff); - if placesChunk >= 0 then MakePlaces(Base + textOff, e); - roOff := (textOff + textSize + 31) div 32 * 32; - roAdr := Base + Page + roOff; - e := Place(secRodata, roAdr); - extraAdr := (e + 7) div 8 * 8; - if roExtra > 0 then e := extraAdr + roExtra; - roSize := e - roAdr; - bssOff := (roOff + roSize + 31) div 32 * 32; - if dynSize > 0 then bssAdr := Base + 2 * Page + bssOff - else bssAdr := (roAdr + roSize + Page - 1) div Page * Page; - e := Place(secBss, bssAdr + dynSize); - bssSize := e - bssAdr; - - textImg := GetMem(textSize + 1); - { the gaps between code chunks are int3, a trap if ever run } - FillChar(textImg^, textSize + 1, $CC); - roImg := GetMem(roSize + 1); - FillChar(roImg^, roSize + 1, 0); - for c := 0 to numChunks - 1 do - if chunks^[c].live then - case chunks^[c].sec of - secText: begin - p := chunks^[c].adr - (Base + textOff); - Move(code^[chunks^[c].start], textImg^[p], chunks^[c].size); - for f := chunks^[c].firstFix to chunks^[c].firstFix + chunks^[c].numFix - 1 do begin - at := fixups^[f].at - chunks^[c].start; - { rel32: from the end of the field to the target } - v := chunks^[fixups^[f].chunk].adr + fixups^[f].addend - - (chunks^[c].adr + at + 4); - PLongint(@textImg^[p + at])^ := longint(v); - end; - end; - secRodata: begin - p := chunks^[c].adr - roAdr; - Move(rodata^[chunks^[c].start], roImg^[p], chunks^[c].size); - for f := chunks^[c].firstFix to chunks^[c].firstFix + chunks^[c].numFix - 1 do - PInt64(@roImg^[p + dataFixups^[f].at])^ := - chunks^[dataFixups^[f].chunk].adr + dataFixups^[f].addend; - end; - end; -end; - -end. diff --git a/seed/parse.pas b/seed/parse.pas deleted file mode 100644 index 58ca27a..0000000 --- a/seed/parse.pas +++ /dev/null @@ -1,3285 +0,0 @@ -{ parse.pas: the parser. - - Reads modules by recursive descent and has gen.pas emit code as it - goes: one pass, no tree. Importing a module that isn't compiled yet - compiles it there and then, so modules are finished in an order where - each comes after the modules it imports; that is the order in which - their bodies run. - - A module may come in one file per target (Name.linux-x86_64.raz and - so on). The file for this target is compiled; the others beside it - are read for their declarations only, and must export the same - interface. - - Depends on: scan, sym, chunk for data, item and gen for code. - Leaves out: linking; a module only records the libraries it names, - and whether it uses C or says link static. } - -unit parse; - -{$mode objfpc}{$H-} - -interface - -uses scan, diag, sym, chunk, gen, item; - -const - Target = 'linux-x86_64'; - TargetOS = 'linux'; - TargetArch = 'x86_64'; - { Whether the target has reals (report, appendix A): x86-64 always has - SSE2. Without them, used code that computes with one is an error, - which raz.pas reports once it knows what the program uses. } - HasReals: boolean = true; - -var - libDir, mainDir: shortstring; - incDirs: array[0..15] of shortstring; - numInc: longint; - firstModule, lastModule: PModule; { in the order they were finished } - -function CompileMain(const path: shortstring): PModule; -function ImportModule(name: longint; const args: TArgs): PModule; - -implementation - -uses BaseUnix; - -type - PLoop = ^TLoop; - TLoop = record - brk: longint; { the chain of its breaks } - base: longint; { the deferred statements in force outside it } - end; - - { A generic module's import whose instance isn't made yet (deferred, - numDeferred); not to be confused with a defer statement (defers) } - TDeferred = record - o: PObj; { the name it imports as } - m: PModule; { the module that imports it } - mname: longint; { the generic module } - args: TScanState; { at the "(" of its arguments } - at: TPos; { the import } - end; - -var - checkMode: boolean; { reading a file only for its interface } - inTypes: boolean; { in a type section: ^T may name a later type } - fwdTypes: array[0..255] of PType; - fwdPos: array[0..255] of TPos; { where each names its type } - numFwd: longint; - lastCalled: PObj; { the procedure the last call was of, if it had a name } - passOn: boolean; { the next factor may be a call with several results, for return } - curProc: PObj; { the procedure being compiled, or nil } - declExported: boolean; { the export mark of the declaration being read } - curLoop: PLoop; { the innermost loop, or nil } - defers: array[0..63] of longint; { the defer statements in force, their code's addresses } - numDefers: longint; - deferring: boolean; { compiling a defer statement's statement } - directDefer: boolean; { ... as the statement itself, not in a list } - deferSlot: int64; { keeps a result while deferred statements run } - 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, 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 } - deferred: array[0..63] of TDeferred; { generic imports not yet made, not defer statements } - numDeferred: longint; - making: boolean; { reading an instance's arguments, at its first use } - stray: boolean; { an "end" in this procedure stood left of its statement's line } - strayAt: TPos; { ... the first such statement } - elseIf: boolean; { an "else if" in this procedure } - drops: array[0..4095] of record - at: TPos; { a call standing on its own that drops results } - n: longint; { ... how many } - end; - numDrops: longint; { the module being compiled has those from its - first one, saved by CompileFile, to here } - ends: boolean; { the statements just read never go on past - their end: each way through them returns } - useAt: TPos; { ... which is here } - -procedure Expression(var x: TItem; want: PType); forward; -function ParseType: PType; forward; -procedure Statements; forward; -procedure Statement; forward; - -{ Little helpers } - -{ A missing symbol is reported just after the one before it. } -procedure Expected(const what: shortstring); -begin - if tok = sBlank then Mark('_ isn''t a name: it is the blank, which stands only left of :='); - MarkAt(MissingPos, 'expected ' + what + ', found ' + Found); -end; - -procedure Expect(s: TSym); -begin - if (tok = sLbrace) and (s in [sThen, sDo]) then - MarkHelp(MissingPos, 'expected ' + SymText(s) + ', found ' + Found, 'a block is written ' + SymText(s) + ' ... end'); - if tok <> s then Expected(SymText(s)); - Next; -end; - -{ The end of a block statement at start, whose line is indented to - ind. An "end" left of that was most likely meant for a block around - the statement, which leaves the statement's own "end" missing: the - first such is kept for EndMissing. } -procedure CloseEnd(const start: TPos; ind: longint); -begin - if (tok = sEnd) and not stray and (Indent < ind) then begin - stray := true; - strayAt := start; - end; - Expect(sEnd); -end; - -{ The error of a procedure or module whose own "end" isn't where it - should be, with what CloseEnd saw } -procedure EndMissing(const p: TPos; const msg: shortstring); -begin - Error(p, msg); - if stray then Note(strayAt, 'is this statement''s "end" missing? one further left closes it'); - if elseIf then Help('raz writes elsif: "else if" begins an if that needs its own "end"'); - Fail; -end; - -function Name(const s: shortstring): longint; -begin - Name := Intern(@s[1], length(s)); -end; - -{ A name being declared, and whether it is exported; at is the name } -procedure IdentDef(var n: longint; var exp: boolean; var at: TPos); -begin - if tok <> sIdent then Expected('a name'); - n := id; - at := TokPos; - Next; - exp := false; - if tok = sTimes then begin - exp := true; - Next; - end; -end; - -{ Declares o in the innermost scope. Its module keeps its declarations - in order: its own, for the interface check, and its procedures', to - warn of those never used. } -procedure Declare(o: PObj); -begin - Insert(o, TopScope); - if TopScope = curModule^.scope then begin - if curModule^.last = nil then curModule^.first := o - else curModule^.last^.link := o; - curModule^.last := o; - end else begin - if curModule^.lastLocal = nil then curModule^.locals := o - else curModule^.lastLocal^.link := o; - curModule^.lastLocal := o; - end; -end; - -{ o is named: a procedure naming itself doesn't count } -procedure Named(o: PObj); -begin - if o <> curProc then begin - o^.used := true; - o^.read := true; - end; -end; - -{ Recovery - - After an error the parser goes on with the next statement or - declaration, so that one run reports every error. Each statement and - declaration is a recovery point: it notes the state of the scanner - and the parser where it starts, and an error (MarkAt) jumps back to - it. The state is put back, the scanner reads the construct again - from its start, skipping to its end, and the parser carries on after - it. Nothing is generated after an error, so the code half made for - the construct does no harm. A name that isn't declared is declared - where it is used, with type tPoison, and what follows from it is not - reported again; so are the names of a declaration that had an error. - - Skipping counts the words that open and close blocks. A symbol at - the start of a line is taken to start a declaration of the module, - as layout has it: a statement skipped up to one gives up its - procedure, and the procedure is skipped up to its end. } - -type - TRecover = record - jb: jmp_buf; - outer: ^jmp_buf; - scan: TScanState; - scopes, depth, pushed, numDefers: longint; - loop: PLoop; - result: PType; - deferring, directDefer, quiet: boolean; - end; - -procedure Guard(var r: TRecover); -begin - r.outer := recovery; - SaveScan(r.scan); - r.scopes := ScopeDepth; r.depth := depth; r.pushed := pushed; r.numDefers := numDefers; - r.loop := curLoop; r.result := curResult; - r.deferring := deferring; r.directDefer := directDefer; r.quiet := quiet; - recovery := @r.jb; - quiet := false; -end; - -procedure Unguard(var r: TRecover); -begin - recovery := r.outer; - quiet := r.quiet; - skipping := false; -end; - -{ After an error: the state as it was at the start of r's construct, - whose first symbol is again the current one } -procedure Restore(var r: TRecover); -begin - RestoreScan(r.scan); - skipping := true; - CutScopes(r.scopes); ResetStack(r.depth, r.pushed); numDefers := r.numDefers; - curLoop := r.loop; curResult := r.result; - deferring := r.deferring; directDefer := r.directDefer; - inTypes := false; declExported := false; inExtern := false; making := false; -end; - -{ Gives up the construct r is for, and the one around it } -procedure GiveUp(var r: TRecover); -begin - Unguard(r); - if recovery = nil then Finish; - longjmp(recovery^, 1); -end; - -{ Reads to the end of a statement or declaration, from its first - symbol: up to the ";" that ends it, not read, or to the "end", - "else", "elsif", "until" or "|" of the statement around it (an arm's - "|" comes after a ";", the operator's after an operand). False if it - stopped at a symbol that starts a line, or the end of the file. } -function SkipConstruct: boolean; -var d, p: longint; prev: TSym; -begin - d := 0; p := 0; prev := sSemicolon; - repeat - case tok of - sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: inc(d); - sEnd, sUntil: if d = 0 then exit(true) else dec(d); - sElse, sElsif: if (d = 0) and (p = 0) then exit(true); - sBar: if (d = 0) and (p = 0) and (prev = sSemicolon) then exit(true); - sLparen, sLbrak, sLbrace: inc(p); - sRparen, sRbrak, sRbrace: if p > 0 then dec(p); - sSemicolon: if (d = 0) and (p = 0) then exit(true); - sEof: exit(false); - end; - prev := tok; - Next; - until AtLineStart; - SkipConstruct := false; -end; - -{ Declares n where it is used, after it was reported as not declared, - or after the declaration of it had an error } -function Poison(n: longint): PObj; -var o: PObj; -begin - o := NewObj(oConst, n, tPoison); - Insert(o, TopScope); - Poison := o; -end; - -procedure WillDeclare(n: longint); -begin - if numDeclaring <= High(declaring) then declaring[numDeclaring] := n; - inc(numDeclaring); -end; - -{ After a declaration had an error: its names are poison, and reading - goes on after it } -procedure SkipDeclaration; -var i: longint; -begin - for i := 0 to numDeclaring - 1 do - if (i <= High(declaring)) and (Find(TopScope, declaring[i]) = nil) then - Poison(declaring[i]); - if SkipConstruct and (tok = sSemicolon) then Next; -end; - -function ConstValue(var x: TItem): int64; -begin - if x.mode <> mConst then MarkAt(x.pos, 'expected a constant'); - ConstValue := x.val; -end; - -function ConstExpr: int64; -var x: TItem; -begin - Expression(x, nil); - if not IsInt(x.typ) then MarkAt(x.pos, 'expected an integer constant, found ' + What(x)); - ConstExpr := ConstValue(x); -end; - -{ Help after a name that isn't found: o, the closest name in reach } -procedure DidYouMean(o: PObj); -begin - if o <> nil then Help('did you mean ' + NameOf(o^.name) + '?'); -end; - -{ Where module n is found, if it is: dir and the file in it } -function ModuleFile(n: longint; var dir, f: shortstring): boolean; forward; - -{ Reports name n at p as not declared, with what it may have meant } -procedure NotDeclared(const p: TPos; n: longint); -var dir, f: shortstring; -begin - Error(p, NameOf(n) + ' isn''t declared'); - if ModuleFile(n, dir, f) then Help(NameOf(n) + ' is a module: import ' + NameOf(n)) - else if (NameOf(n) = 'elif') or (NameOf(n) = 'elseif') then Help('raz writes elsif') - else if Reserved(Name(LowerCase(NameOf(n)))) then Help('a reserved word is written in lower case: ' + LowerCase(NameOf(n))) - else DidYouMean(Closest(n, -1)); -end; - -procedure FirstUse(o: PObj; const at: TPos); forward; -procedure InstancesFor(wholeRest: boolean); forward; -procedure AddImport(m, im: PModule); forward; - -function QualIdent: PObj; -var o: PObj; m: PModule; at: TPos; -begin - if tok <> sIdent then Expected('a name'); - at := TokPos; - o := Lookup(id); - if o = nil then begin - if not making then Poison(id); { it may yet be declared } - quiet := false; - NotDeclared(at, id); - if making then Note(useAt, 'the instance is made here, where it is first used'); - Fail; - end; - if o^.typ = tPoison then quiet := true; - Named(o); - Next; - if o^.cls = oModule then begin - if o^.module = nil then FirstUse(o, at); - Expect(sPeriod); - if tok <> sIdent then Expected('a name'); - m := o^.module; - o := Find(m^.scope, id); - if (o = nil) or not o^.exported then begin - Error(TokPos, NameOf(id) + ' isn''t exported by ' + NameOf(m^.name)); - if o <> nil then Note(o^.pos, NameOf(id) + ' is declared here, without a *') - else DidYouMean(Closest(id, m^.scope)); - Fail; - end; - Next; - end; - QualIdent := o; -end; - -{ The field of record type t named by the current symbol } -function FieldOf(t: PType): PObj; -var f: PObj; -begin - f := Find(t^.scope, id); - if f = nil then begin - Error(TokPos, TypeName(t) + ' has no field ' + NameOf(id)); - DidYouMean(Closest(id, t^.scope)); - Fail; - end; - if not f^.exported and (t^.module <> curModule) then begin - Error(TokPos, 'field ' + NameOf(id) + ' of ' + TypeName(t) + ' isn''t exported'); - Note(f^.pos, NameOf(id) + ' is declared here, without a *'); - Fail; - end; - FieldOf := f; -end; - -function NewPtr(base: PType; vol: boolean): PType; -var t: PType; -begin - t := NewType(fPtr, 8, 8); - t^.base := base; - t^.vol := vol; - NewPtr := t; -end; - -{ Types } - -function RecordType: PType; -var - t, ft: PType; f, last: PObj; names: array[0..63] of longint; - exps: array[0..63] of boolean; poss: array[0..63] of TPos; - n, i: longint; off, a, maxA: int64; -begin - t := NewType(fRecord, 0, 1); - if tok = sPacked then begin t^.packd := true; Next end; - Expect(sRecord); - t^.scope := NewScope; - off := 0; maxA := 1; last := nil; - while tok = sIdent do begin - n := 0; - repeat - if n > High(names) then Mark('more than ' + IntStr(High(names) + 1) + ' names in one declaration'); - IdentDef(names[n], exps[n], poss[n]); - inc(n); - if tok <> sComma then break; - Next; - until false; - Expect(sColon); - ft := ParseType; - if t^.packd then a := 1 else a := ft^.align; - for i := 0 to n - 1 do begin - off := AlignUp(off, a); - f := NewObj(oField, names[i], ft); - f^.exported := exps[i]; - f^.pos := poss[i]; - f^.val := off; - Insert(f, t^.scope); - if last = nil then t^.fields := f else last^.next := f; - last := f; - off := off + ft^.size; - end; - if a > maxA then maxA := a; - Expect(sSemicolon); - end; - Expect(sEnd); - t^.align := maxA; - t^.size := AlignUp(off, maxA); - RecordType := t; -end; - -function VariantType: PType; -var t, ft: PType; c, lastC, f, lastF: PObj; tag, off, maxSize: int64; n: longint; -begin - Expect(sVariant); - t := NewType(fVariant, 8, 8); - tag := 0; maxSize := 8; lastC := nil; - while tok = sIdent do begin - c := NewObj(oCase, id, t); - c^.val := tag; - c^.exported := declExported; - Declare(c); - if lastC = nil then t^.fields := c else lastC^.next := c; - lastC := c; - Next; - off := 8; - if tok = sLparen then begin - Next; - lastF := nil; - repeat - n := 0; - repeat - if tok <> sIdent then Expected('a name'); - f := NewObj(oField, id, nil); - f^.exported := true; - if lastF = nil then c^.fields := f else lastF^.next := f; - lastF := f; - inc(n); - Next; - if tok <> sComma then break; - Next; - until false; - Expect(sColon); - ft := ParseType; - f := c^.fields; - while f^.typ <> nil do f := f^.next; - while f <> nil do begin - f^.typ := ft; - off := AlignUp(off, ft^.align); - f^.val := off; - off := off + ft^.size; - f := f^.next; - end; - if ft^.align > t^.align then t^.align := ft^.align; - if tok <> sSemicolon then break; - Next; - until false; - Expect(sRparen); - end; - if off > maxSize then maxSize := off; - Expect(sSemicolon); - inc(tag); - end; - Expect(sEnd); - t^.len := tag; - t^.size := AlignUp(maxSize, t^.align); - VariantType := t; -end; - -{ Several results: a record of them, laid out as C would, and - returned in rax and rdx if they are two words (InTwoRegs), or else - through a hidden pointer. } -function Results: PType; -var t, ft: PType; f, last: PObj; off: int64; -begin - Next; - t := NewType(fRecord, 0, 1); - t^.tuple := true; - off := 0; last := nil; - repeat - ft := ParseType; - off := AlignUp(off, ft^.align); - f := NewObj(oField, -1, ft); - f^.val := off; - off := off + ft^.size; - if ft^.align > t^.align then t^.align := ft^.align; - if last = nil then t^.fields := f else last^.next := f; - last := f; - inc(t^.len); - if tok <> sComma then break; - Next; - until false; - Expect(sRparen); - t^.size := AlignUp(off, t^.align); - if t^.len = 1 then Results := t^.fields^.typ else Results := t; -end; - -function Signature: PType; -var - t, pt: PType; p, first, last: PObj; isVar: boolean; n: longint; -begin - t := NewType(fProc, 8, 8); - last := nil; n := 0; - if tok = sLparen then begin - Next; - if tok <> sRparen then - repeat - if tok = sEllipsis then begin - if not inExtern then Mark('... is only for extern procedures'); - Next; t^.variadic := true; break - end; - isVar := tok = sVar; - if isVar then Next; - first := nil; - repeat - if tok <> sIdent then Expected('a name'); - p := NewObj(oVar, id, nil); - p^.isVar := isVar; - p^.lev := 1; - if last = nil then t^.fields := p else last^.next := p; - last := p; - if first = nil then first := p; - inc(n); - Next; - if tok <> sComma then break; - Next; - until false; - Expect(sColon); - pt := ParseType; - while first <> nil do begin first^.typ := pt; first := first^.next end; - if tok <> sSemicolon then break; - Next; - until false; - Expect(sRparen); - end; - t^.len := n; - if tok = sColon then begin - Next; - if tok = sLparen then t^.base := Results else t^.base := ParseType; - end; - Signature := t; -end; - -function EnumType: PType; -var t: PType; o, last: PObj; start: TPos; -begin - start := TokPos; - t := NewType(fEnum, 1, 1); - last := nil; - repeat - Next; - if tok <> sIdent then Expected('a name'); - o := NewObj(oConst, id, t); - o^.val := t^.len; - o^.exported := declExported; - o^.used := true; { an enumeration's names are its type's, warned of with it } - Declare(o); - if last = nil then t^.fields := o else last^.next := o; - last := o; - inc(t^.len); - Next; - until tok <> sComma; - Expect(sRparen); - if t^.len > 256 then MarkAt(SpanFrom(start), 'an enumeration has at most 256 names'); - EnumType := t; -end; - -function SetOf(e: PType; const at: TPos): PType; -var t: PType; -begin - if (e^.form <> fEnum) or (e^.len > 64) then MarkAt(at, 'a set needs an enumeration of at most 64 names, found ' + TypeName(e)); - t := NewType(fSet, 8, 8); - if e^.len <= 8 then t^.size := 1 - else if e^.len <= 16 then t^.size := 2 - else if e^.len <= 32 then t^.size := 4; - t^.align := t^.size; - t^.base := e; - t^.len := e^.len; - SetOf := t; -end; - -function ParseType: PType; -var t: PType; o: PObj; n: int64; vol: boolean; start: TPos; -begin - start := TokPos; - case tok of - sIdent: begin - o := QualIdent; - if o^.cls <> oType then MarkAt(SpanFrom(start), NameOf(o^.name) + ' isn''t a type'); - t := o^.typ; - end; - sLbrak: begin - Next; - if tok = sRbrak then begin - Next; - t := NewType(fSlice, 16, 8); - t^.base := ParseType(); - end else begin - start := TokPos; - n := ConstExpr; - if (n <= 0) or (n > (int64(1) shl 40)) then MarkAt(SpanFrom(start), 'an array''s length is from 1 to 2^40, found ' + IntStr(n)); - Expect(sRbrak); - t := NewType(fArray, 0, 1); - t^.len := n; - t^.base := ParseType(); - t^.size := n * t^.base^.size; - t^.align := t^.base^.align; - end; - end; - sArrow: begin - Next; - vol := tok = sVolatile; - if vol then Next; - if inTypes and (tok = sIdent) and (Lookup(id) = nil) then begin - { a type declared later in this section } - t := NewPtr(nil, vol); - t^.fwd := id; - if numFwd > High(fwdTypes) then Mark('more than ' + IntStr(High(fwdTypes) + 1) + ' pointers to types not yet declared'); - fwdTypes[numFwd] := t; - fwdPos[numFwd] := TokPos; - inc(numFwd); - Next; - end else - t := NewPtr(ParseType(), vol); - end; - sPacked, sRecord: t := RecordType; - sVariant: t := VariantType; - sProc: begin Next; t := Signature end; - sLparen: t := EnumType; - sSet: begin - Next; - Expect(sOf); - start := TokPos; - t := SetOf(ParseType(), start); - end; - else Expected('a type'); - end; - ParseType := t; -end; - -{ Expressions } - -procedure Call(var x: TItem); -var c: TCall; a: TItem; want: PType; -begin - BeginCall(c, x); - Expect(sLparen); - if tok <> sRparen then - repeat - if c.param <> nil then want := c.param^.typ else want := nil; - Expression(a, want); - PassArg(c, a); - if tok <> sComma then break; - Next; - until false; - Expect(sRparen); - EndCall(c, x); -end; - -procedure Atomic(var x: TItem; which: longint); -var p, a: TItem; t: PType; i, n: longint; -begin - Expression(p, nil); - if p.typ^.form <> fPtr then MarkAt(p.pos, 'expected a pointer, found ' + What(p)); - t := p.typ^.base; - if not (IsWord(t) or ((t^.form = fPtr) and (which <> bXadd))) then - if which = bXadd then MarkAt(p.pos, 'expected a pointer to an INT or a UINT, found ' + TypeName(p.typ)) - else MarkAt(p.pos, 'expected a pointer to an INT, a UINT or a pointer, found ' + TypeName(p.typ)); - Value(p); - if which = bCas then n := 2 else n := 1; - for i := 1 to n do begin - Expect(sComma); - Expression(a, t); - Coerce(a, t); - Value(a); - end; - gen.Atomic(which); - MakeConst(x, t, 0); - if which = bCas then x.typ := tBool; - x.mode := mStack; -end; - -{ NEW(p, a): p := a^.alloc(a, SIZE(T), alignment), zeroed if not nil. - a is a ^Mem.Allocator, the one interface the compiler knows. } -procedure New_(var x: TItem); -var y, z: TItem; t: PType; f: PObj; s: int64; c: TCall; -begin - Expression(x, nil); - NotReadOnly(x); - if (x.mode <> mVar) or not x.isVar or (x.typ^.form <> fPtr) then MarkAt(x.pos, 'NEW needs a pointer variable'); - t := x.typ^.base; - Expect(sComma); - Expression(y, nil); - if (y.typ^.form <> fPtr) or (y.typ^.base^.obj = nil) or (y.typ^.base^.obj^.module = nil) - or (NameOf(y.typ^.base^.obj^.name) <> 'Allocator') - or (NameOf(y.typ^.base^.obj^.module^.name) <> 'Mem') then MarkAt(y.pos, 'NEW needs a ^Mem.Allocator, found ' + What(y)); - f := Find(y.typ^.base^.scope, Name('alloc')); - s := ToSlot(y); - PushVar(FrameAdr(s), 8, false, kWord); - MakeConst(z, f^.typ, 0); - z.mode := mVar; z.base := bStack; z.off := f^.val; - BeginCall(c, z); - PushVar(FrameAdr(s), 8, false, kWord); - MakeConst(z, y.typ, 0); - z.mode := mStack; - PassArg(c, z); - MakeConst(z, tInt, t^.size); - PassArg(c, z); - MakeConst(z, tInt, t^.align); - PassArg(c, z); - EndCall(c, z); - ZeroNew(t^.size); - z.typ := x.typ; - Assign(x, z); - MakeConst(x, tNone, 0); - x.mode := mNone; -end; - -function IncOrDec(which: longint): shortstring; -begin - if which = bDec then IncOrDec := 'DEC' else IncOrDec := 'INC'; -end; - -procedure Builtin(var x: TItem); -var which, n: longint; y: TItem; t: PType; -begin - which := x.obj^.val; - if which in [bFence, bArgc, bArgv] then begin - if tok = sLparen then begin Next; Expect(sRparen) end; - MakeConst(x, tNone, 0); - case which of - bFence: begin Fence; x.mode := mNone end; - bArgc: begin PushVar(GlobalAdr(argcChunk), 8, false, kWord); x.typ := tInt; x.mode := mStack end; - bArgv: begin PushVar(GlobalAdr(argvChunk), 8, false, kWord); x.typ := tArgv; x.mode := mStack end; - end; - exit; - end; - Expect(sLparen); - case which of - bSize: begin - t := ParseType; - MakeConst(x, tConst, t^.size); - end; - bAdr: begin - Expression(y, nil); - NotReadOnly(y); - if (y.mode <> mVar) or not y.isVar then MarkAt(y.pos, 'ADR needs a variable'); - if y.odd then MarkAt(y.pos, 'a field of a packed record has no address'); - t := NewPtr(y.typ, y.vol); - Address(y); - MakeConst(x, t, 0); - x.mode := mStack; - end; - bLen: begin - Expression(y, nil); - if y.mode = mStr then MakeConst(x, tConst, y.val) - else if y.typ^.form = fArray then begin - Discard(y); - MakeConst(x, tConst, y.typ^.len) - end else if (y.typ^.form = fSlice) and (y.mode = mVar) then begin - { its length, the word after its pointer } - y.off := y.off + 8; - y.typ := tInt; - Value(y); - x := y; - end else MarkAt(y.pos, 'LEN needs an array or a slice, found ' + What(y)); - end; - bSyscall: begin - n := 0; - repeat - if n > 0 then Next; - Expression(y, nil); - if not (IsScalar(y.typ) and (y.typ^.form <> fReal)) then MarkAt(y.pos, 'expected an integer or a pointer, found ' + What(y)); - if y.typ^.form = fConst then Coerce(y, tInt); - Value(y); - inc(n); - until (tok <> sComma) or (n = 7); - SysCall(n); - MakeConst(x, tInt, 0); - x.mode := mStack; - end; - bCas, bXchg, bXadd: Atomic(x, which); - bMsg: begin Expression(x, tError); Msg(x) end; - bInc, bDec: begin - Expression(x, nil); - 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'); - if x.base <> bReg then Address(x); - if tok = sComma then begin - Next; - Expression(y, x.typ); - end else MakeConst(y, x.typ, 1); - IncDec(x, y, which = bDec); - MakeConst(x, tNone, 0); - x.mode := mNone; - end; - bNew: New_(x); - bCopy: begin - Expression(x, nil); - CopyDest(x); - Expect(sComma); - Expression(y, nil); - CopyFrom(x, y); - MakeConst(x, tNone, 0); - x.mode := mNone; - end; - end; - Expect(sRparen); -end; - -procedure ConstructCase(var x: TItem; c: PObj; const at: TPos); -var f: PObj; a: TItem; -begin - Construct(x, c); - f := c^.fields; - if tok = sLparen then begin - Next; - while f <> nil do begin - Expression(a, f^.typ); - SetField(x, f, a); - f := f^.next; - if f <> nil then Expect(sComma); - end; - Expect(sRparen); - end else if f <> nil then MarkAt(at, NameOf(c^.name) + ' needs its fields'); -end; - -{ x, before ".", has no fields; tok is what follows. Other languages - write p.f through a pointer and s.len for a length. } -procedure FieldOfWhat(const x: TItem); -var msg, f: shortstring; -begin - msg := 'expected a record, found ' + What(x); - if tok = sIdent then f := NameOf(id) else f := ''; - if (x.typ^.form = fPtr) and (x.typ^.base^.form = fRecord) then - MarkHelp(x.pos, msg, 'through a pointer, write ' + Source(x.pos) + '^.' + f) - else if (x.typ^.form in [fArray, fSlice]) and ((f = 'len') or (f = 'length') or (f = 'size') or (f = 'count')) then - MarkHelp(x.pos, msg, 'its length is LEN(' + Source(x.pos) + ')'); - MarkAt(x.pos, msg); -end; - -{ A designator, with any selectors and calls after it. called tells - whether the last thing done was a call. } -procedure Designator(var x: TItem; var called: boolean); -var o, f: PObj; y, z: TItem; t: PType; start: TPos; -begin - start := TokPos; - o := QualIdent; - called := false; - if o^.cls = oModule then MarkAt(SpanFrom(start), NameOf(o^.name) + ' is a module, not a value'); - MakeItem(x, o); - if x.mode = mBuiltin then begin - Builtin(x); - called := true; - end else if x.mode = mCase then begin - ConstructCase(x, o, SpanFrom(start)); - end; - repeat - x.pos := SpanFrom(start); - case tok of - sPeriod: begin - Next; - if (x.mode <> mVar) or (x.typ^.form <> fRecord) then FieldOfWhat(x); - if tok <> sIdent then Expected('a field'); - f := FieldOf(x.typ); - Next; - Field(x, f); - called := false; - end; - sArrow: begin Next; Deref(x); called := false end; - sLbrak: begin - Next; - IndexPrep(x); - Expression(y, nil); - if tok = sUpto then begin - Next; - SliceLo(y); - Expression(z, nil); - Slice(x, y, z); - end else Index(x, y); - Expect(sRbrak); - called := false; - end; - sLparen: begin - if x.mode = mType then begin - t := x.typ; - Next; - Expression(x, nil); - Expect(sRparen); - Convert(x, t); - end else begin - if x.mode = mProc then lastCalled := x.obj else lastCalled := nil; - Call(x); - called := true; - end; - end; - else break; - end; - until false; - x.pos := SpanFrom(start); - NilTest(x); -end; - -procedure ArrayLiteral(var x: TItem; want: PType); -var - et, at: PType; e: TItem; slots: array[0..1023] of int64; n, i: longint; - off, es: int64; start: TPos; -begin - start := TokPos; - if (want = nil) or not (want^.form in [fArray, fSlice]) then - Mark('an array literal needs a known array or slice type'); - et := want^.base; - es := et^.size; - Next; - n := 0; - if tok <> sRbrak then - repeat - if n > High(slots) then Mark('more than ' + IntStr(High(slots) + 1) + ' elements'); - Expression(e, et); - Coerce(e, et); - if IsScalar(et) then slots[n] := ToSlot(e) - else begin - if e.isVar or e.vol or (e.mode <> mVar) or (e.base <> bFrame) then CopyToTemp(e); - slots[n] := e.off; - end; - inc(n); - if tok <> sComma then break; - Next; - until false; - Expect(sRbrak); - if (want^.form = fArray) and (n <> want^.len) then MarkAt(SpanFrom(start), 'expected ' + IntStr(want^.len) + ' elements, found ' + IntStr(n)); - if n = 0 then begin - PushConst(kWord, 0); - SliceOf(x, want, 0); - exit; - end; - if want^.form = fArray then begin - at := want; - off := AllocTemp(at^.size, at^.align); - end else begin - at := NewType(fArray, n * es, et^.align); - at^.len := n; - at^.base := et; - off := AllocPerm(at^.size, at^.align); { lives as long as the call } - end; - for i := 0 to n - 1 do - if IsScalar(et) then begin - PushVar(FrameAdr(slots[i]), 8, false, KindOf(et)); - PopVar(FrameAdr(off + i * es), ScalarSize(et)); - end else begin - PushAdr(FrameAdr(slots[i])); - CopyTo(FrameAdr(off + i * es), es); - end; - TempItem(x, at, off); -end; - -{ A record literal: a zeroed temporary, with the fields named filled in. } -procedure RecordLiteral(var x: TItem; t: PType); -var f: PObj; a: TItem; seen: array[0..63] of longint; n, i: longint; -begin - Next; - ZeroTemp(x, t); - FillChar(seen, SizeOf(seen), 0); - n := 0; - if tok <> sRbrace then - repeat - if tok <> sIdent then Expected('a field'); - f := FieldOf(t); - for i := 0 to n - 1 do if seen[i] = id then Mark('field ' + NameOf(id) + ' is given twice'); - if n <= High(seen) then begin seen[n] := id; inc(n) end; - Next; - Expect(sColon); - Expression(a, f^.typ); - SetField(x, f, a); - if tok <> sComma then break; - Next; - until false; - Expect(sRbrace); -end; - -{ A set literal: the bits of the constant names, or'd at run time with - those of the others. } -procedure SetLiteral(var x: TItem; t: PType); -var e: TItem; bits, slot: int64; start: TPos; s: shortstring; -begin - start := TokPos; - Next; - if (t <> nil) and (t^.form <> fSet) then MarkAt(SpanFrom(start), 'expected a set type, found ' + TypeName(t)); - bits := 0; - slot := 0; - if tok <> sRbrace then - repeat - if t = nil then Expression(e, nil) else Expression(e, t^.base); - if t = nil then begin - if e.typ^.form <> fEnum then MarkAt(e.pos, 'a set holds names of an enumeration, found ' + What(e)); - t := SetOf(e.typ, e.pos); - end; - if not Same(e.typ, t^.base) then begin - if e.obj <> nil then s := NameOf(e.obj^.name) else s := What(e); - MarkAt(e.pos, s + ' isn''t a name of ' + TypeName(t^.base)); - end; - if e.mode = mConst then bits := bits or (int64(1) shl e.val) - else begin - if slot = 0 then begin - slot := AllocTemp(8, 8); - PushConst(kWord, 0); - PopVar(FrameAdr(slot), 8); - end; - Value(e); - PushConst(kWord, 1); - Swap; - Op(sShl, kWord, 8, false); - PushVar(FrameAdr(slot), 8, false, kWord); - Op(sBar, kWord, 8, false); - PopVar(FrameAdr(slot), 8); - end; - if tok <> sComma then break; - Next; - until false; - Expect(sRbrace); - if t = nil then MarkAt(SpanFrom(start), '{} needs a known set type'); - MakeConst(x, t, bits); - if slot <> 0 then begin - PushVar(FrameAdr(slot), 8, false, kWord); - PushConst(kWord, bits); - Op(sBar, kWord, 8, false); - x.mode := mStack; - end; -end; - -procedure RunDefers(base: longint); forward; - -{ The type of the last result of t, the results of a procedure: t if - it has one, else the last of its several. } -function LastResult(t: PType): PType; -var f: PObj; -begin - if not t^.tuple then exit(t); - f := t^.fields; - while f^.next <> nil do f := f^.next; - LastResult := f^.typ; -end; - -{ The results of the tuple t but the last: the same fields, one fewer } -function WithoutLast(t: PType): PType; -var r: PType; -begin - r := NewType(fRecord, t^.size, t^.align); - r^.tuple := true; - r^.fields := t^.fields; - r^.len := t^.len - 1; - WithoutLast := r; -end; - -{ try c (the report, 7.8): the call c, then the error it returned, its - last result: if that isn't nil, the procedure returns it, and a zero - for each of its other results, after running the deferred statements - in force. x is left c's other results: none (mNone), one (a value) or - several (a tuple, for a multiple assignment). The error is kept in a - slot of the frame, and tested there; the code for it, out of line, - is made with the stack of values as it stands, and leaves it so, - since what follows is the code for an error that is nil. } -procedure TryCall(var x: TItem); -var - called: boolean; c: TCall; start, at: TPos; res: PType; last: PObj; slot: int64; ok: longint; -begin - start := TokPos; - Next; - if deferring then MarkAt(SpanFrom(start), 'try can''t leave a deferred statement'); - if curResult = nil then - MarkAt(SpanFrom(start), 'try needs a procedure that ends in an ERROR result, and this returns nothing') - else if LastResult(curResult) <> tError then - MarkAt(SpanFrom(start), 'try needs a procedure that ends in an ERROR result, and this returns ' + TypeName(curResult)); - Designator(x, called); - if not called and ((x.mode = mProc) or ((x.mode in [mVar, mStack]) and (x.typ^.form = fProc))) then begin - { a procedure without parameters, written without parentheses } - at := x.pos; - BeginCall(c, x); - EndCall(c, x); - x.pos := at; - called := true; - end; - if not called then MarkAt(x.pos, 'try needs a call, found ' + What(x)); - if x.mode = mNone then - MarkAt(x.pos, 'try needs a call that returns an ERROR last, and this returns nothing'); - if LastResult(x.typ) <> tError then - MarkAt(x.pos, 'try needs a call that returns an ERROR last, and this returns ' + TypeName(x.typ)); - res := x.typ; - if x.mode = mStack then begin - { an ERROR alone } - slot := AllocTemp(8, 8); - PopVar(FrameAdr(slot), 8); - x.mode := mNone; x.typ := tNone; - end else if x.mode = mWords then begin - { two words, the error on top } - slot := AllocTemp(8, 8); - PopVar(FrameAdr(slot), 8); - x.mode := mStack; x.typ := res^.fields^.typ; - end else begin - { several, in a temporary: the error is where it is } - last := res^.fields; - while last^.next <> nil do last := last^.next; - slot := x.off + last^.val; - if res^.len = 2 then Field(x, res^.fields) else x.typ := WithoutLast(res); - end; - ok := NoLabel; - PushVar(FrameAdr(slot), 8, false, kWord); - JumpIf(ok, false); - if numDefers > 0 then TryAlign; - RunDefers(0); - TryReturn(slot); - Fix(ok); - x.pos := SpanFrom(start); -end; - -procedure Factor(var x: TItem; want: PType); -var called, vol, several: boolean; t: PType; start: TPos; s: shortstring; -begin - several := passOn; - passOn := false; - start := TokPos; - case tok of - sInt, sChar: begin - { only a hex number can be above high(I64), and it is a U64 } - if ival < 0 then MakeConst(x, tU64, ival) else MakeConst(x, tConst, ival); - Next; - end; - sReal: begin MakeReal(x, rval); UsesReals(TokPos); Next end; - sString: begin MakeStr(x); Next end; - sIdent: begin - Designator(x, called); - if x.mode = mNone then begin - if lastCalled <> nil then s := NameOf(lastCalled^.name) else s := 'this procedure'; - MarkAt(x.pos, s + ' returns nothing'); - end; - if x.typ^.tuple and not several then begin - if lastCalled <> nil then s := NameOf(lastCalled^.name) else s := 'this procedure'; - MarkHelp(x.pos, s + ' returns several results', 'they go to variables: a, b := ' + s + '(...)'); - if x.mode = mWords then CopyToTemp(x); - end; - end; - sLparen: begin Next; Expression(x, want); Expect(sRparen) end; - sTry: begin - TryCall(x); - if x.mode = mNone then MarkAt(x.pos, 'this try has no value'); - if x.typ^.tuple then - MarkHelp(x.pos, 'this try has several values', 'they go to variables: a, b := try f(...)'); - end; - sNot: begin Next; Factor(x, nil); NotOp(x) end; - sTilde: begin Next; Factor(x, nil); Complement(x) end; - sLbrak: ArrayLiteral(x, want); - sLbrace: if (want <> nil) and (want^.form = fRecord) then RecordLiteral(x, want) - else SetLiteral(x, want); - sArrow: begin - Next; - vol := tok = sVolatile; - if vol then Next; - t := NewPtr(ParseType, vol); - Expect(sLparen); - Expression(x, nil); - Expect(sRparen); - Convert(x, t); - { a conversion is a factor, not a designator: nothing selects from it } - if tok = sArrow then - MarkHelp(TokPos, 'a conversion can''t be dereferenced', 'convert into a pointer variable, then dereference that'); - end; - else Expected('an expression'); - end; - x.pos := SpanFrom(start); -end; - -procedure Term(var x: TItem; want: PType); -var op: TSym; y: TItem; L: longint; start: TPos; -begin - start := TokPos; - Factor(x, want); - while tok in [sTimes, sSlash, sDiv, sMod, sAmp, sShl, sShr] do begin - op := tok; - Next; - Op1(op, x, L); - Factor(y, nil); - Op2(op, x, y, L); - x.pos := SpanFrom(start); - end; -end; - -procedure SimpleExpr(var x: TItem; want: PType); -var op: TSym; y: TItem; L: longint; start: TPos; -begin - start := TokPos; - if tok = sMinus then begin - Next; - Term(x, nil); - x.pos := SpanFrom(start); - Neg(x); - end else Term(x, want); - while tok in [sPlus, sMinus, sBar, sXor] do begin - op := tok; - Next; - Op1(op, x, L); - Term(y, nil); - Op2(op, x, y, L); - x.pos := SpanFrom(start); - end; -end; - -procedure Relation(var x: TItem; want: PType); -var op: TSym; y: TItem; L: longint; -begin - SimpleExpr(x, want); - if tok in [sEql, sNeq, sLss, sLeq, sGtr, sGeq, sIn] then begin - op := tok; - Next; - Op1(op, x, L); - if op = sIn then SimpleExpr(y, nil) else SimpleExpr(y, x.typ); - Op2(op, x, y, L); - x.pos := Join(x.pos, y.pos); - end; -end; - -{ and binds tighter than or, and both below the relations } -procedure Conjunct(var x: TItem; want: PType); -var y: TItem; L: longint; start: TPos; -begin - start := TokPos; - Relation(x, want); - while tok = sAnd do begin - Next; - Op1(sAnd, x, L); - Relation(y, nil); - Op2(sAnd, x, y, L); - x.pos := SpanFrom(start); - end; -end; - -procedure Expression(var x: TItem; want: PType); -var y: TItem; L: longint; start: TPos; -begin - start := TokPos; - Conjunct(x, want); - while tok = sOr do begin - Next; - Op1(sOr, x, L); - Conjunct(y, nil); - Op2(sOr, x, y, L); - x.pos := SpanFrom(start); - end; -end; - -{ Statements } - -procedure Loop(var lp: TLoop; var old: PLoop); -begin - lp.brk := NoLabel; - lp.base := numDefers; - old := curLoop; - curLoop := @lp; -end; - -{ Runs the deferred statements in force above base, newest first. } -procedure RunDefers(base: longint); -var i: longint; -begin - 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: the break must be the - branch's last statement, so ";" and then end, elsif or else follow. } -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; { stays so with a lone break: there is nothing to skip } - if LoneBreak then begin - NoteLine(CurLine, CurCol); { the jump gets the break's line } - CondJumpTrue(x, curLoop^.brk); - Next; Next; { skip "break" and ";" } - ends := true; - end else begin - CondJump(x, L); - Statements; - end; -end; - -{ if, elsif and else: each condition's jump skips its branch to the - next; each branch that doesn't end jumps to the end. A branch that - ends, in return or break, needs no jump past the others, and all of - them ending is told to the caller in the global ends. } -procedure IfStatement(const start: TPos; ind: longint); -var x: TItem; L, endL: longint; all: boolean; -begin - Next; - Expression(x, nil); - ThenPart(x, L); - all := ends; - endL := NoLabel; - while tok = sElsif do begin - if not ends then Jump(endL); - Fix(L); - Next; - Expression(x, nil); - ThenPart(x, L); - all := all and ends; - end; - if tok = sElse then begin - if not ends then Jump(endL); - Fix(L); - Next; - if tok = sIf then elseIf := true; - Statements; - all := all and ends; - end else begin - Fix(L); - all := false; - end; - CloseEnd(start, ind); - Fix(endL); - ends := all; -end; - -{ while c do s end: the test comes after the body, and the loop jumps to - it first, so that a round takes one jump, back to the top if c holds: - - jmp test rather than top: c, jump to out if false - top: s s - test: c, jump to top if true jmp top - out: - - One pass reads c before s: so c is compiled where it is written, for - its messages, and its code taken back (Rewind); then read again, and - compiled, after s (SaveScan, RestoreScan). } -procedure WhileStatement(const start: TPos; ind: longint); -var x: TItem; top, L, test: longint; lp: TLoop; old: PLoop; cond, after: TScanState; m: TCodeMark; -begin - Next; - SaveScan(cond); - MarkCode(m); - Expression(x, nil); - Discard(x); - Rewind(m); - Expect(sDo); - test := NoLabel; - Jump(test); - AlignLoop; - top := pc; - Loop(lp, old); - Statements; - curLoop := old; - SaveScan(after); - RestoreScan(cond); - Fix(test); - NoteLine(CurLine, CurCol); - Expression(x, nil); - ends := (x.mode = mConst) and (x.val <> 0) and (lp.brk = NoLabel); { while true } - if (x.mode = mConst) and (x.typ^.form = fBool) then begin - if x.val <> 0 then JumpBack(top); - end else begin - L := NoLabel; - CondJumpTrue(x, L); - FixTo(L, top); - end; - RestoreScan(after); - CloseEnd(start, ind); - Fix(lp.brk); -end; - -procedure RepeatStatement; -var x: TItem; top, L: longint; lp: TLoop; old: PLoop; -begin - Next; - top := pc; - Loop(lp, old); - Statements; - curLoop := old; - Expect(sUntil); - Expression(x, nil); - ends := (x.mode = mConst) and (x.val = 0) and (lp.brk = NoLabel); { until false } - L := NoLabel; - CondJump(x, L); - FixTo(L, top); - Fix(lp.brk); -end; - -{ for v := a to b by s do ... end, laid out as - v := a; the limit b, in a slot unless it is a constant - if v is past b then goto exit - goto body - top: v := v + s - body: the statements - the end of a round: goto top, or exit (ForNext) - exit: - so that a round of a loop by 1 takes one compare and one jump. } -procedure ForStatement(const start: TPos; ind: longint); -var - o: PObj; v, a, b, s: TItem; step: int64; top, body, bodyL, exitL: longint; - lp: TLoop; old: PLoop; -begin - Next; - if tok <> sIdent then Expected('a name'); - o := Lookup(id); - if o = nil then begin NotDeclared(TokPos, id); Fail end; - Named(o); - if (o^.cls <> oVar) or not (o^.typ^.form in [fInt, fEnum]) then - if o^.cls = oVar then - Mark('a for loop needs an integer or enumeration variable, found ' + TypeName(o^.typ)) - else Mark(NameOf(id) + ' isn''t a variable'); - Next; - Expect(sBecomes); - MakeItem(v, o); - Expression(a, o^.typ); - CoerceExact(a, o^.typ, ''); - Assign(v, a); - Expect(sTo); - Expression(b, o^.typ); - CoerceExact(b, o^.typ, ''); - { the limit, evaluated once: a constant as it is, else in a slot } - if b.mode <> mConst then TempItem(b, b.typ, ToSlot(b)); - step := 1; - if tok = sBy then begin - Next; - Expression(s, nil); - step := ConstValue(s); - if step = 0 then MarkAt(s.pos, 'the step can''t be zero'); - end; - Expect(sDo); - exitL := NoLabel; - if step > 0 then ForCmp(o, b, sGtr, exitL) else ForCmp(o, b, sLss, exitL); - bodyL := NoLabel; - Jump(bodyL); - AlignLoop; - top := pc; - ForStep(o, step); - Fix(bodyL); - body := pc; - Loop(lp, old); - Statements; - curLoop := old; - CloseEnd(start, ind); - ForNext(o, b, step, exitL, top, body); - Fix(exitL); - Fix(lp.brk); -end; - -type - TLabels = record - lo, hi: array[0..1023] of int64; { the ranges of the labels so far } - at: array[0..1023] of longint; { where the arm of each starts } - n: longint; - end; - -{ a < b, for values of an integer type, unsigned or not } -function Below(a, b: int64; unsign: boolean): boolean; -begin - if unsign then Below := qword(a) < qword(b) else Below := a < b; -end; - -{ An arm of a match on an integer of type t: its labels, each a - constant or a range, none overlapping another (report section 7.4), - then its statements. No code tests the labels here; Dispatch does, - after the last arm, for which each label notes where its arm starts. } -procedure IntArm(t: PType; var ls: TLabels; var endL: longint); -var lo, hi: TItem; first, i: longint; u: boolean; start: TPos; -begin - u := not t^.signed; - first := ls.n; - repeat - start := TokPos; - Expression(lo, t); - Coerce(lo, t); - ConstValue(lo); - hi := lo; - if tok = sUpto then begin - Next; - Expression(hi, t); - Coerce(hi, t); - ConstValue(hi); - if Below(hi.val, lo.val, u) then MarkAt(SpanFrom(start), 'the range is empty'); - end; - for i := 0 to ls.n - 1 do - if not Below(hi.val, ls.lo[i], u) and not Below(ls.hi[i], lo.val, u) then - if lo.val = hi.val then MarkAt(SpanFrom(start), Source(SpanFrom(start)) + ' is in another label too') - else MarkAt(SpanFrom(start), Source(SpanFrom(start)) + ' overlaps another label'); - if ls.n > High(ls.lo) then MarkAt(SpanFrom(start), 'more than ' + IntStr(High(ls.lo) + 1) + ' labels in one match'); - ls.lo[ls.n] := lo.val; ls.hi[ls.n] := hi.val; - inc(ls.n); - if tok <> sComma then break; - Next; - until false; - Expect(sColon); - for i := first to ls.n - 1 do ls.at[i] := pc; - Statements; - Jump(endL); -end; - -const - MinTable = 4; { fewer labels are tested one by one } - TableDensity = 8; { a table has at most this many entries to a label } - -{ The code that picks the arm, after the last one, which the match's - start jumped to: label by label, as a chain of compares each to its - arm; or, for four or more labels not far apart, a jump table (JumpTable), - which takes the same few instructions for any of them. It is here and - not before the arms, since a table can only be made once every arm's - place is known; an arm is entered by a jump back to it. elseAt is where - the else arm starts, or NoLabel. } -procedure Dispatch(t: PType; p: int64; const ls: TLabels; elseAt: longint; var endL: longint); -var - lo, hi: int64; i, start: longint; v: int64; u: boolean; body: longint; - entry: array[0..1023] of longint; -begin - u := (t^.form = fInt) and not t^.signed; - lo := 0; hi := 0; - if ls.n > 0 then begin - lo := ls.lo[0]; hi := ls.hi[0]; - for i := 1 to ls.n - 1 do begin - if Below(ls.lo[i], lo, u) then lo := ls.lo[i]; - if Below(hi, ls.hi[i], u) then hi := ls.hi[i]; - end; - end; - if (ls.n >= MinTable) and (lo >= low(longint)) and (lo <= high(longint)) - and (qword(hi - lo) < qword(TableDensity) * ls.n) and (hi - lo <= High(entry)) then begin - start := JumpTable(p, lo, hi - lo + 1, elseAt, endL); - for v := 0 to hi - lo do - if elseAt <> NoLabel then entry[v] := elseAt else entry[v] := start; - for i := 0 to ls.n - 1 do - for v := ls.lo[i] - lo to ls.hi[i] - lo do entry[v] := ls.at[i]; - for v := 0 to hi - lo do TableEntry(start, entry[v]); - exit; - end; - for i := 0 to ls.n - 1 do begin - body := NoLabel; - MatchRange(p, ls.lo[i], ls.hi[i], body); - FixTo(body, ls.at[i]); - end; - if elseAt <> NoLabel then JumpBack(elseAt); -end; - -procedure MatchStatement(const start: TPos; ind: longint); -var - x: TItem; t: PType; c, f, o: PObj; p: int64; L, endL, n, first, disp, elseAt: longint; - seen: array[0..255] of boolean; hasElse, all, byValue: boolean; endAt: TPos; ls: TLabels; -begin - Next; - Expression(x, nil); - if x.typ^.form = fConst then Coerce(x, tI64); - p := MatchBegin(x); - t := x.typ; - Expect(sOf); - FillChar(seen, SizeOf(seen), 0); - hasElse := false; - all := true; - endL := NoLabel; - ls.n := 0; - { an integer or an enumeration is matched by its value, and the arms - are picked by Dispatch, after them; a variant by its tag, arm by arm } - byValue := t^.form in [fInt, fEnum]; - disp := NoLabel; - elseAt := NoLabel; - if byValue then Jump(disp); - while tok = sBar do begin - Next; - if hasElse then Mark('else must be the last arm'); - if tok = sElse then begin - Next; - Expect(sColon); - elseAt := pc; - Statements; - if byValue then Jump(endL); - hasElse := true; - end else if t^.form = fInt then - IntArm(t, ls, endL) - else begin - first := ls.n; - L := NoLabel; - repeat - if tok <> sIdent then Expected('a case'); - c := t^.fields; - while (c <> nil) and (c^.name <> id) do c := c^.next; - if c = nil then Mark(NameOf(id) + ' isn''t a case of ' + TypeName(t)); - if (c^.val <= High(seen)) and seen[c^.val] then Mark(NameOf(c^.name) + ' has two arms'); - if c^.val <= High(seen) then seen[c^.val] := true; - Next; - if t^.form <> fEnum then begin MatchTag(p, c^.val, L); break end; - { an enumeration's arm may name several, which share its place } - ls.lo[ls.n] := c^.val; ls.hi[ls.n] := c^.val; - inc(ls.n); - if tok <> sComma then break; - Next; - until false; - OpenScope(NewScope); - if tok = sLparen then begin - Next; - f := c^.fields; - n := 0; - repeat - if tok <> sIdent then Expected('a name'); - if f = nil then Mark('more names than ' + NameOf(c^.name) + ' has fields'); - o := NewObj(oVar, id, f^.typ); - o^.lev := 1; o^.ind := true; o^.isVar := true; - o^.val := p; o^.off := f^.val; - Declare(o); - f := f^.next; - inc(n); - Next; - if tok <> sComma then break; - Next; - until false; - if f <> nil then Mark('name all the fields of ' + NameOf(c^.name) + ', or none'); - Expect(sRparen); - end; - Expect(sColon); - for n := first to ls.n - 1 do ls.at[n] := pc; - Statements; - CloseScope; - Jump(endL); - if t^.form <> fEnum then Fix(L); - end; - all := all and ends; - end; - endAt := TokPos; - CloseEnd(start, ind); - ends := all; - if (t^.form = fInt) and not hasElse then - MarkHelp(endAt, 'a match on an integer needs an else arm', 'it may be empty: | else:'); - if not hasElse then begin - c := t^.fields; - while c <> nil do begin - if (c^.val > High(seen)) or not seen[c^.val] then MarkAt(endAt, 'no arm for ' + NameOf(c^.name)); - c := c^.next; - end; - end; - if byValue then begin - Fix(disp); - Dispatch(t, p, ls, elseAt, endL); - end; - Fix(endL); -end; - -{ What a message calls x: its name n when x is just that name, else what - it is. } -function Subject(const x: TItem; n: longint): shortstring; -begin - if x.pos.b - x.pos.a = length(NameOf(n)) then Subject := NameOf(n) - else if x.mode = mConst then Subject := 'a constant' - else Subject := 'a value'; -end; - -{ x, named first n, is a variable the program may assign: not an - array constant, nor any part of one. } -procedure Assignable(const x: TItem; n: longint); -begin - if (x.mode = mConst) and (Subject(x, n) = NameOf(n)) then - MarkAt(x.pos, NameOf(n) + ' is a constant, and can''t be changed'); - if (x.mode = mVar) and (x.obj <> nil) and (x.obj^.cls = oConst) then - MarkAt(x.pos, NameOf(x.obj^.name) + ' is a constant, and can''t be changed'); - if (x.mode <> mVar) or not x.isVar then MarkAt(x.pos, 'can''t assign to ' + Subject(x, n)); -end; - -{ The designator a statement starts with. A variable named whole - before := is assigned, not read: naming it there leaves it as unread - as it was. } -procedure LeftSide(var x: TItem; var called: boolean); -var o: PObj; wasRead: boolean; n: longint; -begin - n := id; - o := Lookup(n); - wasRead := (o <> nil) and o^.read; - Designator(x, called); - if (tok in [sBecomes, sComma]) and (x.pos.b - x.pos.a = length(NameOf(n))) then - o^.read := wasRead; -end; - -{ a, b := f(x): the variables first, left to right, then the call; - then each result to its variable, in order. x is the first variable, - first its name, blank whether it is _. } -procedure MultiAssign(var x: TItem; first: longint; blank: boolean); -var - d: array[0..15] of TItem; dn: array[0..15] of longint; blanks: array[0..15] of boolean; - y, z: TItem; n, i: longint; called: boolean; f: PObj; -begin - n := 0; - d[0] := x; - dn[0] := first; - blanks[0] := blank; - repeat - if not blanks[n] then begin - NotReadOnly(d[n]); - Assignable(d[n], dn[n]); - Pin(d[n]); { works out the address now, so that the call can't change it } - end; - inc(n); - if tok <> sComma then break; - if n > High(d) then Mark('more than ' + IntStr(High(d) + 1) + ' variables in one assignment'); - Next; - blanks[n] := tok = sBlank; - if blanks[n] then Next - else begin - dn[n] := id; - LeftSide(d[n], called); - end; - until false; - Expect(sBecomes); - if tok = sTry then begin - TryCall(y); - called := true; - end else Designator(y, called); - if not called or not y.typ^.tuple or (y.typ^.len <> n) then begin - MarkAt(y.pos, 'expected a call with ' + IntStr(n) + ' results'); - if y.mode = mWords then CopyToTemp(y); - end; - { two results on the stack: the first is brought to the top, and each - is popped into its variable in turn, as one value; else each is - read from the temporary they came back in } - if y.mode = mWords then Swap; - f := y.typ^.fields; - for i := 0 to n - 1 do begin - z := y; - if y.mode = mWords then begin z.mode := mStack; z.typ := f^.typ end - else Field(z, f); - if blanks[i] then Discard(z) - else begin - CoerceExact(z, d[i].typ, 'several results go to variables of just their types'); - Assign(d[i], z); - end; - f := f^.next; - end; -end; - -{ return a, b; or return f(x); with f's several results passed on } -procedure ReturnResults; -var f: PObj; x: TItem; -begin - f := curResult^.fields; - passOn := true; - while f <> nil do begin - Expression(x, f^.typ); - if x.typ^.tuple then begin - if not Same(x.typ, curResult) then - MarkAt(x.pos, 'expected the results ' + TypeName(curResult) + ', found ' + TypeName(x.typ)); - ReturnAll(x); - exit; - end; - ReturnField(f, x); - f := f^.next; - if f <> nil then Expect(sComma); - end; -end; - -{ defer s: s is compiled where it stands, as a little subroutine of the - procedure, jumped over; each way out of the statement list calls it. } -procedure Defer; -var L, pos, saved: longint; oldLoop: PLoop; oldDeferring: boolean; start: TPos; -begin - start := TokPos; - Next; - if directDefer then MarkAt(SpanFrom(start), 'defer can''t be deferred'); - if numDefers > High(defers) then MarkAt(SpanFrom(start), 'more than ' + IntStr(High(defers) + 1) + ' deferred statements in one procedure'); - L := NoLabel; - pos := DeferBegin(L, saved); - oldLoop := curLoop; oldDeferring := deferring; - curLoop := nil; - deferring := true; - directDefer := true; - Statement; - directDefer := false; - curLoop := oldLoop; deferring := oldDeferring; - DeferEnd(L, saved); - defers[numDefers] := pos; - inc(numDefers); -end; - -{ Whether the expression of x := ..., which starts at the current - symbol, is x changed by adding to it, taking from it or its bits: - x + e, x - e, x | e or x xor e, with x nowhere in e, so that it can be - worked out in x's own register, if x is in one (gen's inPlace). } -function ChangesItself(const x: TItem): boolean; -var st: TScanState; wasSkipping: boolean; d: longint; -begin - ChangesItself := false; - if (x.mode <> mVar) or (x.base <> bReg) or (x.typ^.form = fSlice) or (tok <> sIdent) or (id <> x.obj^.name) then exit; - SaveScan(st); - wasSkipping := skipping; - skipping := true; { its slips are told when it is compiled } - Next; - if tok in [sPlus, sMinus, sBar, sXor] then begin - ChangesItself := true; - d := 0; - while not ((d = 0) and (tok in [sSemicolon, sEnd])) and (tok <> sEof) do begin - if (tok = sIdent) and (id = x.obj^.name) then ChangesItself := false; - if tok in [sLparen, sLbrak, sLbrace] then inc(d) - else if tok in [sRparen, sRbrak, sRbrace] then dec(d); - Next; - end; - end; - RestoreScan(st); - skipping := wasSkipping; -end; - -procedure OneStatement; -var x, y: TItem; called: boolean; m: int64; c: TCall; start: TPos; first, n, i: longint; k: TKind; -begin - start := TokPos; - first := id; - NoteLine(CurLine, CurCol); - m := TempMark; - ends := false; - case tok of - sIdent: begin - LeftSide(x, called); - if tok = sBecomes then begin - NotReadOnly(x); - Assignable(x, first); - Next; - if ChangesItself(x) then inPlace := x.chunk; - Expression(y, x.typ); - inPlace := -1; - Assign(x, y); - end else if tok = sComma then - MultiAssign(x, first, false) - else if not called then begin - if (x.mode = mProc) or ((x.mode in [mVar, mStack]) and (x.typ^.form = fProc)) then begin - BeginCall(c, x); - EndCall(c, x); - Discard(x); - end else if tok = sEql then - MarkHelp(x.pos, Subject(x, first) + ' isn''t a statement', 'assignment is written :=') - else MarkAt(x.pos, Subject(x, first) + ' isn''t a statement'); - end else begin - if (x.mode <> mNone) and (numDrops <= High(drops)) then begin - drops[numDrops].at := x.pos; - if x.typ^.tuple then drops[numDrops].n := x.typ^.len else drops[numDrops].n := 1; - inc(numDrops); - end; - Discard(x); - end; - end; - sBlank: begin - Next; - if tok = sComma then MultiAssign(x, 0, true) - else begin - Expect(sBecomes); - Expression(x, nil); - { evaluated and dropped: a single value is loaded, so that a - volatile one is read } - if (x.mode in [mType, mBuiltin, mNone, mCase]) or (x.mode <> mStr) and not IsAggregate(x.typ) then - Value(x); - Discard(x); - end; - end; - sIf: IfStatement(start, Indent); - sWhile: WhileStatement(start, Indent); - sRepeat: RepeatStatement; - sFor: ForStatement(start, Indent); - sMatch: MatchStatement(start, Indent); - sReturn: begin - Next; - if deferring then MarkAt(SpanFrom(start), 'return can''t leave a deferred statement'); - if tok = sSemicolon then begin - RunDefers(0); - ReturnNone; - end else begin - if (curResult <> nil) and curResult^.tuple then ReturnResults - else begin - Expression(x, curResult); - ReturnValue(x); - end; - { the result, one value or two words on top, waits in the frame - while the deferred statements run } - if (numDefers > 0) and (curResult <> nil) and not BehindPointer(curResult) then begin - n := 1; k := KindOf(curResult); - if InTwoRegs(curResult) then begin n := 2; k := kWord end; - if deferSlot = 0 then deferSlot := AllocPerm(16, 8); - for i := n - 1 downto 0 do PopVar(FrameAdr(deferSlot + 8 * i), 8); - RunDefers(0); - for i := 0 to n - 1 do PushVar(FrameAdr(deferSlot + 8 * i), 8, false, k); - end else RunDefers(0); - ReturnJump; - ends := true; - end; - end; - sBreak: begin - Next; - if curLoop = nil then MarkAt(SpanFrom(start), 'break outside a loop'); - RunDefers(curLoop^.base); - Jump(curLoop^.brk); - end; - sDefer: Defer; - sTry: begin - TryCall(x); - if (x.mode <> mNone) and (numDrops <= High(drops)) then begin - drops[numDrops].at := x.pos; - if x.typ^.tuple then drops[numDrops].n := x.typ^.len else drops[numDrops].n := 1; - inc(numDrops); - end; - Discard(x); - end; - sArrow: MarkHelp(TokPos, 'a statement starts with a name', 'convert into a pointer variable, then assign through that'); - else if AtLineStart then EndMissing(MissingPos, 'expected "end", found ' + Found) - else Expected('a statement'); - end; - ReleaseTemps(m); -end; - -procedure Statement; -var r: TRecover; m: int64; -begin - m := TempMark; - Guard(r); - if setjmp(r.jb) = 0 then begin - OneStatement; - skipped := false; - end else begin - Restore(r); - { a statement never starts a line: this is the next declaration } - if AtLineStart or not SkipConstruct then GiveUp(r); - ReleaseTemps(m); - skipped := true; - end; - Unguard(r); -end; - -procedure Statements; -var base: longint; old: boolean; -begin - base := numDefers; - old := directDefer; - directDefer := false; - ends := false; - while not (tok in [sEnd, sElse, sElsif, sUntil, sBar, sEof]) do begin - Statement; - if not skipped or (tok = sSemicolon) then Expect(sSemicolon); - end; - RunDefers(base); - numDefers := base; - directDefer := old; -end; - -{ Declarations } - -{ In a file read for its interface only: skip a procedure's body, from - its local declarations to the end that closes it. } -procedure SkipBody; -var d: longint; sawBegin: boolean; -begin - d := 0; - sawBegin := false; - repeat - case tok of - sBegin: begin if d = 0 then sawBegin := true; inc(d) end; - sIf, sWhile, sFor, sMatch, sRecord, sVariant: inc(d); - sEnd: begin - dec(d); - if (d = 0) and sawBegin then begin Next; exit end; - end; - sEof: Expected('"end"'); - end; - Next; - until false; -end; - -procedure Declarations(top: boolean); forward; - -{ 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, 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, i: longint; -begin - case o^.typ^.form of - fInt: k := 2 - ord(o^.typ^.signed); - fEnum, fSet: k := 2; - fBool: k := 3; - fPtr, fProc, fError: k := 4; - fReal: k := 5; - else exit(0); - end; - VarKind := k + o^.typ^.size * 16 + ord(o^.ind) * 256; - for i := 0 to High(ShownRegs) do - if o^.reg = ShownRegs[i] then VarKind := k + o^.typ^.size * 16 + (i + 1) * 512; -end; - -{ Whether variable o could live in registers: a single value, a real - in an xmm register, or a slice, in two, 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, fSlice, fReal]) - or (o^.typ^.form = fSet) and (o^.typ^.size <= 8)); -end; - -{ The first local of the procedure being compiled. Locals are chained - by link in the order declared, the module's own first; before is the - last one declared before the procedure's, or nil if there was none. } -function FirstLocal(before: PObj): PObj; -begin - if before = nil then FirstLocal := curModule^.locals else FirstLocal := before^.link; -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, in - three or more 64, 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. A slice takes two, its pointer's and its length's; - a real one of the xmm registers, stored and loaded again around each - call, as System V keeps none through one. In a procedure that names no procedure, so calls nothing, the - parameters that arrive in the registers no call needs stay there - (KeepArrived), at no cost. } -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, kx, d, loops, best, need: longint; o, q, qual: PObj; st: TScanState; - afterDot, wasSkipping, leaf: boolean; - - function Candidate(name: longint): longint; - var j: longint; - begin - for j := 0 to n - 1 do if cand[j]^.name = name then exit(j); - Candidate := -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; - - { Whether naming o may make a call: a procedure, a procedure variable, - or NEW, SYSCALL or COPY, which use the registers a call would } - function Calls(o: PObj): boolean; - begin - Calls := (o <> nil) and ((o^.cls = oProc) or (o^.cls = oVar) and (o^.typ^.form = fProc) - or (o^.cls = oBuiltin) and ((o^.val = bNew) or (o^.val = bSyscall) or (o^.val = bCopy))); - end; - -begin - n := 0; - o := params; - while o <> nil do begin Add(o); o := o^.next end; - o := FirstLocal(before); - while o <> nil do begin Add(o); o := o^.link end; - 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; leaf := true; qual := nil; - repeat - { a name, or a module's name and one of its exports, that calls } - if (tok = sIdent) and not afterDot then begin - q := Lookup(id); - if Calls(q) then leaf := false; - qual := nil; - if (q <> nil) and (q^.cls = oModule) then qual := q; - end else if (tok = sIdent) and (qual <> nil) then begin - if (qual^.module = nil) or Calls(Find(qual^.module^.scope, id)) then leaf := false; - qual := nil; - end; - 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; - { a hugely negative weight bars it from a register, whatever - its uses add } - if (tok = sIdent) and (Candidate(id) >= 0) then weight[Candidate(id)] := low(longint) div 2; - end else if not afterDot and (Candidate(id) >= 0) then begin - k := Candidate(id); - if loops > 2 then inc(weight[k], 64) else inc(weight[k], 1 shl (2 * loops)); - end; - end; - afterDot := tok = sPeriod; { a name after a dot is a field, not a variable } - if (d > 0) and (tok <> sEof) then Next; - until (d = 0) or (tok = sEof); - RestoreScan(st); - skipping := wasSkipping; - if leaf then begin - o := params; - while o <> nil do begin - k := Candidate(o^.name); - if (k >= 0) and (weight[k] >= 0) then KeepArrived(o); { a candidate whose ADR isn't taken } - o := o^.next; - end; - end; - { a slice's weight is shared by its two registers } - for i := 0 to n - 1 do - if cand[i]^.typ^.form = fSlice then weight[i] := weight[i] div 2; - { the heaviest, each used at least three times a register, take the - five registers in turn, while there are enough for each, and the - reals the four xmm registers of XVarRegs } - k := 0; kx := 0; - repeat - 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; - need := 1 + ord(cand[best]^.typ^.form = fSlice); - if cand[best]^.typ^.form = fReal then begin - if kx < 4 then begin cand[best]^.reg := XVarRegs[kx]; inc(kx) end - else weight[best] := 0; - end else if k + need <= 5 then begin - cand[best]^.reg := VarRegs[k]; - if need = 2 then cand[best]^.reg2 := VarRegs[k + 1]; - inc(k, need); - end else weight[best] := 0; { too big for what is left } - until false; - end; -end; - -{ The registers the variables of the procedure are in, as bits: bit i - is VarRegs[i], bit XBit + i XVarRegs[i] } -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]) or (o^.reg2 = VarRegs[k]) then m := m or (1 shl k); - for k := 0 to 3 do if o^.reg = XVarRegs[k] then m := m or (1 shl (XBit + k)); - o := o^.next; - end; - o := FirstLocal(before); - while o <> nil do begin - if o^.cls = oVar then begin - for k := 0 to 4 do if (o^.reg = VarRegs[k]) or (o^.reg2 = VarRegs[k]) then m := m or (1 shl k); - for k := 0 to 3 do if o^.reg = XVarRegs[k] then m := m or (1 shl (XBit + k)); - end; - o := o^.link; - end; - RegsOf := m; -end; - -{ Gives each local not in a register its slot in the frame, the slots - the prologue zeroes, and then tells gen which registers the - variables are in. A variable in a register has no slot: it starts at - zero in its register, and the trap report finds it there. } -procedure PlaceLocals(params, before: PObj); -var o: PObj; -begin - ResetLocals; - o := FirstLocal(before); - while o <> nil do begin - if (o^.cls = oVar) and (o^.reg = 0) then o^.val := AllocPerm(o^.typ^.size, o^.typ^.align) - else if (o^.cls = oVar) and (o^.reg >= XmmVar) then begin - o^.val := AllocPerm(8, 8); - XHome(o^.reg, o^.val); - end; - o := o^.link; - end; - o := params; - while o <> nil do begin - if o^.reg >= XmmVar then XHome(o^.reg, o^.val); - o := o^.next; - end; - UseRegs(RegsOf(params, before)); -end; - -procedure Body(p: PObj; sig: PType; line: longint); -var - q, params, last, o, before: PObj; old: PType; st: TScanState; - mark: TCodeMark; drops0, errs: longint; -begin - OpenScope(NewScope); - params := nil; last := nil; - q := sig^.fields; - while q <> nil do begin - o := NewObj(oVar, q^.name, q^.typ); - o^.pos := q^.pos; - o^.lev := 1; - o^.isVar := q^.isVar; - o^.param := true; - if last = nil then params := o else last^.next := o; - last := o; - q := q^.next; - end; - BeginProc(sig, params); - deferSlot := 0; - o := params; - while o <> nil do begin - q := o^.next; - Declare(o); - o := q; - end; - curProc := p; - before := curModule^.lastLocal; - Declarations(false); - ChooseRegs(params, before); - PlaceLocals(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 lost) or (errors <> errs) then break; - { a parameter kept where it arrived goes to memory: a call or a copy - wanted its register } - if lost then begin - o := params; - while o <> nil do begin - if KeptIn(o) then begin o^.reg := 0; o^.reg2 := 0 end; - o := o^.next; - end; - end; - numDrops := drops0; - Redo(mark); - PlaceLocals(params, before); - RestoreScan(st); - until false; - EndProc(p^.chunk, p^.openEnd); - { its parameters and variables, for the trap report } - o := FirstLocal(before); - q := params; - while q <> nil do begin - if VarKind(q) <> 0 then NoteVar(p^.chunk, q^.name, q^.val, VarKind(q)); - q := q^.next; - end; - while o <> nil do begin - if (o^.cls = oVar) and (VarKind(o) <> 0) then NoteVar(p^.chunk, o^.name, o^.val, VarKind(o)); - o := o^.link; - end; - curResult := old; - curProc := nil; - CloseScope; -end; - -{ An integer constant in a code procedure, for the assembler: a whole - expression, or a single factor where an expression would read on - too far } -function AsmConst(whole: boolean): int64; -var x: TItem; -begin - if whole then exit(ConstExpr); - Factor(x, nil); - if not IsInt(x.typ) then MarkAt(x.pos, 'expected an integer constant, found ' + What(x)); - AsmConst := ConstValue(x); -end; - -procedure CodeBody(p: PObj; sig: PType; const at: TPos); -var q: PObj; ni, nf: longint; -begin - ni := 0; nf := 0; - q := sig^.fields; - while q <> nil do begin - if not q^.isVar and (q^.typ^.form = fSlice) then inc(ni, 2) { address, then length } - else begin - if not q^.isVar and not IsScalar(q^.typ) then - MarkAt(at, 'a code procedure takes integers, BOOL, reals, pointers, procedures and slices'); - if (q^.typ^.form = fReal) and not q^.isVar then inc(nf) else inc(ni); - end; - q := q^.next; - end; - if (ni > 6) or (nf > 8) or sig^.variadic then MarkAt(at, 'too many parameters for a code procedure'); - if sig^.base <> nil then - if sig^.base^.tuple then begin - q := sig^.base^.fields; - if (sig^.base^.len <> 2) or (q^.typ^.size <> 8) or (q^.next^.typ^.size <> 8) - or not IsScalar(q^.typ) or not IsScalar(q^.next^.typ) - or (q^.typ^.form = fReal) or (q^.next^.typ^.form = fReal) then - MarkAt(at, 'a code procedure returns two results only in rax and rdx'); - end else if not IsScalar(sig^.base) and (sig^.base^.form <> fSlice) then - MarkAt(at, 'a code procedure returns a single value'); - CodeProc(p^.chunk, @AsmConst); - Expect(sEnd); -end; - -procedure ProcDecl; -var n, line: longint; exp: boolean; sig: PType; p: PObj; at: TPos; -begin - InstancesFor(false); - line := CurLine; - Next; - IdentDef(n, exp, at); - sig := Signature; - Expect(sSemicolon); - p := Find(TopScope, n); - if (p <> nil) and (p^.cls = oProc) and p^.fwd then begin - if not Same(p^.typ, sig) then begin - Error(at, NameOf(n) + ' doesn''t have the signature it was declared forward with'); - Note(p^.pos, 'the signature is here'); - Fail; - end; - if tok = sForward then Mark(NameOf(n) + ' is declared forward twice'); - p^.exported := p^.exported or exp; - end else begin - p := NewObj(oProc, n, sig); - p^.pos := at; - p^.exported := exp; - if (curModule^.name = nameRt) and not checkMode and (n = nameFail) then p^.chunk := rtFail - else p^.chunk := NewChunk(secText, curModule^.sname, n); - Declare(p); - end; - if tok = sForward then begin - Next; - p^.fwd := true; - exit; - end; - p^.fwd := false; - if tok = sCode then begin - Next; - p^.isCode := true; - CodeBody(p, sig, at); - end else if checkMode then SkipBody else Body(p, sig, line); - if tok = sIdent then begin - if id = curModule^.name then EndMissing(TokPos, NameOf(n) + ' has no "end": this one closes the module') - else if id <> n then EndMissing(TokPos, 'expected ' + NameOf(n) + ', found ' + NameOf(id)); - Next; - end; -end; - -{ An extern procedure or variable: C's, reached through the quadword - that holds its address. } -procedure ExternDecl; -var n: longint; exp: boolean; o, q: PObj; t: PType; at: TPos; -begin - Next; - curModule^.usesC := true; - if tok = sProc then begin - Next; - IdentDef(n, exp, at); - WillDeclare(n); - inExtern := true; - t := Signature; - inExtern := false; - q := t^.fields; - while q <> nil do begin - if q^.isVar or not IsScalar(q^.typ) then - MarkAt(at, 'C takes integers, BOOL, reals, pointers and procedures'); - q := q^.next; - end; - if (t^.base <> nil) and not IsScalar(t^.base) then MarkAt(at, 'C returns a single value'); - o := NewObj(oProc, n, t); - end else begin - if tok <> sVar then Expected('"proc" or "var"'); - Next; - IdentDef(n, exp, at); - WillDeclare(n); - Expect(sColon); - declExported := exp; - t := ParseType; - declExported := false; - o := NewObj(oVar, n, t); - end; - o^.pos := at; - o^.exported := exp; - o^.ext := true; - o^.chunk := ExternChunk(n); - Declare(o); -end; - -{ An array or record constant: a literal of constants, which become - the bytes of a read-only chunk, as a string constant's do (report - section 4). An address in it, of a string, an array constant, a - procedure or an ERROR, waits in fixes until the chunk is made, then - is a fixup the linker patches. The bytes are the compiler's own - machine's, little-endian, as the target's are. } -var - constBytes: PBytes; - fixes: array[0..4095] of record off: int64; chunk: longint; end; - numFixes: longint; - -procedure ConstFix(off: int64; chunk: longint); -begin - if numFixes > High(fixes) then MarkAt(TokPos, 'more than ' + IntStr(High(fixes) + 1) + ' addresses in one constant'); - fixes[numFixes].off := off; - fixes[numFixes].chunk := chunk; - inc(numFixes); -end; - -{ The part of type t at offset off of the constant } -procedure ConstPart(t: PType; off: int64); -var e: TItem; f: PObj; k: int64; r: single; start: TPos; -begin - start := TokPos; - if (t^.form = fArray) and (tok = sLbrak) then begin - Next; - k := 0; - if tok <> sRbrak then - repeat - if k < t^.len then ConstPart(t^.base, off + k * t^.base^.size) - else ConstPart(t^.base, off); - inc(k); - if tok <> sComma then break; - Next; - until false; - Expect(sRbrak); - if k <> t^.len then MarkAt(SpanFrom(start), 'expected ' + IntStr(t^.len) + ' elements, found ' + IntStr(k)); - exit; - end; - if (t^.form = fRecord) and not t^.tuple and (tok = sLbrace) then begin - Next; - if tok <> sRbrace then - repeat - if tok <> sIdent then Expected('a field'); - f := FieldOf(t); - Next; - Expect(sColon); - ConstPart(f^.typ, off + f^.val); - if tok <> sComma then break; - Next; - until false; - Expect(sRbrace); - exit; - end; - Expression(e, t); - if (e.mode = mStr) and ((t^.form = fSlice) or (t^.form = fArray)) and (t^.base = tU8) then begin - if t^.form = fSlice then begin - ConstFix(off, e.chunk); - Move(e.val, constBytes^[off + 8], 8); - end else if e.val > t^.len then MarkAt(e.pos, 'the string is longer than ' + TypeName(t)) - else Move(rodata^[chunks^[e.chunk].start], constBytes^[off], e.val); - end else if t^.form = fSlice then begin - if (e.mode <> mVar) or (e.obj = nil) or (e.obj^.cls <> oConst) or (e.typ^.form <> fArray) - or (e.pos.b - e.pos.a <> length(NameOf(e.obj^.name))) or not Same(e.typ^.base, t^.base) then - MarkAt(e.pos, 'a constant slice is a string or an array constant of its elements, found ' + What(e)); - ConstFix(off, e.chunk); - Move(e.typ^.len, constBytes^[off + 8], 8); - end else if t^.form = fVariant then MarkAt(e.pos, 'a constant holds no variant') - else if t^.form in [fArray, fRecord] then MarkAt(e.pos, 'expected a literal of ' + TypeName(t)) - else begin - Coerce(e, t); - if (e.mode = mProc) and not e.obj^.ext then ConstFix(off, e.obj^.chunk) - else if e.mode <> mConst then MarkAt(e.pos, 'expected a constant, found ' + What(e)) - else if (t^.form = fError) and (e.val > 0) then ConstFix(off, e.val - 1) - else if (t^.form = fPtr) and (e.val <> 0) then MarkAt(e.pos, 'a constant pointer is nil') - else if (t^.form = fReal) and (t^.size = 4) then begin - r := RealOf(e); - Move(r, constBytes^[off], 4); - end else Move(e.val, constBytes^[off], t^.size); - end; -end; - -{ The chunk of n, a constant of type t whose literal is next } -function AggregateConst(t: PType; n: longint): longint; -var c, i: longint; -begin - constBytes := AllocMem(t^.size + 8); - numFixes := 0; - ConstPart(t, 0); - c := NewChunk(secRodata, curModule^.sname, n); - SetData(c, constBytes, t^.size, t^.align); - for i := 0 to numFixes - 1 do AddDataFixup(c, fixes[i].off, fixes[i].chunk, 0); - FreeMem(constBytes); - AggregateConst := c; -end; - -procedure ConstDecl(top: boolean); -var n: longint; exp: boolean; x: TItem; o: PObj; t: PType; start, at: TPos; -begin - IdentDef(n, exp, at); - WillDeclare(n); - t := nil; - if tok = sColon then begin - Next; - start := TokPos; - t := ParseType; - if (t <> tError) and not ((t^.form = fArray) or (t^.form = fRecord) and not t^.tuple) then - MarkAt(SpanFrom(start), 'only an ERROR, an array or a record constant has a type'); - end; - Expect(sEql); - if (t <> nil) and (t^.form in [fArray, fRecord]) then begin - o := NewObj(oConst, n, t); - o^.chunk := AggregateConst(t, n); - o^.pos := at; - o^.exported := exp and top; - Declare(o); - Expect(sSemicolon); - exit; - end; - Expression(x, nil); - o := NewObj(oConst, n, x.typ); - o^.pos := at; - o^.exported := exp and top; - if t = tError then begin - o^.typ := tError; - o^.val := ErrorChunk(x, curModule^.sname, n) + 1; - end else if x.mode = mStr then begin o^.val := x.val; o^.chunk := x.chunk end - else o^.val := ConstValue(x); - Declare(o); - Expect(sSemicolon); -end; - -procedure TypeDecl(top: boolean); -var n: longint; exp: boolean; o: PObj; t: PType; at: TPos; -begin - IdentDef(n, exp, at); - WillDeclare(n); - Expect(sEql); - declExported := exp and top; - inTypes := true; - t := ParseType; - o := NewObj(oType, n, t); - o^.pos := at; - o^.exported := exp and top; - if t^.obj = nil then t^.obj := o; - Declare(o); - Expect(sSemicolon); -end; - -procedure VarDecl(top: boolean); -var - i, k: longint; o: PObj; t: PType; - names: array[0..63] of longint; exps: array[0..63] of boolean; - poss: array[0..63] of TPos; -begin - k := 0; - repeat - if k > High(names) then Mark('more than ' + IntStr(High(names) + 1) + ' names in one declaration'); - IdentDef(names[k], exps[k], poss[k]); - WillDeclare(names[k]); - inc(k); - if tok <> sComma then break; - Next; - until false; - Expect(sColon); - declExported := top and exps[0]; - t := ParseType; - declExported := false; - for i := 0 to k - 1 do begin - o := NewObj(oVar, names[i], t); - o^.pos := poss[i]; - o^.exported := exps[i] and top; - o^.isVar := false; - if top then begin - o^.lev := 0; - o^.chunk := NewChunk(secBss, curModule^.sname, names[i]); - SetBss(o^.chunk, t^.size, t^.align); - end else - o^.lev := 1; { its slot comes from PlaceLocals, if it needs one } - Declare(o); - end; - Expect(sSemicolon); -end; - -{ After a procedure had an error: its name is poison if it wasn't - declared, and reading goes on after the "end Name;" that closes it, - or at the next procedure if that is missing } -procedure SkipProc; -var st: TScanState; -begin - Next; - if (tok = sIdent) and (Find(TopScope, id) = nil) then Poison(id); - repeat - repeat Next until AtLineStart or (tok = sEof); - if tok in [sProc, sExtern, sEof] then exit; - if tok = sEnd then begin - SaveScan(st); - Next; - if tok = sIdent then Next; - if tok = sSemicolon then begin Next; exit end; - RestoreScan(st); - exit; - end; - until false; -end; - -{ One declaration, of the kind k, as a recovery point } -procedure Declaration(k: TSym; top: boolean); -var r: TRecover; -begin - Guard(r); - numDeclaring := 0; - if setjmp(r.jb) = 0 then - case k of - sConst: ConstDecl(top); - sType: TypeDecl(top); - sVar: VarDecl(top); - sProc: begin - if not top then Mark('procedures don''t nest'); - ProcDecl; - Expect(sSemicolon); - end; - sExtern: begin - if not top then Mark('extern is only for the top of a module'); - ExternDecl; - Expect(sSemicolon); - end; - end - else begin - Restore(r); - if k = sProc then SkipProc else SkipDeclaration; - end; - Unguard(r); -end; - -procedure Declarations(top: boolean); -var i: longint; o: PObj; k: TSym; -begin - repeat - k := tok; - case k of - sConst, sVar: begin - Next; - while tok = sIdent do Declaration(k, top); - end; - sType: begin - Next; - numFwd := 0; - while tok = sIdent do Declaration(sType, top); - inTypes := false; - for i := 0 to numFwd - 1 do begin - o := Lookup(fwdTypes[i]^.fwd); - if (o = nil) or (o^.cls <> oType) then begin - NotDeclared(fwdPos[i], fwdTypes[i]^.fwd); - fwdTypes[i]^.base := tPoison; - end else begin - fwdTypes[i]^.base := o^.typ; - Named(o); - end; - fwdTypes[i]^.fwd := -1; - end; - end; - sProc, sExtern: Declaration(k, top); - else exit; - end; - until false; -end; - -{ Modules } - -{ Whether m is module n with these arguments. } -function IsModule(m: PModule; n: longint; const args: TArgs): boolean; -var i: longint; -begin - IsModule := false; - if (m^.name <> n) or (m^.args.n <> args.n) then exit; - for i := 0 to args.n - 1 do - if (m^.args.o[i] <> args.o[i]) or not Same(m^.args.t[i], args.t[i]) then exit; - IsModule := true; -end; - -function FindModule(n: longint; const args: TArgs): PModule; -var m: PModule; -begin - m := firstModule; - while (m <> nil) and not IsModule(m, n, args) do m := m^.next; - FindModule := m; -end; - -{ The arguments of an instance: types, or procedures named. } -procedure ParseArgs(var args: TArgs; const mname: shortstring); -var o: PObj; start: TPos; -begin - Next; - repeat - if args.n > High(args.t) then Mark('too many type arguments for ' + mname); - args.o[args.n] := nil; - start := TokPos; - if tok = sIdent then begin - o := QualIdent; - if o^.cls = oProc then args.o[args.n] := o - else if o^.cls <> oType then MarkAt(SpanFrom(start), NameOf(o^.name) + ' isn''t a type or a procedure'); - args.t[args.n] := o^.typ; - end else args.t[args.n] := ParseType; - args.pos[args.n] := SpanFrom(start); - inc(args.n); - if tok <> sComma then break; - Next; - until false; - Expect(sRparen); -end; - -{ Past an instance's arguments, to be read when it is made } -procedure SkipArgs; -var p: longint; -begin - p := 0; - repeat - if tok = sLparen then inc(p) - else if tok = sRparen then dec(p) - else if tok in [sSemicolon, sEof] then Expected('")"'); - Next; - until p = 0; -end; - -{ A generic module's parameters, bound to the instance's arguments: a - type parameter names its type, a procedure parameter its procedure. } -procedure Params(m: PModule); -var i: longint; o, a: PObj; sig: PType; s: shortstring; at: TPos; -begin - i := 0; - s := NameOf(m^.name) + '('; - Next; - repeat - if tok <> sIdent then Expected('a name'); - if i >= m^.args.n then MarkAt(m^.args.at, NameOf(m^.name) + ' needs a type for ' + NameOf(id)); - if m^.args.o[i] <> nil then MarkAt(m^.args.pos[i], NameOf(m^.name) + ' needs a type for ' + NameOf(id)); - o := NewObj(oType, id, m^.args.t[i]); - o^.used := true; { a parameter of the module, not a declaration } - Declare(o); - s := s + TypeName(m^.args.t[i]) + ','; - inc(i); - Next; - if tok <> sComma then break; - Next; - until false; - while tok = sSemicolon do begin - Next; - if tok <> sIdent then Expected('a name'); - at := TokPos; - o := NewObj(oProc, id, nil); - Next; - Expect(sColon); - Expect(sProc); - sig := Signature; - if i >= m^.args.n then MarkAt(m^.args.at, NameOf(m^.name) + ' needs a procedure for ' + NameOf(o^.name)); - a := m^.args.o[i]; - if a = nil then MarkAt(m^.args.pos[i], NameOf(m^.name) + ' needs a procedure for ' + NameOf(o^.name)); - if not Same(a^.typ, sig) then begin - Error(m^.args.pos[i], NameOf(a^.name) + ' doesn''t have the signature of ' + NameOf(o^.name)); - Note(at, 'the signature is here'); - Finish; - end; - o^.typ := a^.typ; o^.chunk := a^.chunk; o^.isCode := a^.isCode; o^.ext := a^.ext; - o^.used := true; - Declare(o); - s := s + NameOf(a^.module^.name) + '.' + NameOf(a^.name) + ','; - inc(i); - end; - Expect(sRparen); - if i <> m^.args.n then MarkAt(m^.args.at, 'too many type arguments for ' + NameOf(m^.name)); - s[length(s)] := ')'; - m^.sname := Name(s); -end; - -{ Warns of o if it is never used, or a variable only assigned. What - is exported may be used elsewhere, and a name that starts with _ says - it is meant to go unused. Writing a var parameter, a match's name for - a field or C's variable is what it is for. } -procedure Warn(o: PObj); -var s: shortstring; -begin - s := NameOf(o^.name); - if (o^.cls = oProc) and o^.openEnd then - Warning(o^.pos, s + ' may reach its end without return, and then returns zero'); - if o^.exported or (s[1] = '_') then exit; - if o^.used and (o^.read or (o^.cls <> oVar) or o^.isVar or o^.ext) then exit; - case o^.cls of - oConst: s := 'constant ' + s; - oType: s := 'type ' + s; - oVar: if o^.param then s := 'parameter ' + s else s := 'variable ' + s; - oProc: s := 'procedure ' + s; - oModule: s := 'module ' + s; - else exit; - end; - if o^.used then Warning(o^.pos, s + ' is assigned but never read') - else if o^.cls = oModule then Warning(o^.pos, s + ' is imported but never used') - else Warning(o^.pos, s + ' is never used'); - if not o^.used and (o^.param or o^.ind) then - Help('if it must be there, call it _' + NameOf(o^.name)); -end; - -{ Warns of the call at p, which drops its n results } -procedure Dropped(const p: TPos; n: longint); -var s, blanks: shortstring; i: longint; -begin - s := Source(p); - i := Pos('(', s); - if i > 0 then s := copy(s, 1, i - 1); - blanks := '_'; - for i := 2 to n do blanks := blanks + ', _'; - if n = 1 then Warning(p, 'the result of ' + s + ' is dropped') - else Warning(p, 'the results of ' + s + ' are dropped'); - Help('if that is meant, write ' + blanks + ' := ' + s + '(...)'); -end; - -{ The warnings of module m, by where each declaration is: its own - declarations and its procedures' are two lists, each in order, and - firstDrop on are the calls that drop results. The - instances of a generic module share its text, and so its warnings: - only the first is warned of. } -procedure Warnings(m: PModule; firstDrop: longint); -var a, b: PObj; n: PModule; i: longint; -begin - n := firstModule; - while (n <> nil) and (n^.name <> m^.name) do n := n^.next; - if n <> nil then exit; - a := m^.first; b := m^.locals; - i := firstDrop; - while (a <> nil) or (b <> nil) or (i < numDrops) do - if (i < numDrops) and ((a = nil) or (drops[i].at.a < a^.pos.a)) and ((b = nil) or (drops[i].at.a < b^.pos.a)) then begin - Dropped(drops[i].at, drops[i].n); - inc(i); - end else if (b = nil) or (a <> nil) and (a^.pos.a < b^.pos.a) then begin - Warn(a); - a := a^.link; - end else begin - Warn(b); - b := b^.link; - end; -end; - -{ Modules being compiled, not yet finished: for finding a cycle. } -var - pending: array[0..63] of PModule; - numPending: longint; - -function Exists(const path: shortstring): boolean; -var st: Stat; p: shortstring; -begin - p := path + #0; - Exists := (FpStat(@p[1], st) = 0) and ((st.st_mode and S_IFMT) = S_IFREG); -end; - -{ Compiles module n from path, an instance if args are given, or only - reads its interface if checkOnly; returns it. An import calls this in - the middle of reading another file, so it is re-entrant: it saves the - scanner's state, the open scopes, the current module and file and - whether checks are on, and puts them back at the end. } -function CompileFile(const path: shortstring; n: longint; const args: TArgs; checkOnly: boolean): PModule; -var - st: TScanState; saved: array[0..MaxDepth - 1] of longint; d: longint; - oldMod: PModule; oldCheck, oldChecks: boolean; m: PModule; - lib: PLib; start: TPos; alias, mname, line, oldPath: longint; o: PObj; body: longint; iargs: TArgs; - generic: boolean; argsAt: TScanState; why: shortstring; firstDrop: longint; -begin - firstDrop := numDrops; - SaveScan(st); - SaveScopes(d, saved); - oldMod := curModule; oldCheck := checkMode; oldPath := curFile; oldChecks := checks; - checks := true; - curFile := Name(path); - why := Open(path); - if why <> '' then Fatal('can''t read ' + path + ': ' + why); - New(m); - FillChar(m^, SizeOf(TModule), 0); - m^.name := n; - m^.sname := n; - m^.args := args; - m^.scope := NewScope; - m^.path := path; - m^.body := -1; - m^.checkOnly := checkOnly; - curModule := m; - checkMode := checkOnly; - if not checkOnly then begin - if numPending > High(pending) then Mark('imports nested more than ' + IntStr(High(pending) + 1) + ' deep'); - pending[numPending] := m; - inc(numPending); - end; - OpenScope(m^.scope); - Next; - Expect(sModule); - if (tok <> sIdent) or (id <> n) then Mark('expected module ' + NameOf(n) + ', found ' + Found); - Next; - { the module first pending is the one named on the command line, - which nothing imports, so no arguments come with it } - if (tok = sLparen) and not checkOnly and (numPending = 1) then - Mark(NameOf(n) + ' is generic: it is compiled where a module imports it') - else if tok = sLparen then Params(m) - else if args.n > 0 then MarkAt(args.at, NameOf(n) + ' isn''t generic'); - Expect(sSemicolon); - while tok = sImport do begin - Next; - repeat - if tok <> sIdent then Expected('a module name'); - start := TokPos; - alias := id; - mname := id; - iargs.n := 0; - generic := false; - Next; - if tok = sBecomes then begin - Next; - if tok <> sIdent then Expected('a module name'); - mname := id; - Next; - if tok = sLparen then begin - generic := true; - SaveScan(argsAt); - SkipArgs; - end; - end; - iargs.at := SpanFrom(start); - o := NewObj(oModule, alias, nil); - o^.pos := start; - Declare(o); - if not generic then begin - o^.module := ImportModule(mname, iargs); - AddImport(m, o^.module); - end else begin - o^.module := nil; { until the instance is made, at its first use } - if numDeferred > High(deferred) then Mark('more than ' + IntStr(High(deferred) + 1) + ' generic imports'); - deferred[numDeferred].o := o; - deferred[numDeferred].m := m; - deferred[numDeferred].mname := mname; - deferred[numDeferred].args := argsAt; - deferred[numDeferred].at := iargs.at; - inc(numDeferred); - end; - if tok <> sComma then break; - Next; - until false; - Expect(sSemicolon); - end; - while tok = sLink do begin - Next; - if (tok = sIdent) and (id = nameStatic) then m^.linkStatic := true - else if tok = sString then begin - New(lib); - lib^.name := Intern(@sbuf, slen); - lib^.next := m^.libs; - m^.libs := lib; - m^.usesC := true; - end else Expected('a library or "static"'); - Next; - Expect(sSemicolon); - end; - { check off;: the module's index and slice checks left out; neither - word is reserved } - if (tok = sIdent) and (id = nameCheck) then begin - Next; - if (tok <> sIdent) or (id <> nameOff) then Expected('"off"'); - Next; - Expect(sSemicolon); - checks := false; - end; - Declarations(true); - if tok = sBegin then begin - if checkMode then SkipBody - else begin - InstancesFor(true); - line := CurLine; - Next; - body := NewChunk(secText, m^.sname, nameBody); - m^.body := body; - BeginProc(tBodySig, nil); - deferSlot := 0; - curResult := nil; - EnterBody(body, line); - stray := false; elseIf := false; - Statements; - NoteLine(CurLine, CurCol); - Expect(sEnd); - EndProc(body, false); - end; - end else Expect(sEnd); - if (tok <> sIdent) or (id <> n) then EndMissing(MissingPos, 'expected ' + NameOf(n) + ', found ' + Found); - Next; - if tok <> sPeriod then Expected('"."'); - o := m^.first; - while o <> nil do begin - if (o^.cls = oProc) and o^.fwd then Error(TokPos, NameOf(o^.name) + ' is declared forward but never defined'); - o := o^.link; - end; - if (errors = 0) and not checkOnly then Warnings(m, firstDrop); - numDrops := firstDrop; - if errors > 0 then Finish; { a module with errors stops the compiler after it } - CloseScope; - m^.done := true; - if not checkOnly then begin - dec(numPending); - if lastModule = nil then firstModule := m else lastModule^.next := m; - lastModule := m; - end; - curModule := oldMod; checkMode := oldCheck; curFile := oldPath; checks := oldChecks; - RestoreScopes(d, saved); - RestoreScan(st); - CompileFile := m; -end; - -{ The interface check: b must export just what a does. } -procedure CompareIface(a, b: PModule); -var o, q: PObj; -begin - o := a^.first; - while o <> nil do begin - if o^.exported then begin - q := Find(b^.scope, o^.name); - if (q = nil) or not q^.exported or (Fingerprint(o) <> Fingerprint(q)) then - Fatal(b^.path + ': ' + NameOf(o^.name) + ' isn''t exported as in ' + a^.path); - end; - o := o^.link; - end; - q := b^.first; - while q <> nil do begin - o := Find(a^.scope, q^.name); - if q^.exported and ((o = nil) or not o^.exported) then - Fatal(b^.path + ': ' + NameOf(q^.name) + ' isn''t exported by ' + a^.path); - q := q^.link; - end; -end; - -{ Reads every other file of module n in dir, and checks its interface - against m, compiled from the file named chosen. } -procedure CheckSiblings(const dir, chosen: shortstring; n: longint; m: PModule; const args: TArgs); -var - dp: pDir; e: pDirent; f, prefix: shortstring; i: longint; - others: array[0..31] of shortstring; numOthers: longint; -begin - prefix := NameOf(n) + '.'; - numOthers := 0; - dp := FpOpenDir(dir); - if dp = nil then exit; - repeat - e := FpReadDir(dp^); - if e = nil then break; - f := ''; - i := 0; - while (e^.d_name[i] <> #0) and (i < 255) do begin - f := f + e^.d_name[i]; - inc(i); - end; - if (copy(f, 1, length(prefix)) = prefix) and (length(f) > 4) - and (copy(f, length(f) - 3, 4) = '.raz') and (f <> chosen) - and (numOthers <= High(others)) then begin - others[numOthers] := f; - inc(numOthers); - end; - until false; - FpCloseDir(dp^); - for i := 0 to numOthers - 1 do - CompareIface(m, CompileFile(dir + '/' + others[i], n, args, true)); -end; - -const Suffixes: array[0..3] of string[16] = ('.' + Target, '.' + TargetOS, '.' + TargetArch, ''); - -{ The directories searched for modules, in order, from -1 to numInc } -function SearchDir(i: longint): shortstring; -begin - if i = -1 then SearchDir := mainDir - else if i = numInc then SearchDir := libDir - else SearchDir := incDirs[i]; -end; - -function ModuleFile(n: longint; var dir, f: shortstring): boolean; -var i, j: longint; -begin - for i := -1 to numInc do begin - dir := SearchDir(i); - for j := 0 to 3 do begin - f := NameOf(n) + Suffixes[j] + '.raz'; - if Exists(dir + '/' + f) then exit(true); - end; - end; - ModuleFile := false; -end; - -{ A program has one module of each name: module n, found as dir/f, - must have no files in a later directory, unless dir/f is a link to - one of them, which chooses it (report, section 3) } -procedure CheckOneModule(n: longint; const dir, f: shortstring; const at: TPos); -var i, j: longint; past, chosen: boolean; g, files, others: shortstring; - st, mine: Stat; -begin - g := dir + '/' + f + #0; - FpStat(@g[1], mine); - others := ''; - past := false; - for i := -1 to numInc do begin - if past then begin - files := ''; - chosen := false; - for j := 0 to 3 do begin - g := SearchDir(i) + '/' + NameOf(n) + Suffixes[j] + '.raz'; - if Exists(g) then begin - files := files + ' and ' + ShownPath(g); - g := g + #0; - FpStat(@g[1], st); - chosen := chosen or ((st.st_dev = mine.st_dev) and (st.st_ino = mine.st_ino)); - end; - end; - if not chosen then others := others + files; - end; - past := past or (SearchDir(i) = dir); - end; - if others = '' then exit; - Error(at, 'module ' + NameOf(n) + ' is in ' + ShownPath(dir + '/' + f) + others); - Help('a program has one module of each name; a symbolic link to one of these files chooses it'); - Fail; -end; - -function ImportModule(name: longint; const args: TArgs): PModule; -var m: PModule; i: longint; dir, f: shortstring; -begin - m := FindModule(name, args); - if m <> nil then exit(m); - for i := 0 to numPending - 1 do - if IsModule(pending[i], name, args) then MarkAt(args.at, NameOf(name) + ' imports itself'); - if not ModuleFile(name, dir, f) then begin - Error(args.at, 'can''t find module ' + NameOf(name)); - dir := ShownPath(SearchDir(-1)); - for i := 0 to numInc do dir := dir + ', ' + ShownPath(SearchDir(i)); - Help('looked for ' + NameOf(name) + '.raz in ' + dir); - Fail; - end; - CheckOneModule(name, dir, f, args.at); - m := CompileFile(dir + '/' + f, name, args, false); - CheckSiblings(dir, f, name, m, args); - ImportModule := m; -end; - -procedure AddImport(m, im: PModule); -var imp: PImport; -begin - New(imp); - imp^.module := im; - imp^.next := m^.imports; - m^.imports := imp; -end; - -{ Makes the instance that deferred[i] imports: its arguments are read - where the import wrote them, and must be declared by now. Compiling - the instance comes in the middle of a declaration, so what that - declaration has under way is kept aside meanwhile. } -procedure MakeInstance(i: longint; const at: TPos); -var - d: TDeferred; st: TScanState; args: TArgs; types, exported, ext, wasQuiet: boolean; nf, nd: longint; - ft: array[0..255] of PType; fp: array[0..255] of TPos; decl: array[0..63] of longint; -begin - d := deferred[i]; - dec(numDeferred); - deferred[i] := deferred[numDeferred]; - SaveScan(st); - RestoreScan(d.args); - args.n := 0; - making := true; useAt := at; - ParseArgs(args, NameOf(d.mname)); - making := false; - RestoreScan(st); - args.at := d.at; - types := inTypes; exported := declExported; ext := inExtern; wasQuiet := quiet; - nf := numFwd; ft := fwdTypes; fp := fwdPos; nd := numDeclaring; decl := declaring; - d.o^.module := ImportModule(d.mname, args); - inTypes := types; declExported := exported; inExtern := ext; quiet := wasQuiet; - numFwd := nf; fwdTypes := ft; fwdPos := fp; numDeclaring := nd; declaring := decl; - AddImport(curModule, d.o^.module); -end; - -procedure FirstUse(o: PObj; const at: TPos); -var i: longint; -begin - for i := 0 to numDeferred - 1 do - if deferred[i].o = o then begin MakeInstance(i, at); exit end; - Fail; { its arguments had an error, already reported } -end; - -{ An instance can't be compiled in the middle of another procedure's - code, so before a procedure's code begins, from its "proc" on, or - the module body's, from its "begin" to the end of the file, this - reads ahead for the names of imports not yet made, and makes those. } -procedure InstancesFor(wholeRest: boolean); -var st: TScanState; d, i: longint; begun: boolean; -begin - if checkMode then exit; - i := numDeferred - 1; - while (i >= 0) and (deferred[i].m <> curModule) do dec(i); - if i < 0 then exit; - { The procedure ends at the "end" that closes its first "begin": d - counts the words still open that "end" or "until" closes, and begun - says that begin was met, so that a record's end in its declarations - doesn't stop it. A forward or code procedure has no raz body to - read, so it stops at that word. The body reads to the end of the - file, as wholeRest says. } - SaveScan(st); - d := 0; begun := false; - repeat - case tok of - sIdent: for i := numDeferred - 1 downto 0 do - if (deferred[i].m = curModule) and (deferred[i].o^.name = id) then MakeInstance(i, TokPos); - sBegin: begin begun := begun or (d = 0); inc(d) end; - sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: inc(d); - sEnd, sUntil: dec(d); - end; - if not wholeRest and (d = 0) and (begun or (tok in [sForward, sCode])) then break; - Next; - until tok = sEof; - RestoreScan(st); -end; - -function CompileMain(const path: shortstring): PModule; -var base: shortstring; i, n: longint; none: TArgs; -begin - none.n := 0; - i := length(path); - while (i > 0) and (path[i] <> '/') do dec(i); - if i = 0 then mainDir := '.' else mainDir := copy(path, 1, i - 1); - base := copy(path, i + 1, 255); - i := pos('.', base); - if i > 0 then base := copy(base, 1, i - 1); - if base = '' then Fatal('no module in ' + path); - n := Name(base); - none.at := TokPos; - if n <> nameRt then ImportModule(nameRt, none); - if FindModule(n, none) <> nil then CompileMain := FindModule(n, none) - else CompileMain := CompileFile(path, n, none, false); -end; - -initialization - nameRt := Name('Rt'); - nameFail := Name('fail'); - nameMain := Name('main'); - nameAdr := Name('ADR'); - nameBody := Name('body'); - nameStatic := Name('static'); - nameCheck := Name('check'); - nameOff := Name('off'); - tArgv := NewPtr(NewPtr(tU8, false), false); - tBodySig := NewType(fProc, 8, 8); - curLoop := nil; - numPending := 0; - firstModule := nil; - lastModule := nil; -end. diff --git a/seed/raz.pas b/seed/raz.pas deleted file mode 100644 index c0ef892..0000000 --- a/seed/raz.pas +++ /dev/null @@ -1,245 +0,0 @@ -{ raz.pas: the command line. - - raz [-I dir]... [-o file] [-Werror] [-S] Main.raz - raz run [-I dir]... Main.raz [arg]... - raz --version - - Compiles the main module and every module it imports, writes the - entry point, links what it reaches, and writes the executable: by - default the main module's file without its .raz; with -S, it lists - the main module's code instead. raz run writes it to a memfd - instead, a file that lives only in memory, and executes it in raz's - place with the arguments after Main.raz, so its status is the - program's; its argv[0] is Main.raz. - - The program starts by saving argc and argv, runs every module's body - (those of the modules the program imports, imported modules first), - then the main module's main, and ends with Rt.exit and main's - status. A static program does this from its entry point. One that - uses C starts through the C library, __libc_start_main, which sets - C up and calls this as C's main; first it gives Rt C's exit, which - Rt.exit then ends the program with. - - Depends on: everything else. - Leaves out: the work itself; the other units compile, link and - write, and this only reads the command line and runs them in order. } - -program raz; - -{$mode objfpc}{$H-} - -uses math, BaseUnix, syscall, scan, diag, sym, chunk, x64, gen, parse, link, elf; - -const - { what git describe says, made by make: 0.3.0 at the tag v0.3.0, - 0.3.0-5-g38d29a8 five commits past it } - Version = {$I version.inc}; - Report = '2026-10.21'; { the version of doc/raz.md it follows } - MemfdCreate = 319; { the system call; FPC 3.2.2 has no name for it } - MfdCloexec = 1; { an ELF still executes: the kernel opens it first } - -{ The modules the program uses: the main module, Rt, and every module - they import. A module read only for the interface check is not. } -procedure Use(m: PModule); -var i: PImport; -begin - if m^.used then exit; - m^.used := true; - i := m^.imports; - while i <> nil do begin - Use(i^.module); - i := i^.next; - end; -end; - -{ Whether the program uses C: if so, the libraries it needs go to - elf.pas, the C library first. } -function UsesC: boolean; -var m, st, c: PModule; l: PLib; i: longint; seen: boolean; -begin - st := nil; c := nil; - numNeeded := 1; - needed[0] := Intern(PChar('libc.so.6'), 9); - m := firstModule; - while m <> nil do begin - if m^.used and m^.linkStatic then st := m; - if m^.used and m^.usesC then c := m; - l := m^.libs; - while m^.used and (l <> nil) do begin - seen := false; - for i := 0 to numNeeded - 1 do seen := seen or (needed[i] = l^.name); - if not seen then begin - if numNeeded > High(needed) then Fatal('more than ' + IntStr(High(needed) + 1) + ' libraries'); - needed[numNeeded] := l^.name; - inc(numNeeded); - end; - l := l^.next; - end; - m := m^.next; - end; - if (st <> nil) and (c <> nil) then - Fatal(NameOf(st^.name) + ' says link static, but ' + NameOf(c^.name) + ' uses C'); - if c = nil then numNeeded := 0; - UsesC := c <> nil; -end; - -{ What raz -h says } -procedure Usage; -begin - writeln('usage: raz [option]... Main.raz compiles Main.raz and the modules it imports'); - writeln(' raz run [option]... Main.raz [arg]... compiles it and runs it, with the args'); - writeln('options:'); - writeln(' -o file the program''s file, Main without .raz if left out'); - writeln(' -I dir looks for imported modules in dir too, after Main.raz''s own'); - writeln(' -Werror a warning counts as an error'); - writeln(' -S lists the main module''s code, under each line of source'); - writeln(' -s strips symbols, line numbers, the places a failure is told'); - writeln(' by and the profiler: a failure says only its address'); - writeln(' -noprofile leaves out the profiler, which RAZ_PROFILE turns on'); - writeln(' -h, --help says this'); - writeln(' --version says the version, and the report it follows'); - writeln('see raz(1), and the report, doc/raz.md'); -end; - -function RtObj(rt: PModule; const n: shortstring): PObj; -var o: PObj; -begin - o := Find(rt^.scope, Intern(@n[1], length(n))); - if o = nil then Fatal('Rt has no ' + n); - RtObj := o; -end; - -var - path, outPath, dir, s: shortstring; - i, first, entry, fd: longint; - m, rt: PModule; - main: PObj; - run, noProfile: boolean; - links: array[0..3] of TLink; - numLinks: longint; - - -{ Rt is given the address of chunk, in its variable v } -procedure AddLink(chunk: longint; v: PObj); -begin - links[numLinks].chunk := chunk; - links[numLinks].into := v^.chunk; - inc(numLinks); -end; - -begin - { constants fold as the machine computes: NaN and infinities, no traps } - SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]); - path := ''; - outPath := ''; - numInc := 0; - noProfile := false; - run := (ParamCount >= 1) and (ParamStr(1) = 'run'); - i := 1 + ord(run); - while i <= ParamCount do begin - s := ParamStr(i); - if s = '-I' then begin - inc(i); - if numInc > High(incDirs) then Fatal('more than ' + IntStr(High(incDirs) + 1) + ' -I directories'); - incDirs[numInc] := ParamStr(i); - inc(numInc); - end else if s = '-o' then begin - inc(i); - outPath := ParamStr(i); - end else if s = '-Werror' then - werror := true - else if s = '-S' then - listing := true - else if s = '-s' then - stripped := true - else if s = '-noprofile' then - noProfile := true - else if (s = '-h') or (s = '--help') then begin - Usage; - Halt(0); - end else if s = '--version' then begin - writeln('raz ', Version, ', report ', Report); - Halt(0); - end else if (s <> '') and (s[1] = '-') then - Fatal('unknown option ' + s) - else begin - path := s; - first := i; - if run then break; { the rest are the program's } - end; - inc(i); - end; - if path = '' then begin - Usage; - Halt(1); - end; - if run and (outPath <> '') then Fatal('raz run takes no -o'); - dir := ParamStr(0); - i := length(dir); - while (i > 0) and (dir[i] <> '/') do dec(i); - if i = 0 then libDir := 'lib' else libDir := copy(dir, 1, i) + 'lib'; - if outPath = '' then begin - outPath := path; - if copy(outPath, length(outPath) - 3, 4) = '.raz' then - outPath := copy(outPath, 1, length(outPath) - 4) - else outPath := outPath + '.out'; - end; - - m := CompileMain(path); - if errors > 0 then Finish; - - Use(m); - rt := firstModule; - while (rt <> nil) and (NameOf(rt^.name) <> 'Rt') do rt := rt^.next; - if rt <> nil then Use(rt); - - main := Find(m^.scope, Intern('main', 4)); - if main <> nil then begin - if (main^.cls <> oProc) or not main^.exported then Error(main^.pos, 'main must be an exported procedure') - else if (main^.typ^.len <> 0) or ((main^.typ^.base <> nil) and (main^.typ^.base <> tInt)) then - Error(main^.pos, 'main must be proc main* or proc main*: INT'); - if errors > 0 then Finish; - end; - Finish; - - if rt = nil then Fatal('can''t find module Rt'); - { what Rt is given: the places, which the linker makes, for Rt to say - where a failed check or a signal was (place), and the calls under - way then (calls); and the profiler, which needs them too. raz -s - gives none, -noprofile no profiler. } - numLinks := 0; - if not stripped then begin - placesChunk := NewChunk(secRodata, -1, -1); - SetData(placesChunk, nil, 0, 8); - AddLink(placesChunk, RtObj(rt, 'places')); - AddLink(RtObj(rt, 'calls')^.chunk, RtObj(rt, 'teller')); - AddLink(RtObj(rt, 'place')^.chunk, RtObj(rt, 'placer')); - if not noProfile then AddLink(RtObj(rt, 'startProfile')^.chunk, RtObj(rt, 'profiler')); - end; - entry := EntryPoint(UsesC, firstModule, main, RtObj(rt, 'cExit')^.chunk, - RtObj(rt, 'exit')^.chunk, links, numLinks); - - MarkLive(entry); - if not HasReals then - for i := 0 to numChunks - 1 do - if chunks^[i].live and chunks^[i].reals then - Error(chunks^[i].realsAt, 'this target has no reals'); - if errors > 0 then Finish; - if listing then begin - List(m^.sname); - exit; - end; - - mainPath := path; - if run then begin - { argv from Main.raz on is the program's, ending in nil as it must } - fd := Do_SysCall(MemfdCreate, TSysParam(PChar('raz')), MfdCloexec); - if fd < 0 then Fatal('can''t create a memfd'); - Str(fd, s); - outPath := '/proc/self/fd/' + s + #0; - WriteElf(outPath, entry); - FpExecve(@outPath[1], @argv[first], envp); - Fatal('can''t run ' + path); - end; - WriteElf(outPath, entry); -end. diff --git a/seed/scan.pas b/seed/scan.pas deleted file mode 100644 index ac8f725..0000000 --- a/seed/scan.pas +++ /dev/null @@ -1,886 +0,0 @@ -{ scan.pas: the scanner. - - Reads a raz source file and hands the parser one symbol at a time: - reserved words, identifiers, numbers, characters, strings and - operators. Identifiers are interned, so that the rest of the compiler - compares names as small integers. The scanner also says where the - current symbol is, for messages. - - Depends on: BaseUnix, to read files; diag, to report errors. - Leaves out: recovery from errors in the text itself, such as a string - not closed: the first such error stops the compiler. The parser goes - on after its own errors, through recovery below. } - -unit scan; - -{$mode objfpc}{$H-} - -interface - -uses diag; - -type - TSym = (sNull, sIdent, sInt, sReal, sChar, sString, - sPlus, sMinus, sTimes, sSlash, sEql, sNeq, sLss, sLeq, sGtr, sGeq, - sBecomes, sColon, sSemicolon, sComma, sPeriod, sUpto, sEllipsis, - sLparen, sRparen, sLbrak, sRbrak, sLbrace, sRbrace, sArrow, sAmp, sTilde, sBar, - sBlank, - { the reserved words, in the order of Words below } - sAnd, sBegin, sBreak, sBy, sCode, sConst, sDefer, sDiv, sDo, sElse, - sElsif, sEnd, sExtern, sFor, sForward, sIf, sImport, sIn, sLink, - sMatch, sMod, sModule, sNot, sOf, sOr, sPacked, sProc, sRecord, - sRepeat, sReturn, sSet, sShl, sShr, sThen, sTo, sTry, sType, sUntil, sVar, - sVariant, sVolatile, sWhile, sXor, - sEof); - - PBytes = ^TBytes; - TBytes = array[0..MaxInt - 1] of byte; - PLongs = ^TLongs; - TLongs = array[0..MaxInt div 4 - 1] of longint; - - { Where the scanner is. Importing a module compiles it in the middle - of another, so the parser saves this and restores it afterwards. } - TScanState = record - buf: PChar; - len, pos, line, lineStart: longint; - tokPos, tokLine, tokLineStart: longint; - prevEnd: longint; { where the symbol before this one ends } - tok: TSym; - ival: int64; - rval: double; - id: longint; - f: longint; { the file, as diag knows it } - end; - -const - MaxIdent = 63; - MaxStr = 65536; - -var - tok: TSym; { the current symbol } - ival: int64; { sInt, sChar: its value } - rval: double; { sReal: its value } - id: longint; { sIdent: its name } - sbuf: array[0..MaxStr] of byte; { sString: its bytes, then a zero } - slen: longint; { sString: how many bytes } - -function Intern(p: PChar; n: longint): longint; -function NameOf(n: longint): shortstring; -function Reserved(n: longint): boolean; -function Open(const path: shortstring): shortstring; -procedure Next; -procedure Mark(const msg: shortstring); -procedure MarkAt(const p: TPos; const msg: shortstring); -procedure MarkHelp(const p: TPos; const msg, hint: shortstring); -procedure Fail; -function AtLineStart: boolean; -function Indent: longint; -function SymText(s: TSym): shortstring; -function Found: shortstring; - -var - { Where the parser goes on after an error: the innermost statement or - declaration being read. nil stops the compiler at the first error. } - recovery: ^jmp_buf; - { The parser is skipping what it has read once already, after an - error, so slips in it aren't reported again. } - skipping: boolean; -procedure SaveScan(var st: TScanState); -procedure RestoreScan(const st: TScanState); -function TokPos: TPos; -function AfterPrev: TPos; -function MissingPos: TPos; -function SpanFrom(const p: TPos): TPos; -function CurLine: longint; -function CurCol: longint; -procedure LineCol(a: longint; out line, col: longint); - -implementation - -uses BaseUnix; - -const - NumWords = ord(sXor) - ord(sAnd) + 1; - Words: array[0..NumWords - 1] of string[8] = ( - 'and', 'begin', 'break', 'by', 'code', 'const', 'defer', 'div', 'do', - 'else', 'elsif', 'end', 'extern', 'for', 'forward', 'if', 'import', - 'in', 'link', 'match', 'mod', 'module', 'not', 'of', 'or', 'packed', - 'proc', 'record', 'repeat', 'return', 'set', 'shl', 'shr', 'then', - 'to', 'try', 'type', 'until', 'var', 'variant', 'VOLATILE', 'while', 'xor'); - Ops: array[sPlus..sBlank] of string[3] = ( - '+', '-', '*', '/', '=', '#', '<', '<=', '>', '>=', - ':=', ':', ';', ',', '.', '..', '...', - '(', ')', '[', ']', '{', '}', '^', '&', '~', '|', '_'); - -var - cur: TScanState; { buf .. path; tok, ival, rval and id live above } - - { The name table: every distinct identifier once, in a pool of - characters, found through an open-addressed hash table. } - pool: PChar; - poolLen, poolCap: longint; - nameOff, nameLen, nameHash: PLongs; - numNames, nameCap: longint; - table: PLongs; { name + 1, or 0 for an empty slot } - tableMask: longint; - -{ Names } - -function Hash(p: PChar; n: longint): longint; -var h: longword; i: longint; -begin - h := 2166136261; - for i := 0 to n - 1 do h := (h xor byte(p[i])) * 16777619; - Hash := longint(h and $7FFFFFFF); -end; - -procedure Grow; -var i, j, n: longint; -begin - FreeMem(table); - tableMask := tableMask * 2 + 1; - table := GetMem((tableMask + 1) * 4); - FillChar(table^, (tableMask + 1) * 4, 0); - for n := 0 to numNames - 1 do begin - i := nameHash^[n] and tableMask; - while table^[i] <> 0 do i := (i + 1) and tableMask; - table^[i] := n + 1; - end; - j := nameCap * 2; - nameOff := ReAllocMem(nameOff, j * 4); - nameLen := ReAllocMem(nameLen, j * 4); - nameHash := ReAllocMem(nameHash, j * 4); - nameCap := j; -end; - -function Intern(p: PChar; n: longint): longint; -var h, i, k: longint; -begin - h := Hash(p, n); - i := h and tableMask; - while table^[i] <> 0 do begin - k := table^[i] - 1; - if (nameHash^[k] = h) and (nameLen^[k] = n) - and (CompareByte(pool[nameOff^[k]], p^, n) = 0) then exit(k); - i := (i + 1) and tableMask; - end; - if poolLen + n > poolCap then begin - poolCap := poolCap * 2 + n; - pool := ReAllocMem(pool, poolCap); - end; - Move(p^, pool[poolLen], n); - k := numNames; - nameOff^[k] := poolLen; - nameLen^[k] := n; - nameHash^[k] := h; - inc(poolLen, n); - inc(numNames); - table^[i] := k + 1; - if numNames * 2 > tableMask then Grow; - Intern := k; -end; - -function NameOf(n: longint): shortstring; -var s: shortstring; -begin - SetLength(s, nameLen^[n]); - Move(pool[nameOff^[n]], s[1], nameLen^[n]); - NameOf := s; -end; - -{ Errors } - -{ The current symbol } -function TokPos: TPos; -begin - TokPos.f := cur.f; - TokPos.a := cur.tokPos; - TokPos.b := cur.pos; -end; - -{ The place just after the symbol before the current one, where a - missing symbol belongs } -function AfterPrev: TPos; -begin - AfterPrev.f := cur.f; - AfterPrev.a := cur.prevEnd; - AfterPrev.b := cur.prevEnd; -end; - -{ Where to say a symbol is missing: at the current symbol, unless it - starts a later line than the symbol before it, which is more likely - where the missing one belongs } -function MissingPos: TPos; -var i: longint; -begin - MissingPos := TokPos; - for i := cur.prevEnd to cur.tokPos - 1 do - if cur.buf[i] = #10 then MissingPos := AfterPrev; -end; - -{ From the start of p to the end of the symbol before the current one: - the whole of a construct that has just been read } -function SpanFrom(const p: TPos): TPos; -begin - SpanFrom := p; - SpanFrom.b := cur.prevEnd; -end; - -function CurLine: longint; -begin - CurLine := cur.tokLine; -end; - -{ The line and column of byte a of the file, at or before the current - symbol: counted back from the symbol's line, so that it costs only - the distance. A column counts characters, as diag's do. } -procedure LineCol(a: longint; out line, col: longint); -var i, start: longint; -begin - line := cur.tokLine; - start := cur.tokLineStart; - while a < start do begin - dec(line); - dec(start); - while (start > 0) and (cur.buf[start - 1] <> #10) do dec(start); - end; - col := 1; - for i := start to a - 1 do - if (byte(cur.buf[i]) and $C0) <> $80 then inc(col); -end; - -function CurCol: longint; -var line: longint; -begin - LineCol(cur.tokPos, line, CurCol); -end; - -procedure Mark(const msg: shortstring); -begin - MarkAt(TokPos, msg); -end; - -{ After an error in the parser's construct, reported with its notes - and help: the parser goes on from the recovery point. } -procedure Fail; -begin - if recovery = nil then Finish; - longjmp(recovery^, 1); -end; - -procedure MarkAt(const p: TPos; const msg: shortstring); -begin - Error(p, msg); - Fail; -end; - -{ MarkAt, with a line of help after the message. } -procedure MarkHelp(const p: TPos; const msg, hint: shortstring); -begin - Error(p, msg); - Help(hint); - Fail; -end; - -{ An error in the text at bytes a to b of the file being read, which - stops the compiler: past it, the symbols can't be trusted. } -procedure MarkBytes(a, b: longint; const msg: shortstring); -var p: TPos; -begin - p.f := cur.f; p.a := a; p.b := b; - quiet := false; - Error(p, msg); - Finish; -end; - -procedure LexError(const msg: shortstring); -begin - MarkBytes(cur.tokPos, cur.pos, msg); -end; - -{ The n characters at the scanner are how another language writes t: - an error, but reading goes on as if t were written. } -procedure Slip(n: longint; t: TSym; const msg: shortstring); -var p: TPos; -begin - p.f := cur.f; p.a := cur.pos; p.b := cur.pos + n; - if not skipping then Error(p, msg); - inc(cur.pos, n); - tok := t; -end; - -{ How an operator or reserved word is written, quoted, for messages. } -function SymText(s: TSym): shortstring; -begin - if s in [sPlus..sBlank] then SymText := '"' + Ops[s] + '"' - else SymText := '"' + Words[ord(s) - ord(sAnd)] + '"'; -end; - -{ The current symbol, for "expected ..., found ...": a name as it is, - a literal by its kind, an operator or reserved word quoted. } -function Found: shortstring; -begin - case tok of - sIdent: Found := NameOf(id); - sInt, sReal: Found := 'a number'; - sChar: Found := 'a character'; - sString: Found := 'a string'; - sEof: Found := 'the end of the file'; - else Found := SymText(tok); - end; -end; - -{ The current symbol is the first on its line: at the top level of a - module, by the usual layout, so where reading can start again. } -function AtLineStart: boolean; -begin - AtLineStart := cur.tokPos = cur.tokLineStart; -end; - -{ The column the current symbol's line is indented to } -function Indent: longint; -var i: longint; -begin - i := cur.tokLineStart; - while cur.buf[i] in [' ', #9] do inc(i); - Indent := i - cur.tokLineStart + 1; -end; - -{ Files } - -{ Name n is a reserved word } -function Reserved(n: longint): boolean; -begin - Reserved := n < NumWords; -end; - -{ Reads the file at path to scan it; '' if it can, else why not } -function Open(const path: shortstring): shortstring; -var fd: cint; st: Stat; n, got, r: longint; p: shortstring; -begin - p := path + #0; - fd := FpOpen(@p[1], O_RDONLY); - if fd < 0 then - case FpGetErrno of - ESysENOENT: exit('there is no such file'); - ESysEACCES: exit('permission denied'); - else exit('it can''t be opened'); - end; - if FpFStat(fd, st) <> 0 then begin FpClose(fd); exit('it can''t be opened') end; - if (st.st_mode and S_IFMT) <> S_IFREG then begin FpClose(fd); exit('it isn''t a file') end; - n := st.st_size; - cur.buf := GetMem(n + 1); - got := 0; - while got < n do begin - r := FpRead(fd, cur.buf[got], n - got); - if r <= 0 then Fatal('can''t read ' + path); - got := got + r; - end; - FpClose(fd); - cur.buf[n] := #0; { the sentinel that ends every scan } - cur.len := n; - cur.pos := 0; - cur.line := 1; - cur.lineStart := 0; - cur.tokPos := 0; - cur.tokLine := 1; - cur.tokLineStart := 0; - cur.f := AddFile(path, cur.buf, n); - Open := ''; -end; - -procedure SaveScan(var st: TScanState); -begin - st := cur; - st.tok := tok; st.ival := ival; st.rval := rval; st.id := id; -end; - -procedure RestoreScan(const st: TScanState); -begin - cur := st; - tok := st.tok; ival := st.ival; rval := st.rval; id := st.id; -end; - -{ UTF-8 } - -{ Decodes the character at buf[pos], which is not ASCII, checking that - it is well formed; returns its code point and moves pos past it. } -function Utf8(var pos: longint): longint; -var b0, b1, n, i, cp: longint; lo, hi: byte; -begin - b0 := byte(cur.buf[pos]); - lo := $80; hi := $BF; - case b0 of - $C2..$DF: begin n := 1; cp := b0 and $1F end; - $E0: begin n := 2; cp := 0; lo := $A0 end; - $E1..$EC, $EE, $EF: begin n := 2; cp := b0 and $0F end; - $ED: begin n := 2; cp := $0D; hi := $9F end; { no surrogates } - $F0: begin n := 3; cp := 0; lo := $90 end; - $F1..$F3: begin n := 3; cp := b0 and $07 end; - $F4: begin n := 3; cp := 4; hi := $8F end; { up to 10FFFFH } - else - cur.tokPos := pos; - LexError('invalid UTF-8'); - end; - for i := 1 to n do begin - b1 := byte(cur.buf[pos + i]); - if (b1 < lo) or (b1 > hi) or (pos + i >= cur.len) then begin - cur.tokPos := pos; - LexError('bad UTF-8'); - end; - cp := cp shl 6 or (b1 and $3F); - lo := $80; hi := $BF; - end; - pos := pos + n + 1; - Utf8 := cp; -end; - -procedure Put(b: longint); -begin - if slen >= MaxStr then LexError('a string holds at most ' + IntStr(MaxStr) + ' bytes'); - sbuf[slen] := b; - inc(slen); -end; - -procedure PutUtf8(cp: longint); -begin - if cp < $80 then Put(cp) - else if cp < $800 then begin - Put($C0 or cp shr 6); Put($80 or cp and $3F) - end else if cp < $10000 then begin - Put($E0 or cp shr 12); Put($80 or cp shr 6 and $3F); Put($80 or cp and $3F) - end else begin - Put($F0 or cp shr 18); Put($80 or cp shr 12 and $3F); - Put($80 or cp shr 6 and $3F); Put($80 or cp and $3F) - end; -end; - -function HexVal(c: char): longint; -begin - case c of - '0'..'9': HexVal := ord(c) - ord('0'); - 'A'..'F': HexVal := ord(c) - ord('A') + 10; - 'a'..'f': HexVal := ord(c) - ord('a') + 10; - else HexVal := -1; - end; -end; - -{ The text of the file from byte a up to but not including b } -function Text(a, b: longint): shortstring; -var p: TPos; -begin - p.f := cur.f; p.a := a; p.b := b; - Text := Source(p); -end; - -{ One character of a character or string literal, at buf[pos]: its code - point, or for \xHH, minus one minus the byte. } -function LitChar(inString: boolean): longint; -var c: char; v, d, n, esc, digits: longint; -begin - c := cur.buf[cur.pos]; - esc := cur.pos; - if c = '\' then begin - inc(cur.pos); - c := cur.buf[cur.pos]; - inc(cur.pos); - case c of - 'n': v := 10; - 't': v := 9; - 'r': v := 13; - '0': v := 0; - '\', '''', '"': v := ord(c); - 'x': begin - if not inString then MarkBytes(esc, cur.pos, '\x is only for strings'); - d := HexVal(cur.buf[cur.pos]); - n := HexVal(cur.buf[cur.pos + 1]); - if (d < 0) or (n < 0) then MarkBytes(esc, cur.pos + 2, '\x needs two hex digits'); - inc(cur.pos, 2); - v := -1 - (d * 16 + n); - end; - 'u': begin - if cur.buf[cur.pos] <> '{' then MarkBytes(esc, cur.pos, 'expected "{" after \u'); - inc(cur.pos); - digits := cur.pos; - v := 0; n := 0; - while HexVal(cur.buf[cur.pos]) >= 0 do begin - v := v * 16 + HexVal(cur.buf[cur.pos]); - inc(n); inc(cur.pos); - if n > 6 then MarkBytes(esc, cur.pos, 'a code point has at most 6 hex digits'); - end; - if (n = 0) or (cur.buf[cur.pos] <> '}') then MarkBytes(esc, cur.pos, 'expected hex digits and "}" after \u{'); - inc(cur.pos); - if (v > $10FFFF) or ((v >= $D800) and (v <= $DFFF)) then - MarkBytes(esc, cur.pos, Text(digits, cur.pos - 1) + ' isn''t a code point'); - end; - else MarkBytes(esc, cur.pos, 'unknown escape \' + c); - end; - end else if byte(c) >= $80 then - v := Utf8(cur.pos) - else if (c < ' ') or (c = #127) then - if inString then LexError('string not closed') - else LexError('character not closed') - else begin - v := ord(c); - inc(cur.pos); - end; - LitChar := v; -end; - -{ Symbols } - -procedure Comment; -var depth, open: longint; c: char; -begin - depth := 1; - open := cur.pos; - inc(cur.pos, 2); - repeat - c := cur.buf[cur.pos]; - if c = #0 then begin - if cur.pos >= cur.len then MarkBytes(open, open + 2, 'comment not closed'); - inc(cur.pos); - end else if (c = '(') and (cur.buf[cur.pos + 1] = '*') then begin - inc(depth); inc(cur.pos, 2) - end else if (c = '*') and (cur.buf[cur.pos + 1] = ')') then begin - dec(depth); inc(cur.pos, 2) - end else if c = #10 then begin - inc(cur.pos); inc(cur.line); cur.lineStart := cur.pos - end else if byte(c) >= $80 then - Utf8(cur.pos) - else - inc(cur.pos); - until depth = 0; -end; - -{ Reading a decimal real exactly: the F64 nearest to digits times 10 to - an exponent, ties to the even one, which a library's Val doesn't - promise. The number is a fraction of two big integers, num / den, - scaled by 2^e until its whole part has 53 or 54 bits; that part and - the remainder give the bits and the rounding. } -type - TBig = record - n: longint; { words in use; 0 is zero } - w: array[0..95] of longword; { least significant first } - end; - { 96 words, 3072 bits, are plenty: a shortstring holds at most 255 - digits, so ReadReal's den is at most 10^(330 + 255), about 2^1944, - and num below 10^310; the shift that follows makes the larger one at - most 54 bits longer than den, about 2000 bits in all. } - -{ a := a * m + add } -procedure BigMul(var a: TBig; m, add: longword); -var i: longint; c: qword; -begin - c := add; - for i := 0 to a.n - 1 do begin - c := qword(a.w[i]) * m + c; - a.w[i] := longword(c); - c := c shr 32; - end; - if c <> 0 then begin a.w[a.n] := longword(c); inc(a.n) end; -end; - -procedure BigShl(var a: TBig; k: longint); -var i, words, bits: longint; -begin - if a.n = 0 then exit; - words := k div 32; bits := k mod 32; - a.w[a.n + words] := 0; - for i := a.n - 1 downto 0 do begin - if bits > 0 then a.w[i + words + 1] := a.w[i + words + 1] or (a.w[i] shr (32 - bits)); - a.w[i + words] := a.w[i] shl bits; - end; - for i := 0 to words - 1 do a.w[i] := 0; - inc(a.n, words + 1); - while (a.n > 0) and (a.w[a.n - 1] = 0) do dec(a.n); -end; - -procedure BigShr1(var a: TBig); -var i: longint; -begin - for i := 0 to a.n - 1 do begin - a.w[i] := a.w[i] shr 1; - if i + 1 < a.n then a.w[i] := a.w[i] or (a.w[i + 1] shl 31); - end; - while (a.n > 0) and (a.w[a.n - 1] = 0) do dec(a.n); -end; - -function BigCmp(const a, b: TBig): longint; -var i: longint; -begin - if a.n <> b.n then exit(ord(a.n > b.n) * 2 - 1); - for i := a.n - 1 downto 0 do - if a.w[i] <> b.w[i] then exit(ord(a.w[i] > b.w[i]) * 2 - 1); - BigCmp := 0; -end; - -{ a := a - b, b not above a } -procedure BigSub(var a: TBig; const b: TBig); -var i: longint; d: int64; -begin - d := 0; - for i := 0 to a.n - 1 do begin - d := d + a.w[i]; - if i < b.n then d := d - b.w[i]; - a.w[i] := longword(d); - d := -ord(d < 0); { a borrow } - end; - while (a.n > 0) and (a.w[a.n - 1] = 0) do dec(a.n); -end; - -function BigBits(const a: TBig): longint; -var t: longword; -begin - if a.n = 0 then exit(0); - BigBits := (a.n - 1) * 32; - t := a.w[a.n - 1]; - while t <> 0 do begin inc(BigBits); t := t shr 1 end; -end; - -{ s is digits, a point, digits, and maybe E, a sign and digits. False if - the value is past the largest F64; one below the smallest is 0. } -function ReadReal(const s: shortstring; out x: double): boolean; -var - num, den, d: TBig; i, digits, e, ex: longint; neg, half, sticky: boolean; - q, b: qword; -begin - num.n := 0; den.n := 1; den.w[0] := 1; - digits := 0; e := 0; i := 1; - while (i <= length(s)) and (s[i] <> 'E') do begin - if s[i] = '.' then e := 1 - else begin - BigMul(num, 10, ord(s[i]) - ord('0')); - if num.n > 0 then inc(digits); { counted from the first that isn't 0 } - if e > 0 then inc(e); - end; - inc(i); - end; - if e > 0 then e := 1 - e; { minus the digits after the point } - ex := 0; neg := false; - if i <= length(s) then begin - inc(i); - neg := s[i] = '-'; - if s[i] in ['+', '-'] then inc(i); - for i := i to length(s) do - if ex < 100000 then ex := ex * 10 + ord(s[i]) - ord('0'); - end; - if neg then ex := -ex; - inc(e, ex); - x := 0.0; - if num.n = 0 then exit(true); - if digits + e > 310 then exit(false); { 10^310 is past every F64 } - if digits + e < -330 then exit(true); { and 10^-330 below half the least } - for i := 1 to e do BigMul(num, 10, 0); - for i := 1 to -e do BigMul(den, 10, 0); - { num / den 2^-e from 2^52 to 2^54, but not past the least exponent } - e := BigBits(num) - BigBits(den) - 53; - if e < -1074 then e := -1074; - if e < 0 then BigShl(num, -e) else BigShl(den, e); - { q, its whole part, by long division; num is left the remainder } - d := den; BigShl(d, 53); - q := 0; - for i := 53 downto 0 do begin - if BigCmp(num, d) >= 0 then begin BigSub(num, d); q := q or (qword(1) shl i) end; - BigShr1(d); - end; - if q >= qword(1) shl 53 then begin { a bit too many: it rounds } - half := odd(q); sticky := num.n > 0; - q := q shr 1; inc(e); - end else begin { the remainder against half of den } - BigShl(num, 1); - i := BigCmp(num, den); - half := i >= 0; sticky := i > 0; - end; - if half and (sticky or odd(q)) then begin - inc(q); - if q = qword(1) shl 53 then begin q := q shr 1; inc(e) end; - end; - if e > 971 then exit(false); - if q >= qword(1) shl 52 then b := qword(e + 1075) shl 52 or (q and (qword(1) shl 52 - 1)) - else b := q; { below the least normal, e is -1074 } - Move(b, x, 8); - ReadReal := true; -end; - -procedure Number; -var start, i, d: longint; allDec: boolean; v: qword; s: shortstring; -begin - start := cur.pos; - allDec := true; - while cur.buf[cur.pos] in ['0'..'9', 'A'..'F'] do begin - if cur.buf[cur.pos] > '9' then allDec := false; - inc(cur.pos); - end; - if cur.buf[cur.pos] = 'H' then begin - v := 0; - for i := start to cur.pos - 1 do begin - if v shr 60 <> 0 then LexError(Text(start, cur.pos) + ' is too big for U64'); - v := v * 16 + qword(HexVal(cur.buf[i])); - end; - inc(cur.pos); - tok := sInt; - ival := int64(v); { 16 digits are the bits of a 64-bit word } - end else if (cur.buf[cur.pos] = '.') and (cur.buf[cur.pos + 1] in ['0'..'9']) then begin - if not allDec then LexError('a decimal number has only the digits 0 to 9'); - inc(cur.pos); - while cur.buf[cur.pos] in ['0'..'9'] do inc(cur.pos); - if cur.buf[cur.pos] = 'E' then begin - inc(cur.pos); - if cur.buf[cur.pos] in ['+', '-'] then inc(cur.pos); - if not (cur.buf[cur.pos] in ['0'..'9']) then LexError('expected a digit in the exponent'); - while cur.buf[cur.pos] in ['0'..'9'] do inc(cur.pos); - end; - if cur.pos - start > 255 then LexError('a number has at most 255 characters'); - SetLength(s, cur.pos - start); - Move(cur.buf[start], s[1], cur.pos - start); - if not ReadReal(s, rval) then LexError(Text(start, cur.pos) + ' is out of the range of F64'); - tok := sReal; - end else begin - if not allDec then LexError('a hex number ends with H'); - v := 0; - for i := start to cur.pos - 1 do begin - d := ord(cur.buf[i]) - ord('0'); - if v > (qword(high(int64)) - qword(d)) div 10 then LexError(Text(start, cur.pos) + ' is too big for I64'); - v := v * 10 + qword(d); - end; - tok := sInt; - ival := int64(v); - end; - if cur.buf[cur.pos] in ['A'..'Z', 'a'..'z', '_', '0'..'9'] then - LexError('a name can''t start with a digit'); -end; - -procedure Next; -var c: char; start, h, v, i: longint; -begin - cur.prevEnd := cur.pos; - repeat - c := cur.buf[cur.pos]; - while c in [' ', #9, #13, #10] do begin - if c = #10 then begin - inc(cur.line); cur.lineStart := cur.pos + 1 - end; - inc(cur.pos); - c := cur.buf[cur.pos]; - end; - if (c = '(') and (cur.buf[cur.pos + 1] = '*') then begin - Comment; c := ' ' - end; - until c <> ' '; - cur.tokPos := cur.pos; - cur.tokLine := cur.line; - cur.tokLineStart := cur.lineStart; - case c of - 'A'..'Z', 'a'..'z', '_': begin - start := cur.pos; - repeat inc(cur.pos) - until not (cur.buf[cur.pos] in ['A'..'Z', 'a'..'z', '0'..'9', '_']); - if cur.pos - start > MaxIdent then LexError('a name has at most ' + IntStr(MaxIdent) + ' characters'); - h := Intern(@cur.buf[start], cur.pos - start); - if (cur.pos - start = 1) and (c = '_') then tok := sBlank - else if h < NumWords then tok := TSym(ord(sAnd) + h) - else begin tok := sIdent; id := h end; - end; - '0'..'9': Number; - '''': begin - inc(cur.pos); - if cur.buf[cur.pos] = '''' then LexError('empty character'); - v := LitChar(false); - if cur.buf[cur.pos] <> '''' then begin - { 'ab': several characters, as some languages write a string } - i := cur.pos; - while not (cur.buf[i] in ['''', #10, #0]) do inc(i); - if cur.buf[i] = '''' then MarkBytes(cur.tokPos, i + 1, 'a character is one character: the string is "' + Text(cur.tokPos + 1, i) + '"') - else LexError('character not closed'); - end; - inc(cur.pos); - tok := sChar; - ival := v; - end; - '"': begin - inc(cur.pos); - slen := 0; - while cur.buf[cur.pos] <> '"' do begin - v := LitChar(true); - if v < 0 then Put(-1 - v) else PutUtf8(v); - end; - inc(cur.pos); - sbuf[slen] := 0; - tok := sString; - end; - '+': begin inc(cur.pos); tok := sPlus end; - '-': begin inc(cur.pos); tok := sMinus end; - '*': begin inc(cur.pos); tok := sTimes end; - '/': begin inc(cur.pos); tok := sSlash end; - '=': - if cur.buf[cur.pos + 1] = '=' then Slip(2, sEql, 'comparing is written =, not ==') - else begin inc(cur.pos); tok := sEql end; - '&': - if cur.buf[cur.pos + 1] = '&' then Slip(2, sAnd, '"and" is written and, not &&') - else begin inc(cur.pos); tok := sAmp end; - '#': begin inc(cur.pos); tok := sNeq end; - '<': begin - inc(cur.pos); - if cur.buf[cur.pos] = '=' then begin inc(cur.pos); tok := sLeq end - else tok := sLss; - end; - '>': begin - inc(cur.pos); - if cur.buf[cur.pos] = '=' then begin inc(cur.pos); tok := sGeq end - else tok := sGtr; - end; - ':': begin - inc(cur.pos); - if cur.buf[cur.pos] = '=' then begin inc(cur.pos); tok := sBecomes end - else tok := sColon; - end; - ';': begin inc(cur.pos); tok := sSemicolon end; - ',': begin inc(cur.pos); tok := sComma end; - '.': begin - inc(cur.pos); - if cur.buf[cur.pos] = '.' then begin - inc(cur.pos); - if cur.buf[cur.pos] = '.' then begin inc(cur.pos); tok := sEllipsis end - else tok := sUpto; - end else tok := sPeriod; - end; - '(': begin inc(cur.pos); tok := sLparen end; - ')': begin inc(cur.pos); tok := sRparen end; - '[': begin inc(cur.pos); tok := sLbrak end; - ']': begin inc(cur.pos); tok := sRbrak end; - '{': begin inc(cur.pos); tok := sLbrace end; - '}': begin inc(cur.pos); tok := sRbrace end; - '^': begin inc(cur.pos); tok := sArrow end; - '|': - if cur.buf[cur.pos + 1] = '|' then Slip(2, sOr, '"or" is written or, not ||') - else begin inc(cur.pos); tok := sBar end; - '~': begin inc(cur.pos); tok := sTilde end; - '!': - if cur.buf[cur.pos + 1] = '=' then Slip(2, sNeq, '"not equal" is written #, not !=') - else Slip(1, sNot, '"not" is written not, not !'); - #0: begin - if cur.pos < cur.len then MarkBytes(cur.pos, cur.pos + 1, 'NUL byte in the text'); - tok := sEof; - end; - else - if byte(c) >= $80 then - LexError('only ASCII outside strings, characters and comments'); - MarkBytes(cur.pos, cur.pos + 1, 'unexpected character "' + c + '"'); - end; -end; - -var i: longint; - -initialization - poolCap := 1 shl 16; - pool := GetMem(poolCap); - nameCap := 1 shl 12; - nameOff := GetMem(nameCap * 4); - nameLen := GetMem(nameCap * 4); - nameHash := GetMem(nameCap * 4); - tableMask := 2 * nameCap - 1; - table := GetMem((tableMask + 1) * 4); - FillChar(table^, (tableMask + 1) * 4, 0); - for i := 0 to NumWords - 1 do Intern(@Words[i][1], length(Words[i])); -end. diff --git a/seed/sym.pas b/seed/sym.pas deleted file mode 100644 index 29c01fd..0000000 --- a/seed/sym.pas +++ /dev/null @@ -1,646 +0,0 @@ -{ sym.pas: types, objects and scopes. - - Every name the program declares becomes an object (TObj): a constant, - type, variable, procedure, module, record field, variant case or - built-in. Every type is a TType. Objects are found through one hash - table keyed by scope and name, so a lookup costs the same however - big a module grows. A scope is just a number: the universe is 0, - and each module, procedure, record and match arm gets a fresh one. - - Depends on: scan, for names and errors. - Leaves out: code. Where a variable lives is decided here (frame - offsets, chunk numbers), but nothing is emitted. } - -unit sym; - -{$mode objfpc}{$H-} - -interface - -uses scan, diag; - -type - TForm = (fNone, fBool, fInt, fReal, fConst, fNil, fStr, fPtr, fArray, - fSlice, fRecord, fVariant, fProc, fEnum, fSet, fError); - { fConst is the type of an untyped integer constant; fStr of a string - literal, whose length the literal carries. F32 and F64 are fReal, - told apart by size, and so is tRConst, an untyped real constant. } - - TClass = (oConst, oType, oVar, oProc, oModule, oField, oCase, oBuiltin); - - PType = ^TType; - PObj = ^TObj; - PModule = ^TModule; - PImport = ^TImport; - PLib = ^TLib; - - TType = record - form: TForm; - size, align: int64; - signed: boolean; { fInt } - vol: boolean; { fPtr: ^VOLATILE } - packd: boolean; { fRecord } - variadic: boolean; { fProc: ends in ... } - tuple: boolean; { fRecord: the results of a procedure that has several } - base: PType; { fPtr, fArray, fSlice: what it holds; fProc: result } - len: int64; { fArray: elements; fProc: parameters; fVariant: cases; a tuple: results } - fields: PObj; { fRecord: fields; fVariant: cases; fProc: parameters } - scope: longint; { fRecord: the scope of its fields } - fwd: longint; { fPtr whose base isn't declared yet: its name, else -1 } - obj: PObj; { the declaration that names it, or nil } - module: PModule; { the module that built it } - end; - - TObj = record - cls: TClass; - name: longint; - exported: boolean; - typ: PType; - next: PObj; { the next in its list: scope, fields, parameters } - scope: longint; { where it is declared } - pos: TPos; { where its name is declared, for messages } - val: int64; { oConst: value; oBuiltin: which; oCase: tag; - oField: offset; oVar: frame offset } - chunk: longint; { global oVar, oProc, string oConst: its chunk } - lev: integer; { oVar: 0 for a module variable, 1 for a local } - ind: boolean; { oVar: the frame slot holds the variable's address } - off: int64; { oVar with ind: added to that address } - isVar: boolean; { a var parameter } - param: boolean; { oVar: a parameter } - used: boolean; { named somewhere but in its own body } - read: boolean; { oVar: named other than as what := assigns } - 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; - for a slice, the one its pointer is in } - reg2: longint; { oVar: a slice in registers: the one its length is in } - ext: boolean; { oProc, oVar: C's, reached through its chunk, which - holds its address } - fields: PObj; { oCase: its fields } - module: PModule; { oModule: the module; others: where declared } - link: PObj; { the next declaration of its module, top-level or - local } - end; - - { The arguments of a generic module's instance: a type, or a - procedure (o) and its type. } - TArgs = record - n: longint; - t: array[0..7] of PType; - o: array[0..7] of PObj; - pos: array[0..7] of TPos; { where each argument is, for messages } - at: TPos; { where the import is } - end; - - TImport = record - module: PModule; - next: PImport; - end; - - { A library a module links, by its name, as interned } - TLib = record - name: longint; - next: PLib; - end; - - TModule = record - name: longint; - sname: longint; { the name of its symbols: List(I64) for an instance } - args: TArgs; - scope: longint; - path: shortstring; - first, last: PObj; { its top-level declarations, in order } - locals, lastLocal: PObj; { its procedures' declarations, in order } - imports: PImport; - body: longint; { the chunk of its body, or -1 } - done: boolean; { compiled to the end } - checkOnly: boolean; { read only to check another file's interface } - used: boolean; { imported, through others, by the main module } - usesC: boolean; { has an extern, or links a library } - linkStatic: boolean; { says link static } - libs: PLib; { the libraries it links } - next: PModule; { modules in the order they were finished } - end; - -const - { built-in procedures } - bSize = 0; bAdr = 1; bLen = 2; bNew = 3; bMsg = 4; bSyscall = 5; - bFence = 6; bCas = 7; bXchg = 8; bXadd = 9; bArgc = 10; bArgv = 11; - bInc = 12; bDec = 13; bCopy = 14; - - MaxDepth = 64; { scopes open at once } - -var - tI8, tI16, tI32, tI64, tU8, tU16, tU32, tU64: PType; - tInt, tUInt: PType; { INT and UINT, as big as an address: 8 bytes here } - tBool, tF32, tReal, tRConst, tError, tConst, tNil, tStr, tNone, tPtrU8, tBytes: PType; - tPoison: PType; { of a name reported as not declared } - curModule: PModule; - -function NewType(form: TForm; size, align: int64): PType; -function NewObj(cls: TClass; name: longint; typ: PType): PObj; -function NewScope: longint; -procedure OpenScope(s: longint); -procedure CloseScope; -function ScopeDepth: longint; -procedure CutScopes(d: longint); -function TopScope: longint; -procedure SaveScopes(var d: longint; var saved: array of longint); -procedure RestoreScopes(d: longint; const saved: array of longint); -procedure Insert(obj: PObj; s: longint); -function Find(s, name: longint): PObj; -function Lookup(name: longint): PObj; -function Closest(name, s: longint): PObj; - -function AlignUp(x, a: int64): int64; -function Same(a, b: PType): boolean; -function IsInt(t: PType): boolean; -function IsScalar(t: PType): boolean; -function IsAggregate(t: PType): boolean; -function InTwoRegs(t: PType): boolean; -function BehindPointer(t: PType): boolean; -function Fits(v: int64; t: PType): boolean; -function TypeName(t: PType): shortstring; -function Fingerprint(o: PObj): qword; - -implementation - -uses math; - -type - PObjTab = ^TObjTab; - TObjTab = array[0..MaxInt div 16] of PObj; - -var - scopes: array[0..MaxDepth - 1] of longint; - depth: longint; - nextScope: longint; - hashTab: PObjTab; - hashMask, hashCount: longint; - -function NewType(form: TForm; size, align: int64): PType; -var t: PType; -begin - New(t); - FillChar(t^, SizeOf(TType), 0); - t^.form := form; - t^.size := size; - t^.align := align; - t^.fwd := -1; - t^.module := curModule; - NewType := t; -end; - -function NewObj(cls: TClass; name: longint; typ: PType): PObj; -var o: PObj; -begin - New(o); - FillChar(o^, SizeOf(TObj), 0); - o^.cls := cls; - o^.name := name; - o^.typ := typ; - o^.chunk := -1; - o^.module := curModule; - o^.pos := TokPos; - NewObj := o; -end; - -{ Scopes } - -function NewScope: longint; -begin - inc(nextScope); - NewScope := nextScope; -end; - -procedure OpenScope(s: longint); -begin - if depth = MaxDepth then Mark('scopes nested more than ' + IntStr(MaxDepth) + ' deep'); - scopes[depth] := s; - inc(depth); -end; - -procedure CloseScope; -begin - dec(depth); -end; - -{ An imported module is compiled in the middle of another, and must - see only the universe and itself. } -procedure SaveScopes(var d: longint; var saved: array of longint); -var i: longint; -begin - d := depth; - for i := 0 to depth - 1 do saved[i] := scopes[i]; - depth := 1; -end; - -procedure RestoreScopes(d: longint; const saved: array of longint); -var i: longint; -begin - depth := d; - for i := 0 to depth - 1 do scopes[i] := saved[i]; -end; - -function ScopeDepth: longint; -begin - ScopeDepth := depth; -end; - -{ Closes the scopes opened since there were d, after an error } -procedure CutScopes(d: longint); -begin - depth := d; -end; - -function TopScope: longint; -begin - TopScope := scopes[depth - 1]; -end; - -{ Where the search for name in scope s starts in the hash table: each - number is multiplied by an odd constant near 2^32 or 2^16 over the - golden ratio (Knuth's multiplicative hashing), which spreads the low - bits the mask keeps. } -function Slot(s, name: longint): longint; -begin - Slot := longint((longword(s) * 2654435761 xor longword(name) * 40503) and longword(hashMask)); -end; - -{ Doubles the table, which Insert keeps at most half full so that the - linear probing stays short, and puts every entry in its new slot. } -procedure Rehash; -var old: PObjTab; n, i, j: longint; -begin - old := hashTab; - n := hashMask + 1; - hashMask := n * 2 - 1; - hashTab := GetMem(n * 2 * SizeOf(PObj)); - FillChar(hashTab^, n * 2 * SizeOf(PObj), 0); - for i := 0 to n - 1 do - if old^[i] <> nil then begin - j := Slot(old^[i]^.scope, old^[i]^.name); - while hashTab^[j] <> nil do j := (j + 1) and hashMask; - hashTab^[j] := old^[i]; - end; - FreeMem(old); -end; - -procedure Insert(obj: PObj; s: longint); -var i: longint; o: PObj; -begin - i := Slot(s, obj^.name); - o := hashTab^[i]; - while o <> nil do begin - if (o^.scope = s) and (o^.name = obj^.name) then begin - Error(obj^.pos, NameOf(obj^.name) + ' is declared twice'); - Note(o^.pos, 'the first one is here'); - Fail; - end; - i := (i + 1) and hashMask; - o := hashTab^[i]; - end; - obj^.scope := s; - hashTab^[i] := obj; - inc(hashCount); - if hashCount * 2 > hashMask then Rehash; -end; - -function Find(s, name: longint): PObj; -var i: longint; o: PObj; -begin - i := Slot(s, name); - o := hashTab^[i]; - while o <> nil do begin - if (o^.scope = s) and (o^.name = name) then exit(o); - i := (i + 1) and hashMask; - o := hashTab^[i]; - end; - Find := nil; -end; - -function Lookup(name: longint): PObj; -var i: longint; o: PObj; -begin - for i := depth - 1 downto 0 do begin - o := Find(scopes[i], name); - if o <> nil then exit(o); - end; - Lookup := nil; -end; - -{ How far apart two names are: the edits, a character put in, taken out, - changed or swapped with the next, that make one the other, ignoring - case. } -function Distance(const a, b: shortstring): longint; -var d: array[0..MaxIdent + 1, 0..MaxIdent + 1] of longint; i, j, c: longint; -begin - for i := 0 to length(a) do d[i, 0] := i; - for j := 0 to length(b) do d[0, j] := j; - for i := 1 to length(a) do - for j := 1 to length(b) do begin - c := ord(UpCase(a[i]) <> UpCase(b[j])); - d[i, j] := Min(Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + c); - if (i > 1) and (j > 1) and (UpCase(a[i]) = UpCase(b[j - 1])) - and (UpCase(a[i - 1]) = UpCase(b[j])) then - d[i, j] := Min(d[i, j], d[i - 2, j - 2] + 1); - end; - Distance := d[length(a), length(b)]; -end; - -{ The name spelled most like name, for "did you mean": in scope s, if - it can be reached from here, or in the scopes in reach if s < 0; nil - if none is within an edit for every three characters. Only after an - error, so it looks at every object. } -function Closest(name, s: longint): PObj; -var i, j, d, best: longint; o: PObj; n: shortstring; reach: boolean; -begin - n := NameOf(name); - best := length(n) div 3 + 1; - Closest := nil; - for i := 0 to hashMask do begin - o := hashTab^[i]; - if (o = nil) or (o^.name = name) or (o^.name < 0) or (o^.typ = tPoison) then continue; - if s >= 0 then reach := (o^.scope = s) and (o^.exported or (o^.module = curModule)) - else begin - reach := false; - for j := 0 to depth - 1 do reach := reach or (o^.scope = scopes[j]); - end; - if reach then begin - d := Distance(n, NameOf(o^.name)); - if d < best then begin best := d; Closest := o end; - end; - end; -end; - -{ Types } - -function AlignUp(x, a: int64): int64; -begin - AlignUp := (x + a - 1) div a * a; -end; - -function IsInt(t: PType): boolean; -begin - IsInt := t^.form in [fInt, fConst]; -end; - -function IsScalar(t: PType): boolean; -begin - IsScalar := t^.form in [fBool, fInt, fReal, fConst, fNil, fPtr, fProc, - fEnum, fSet, fError]; -end; - -function IsAggregate(t: PType): boolean; -begin - IsAggregate := t^.form in [fArray, fSlice, fRecord, fVariant]; -end; - -{ Whether a procedure's result t is two words, which come back in rax - and rdx, as System V returns a struct of two integers: a slice (its - pointer, then its length), or two results that are each a single - value of 8 bytes at most and not a real. } -function InTwoRegs(t: PType): boolean; - - function OneWord(f: PObj): boolean; - begin - OneWord := IsScalar(f^.typ) and (f^.typ^.form <> fReal) and (f^.typ^.size <= 8); - end; - -begin - if t^.form = fSlice then exit(true); - InTwoRegs := t^.tuple and (t^.len = 2) and OneWord(t^.fields) and OneWord(t^.fields^.next); -end; - -{ Whether a procedure's result t comes back in memory the caller - provides, whose address the caller passes as a hidden first argument, - in rdi: any result that is neither one value, in rax or xmm0, nor two - words, in rax and rdx. } -function BehindPointer(t: PType): boolean; -begin - BehindPointer := IsAggregate(t) and not InTwoRegs(t); -end; - -function Fits(v: int64; t: PType): boolean; -begin - if t^.form <> fInt then exit(t^.form = fConst); - case t^.size of - 1: if t^.signed then Fits := (v >= -128) and (v <= 127) - else Fits := (v >= 0) and (v <= 255); - 2: if t^.signed then Fits := (v >= -32768) and (v <= 32767) - else Fits := (v >= 0) and (v <= 65535); - 4: if t^.signed then Fits := (v >= -2147483648) and (v <= 2147483647) - else Fits := (v >= 0) and (v <= 4294967295); - else Fits := t^.signed or (v >= 0); - end; -end; - -{ Structural sameness of two types. Named types are the same only if - they are one declaration; a type with no name is the same as another - built alike. } -function Alike(a, b: PType): boolean; -var p, q: PObj; -begin - if a = b then exit(true); - if a^.form <> b^.form then exit(false); - case a^.form of - fPtr: Alike := (a^.vol = b^.vol) and Same(a^.base, b^.base); - fArray: Alike := (a^.len = b^.len) and Same(a^.base, b^.base); - fSlice, fSet: Alike := Same(a^.base, b^.base); - fProc, fRecord: begin - { a record is the same only as itself, but for several results } - if (a^.form = fRecord) and not (a^.tuple and b^.tuple) then exit(false); - if (a^.len <> b^.len) or (a^.variadic <> b^.variadic) then exit(false); - if (a^.base = nil) <> (b^.base = nil) then exit(false); - if (a^.base <> nil) and not Same(a^.base, b^.base) then exit(false); - p := a^.fields; q := b^.fields; - while p <> nil do begin - if (p^.isVar <> q^.isVar) or not Same(p^.typ, q^.typ) then exit(false); - p := p^.next; q := q^.next; - end; - Alike := true; - end; - else Alike := false; - end; -end; - -function Same(a, b: PType): boolean; -begin - if a = b then exit(true); - if (a = nil) or (b = nil) then exit(false); - if (a^.obj <> nil) and (b^.obj <> nil) then exit(false); - Same := Alike(a, b); -end; - -function TypeName(t: PType): shortstring; -var s: shortstring; f: PObj; -begin - if t = nil then exit('nothing'); - if t^.obj <> nil then begin - if (t^.obj^.module <> nil) and (t^.obj^.module <> curModule) then - exit(NameOf(t^.obj^.module^.sname) + '.' + NameOf(t^.obj^.name)); - exit(NameOf(t^.obj^.name)); - end; - case t^.form of - fConst: TypeName := 'an integer constant'; - fReal: TypeName := 'a real constant'; - fNil: TypeName := 'nil'; - fStr: TypeName := 'a string'; - fPtr: if t^.vol then TypeName := '^VOLATILE ' + TypeName(t^.base) - else TypeName := '^' + TypeName(t^.base); - fArray: begin Str(t^.len, s); TypeName := '[' + s + ']' + TypeName(t^.base) end; - fSlice: TypeName := '[]' + TypeName(t^.base); - fRecord: if not t^.tuple then TypeName := 'record' - else begin - s := '('; - f := t^.fields; - while f <> nil do begin - s := s + TypeName(f^.typ); - f := f^.next; - if f <> nil then s := s + ', '; - end; - TypeName := s + ')'; - end; - fVariant: TypeName := 'variant'; - fProc: begin - s := 'proc('; - f := t^.fields; - while f <> nil do begin - if f^.isVar then s := s + 'var '; - s := s + TypeName(f^.typ); - f := f^.next; - if f <> nil then s := s + ', '; - end; - s := s + ')'; - if t^.base <> nil then s := s + ': ' + TypeName(t^.base); - TypeName := s; - end; - else TypeName := '?'; - end; -end; - -{ A fingerprint of what a declaration exports, for the interface - check: two files of one module export the same thing when their - fingerprints agree. A named type counts by its name, so that a type - declared in each file stands for the other's. } -procedure Mix(var h: qword; v: int64); -begin - h := (h xor qword(v)) * 1099511628211; { FNV-1a's 64-bit prime } -end; - -procedure Shape(var h: qword; t: PType; top: boolean); -var f, g: PObj; -begin - if t = nil then begin Mix(h, -1); exit end; - if (t^.obj <> nil) and not top then begin - Mix(h, t^.obj^.name); - if t^.obj^.module <> nil then Mix(h, t^.obj^.module^.sname); - exit; - end; - Mix(h, ord(t^.form)); - Mix(h, ord(t^.vol) + 2 * ord(t^.variadic)); - Mix(h, t^.len); - if t^.form in [fPtr, fArray, fSlice, fProc, fSet] then Shape(h, t^.base, false); - f := t^.fields; - while f <> nil do begin - if (t^.form <> fRecord) or f^.exported then begin - Mix(h, f^.name); - Mix(h, ord(f^.isVar)); - Shape(h, f^.typ, false); - g := f^.fields; - while g <> nil do begin Shape(h, g^.typ, false); g := g^.next end; - end; - f := f^.next; - end; -end; - -function Fingerprint(o: PObj): qword; -var h: qword; f: PObj; -begin - h := 14695981039346656037; { FNV-1a's 64-bit offset basis } - Mix(h, ord(o^.cls)); - if o^.cls = oCase then begin - Mix(h, o^.val); - f := o^.fields; - while f <> nil do begin Shape(h, f^.typ, false); f := f^.next end; - end else Shape(h, o^.typ, o^.cls = oType); - Fingerprint := h; -end; - -{ The universe } - -function Basic(const name: shortstring; form: TForm; size: int64; signed: boolean): PType; -var t: PType; o: PObj; -begin - t := NewType(form, size, size); - t^.signed := signed; - o := NewObj(oType, Intern(@name[1], length(name)), t); - o^.exported := true; - t^.obj := o; - Insert(o, 0); - Basic := t; -end; - -procedure Enter(const name: shortstring; cls: TClass; t: PType; v: int64); -var o: PObj; -begin - o := NewObj(cls, Intern(@name[1], length(name)), t); - o^.val := v; - o^.exported := true; - Insert(o, 0); -end; - -initialization - hashMask := (1 shl 14) - 1; - hashTab := GetMem((hashMask + 1) * SizeOf(PObj)); - FillChar(hashTab^, (hashMask + 1) * SizeOf(PObj), 0); - depth := 1; - scopes[0] := 0; - nextScope := 0; - curModule := nil; - tI8 := Basic('I8', fInt, 1, true); - tI16 := Basic('I16', fInt, 2, true); - tI32 := Basic('I32', fInt, 4, true); - tI64 := Basic('I64', fInt, 8, true); - tU8 := Basic('U8', fInt, 1, false); - tU16 := Basic('U16', fInt, 2, false); - tU32 := Basic('U32', fInt, 4, false); - tU64 := Basic('U64', fInt, 8, false); - tInt := Basic('INT', fInt, 8, true); - tUInt := Basic('UINT', fInt, 8, false); - tBool := Basic('BOOL', fBool, 1, false); - tF32 := Basic('F32', fReal, 4, false); - tReal := Basic('F64', fReal, 8, false); - tRConst := NewType(fReal, 8, 8); - tError := Basic('ERROR', fError, 8, false); - tConst := NewType(fConst, 8, 8); - tConst^.signed := true; - tNil := NewType(fNil, 8, 8); - tStr := NewType(fStr, 0, 1); - tNone := NewType(fNone, 0, 1); - tPtrU8 := NewType(fPtr, 8, 8); - tPtrU8^.base := tU8; - tBytes := NewType(fSlice, 16, 8); - tBytes^.base := tU8; - tPoison := NewType(fInt, 8, 8); - tPoison^.signed := true; - Enter('true', oConst, tBool, 1); - Enter('false', oConst, tBool, 0); - Enter('nil', oConst, tNil, 0); - Enter('SIZE', oBuiltin, nil, bSize); - Enter('ADR', oBuiltin, nil, bAdr); - Enter('LEN', oBuiltin, nil, bLen); - Enter('NEW', oBuiltin, nil, bNew); - Enter('MSG', oBuiltin, nil, bMsg); - Enter('SYSCALL', oBuiltin, nil, bSyscall); - Enter('FENCE', oBuiltin, nil, bFence); - Enter('CAS', oBuiltin, nil, bCas); - Enter('XCHG', oBuiltin, nil, bXchg); - Enter('XADD', oBuiltin, nil, bXadd); - Enter('ARGC', oBuiltin, nil, bArgc); - Enter('ARGV', oBuiltin, nil, bArgv); - Enter('INC', oBuiltin, nil, bInc); - Enter('DEC', oBuiltin, nil, bDec); - Enter('COPY', oBuiltin, nil, bCopy); -end. diff --git a/seed/x64.pas b/seed/x64.pas deleted file mode 100644 index e7efa73..0000000 --- a/seed/x64.pas +++ /dev/null @@ -1,1208 +0,0 @@ -{ x64.pas: machine code for x86-64. - - The encoder writes the instructions the code generator needs, and - no others, into the text of chunk.pas. Registers are numbered as the - hardware numbers them. Jumps within a procedure are patched here, as - soon as their target is known. - - Depends on: scan, for errors; chunk, for the code buffer and fixups. - Leaves out: choosing instructions; that is gen.pas. } - -unit x64; - -{$mode objfpc}{$H-} - -interface - -uses scan, diag, chunk; - -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; R12 = 12; R13 = 13; R14 = 14; R15 = 15; - RIP = -1; { a base meaning rip-relative, to a chunk } - NoIndex = -1; - - { condition codes } - ccB = 2; ccAE = 3; ccE = 4; ccNE = 5; ccBE = 6; ccA = 7; ccS = 8; - ccP = 10; ccNP = 11; ccL = 12; ccGE = 13; ccLE = 14; ccG = 15; - - { group 1 operations, the /digit of 81 and 83 } - aluAdd = 0; aluOr = 1; aluAnd = 4; aluSub = 5; aluXor = 6; aluCmp = 7; - - { the /digit of D3 and C1 } - shShl = 4; shShr = 5; shSar = 7; - - NoLabel = -1; - -type - TMem = record - base: longint; { a register, or RIP } - index: longint; { a register, or NoIndex } - scale: longint; { 1, 2, 4 or 8 } - disp: longint; - chunk: longint; { with RIP: the chunk addressed } - end; - -var - listing: boolean; { -S: each instruction's text is kept, for List } - -function Here: TMem; -function Mem(base: longint; disp: int64): TMem; -function MemRip(chunk: longint; disp: longint): TMem; -function MemIdx(base, index, scale: longint; disp: int64): TMem; - -procedure MovRR(dst, src: longint); -procedure MovRI(r: longint; v: int64); -procedure Load(r: longint; const m: TMem; size: longint; signed: boolean); -procedure Store(const m: TMem; r: longint; size: longint); -procedure Lea(r: longint; const m: TMem); -procedure Alu(op, dst, src: longint); -procedure AluI(op, r: longint; v: longint); -procedure AluM(op, r: longint; const m: TMem); -procedure AluMI(op: longint; m: TMem; v, size: longint); -procedure StoreI(m: TMem; v, size: longint); -procedure Imul(dst, src: longint); -procedure ImulI(r: longint; v: longint); -procedure Shift(op, r: longint); -procedure ShiftI(op, r, n: longint); -procedure Unary(ext, r: longint); { F7 /ext: 2 not, 3 neg, 6 div, 7 idiv } -procedure Cqo; -procedure Extend(r, size: longint; signed: boolean); -procedure SetCC(cc, r: longint); -procedure TestRR(a, b: longint); -procedure Push(r: longint); -procedure Pop(r: longint); -procedure CallChunk(c: longint); -procedure CallBack(target: longint); -procedure CallR(r: longint); -procedure JmpR(r: longint); -procedure CallM(const m: TMem); -procedure Ret; -procedure Leave; -procedure Syscall; -procedure Mfence; -procedure Ud2; -procedure Align(n: longint); -procedure RepMovsb; -procedure Std; -procedure Cld; -procedure RepStosb; -procedure RepeCmpsb; -procedure LockCmpxchg(const m: TMem; r: longint); -procedure Xchg(const m: TMem; r: longint); -procedure LockXadd(const m: TMem; r: longint); -procedure MovqXR(x, r: longint); -procedure MovqRX(r, x: longint); -procedure MovX(x, y: longint); -{ The real instructions take single: F32 (ss) rather than F64 (sd) } -procedure MovsXM(x: longint; const m: TMem; single: boolean); -procedure MovsMX(const m: TMem; x: longint; single: boolean); -procedure Sse(op, x, y: longint; single: boolean); { 58 add, 59 mul, 5C sub, 5E div, 5A convert } -procedure SseM(op, x: longint; const m: TMem; single: boolean); -procedure Ucomis(x, y: longint; single: boolean); -procedure Cvtsi2s(x, r: longint; single: boolean); -procedure Cvtts2si(r, x: longint; single: boolean); -procedure Btc(r, bit: longint); - -procedure Jmp(var L: longint); -procedure Jcc(cc: longint; var L: longint); -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; - -type - { The parser's reader of an integer constant in a code procedure: a - whole expression, or, when whole is false, a single factor } - TConstFn = function(whole: boolean): int64; - -const - RegNames: array[0..3, 0..15] of string[5] = ( - ('rax', 'rcx', 'rdx', 'rbx', 'rsp', 'rbp', 'rsi', 'rdi', - 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15'), - ('eax', 'ecx', 'edx', 'ebx', 'esp', 'ebp', 'esi', 'edi', - 'r8d', 'r9d', 'r10d', 'r11d', 'r12d', 'r13d', 'r14d', 'r15d'), - ('ax', 'cx', 'dx', 'bx', 'sp', 'bp', 'si', 'di', - 'r8w', 'r9w', 'r10w', 'r11w', 'r12w', 'r13w', 'r14w', 'r15w'), - ('al', 'cl', 'dl', 'bl', 'spl', 'bpl', 'sil', 'dil', - 'r8b', 'r9b', 'r10b', 'r11b', 'r12b', 'r13b', 'r14b', 'r15b')); - CondNames: array[0..15] of string[3] = ('o', 'no', 'b', 'ae', 'e', 'ne', - 'be', 'a', 's', 'ns', 'p', 'np', 'l', 'ge', 'le', 'g'); - -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); - -implementation - -{ Operands } - -function Mem(base: longint; disp: int64): TMem; -begin - if (disp < low(longint)) or (disp > high(longint)) then Mark('an offset beyond 32 bits'); - Mem.base := base; Mem.index := NoIndex; Mem.scale := 1; - Mem.disp := disp; Mem.chunk := -1; -end; - -function MemRip(chunk: longint; disp: longint): TMem; -begin - MemRip.base := RIP; MemRip.index := NoIndex; MemRip.scale := 1; - MemRip.disp := disp; MemRip.chunk := chunk; -end; - -function MemIdx(base, index, scale: longint; disp: int64): TMem; -begin - MemIdx := Mem(base, disp); - MemIdx.index := index; - MemIdx.scale := scale; -end; - -{ The address of the code about to be written, as an operand } -function Here: TMem; -begin - Here := MemRip(curChunk, pc - chunks^[curChunk].start); -end; - -{ Encoding. An instruction is: a legacy prefix, REX, the opcode, ModRM, - SIB and displacement. Opcodes of more than one byte are given with - their first byte in the low eight bits. } - -procedure Opcode(op: longint); -begin - repeat - Put1(op and $FF); - op := op shr 8; - until op = 0; -end; - -{ The legacy prefix pfx, if any, and REX: wide is REX.W; byte4 says - a byte register of 4 to 7 is used, spl to dil, which exist only with - a REX prefix. } -procedure Prefix(pfx: longint; w: boolean; reg, index, base: longint; byte4: boolean); -var rex: longint; -begin - if pfx <> 0 then Put1(pfx); - rex := 0; - if w then rex := rex or 8; - if reg >= 8 then rex := rex or 4; - if index >= 8 then rex := rex or 2; - if base >= 8 then rex := rex or 1; - if (rex <> 0) or byte4 then Put1($40 or rex); -end; - -{ op reg, [mem] } -procedure OpM(pfx: longint; w: boolean; op, reg: longint; const m: TMem; byteReg: boolean = false); -var md, b, sc: longint; -begin - byteReg := byteReg and (reg >= 4) and (reg <= 7); - if m.base = RIP then Prefix(pfx, w, reg, NoIndex, 0, byteReg) - else Prefix(pfx, w, reg, m.index, m.base, byteReg); - Opcode(op); - reg := reg and 7; - if m.base = RIP then begin - Put1(reg shl 3 or 5); - { mod 00 with r/m 101 is rip + disp32. The displacement counts - from the end of the instruction, and the fixup takes it to end - with these four bytes: an instruction with an immediate after - them, AluMI's or StoreI's, takes the immediate's size off disp - first (the assembler can't name a chunk). } - AddFixup(pc, m.chunk, m.disp); - Put4(0); - exit; - end; - b := m.base and 7; - { mod 00 takes no displacement, but with r/m 101 (RBP or R13) it means - rip-relative, or disp32 under a SIB byte, so those bases take a - zero disp8 } - if (m.disp = 0) and (b <> RBP) then md := 0 - else if (m.disp >= -128) and (m.disp <= 127) then md := 1 - else md := 2; - { r/m 100 (RSP or R12) means a SIB byte follows, so those bases need - one, with index 100 meaning none } - if (m.index <> NoIndex) or (b = RSP) then begin - Put1(md shl 6 or reg shl 3 or 4); - case m.scale of 1: sc := 0; 2: sc := 1; 4: sc := 2; else sc := 3; end; - if m.index = NoIndex then Put1(sc shl 6 or 4 shl 3 or b) - else Put1(sc shl 6 or (m.index and 7) shl 3 or b); - end else - Put1(md shl 6 or reg shl 3 or b); - if md = 1 then Put1(m.disp) - else if md = 2 then Put4(m.disp); -end; - -{ op reg, rm (both registers) } -procedure OpR(pfx: longint; w: boolean; op, reg, rm: longint; byteReg: boolean = false); -begin - Prefix(pfx, w, reg, NoIndex, rm, byteReg and ((reg in [4..7]) or (rm in [4..7]))); - Opcode(op); - Put1($C0 or (reg and 7) shl 3 or (rm and 7)); -end; - -{ The listing: the text of each instruction, as it is made } - -type - TSaid = record - at: longint; { where the instruction starts in code } - text: string[63]; - end; - -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 - if not listing then exit; - if numSaid = saidCap then begin - saidCap := saidCap * 2 + 1024; - said := ReAllocMem(said, saidCap * SizeOf(TSaid)); - end; - said[numSaid].at := at; - said[numSaid].text := s; - inc(numSaid); -end; - -{ The text of the instruction about to be written } -procedure Say(const s: shortstring); -begin - SayAt(pc, s); -end; - -{ The text of the instruction at at, said again, as when its operand is - patched } -procedure Restate(at: longint; const s: shortstring); -var i: longint; -begin - i := numSaid - 1; - while (i >= 0) and (said[i].at <> at) do dec(i); - if i >= 0 then said[i].text := s; -end; - -function RN(r: longint; size: longint = 8): shortstring; -begin - case size of - 1: RN := RegNames[3, r]; - 2: RN := RegNames[2, r]; - 4: RN := RegNames[1, r]; - else RN := RegNames[0, r]; - end; -end; - -function XN(x: longint): shortstring; -begin - XN := 'xmm' + IntStr(x); -end; - -{ A memory operand, with the size of what it holds, as the assembler - reads it } -function MN(const m: TMem; size: longint = 0): shortstring; -var s: shortstring; -begin - case size of - 1: s := 'byte '; - 2: s := 'word '; - 4: s := 'dword '; - 8: s := 'qword '; - else s := ''; - end; - if m.base = RIP then s := s + '[' + ChunkName(m.chunk) - else s := s + '[' + RN(m.base); - if m.index <> NoIndex then s := s + ' + ' + RN(m.index) + ' * ' + IntStr(m.scale); - if m.disp > 0 then s := s + ' + ' + IntStr(m.disp) - else if m.disp < 0 then s := s + ' - ' + IntStr(-m.disp); - MN := s + ']'; -end; - -const - AluNames: array[0..7] of string[3] = ('add', 'or', 'adc', 'sbb', 'and', 'sub', 'xor', 'cmp'); - ShiftNames: array[0..7] of string[3] = ('rol', 'ror', 'rcl', 'rcr', 'shl', 'shr', 'sal', 'sar'); - UnaryNames: array[2..7] of string[4] = ('not', 'neg', 'mul', 'imul', 'div', 'idiv'); - -procedure MovRR(dst, src: longint); -begin - if listing then Say('mov ' + RN(dst) + ', ' + RN(src)); - OpR(0, true, $89, src, dst); -end; - -{ The immediate of n bytes that ends an instruction } -procedure PutImm(v, n: longint); -begin - if n = 4 then Put4(v) - else begin - Put1(v and $FF); - if n = 2 then Put1((v shr 8) and $FF); - end; -end; - -{ op [m], v, on size bytes; v fits in them, or in 32 bits for 8 } -procedure AluMI(op: longint; m: TMem; v, size: longint); -var n: longint; -begin - if listing then Say(AluNames[op] + ' ' + MN(m, size) + ', ' + IntStr(v)); - if (size = 1) or (v >= -128) and (v <= 127) then n := 1 - else if size = 2 then n := 2 - else n := 4; - if m.base = RIP then dec(m.disp, n); - if size = 1 then OpM(0, false, $80, op, m) - else if n = 1 then OpM(ord(size = 2) * $66, size = 8, $83, op, m) - else OpM(ord(size = 2) * $66, size = 8, $81, op, m); - PutImm(v, n); -end; - -{ mov [m], v, of size bytes; v fits in them, or in 32 bits for 8 } -procedure StoreI(m: TMem; v, size: longint); -var n: longint; -begin - if listing then Say('mov ' + MN(m, size) + ', ' + IntStr(v)); - n := size; - if n > 4 then n := 4; - if m.base = RIP then dec(m.disp, n); - if size = 1 then OpM(0, false, $C6, 0, m) - else OpM(ord(size = 2) * $66, size = 8, $C7, 0, m); - PutImm(v, n); -end; - -procedure MovRI(r: longint; v: int64); -begin - if not listing then - else if v = 0 then Say('xor ' + RN(r, 4) + ', ' + RN(r, 4)) - else Say('mov ' + RN(r) + ', ' + IntStr(v)); - if (v >= low(longint)) and (v <= high(longint)) then begin - if v = 0 then OpR(0, false, $31, r, r) { xor r32, r32 } - else if v > 0 then begin { mov r32, imm32 } - Prefix(0, false, 0, NoIndex, r, false); Put1($B8 + r and 7); Put4(v) - end else begin - OpR(0, true, $C7, 0, r); Put4(v) { sign-extended imm32 } - end; - end else if (v > 0) and (v <= $FFFFFFFF) then begin - Prefix(0, false, 0, NoIndex, r, false); Put1($B8 + r and 7); Put4(longint(v)) - end else begin - Prefix(0, true, 0, NoIndex, r, false); Put1($B8 + r and 7); Put8(v) - end; -end; - -procedure Load(r: longint; const m: TMem; size: longint; signed: boolean); -begin - if not listing then - else if size = 8 then Say('mov ' + RN(r) + ', ' + MN(m)) - else if (size = 4) and not signed then Say('mov ' + RN(r, 4) + ', ' + MN(m)) - else if size = 4 then Say('movsxd ' + RN(r) + ', ' + MN(m, 4)) - else if signed then Say('movsx ' + RN(r) + ', ' + MN(m, size)) - else Say('movzx ' + RN(r, 4) + ', ' + MN(m, size)); - case size of - 1: if signed then OpM(0, true, $BE0F, r, m) else OpM(0, false, $B60F, r, m); - 2: if signed then OpM(0, true, $BF0F, r, m) else OpM(0, false, $B70F, r, m); - 4: if signed then OpM(0, true, $63, r, m) else OpM(0, false, $8B, r, m); - else OpM(0, true, $8B, r, m); - end; -end; - -procedure Store(const m: TMem; r: longint; size: longint); -begin - if listing then Say('mov ' + MN(m) + ', ' + RN(r, size)); - case size of - 1: OpM(0, false, $88, r, m, true); - 2: OpM($66, false, $89, r, m); - 4: OpM(0, false, $89, r, m); - else OpM(0, true, $89, r, m); - end; -end; - -procedure Lea(r: longint; const m: TMem); -begin - if listing then Say('lea ' + RN(r) + ', ' + MN(m)); - OpM(0, true, $8D, r, m); -end; - -procedure Alu(op, dst, src: longint); -begin - if listing then Say(AluNames[op] + ' ' + RN(dst) + ', ' + RN(src)); - OpR(0, true, op shl 3 or 1, src, dst); -end; - -procedure AluI(op, r: longint; v: longint); -begin - if listing then Say(AluNames[op] + ' ' + RN(r) + ', ' + IntStr(v)); - if (v >= -128) and (v <= 127) then begin - OpR(0, true, $83, op, r); Put1(v) - end else begin - OpR(0, true, $81, op, r); Put4(v) - end; -end; - -{ op r, [m] } -procedure AluM(op, r: longint; const m: TMem); -begin - if listing then Say(AluNames[op] + ' ' + RN(r) + ', ' + MN(m)); - OpM(0, true, op shl 3 or 3, r, m); -end; - -procedure Imul(dst, src: longint); -begin - if listing then Say('imul ' + RN(dst) + ', ' + RN(src)); - OpR(0, true, $AF0F, dst, src); -end; - -procedure ImulI(r: longint; v: longint); -begin - if listing then Say('imul ' + RN(r) + ', ' + RN(r) + ', ' + IntStr(v)); - OpR(0, true, $69, r, r); - Put4(v); -end; - -procedure Shift(op, r: longint); -begin - if listing then Say(ShiftNames[op] + ' ' + RN(r) + ', cl'); - OpR(0, true, $D3, op, r); -end; - -procedure ShiftI(op, r, n: longint); -begin - if listing then Say(ShiftNames[op] + ' ' + RN(r) + ', ' + IntStr(n)); - OpR(0, true, $C1, op, r); - Put1(n); -end; - -procedure Unary(ext, r: longint); -begin - if listing then Say(UnaryNames[ext] + ' ' + RN(r)); - OpR(0, true, $F7, ext, r); -end; - -procedure Cqo; -begin - if listing then Say('cqo'); - Put1($48); Put1($99); -end; - -{ Brings a value of size bytes in r to 64 bits, by its sign or zeros. } -procedure Extend(r, size: longint; signed: boolean); -begin - if not listing then - else if size = 4 then begin - if signed then Say('movsxd ' + RN(r) + ', ' + RN(r, 4)) else Say('mov ' + RN(r, 4) + ', ' + RN(r, 4)) - end else if signed then Say('movsx ' + RN(r) + ', ' + RN(r, size)) - else Say('movzx ' + RN(r, 4) + ', ' + RN(r, size)); - case size of - 1: if signed then OpR(0, true, $BE0F, r, r, true) else OpR(0, false, $B60F, r, r, true); - 2: if signed then OpR(0, true, $BF0F, r, r) else OpR(0, false, $B70F, r, r); - 4: if signed then OpR(0, true, $63, r, r) else OpR(0, false, $89, r, r); - end; -end; - -{ r := 1 if the condition holds, else 0 } -procedure SetCC(cc, r: longint); -begin - if listing then Say('set' + CondNames[cc] + ' ' + RN(r, 1)); - OpR(0, false, $900F + cc shl 8, 0, r, true); - if listing then Say('movzx ' + RN(r, 4) + ', ' + RN(r, 1)); - OpR(0, false, $B60F, r, r, true); -end; - -procedure TestRR(a, b: longint); -begin - if listing then Say('test ' + RN(a) + ', ' + RN(b)); - OpR(0, true, $85, b, a); -end; - -procedure Push(r: longint); -begin - if listing then Say('push ' + RN(r)); - if r >= 8 then Put1($41); - Put1($50 + r and 7); -end; - -procedure Pop(r: longint); -begin - if listing then Say('pop ' + RN(r)); - if r >= 8 then Put1($41); - Put1($58 + r and 7); -end; - -procedure CallChunk(c: longint); -begin - if listing then Say('call ' + ChunkName(c)); - Put1($E8); - AddFixup(pc, c, 0); - Put4(0); -end; - -procedure CallBack(target: longint); -begin - if listing then Say('call'); - Put1($E8); - Put4(target - (pc + 4)); -end; - -procedure CallR(r: longint); -begin - if listing then Say('call ' + RN(r)); - OpR(0, false, $FF, 2, r); -end; - -procedure JmpR(r: longint); -begin - if listing then Say('jmp ' + RN(r)); - OpR(0, false, $FF, 4, r); -end; - -procedure CallM(const m: TMem); -begin - if listing then Say('call ' + MN(m)); - OpM(0, false, $FF, 2, m); -end; - -procedure Ret; begin if listing then Say('ret'); Put1($C3) end; -procedure Leave; begin Say('leave'); Put1($C9) end; -procedure Syscall; begin Say('syscall'); Put1($0F); Put1($05) end; -procedure Mfence; begin Say('mfence'); Put1($0F); Put1($AE); Put1($F0) end; -procedure Ud2; begin Say('ud2'); Put1($0F); Put1($0B) end; - -{ Code made up to a multiple of n bytes with no-ops, the fewest: the - long forms of nop, of up to 8 bytes, that x86 decodes as one } -procedure Align(n: longint); -const - Nops: array[1..8] of string[8] = (#$90, #$66#$90, #$0F#$1F#$00, #$0F#$1F#$40#$00, - #$0F#$1F#$44#$00#$00, #$66#$0F#$1F#$44#$00#$00, #$0F#$1F#$80#$00#$00#$00#$00, - #$0F#$1F#$84#$00#$00#$00#$00#$00); -var k, i: longint; -begin - while pc mod n <> 0 do begin - k := n - pc mod n; - if k > 8 then k := 8; - Say('nop'); - for i := 1 to k do Put1(ord(Nops[k][i])); - end; -end; -procedure RepMovsb; begin Say('rep movsb'); Put1($F3); Put1($A4) end; -{ the direction flag, which has rep movsb go down, and back up } -procedure Std; begin Say('std'); Put1($FD) end; -procedure Cld; begin Say('cld'); Put1($FC) end; -procedure RepStosb; begin Say('rep stosb'); Put1($F3); Put1($AA) end; -procedure RepeCmpsb; begin Say('repe cmpsb'); Put1($F3); Put1($A6) end; - -procedure LockCmpxchg(const m: TMem; r: longint); -begin - if listing then Say('lock cmpxchg ' + MN(m) + ', ' + RN(r)); - Put1($F0); - OpM(0, true, $B10F, r, m); -end; - -procedure Xchg(const m: TMem; r: longint); -begin - if listing then Say('xchg ' + MN(m) + ', ' + RN(r)); - OpM(0, true, $87, r, m); -end; - -procedure LockXadd(const m: TMem; r: longint); -begin - if listing then Say('lock xadd ' + MN(m) + ', ' + RN(r)); - Put1($F0); - OpM(0, true, $C10F, r, m); -end; - -procedure MovqXR(x, r: longint); -begin - if listing then Say('movq ' + XN(x) + ', ' + RN(r)); - OpR($66, true, $6E0F, x, r); -end; - -procedure MovqRX(r, x: longint); -begin - if listing then Say('movq ' + RN(r) + ', ' + XN(x)); - OpR($66, true, $7E0F, x, r); -end; - -{ movaps: all of xmm y to xmm x, the shortest move between two } -procedure MovX(x, y: longint); -begin - if listing then Say('movaps ' + XN(x) + ', ' + XN(y)); - OpR(0, false, $280F, x, y); -end; - -const - RealPfx: array[boolean] of longint = ($F2, $F3); - RealEnd: array[boolean] of string[2] = ('sd', 'ss'); - -procedure MovsXM(x: longint; const m: TMem; single: boolean); -begin - if listing then Say('movs' + RealEnd[single][2] + ' ' + XN(x) + ', ' + MN(m)); - OpM(RealPfx[single], false, $100F, x, m); -end; - -procedure MovsMX(const m: TMem; x: longint; single: boolean); -begin - if listing then Say('movs' + RealEnd[single][2] + ' ' + MN(m) + ', ' + XN(x)); - OpM(RealPfx[single], false, $110F, x, m); -end; - -function SseName(op: longint; single: boolean): shortstring; -begin - case op of - $58: SseName := 'add' + RealEnd[single]; - $59: SseName := 'mul' + RealEnd[single]; - $5C: SseName := 'sub' + RealEnd[single]; - $5E: SseName := 'div' + RealEnd[single]; - else SseName := 'cvt' + RealEnd[single] + '2' + RealEnd[not single]; - end; -end; - -procedure Sse(op, x, y: longint; single: boolean); -begin - if listing then Say(SseName(op, single) + ' ' + XN(x) + ', ' + XN(y)); - OpR(RealPfx[single], false, $0F or op shl 8, x, y); -end; - -{ The same, its right operand in memory: addsd x, [m] } -procedure SseM(op, x: longint; const m: TMem; single: boolean); -begin - if listing then Say(SseName(op, single) + ' ' + XN(x) + ', ' + MN(m)); - OpM(RealPfx[single], false, $0F or op shl 8, x, m); -end; - -procedure Ucomis(x, y: longint; single: boolean); -begin - if listing then Say('ucomi' + RealEnd[single] + ' ' + XN(x) + ', ' + XN(y)); - if single then OpR(0, false, $2E0F, x, y) else OpR($66, false, $2E0F, x, y); -end; - -procedure Cvtsi2s(x, r: longint; single: boolean); -begin - if listing then Say('cvtsi2' + RealEnd[single] + ' ' + XN(x) + ', ' + RN(r)); - OpR(RealPfx[single], true, $2A0F, x, r); -end; - -procedure Cvtts2si(r, x: longint; single: boolean); -begin - if listing then Say('cvtt' + RealEnd[single] + '2si ' + RN(r) + ', ' + XN(x)); - OpR(RealPfx[single], true, $2C0F, r, x); -end; - -procedure Btc(r, bit: longint); -begin - if listing then Say('btc ' + RN(r) + ', ' + IntStr(bit)); - OpR(0, true, $BA0F, 7, r); - Put1(bit); -end; - -{ Jumps. A label not yet placed is the chain of the jumps to it, each - rel32 field holding the position of the one before, NoLabel ending - it. Placing the label walks the chain and patches each. } - -procedure Jmp(var L: longint); -begin - if listing then Say('jmp'); - Put1($E9); - Put4(L); - L := pc - 4; -end; - -procedure Jcc(cc: longint; var L: longint); -begin - if listing then Say('j' + CondNames[cc]); - Put1($0F); Put1($80 + cc); - Put4(L); - L := pc - 4; -end; - -procedure JmpBack(target: longint); -begin - if listing then Say('jmp'); - Put1($E9); - Put4(target - (pc + 4)); -end; - -procedure JccBack(cc, target: longint); -begin - if listing then Say('j' + CondNames[cc]); - Put1($0F); Put1($80 + cc); - Put4(target - (pc + 4)); -end; - -procedure FixLinkTo(L, target: longint); -var next: longint; -begin - while L <> NoLabel do begin - next := Get4At(L); - Put4At(L, target - (L + 4)); - L := next; - end; -end; - -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. L is the place of the latest - jump's 4-byte field, so the last instruction is that jump when L is - 4 bytes back and an E9 byte (jmp) is before it; a jcc's field follows - the bytes 0F 8x, never E9. L then becomes the next jump on the chain, - which the field held. The caller must place L next, before anything - can have noted where the jmp ended. } -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 - the next one's place until it is fixed, the last NoLabel } -function JoinLinks(L1, L2: longint): longint; -var L: longint; -begin - if L2 = NoLabel then exit(L1); - if L1 <> NoLabel then begin - L := L2; - while Get4At(L) <> NoLabel do L := Get4At(L); - Put4At(L, L1); - end; - JoinLinks := L2; -end; - - -{ The assembler, for code procedures: x86-64 in Intel's syntax as NASM - writes it (report, appendix A). It reads instructions with the - scanner up to end, and encodes them with OpM and OpR; constants are - read by the parser's constExpr. } - -const - NoBase = -3; { a memory operand's base, not yet read } - -type - TOpKind = (oReg, oXmm, oMem, oImm); - TOpd = record - kind: TOpKind; - r, size: longint; { oReg, oXmm: the register and its size; oMem: its size, or 0 } - m: TMem; - v: int64; { oImm } - end; - -{ The current symbol as a word: an identifier, or a reserved word that - is also an instruction } -function AsmWord: shortstring; -begin - case tok of - sIdent: AsmWord := NameOf(id); - sAnd: AsmWord := 'and'; - sOr: AsmWord := 'or'; - sXor: AsmWord := 'xor'; - sNot: AsmWord := 'not'; - sDiv: AsmWord := 'div'; - sShl: AsmWord := 'shl'; - sShr: AsmWord := 'shr'; - else AsmWord := ''; - end; -end; - -{ Whether w names a register: rax, eax, ax, al and so on, or xmm0 to - xmm15 (size 16) } -function IsReg(const w: shortstring; var r, size: longint): boolean; -const Sizes: array[0..3] of longint = (8, 4, 2, 1); -var i, j, e: longint; -begin - IsReg := true; - for i := 0 to 3 do - for j := 0 to 15 do - if RegNames[i, j] = w then begin r := j; size := Sizes[i]; exit end; - size := 16; - Val(copy(w, 4, 2), r, e); - IsReg := (copy(w, 1, 3) = 'xmm') and (length(w) > 3) and (e = 0) and (r in [0..15]); -end; - -{ Which word of list, a list of words each with a space either side, - w is, from 0; -1 if none } -function WordIndex(const w, list: shortstring): longint; -var i, k: longint; -begin - k := pos(' ' + w + ' ', list); - WordIndex := -1; - if k = 0 then exit; - WordIndex := 0; - for i := 2 to k do if list[i] = ' ' then inc(WordIndex); -end; - -{ The condition a name ends in: e of je, nz of jnz } -function Cond(const w: shortstring): longint; -const - Alias: array[0..11] of string[3] = ('c', 'nae', 'nc', 'nb', 'z', 'nz', 'na', 'nbe', 'nge', 'nl', 'ng', 'nle'); - AliasCc: array[0..11] of longint = (2, 2, 3, 3, 4, 5, 6, 7, 12, 13, 14, 15); -var i: longint; -begin - for i := 0 to 15 do if CondNames[i] = w then exit(i); - for i := 0 to 11 do if Alias[i] = w then exit(AliasCc[i]); - Cond := -1; -end; - -procedure Operand(var o: TOpd; constExpr: TConstFn); -var w: shortstring; r, size, sz: longint; st: TScanState; -begin - FillChar(o, SizeOf(o), 0); - w := AsmWord; - sz := 0; - if w = 'byte' then sz := 1 else if w = 'word' then sz := 2 - else if w = 'dword' then sz := 4 else if w = 'qword' then sz := 8; - if sz <> 0 then begin Next; w := AsmWord end; - if tok = sLbrak then begin - { [base + index * scale + disp], the displacement last } - Next; - o.kind := oMem; o.size := sz; - o.m := Mem(NoBase, 0); - repeat - if IsReg(AsmWord, r, size) and (size = 8) then begin - Next; - { the scale is a single number or constant: a whole expression - would take in the displacement after it, as 4 + 16 in - [rdi + rsi * 4 + 16] } - if tok = sTimes then begin - Next; - o.m.index := r; - o.m.scale := constExpr(false); - end - else if o.m.base = NoBase then o.m.base := r - else begin o.m.index := r; o.m.scale := 1 end; - end else o.m.disp := o.m.disp + constExpr(true); - if not (tok in [sPlus, sMinus]) then break; - SaveScan(st); - Next; - if not IsReg(AsmWord, r, size) and (st.tok = sMinus) then RestoreScan(st); - until false; - if (tok <> sRbrak) or (o.m.base = NoBase) or not (o.m.scale in [1, 2, 4, 8]) then - Mark('expected a memory operand, [base + index * scale + disp]'); - Next; - end else if IsReg(w, o.r, o.size) then begin - if o.size = 16 then o.kind := oXmm else o.kind := oReg; - Next; - end else begin - o.kind := oImm; - o.v := constExpr(true); - end; -end; - -{ op with register reg and the register or memory operand o } -procedure RM(pfx: longint; w: boolean; op, reg: longint; const o: TOpd; byteReg: boolean = false); -begin - if o.kind = oMem then OpM(pfx, w, op, reg, o.m, byteReg) - else OpR(pfx, w, op, reg, o.r, byteReg); -end; - -procedure PutImm(v: int64; size: longint); -begin - case size of - 1: Put1(v); - 2: begin Put1(v); Put1(v shr 8) end; - else Put4(v); - end; -end; - -procedure Assemble(constExpr: TConstFn); -const - Alus = ' add or adc sbb and sub xor cmp '; - Unaries = ' not neg mul imul div idiv '; - Shifts = ' rol ror rcl rcr shl shr sal sar '; - SseOps = ' sqrt add mul sub min div max '; - SseCodes: array[0..6] of longint = ($51, $58, $59, $5C, $5D, $5E, $5F); - { SSE2 integer instructions that work on 16 bytes at a time: 66 0F code, - xmm and xmm or memory (pshufd also takes a byte) } - PackedOps = ' punpcklbw punpcklwd pcmpeqb pshufd pand pandn por pxor paddb psubb '; - PackedCodes: array[0..9] of longint = ($60, $61, $74, $70, $DB, $DF, $EB, $EF, $FC, $F8); - { bit scans and counts: reg, reg or memory, with the prefix and code that tell them } - BitOps = ' bsf bsr tzcnt lzcnt popcnt '; - BitPfx: array[0..4] of longint = (0, 0, $F3, $F3, $F3); - BitCodes: array[0..4] of longint = ($BC0F, $BD0F, $BC0F, $BD0F, $B80F); - Plain: array[0..14] of string[7] = ('ret', 'leave', 'syscall', 'cpuid', 'rdtsc', - 'pause', 'nop', 'ud2', 'int3', 'hlt', 'cqo', 'cdq', 'mfence', 'lfence', 'sfence'); - PlainOp: array[0..14] of longint = ($C3, $C9, $050F, $A20F, $310F, - $90F3, $90, $0B0F, $CC, $F4, $9948, $99, $F0AE0F, $E8AE0F, $F8AE0F); -var - w: shortstring; o: array[0..2] of TOpd; n, i, k, size, pfx, cc: longint; - wide, byteOp, wasListing: boolean; at, start: TPos; v: int64; first: longint; - names, places, chains: array[0..63] of longint; numLabels: longint; - usedAt: array[0..63] of TPos; - - { the label called n, entered if new } - function Lab(n: longint): longint; - var i: longint; - begin - for i := 0 to numLabels - 1 do if names[i] = n then exit(i); - if numLabels > High(names) then Mark('more than 64 labels'); - names[numLabels] := n; places[numLabels] := -1; chains[numLabels] := NoLabel; - usedAt[numLabels] := TokPos; - Lab := numLabels; - inc(numLabels); - end; - - procedure Bad; - begin - MarkAt(at, 'can''t assemble ' + w + ' with these operands'); - end; - - { an instruction of two operands: a register or memory, and a - register (opcode toRM), the other way (fromRM), or an immediate - (opImm /digit, or none if opImm < 0) } - procedure Two(toRM, fromRM, opImm, digit: longint); - begin - if n <> 2 then Bad; - if o[1].kind = oImm then begin - if (o[0].kind = oImm) or (opImm < 0) then Bad; - if (opImm = $81) and not byteOp and (o[1].v >= -128) and (o[1].v <= 127) then begin - RM(pfx, wide, $83, digit, o[0]); { a byte, sign-extended } - Put1(o[1].v); - end else begin - RM(pfx, wide, opImm - ord(byteOp), digit, o[0]); - PutImm(o[1].v, size); - end; - end else if (o[1].kind = oReg) and (o[0].kind in [oReg, oMem]) then - RM(pfx, wide, toRM - ord(byteOp), o[1].r, o[0], byteOp) - else if (o[0].kind = oReg) and (o[1].kind = oMem) then - RM(pfx, wide, fromRM - ord(byteOp), o[0].r, o[1], byteOp) - else Bad; - end; - -begin - numLabels := 0; - while not (tok in [sEnd, sEof]) do begin - at := TokPos; - w := AsmWord; - if tok = sSemicolon then begin Next; continue end; - if w = '' then Mark('expected an instruction'); - Next; - if tok = sColon then begin - SayAt(pc, w + ':'); - k := Lab(Intern(@w[1], length(w))); - if places[k] >= 0 then MarkAt(at, 'label ' + w + ' is defined twice'); - places[k] := pc; - FixLink(chains[k]); - Next; - continue; - end; - first := pc; - wasListing := listing; - listing := false; { the instruction is said as it is written } - if w = 'lock' then begin - Put1($F0); - w := AsmWord; - Next; - end; - cc := -1; - if w = 'db' then - repeat - start := TokPos; - v := constExpr(true); - if (v < -128) or (v > 255) then MarkAt(SpanFrom(start), 'expected a byte from 0 to 255, found ' + IntStr(v)); - Put1(v); - if tok <> sComma then break; - Next; - until false - else if (w[1] = 'j') and ((w = 'jmp') or (Cond(copy(w, 2, 3)) >= 0)) and (tok = sIdent) then begin - { a jump to a label } - k := Lab(id); - Next; - if w <> 'jmp' then cc := Cond(copy(w, 2, 3)); - if places[k] >= 0 then begin - if cc < 0 then JmpBack(places[k]) else JccBack(cc, places[k]) - end else if cc < 0 then Jmp(chains[k]) else Jcc(cc, chains[k]); - end else begin - n := 0; - if tok <> sSemicolon then - repeat - if n > High(o) then Mark('too many operands'); - Operand(o[n], constExpr); - inc(n); - if tok <> sComma then break; - Next; - until false; - { the size: a register's, or what the memory operand says } - size := 8; - for i := n - 1 downto 0 do - if (o[i].kind = oReg) or (o[i].kind = oMem) and (o[i].size <> 0) then size := o[i].size; - if n > 0 then - if (o[0].kind = oReg) or (o[0].kind = oMem) and (o[0].size <> 0) then size := o[0].size; - wide := size = 8; - byteOp := size = 1; - if size = 2 then pfx := $66 else pfx := 0; - if WordIndex(w, Alus) >= 0 then begin - k := WordIndex(w, Alus); - Two(k * 8 + 1, k * 8 + 3, $81, k) - end - else if w = 'mov' then begin - if (n = 2) and (o[0].kind = oReg) and (o[1].kind = oImm) and (size >= 4) then begin - if wide then MovRI(o[0].r, o[1].v) - else begin Prefix(0, false, 0, NoIndex, o[0].r, false); Put1($B8 + o[0].r and 7); Put4(o[1].v) end; - end else Two($89, $8B, $C7, 0); - end else if w = 'test' then Two($85, $85, $F7, 0) - else if w = 'xchg' then Two($87, $87, -1, 0) - else if (w = 'cmpxchg') or (w = 'xadd') then begin - if (n <> 2) or (o[1].kind <> oReg) then Bad; - if w = 'xadd' then k := $C10F else k := $B10F; - RM(pfx, wide, k - ord(byteOp) shl 8, o[1].r, o[0], byteOp); - end else if w = 'lea' then begin - if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind <> oMem) then Bad; - RM(pfx, wide, $8D, o[0].r, o[1]); - end else if (w = 'movzx') or (w = 'movsx') or (w = 'movsxd') then begin - if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) then Bad; - if w = 'movsxd' then k := $63 - else if o[1].size = 1 then k := $B60F - else if o[1].size = 2 then k := $B70F - else Bad; - if w = 'movsx' then k := k + $0800; - RM(pfx, wide, k, o[0].r, o[1], o[1].size = 1); - end else if ((WordIndex(w, Unaries) >= 0) and (n = 1)) or (w = 'inc') or (w = 'dec') then begin - if o[0].kind = oImm then Bad; - if w = 'inc' then RM(pfx, wide, $FF - ord(byteOp), 0, o[0], byteOp) - else if w = 'dec' then RM(pfx, wide, $FF - ord(byteOp), 1, o[0], byteOp) - else RM(pfx, wide, $F7 - ord(byteOp), WordIndex(w, Unaries) + 2, o[0], byteOp); - end else if w = 'imul' then begin - if (n < 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) then Bad; - if n = 2 then RM(pfx, wide, $AF0F, o[0].r, o[1]) - else begin RM(pfx, wide, $69, o[0].r, o[1]); PutImm(o[2].v, size) end; - end else if WordIndex(w, Shifts) >= 0 then begin - k := WordIndex(w, Shifts); - if k = 6 then k := 4; { sal is shl } - if (n <> 2) or (o[0].kind = oImm) then Bad; - if o[1].kind = oImm then begin RM(pfx, wide, $C1 - ord(byteOp), k, o[0], byteOp); Put1(o[1].v) end - else if (o[1].kind = oReg) and (o[1].r = RCX) and (o[1].size = 1) then RM(pfx, wide, $D3 - ord(byteOp), k, o[0], byteOp) - else Bad; - end else if (w = 'push') or (w = 'pop') then begin - if (n <> 1) or (o[0].kind <> oReg) or not wide then Bad; - if w = 'push' then Push(o[0].r) else Pop(o[0].r); - end else if (w = 'call') or (w = 'jmp') then begin - if (n <> 1) or (o[0].kind = oImm) then Bad; - if w = 'call' then RM(0, false, $FF, 2, o[0]) else RM(0, false, $FF, 4, o[0]); - end else if (copy(w, 1, 3) = 'set') and (Cond(copy(w, 4, 3)) >= 0) then begin - if (n <> 1) or (o[0].kind = oImm) or (size <> 1) then Bad; - RM(0, false, $900F + Cond(copy(w, 4, 3)) shl 8, 0, o[0], true); - end else if (copy(w, 1, 4) = 'cmov') and (Cond(copy(w, 5, 3)) >= 0) then begin - if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) then Bad; - RM(pfx, wide, $400F + Cond(copy(w, 5, 3)) shl 8, o[0].r, o[1]); - end else if (length(w) > 2) and (WordIndex(copy(w, 1, length(w) - 2), SseOps) >= 0) - and ((copy(w, length(w) - 1, 2) = 'sd') or (copy(w, length(w) - 1, 2) = 'ss')) then begin - { sqrtsd, addss and the like: xmm, xmm or memory } - if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad; - k := $0F or SseCodes[WordIndex(copy(w, 1, length(w) - 2), SseOps)] shl 8; - RM(RealPfx[w[length(w)] = 's'], false, k, o[0].r, o[1]); - end else if WordIndex(w, PackedOps) >= 0 then begin - if (n < 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad; - k := WordIndex(w, PackedOps); - RM($66, false, $0F or PackedCodes[k] shl 8, o[0].r, o[1]); - if w = 'pshufd' then begin - if (n <> 3) or (o[2].kind <> oImm) then Bad; - Put1(o[2].v); - end else if n <> 2 then Bad; - end else if (w = 'movdqu') or (w = 'movdqa') then begin - { the load is 6F and the store 7F; movdqu is F3, movdqa 66 } - if w = 'movdqu' then k := $F3 else k := $66; - if (n = 2) and (o[0].kind = oXmm) and (o[1].kind in [oXmm, oMem]) then RM(k, false, $6F0F, o[0].r, o[1]) - else if (n = 2) and (o[0].kind = oMem) and (o[1].kind = oXmm) then RM(k, false, $7F0F, o[1].r, o[0]) - else Bad; - end else if w = 'pmovmskb' then begin - if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind <> oXmm) then Bad; - RM($66, false, $D70F, o[0].r, o[1]); - end else if WordIndex(w, BitOps) >= 0 then begin - if (n <> 2) or (o[0].kind <> oReg) or (o[1].kind = oImm) or (size < 4) then Bad; - k := WordIndex(w, BitOps); - RM(BitPfx[k], wide, BitCodes[k], o[0].r, o[1]); - end else if (w = 'movsd') or (w = 'movss') then begin - if w = 'movsd' then k := $F2 else k := $F3; - if (n = 2) and (o[0].kind = oXmm) and (o[1].kind in [oXmm, oMem]) then RM(k, false, $100F, o[0].r, o[1]) - else if (n = 2) and (o[0].kind = oMem) and (o[1].kind = oXmm) then RM(k, false, $110F, o[1].r, o[0]) - else Bad; - end else if (w = 'movq') or (w = 'movd') then begin - if (n = 2) and (o[0].kind = oXmm) and (o[1].kind in [oReg, oMem]) then RM($66, w = 'movq', $6E0F, o[0].r, o[1]) - else if (n = 2) and (o[1].kind = oXmm) and (o[0].kind in [oReg, oMem]) then RM($66, w = 'movq', $7E0F, o[1].r, o[0]) - else Bad; - end else if (w = 'ucomisd') or (w = 'ucomiss') then begin - if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad; - if w = 'ucomisd' then RM($66, false, $2E0F, o[0].r, o[1]) else RM(0, false, $2E0F, o[0].r, o[1]); - end else if (w = 'cvtsi2sd') or (w = 'cvtsi2ss') then begin - if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oReg, oMem]) then Bad; - RM(RealPfx[w = 'cvtsi2ss'], o[1].size <> 4, $2A0F, o[0].r, o[1]); - end else if (w = 'cvttsd2si') or (w = 'cvttss2si') then begin - if (n <> 2) or (o[0].kind <> oReg) or not (o[1].kind in [oXmm, oMem]) then Bad; - RM(RealPfx[w = 'cvttss2si'], wide, $2C0F, o[0].r, o[1]); - end else if (w = 'cvtsd2ss') or (w = 'cvtss2sd') then begin - if (n <> 2) or (o[0].kind <> oXmm) or not (o[1].kind in [oXmm, oMem]) then Bad; - RM(RealPfx[w = 'cvtss2sd'], false, $5A0F, o[0].r, o[1]); - end else begin - k := 0; - while (k <= High(Plain)) and (Plain[k] <> w) do inc(k); - if (k > High(Plain)) or (n <> 0) then MarkAt(at, 'unknown instruction ' + w); - Opcode(PlainOp[k]); - end; - end; - if tok <> sSemicolon then Mark('expected ";"'); - listing := wasListing; - SayAt(first, Source(SpanFrom(at))); - Next; - end; - for k := 0 to numLabels - 1 do - if places[k] < 0 then MarkAt(usedAt[k], 'label ' + NameOf(names[k]) + ' isn''t defined'); -end; - -{ The listing, raz -S: each live procedure of the module in the order - it was made, each line of source it comes from, and under it the - instructions made for it, at their offsets in the procedure; a jump - within it says where to by its offset too. } -procedure List(module: longint); -var order: ^longint; n, i, j, k, c, t, line: longint; text: shortstring; -begin - order := GetMem(numChunks * SizeOf(longint)); - n := 0; - for c := 0 to numChunks - 1 do - if chunks^[c].live and (chunks^[c].sec = secText) and (chunks^[c].module = module) then begin - i := n; - while (i > 0) and (chunks^[order[i - 1]].start > chunks^[c].start) do begin - order[i] := order[i - 1]; - dec(i); - end; - order[i] := c; - inc(n); - end; - i := 0; j := 0; - for k := 0 to n - 1 do begin - c := order[k]; - writeln; - writeln(ChunkName(c), ':'); - line := -1; - while (i < numSaid) and (said[i].at < chunks^[c].start) do inc(i); - while (i < numSaid) and (said[i].at < chunks^[c].start + chunks^[c].size) do begin - while (j < numLines) and (lines^[j].at <= said[i].at) do begin - if (lines^[j].chunk = c) and (lines^[j].line <> line) then begin - line := lines^[j].line; - writeln(line: 6, ' ', LineText(NameOf(lines^[j].path), line)); - end; - inc(j); - end; - text := said[i].text; - t := said[i].at; - if (text = 'jmp') or (text = 'call') then text := text + ' ' + IntStr(t + 5 + Get4At(t + 1) - chunks^[c].start) - else if (text[1] = 'j') and (pos(' ', text) = 0) then text := text + ' ' + IntStr(t + 6 + Get4At(t + 2) - chunks^[c].start); - writeln(t - chunks^[c].start: 14, ' ', text); - inc(i); - end; - end; - FreeMem(order); -end; - -end. diff --git a/src/bench.sh b/src/bench.sh index 5d211f3..385050d 100755 --- a/src/bench.sh +++ b/src/bench.sh @@ -1,35 +1,25 @@ #!/bin/sh -# The scanner's speed against the seed's, on the compiler's own -# benchmark program: the best of seven runs of each. Run from the -# repository root, after make raz. +# The compiler's speed against the previous release's, the one BOOT +# names (build/boot/raz), on the same generated program: the best of +# five runs of each, as build/cmp/raz, which finds the library beside +# it. A regression test: it fails if this compiler takes more than a +# tenth longer. Run from the repository root, after make raz. set -e -b=build/src -mkdir -p $b -python3 test/genbench.py 12000 >$b/Bench.raz -fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/scanbench.seed src/test/ScanBench.pas >/dev/null -./raz -Werror -I src -o $b/scanbench.src src/test/ScanBench.raz -echo "$(wc -l <$b/Bench.raz) lines" -for t in seed src; do - best=0 - for i in 1 2 3 4 5 6 7; do - s=$(date +%s%N); $b/scanbench.$t $b/Bench.raz >/dev/null; e=$(date +%s%N) - d=$(( (e - s) / 1000000 )); if [ $best = 0 ] || [ $d -lt $best ]; then best=$d; fi - done - echo "$t: $best ms" -done - -# The whole compiler's speed, the seed's and this one's, on the same -# program: the best of five runs of each, as build/cmp/raz, which finds -# the library beside it. mkdir -p build/cmp/bench ln -sfn ../../lib build/cmp/lib -cp $b/Bench.raz build/cmp/bench/Bench.raz -for t in seed src; do - if [ $t = seed ]; then cp build/seed/raz build/cmp/raz; else cp $b/raz.src build/cmp/raz; fi +python3 test/genbench.py 12000 >build/cmp/bench/Bench.raz +echo "$(wc -l /dev/null; then + id=$(gh api repos/$repo/releases/tags/$tag --jq ".assets[] | select(.name == \"$t\") | .id" 2>/dev/null) && + [ -n "$id" ] && + gh api -H 'Accept: application/octet-stream' repos/$repo/releases/assets/$id >$d/$t 2>/dev/null || + { rm -f $d/$t; echo "boot: can't fetch $t; put it in $d" >&2; exit 1; } + fi +fi +if ! echo "$sum $d/$t" | sha256sum -c --quiet - >/dev/null 2>&1; then + echo "boot: $d/$t isn't $tag's tarball: its SHA-256 isn't BOOT's" >&2 + exit 1 +fi +rm -rf $d/raz-$v-linux-x86_64 +tar -xzf $d/$t -C $d +cp $d/raz-$v-linux-x86_64/raz $d/raz +ln -sfn ../../lib $d/lib diff --git a/src/fixpoint.sh b/src/fixpoint.sh index 5375bc0..9677719 100755 --- a/src/fixpoint.sh +++ b/src/fixpoint.sh @@ -1,27 +1,28 @@ #!/bin/sh -# The fixpoint: the seed builds src/ (stage 1), that builds src/ -# (stage 2), that builds it again (stage 3), and stages 2 and 3 must -# be the same file. A program holds the paths it was made from, so each +# The fixpoint: the previous release, BOOT's, builds src/ (stage 1), +# that builds src/ (stage 2), that builds it again (stage 3), and +# stages 2 and 3 must be the same file. A program holds the paths it was made from, so each # stage is built by the same command in the same place, from the # compiler before it copied to build/fix/raz. Run from the repository # root, after `make raz`. Then stage 3 stands in for ./raz (messages name # the library by its path from the compiler, so it must be at the root) -# while `make check` and `make bench` run on it; the seed's comes back. +# while `make check` and `make bench` run on it; the one make built +# comes back. set -e d=build/fix rm -rf $d mkdir -p $d/v ln -s ../../lib $d/lib printf 'module Version;\nconst Text* = "%s";\nend Version.\n' "$(tr -d "'" < build/version.inc)" >$d/v/Version.raz -cp build/seed/raz $d/stage0 +cp build/boot/raz $d/stage0 for n in 1 2 3; do cp $d/stage$((n - 1)) $d/raz $d/raz -Werror -I src -I $d/v -o $d/stage$n src/Raz.raz done cmp $d/stage2 $d/stage3 echo "fixpoint: stages 2 and 3 are the same, $(wc -c <$d/stage3) bytes" -cp raz $d/seed -trap 'cp $d/seed raz' EXIT +cp raz $d/made +trap 'cp $d/made raz' EXIT cp $d/stage3 raz make check make bench diff --git a/src/test/ScanBench.pas b/src/test/ScanBench.pas deleted file mode 100644 index 75b0336..0000000 --- a/src/test/ScanBench.pas +++ /dev/null @@ -1,12 +0,0 @@ -{ Counts the symbols of a file and nothing else, for timing scan.pas - against src/Scan.raz (ScanBench.raz). } -program scanbench; -{$mode objfpc}{$H-} -uses diag, scan; -var n: longint; -begin - if Open(ParamStr(1)) <> '' then Fatal('no file'); - n := 0; - repeat Next; inc(n) until tok = sEof; - writeln(n, ' symbols'); -end. diff --git a/src/test/ScanBench.raz b/src/test/ScanBench.raz deleted file mode 100644 index a49e516..0000000 --- a/src/test/ScanBench.raz +++ /dev/null @@ -1,15 +0,0 @@ -(* Counts the symbols of a file and nothing else, for timing Scan.raz - against the seed's scan.pas (ScanBench.pas). *) -module ScanBench; -import Out, Files, Diag, Scan; - -proc main*; -var n: INT; -begin - if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end; - n := 0; - repeat Scan.next; INC(n); until Scan.tok = Scan.sEof; - Out.int(n); Out.str(" symbols\n"); -end; - -end ScanBench. diff --git a/test/enctest.pas b/test/enctest.pas deleted file mode 100644 index b1edf8d..0000000 --- a/test/enctest.pas +++ /dev/null @@ -1,37 +0,0 @@ -{ Emits one of each instruction form into a chunk, for objdump: a test - of the encoder in x64.pas. } -program enctest; -{$mode objfpc}{$H-} -uses scan, chunk, x64, link, elf; -var e, d: longint; L: longint; -begin - d := NewChunk(secBss, -1, Intern('data', 4)); SetBss(d, 8, 8); - e := NewChunk(secText, -1, Intern('start', 5)); - BeginChunk(e); - MovRR(RAX, RCX); MovRR(R11, RDI); MovRR(RSI, R9); - MovRI(RAX, 0); MovRI(RCX, 5); MovRI(RDX, -5); MovRI(R10, $FFFFFFFF); MovRI(RAX, $123456789A); - Load(RAX, Mem(RBP, -8), 8, true); Load(RAX, Mem(RBP, -200), 4, true); Load(RCX, Mem(RAX, 0), 4, false); - Load(RAX, Mem(RCX, 16), 2, true); Load(RAX, Mem(RAX, 3), 2, false); Load(RAX, Mem(RSP, 8), 1, true); - Load(RAX, Mem(RBP, 0), 1, false); Load(R10, Mem(12, 0), 8, true); Load(RAX, Mem(13, 0), 8, true); - Store(Mem(RBP, -16), RAX, 8); Store(Mem(RBP, -16), RSI, 1); Store(Mem(RCX, 0), RAX, 2); Store(Mem(RCX, 4), RDX, 4); - Store(MemIdx(RBP, R10, 8, 0), RAX, 8); Store(MemRip(d, 0), RAX, 8); Lea(RAX, MemRip(d, 4)); - Alu(aluAdd, RAX, RCX); Alu(aluSub, RCX, RAX); Alu(aluCmp, RAX, RCX); Alu(aluXor, R8, R9); - AluI(aluAdd, RAX, 1); AluI(aluAnd, RAX, 1000); AluI(aluCmp, RSP, 8); AluM(aluCmp, RAX, Mem(RCX, 8)); AluM(aluAdd, RAX, Mem(RCX, 0)); - Imul(RAX, RCX); ImulI(RAX, 24); Shift(shShl, RAX); Shift(shSar, RAX); ShiftI(shShr, RCX, 3); - Unary(2, RAX); Unary(3, RAX); Unary(6, RCX); Unary(7, RCX); Cqo; - Extend(RAX, 1, true); Extend(RAX, 1, false); Extend(RDI, 1, false); Extend(RSI, 1, true); Extend(RAX, 2, true); Extend(RAX, 2, false); Extend(RAX, 4, true); Extend(RAX, 4, false); - SetCC(ccL, RAX); SetCC(ccA, RCX); SetCC(ccE, RDI); TestRR(RAX, RAX); - Push(RAX); Push(12); Pop(RCX); Pop(R11); CallR(R11); CallM(Mem(RCX, 8)); Ret; Leave; Syscall; Mfence; Ud2; RepMovsb; RepStosb; - LockCmpxchg(Mem(RCX, 0), RDX); Xchg(Mem(RCX, 0), RAX); LockXadd(Mem(RCX, 0), RAX); - MovqXR(0, RAX); MovqXR(1, RCX); MovqRX(RAX, 0); MovsXM(2, Mem(RBP, -8), false); MovsMX(Mem(RBP, -8), 7, false); - MovX(9, 12); MovX(0, 8); MovsXM(8, MemIdx(R13, R9, 8, -8), true); MovsMX(Mem(RBP, -8), 11, true); - SseM($58, 9, MemIdx(R13, R10, 8, 4096), false); SseM($59, 0, Mem(RBP, -16), true); Sse($5C, 8, 11, false); - Sse($58, 0, 1, false); Sse($5E, 0, 1, true); Sse($5A, 0, 0, false); Sse($5A, 0, 0, true); - Ucomis(0, 1, false); Ucomis(0, 1, true); Cvtsi2s(0, RAX, false); Cvtsi2s(0, RAX, true); - Cvtts2si(RAX, 0, false); Cvtts2si(RAX, 0, true); Btc(RAX, 63); - L := NoLabel; Jcc(ccE, L); Jmp(L); FixLink(L); JmpBack(chunks^[e].start); JccBack(ccNE, chunks^[e].start); - Ret; Align(32); - EndChunk(e); - MarkLive(e); - WriteElf(ParamStr(1), e); -end. diff --git a/test/handtest.pas b/test/handtest.pas deleted file mode 100644 index 833d963..0000000 --- a/test/handtest.pas +++ /dev/null @@ -1,46 +0,0 @@ -{ Builds a program by hand, chunk by chunk, links it and writes it: - a test of x64.pas, link.pas and elf.pas. The program writes "hand" - from rodata, adds one to a bss variable through a call, and exits - with that variable plus 41: status 42. A chunk nothing reaches is - left out. } -program handtest; -{$mode objfpc}{$H-} -uses scan, chunk, x64, link, elf; -var entry, msg, count, bump, unused: longint; s: shortstring; -begin - s := 'hand'#10; - msg := NewChunk(secRodata, -1, Intern('msg', 3)); - SetData(msg, @s[1], length(s), 1); - count := NewChunk(secBss, -1, Intern('count', 5)); - SetBss(count, 8, 8); - bump := NewChunk(secText, -1, Intern('bump', 4)); - unused := NewChunk(secText, -1, Intern('unused', 6)); - entry := NewChunk(secText, -1, Intern('start', 5)); - - BeginChunk(bump); { count := count + 1 } - Load(RAX, MemRip(count, 0), 8, true); - AluI(aluAdd, RAX, 1); - Store(MemRip(count, 0), RAX, 8); - Ret; - EndChunk(bump); - - BeginChunk(unused); - Ud2; - EndChunk(unused); - - BeginChunk(entry); - MovRI(RAX, 1); { write(1, msg, 5) } - MovRI(RDI, 1); - Lea(RSI, MemRip(msg, 0)); - MovRI(RDX, length(s)); - Syscall; - CallChunk(bump); - Load(RDI, MemRip(count, 0), 8, true); - AluI(aluAdd, RDI, 41); - MovRI(RAX, 60); { exit(count + 41) } - Syscall; - EndChunk(entry); - - MarkLive(entry); - WriteElf(ParamStr(1), entry); -end. diff --git a/test/scantest.pas b/test/scantest.pas deleted file mode 100644 index bd228f0..0000000 --- a/test/scantest.pas +++ /dev/null @@ -1,19 +0,0 @@ -{ Prints the symbols of a file, one per line: a test of scan.pas. } -program scantest; -{$mode objfpc}{$H-} -uses diag, scan; -var i: longint; -begin - if Open(ParamStr(1)) <> '' then Fatal('no file'); - repeat - Next; - write(LineOf(TokPos), ':', TokPos.a, ' ', ord(tok)); - case tok of - sIdent: write(' ', NameOf(id)); - sInt, sChar: write(' ', ival); - sReal: write(' ', rval:0:6); - sString: begin write(' "'); for i := 0 to slen - 1 do write(sbuf[i], ','); write('"') end; - end; - writeln; - until tok = sEof; -end.