From 596c810a869276216bd222ece75c8df55949f991 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:44:08 +0100 Subject: [PATCH] src/ is the compiler in raz; the Pascal seed moves to seed/ git mv src seed, self src, and every path in the Makefile, scripts, tests and docs follows. The seed is frozen: it builds src/ the first time and is the reference src/'s units are tested against, until it is dropped. make check, make self and make fixpoint pass as before. --- diff --git a/CLAUDE.md b/CLAUDE.md index cbf96b2..0036ed0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -131,12 +131,14 @@ a link in its `mods`. A test or example without `.expect` is only compiled (`examples/Window.raz` needs a display). -## The seed and self +## The compiler and the seed -`src/`, the Free Pascal compiler, is the **seed**. `self/` is its port -to raz (`PLAN.md`, "Self"): one module to a seed unit, the same names. -Never edit the seed to suit the port; a difference found goes on the -plan, for the owner. +`src/` is the compiler, in raz (`PLAN.md`, "Self"): one module to a +seed unit, the same names. `seed/`, the Free Pascal compiler it was +ported from, is the **seed**: frozen at its last version, kept to build +`src/` the first time and as the reference its units are tested +against, and to be dropped in time. Never edit the seed; a difference +found goes on the plan, for the owner. ## Readings of the report already taken diff --git a/Makefile b/Makefile index 213c4be..67d1b50 100644 --- a/Makefile +++ b/Makefile @@ -1,11 +1,11 @@ -# Builds the compiler, raz, from src/ into the repository's root; the +# Builds the compiler, raz, from seed/ into the repository's root; the # library it needs is lib/, beside it. FPC = fpc FPCFLAGS = -O2 -Mobjfpc -Sh- -vew -FUbuild -raz: src/*.pas build/version.inc | build - $(FPC) $(FPCFLAGS) -Fibuild -FE. -oraz src/raz.pas +raz: seed/*.pas build/version.inc | build + $(FPC) $(FPCFLAGS) -Fibuild -FE. -oraz seed/raz.pas # The version is git's name for the commit; the file changes only when # that does, so raz isn't rebuilt for nothing. @@ -15,14 +15,14 @@ FORCE: -units: src/*.pas | build - for u in diag scan sym chunk x64 link elf; do $(FPC) $(FPCFLAGS) src/$$u.pas || exit 1; done +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) -Fusrc -obuild/scantest test/scantest.pas - $(FPC) $(FPCFLAGS) -Fusrc -obuild/enctest test/enctest.pas - $(FPC) $(FPCFLAGS) -Fusrc -obuild/handtest test/handtest.pas + $(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: @@ -35,17 +35,17 @@ check: raz build/raz-lib.3 test/check.sh -# the raz compiler in raz, self/, tested against the seed's units +# the raz compiler in raz, src/, tested against the seed's units self: raz | build - self/check.sh + src/check.sh self-bench: raz | build - self/bench.sh + src/bench.sh -# the seed builds self/, that builds self/, that builds it again: the +# 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 fixpoint: raz | build - self/fixpoint.sh + src/fixpoint.sh # line numbers: gdb stops at a line and names it gdb: raz @@ -81,15 +81,15 @@ # formatted already fmt: raz | build ./raz -o build/Pretty tools/Pretty.raz - @fail=0; for f in lib/*.raz examples/*.raz tools/*.raz self/*.raz self/test/*.raz; do \ + @fail=0; for f in lib/*.raz examples/*.raz tools/*.raz src/*.raz src/test/*.raz; do \ build/Pretty $$f | cmp -s - $$f || { echo "not formatted: $$f"; fail=1; }; \ done; test $$fail = 0 # lines of the compiler, by rloc: each file's blank, comment and code, # then the lines of code in all loc: - @rloc -f src/*.pas - @rloc -c src/*.pas + @rloc -f seed/*.pas + @rloc -c seed/*.pas # raz-lib(3), the library's manual page, made by tools/Doc.raz from # its sources, in the order of the report's section 11 diff --git a/PLAN.md b/PLAN.md index 5d385b7..3124a2a 100644 --- a/PLAN.md +++ b/PLAN.md @@ -12,10 +12,10 @@ ## Self: the compiler in raz (under way) For: a compiler written in raz that compiles itself, so that raz needs -no Free Pascal. The Pascal compiler in `src/` is the **seed**: it is +no Free Pascal. The Pascal compiler in `seed/` is the **seed**: it is never edited for this, and stays the one `make check` builds. The new -compiler lives in `self/`, one raz module to a seed unit, the same -names, and has its own targets; nothing in `src/` or `lib/` changes. +compiler lives in `src/`, one raz module to a seed unit, the same +names, and has its own targets; nothing in `seed/` or `lib/` changes. The language gained `try` (report 2026-10.20) for this: the parser's errors return an `ERROR` (`Scan.Failed`) that `try` passes up to where @@ -39,13 +39,13 @@ builds, tested by compiling 409 programs, the library and the compiler itself with both and comparing the executables, messages and status; 452,000 lines a second, the seed's 815,000. -5. Fixpoint (done: `self/fixpoint.sh`, `make fixpoint`): the seed builds `self`, that builds `self`, that builds - `self` again, and the last two are byte for byte the same (all +5. Fixpoint (done: `src/fixpoint.sh`, `make fixpoint`): the seed builds `src`, that builds `src`, that builds + `src` again, and the last two are byte for byte the same (all three are, 547,000 bytes: the seed and this compiler make the same - code from `self/`). `make check` passes on the compiler it made, + code from `src/`). `make check` passes on the compiler it made, 661 tests, and `make bench` gives 493,000 to 870,000 lines a second. - Then the seed's last tag is the bootstrap, and the split of `src/` from - the rest is the owner's to decide. + Then `seed/` is frozen and `self/` is `src/` (the owner's word, + 2026-10-13); the seed is dropped in time, its last tag the bootstrap. Done when step 5 passes with `make check` and `make bench` on the compiler it made, and the budget of lines kept. diff --git a/README.md b/README.md index a646945..5bd9f45 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,8 @@ | `doc/raz.md` | The language report: the definition of raz | | `doc/compiler.md` | A guide to reading the compiler, file by file | | `doc/raz.1`, `doc/raz.7`, `doc/raz-tutorial.7` | The manual pages: the command, the language at a glance, a tour; `make man` makes the library's, raz-lib(3), from `lib/` | -| `src/` | The compiler, in Free Pascal | +| `src/` | The compiler, in raz | +| `seed/` | The first compiler, in Free Pascal: frozen, it builds `src/` the first time | | `lib/` | The library, in raz; the compiler finds it beside itself | | `examples/` | Small programs, each with the output it should give | | `tools/Doc.raz` | Prints what a module exports, with its comments | diff --git a/doc/book/PLAN.md b/doc/book/PLAN.md index ea6c683..96f7006 100644 --- a/doc/book/PLAN.md +++ b/doc/book/PLAN.md @@ -8,7 +8,7 @@ ## Read first - CLAUDE.md, doc/raz.md (the report), doc/compiler.md, README.md. -- src/*.pas, the whole compiler (about 5,000 lines), and enough of lib/ +- seed/*.pas, the whole compiler (about 5,000 lines), and enough of lib/ (Rt, Heap, Mem, Thread, Sys) to explain the runtime. - The tiza skill, for drawings. @@ -75,13 +75,13 @@ run by `make check`. It must: - compile and run every raz example marked as runnable and compare the expected output written in the book; - - confirm every quoted Pascal excerpt still matches src/, quoted by + - confirm every quoted Pascal excerpt still matches seed/, quoted by unit and routine name, never by line number; - regenerate or verify the cleaned disassembly. The goal: when the compiler changes, `make check` fails rather than the book going quietly wrong. - CI (.github/workflows/): on a push to main that touches doc/book/**, - src/** or lib/**, build the epub and replace the file on a standing + seed/** or lib/**, build the epub and replace the file on a standing prerelease tagged `book` (gh release upload --clobber), so the owner has a fixed URL to open on an iPad. Tagged releases also attach that version's epub. diff --git a/doc/compiler.md b/doc/compiler.md index a20f26e..1ea6fd6 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -10,17 +10,17 @@ | File | Lines | Code | What | |---|---|---|---| -| `src/diag.pas` | 316 | 233 | Messages: positions, source excerpts, colour, counts | -| `src/scan.pas` | 886 | 747 | Symbols, literals, comments, positions | -| `src/sym.pas` | 646 | 528 | Types, objects, scopes, layout | -| `src/chunk.pas` | 318 | 246 | The compiled program: chunks, fixups, line notes | -| `src/x64.pas` | 1,208 | 998 | The instruction encoder, jumps within a procedure, the assembler | -| `src/gen.pas` | 2,322 | 1,670 | The stack machine, for x86-64: values, operations, checks, calls, frames | -| `src/item.pas` | 1,575 | 1,299 | Items: types, constants, variables, operators, conversions, calls | -| `src/parse.pas` | 3,280 | 2,851 | Declarations, statements, expressions, built-ins, recovery, warnings | -| `src/link.pas` | 334 | 258 | Tree shaking, layout, patching, the places | -| `src/elf.pas` | 373 | 294 | Static and dynamic ELF, symbol table, line numbers | -| `src/raz.pas` | 245 | 188 | The command line | +| `seed/diag.pas` | 316 | 233 | Messages: positions, source excerpts, colour, counts | +| `seed/scan.pas` | 886 | 747 | Symbols, literals, comments, positions | +| `seed/sym.pas` | 646 | 528 | Types, objects, scopes, layout | +| `seed/chunk.pas` | 318 | 246 | The compiled program: chunks, fixups, line notes | +| `seed/x64.pas` | 1,208 | 998 | The instruction encoder, jumps within a procedure, the assembler | +| `seed/gen.pas` | 2,322 | 1,670 | The stack machine, for x86-64: values, operations, checks, calls, frames | +| `seed/item.pas` | 1,575 | 1,299 | Items: types, constants, variables, operators, conversions, calls | +| `seed/parse.pas` | 3,280 | 2,851 | Declarations, statements, expressions, built-ins, recovery, warnings | +| `seed/link.pas` | 334 | 258 | Tree shaking, layout, patching, the places | +| `seed/elf.pas` | 373 | 294 | Static and dynamic ELF, symbol table, line numbers | +| `seed/raz.pas` | 245 | 188 | The command line | Every file opens with a comment that says what it is, what it depends on and what it leaves out. Read those first; they are the map. diff --git a/seed/chunk.pas b/seed/chunk.pas new file mode 100644 index 0000000..91b6dff --- /dev/null +++ b/seed/chunk.pas @@ -0,0 +1,318 @@ +{ 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 new file mode 100644 index 0000000..9480509 --- /dev/null +++ b/seed/diag.pas @@ -0,0 +1,316 @@ +{ 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 new file mode 100644 index 0000000..79b576f --- /dev/null +++ b/seed/elf.pas @@ -0,0 +1,373 @@ +{ 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 new file mode 100644 index 0000000..aeed68b --- /dev/null +++ b/seed/gen.pas @@ -0,0 +1,2322 @@ +{ 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 new file mode 100644 index 0000000..e2afc4f --- /dev/null +++ b/seed/item.pas @@ -0,0 +1,1575 @@ +{ 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 new file mode 100644 index 0000000..edf0611 --- /dev/null +++ b/seed/link.pas @@ -0,0 +1,334 @@ +{ 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 new file mode 100644 index 0000000..58ca27a --- /dev/null +++ b/seed/parse.pas @@ -0,0 +1,3285 @@ +{ 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 new file mode 100644 index 0000000..c0ef892 --- /dev/null +++ b/seed/raz.pas @@ -0,0 +1,245 @@ +{ 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 new file mode 100644 index 0000000..ac8f725 --- /dev/null +++ b/seed/scan.pas @@ -0,0 +1,886 @@ +{ 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 new file mode 100644 index 0000000..29c01fd --- /dev/null +++ b/seed/sym.pas @@ -0,0 +1,646 @@ +{ 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 new file mode 100644 index 0000000..e7efa73 --- /dev/null +++ b/seed/x64.pas @@ -0,0 +1,1208 @@ +{ 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/self/Chunk.raz b/self/Chunk.raz deleted file mode 100644 index 3078ac5..0000000 --- a/self/Chunk.raz +++ /dev/null @@ -1,354 +0,0 @@ -(* Chunk: 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). - - Depends on: Scan, for names and memory; Diag, for positions. - Leaves out: the instructions; that is X64. - - Exported variables can't be set from outside, so the setters at the - end do what the seed's other units do to these. *) -module Chunk; -import Fmt, Diag, Scan; - -type - Section* = (secText, secRodata, secBss); - - Chunk* = record - sec*: Section; - start*, size*, align*: INT; (* in its section's buffer *) - firstFix*, numFix*: INT; (* its fixups: text's in fixups, rodata's in dataFixups *) - home*, name*: INT; (* its module and its name, for the symbol table; -1 if none *) - adr*: INT; (* its address, set by the linker *) - live*: BOOL; (* reached from the entry point *) - ext*: BOOL; (* bss: the address of a C symbol, its name *) - reals*: BOOL; (* code: computes with reals, first at realsAt *) - realsAt*: Diag.Pos; - saveMask*: INT; (* code: the registers of variables it saves, as bits of Gen's VarRegs *) - saveAt*: INT; (* ... 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 *) - Line* = record - at*, chunk*: INT; (* the place in text, and its chunk *) - path*, line*, col*: INT; (* 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 *) - VarNote* = record - chunk*, name*: INT; - off*: INT; (* from the frame pointer *) - kind*: INT; (* how Rt shows it: see Link *) - end; - - Fixup* = record - at*: INT; (* the 32-bit field, as an offset in text; in - dataFixups, the 64-bit one, from its chunk's start *) - chunk*: INT; (* the chunk it refers to *) - addend*: INT; (* added to the chunk's address *) - end; - -var - text*: ^U8; (* text *) - pc*: INT; (* its length *) - rodata*: ^U8; - rolen*: INT; - chunks*: ^Chunk; - numChunks*: INT; - fixups*: ^Fixup; - numFixups*: INT; - (* 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*: ^Fixup; - numDataFixups*: INT; - lines*: ^Line; - numLines*: INT; - curFile: INT; (* the file being compiled, for noteLine *) - curChunk*: INT; (* the chunk of code being written *) - varNotes*: ^VarNote; - numVarNotes*: INT; - - codeCap, roCap, chunkCap, fixCap, dataFixCap, lineCap, noteCap: INT; - -(* Room for n more bytes of code *) -proc room(n: INT); -begin - if pc + n > codeCap then - text := Scan.regrab(text, pc, codeCap * 2 + n); - codeCap := codeCap * 2 + n; - end; -end; - -proc put1*(b: INT); -begin - if pc + 16 > codeCap then room(16); end; - text[pc] := U8(b & 0FFH); - INC(pc); -end; - -(* The low 32 bits of v, least significant byte first *) -proc put4*(v: INT); -var i: INT; -begin - if pc + 16 > codeCap then room(16); end; - for i := 0 to 3 do text[pc + i] := U8((v shr (8 * i)) & 0FFH); end; - INC(pc, 4); -end; - -proc put4At*(at, v: INT); -var i: INT; -begin - for i := 0 to 3 do text[at + i] := U8((v shr (8 * i)) & 0FFH); end; -end; - -(* The 32 bits at at, as a signed number *) -proc get4At*(at: INT): INT; -var u, i: INT; -begin - u := 0; - for i := 0 to 3 do u := u * 256 + INT(text[at + 3 - i]); end; - if u >= 80000000H then u := u - 100000000H; end; - return u; -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. *) -proc takeBack*(n: INT); -begin - DEC(pc, n); - if (numLines > 0) and (lines[numLines - 1].at > pc) then - lines[numLines - 1].at := pc; - if (numLines > 1) and (lines[numLines - 2].at = pc) then - lines[numLines - 2] := lines[numLines - 1]; - DEC(numLines); - end; - end; -end; - -proc put8*(v: I64); -begin - put4(INT(v & 0FFFFFFFFH)); - put4(INT((v shr 32) & 0FFFFFFFFH)); -end; - -proc newChunk*(sec: Section; home, name: INT): INT; -var c: ^Chunk; -begin - if numChunks = chunkCap then - chunks := ^Chunk(Scan.regrab(^U8(chunks), numChunks * SIZE(Chunk), chunkCap * 2 * SIZE(Chunk))); - chunkCap := chunkCap * 2; - end; - c := ADR(chunks[numChunks]); - c^ := {}; - c^.sec := sec; - c^.home := home; - c^.name := name; - c^.align := 1; - c^.size := -1; (* not yet defined *) - INC(numChunks); - return numChunks - 1; -end; - -proc beginChunk*(c: INT); -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 & 31 # 0 do put1(0CCH); end; - curChunk := c; - chunks[c].start := pc; - chunks[c].align := 32; - chunks[c].firstFix := numFixups; -end; - -proc endChunk*(c: INT); -begin - chunks[c].size := pc - chunks[c].start; - chunks[c].numFix := numFixups - chunks[c].firstFix; -end; - -(* The n bytes at p are the data of rodata chunk c *) -proc setData*(c: INT; p: ^U8; n, align: INT); -begin - if rolen + n > roCap then - rodata := Scan.regrab(rodata, rolen, roCap * 2 + n); - roCap := roCap * 2 + n; - end; - COPY(rodata[rolen..rolen + n], p[0..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; - -proc setBss*(c: INT; size, align: INT); -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. *) -proc noteLine*(line, col: INT); -begin - if (numLines > 0) and (lines[numLines - 1].at = pc) then DEC(numLines); end; - 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 - return; - end; - if numLines = lineCap then - lines := ^Line(Scan.regrab(^U8(lines), numLines * SIZE(Line), lineCap * 2 * SIZE(Line))); - lineCap := lineCap * 2; - 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. *) -proc externChunk*(name: INT): INT; -var c: INT; -begin - for c := 0 to numChunks - 1 do - if chunks[c].ext and (chunks[c].name = name) then return c; end; - end; - c := newChunk(secBss, -1, name); - setBss(c, 8, 8); - chunks[c].ext := true; - return c; -end; - -proc addFixup*(at, chunk, addend: INT); -begin - if numFixups = fixCap then - fixups := ^Fixup(Scan.regrab(^U8(fixups), numFixups * SIZE(Fixup), fixCap * 2 * SIZE(Fixup))); - fixCap := fixCap * 2; - 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. *) -proc addDataFixup*(c, at, chunk, addend: INT); -begin - if numDataFixups = dataFixCap then - dataFixups := ^Fixup(Scan.regrab(^U8(dataFixups), numDataFixups * SIZE(Fixup), dataFixCap * 2 * SIZE(Fixup))); - dataFixCap := dataFixCap * 2; - end; - dataFixups[numDataFixups].at := at; - dataFixups[numDataFixups].chunk := chunk; - dataFixups[numDataFixups].addend := addend; - INC(numDataFixups); - INC(chunks[c].numFix); -end; - -proc noteVar*(chunk, name, off, kind: INT); -begin - if numVarNotes = noteCap then - varNotes := ^VarNote(Scan.regrab(^U8(varNotes), numVarNotes * SIZE(VarNote), noteCap * 2 * SIZE(VarNote))); - noteCap := noteCap * 2; - end; - 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 *) -proc chunkName*(c: INT): []U8; -begin - if chunks[c].name < 0 then return Diag.say("literal{}", [Fmt.int(c)]); end; - if chunks[c].home < 0 then return Scan.nameOf(chunks[c].name); end; - return Diag.say("{}.{}", [Fmt.str(Scan.nameOf(chunks[c].home)), Fmt.str(Scan.nameOf(chunks[c].name))]); -end; - -(* What Gen's Redo and Rewind put back: the code, fixups and lines made - since are forgotten *) -proc rewindTo*(atPc, atFixups, atLines: INT); -begin - pc := atPc; - numFixups := atFixups; - numLines := atLines; -end; - -(* The file the code is being made from, as its path interned *) -proc setCurFile*(path: INT); -begin - curFile := path; -end; - -proc curFilePath*: INT; -begin - return curFile; -end; - -proc setLive*(c: INT); -begin - chunks[c].live := true; -end; - -proc setAdr*(c: INT; a: INT); -begin - chunks[c].adr := a; -end; - -(* Chunk c computes with reals, the first of them at p *) -proc setReals*(c: INT; p: Diag.Pos); -begin - chunks[c].reals := true; - chunks[c].realsAt := p; -end; - -proc setSaves*(c, mask, at: INT); -begin - chunks[c].saveMask := mask; - chunks[c].saveAt := at; -end; - -begin - codeCap := 1 shl 20; - text := Scan.grab(codeCap); - pc := 0; - roCap := 1 shl 16; - rodata := Scan.grab(roCap); - rolen := 0; - chunkCap := 1 shl 10; - chunks := ^Chunk(Scan.grab(chunkCap * SIZE(Chunk))); - numChunks := 0; - fixCap := 1 shl 12; - fixups := ^Fixup(Scan.grab(fixCap * SIZE(Fixup))); - numFixups := 0; - dataFixCap := 1 shl 8; - dataFixups := ^Fixup(Scan.grab(dataFixCap * SIZE(Fixup))); - numDataFixups := 0; - lineCap := 1 shl 12; - lines := ^Line(Scan.grab(lineCap * SIZE(Line))); - numLines := 0; - noteCap := 1 shl 8; - varNotes := ^VarNote(Scan.grab(noteCap * SIZE(VarNote))); - numVarNotes := 0; -end Chunk. diff --git a/self/Diag.raz b/self/Diag.raz deleted file mode 100644 index fc1ab64..0000000 --- a/self/Diag.raz +++ /dev/null @@ -1,410 +0,0 @@ -(* Diag: 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: Sys, to write and to ask about the terminal; Buf and Fmt, - to build what it writes. - Leaves out: wording. The callers say what is wrong, with say; a - message is at most 255 characters, which every message so far keeps - well within. A message made by say is kept for good, since it is - made only where it is about to be shown. *) -module Diag; -import Sys, Rt, Heap, Mem, Buf, Fmt, Str; - -type - (* A stretch of a source file: bytes a up to but not including b. - a = b marks the place between two characters. *) - Pos* = record f*, a*, b*: INT; end; - - File = record - path: []U8; - buf: ^U8; - len: INT; - end; - -const - MaxErrors* = 20; - Bold = "\x1B[1m"; Red = "\x1B[1;31m"; Yellow = "\x1B[1;33m"; - Cyan = "\x1B[1;36m"; Green = "\x1B[1;32m"; Blue = "\x1B[1;34m"; - Plain = "\x1B[0m"; - (* A long line is shown cut to this many bytes around the place, its - cut ends marked ... *) - ShownBytes = 100; - -var - errors*, warnings*: INT; - werror*: BOOL; (* -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*: BOOL; - - files: ^File; (* numFiles of them, in room for cap *) - numFiles, cap: INT; - colour, colourKnown, cwdKnown: BOOL; - cwd: Buf.Buf; (* the working directory and a /, or empty if unknown *) - out: Buf.Buf; (* the message being made *) - lastError: Pos; (* where the last error was *) - shown: BOOL; (* whether it was shown: its notes and help are only then *) - -(* Exported variables can't be set from outside, so these do it. *) -proc setWerror*(yes: BOOL); -begin - werror := yes; -end; - -proc setQuiet*(yes: BOOL); -begin - quiet := yes; -end; - -(* Paths are shown from the working directory where they are under it, - so messages read the same wherever the compiler or its library is. *) -proc shownPath*(path: []U8): []U8; -var d: []U8; err: INT; c: []U8; -begin - if not cwdKnown then - d, err := Sys.workDir(); - if err = 0 then - Buf.str(ADR(cwd), d); - Buf.add(ADR(cwd), '/'); - end; - cwdKnown := true; - end; - c := Buf.bytes(ADR(cwd)); - if (LEN(c) > 0) and Str.hasPrefix(path, c) then return path[LEN(c)..LEN(path)]; end; - return path; -end; - -proc fatal*(msg: []U8); forward; - -(* Memory, or the end of the compile when there is none *) -proc grab(size: INT): ^U8; -var p: ^U8; -begin - p := Mem.alloc(Heap.heap, size, 8); - if p = nil then fatal("out of memory"); end; - return p; -end; - -(* Keeps buf, len bytes of a file, under a number, which it gives back; - buf stays as it is, and its path is copied. *) -proc addFile*(path: []U8; buf: ^U8; len: INT): INT; -var more: ^File; i: INT; p: []U8; ok: BOOL; -begin - if numFiles = cap then - more := ^File(grab((2 * cap + 8) * SIZE(File))); - for i := 0 to numFiles - 1 do more[i] := files[i]; end; - if files # nil then Mem.free(Heap.heap, ^U8(files)); end; - files := more; - cap := 2 * cap + 8; - end; - p, ok := Str.copy(Heap.heap, shownPath(path)); - if not ok then fatal("out of memory"); end; - files[numFiles] := {path: p, buf: buf, len: len}; - INC(numFiles); - return numFiles - 1; -end; - -proc pathOf*(f: INT): []U8; -begin - return files[f].path; -end; - -(* Writing *) - -(* Whether NO_COLOR is set. The library can't tell it set to nothing - from not set, so that counts as not set, as no-color.org has it. *) -proc noColour: BOOL; -begin - return LEN(Sys.env("NO_COLOR")) > 0; -end; - -proc put(s: []U8); -begin - Buf.str(ADR(out), s); -end; - -proc putc(c: U8); -begin - Buf.add(ADR(out), c); -end; - -proc putNum(n: INT); -begin - Fmt.write(ADR(out), "{}", [Fmt.int(n)]); -end; - -(* The text of a number *) -proc say*(f: []U8; args: []Fmt.Arg): []U8; -var b: ^Buf.Buf; -begin - b := ^Buf.Buf(grab(SIZE(Buf.Buf))); - Buf.init(b, Heap.heap); - Fmt.write(b, f, args); - return Buf.bytes(b); -end; - -(* c, when colour is on *) -proc paintOn(c: []U8); -begin - if not colourKnown then - colour := Sys.isTerminal(2) and not noColour(); - colourKnown := true; - end; - if colour then put(c); end; -end; - -(* s in colour c, when colour is on *) -proc paint(c, s: []U8); -begin - paintOn(c); - put(s); - paintOn(Plain); -end; - -(* What has been made, written to standard error *) -proc flush; -var s: []U8; n: INT; -begin - s := Buf.bytes(ADR(out)); - while LEN(s) > 0 do - n := Sys.write(Sys.stderr, s); - if n <= 0 then break; end; - s := s[n..LEN(s)]; - end; - Buf.reset(ADR(out)); -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. *) -proc locate(p: Pos): (INT, INT); -var i, line, start: INT; buf: ^U8; -begin - buf := files[p.f].buf; - line := 1; - start := 0; - for i := 0 to p.a - 1 do - if buf[i] = 10 then INC(line); start := i + 1; end; - end; - return line, start; -end; - -proc lineOf*(p: Pos): INT; -var line: INT; -begin - line, _ := locate(p); - return line; -end; - -(* A byte that starts a character: every one but a UTF-8 continuation *) -proc starts(c: U8): BOOL; -begin - return (c & 0C0H) # 80H; -end; - -(* Characters from byte i to byte j of buf *) -proc chars(buf: ^U8; i, j: INT): INT; -var n: INT; -begin - n := 0; - while i < j do - if starts(buf[i]) then INC(n); end; - INC(i); - end; - return 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. *) -proc show(p: Pos; kind, kindColour, msg: []U8); -var line, start, stop, lo, hi, i, n: INT; buf: ^U8; f: ^File; digits: []U8; -begin - if p.f >= numFiles then - (* about no place in a file, as for Rt, which the compiler - imports before it reads one *) - paint(Bold, "raz:"); - put(" "); - paintOn(kindColour); put(kind); put(":"); paintOn(Plain); - put(" "); - paint(Bold, msg); - putc('\n'); - flush; - return; - end; - line, start := locate(p); - f := ADR(files[p.f]); - buf := f^.buf; - paintOn(Bold); - put(f^.path); put(":"); putNum(line); put(":"); putNum(chars(buf, start, p.a) + 1); put(":"); - paintOn(Plain); - put(" "); - paintOn(kindColour); put(kind); put(":"); paintOn(Plain); - put(" "); - paint(Bold, msg); - putc('\n'); - stop := start; - while (stop < f^.len) and (buf[stop] # 10) do INC(stop); end; - lo := start; - hi := stop; - if hi - lo > ShownBytes then - if p.a - lo > ShownBytes div 2 then lo := p.a - ShownBytes div 2; end; - while not starts(buf[lo]) do INC(lo); end; - if hi - lo > ShownBytes then hi := lo + ShownBytes; end; - while (hi < stop) and not starts(buf[hi]) do INC(hi); end; - end; - paintOn(Blue); - digits := say("{}", [Fmt.int(line)]); - for i := LEN(digits) to 4 do put(" "); end; - put(digits); put(" |"); - paintOn(Plain); - put(" "); - if lo > start then put("..."); end; - put(buf[lo..hi]); - if hi < stop then put("..."); end; - putc('\n'); - paint(Blue, " |"); - put(" "); - if lo > start then put(" "); end; - for i := lo to p.a - 1 do - if buf[i] = '\t' then putc('\t'); elsif starts(buf[i]) then putc(' '); end; - end; - if p.b < hi then n := chars(buf, p.a, p.b); else n := chars(buf, p.a, hi); end; - if n < 1 then n := 1; end; - paintOn(kindColour); - for i := 1 to n do putc('^'); end; - paintOn(Plain); - putc('\n'); - flush; -end; - -(* From the start of p to the end of q *) -proc join*(p, q: Pos): Pos; -begin - p.b := q.b; - return p; -end; - -(* The text at p, at most the 255 bytes a message can hold *) -proc source*(p: Pos): []U8; -var n: INT; -begin - n := p.b - p.a; - if n > 255 then n := 255; end; - return files[p.f].buf[p.a..p.a + n]; -end; - -(* Messages *) - -(* Line line of the file at path, as written, to at most 255 bytes *) -proc lineText*(path: []U8; line: INT): []U8; -var i, k, n, j: INT; f: ^File; want: []U8; -begin - want := shownPath(path); - for i := 0 to numFiles - 1 do - f := ADR(files[i]); - if f^.path = want then - k := 0; - n := 1; - while (n < line) and (k < f^.len) do - if f^.buf[k] = 10 then INC(n); end; - INC(k); - end; - j := k; - while (j < f^.len) and (f^.buf[j] # 10) and (j - k < 255) do INC(j); end; - return f^.buf[k..j]; - end; - end; - return ""; -end; - -proc error*(p: Pos; msg: []U8); -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 return; end; - lastError := p; - show(p, "error", Red, msg); - INC(errors); - if errors >= MaxErrors then - put("raz: stopping after "); - putNum(MaxErrors); - put(" errors\n"); - flush; - Rt.exit(1); - end; -end; - -proc warning*(p: Pos; msg: []U8); -begin - if werror then - error(p, msg); - else - 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 *) -proc note*(p: Pos; msg: []U8); -begin - if shown then show(p, "note", Cyan, msg); end; -end; - -proc help*(msg: []U8); -begin - if shown then - paint(Green, "help:"); - put(" "); - put(msg); - putc('\n'); - flush; - end; -end; - -(* An error with no place in the source, such as a file that can't be - read: it stops the compiler at once. *) -proc fatal*(msg: []U8); -begin - put("raz: "); - put(msg); - putc('\n'); - flush; - Rt.exit(1); -end; - -proc count(n: INT; what: []U8): []U8; -begin - if n = 1 then return say("1 {}", [Fmt.str(what)]); end; - return say("{} {}s", [Fmt.int(n), Fmt.str(what)]); -end; - -(* Says how many errors and warnings there were, and stops the compiler - if there were errors. *) -proc finish*; -begin - if (errors > 0) and (warnings > 0) then - put("raz: "); put(count(errors, "error")); put(", "); put(count(warnings, "warning")); putc('\n'); - elsif errors > 0 then - put("raz: "); put(count(errors, "error")); putc('\n'); - elsif warnings > 0 then - put("raz: "); put(count(warnings, "warning")); putc('\n'); - end; - flush; - if errors > 0 then Rt.exit(1); end; -end; - -begin - Buf.init(ADR(cwd), Heap.heap); - Buf.init(ADR(out), Heap.heap); -end Diag. diff --git a/self/Elf.raz b/self/Elf.raz deleted file mode 100644 index 19defdb..0000000 --- a/self/Elf.raz +++ /dev/null @@ -1,431 +0,0 @@ -(* Elf: 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 memory, Diag for errors, Sys and Files to write - the file. - Leaves out: position independent executables, symbol versions, the - rest of DWARF. - - Exported variables can't be set from outside, so needLib, setMainPath - and setStripped do it. *) -module Elf; -import Sys, Files, Fmt, Diag, Scan, Chunk, Link; - -var - needed: [32]INT; (* the libraries to load, names interned *) - numNeeded*: INT; (* none: a static program *) - mainPath: []U8; (* the main module's file, for gdb *) - stripped*: BOOL; (* -s: no symbols and no line numbers; the sections are there, empty *) - - buf: ^U8; - len, cap: INT; - -(* The library name, to be loaded, unless it is already: false if there - are too many *) -proc needLib*(name: INT): BOOL; -var i: INT; -begin - for i := 0 to numNeeded - 1 do - if needed[i] = name then return true; end; - end; - if numNeeded = 32 then return false; end; - needed[numNeeded] := name; - INC(numNeeded); - return true; -end; - -(* A static program again *) -proc noLibs*; -begin - numNeeded := 0; -end; - -proc setMainPath*(path: []U8); -begin - mainPath := path; -end; - -proc setStripped*(yes: BOOL); -begin - stripped := yes; -end; - -proc room(n: INT); -begin - if len + n > cap then - buf := Scan.regrab(buf, len, cap * 2 + n); - cap := cap * 2 + n; - end; -end; - -(* The n low bytes of v, least significant first *) -proc putN(v: INT; n: INT); -var i: INT; -begin - room(n); - for i := 0 to n - 1 do - buf[len] := U8(v & 0FFH); - v := v shr 8; - INC(len); - end; -end; - -proc putBytes(p: ^U8; n: INT); -begin - room(n); - if n > 0 then COPY(buf[len..len + n], p[0..n]); end; - len := len + n; -end; - -proc padTo(off: INT); -begin - while len < off do putN(0, 1); end; -end; - -proc patch(at: INT; v: INT; n: INT); -var i: INT; -begin - for i := 0 to n - 1 do - buf[at + i] := U8(v & 0FFH); - v := v shr 8; - end; -end; - -proc phdr(typ, flags: INT; off, adr, filesz, memsz, align: INT); -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"; - -(* Where in ShNames the name is: the byte after a zero that starts it and - is followed by one; the empty name, found nowhere, is 0 *) -proc nameAt(name: []U8): INT; -var i, k: INT; same: BOOL; -begin - for i := 1 to LEN(ShNames) - LEN(name) - 1 do - if ShNames[i - 1] = 0 then - same := ShNames[i + LEN(name)] = 0; - for k := 0 to LEN(name) - 1 do - if ShNames[i + k] # name[k] then same := false; end; - end; - if same and (LEN(name) > 0) then return i; end; - end; - end; - return 0; -end; - -(* A section header. Its name is stored as its offset in ShNames. *) -proc shdr(name: []U8; typ: INT; flags, adr, off, size: INT; lnk, info: INT; align, entsize: INT); -begin - putN(nameAt(name), 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; - -proc putStr(s: []U8); -begin - putBytes(ADR(s[0]), LEN(s)); - putN(0, 1); -end; - -(* LEB128, unsigned *) -proc putU(v: INT); -begin - while v >= 80H do - putN(v & 7FH | 80H, 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). Section - offsets go in off, sizes in size: line, info, abbrev. *) -proc putDebug(off, size: []INT); -var cwd: []U8; err: INT; -begin - off[0] := Chunk.chunks[Link.placesChunk].adr - Link.roAdr + Link.roOff + Link.linesOff; - size[0] := Link.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); - cwd, err := Sys.workDir(); - if err # 0 then cwd := ""; end; - putStr(cwd); - putStr("raz"); - putN(0, 4); (* the line table, at 0 *) - putN(Link.Base + Link.textOff, 8); putN(Link.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(11H); putN(0, 1); (* 1: a compile unit, no children *) - putU(03H); putU(08H); (* name, a string *) - putU(1BH); putU(08H); (* comp_dir, a string *) - putU(25H); putU(08H); (* producer, a string *) - putU(10H); putU(17H); (* stmt_list, a section offset *) - putU(11H); putU(01H); (* low_pc, an address *) - putU(12H); putU(07H); (* 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 = 6474E551H; - -var - (* in the room at the end of rodata: where each of the loader's - tables starts, from extraAdr *) - symAt, relaAt, hashAt, strAt: INT; - nsym, strLen: INT; - -(* Whether chunk c is a C symbol the program uses *) -proc isExt(c: INT): BOOL; -begin - return Chunk.chunks[c].live and Chunk.chunks[c].ext; -end; - -(* The sizes of the loader's tables: what linkAll must leave room for. *) -proc sizeTables(roExtra, dynSize: ^INT); -var c, i: INT; -begin - nsym := 1; - strLen := 1; - for i := 0 to numNeeded - 1 do strLen := strLen + LEN(Scan.nameOf(needed[i])) + 1; end; - for c := 0 to Chunk.numChunks - 1 do - if isExt(c) then - INC(nsym); - strLen := strLen + LEN(Scan.nameOf(Chunk.chunks[c].name)) + 1; - end; - end; - symAt := (LEN(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. *) -proc putTables; -var c, k, i, at, name: INT; -begin - len := Link.extraAdr - Link.roAdr + Link.roOff; - putStr(Interp); - padTo(Link.extraAdr - Link.roAdr + Link.roOff + symAt); - putN(0, 24); - name := strLen; - for c := Chunk.numChunks - 1 to 0 by -1 do (* names go last in the string table *) - if isExt(c) then name := name - LEN(Scan.nameOf(Chunk.chunks[c].name)) - 1; end; - end; - for c := 0 to Chunk.numChunks - 1 do - if isExt(c) then - putN(name, 4); putN(10H, 1); putN(0, 1); putN(0, 2); (* global, undefined *) - putN(0, 8); putN(0, 8); - name := name + LEN(Scan.nameOf(Chunk.chunks[c].name)) + 1; - end; - end; - k := 1; - for c := 0 to Chunk.numChunks - 1 do - if isExt(c) then - putN(Chunk.chunks[c].adr, 8); - putN((k shl 32) | 6, 8); (* R_X86_64_GLOB_DAT *) - putN(0, 8); - INC(k); - end; - 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); end; - putN(0, 1); - for i := 0 to numNeeded - 1 do putStr(Scan.nameOf(needed[i])); end; - for c := 0 to Chunk.numChunks - 1 do - if isExt(c) then putStr(Scan.nameOf(Chunk.chunks[c].name)); end; - end; - len := Link.roOff + Link.roSize; - - (* the dynamic table, at the start of the writable segment *) - padTo(Link.bssOff); - at := 1; - for i := 0 to numNeeded - 1 do - putN(1, 8); putN(at, 8); (* DT_NEEDED *) - at := at + LEN(Scan.nameOf(needed[i])) + 1; - end; - putN(4, 8); putN(Link.extraAdr + hashAt, 8); (* DT_HASH *) - putN(5, 8); putN(Link.extraAdr + strAt, 8); (* DT_STRTAB *) - putN(6, 8); putN(Link.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(Link.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; - -proc writeElf*(path: []U8; entry: INT); -var - nph, nsh, c, nsyms, sec, strsCap: INT; - roExtra, dynSize, symOff, strOff, shstrOff, shOff, strsLen: INT; - dbgOff, dbgSize: [3]INT; - strs: ^U8; - s: []U8; - dyn: BOOL; -begin - cap := 1 shl 16; - buf := Scan.grab(cap); - len := 0; - dyn := numNeeded > 0; - roExtra := 0; dynSize := 0; - if dyn then sizeTables(ADR(roExtra), ADR(dynSize)); end; - (* room for the most program headers either kind of program has *) - Link.linkAll(64 + 6 * 56, roExtra, dynSize); - if dyn then - nph := 6; - else - nph := 2; - if Link.roSize > 0 then INC(nph); end; - if Link.bssSize > 0 then INC(nph); end; - end; - - (* ELF header *) - putN(464C457FH, 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(Chunk.chunks[entry].adr, 8); - putN(64, 8); (* program headers follow *) - putN(0, 8); (* section headers: patched below *) - putN(0, 4); - nsh := 10; - if dyn then nsh := 13; end; - 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 dyn then - phdr(PtInterp, 4, Link.extraAdr - Link.roAdr + Link.roOff, Link.extraAdr, LEN(Interp) + 1, LEN(Interp) + 1, 1); - end; - (* the first segment maps the headers too, so text can follow them *) - phdr(PtLoad, 5, 0, Link.Base, Link.textOff + Link.textSize, Link.textOff + Link.textSize, Link.Page); - if Link.roSize > 0 then phdr(PtLoad, 4, Link.roOff, Link.roAdr, Link.roSize, Link.roSize, Link.Page); end; - if dyn then - phdr(PtLoad, 6, Link.bssOff, Link.bssAdr, dynSize, Link.bssSize, Link.Page); - phdr(PtDynamic, 6, Link.bssOff, Link.bssAdr, dynSize, dynSize, 8); - elsif Link.bssSize > 0 then - phdr(PtLoad, 6, 0, Link.bssAdr, 0, Link.bssSize, Link.Page); - end; - phdr(PtGnuStack, 6, 0, 0, 0, 0, 16); (* a stack that can't run code *) - - padTo(Link.textOff); - putBytes(Link.textImg, Link.textSize); - padTo(Link.roOff); (* even when empty, so that every section lies in the file *) - putBytes(Link.roImg, Link.roSize); - if dyn then putTables; end; - - (* the symbol table: one local symbol for each named live chunk *) - padTo((len + 7) div 8 * 8); - symOff := len; - strsCap := 1 shl 16; - strs := Scan.grab(strsCap); - strsLen := 1; - strs[0] := 0; - putN(0, 24); - nsyms := 1; - for c := 0 to Chunk.numChunks - 1 do - if not stripped and Chunk.chunks[c].live and (Chunk.chunks[c].name >= 0) and not Chunk.chunks[c].ext then - s := Chunk.chunkName(c); - if strsLen + LEN(s) + 1 > strsCap then - strs := Scan.regrab(strs, strsLen, strsLen * 2 + 256); - strsCap := strsLen * 2 + 256; - end; - COPY(strs[strsLen..strsLen + LEN(s)], s); - strs[strsLen + LEN(s)] := 0; - if Chunk.chunks[c].sec = Chunk.secText then (* the section's index in the headers below *) - sec := 1; - elsif Chunk.chunks[c].sec = Chunk.secRodata then - sec := 2; - else - sec := 3; - end; - putN(strsLen, 4); - if sec = 1 then putN(2, 1); else putN(1, 1); end; (* STT_FUNC, STT_OBJECT *) - putN(0, 1); - putN(sec, 2); - putN(Chunk.chunks[c].adr, 8); - putN(Chunk.chunks[c].size, 8); - strsLen := strsLen + LEN(s) + 1; - INC(nsyms); - end; - end; - strOff := len; - putBytes(strs, strsLen); - shstrOff := len; - putBytes(ADR(ShNames[0]), LEN(ShNames)); - if stripped or (Link.placesChunk < 0) then - for c := 0 to 2 do dbgOff[c] := len; dbgSize[c] := 0; end; - else - putDebug(dbgOff, dbgSize); - end; - - 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, Link.Base + Link.textOff, Link.textOff, Link.textSize, 0, 0, 16, 0); - shdr(".rodata", 1, 2, Link.roAdr, Link.roOff, Link.roSize, 0, 0, 16, 0); - shdr(".bss", 8, 3, Link.bssAdr + dynSize, Link.roOff + Link.roSize, Link.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, LEN(ShNames), 0, 0, 1, 0); - if dyn then (* the loader's tables, for readelf and objdump *) - shdr(".dynamic", 6, 3, Link.bssAdr, Link.bssOff, dynSize, 8, 0, 8, 16); - shdr(".dynstr", 3, 2, Link.extraAdr + strAt, Link.extraAdr + strAt - Link.roAdr + Link.roOff, strLen, 0, 0, 1, 0); - shdr(".dynsym", 11, 2, Link.extraAdr + symAt, Link.extraAdr + symAt - Link.roAdr + Link.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); - - if not Files.write(path, buf[0..len]) or (Sys.chmod(path, 1EDH) < 0) then - Diag.fatal(Diag.say("can't write {}", [Fmt.str(path)])); - end; -end; - -begin - mainPath := ""; -end Elf. diff --git a/self/Gen.raz b/self/Gen.raz deleted file mode 100644 index a1aa224..0000000 --- a/self/Gen.raz +++ /dev/null @@ -1,2350 +0,0 @@ -(* Gen: the code generator, for x86-64. - - Item and Parse 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, 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. - - The seed's `Mark` in the middle of a push or a check can't give an - error back, so it is shown and the call goes on without doing what - it could not (see newEntry and check): the compile ends with the - message, and the parser's recovery makes the stack right again with - resetStack. endProc returns its error, for the parser to pass up. - - What the parser sets, `inPlace`, has a setter, as the exported - variables can't be set from outside. The seed's types lose their T - (`TAdr` is `Adr`), and its `Call` record, which the procedure `call` - takes, is `CallInfo`. *) -module Gen; -import Fmt, Diag, Scan, Sym, Chunk, X := 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; - - RAX = X.RAX; RCX = X.RCX; RDX = X.RDX; RSP = X.RSP; RBP = X.RBP; - RSI = X.RSI; RDI = X.RDI; R8 = X.R8; R9 = X.R9; R10 = X.R10; R11 = X.R11; - -type - Kind* = (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 *) - Base* = (bFrame, bGlobal, bStack, bSlot, bReg); - Adr* = record - base*: Base; - chunk*: INT; (* bGlobal: the chunk; bSlot: the frame slot; bReg: the register *) - off*: I64; (* added to the address; for bReg, which word, 0 or 8 *) - hi*: INT; (* 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 *) - CodeMark* = record pc*, fixups*, lines*, said*, fails*: INT; end; - - (* For entryPoint: the address of chunk, put in the variable whose - chunk is into before the program starts *) - Link* = record chunk*, into*: INT; end; - - CallInfo* = record - sig*: ^Sym.Type; - param*: ^Sym.Obj; (* the parameter the next argument is for *) - obj*: ^Sym.Obj; (* the procedure called, if it has a name *) - n*: INT; (* the arguments *) - isF*: [64]BOOL; (* ... goes in an xmm register *) - pair*: [64]BOOL; (* ... is a slice's first word, the next its second *) - target*: I64; (* the frame slot of a procedure value, if chunk < 0 *) - chunk*: INT; (* else the procedure's chunk *) - ext*: BOOL; (* C's: called through the chunk holding its address *) - ret*: I64; (* 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*: [5]INT = [X.RBX, X.R12, X.R13, X.R14, X.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*: [7]INT = [X.RBX, X.R12, X.R13, X.R14, X.R15, X.RDI, X.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*: [4]INT = [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*: INT; - (* the stubs that check's code calls, one for each kind of failure, - made by entryPoint for those used *) - failStubs: [6]INT; - lost*: BOOL; (* a parameter kept where it arrived was wanted - for other work: the procedure is compiled again, - the parameter in memory *) - inPlace: INT; (* 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*: INT; (* the values on the stack *) - pushed*: INT; (* quadwords pushed on the machine's stack *) - codeChunk*: INT; (* the procedure or body being compiled, or -1 *) - -type - (* where a value on the stack is *) - Loc = (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 *) - - Entry = record - loc: Loc; - val: I64; (* lConst: the value; lHeld: the register; lAdr: the - offset; lFrame: the frame slot *) - chunk: INT; (* lAdr: the chunk, or -1 for the frame *) - m: X.Mem; (* lIdx, lMem *) - size: INT; (* lMem *) - signed: BOOL; (* lMem *) - k: Kind; - off: I64; (* 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; - - (* a check of the procedure, whose failure endFails makes *) - Fail = record - L, what, ra, name, at: INT; - m: X.Mem; - n: I64; - end; - -const - StubNames: [6][]U8 = ["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: [NumRegs]INT = [R8, R9, R10, R11]; - XRegs: [NumRegs]INT = [8, 9, 10, 11]; (* xmm8 to xmm11 *) - IntRegs: [6]INT = [RDI, RSI, RDX, RCX, R8, R9]; - -var - stack: [256]Entry; - owner: [NumRegs]INT; (* the value in each register, or -1 *) - frameTop, frameMax, permTop: I64; - frameFix: INT; (* where the frame size is patched in *) - paramTop: I64; (* the parameters' slots end here *) - zeroTop: I64; (* the locals the prologue zeroes end here *) - retSlot: I64; (* holds the hidden result pointer *) - resType: ^Sym.Type; (* the procedure's result, or nil *) - exitL: INT; - (* parameters arriving in registers: where each is stored on entry *) - inReg: [14]INT; - inSlot: [14]I64; - inSize: [14]INT; - inObj: [14]^Sym.Obj; - numIn: INT; - procParams: ^Sym.Obj; (* the parameters, for enterBody *) - regMask: INT; (* the registers of variables, as bits (XBit) *) - kept: INT; (* bit r: register r holds a parameter, as it arrived *) - saveAt: I64; (* where they are saved, a quadword each *) - homes: [4]I64; (* the slots of the variables in XVarRegs *) - frameAt: [3]I64; (* frameTop, frameMax, permTop after the declarations *) - fails: [4096]Fail; - numFails: INT; - -proc setInPlace*(r: INT); -begin - inPlace := r; -end; - -proc kindOf*(t: ^Sym.Type): Kind; -begin - if t^.form = Sym.fReal then - if t^.size = 4 then return kF32; end; - return kF64; - end; - if t^.size > WordSize then return kLong; end; - return 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. *) - -proc fits32(v: I64): BOOL; -begin - return (v >= -2147483648) and (v <= 2147483647); -end; - -(* The register of kind k for the value at depth i *) -proc regIn(k: Kind; i: INT): INT; -begin - if k in {kF32, kF64} then return XRegs[i mod NumRegs]; end; - return Regs[i mod NumRegs]; -end; - -proc regOf(i: INT): INT; -begin - return regIn(stack[i].k, i); -end; - -proc isReal(i: INT): BOOL; -begin - return 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 *) -proc realConst(v: I64): X.Mem; -var c: INT; -begin - c := Chunk.newChunk(Chunk.secRodata, -1, -1); - Chunk.setData(c, ^U8(ADR(v)), 8, 8); - return X.memRip(c, 0); -end; - -(* The real i into xmm register x, from wherever it is, as valueTo does - for an integer register *) -proc xValueTo(i, x: INT); -begin - match stack[i].loc of - | lConst: X.movsXM(x, realConst(stack[i].val), stack[i].k = kF32); - | lMem: X.movsXM(x, stack[i].m, stack[i].size = 4); - | lHeld: if INT(stack[i].val) # x then X.movX(x, INT(stack[i].val)); end; - | lInto: if INT(stack[i].val) # x then X.movX(x, INT(stack[i].val)); end; - | lReg: if regOf(i) # x then X.movX(x, regOf(i)); end; - | else: X.movsXM(x, X.mem(RBP, stack[i].val), false); (* spilled, as 8 bytes *) - end; -end; - -proc loaded(i: INT): INT; forward; -proc allocTemp*(size, align: I64): I64; 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 *) -proc spill(i: INT); -var s: I64; -begin - if (stack[i].loc # lReg) or (stack[i].off # 0) then _ := loaded(i); end; - s := allocTemp(8, 8); - if isReal(i) then X.movsMX(X.mem(RBP, s), regOf(i), false); - else X.store(X.mem(RBP, s), regOf(i), 8); end; - 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 *) -proc readMems(d: INT); -var i: INT; -begin - for i := 0 to d - 1 do - if stack[i].loc = lMem then _ := loaded(i); end; - end; -end; - -(* Every value below depth d in a register, spilled; one noted in memory - is read first, as a call may change it *) -proc spillBelow(d: INT); -var r: INT; -begin - readMems(d); - for r := 0 to NumRegs - 1 do - if (owner[r] >= 0) and (owner[r] < d) then spill(owner[r]); end; - end; -end; - -(* The register of kind k of value i, for it to hold: a lower value at - its depth's registers is spilled. *) -proc claim(i: INT; k: Kind): INT; -var r: INT; -begin - r := i mod NumRegs; - if (owner[r] >= 0) and (owner[r] # i) then spill(owner[r]); end; - owner[r] := i; - return regIn(k, i); -end; - -(* The memory at the noted address i, plus off *) -proc adrMem(i: INT; off: I64): X.Mem; -begin - if stack[i].chunk < 0 then return X.mem(RBP, stack[i].val + off); end; - return X.memRip(stack[i].chunk, INT(stack[i].val + off)); -end; - -(* The value i, in its register *) -proc loaded(i: INT): INT; -var r: INT; -begin - if stack[i].loc = lInto then return INT(stack[i].val); end; - if (stack[i].loc # lReg) and isReal(i) then - xValueTo(i, claim(i, stack[i].k)); - stack[i].loc := lReg; - elsif stack[i].loc # lReg then - r := claim(i, kWord); - match stack[i].loc of - | lConst: X.movRI(r, stack[i].val); - | lHeld: X.movRR(r, INT(stack[i].val)); - | lAdr: X.lea(r, adrMem(i, 0)); - | lIdx: X.lea(r, stack[i].m); - | lMem: X.load(r, stack[i].m, stack[i].size, stack[i].signed); - | else: X.load(r, X.mem(RBP, stack[i].val), 8, false); - end; - stack[i].loc := lReg; - end; - if stack[i].off # 0 then - X.lea(regOf(i), X.mem(regOf(i), stack[i].off)); - stack[i].off := 0; - end; - return regOf(i); -end; - -(* The register value i is in, only to be read: a variable's own, or - its register *) -proc peek(i: INT): INT; -begin - if (stack[i].loc = lHeld) and (stack[i].off = 0) then return INT(stack[i].val); end; - return loaded(i); -end; - -(* The offset of value i, taken from it, for the caller to add or to - make a displacement of *) -proc takeOff(i: INT): I64; -var o: I64; -begin - o := stack[i].off; - stack[i].off := 0; - return o; -end; - -(* The word on top, in a register, has o added: noted, if o can be a - displacement, else added now *) -proc putOff(o: I64); -begin - if fits32(stack[depth - 1].off + o) then - stack[depth - 1].off := stack[depth - 1].off + o; - else - X.movRI(RCX, o); - X.alu(X.aluAdd, loaded(depth - 1), RCX); - end; -end; - -proc top: INT; -begin - if depth = 0 then Diag.fatal("internal error: the stack is empty"); end; - return loaded(depth - 1); -end; - -(* A value on the stack's top. At the stack's last place it is shown as - an error and nothing is pushed: see the head of this unit. *) -proc newEntry(k: Kind; loc: Loc; v: I64); -begin - if depth > LEN(stack) - 1 then - _ := Scan.mark("the expression is too deep"); - return; - end; - 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. *) -proc newMem(loc: Loc; m: X.Mem; k: Kind; size: INT; signed: BOOL); -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; -end; - -(* The register a new value on top is to be computed in *) -proc target: INT; -begin - return claim(depth, kWord); -end; - -(* The xmm register a new real on top is to be computed in *) -proc xTarget: INT; -begin - return claim(depth, kF64); -end; - -(* The value just computed in target goes on top *) -proc computed(k: Kind); -begin - newEntry(k, lReg, 0); -end; - -proc drop*; -begin - DEC(depth); - if owner[depth mod NumRegs] = depth then owner[depth mod NumRegs] := -1; end; -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). *) -proc clobberArgs; -begin - if kept # 0 then lost := true; end; -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. *) -proc valueTo(i, r: INT); -begin - if isReal(i) and (stack[i].loc in {lHeld, lInto}) then - X.movqRX(r, INT(stack[i].val)); - else - match stack[i].loc of - | lConst: X.movRI(r, stack[i].val); - | lHeld: X.movRR(r, INT(stack[i].val)); - | lInto: X.movRR(r, INT(stack[i].val)); - | lAdr: X.lea(r, adrMem(i, 0)); - | lIdx: X.lea(r, stack[i].m); - | lMem: X.load(r, stack[i].m, stack[i].size, stack[i].signed); - | lReg: - if isReal(i) then X.movqRX(r, regOf(i)); - elsif regOf(i) # r then X.movRR(r, regOf(i)); end; - | else: X.load(r, X.mem(RBP, stack[i].val), 8, false); - end; - end; - if stack[i].off # 0 then X.lea(r, X.mem(r, stack[i].off)); end; -end; - -(* The value on top, popped into register r *) -proc popTo(r: INT); -begin - valueTo(depth - 1, r); - drop(); -end; - -(* Whether the value on top is a constant, and if so, which *) -proc topConst: (BOOL, I64); -begin - return stack[depth - 1].loc = lConst, stack[depth - 1].val; -end; - -proc resetStack*(d, p: INT); -var r: INT; -begin - depth := d; - pushed := p; - for r := 0 to NumRegs - 1 do owner[r] := -1; end; -end; - -proc pushConst*(k: Kind; v: I64); -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) *) -proc regAt(a: Adr): INT; -var r: INT; -begin - if a.off = 0 then r := a.chunk; else r := a.hi; end; - if r >= XmmVar then r := r - XmmVar; end; (* an xmm register, XVarRegs *) - return r; -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. *) -proc place(a: Adr; r: INT): X.Mem; -var m: X.Mem; ra: INT; o: I64; -begin - if a.base = bReg then Diag.fatal("internal error: a register has no address"); end; - match a.base of - | bFrame: return X.mem(RBP, a.off); - | bGlobal: return X.memRip(a.chunk, INT(a.off)); - | bStack: - if stack[depth - 1].loc = lAdr then - m := adrMem(depth - 1, a.off); - drop(); - return m; - elsif stack[depth - 1].loc = lIdx then - m := stack[depth - 1].m; - m.disp := m.disp + INT(a.off); - drop(); - return m; - end; - (* 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; end; - ra := peek(depth - 1); - drop(); - return X.mem(ra, a.off + o); - | else: (* bSlot: the address is in the frame slot a.chunk *) - X.load(r, X.mem(RBP, a.chunk), 8, false); - return X.mem(r, a.off); - end; -end; - -(* The address a names, on top of the stack *) -proc pushAdr*(a: Adr); -var m: X.Mem; r: INT; -begin - if (a.base = bStack) and (a.off = 0) then return; end; (* it is on top already *) - if a.base in {bFrame, bGlobal} then - newEntry(kWord, lAdr, a.off); - if a.base = bGlobal then stack[depth - 1].chunk := a.chunk; end; - return; - 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 - m := place(a, -1); r := target(); - else - r := target(); m := place(a, r); - end; - X.lea(r, m); - computed(kWord); -end; - -proc pushVar*(a: Adr; size: INT; signed: BOOL; k: Kind); -var m: X.Mem; r: INT; -begin - r := inPlace; - inPlace := -1; - if r >= XmmVar then r := r - XmmVar; end; - if (a.base = bReg) and (regAt(a) = r) then - newEntry(k, lInto, r); - return; - end; - if a.base = bReg then - newEntry(k, lHeld, regAt(a)); - return; - 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 - m := place(a, -1); - newMem(lMem, m, k, size, signed); - return; - end; - (* in the order pushAdr explains *) - if a.base = bStack then - m := place(a, -1); r := target(); - else - r := target(); m := place(a, r); - end; - if k in {kF32, kF64} then X.movsXM(xTarget(), m, size = 4); - else X.load(r, m, size, signed); end; - computed(k); -end; - -proc pushProc*(c: INT; ext: BOOL); -var r: INT; -begin - r := target(); - if ext then X.load(r, X.memRip(c, 0), 8, false); - else X.lea(r, X.memRip(c, 0)); end; - computed(kWord); -end; - -(* The slot of the variable in xmm register x *) -proc homeOf(x: INT): X.Mem; -begin - return X.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. *) -proc popVar*(a: Adr; size: INT); -var r: INT; v: I64; c, fl: BOOL; -begin - if (a.base = bReg) and isReal(depth - 1) then - xValueTo(depth - 1, regAt(a)); - drop(); - X.movsMX(homeOf(regAt(a)), regAt(a), false); (* written through, as xHome says *) - return; - end; - if a.base = bReg then - c, v := topConst(); - if c then X.movRI(regAt(a), v); - elsif peek(depth - 1) # regAt(a) then X.movRR(regAt(a), peek(depth - 1)); end; (* else it is there, lInto *) - drop(); - return; - end; - c, v := topConst(); - if c and fits32(v) then - drop(); - X.storeI(place(a, RCX), INT(v), size); - return; - end; - if c then r := RAX; X.movRI(RAX, v); - else r := peek(depth - 1); end; - fl := (stack[depth - 1].loc # lConst) and isReal(depth - 1); - drop(); - if fl then X.movsMX(place(a, RCX), r, size = 4); - else X.store(place(a, RCX), r, size); end; -end; - -(* Register src to dst, an xmm register's if fl *) -proc movReg(fl: BOOL; dst, src: INT); -begin - if fl then X.movX(dst, src); else X.movRR(dst, src); end; -end; - -(* The two values on top, of one kind, change places. *) -proc swap*; -var e: Entry; x, y, t: INT; rx, ry, fl: BOOL; -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); end; - if stack[y].loc in {lIdx, lMem} then _ := loaded(y); end; - rx := stack[x].loc = lReg; - ry := stack[y].loc = lReg; - fl := isReal(y); - if fl then t := 0; else t := RAX; end; (* xmm0, or rax *) - if rx and ry then - movReg(fl, t, regOf(x)); - movReg(fl, regOf(x), regOf(y)); - movReg(fl, regOf(y), t); - elsif rx then - owner[x mod NumRegs] := -1; - movReg(fl, claim(y, stack[y].k), regOf(x)); - elsif ry then - owner[y mod NumRegs] := -1; - movReg(fl, 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. *) -proc copyBytes(size: I64); -var o, n: I64; -begin - if size > 64 then - X.movRI(RCX, size); - X.repMovsb(); - return; - end; - o := 0; - while o < size do - n := 8; - while n > size - o do n := n div 2; end; - X.load(RCX, X.mem(RSI, o), INT(n), false); - X.store(X.mem(RDI, o), RCX, INT(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. *) -proc copyBlock*(size, off: I64); -begin - clobberArgs(); - popTo(RSI); - popTo(RDI); - if off # 0 then X.lea(RDI, X.mem(RDI, off)); end; - copyBytes(size); -end; - -(* Pops a source's address, and copies size bytes to a: for a slice in - registers, its two words into them. *) -proc copyTo*(a: Adr; size: I64); -begin - clobberArgs(); - popTo(RSI); - if a.base = bReg then - X.load(a.chunk, X.mem(RSI, 0), 8, false); - X.load(a.hi, X.mem(RSI, 8), 8, false); - return; - end; - X.lea(RDI, place(a, RDI)); - copyBytes(size); -end; - -proc zeroVar*(a: Adr; size: I64); -begin - clobberArgs(); - X.lea(RDI, place(a, RDI)); - X.movRI(RCX, size); - X.movRI(RAX, 0); - X.repStosb(); -end; - -(* Operations *) - -(* n if v is 2^n, which is 0 for 1; -1 if v isn't a power of two *) -proc exactLog2(v: I64): INT; -var n: INT; -begin - n := 0; - while (v > 1) and ((v & 1) = 0) do v := v shr 1; INC(n); end; - if v # 1 then n := -1; end; - return 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 *) -proc mulI(r: INT; v: I64); -begin - if exactLog2(v) > 0 then X.shiftI(X.shShl, r, exactLog2(v)); - elsif v # 1 then X.imulI(r, INT(v)); end; -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 *) -proc cmpI(r: INT; v: I64); -begin - if v = 0 then X.testRR(r, r); - elsif fits32(v) then X.aluI(X.aluCmp, r, INT(v)); - else X.movRI(RDX, v); X.alu(X.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). *) -proc divPow2(sy: Scan.Sym; r, k: INT; unsign: BOOL); -begin - (* unsigned: div shifts right; mod keeps the low k bits, by shifting - them up to the top and back down *) - if unsign then - if sy = Scan.sDiv then X.shiftI(X.shShr, r, k); - else X.shiftI(X.shShl, r, 64 - k); X.shiftI(X.shShr, r, 64 - k); end; - return; - 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. *) - X.movRR(RCX, r); - X.shiftI(X.shSar, RCX, 63); - X.shiftI(X.shShr, RCX, 64 - k); - X.alu(X.aluAdd, RCX, r); - X.shiftI(X.shSar, RCX, k); - if sy = Scan.sDiv then X.movRR(r, RCX); - else X.shiftI(X.shShl, RCX, k); X.alu(X.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. *) -proc divTrap(bits, y: INT); -var L: INT; -begin - L := NoLabel; - cmpI(y, -1); - X.jcc(X.ccNE, L); - cmpI(RAX, I64(-1) shl (bits - 1)); - X.jcc(X.ccNE, L); - X.shiftI(X.shShl, RAX, 64 - bits); - X.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] *) -proc topInMem: BOOL; -begin - return (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 with y. *) -proc operands: (INT, INT); -var v: I64; c: BOOL; y: INT; -begin - c, v := topConst(); - if c then X.movRI(RCX, v); y := RCX; else y := peek(depth - 1); end; - drop(); - return top(), y; -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]. *) -proc realOp(sy: Scan.Sym; k: Kind); -var f: BOOL; c, x, y: INT; m: X.Mem; -begin - f := k = kF32; - match sy of - | sPlus: c := 58H; (* addsd, or addss for an F32 *) - | sMinus: c := 5CH; (* subsd, subss *) - | sTimes: c := 59H; (* mulsd, mulss *) - | else: c := 5EH; (* divsd, divss *) - end; - if stack[depth - 1].loc in {lConst, lMem, lFrame} then - match stack[depth - 1].loc of - | lConst: m := realConst(stack[depth - 1].val); - | lMem: m := stack[depth - 1].m; - | else: m := X.mem(RBP, stack[depth - 1].val); - end; - drop(); - X.sseM(c, top(), m, f); - else - y := peek(depth - 1); - drop(); - x := top(); - X.sse(c, x, y, f); - end; -end; - -(* The group 1 operation of +, -, &, | and xor *) -proc aluOf(sy: Scan.Sym): INT; -begin - match sy of - | sPlus: return X.aluAdd; - | sMinus: return X.aluSub; - | sAmp: return X.aluAnd; - | sBar: return X.aluOr; - | else: return X.aluXor; - end; -end; - -const - (* the condition codes of the comparisons, from sEql: = # < <= > >= *) - CcSigned: [6]INT = [X.ccE, X.ccNE, X.ccL, X.ccLE, X.ccG, X.ccGE]; - CcUnsigned: [6]INT = [X.ccE, X.ccNE, X.ccB, X.ccBE, X.ccA, X.ccAE]; - -(* The two values on top, the left op the right, an integer of size - bytes, signed or not, brought back to its width. *) -proc op*(sy: Scan.Sym; k: Kind; size: INT; signed: BOOL); -var v, o: I64; r, y, sh, bits: INT; c: BOOL; m: X.Mem; -begin - if k in {kF32, kF64} then realOp(sy, k); return; 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 (((sy = Scan.sPlus) or (sy = Scan.sTimes) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor))) and (stack[depth - 2].loc = lConst) - and (stack[depth - 1].loc # lConst) then swap(); end; - c, v := topConst(); - (* A word's offset (see Entry) 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 ((((sy = Scan.sPlus) or (sy = Scan.sMinus))) or ((sy = Scan.sTimes) and c and fits32(v))) then - o := takeOff(depth - 2); - if sy = Scan.sTimes then o := o * v; - elsif c and fits32(v) then - if sy = Scan.sPlus then o := o + v; else o := o - v; end; - drop(); - if not (stack[depth - 1].loc in {lReg, lHeld}) then _ := top(); end; - putOff(o); - return; - elsif sy = Scan.sPlus then o := o + takeOff(depth - 1); - else o := o - takeOff(depth - 1); end; - end; - sh := -1; - if c and (((sy = Scan.sTimes) or (sy = Scan.sDiv) or (sy = Scan.sMod))) then sh := exactLog2(v); end; - if c and (sh >= 1) then - drop(); - r := top(); - if sy = Scan.sTimes then X.shiftI(X.shShl, r, sh); else divPow2(sy, r, sh, not signed); end; - elsif c and fits32(v) and (((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sBar) or (sy = Scan.sXor) or (sy = Scan.sAmp) or (sy = Scan.sTimes) or (sy = Scan.sShl) or (sy = Scan.sShr))) then - drop(); - r := top(); - match sy of - | sTimes: X.imulI(r, INT(v)); - | sShl: X.shiftI(X.shShl, r, INT(v & I64(bits - 1))); - | sShr: - if signed then X.shiftI(X.shSar, r, INT(v & I64(bits - 1))); - else X.shiftI(X.shShr, r, INT(v & I64(bits - 1))); end; - | else: X.aluI(aluOf(sy), r, INT(v)); - end; - elsif topInMem() and (((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor))) then - m := stack[depth - 1].m; - drop(); - r := top(); - X.aluM(aluOf(sy), r, m); - else - r, y := operands(); - if ((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor)) then - X.alu(aluOf(sy), r, y); - elsif sy = Scan.sTimes then - X.imul(r, y); - elsif ((sy = Scan.sDiv) or (sy = Scan.sMod)) then - X.movRR(RAX, r); - if not signed then - X.movRI(RDX, 0); X.unary(6, y); (* div *) - else - (* 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); end; - X.cqo(); X.unary(7, y); (* idiv, of rdx:rax, which cqo made from rax *) - end; - if sy = Scan.sDiv then X.movRR(r, RAX); else X.movRR(r, RDX); end; - else (* sShl, sShr *) - (* the count modulo the width: the machine takes it modulo 64 *) - if y # RCX then X.movRR(RCX, y); end; - if bits < 64 then X.aluI(X.aluAnd, RCX, bits - 1); end; - if sy = Scan.sShl then X.shift(X.shShl, r); - elsif signed then X.shift(X.shSar, r); - else X.shift(X.shShr, r); end; - end; - end; - if bits < 64 then X.extend(r, size, signed); end; - stack[depth - 1].k := k; - if o # 0 then putOff(o); end; -end; - -(* The left op the right of the two values on top, as a BOOL *) -proc compare*(sy: Scan.Sym; k: Kind; signed: BOOL); -var f: BOOL; r, x, y, i: INT; v: I64; c: BOOL; m: X.Mem; -begin - i := INT(sy) - INT(Scan.sEql); - if k in {kF32, kF64} then - 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. *) - match sy of - | sEql: X.ucomis(x, y, f); X.setCC(X.ccE, r); X.setCC(X.ccNP, RCX); X.alu(X.aluAnd, r, RCX); - | sNeq: X.ucomis(x, y, f); X.setCC(X.ccNE, r); X.setCC(X.ccP, RCX); X.alu(X.aluOr, r, RCX); - | sLss: X.ucomis(y, x, f); X.setCC(X.ccA, r); - | sLeq: X.ucomis(y, x, f); X.setCC(X.ccAE, r); - | sGtr: X.ucomis(x, y, f); X.setCC(X.ccA, r); - | else: X.ucomis(x, y, f); X.setCC(X.ccAE, r); - end; - computed(kWord); - else - c, v := topConst(); - if c then - drop(); r := top(); cmpI(r, v); - elsif topInMem() then - m := stack[depth - 1].m; drop(); r := top(); X.aluM(X.aluCmp, r, m); - else - r, y := operands(); X.alu(X.aluCmp, r, y); - end; - if signed then X.setCC(CcSigned[i], r); else X.setCC(CcUnsigned[i], r); end; - end; - stack[depth - 1].k := kWord; -end; - -(* A real is negated by flipping its sign bit, in rax *) -proc neg*(k: Kind; size: INT; signed: BOOL); -var r: INT; -begin - r := top(); - if k in {kF32, kF64} then - X.movqRX(RAX, r); - if k = kF32 then X.btc(RAX, 31); else X.btc(RAX, 63); end; - X.movqXR(r, RAX); - else - X.unary(3, r); (* neg *) - if size < 8 then X.extend(r, size, signed); end; - end; -end; - -proc complement*(size: INT; signed: BOOL); -var r: INT; -begin - r := top(); - X.unary(2, r); (* not *) - if size < 8 then X.extend(r, size, signed); end; -end; - -proc notBool*; -begin - X.aluI(X.aluXor, top(), 1); -end; - -(* The integer on top, brought to size bytes *) -proc narrow*(size: INT; signed: BOOL); -var r: INT; -begin - r := top(); - if size < 8 then X.extend(r, size, signed); end; - 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 *) -proc intToReal*(k: Kind; big: BOOL); -var L1, L2, r, x: INT; f: BOOL; -begin - f := k = kF32; - r := top(); - x := regIn(k, depth - 1); (* its xmm register *) - if big then - (* above high(I64): halve, keeping the low bit, and double *) - L1 := NoLabel; L2 := NoLabel; - X.testRR(r, r); - X.jcc(X.ccS, L1); - X.cvtsi2s(x, r, f); - X.jmp(L2); - X.fixLink(L1); - X.movRR(RCX, r); - X.shiftI(X.shShr, RCX, 1); - X.aluI(X.aluAnd, r, 1); - X.alu(X.aluOr, RCX, r); - X.cvtsi2s(x, RCX, f); - X.sse(58H, x, x, f); (* adds it to itself: doubles *) - X.fixLink(L2); - else - X.cvtsi2s(x, r, f); - end; - stack[depth - 1].k := k; -end; - -(* The real of kind k on top, truncated to an integer *) -proc realToInt*(k: Kind); -var x: INT; -begin - x := top(); - X.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 *) -proc realToReal*(k: Kind); -var x: INT; -begin - x := top(); - X.sse(5AH, x, x, k = kF32); (* cvtss2sd, or cvtsd2ss *) - if k = kF32 then stack[depth - 1].k := kF64; else stack[depth - 1].k := kF32; end; -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. *) -proc compareSeq*(a, b: I64; shift: INT; eq: BOOL); -var differ, r: INT; -begin - clobberArgs(); - r := target(); - X.load(RCX, X.mem(RBP, b + 8), 8, false); - X.aluM(X.aluCmp, RCX, X.mem(RBP, a + 8)); - differ := NoLabel; - X.jcc(X.ccNE, differ); - X.load(RSI, X.mem(RBP, b), 8, false); - X.load(RDI, X.mem(RBP, a), 8, false); - if shift > 0 then X.shiftI(X.shShl, RCX, shift); end; - (* repe cmpsb with rcx = 0 leaves the flags alone, so make them say - equal first, which is right if there are no bytes *) - X.alu(X.aluCmp, RCX, RCX); - X.repeCmpsb(); - X.fixLink(differ); - if eq then X.setCC(X.ccE, r); else X.setCC(X.ccNE, r); end; - 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. *) -proc errorText*(tmp: I64); -var L: INT; -begin - popTo(RAX); - X.movRI(RCX, 0); - L := NoLabel; - X.testRR(RAX, RAX); - X.jcc(X.ccE, L); - X.load(RCX, X.mem(RAX, 0), 8, false); - X.lea(RAX, X.mem(RAX, 8)); - X.fixLink(L); - X.store(X.mem(RBP, tmp), RAX, 8); - X.store(X.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. *) -proc incDec*(size: INT; signed, dec: BOOL); -var r, y, o: INT; v: I64; a: Adr; c: BOOL; -begin - c, v := topConst(); - if dec then o := X.aluSub; else o := X.aluAdd; end; - if c and fits32(v) then - drop(); - a.base := bStack; a.off := 0; - X.aluMI(o, place(a, RCX), INT(v), size); - return; - end; - r, y := operands(); - drop(); - X.load(RAX, X.mem(r, 0), size, signed); - X.alu(o, RAX, y); - X.store(X.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 *) -proc incDecReg*(r, size: INT; signed, dec: BOOL); -var y, o: INT; v: I64; c: BOOL; -begin - if dec then o := X.aluSub; else o := X.aluAdd; end; - c, v := topConst(); - if c and fits32(v) then X.aluI(o, r, INT(v)); - else y := top(); X.alu(o, r, y); end; - drop(); - if size < 8 then X.extend(r, size, signed); end; -end; - -(* The pointer on top, which NEW got, to size zero bytes unless nil *) -proc zeroNew*(size: I64); -var L, r: INT; -begin - clobberArgs(); - r := top(); - L := NoLabel; - X.testRR(r, r); - X.jcc(X.ccE, L); - X.movRR(RDI, r); - X.movRI(RCX, size); - X.movRI(RAX, 0); - X.repStosb(); - X.fixLink(L); -end; - -(* CAS(p, old, new), XCHG(p, v) or XADD(p, v), from the stack: the - result where p was *) -proc atomic*(which: INT); -var r, n: INT; -begin - if which = Sym.bCas then readMems(depth - 3); else readMems(depth - 2); end; (* what it writes may be one *) - if which = Sym.bCas then n := top(); drop(); end; - popTo(RAX); (* cmpxchg compares with rax, so CAS's old value goes there *) - r := top(); - match which of - | Sym.bCas: X.lockCmpxchg(X.mem(r, 0), n); X.setCC(X.ccE, r); - | Sym.bXchg: X.xchg(X.mem(r, 0), RAX); X.movRR(r, RAX); - | else: X.lockXadd(X.mem(r, 0), RAX); X.movRR(r, RAX); - 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. *) -proc sysCall*(n: INT); -const SysRegs: [7]INT = [RAX, RDI, RSI, RDX, R10, R8, R9]; -var i: INT; -begin - clobberArgs(); - spillBelow(depth); - for i := 0 to n - 1 do valueTo(depth - n + i, SysRegs[i]); end; - for i := 1 to n do drop(); end; - X.syscall(); - X.movRR(target(), RAX); - computed(kWord); -end; - -proc fence*; -begin - X.mfence(); -end; - -(* Jumps. A label is the chain of the jumps to it, until it is placed. *) - -proc jump*(var L: INT); -begin - X.jmp(L); -end; - -(* Pops a BOOL, and jumps if it is when *) -proc jumpIf*(var L: INT; when: BOOL); -var r: INT; -begin - r := peek(depth - 1); - drop(); - X.testRR(r, r); - if when then X.jcc(X.ccNE, L); else X.jcc(X.ccE, L); end; -end; - -(* Pops two integers, and jumps if the left op the right *) -proc jumpCmp*(sy: Scan.Sym; signed: BOOL; var L: INT); -var r, y, i: INT; v: I64; c: BOOL; m: X.Mem; -begin - i := INT(sy) - INT(Scan.sEql); - (* a comparison changes neither: a variable's register will do *) - c, v := topConst(); - if c then - drop(); r := peek(depth - 1); cmpI(r, v); - elsif topInMem() then - m := stack[depth - 1].m; drop(); r := peek(depth - 1); X.aluM(X.aluCmp, r, m); - else - y := peek(depth - 1); drop(); r := peek(depth - 1); X.alu(X.aluCmp, r, y); - end; - drop(); - if signed then X.jcc(CcSigned[i], L); else X.jcc(CcUnsigned[i], L); end; -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. *) -proc jumpOut*(sy: Scan.Sym; signed: BOOL; var L: INT); -begin - spillBelow(depth - 2); - jumpCmp(sy, 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. *) -proc condValue*(notOp: Scan.Sym; signed: BOOL; fj, tj: INT); -var r, e: INT; -begin - jumpOut(notOp, signed, fj); - X.fixLink(tj); - r := target(); - X.movRI(r, 1); - e := NoLabel; - X.jmp(e); - X.fixLink(fj); - X.movRI(r, 0); - X.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. *) -proc jumpBack*(top: INT); -begin - X.jmpBack(top); -end; - -proc fix*(L: INT); -begin - X.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. *) -proc jumpTable*(slot, lo: I64; n, elseAt: INT; var endL: INT): INT; -const TableAt = 17; -var start: INT; -begin - X.load(RAX, X.mem(RBP, slot), 8, false); - if lo # 0 then X.aluI(X.aluSub, RAX, INT(lo)); end; - X.aluI(X.aluCmp, RAX, n - 1); - if elseAt # NoLabel then X.jccBack(X.ccA, elseAt); else X.jcc(X.ccA, endL); end; - start := Chunk.pc; - X.lea(RCX, X.here()); - X.load(RAX, X.memIdx(RCX, RAX, 4, TableAt), 4, true); - X.alu(X.aluAdd, RAX, RCX); - X.jmpR(RAX); - if Chunk.pc # start + TableAt then Diag.fatal("internal error: the jump table is not where it was said"); end; - return start; -end; - -(* The next entry of the table that jumpTable started at table: the - code at target *) -proc tableEntry*(table, target: INT); -begin - Chunk.put4(target - table); -end; - -proc alignLoop*; -begin - X.align(32); -end; - -proc joinJumps*(L1, L2: INT): INT; -begin - return X.joinLinks(L1, L2); -end; - -proc fixTo*(L, top: INT); -begin - X.fixLinkTo(L, top); -end; - -(* Checks *) - -const - NoBase = -2; (* a Mem that is no memory *) - ARegister = -3; (* a Mem that is no memory but a register, its index *) - -(* The name s, interned *) -proc internStr(s: []U8): INT; -begin - return Scan.intern(ADR(s[0]), LEN(s)); -end; - -(* 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. *) -proc check(cc, what: INT; p: Diag.Pos; ra: INT; m: X.Mem; n: I64; name: INT); -begin - if numFails > LEN(fails) - 1 then - _ := Scan.mark(Diag.say("more than {} checks in one procedure", [Fmt.int(LEN(fails))])); - return; - end; - fails[numFails].L := NoLabel; - X.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 *) -proc endFails; -var i, line, col: INT; f: Fail; -begin - for i := 0 to numFails - 1 do - f := fails[i]; - X.fixLink(f.L); - line, col := Scan.lineCol(f.at); - Chunk.noteLine(line, col); - if f.ra # RAX then X.movRR(RAX, f.ra); end; - if f.m.base = NoBase then X.movRI(RCX, f.n); - elsif f.m.base = ARegister then X.movRR(RCX, f.m.index); - else X.load(RCX, f.m, 8, false); end; - if f.name >= 0 then X.lea(R9, X.memRip(f.name, 0)); end; - if failStubs[f.what] < 0 then - failStubs[f.what] := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr(StubNames[f.what])); - end; - X.callChunk(failStubs[f.what]); - end; - numFails := 0; -end; - -(* For check: a length known here, not in memory *) -proc noMem: X.Mem; -begin - return X.mem(NoBase, 0); -end; - -(* For check: a length in register r, a slice's in registers *) -proc inRegister(r: INT): X.Mem; -var m: X.Mem; -begin - m := X.mem(ARegister, 0); - m.index := r; - return m; -end; - -(* The index on top is below n, unsigned *) -proc checkIndex*(n: I64; p: Diag.Pos); -var r: INT; -begin - r := peek(depth - 1); - cmpI(r, n); - check(X.ccB, 0, p, r, noMem(), n, -1); -end; - -(* The integer on top is a position of an enumeration of n names *) -proc checkEnum*(n: I64; name: INT; p: Diag.Pos); -var r: INT; -begin - r := top(); - cmpI(r, n); - check(X.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. *) -proc checkNil*(reach: I64; p: Diag.Pos); -var r: INT; -begin - if reach <= NilPage then return; end; - r := top(); - X.testRR(r, r); - check(X.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] *) -proc indexOff(size, disp: I64): I64; -begin - if fits32(disp + stack[depth - 1].off * size) then return disp + takeOff(depth - 1) * size; end; - return disp; -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). *) -proc indexSlice*(a: Adr; size: I64; checked: BOOL; p: Diag.Pos); -var m, ml: X.Mem; r: INT; inRax: BOOL; o: I64; -begin - if (a.base = bReg) and (((size = 1) or (size = 2) or (size = 4) or (size = 8))) then - o := 0; - if not checked then o := indexOff(size, 0); end; - r := peek(depth - 1); - if checked then - X.alu(X.aluCmp, r, a.hi); - check(X.ccB, 0, p, r, inRegister(a.hi), 0, -1); - end; - drop(); - newMem(lIdx, X.memIdx(a.chunk, r, INT(size), o), kWord, 8, false); - return; - end; - inRax := a.base = bStack; - if inRax then r := RAX; popTo(RAX); - else r := top(); drop(); end; - if a.base = bReg then - if checked then - X.alu(X.aluCmp, r, a.hi); - check(X.ccB, 0, p, r, inRegister(a.hi), 0, -1); - end; - mulI(r, size); - X.alu(X.aluAdd, r, a.chunk); - else - m := place(a, RCX); - ml := m; ml.disp := ml.disp + 8; - if checked then - X.aluM(X.aluCmp, r, ml); - check(X.ccB, 0, p, r, ml, 0, -1); - end; - mulI(r, size); - X.aluM(X.aluAdd, r, m); - end; - if inRax then X.movRR(target(), RAX); - else _ := claim(depth, kWord); end; (* 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. *) -proc indexArray*(a: Adr; size: I64); -var r, b: INT; o: I64; -begin - if (((size = 1) or (size = 2) or (size = 4) or (size = 8))) and (a.base = bFrame) then - o := indexOff(size, a.off); - r := peek(depth - 1); - drop(); - newMem(lIdx, X.memIdx(RBP, r, INT(size), o), kWord, 8, false); - elsif (((size = 1) or (size = 2) or (size = 4) or (size = 8))) and (a.base = bGlobal) and (stack[depth - 1].loc = lHeld) then - o := indexOff(size, 0); - r := peek(depth - 1); - drop(); - b := target(); - X.lea(b, X.memRip(a.chunk, INT(a.off))); - newMem(lIdx, X.memIdx(b, r, INT(size), o), kWord, 8, false); - else - mulI(top(), size); - pushAdr(a); - op(Scan.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. *) -proc slice*(a: Adr; isArray: BOOL; n, size, tmp: I64; checked: BOOL; p: Diag.Pos); -var m, ml: X.Mem; -begin - popTo(RDX); - popTo(RCX); - if a.base = bSlot then clobberArgs(); end; (* place loads its slot into rdi *) - if a.base = bReg then - ml := inRegister(a.hi); (* a slice in registers *) - else - m := place(a, RDI); - ml := m; ml.disp := ml.disp + 8; - end; - if checked then - (* two checks, both unsigned, so that a negative bound fails too: - hi against the length, then lo against hi *) - if isArray then cmpI(RDX, n); ml := noMem(); - elsif a.base = bReg then X.alu(X.aluCmp, RDX, a.hi); - else X.aluM(X.aluCmp, RDX, ml); end; - check(X.ccBE, 1, p, RCX, ml, n, -1); - X.alu(X.aluCmp, RCX, RDX); - check(X.ccBE, 1, p, RCX, ml, n, -1); - end; - X.movRR(RAX, RDX); - X.alu(X.aluSub, RAX, RCX); - X.store(X.mem(RBP, tmp + 8), RAX, 8); - mulI(RCX, size); - if isArray then X.lea(RAX, m); - elsif a.base = bReg then X.movRR(RAX, a.chunk); - else X.load(RAX, m, 8, false); end; - X.alu(X.aluAdd, RAX, RCX); - X.store(X.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. *) -proc copySlice*(dOff, sOff, size: I64; checked: BOOL; p: Diag.Pos); -var ml: X.Mem; L, E: INT; -begin - clobberArgs(); - X.load(RDX, X.mem(RBP, sOff + 8), 8, false); - if checked then - ml := X.mem(RBP, dOff + 8); - X.movRI(RAX, 0); - X.aluM(X.aluCmp, RDX, ml); - check(X.ccBE, 1, p, RAX, ml, 0, -1); - end; - X.movRR(RCX, RDX); - mulI(RCX, size); - X.load(RSI, X.mem(RBP, sOff), 8, false); - X.load(RDI, X.mem(RBP, dOff), 8, false); - X.alu(X.aluCmp, RDI, RSI); - L := NoLabel; - X.jcc(X.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 *) - X.lea(RSI, X.memIdx(RSI, RCX, 1, -1)); - X.lea(RDI, X.memIdx(RDI, RCX, 1, -1)); - X.std(); - X.repMovsb(); - X.cld(); - E := NoLabel; - X.jmp(E); - X.fixLink(L); - X.repMovsb(); - X.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. *) -proc slicePtr*(size, tmp: I64; checked: BOOL; p: Diag.Pos); -begin - clobberArgs(); - popTo(RDX); - popTo(RCX); - popTo(RDI); - if checked then - X.alu(X.aluCmp, RCX, RDX); - check(X.ccLE, 3, p, RCX, noMem(), 0, -1); - end; - X.movRR(RAX, RDX); - X.alu(X.aluSub, RAX, RCX); - X.store(X.mem(RBP, tmp + 8), RAX, 8); - mulI(RCX, size); - X.alu(X.aluAdd, RCX, RDI); - X.store(X.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. *) - -proc call*(var c: CallInfo); -var - res: ^Sym.Type; i, ni, nf, k, pad, r, first: INT; - onStack: [64]BOOL; late: [2]INT; (* late: the values for r8 and r9 *) -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 (Sym.behindPointer(res) or (res^.form = Sym.fSlice)) then - c.ret := allocTemp(res^.size, res^.align); - if Sym.behindPointer(res) then ni := 1; end; - 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 - if c.isF[i] then - onStack[i] := nf >= 8; - if nf < 8 then INC(nf); end; - else - (* 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]; - elsif c.pair[i] then onStack[i] := ni > 4; - else onStack[i] := ni >= 6; end; - if not onStack[i] then INC(ni); end; - end; - if onStack[i] then INC(k); end; - 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 := 0; - if ((pushed + k) & 1) # 0 then pad := 1; end; - if pad # 0 then X.aluI(X.aluSub, RSP, 8); end; - for i := c.n - 1 to 0 by -1 do - if onStack[i] then - valueTo(first + i, RAX); - X.push(RAX); - end; - end; - ni := 0; nf := 0; - late[0] := -1; late[1] := -1; - if (c.ret # 0) and Sym.behindPointer(res) then X.lea(RDI, X.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 - xValueTo(first + i, nf); - INC(nf); - else - if ni < 4 then valueTo(first + i, IntRegs[ni]); else late[ni - 4] := first + i; end; - INC(ni); - end; - end; - end; - if late[0] >= 0 then valueTo(late[0], RAX); end; - if late[1] >= 0 then valueTo(late[1], R9); end; - if late[0] >= 0 then X.movRR(R8, RAX); end; - for i := 1 to c.n do drop(); end; - (* a procedure taking ... is told in al how many xmm registers it got *) - if c.sig^.variadic then X.movRI(RAX, nf); end; - if c.ext then X.callM(X.memRip(c.chunk, 0)); - elsif c.chunk >= 0 then X.callChunk(c.chunk); - else - (* r11 is scratch: caller-saved, carrying no argument, and free, - as the value stack was spilled above *) - X.load(R11, X.mem(RBP, c.target), 8, false); - X.callR(R11); - end; - if k + pad > 0 then X.aluI(X.aluAdd, RSP, 8 * (k + pad)); end; - (* the variables in xmm registers, which the call may have changed, - from their slots *) - for i := 0 to 3 do - if (regMask & (1 shl (XBit + i))) # 0 then - X.movsXM(XVarRegs[i] - XmmVar, X.mem(RBP, homes[i]), false); - end; - end; - (* 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 - if res^.form = Sym.fSlice then - X.store(X.mem(RBP, c.ret), RAX, 8); - X.store(X.mem(RBP, c.ret + 8), RDX, 8); - elsif Sym.inTwoRegs(res) then - X.movRR(target(), RAX); computed(kWord); - X.movRR(target(), RDX); computed(kWord); - elsif (c.ret = 0) and (res^.form = Sym.fReal) then - X.movX(xTarget(), 0); - computed(kindOf(res)); - elsif c.ret = 0 then - r := target(); - X.movRR(r, RAX); - if res^.form = Sym.fBool then X.extend(r, 1, false); - elsif (res^.form = Sym.fInt) and (res^.size < 8) then X.extend(r, INT(res^.size), res^.signed); end; - computed(kindOf(res)); - end; - 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. *) -proc allocTemp*(size, align: I64): I64; -begin - if align < 1 then align := 1; end; - frameTop := Sym.alignUp(frameTop + size, align); - if frameTop > frameMax then frameMax := frameTop; end; - return -frameTop; -end; - -proc allocPerm*(size, align: I64): I64; -var s: I64; -begin - s := allocTemp(size, align); - permTop := frameTop; - return s; -end; - -proc tempMark*: I64; -begin - return frameTop; -end; - -(* The slots allocated since the mark m are free again, but those - allocPerm made stay *) -proc releaseTemps*(m: I64); -begin - if m < permTop then m := permTop; end; - 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. *) -proc 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). *) -proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj); -var p: ^Sym.Obj; ni, nf, k: INT; stackOff: I64; f: BOOL; -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 Sym.behindPointer(resType) then - 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 - p^.ind := p^.isVar or (Sym.isAggregate(p^.typ) and (p^.typ^.form # Sym.fSlice)); - f := (p^.typ^.form = Sym.fReal) and not p^.isVar; - if (p^.typ^.form = Sym.fSlice) and not p^.isVar then - (* its two words, in two registers or both on the stack *) - if ni <= 4 then - p^.val := allocPerm(16, 8); - for k := 0 to 1 do - inReg[numIn] := IntRegs[ni]; inSlot[numIn] := p^.val + I64(8 * k); - inSize[numIn] := 8; inObj[numIn] := p; - INC(numIn); INC(ni); - end; - else - p^.val := stackOff; - INC(stackOff, 16); - end; - elsif (f and (nf < 8)) or (not f and (ni < 6)) then - 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 - inReg[numIn] := -1 - nf; INC(nf); - else - inReg[numIn] := IntRegs[ni]; INC(ni); - end; - inSlot[numIn] := p^.val; - inObj[numIn] := p; - if p^.ind then inSize[numIn] := 8; - elsif p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fReal} then inSize[numIn] := INT(p^.typ^.size); - else inSize[numIn] := 8; end; - INC(numIn); - else - 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. *) -proc 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 *) -proc arrivesIn(o: ^Sym.Obj; word: INT): INT; -var i, r: INT; -begin - r := -1; - for i := 0 to numIn - 1 do - if (inObj[i] = o) and (inSlot[i] = o^.val + I64(8 * word)) and (inReg[i] >= 0) then r := inReg[i]; end; - end; - return r; -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. *) -proc keepArrived*(o: ^Sym.Obj); -var r: INT; -begin - r := arrivesIn(o, 0); - if o^.typ^.form = Sym.fSlice then - if (r = RDI) and (arrivesIn(o, 1) = RSI) then o^.reg := RDI; o^.reg2 := RSI; end; - elsif (r = RDI) or (r = RSI) then o^.reg := r; end; -end; - -(* Whether parameter o is kept where it arrived *) -proc keptIn*(o: ^Sym.Obj): BOOL; -begin - return (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. *) -proc useRegs*(mask: INT); -var i, k: INT; p: ^Sym.Obj; -begin - zeroTop := permTop; - regMask := mask; - (* the parameters left in rdi and rsi, as they arrived *) - kept := 0; - p := procParams; - while p # nil do - if ((p^.reg = RDI) or (p^.reg = RSI)) then kept := kept | (1 shl p^.reg); end; - if ((p^.reg2 = RDI) or (p^.reg2 = RSI)) then kept := kept | (1 shl p^.reg2); end; - p := p^.next; - end; - k := 0; - for i := 0 to 4 do - if (mask & (1 shl i)) # 0 then INC(k); end; - end; - if k > 0 then saveAt := allocPerm(8 * k, 8); end; - 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 *) -proc xHome*(r: INT; slot: I64); -begin - homes[r - XVarRegs[0]] := slot; -end; - -proc markCode*(var m: CodeMark); -begin - m.pc := Chunk.pc; m.fixups := Chunk.numFixups; m.lines := Chunk.numLines; m.said := X.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 *) -proc rewind*(m: CodeMark); -begin - Chunk.rewindTo(m.pc, m.fixups, m.lines); - X.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 *) -proc redo*(m: CodeMark); -begin - Chunk.rewindTo(m.pc, m.fixups, m.lines); - X.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. *) -proc enterBody*(c, line: INT); -var i, loop, r: INT; n: I64; p: ^Sym.Obj; -begin - Chunk.beginChunk(c); - codeChunk := c; - Chunk.noteLine(line, 1); (* a declaration starts a line *) - X.push(RBP); - X.movRR(RBP, RSP); - X.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 *) - Chunk.put1(48H); Chunk.put1(81H); Chunk.put1(0ECH); - frameFix := Chunk.pc; Chunk.put4(0); - n := (Sym.alignUp(zeroTop, 8) - paramTop) div 8; - if n > 0 then X.movRI(RAX, 0); end; - if n <= 4 then - for i := 1 to INT(n) do X.store(X.mem(RBP, -paramTop - I64(8 * i)), RAX, 8); end; - else - (* a quadword at a time: r10 runs from -n up to 0, and the store's - address is scaled by it *) - X.movRI(R10, -n); - loop := Chunk.pc; - X.store(X.memIdx(RBP, R10, 8, -paramTop), RAX, 8); - X.aluI(X.aluAdd, R10, 1); - X.jccBack(X.ccNE, loop); - end; - (* each register that holds a variable is saved, for the caller, and - zeroed, as a variable starts at zero *) - Chunk.setSaves(c, regMask & ((1 shl XBit) - 1), INT(saveAt)); - n := 0; - for i := 0 to 4 do - if (regMask & (1 shl i)) # 0 then - X.store(X.mem(RBP, saveAt + 8 * n), VarRegs[i], 8); - X.movRI(VarRegs[i], 0); - INC(n); - end; - 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 & (1 shl (XBit + i))) # 0 then - X.movRI(RAX, 0); - X.movqXR(XVarRegs[i] - XmmVar, RAX); - end; - 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 - X.movsMX(X.mem(RBP, inSlot[i]), -1 - inReg[i], false); - if inObj[i]^.reg # 0 then X.movX(inObj[i]^.reg - XmmVar, -1 - inReg[i]); end; - elsif (inObj[i] # nil) and (inObj[i]^.reg # 0) then - r := inObj[i]^.reg; - if inSlot[i] # inObj[i]^.val then r := inObj[i]^.reg2; end; - if r # inReg[i] then X.movRR(r, inReg[i]); end; (* else it is kept where it is *) - if inSize[i] < 8 then X.extend(r, inSize[i], inObj[i]^.typ^.signed); end; - else - X.store(X.mem(RBP, inSlot[i]), inReg[i], inSize[i]); - end; - end; - (* 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 - if (p^.reg # 0) and (p^.val > 0) then - if p^.typ^.form = Sym.fReal then - X.movsXM(p^.reg - XmmVar, X.mem(RBP, p^.val), p^.typ^.size = 4); - elsif p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet} then - X.load(p^.reg, X.mem(RBP, p^.val), INT(p^.typ^.size), p^.typ^.signed); - else - X.load(p^.reg, X.mem(RBP, p^.val), 8, false); - if p^.typ^.form = Sym.fSlice then X.load(p^.reg2, X.mem(RBP, p^.val + 8), 8, false); end; - end; - 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. *) -proc resultTo*(off: I64; size: INT); -var r: INT; fl: BOOL; -begin - r := top(); - fl := isReal(depth - 1); - drop(); - X.load(RCX, X.mem(RBP, retSlot), 8, false); - if fl then X.movsMX(X.mem(RCX, off), r, size = 4); - else X.store(X.mem(RCX, off), r, size); end; -end; - -(* Pops an address, and copies size bytes from it to the result, off - bytes into it. *) -proc copyResult*(off, size: I64); -begin - clobberArgs(); - popTo(RSI); - X.load(RDI, X.mem(RBP, retSlot), 8, false); - if off # 0 then X.lea(RDI, X.mem(RDI, off)); end; - 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. *) -proc returnJump*; -begin - if resType # nil then - if Sym.behindPointer(resType) then - X.load(RAX, X.mem(RBP, retSlot), 8, false); - elsif Sym.inTwoRegs(resType) then - popTo(RDX); - popTo(RAX); - elsif resType^.form = Sym.fReal then - xValueTo(depth - 1, 0); - drop(); - else - popTo(RAX); - end; - end; - X.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. *) -proc tryAlign*; -begin - X.aluI(X.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. *) -proc tryReturn*(slot: I64); -var f: ^Sym.Obj; -begin - if Sym.behindPointer(resType) then - X.load(RDI, X.mem(RBP, retSlot), 8, false); - X.movRI(RCX, resType^.size); - X.movRI(RAX, 0); - X.repStosb(); - f := resType^.fields; - while f^.next # nil do f := f^.next; end; - X.load(RCX, X.mem(RBP, slot), 8, false); - X.load(RDX, X.mem(RBP, retSlot), 8, false); - X.store(X.mem(RDX, f^.val), RCX, 8); - X.load(RAX, X.mem(RBP, retSlot), 8, false); - elsif Sym.inTwoRegs(resType) then - X.load(RDX, X.mem(RBP, slot), 8, false); - X.movRI(RAX, 0); - else - X.load(RAX, X.mem(RBP, slot), 8, false); - end; - X.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. *) -proc endProc*(c: INT; open: BOOL): ERROR; -var n: I64; i: INT; -begin - codeChunk := -1; - if (depth # 0) or (pushed # 0) then Diag.fatal("internal error: stack depth"); end; - if open then - if Sym.behindPointer(resType) then - X.load(RDI, X.mem(RBP, retSlot), 8, false); - X.movRI(RCX, resType^.size); - X.movRI(RAX, 0); - X.repStosb(); - X.load(RAX, X.mem(RBP, retSlot), 8, false); - else - X.movRI(RAX, 0); - if Sym.inTwoRegs(resType) then X.movRI(RDX, 0); end; - X.movqXR(0, RAX); - end; - else - X.dropJumpTo(exitL); - end; - X.fixLink(exitL); - n := 0; - for i := 0 to 4 do - if (regMask & (1 shl i)) # 0 then - X.load(VarRegs[i], X.mem(RBP, saveAt + 8 * n), 8, false); - INC(n); - end; - end; - X.leave(); - X.ret(); - endFails(); - n := Sym.alignUp(frameMax, 16); - if n < 16 then n := 16; end; - if n > 2147483647 then return Scan.mark("frame too big"); end; - Chunk.put4At(frameFix, INT(n)); - (* the listing's text for the sub, which starts 3 bytes (REX.W, opcode, - ModRM) before its immediate *) - if X.listing then X.restate(frameFix - 3, Diag.say("sub rsp, {}", [Fmt.int(INT(n))])); end; - Chunk.endChunk(c); - return nil; -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 what pushed was, and starts it, with the return address - pushed. The stack is empty where it is called, and where it begins. *) -proc deferBegin*(var L: INT): (INT, INT); -var saved: INT; -begin - X.jmp(L); - saved := pushed; - pushed := 1; - return Chunk.pc, saved; -end; - -proc deferEnd*(L, saved: INT); -begin - keepTemps(); - X.ret(); - X.fixLink(L); - pushed := saved; -end; - -proc runDefer*(at: INT); -begin - X.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. mainObj: 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. *) -proc entryPoint*(dynamic: BOOL; first: ^Sym.Module; mainObj: ^Sym.Obj; cExit, exitProc: INT; links: []Link; numLinks: INT): INT; -var entry, start, i: INT; m: ^Sym.Module; -begin - entry := Chunk.newChunk(Chunk.secText, -1, internStr("_start")); - if dynamic then - start := Chunk.newChunk(Chunk.secText, -1, internStr("main")); - Chunk.beginChunk(entry); - (* at the start rdx holds rtld_fini, from the dynamic loader, and the - stack argc, then argv *) - X.movRI(X.RBP, 0); (* no frame above, where a trace stops *) - X.movRR(R9, RDX); (* rtld_fini, the sixth argument *) - X.pop(RSI); (* argc, the second *) - X.movRR(RDX, RSP); (* argv, the third *) - X.aluI(X.aluAnd, RSP, -16); - X.push(RAX); (* padding, so that the next push, the seventh *) - X.push(RSP); (* argument, stack_end, leaves rsp aligned *) - X.movRI(R8, 0); (* fini and init: none *) - X.movRI(RCX, 0); - X.lea(RDI, X.memRip(start, 0)); (* main, the first argument *) - X.callM(X.memRip(Chunk.externChunk(internStr("__libc_start_main")), 0)); - X.ud2(); (* it never returns *) - Chunk.endChunk(entry); - Chunk.beginChunk(start); - X.push(RBP); (* aligns the stack again *) - X.store(X.memRip(argcChunk, 0), RDI, 8); - X.store(X.memRip(argvChunk, 0), RSI, 8); - X.load(RAX, X.memRip(Chunk.externChunk(internStr("exit")), 0), 8, false); - X.store(X.memRip(cExit, 0), RAX, 8); - else - start := entry; - Chunk.beginChunk(entry); - X.load(RAX, X.mem(RSP, 0), 8, false); - X.store(X.memRip(argcChunk, 0), RAX, 8); - X.lea(RAX, X.mem(RSP, 8)); - X.store(X.memRip(argvChunk, 0), RAX, 8); - end; - for i := 0 to numLinks - 1 do - X.lea(RAX, X.memRip(links[i].chunk, 0)); - X.store(X.memRip(links[i].into, 0), RAX, 8); - end; - m := first; - while m # nil do - if m^.used and (m^.body >= 0) then X.callChunk(m^.body); end; - m := m^.next; - end; - if mainObj # nil then X.callChunk(mainObj^.chunk); end; - if (mainObj # nil) and (mainObj^.typ^.base # nil) then X.movRR(RDI, RAX); else X.movRI(RDI, 0); end; - X.callChunk(exitProc); - X.ud2(); (* exit never returns: trap if it does *) - Chunk.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 LEN(failStubs) - 1 do - if failStubs[i] >= 0 then - Chunk.beginChunk(failStubs[i]); - X.load(R8, X.mem(RSP, 0), 8, false); - X.aluI(X.aluSub, R8, 1); - X.aluI(X.aluAnd, RSP, -16); - X.push(RSI); - X.push(RDI); - X.movRR(RSI, RAX); - X.movRI(RDI, i); - X.callChunk(rtFail); - X.ud2(); - Chunk.endChunk(failStubs[i]); - end; - end; - return entry; -end; - -(* A code procedure: its instructions, read by the assembler (X64), - are the whole of chunk c *) -proc codeProc*(c: INT; constExpr: X.ConstFn): ERROR; -begin - Chunk.beginChunk(c); - try X.assemble(constExpr); - Chunk.endChunk(c); - return nil; -end; - -var i: INT; -begin - for i := 0 to LEN(failStubs) - 1 do failStubs[i] := -1; end; - inPlace := -1; - codeChunk := -1; - resetStack(0, 0); - rtFail := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr("fail")); - argcChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argc")); - Chunk.setBss(argcChunk, 8, 8); - argvChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argv")); - Chunk.setBss(argvChunk, 8, 8); -end Gen. diff --git a/self/Item.raz b/self/Item.raz deleted file mode 100644 index 25e0303..0000000 --- a/self/Item.raz +++ /dev/null @@ -1,1729 +0,0 @@ -(* Item: operands, their types, and what they mean. - - The parser describes each operand as an item, 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 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; the machine, which - is Gen. - - An error the seed's `Mark` ended in a jump back to the parser's - recovery point. Here the routine that finds it shows it and returns - `Scan.Failed`, and every routine that calls one passes it up with - `try`, to where the parser reads on: what has been made by then is - what the seed had made when it jumped. So most routines here return an - ERROR, as the last of their results. - - The seed's `Mismatch` of two operands is `mismatchOps` (raz has no - overloading), and what the parser sets, `demoted` and `checks`, has a - setter each, as an exported variable is read-only outside its module. - The seed's `TItem` is `Item` and `TMode` is `Mode`; its procedures begin - in lower case. *) -module Item; -import Fmt, Diag, Scan, Sym, Chunk, Gen; - -type - Mode* = (mConst, mVar, mStack, mProc, mType, mStr, mBuiltin, mCase, mNone, mCond, - mWords); (* two results of a call, on the stack, the first under the second *) - - Item* = record - mode*: Mode; - typ*: ^Sym.Type; - rel*: Scan.Sym; (* mCond: the comparison of the two integers on - the stack, not yet made, as Wirth's compilers - keep a condition *) - relSigned*: BOOL; - fj*, tj*: INT; (* 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*: I64; (* mConst: the value, an F64's bits; mStr: its length *) - base*: Gen.Base; (* mVar: what the address is relative to *) - chunk*: INT; (* mVar with bGlobal, mStr: the chunk; bSlot: the slot *) - off*: I64; (* mVar: added to the base *) - vol*: BOOL; (* mVar: reached through ^VOLATILE *) - isVar*: BOOL; (* mVar: a variable of the program, not a temporary *) - odd*: BOOL; (* mVar: in a packed record, so maybe misaligned *) - ro*: BOOL; (* mVar: another module's exported variable, or part - of one, which only that module changes *) - deref*: BOOL; (* mVar: at an address from a pointer, which may be - nil and isn't tested yet (nilTest) *) - obj*: ^Sym.Obj; (* mProc, mBuiltin, mCase; mVar: the variable named *) - pos*: Diag.Pos; (* where it is in the source, for messages *) - end; - -const - (* the comparison that holds when the one at the same place doesn't, for integers *) - NegatedOps: [6]Scan.Sym = [Scan.sNeq, Scan.sEql, Scan.sGeq, Scan.sGtr, Scan.sLeq, Scan.sLss]; - -const - MaxI64 = 9223372036854775807; - MinI64 = -9223372036854775807 - 1; - -var - demoted*: BOOL; (* address wanted a register variable's address: its - procedure is compiled again, the variable in memory *) - checks*: BOOL; (* the module's index and slice checks are made: it - doesn't say check off *) - result: ^Sym.Type; (* the result of the procedure being compiled, or nil *) - passing: ^Sym.Obj; (* the parameter the argument at passingAt goes to *) - passingAt: Diag.Pos; - -proc setDemoted*(yes: BOOL); -begin - demoted := yes; -end; - -proc setChecks*(yes: BOOL); -begin - checks := yes; -end; - -(* The comparison that holds when op doesn't *) -proc negated(op: Scan.Sym): Scan.Sym; -begin - return NegatedOps[INT(op) - INT(Scan.sEql)]; -end; - -proc isRel(op: Scan.Sym): BOOL; -begin - return (op >= Scan.sEql) and (op <= Scan.sGeq); -end; - -(* Whether op is one of the list: Scan.Sym has too many names for a set *) -proc oneOf(op: Scan.Sym; list: []Scan.Sym): BOOL; -var i: INT; -begin - for i := 0 to LEN(list) - 1 do - if list[i] = op then return true; end; - end; - return false; -end; - -proc bit(f: BOOL): I64; -begin - if f then return 1; end; - return 0; -end; - -(* A message, from a format and the strings that fill it *) -proc say1(f, a: []U8): []U8; -begin - return Diag.say(f, [Fmt.str(a)]); -end; - -proc say2(f, a, b: []U8): []U8; -begin - return Diag.say(f, [Fmt.str(a), Fmt.str(b)]); -end; - -(* Items *) - -proc makeConst*(var x: Item; t: ^Sym.Type; v: I64); -var p: Diag.Pos; -begin - p := x.pos; - x := {}; - 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. *) -proc makeReal*(var x: Item; r: F64); -var p: ^F64; -begin - makeConst(x, Sym.tRConst, 0); - p := ^F64(ADR(x.val)); - p^ := r; -end; - -proc isF32(t: ^Sym.Type): BOOL; -begin - return (t^.form = Sym.fReal) and (t^.size = 4); -end; - -proc realOf*(x: Item): F64; -var v: I64; p: ^F64; -begin - v := x.val; - p := ^F64(ADR(v)); - return p^; -end; - -(* Gives a real constant the real type t, rounded to it. *) -proc realTo(var x: Item; t: ^Sym.Type); -var r: F64; -begin - r := realOf(x); - if isF32(t) then makeReal(x, F64(F32(r))); else makeReal(x, r); end; - x.typ := t; -end; - -(* The current string literal, as an item of its own chunk. *) -proc makeStr*(var x: Item); -begin - x := {}; - x.mode := mStr; - x.typ := Sym.tStr; - x.val := Scan.slen; - x.chunk := Chunk.newChunk(Chunk.secRodata, -1, -1); - Chunk.setData(x.chunk, Scan.strWithZero(), Scan.slen + 1, 1); -end; - -proc frameAdr*(off: I64): Gen.Adr; -var a: Gen.Adr; -begin - a.base := Gen.bFrame; - a.chunk := -1; - a.off := off; - a.hi := 0; - return a; -end; - -proc globalAdr*(c: INT): Gen.Adr; -var a: Gen.Adr; -begin - a.base := Gen.bGlobal; - a.chunk := c; - a.off := 0; - a.hi := 0; - return a; -end; - -(* Where the variable x is, for Gen; a slice in registers has two *) -proc adrOf*(x: Item): Gen.Adr; -var a: Gen.Adr; -begin - a.base := x.base; - a.chunk := x.chunk; - a.off := x.off; - a.hi := 0; - if x.base = Gen.bReg then a.hi := x.obj^.reg2; end; - return a; -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. *) -proc what*(x: Item): []U8; -begin - if (x.mode = mConst) and ((x.typ = Sym.tConst) or (x.typ = Sym.tRConst)) then - return Diag.source(x.pos); - end; - return Sym.typeName(x.typ); -end; - -(* Two operands of different types. Numbers convert, so say how. *) -proc mismatchOps(x, y: Item; xt, yt: ^Sym.Type): ERROR; -var text: []U8; -begin - text := say2("{} and {} are different types", Sym.typeName(xt), Sym.typeName(yt)); - if (Sym.isInt(xt) or (xt^.form = Sym.fReal)) and (Sym.isInt(yt) or (yt^.form = Sym.fReal)) - and (xt # Sym.tConst) and (xt # Sym.tRConst) then - return Scan.markHelp(Diag.join(x.pos, y.pos), text, - say2("convert one to the other's type, as in {}({})", Sym.typeName(xt), Diag.source(y.pos))); - end; - return Scan.markAt(Diag.join(x.pos, y.pos), text); -end; - -(* An item that is not a value, by what it is. *) -proc notValue(x: Item): ERROR; -begin - match x.mode of - | mType: return Scan.markAt(x.pos, say1("{} is a type, not a value", Sym.typeName(x.typ))); - | mBuiltin: return Scan.markAt(x.pos, say1("{} is a built-in procedure, not a value", Scan.nameOf(x.obj^.name))); - | mCase: return Scan.markAt(x.pos, say1("{} is a case, not a value", Scan.nameOf(x.obj^.name))); - | mNone: - if x.obj # nil then return Scan.markAt(x.pos, say1("{} returns nothing", Scan.nameOf(x.obj^.name))); end; - return Scan.markAt(x.pos, "the procedure returns nothing"); - | else: return Scan.markAt(x.pos, "a string can't be an operand"); - end; -end; - -proc makeItem*(var x: Item; o: ^Sym.Obj): ERROR; -begin - x := {}; - x.typ := o^.typ; - x.obj := o; - match o^.cls of - | oConst: - if o^.typ = Sym.tStr then - x.mode := mStr; x.val := o^.val; x.chunk := o^.chunk; - elsif o^.typ^.form in {Sym.fArray, Sym.fRecord} then - (* 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 := Gen.bGlobal; x.chunk := o^.chunk; - else - x.mode := mConst; x.val := o^.val; - end; - | oVar: - x.mode := mVar; - x.ro := (o^.lev = 0) and (o^.home # Sym.curModule); - x.isVar := not x.ro; - if o^.ext then - Gen.pushVar(globalAdr(o^.chunk), 8, false, Gen.kWord); - x.base := Gen.bStack; - elsif o^.lev = 0 then - x.base := Gen.bGlobal; x.chunk := o^.chunk; - elsif o^.ind then - x.base := Gen.bSlot; x.chunk := INT(o^.val); x.off := o^.off; - elsif o^.reg # 0 then - x.base := Gen.bReg; x.chunk := o^.reg; - else - x.base := Gen.bFrame; x.off := o^.val; - end; - | oProc: x.mode := mProc; - | oType: x.mode := mType; - | oBuiltin: x.mode := mBuiltin; - | oCase: x.mode := mCase; - | else: return Scan.mark(say1("{} is not a value", Scan.nameOf(o^.name))); - end; - return nil; -end; - -proc scalarSize*(t: ^Sym.Type): INT; -begin - if t^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fReal} then return INT(t^.size); end; - return 8; -end; - -(* The width an operation on t is brought back to, and whether signed *) -proc intSize(t: ^Sym.Type): INT; -begin - if t^.form = Sym.fInt then return INT(t^.size); end; - return 8; -end; - -proc signed(t: ^Sym.Type): BOOL; -begin - return ((t^.form = Sym.fInt) and t^.signed) or (t^.form = Sym.fConst); -end; - -proc cut(v: I64; t: ^Sym.Type): I64; -begin - if t^.form # Sym.fInt then return v; end; - match t^.size of - | 1: if t^.signed then return I64(I8(v)); end; return I64(U8(v)); - | 2: if t^.signed then return I64(I16(v)); end; return I64(U16(v)); - | 4: if t^.signed then return I64(I32(v)); end; return I64(U32(v)); - | else: return 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. *) -proc usesReals*(p: Diag.Pos); -begin - if (Gen.codeChunk >= 0) and not Chunk.chunks[Gen.codeChunk].reals then - Chunk.setReals(Gen.codeChunk, 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. *) -proc nilTest*(var x: Item); -begin - if (x.mode = mVar) and x.deref then Gen.checkNil(x.off + x.typ^.size, x.pos); end; - x.deref := false; -end; - -(* x's value, on top of the stack *) -proc value*(var x: Item): ERROR; -var f: F32; p: ^U32; -begin - if x.mode = mCond then - if (x.fj = Gen.NoLabel) and (x.tj = Gen.NoLabel) then Gen.compare(x.rel, Gen.kWord, x.relSigned); - else Gen.condValue(negated(x.rel), x.relSigned, x.fj, x.tj); end; - x.mode := mStack; - return nil; - end; - if x.typ^.form = Sym.fReal then usesReals(x.pos); end; - nilTest(x); - match x.mode of - | mConst: - if (x.typ^.form = Sym.fError) and (x.val > 0) then Gen.pushAdr(globalAdr(INT(x.val) - 1)); - elsif isF32(x.typ) then - f := F32(realOf(x)); - p := ^U32(ADR(f)); - Gen.pushConst(Gen.kF32, I64(p^)); - else Gen.pushConst(Gen.kindOf(x.typ), x.val); end; - | mVar: - if not Sym.isScalar(x.typ) then - return Scan.markAt(x.pos, say1("expected a single value, found {}", what(x))); - end; - Gen.pushVar(adrOf(x), scalarSize(x.typ), (x.typ^.form = Sym.fInt) and x.typ^.signed, Gen.kindOf(x.typ)); - | mStack: x.mode := mStack; - | mProc: - if x.obj^.isCode and (x.obj^.typ^.base # nil) and x.obj^.typ^.base^.tuple then - return Scan.markAt(x.pos, "a code procedure with two results can only be called"); - end; - Gen.pushProc(x.obj^.chunk, x.obj^.ext); - | else: return notValue(x); - end; - x.mode := mStack; - return nil; -end; - -(* The address of the variable or string x, on top of the stack *) -proc address*(var x: Item): ERROR; -begin - nilTest(x); - if (x.mode = mVar) and (x.base = Gen.bReg) then - (* 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 := Gen.bFrame; - x.off := x.obj^.val; - end; - if x.mode = mStr then Gen.pushAdr(globalAdr(x.chunk)); - elsif x.mode = mVar then - Gen.pushAdr(adrOf(x)); - x.base := Gen.bStack; x.off := 0; - else return Scan.markAt(x.pos, "expected a variable"); end; - return nil; -end; - -(* x isn't wanted: what it has on the stack is dropped *) -proc discard*(x: Item): ERROR; -var y: Item; -begin - if x.mode = mCond then - y := x; - try value(y); - Gen.drop(); - return nil; - end; - if (x.mode = mStack) or ((x.mode = mVar) and (x.base = Gen.bStack)) then Gen.drop(); end; - if x.mode = mWords then Gen.drop(); Gen.drop(); end; - return nil; -end; - -(* Frames *) - -proc tempItem*(var x: Item; t: ^Sym.Type; off: I64); -var p: Diag.Pos; -begin - p := x.pos; - x := {}; - x.pos := p; - x.mode := mVar; x.typ := t; x.base := Gen.bFrame; x.off := off; -end; - -proc toSlot*(var x: Item): (I64, ERROR); -var s: I64; -begin - try value(x); - s := Gen.allocTemp(8, 8); - Gen.popVar(frameAdr(s), 8); - return s, nil; -end; - -(* Copying *) - -(* x, copied to a temporary *) -proc copyToTemp*(var x: Item): ERROR; -var t: I64; f, g: ^Sym.Obj; a: Gen.Adr; -begin - if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end; - t := Gen.allocTemp(x.typ^.size, x.typ^.align); - if (x.mode = mVar) and (x.base = Gen.bReg) then - (* a slice in registers, which has no address: its words stored *) - a := adrOf(x); - Gen.pushVar(a, 8, false, Gen.kWord); - Gen.popVar(frameAdr(t), 8); - a.off := 8; - Gen.pushVar(a, 8, false, Gen.kWord); - Gen.popVar(frameAdr(t + 8), 8); - tempItem(x, x.typ, t); - return nil; - end; - if x.mode = mWords then - (* the second result is on top, so it is popped first *) - f := x.typ^.fields; g := f^.next; - Gen.popVar(frameAdr(t + g^.val), scalarSize(g^.typ)); - Gen.popVar(frameAdr(t + f^.val), scalarSize(f^.typ)); - tempItem(x, x.typ, t); - return nil; - end; - try address(x); - Gen.copyTo(frameAdr(t), x.typ^.size); - tempItem(x, x.typ, t); - return nil; -end; - -(* A slice made from an address on the stack and a length. *) -proc sliceOf*(var x: Item; t: ^Sym.Type; len: I64); -var s: I64; -begin - s := Gen.allocTemp(16, 8); - Gen.popVar(frameAdr(s), 8); - Gen.pushConst(Gen.kWord, len); - Gen.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). *) -proc widens(s, t: ^Sym.Type): BOOL; -begin - return ((s = Sym.tInt) and Sym.same(t, Sym.tI64)) or ((s = Sym.tUInt) and Sym.same(t, Sym.tU64)); -end; - -(* Another module's exported variable can be read, not changed, nor - handed to anything that could change it (report section 3). *) -proc notReadOnly*(x: Item): ERROR; -begin - if x.ro then - return Scan.markAt(x.pos, Diag.say("{} is {}'s, and can't be changed outside it", - [Fmt.str(Diag.source(x.pos)), Fmt.str(Scan.nameOf(x.obj^.home^.name))])); - end; - return nil; -end; - -(* An error in x's type; if x is an argument, a note at the parameter - it goes to. *) -proc mismatch(x: Item; text: []U8): ERROR; -begin - Diag.error(x.pos, text); - if (passing # nil) and (x.pos.f = passingAt.f) and (x.pos.a = passingAt.a) and (x.pos.b = passingAt.b) then - Diag.note(passing^.pos, say1("it goes to {}, declared here", Scan.nameOf(passing^.name))); - end; - return Scan.Failed; -end; - -proc coerce*(var x: Item; t: ^Sym.Type): ERROR; -var s: ^Sym.Type; tmp: I64; -begin - if x.mode = mCond then try value(x); end; - s := x.typ; - if x.mode = mStr then - if (t^.form = Sym.fSlice) and (t^.base = Sym.tU8) then - try address(x); sliceOf(x, t, x.val); - elsif (t^.form = Sym.fPtr) and (t^.base = Sym.tU8) then - try address(x); x.mode := mStack; x.typ := t; - elsif (t^.form = Sym.fArray) and (t^.base = Sym.tU8) and (t^.len >= x.val) then - tmp := Gen.allocTemp(t^.size, 1); - try address(x); - Gen.copyTo(frameAdr(tmp), x.val); - if t^.len > x.val then Gen.zeroVar(frameAdr(tmp + x.val), t^.len - x.val); end; - tempItem(x, t, tmp); - else return mismatch(x, say1("can't use a string as {}", Sym.typeName(t))); end; - return nil; - end; - if x.mode in {mType, mBuiltin, mNone, mCase} then return notValue(x); end; - if Sym.same(s, t) then return nil; end; - if widens(s, t) then x.typ := t; (* the same bits, on a 64-bit target *) - elsif (s = Sym.tRConst) and (t^.form = Sym.fReal) then realTo(x, t); - elsif (s^.form = Sym.fConst) and (t^.form = Sym.fInt) then - if (x.mode = mConst) and not Sym.fits(x.val, t) then - return Scan.markAt(x.pos, Diag.say("{} doesn't fit {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(t))])); - end; - x.typ := t; - elsif (s^.form = Sym.fNil) and (t^.form in {Sym.fPtr, Sym.fProc, Sym.fError}) then - x.typ := t; - elsif (s^.form = Sym.fPtr) and (t^.form = Sym.fPtr) and t^.vol and not s^.vol - and Sym.same(s^.base, t^.base) then - x.typ := t; - elsif (s^.form = Sym.fArray) and (t^.form = Sym.fSlice) and Sym.same(s^.base, t^.base) then - try notReadOnly(x); - if x.vol then return Scan.markAt(x.pos, "can't make a slice through a volatile pointer"); end; - if x.odd then return Scan.markAt(x.pos, "can't make a slice of a field of a packed record"); end; - try address(x); - sliceOf(x, t, s^.len); - elsif (x.mode = mProc) and (t^.form # Sym.fProc) and (s^.base = nil) then - return Scan.markAt(x.pos, say1("{} is a procedure, and returns nothing", Diag.source(x.pos))); - elsif (x.mode = mProc) and (t^.form # Sym.fProc) then - return Scan.markHelp(x.pos, - say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)), - say1("to call it, write {}()", Diag.source(x.pos))); - else - return mismatch(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t))); - end; - return nil; -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. *) -proc coerceExact*(var x: Item; t: ^Sym.Type; help: []U8): ERROR; -var h: []U8; -begin - if widens(x.typ, t) then - h := help; - if LEN(h) = 0 then - h := say2("they don't mix here: write {}({})", Sym.typeName(t), Diag.source(x.pos)); - end; - return Scan.markHelp(x.pos, say2("expected {}, found {}", Sym.typeName(t), what(x)), h); - end; - return coerce(x, t); -end; - -(* dst := src. The address of dst, if it has to be computed, is on the - stack already, under src's. *) -proc assign*(var dst, src: Item): ERROR; -begin - try coerce(src, dst.typ); - if Sym.isScalar(dst.typ) then - try value(src); - Gen.popVar(adrOf(dst), scalarSize(dst.typ)); - else - if dst.vol or src.vol then return Scan.markAt(src.pos, "can't copy through a volatile pointer"); end; - if (src.mode = mVar) and (src.base = Gen.bReg) then try copyToTemp(src); end; (* a slice in registers *) - try address(src); - if dst.base = Gen.bStack then Gen.copyBlock(dst.typ^.size, dst.off); - else Gen.copyTo(adrOf(dst), dst.typ^.size); end; - end; - return nil; -end; - -(* t's name, ending in a zero byte, for Rt.fail *) -proc nameChunk(t: ^Sym.Type): INT; -var s: []U8; p: ^U8; n, c: INT; -begin - s := Sym.typeName(t); - n := LEN(s); - p := Scan.grab(n + 1); - COPY(p[0..n], s); - p[n] := 0; - c := Chunk.newChunk(Chunk.secRodata, -1, -1); - Chunk.setData(c, p, n + 1, 1); - return c; -end; - -(* Selectors *) - -proc deref*(var x: Item): ERROR; -var t: ^Sym.Type; -begin - t := x.typ; - if t^.form # Sym.fPtr then - return Scan.markAt(x.pos, say1("expected a pointer, found {}", Sym.typeName(t))); - end; - if t^.base = nil then - return Scan.markAt(x.pos, say1("{} points to a type never declared", Sym.typeName(t))); - end; - try value(x); - x.mode := mVar; x.base := Gen.bStack; x.off := 0; x.deref := true; - x.typ := t^.base; x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false; - return nil; -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). *) -proc field*(var x: Item; f: ^Sym.Obj): ERROR; -begin - if x.typ^.packd and (f^.typ^.align > 1) then - if x.vol then return Scan.markAt(x.pos, "a field of a packed record can't be volatile"); end; - x.odd := true; - end; - x.off := x.off + f^.val; - x.typ := f^.typ; - return nil; -end; - -proc indexPrep*(var x: Item): ERROR; -begin - nilTest(x); - if x.mode = mStr then try coerce(x, Sym.tBytes); end; - if (x.typ^.form = Sym.fPtr) and (x.typ^.base^.form = Sym.fArray) then - return Scan.markAt(x.pos, "a pointer to an array is indexed as p^[i]"); - end; - if x.typ^.form = Sym.fPtr then try value(x); - elsif not ((x.mode = mVar) and (x.typ^.form in {Sym.fArray, Sym.fSlice})) then - return Scan.markAt(x.pos, say1("expected an array, a slice or a pointer, found {}", what(x))); - end; - return nil; -end; - -(* The index on top, times the size of an element *) -proc scaleBy(s: I64); -begin - if s # 1 then - Gen.pushConst(Gen.kWord, s); - Gen.op(Scan.sTimes, Gen.kWord, 8, true); - end; -end; - -proc index*(var x, y: Item): ERROR; -var t: ^Sym.Type; s: I64; -begin - t := x.typ; - s := t^.base^.size; - if not Sym.isInt(y.typ) then - return Scan.markAt(y.pos, say1("an index is an integer, found {}", what(y))); - end; - if t^.form = Sym.fPtr then - try value(y); - scaleBy(s); - Gen.op(Scan.sPlus, Gen.kWord, 8, false); - x.mode := mVar; x.base := Gen.bStack; x.off := 0; - x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false; - elsif (t^.form = Sym.fArray) and (y.mode = mConst) then - if (y.val < 0) or (y.val >= t^.len) then - return Scan.markAt(y.pos, Diag.say("index {} is out of range for a length of {}", [Fmt.int(y.val), Fmt.int(t^.len)])); - end; - x.off := x.off + y.val * s; - elsif t^.form = Sym.fArray then - try value(y); - if checks then Gen.checkIndex(t^.len, y.pos); end; - if x.base = Gen.bStack then scaleBy(s); Gen.op(Scan.sPlus, Gen.kWord, 8, false); - else Gen.indexArray(adrOf(x), s); x.off := 0; end; - x.base := Gen.bStack; - else - try value(y); - Gen.indexSlice(adrOf(x), s, checks, y.pos); - x.base := Gen.bStack; x.off := 0; x.isVar := true; x.vol := false; x.ro := false; - end; - x.typ := t^.base; - return nil; -end; - -proc sliceLo*(var lo: Item): ERROR; -begin - if not Sym.isInt(lo.typ) then - return Scan.markAt(lo.pos, say1("an index is an integer, found {}", what(lo))); - end; - return value(lo); -end; - -proc slice*(var x, lo, hi: Item): ERROR; -var t, st: ^Sym.Type; tmp: I64; -begin - t := x.typ; - if not Sym.isInt(hi.typ) then - return Scan.markAt(hi.pos, say1("an index is an integer, found {}", what(hi))); - end; - if x.vol then return Scan.markAt(x.pos, "can't make a slice through a volatile pointer"); end; - if x.odd then return Scan.markAt(x.pos, "can't make a slice of a field of a packed record"); end; - if t^.form = Sym.fArray then try notReadOnly(x); end; - try value(hi); - tmp := Gen.allocTemp(16, 8); - if t^.form = Sym.fPtr then Gen.slicePtr(t^.base^.size, tmp, checks, lo.pos); - else Gen.slice(adrOf(x), t^.form = Sym.fArray, t^.len, t^.base^.size, tmp, checks, lo.pos); end; - st := Sym.newType(Sym.fSlice, 16, 8); - st^.base := t^.base; - tempItem(x, st, tmp); - return nil; -end; - -(* Operators *) - -proc neg*(var x: Item): ERROR; -begin - if x.typ^.form = Sym.fReal then - if x.mode = mConst then x.val := x.val xor MinI64; - else try value(x); Gen.neg(Gen.kindOf(x.typ), 8, false); end; - elsif Sym.isInt(x.typ) then - if (x.mode = mConst) and (x.typ^.form = Sym.fConst) and (x.val = MinI64) then - return Scan.markAt(x.pos, "the constant is too big for I64"); - elsif x.mode = mConst then x.val := cut(-x.val, x.typ); - else try value(x); Gen.neg(Gen.kWord, intSize(x.typ), signed(x.typ)); end; - else return Scan.markAt(x.pos, say1("can't negate {}", Sym.typeName(x.typ))); end; - return nil; -end; - -proc notOp*(var x: Item): ERROR; -var L: INT; -begin - if Sym.isInt(x.typ) then - return Scan.markHelp(x.pos, say1("\"not\" needs a BOOL, found {}", what(x)), "the bits of an integer flip with ~"); - end; - if x.typ^.form # Sym.fBool then - return Scan.markAt(x.pos, say1("\"not\" needs a BOOL, found {}", what(x))); - end; - if x.mode = mConst then x.val := 1 - x.val; - elsif x.mode = mCond then - x.rel := negated(x.rel); - L := x.fj; x.fj := x.tj; x.tj := L; - else try value(x); Gen.notBool(); end; - return nil; -end; - -proc complement*(var x: Item): ERROR; -begin - if x.typ^.form = Sym.fBool then - return Scan.markHelp(x.pos, say1("\"~\" needs an integer, found {}", what(x)), "a BOOL is negated with not"); - end; - if not Sym.isInt(x.typ) then - return Scan.markAt(x.pos, say1("\"~\" needs an integer, found {}", what(x))); - end; - if x.mode = mConst then x.val := cut(~x.val, x.typ); - else try value(x); Gen.complement(intSize(x.typ), signed(x.typ)); end; - return nil; -end; - -(* Arrays, slices and strings, which = and # compare element by element *) -proc isSeq(t: ^Sym.Type): BOOL; -begin - return t^.form in {Sym.fStr, Sym.fArray, Sym.fSlice}; -end; - -proc elemOf(t: ^Sym.Type): ^Sym.Type; -begin - if t^.form = Sym.fStr then return Sym.tU8; end; - return t^.base; -end; - -(* An array, slice or string as a slice in a temporary, for comparing. *) -proc seqSlice(var x: Item): ERROR; -var t: ^Sym.Type; -begin - t := Sym.newType(Sym.fSlice, 16, 8); - t^.base := elemOf(x.typ); - if x.typ^.form = Sym.fSlice then - x.typ := t; try copyToTemp(x); - elsif x.mode = mStr then - try address(x); sliceOf(x, t, x.val); - else - if x.vol then return Scan.markAt(x.pos, "can't compare through a volatile pointer"); end; - try address(x); sliceOf(x, t, x.typ^.len); - end; - return nil; -end; - -(* x, a BOOL, as a condition: a value compared with 0 if it isn't one *) -proc makeCond(var x: Item): ERROR; -begin - if x.mode = mCond then return nil; end; - try value(x); - Gen.pushConst(Gen.kWord, 0); - x.mode := mCond; - x.rel := Scan.sNeq; - x.relSigned := false; - x.fj := Gen.NoLabel; - x.tj := Gen.NoLabel; - return nil; -end; - -proc op1*(op: Scan.Sym; var x: Item; var L: INT): ERROR; -begin - L := Gen.NoLabel; - if ((op = Scan.sAnd) or (op = Scan.sOr)) and (x.typ^.form = Sym.fBool) then - if x.mode = mConst then return nil; end; (* folded by op2 *) - try makeCond(x); - if op = Scan.sAnd then - Gen.jumpOut(negated(x.rel), x.relSigned, x.fj); - Gen.fix(x.tj); - x.tj := Gen.NoLabel; - else - Gen.jumpOut(x.rel, x.relSigned, x.tj); - Gen.fix(x.fj); - x.fj := Gen.NoLabel; - end; - elsif ((op = Scan.sEql) or (op = Scan.sNeq)) and isSeq(x.typ) then - try seqSlice(x); - elsif (op = Scan.sPlus) and (x.mode = mStr) then - (* two string constants to be joined: nothing to compute *) - elsif (op = Scan.sPlus) and isSeq(x.typ) then - return Scan.markHelp(x.pos, say1("+ doesn't join {}", what(x)), "strings are joined in a Buf: Buf.str(b, s)"); - elsif x.mode in {mType, mBuiltin, mNone, mCase, mStr} then - return notValue(x); - elsif x.mode # mConst then - try value(x); - end; - return nil; -end; - -proc log2(v: I64): INT; -var n: INT; -begin - n := 0; - while (v > 1) and ((v & 1) = 0) do v := v shr 1; INC(n); end; - if v # 1 then n := -1; end; - return n; -end; - -(* Whether a op b, for + - *, overflows an I64: an untyped constant - doesn't wrap, it is an error (report section 4). *) -proc overflows(op: Scan.Sym; a, b: I64): BOOL; -begin - match op of - | sPlus: return ((b > 0) and (a > MaxI64 - b)) or ((b < 0) and (a < MinI64 - b)); - | sMinus: return ((b < 0) and (a > MaxI64 + b)) or ((b > 0) and (a < MinI64 + b)); - | sTimes: - if (a = 0) or (b = 0) then return false; end; - if a = -1 then return b = MinI64; end; - if b = -1 then return a = MinI64; end; - return (a * b) div b # a; - | else: return false; - end; -end; - -(* A type's width in bits; an untyped constant's is an I64's *) -proc bits(t: ^Sym.Type): I64; -begin - return t^.size * 8; -end; - -proc foldInt(op: Scan.Sym; a, b: I64; t: ^Sym.Type; p: Diag.Pos): (I64, ERROR); -var u: BOOL; -begin - u := (t^.form = Sym.fInt) and not t^.signed; - if (t^.form = Sym.fConst) and overflows(op, a, b) then - return 0, Scan.markAt(p, "the constant is too big for I64"); - end; - match op of - | sPlus: return a + b, nil; - | sMinus: return a - b, nil; - | sTimes: return a * b, nil; - | sDiv, sMod: - if b = 0 then return 0, Scan.markAt(p, "division by zero"); end; - if u then - if op = Scan.sDiv then return I64(U64(a) div U64(b)), nil; end; - return I64(U64(a) mod U64(b)), nil; - end; - if (b = -1) and (a = I64(-1) shl (bits(t) - 1)) then return 0, Scan.markAt(p, "division overflows"); end; - if op = Scan.sDiv then return a div b, nil; end; - return a mod b, nil; - | sAmp: return a & b, nil; - | sBar: return a | b, nil; - | sXor: return a xor b, nil; - | sShl: return a shl (b & (bits(t) - 1)), nil; - | sShr: - if u then return I64(U64(a) shr (b & (bits(t) - 1))), nil; end; - return a shr (b & (bits(t) - 1)), nil; - | sEql: return bit(a = b), nil; - | sNeq: return bit(a # b), nil; - | sLss: - if u then return bit(U64(a) < U64(b)), nil; end; - return bit(a < b), nil; - | sLeq: - if u then return bit(U64(a) <= U64(b)), nil; end; - return bit(a <= b), nil; - | sGtr: - if u then return bit(U64(a) > U64(b)), nil; end; - return bit(a > b), nil; - | sGeq: - if u then return bit(U64(a) >= U64(b)), nil; end; - return bit(a >= b), nil; - | else: return 0, Scan.markAt(p, "bad operator"); - end; -end; - -(* Folds x op y, of the real type t: an F32 rounded at each step, as - the machine would. *) -proc foldReal(op: Scan.Sym; x, y: Item; t: ^Sym.Type; var r: Item): BOOL; -var a, b: F64; ok: BOOL; -begin - a := realOf(x); b := realOf(y); - ok := true; - match 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, Sym.tBool, bit(a = b)); - | sNeq: makeConst(r, Sym.tBool, bit(a # b)); - | sLss: makeConst(r, Sym.tBool, bit(a < b)); - | sLeq: makeConst(r, Sym.tBool, bit(a <= b)); - | sGtr: makeConst(r, Sym.tBool, bit(a > b)); - | sGeq: makeConst(r, Sym.tBool, bit(a >= b)); - | else: ok := false; - end; - if r.typ^.form = Sym.fReal then realTo(r, t); end; - return ok; -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 *) -proc wrongLogic(op: Scan.Sym; var x: Item): ERROR; -var bitsOf: []U8; -begin - bitsOf := "the bits of integers take "; - if (op = Scan.sAnd) and Sym.isInt(x.typ) then - return Scan.markHelp(x.pos, say1("\"and\" needs BOOLs, found {}", what(x)), say1("{}&", bitsOf)); - elsif (op = Scan.sOr) and Sym.isInt(x.typ) then - return Scan.markHelp(x.pos, say1("\"or\" needs BOOLs, found {}", what(x)), say1("{}|", bitsOf)); - elsif op = Scan.sAmp then - return Scan.markHelp(x.pos, say1("\"&\" needs integers, found {}", what(x)), "BOOLs take and"); - elsif op = Scan.sBar then - return Scan.markHelp(x.pos, say1("\"|\" needs integers, found {}", what(x)), "BOOLs take or"); - elsif op = Scan.sXor then - return Scan.markHelp(x.pos, say1("\"xor\" needs integers, found {}", what(x)), "BOOLs that differ are #"); - end; - return Scan.markAt(x.pos, say2("{} needs BOOLs, found {}", Scan.symText(op), what(x))); -end; - -(* x + y, of two string constants: one string, in a chunk of its own - (report section 4) *) -proc joinStr(var x, y: Item): ERROR; -var p: ^U8; c, xs, ys, xl, yl: INT; -begin - if y.mode # mStr then - return Scan.markAt(y.pos, say1("\"+\" joins two strings, found {}", what(y))); - end; - xs := Chunk.chunks[x.chunk].start; - ys := Chunk.chunks[y.chunk].start; - xl := INT(x.val); - yl := INT(y.val); - p := Scan.grab(xl + yl + 1); - COPY(p[0..xl], Chunk.rodata[xs..xs + xl]); - COPY(p[xl..xl + yl + 1], Chunk.rodata[ys..ys + yl + 1]); - c := Chunk.newChunk(Chunk.secRodata, -1, -1); - Chunk.setData(c, p, xl + yl + 1, 1); - x.chunk := c; - x.val := x.val + y.val; - return nil; -end; - -(* A set's operations, as operations on its bits: the two values on top *) -proc setOp(op: Scan.Sym); -begin - match op of - | sPlus: Gen.op(Scan.sBar, Gen.kWord, 8, false); - | sTimes: Gen.op(Scan.sAmp, Gen.kWord, 8, false); - | sMinus: Gen.complement(8, false); Gen.op(Scan.sAmp, Gen.kWord, 8, false); - | sLeq, sGeq: - (* x <= y has no bit of x outside y *) - if op = Scan.sGeq then Gen.swap(); end; - Gen.complement(8, false); - Gen.op(Scan.sAmp, Gen.kWord, 8, false); - Gen.pushConst(Gen.kWord, 0); - Gen.compare(Scan.sEql, Gen.kWord, false); - | sIn: - Gen.swap(); - Gen.op(Scan.sShr, Gen.kWord, 8, false); - Gen.pushConst(Gen.kWord, 1); - Gen.op(Scan.sAmp, Gen.kWord, 8, false); - | else: Gen.compare(op, Gen.kWord, false); - end; -end; - -(* The operators the arithmetic of integers, of reals and of sets - stand for, and the comparisons *) -proc intOp(op: Scan.Sym): BOOL; -begin - return isRel(op) or oneOf(op, [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod, - Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr]); -end; - -proc doesntApply(op: Scan.Sym; x, y: Item; t: ^Sym.Type): ERROR; -begin - return Scan.markAt(Diag.join(x.pos, y.pos), say2("{} doesn't apply to {}", Scan.symText(op), Sym.typeName(t))); -end; - -proc op2*(op: Scan.Sym; var x, y: Item; _L: INT): ERROR; -var xt, yt, t, e: ^Sym.Type; r: Item; scale: INT; isPtr: BOOL; a, b, v: I64; -begin - xt := x.typ; yt := y.typ; - if y.mode in {mType, mBuiltin, mNone, mCase} then return notValue(y); end; - if (op = Scan.sPlus) and (x.mode = mStr) then return joinStr(x, y); end; - - if (op = Scan.sAnd) or (op = Scan.sOr) then - if xt^.form # Sym.fBool then return wrongLogic(op, x); end; - if yt^.form # Sym.fBool then return wrongLogic(op, y); end; - if (x.mode = mConst) and (y.mode = mConst) then - if op = Scan.sAnd then x.val := x.val & y.val; else x.val := x.val | y.val; end; - elsif x.mode = mConst then - (* true and y, false or y: y; else x, y computed and dropped *) - if (x.val = 1) = (op = Scan.sAnd) then x := y; - else try discard(y); end; - else - try makeCond(y); - if op = Scan.sAnd then x.fj := Gen.joinJumps(x.fj, y.fj); x.tj := y.tj; - else x.tj := Gen.joinJumps(x.tj, y.tj); x.fj := y.fj; end; - x.rel := y.rel; - x.relSigned := y.relSigned; - end; - return nil; - end; - - if oneOf(op, [Scan.sAmp, Scan.sBar, Scan.sXor]) and (xt^.form = Sym.fBool) then return wrongLogic(op, x); end; - if oneOf(op, [Scan.sAmp, Scan.sBar, Scan.sXor]) and (yt^.form = Sym.fBool) then return wrongLogic(op, y); end; - - (* 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 = Scan.sEql) or (op = Scan.sNeq)) and isSeq(xt) then - e := elemOf(xt); - if not isSeq(yt) then - return Scan.markAt(Diag.join(x.pos, y.pos), say1("can't compare an array with {}", Sym.typeName(yt))); - elsif not Sym.same(e, elemOf(yt)) then - return Scan.markAt(Diag.join(x.pos, y.pos), - say2("can't compare an array of {} with one of {}", Sym.typeName(e), Sym.typeName(elemOf(yt)))); - end; - if e^.form = Sym.fReal then - return Scan.markHelp(Diag.join(x.pos, y.pos), - say1("can't compare arrays of reals with {}", Scan.symText(op)), - "-0.0 = 0.0 and a NaN equals nothing, though their bytes say otherwise: write a loop"); - elsif not (e^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fPtr}) then - return Scan.markHelp(Diag.join(x.pos, y.pos), - say2("can't compare arrays of {} with {}", Sym.typeName(e), Scan.symText(op)), "write a loop"); - end; - try seqSlice(y); - Gen.compareSeq(x.off, y.off, log2(e^.size), op = Scan.sEql); - makeConst(x, Sym.tBool, 0); - x.mode := mStack; - return nil; - end; - - (* the type of the result, and the checks *) - t := nil; scale := 1; isPtr := false; - if Sym.isInt(xt) and Sym.isInt(yt) then - if op = Scan.sSlash then - return Scan.markHelp(Diag.join(x.pos, y.pos), "\"/\" divides reals, not integers", - say2("to divide integers, write {} div {}", Diag.source(x.pos), Diag.source(y.pos))); - end; - if (op = Scan.sShl) or (op = Scan.sShr) then - if xt^.form = Sym.fConst then t := Sym.tConst; else t := xt; end; - elsif (xt^.form = Sym.fConst) and (yt^.form = Sym.fConst) then t := Sym.tConst; - elsif xt^.form = Sym.fConst then - if (x.mode = mConst) and not Sym.fits(x.val, yt) then - return Scan.markAt(x.pos, Diag.say("{} doesn't fit {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(yt))])); - end; - t := yt; - elsif yt^.form = Sym.fConst then - if (y.mode = mConst) and not Sym.fits(y.val, xt) then - return Scan.markAt(y.pos, Diag.say("{} doesn't fit {}", [Fmt.int(y.val), Fmt.str(Sym.typeName(xt))])); - end; - t := xt; - elsif Sym.same(xt, yt) then t := xt; - else return mismatchOps(x, y, xt, yt); end; - if not intOp(op) then return doesntApply(op, x, y, t); end; - elsif (xt^.form = Sym.fReal) and (yt^.form = Sym.fReal) then - if not (isRel(op) or oneOf(op, [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sSlash])) then - return doesntApply(op, x, y, xt); - end; - if xt = Sym.tRConst then t := yt; - elsif (yt = Sym.tRConst) or Sym.same(xt, yt) then t := xt; - else return mismatchOps(x, y, xt, yt); end; - if (x.mode = mConst) and (x.typ # t) then realTo(x, t); end; - if (y.mode = mConst) and (y.typ # t) then realTo(y, t); end; - elsif (xt^.form = Sym.fBool) and (yt^.form = Sym.fBool) then - if (op # Scan.sEql) and (op # Scan.sNeq) then return doesntApply(op, x, y, xt); end; - t := Sym.tBool; - elsif (xt^.form = Sym.fPtr) and Sym.isInt(yt) and ((op = Scan.sPlus) or (op = Scan.sMinus)) then - t := xt; scale := INT(xt^.base^.size); isPtr := true; - if y.mode = mConst then y.typ := Sym.tInt; end; - elsif (xt^.form = Sym.fPtr) and (yt^.form = Sym.fPtr) and (op = Scan.sMinus) then - if not Sym.same(xt, yt) then return mismatchOps(x, y, xt, yt); end; - t := Sym.tInt; scale := INT(xt^.base^.size); isPtr := true; - elsif (xt^.form in {Sym.fPtr, Sym.fProc, Sym.fNil, Sym.fError}) and (yt^.form in {Sym.fPtr, Sym.fProc, Sym.fNil, Sym.fError}) then - if not isRel(op) then return doesntApply(op, x, y, xt); end; - if (xt^.form in {Sym.fProc, Sym.fError}) or (yt^.form in {Sym.fProc, Sym.fError}) then - if (op # Scan.sEql) and (op # Scan.sNeq) then return doesntApply(op, x, y, xt); end; - end; - if (xt^.form # Sym.fNil) and (yt^.form # Sym.fNil) and not Sym.same(xt, yt) then - if not ((xt^.form = Sym.fPtr) and (yt^.form = Sym.fPtr) and Sym.same(xt^.base, yt^.base)) then - return mismatchOps(x, y, xt, yt); - end; - end; - t := Sym.tU64; - elsif (xt^.form = Sym.fEnum) and Sym.same(xt, yt) then - if not isRel(op) then return doesntApply(op, x, y, xt); end; - t := xt; - elsif (xt^.form = Sym.fSet) and Sym.same(xt, yt) then - if not oneOf(op, [Scan.sPlus, Scan.sTimes, Scan.sMinus, Scan.sEql, Scan.sNeq, Scan.sLeq, Scan.sGeq]) then - return doesntApply(op, x, y, xt); - end; - t := xt; - elsif (op = Scan.sIn) and (yt^.form = Sym.fSet) and Sym.same(xt, yt^.base) then - t := yt; - else - return mismatchOps(x, y, xt, yt); - end; - - (* constants *) - if (x.mode = mConst) and (y.mode = mConst) and not isPtr then - if t^.form = Sym.fReal then - if not foldReal(op, x, y, t, r) then return doesntApply(op, x, y, xt); end; - x := r; - elsif t^.form = Sym.fSet then - a := x.val; b := y.val; - match op of - | sPlus: makeConst(x, t, a | b); - | sTimes: makeConst(x, t, a & b); - | sMinus: makeConst(x, t, a & ~b); - | sIn: makeConst(x, Sym.tBool, (b shr a) & 1); - | sLeq: makeConst(x, Sym.tBool, bit((a & ~b) = 0)); - | sGeq: makeConst(x, Sym.tBool, bit((b & ~a) = 0)); - | else: makeConst(x, Sym.tBool, bit((a = b) = (op = Scan.sEql))); - end; - elsif isRel(op) then - v := try foldInt(op, x.val, y.val, t, Diag.join(x.pos, y.pos)); - makeConst(x, Sym.tBool, v); - else - v := try foldInt(op, x.val, y.val, t, Diag.join(x.pos, y.pos)); - makeConst(x, t, cut(v, t)); - end; - return nil; - 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] *) - try value(y); - if x.mode = mConst then - try value(x); - if not oneOf(op, [Scan.sPlus, Scan.sTimes, Scan.sAmp, Scan.sBar, Scan.sXor]) or isPtr then Gen.swap(); end; - end; - - if t^.form = Sym.fReal then - if isRel(op) then Gen.compare(op, Gen.kindOf(t), false); - else Gen.op(op, Gen.kindOf(t), 8, false); end; - elsif t^.form = Sym.fSet then - setOp(op); - elsif isRel(op) then - x.mode := mCond; - x.rel := op; - x.relSigned := signed(t); - x.fj := Gen.NoLabel; - x.tj := Gen.NoLabel; - x.typ := Sym.tBool; - return nil; - elsif isPtr then - if t # Sym.tInt then scaleBy(scale); end; - Gen.op(op, Gen.kWord, 8, false); - if (t = Sym.tInt) and (scale # 1) then - Gen.pushConst(Gen.kWord, scale); - Gen.op(Scan.sDiv, Gen.kWord, 8, true); - end; - else - Gen.op(op, Gen.kindOf(t), intSize(t), signed(t)); - end; - x.mode := mStack; - if isRel(op) or (op = Scan.sIn) then x.typ := Sym.tBool; else x.typ := t; end; - return nil; -end; - -(* INT and UINT, the integers as big as an address, through which - integers and pointers convert (report section 6.7) *) -proc isWord*(t: ^Sym.Type): BOOL; -begin - return Sym.same(t, Sym.tInt) or Sym.same(t, Sym.tUInt); -end; - -proc convert*(var x: Item; t: ^Sym.Type): ERROR; -var s: ^Sym.Type; r: F64; -begin - s := x.typ; - if x.mode in {mType, mBuiltin, mNone, mCase, mStr} then - if x.mode = mStr then return Scan.markAt(x.pos, "can't convert a string"); end; - return notValue(x); - end; - if Sym.same(s, t) then return nil; end; - if (Sym.isInt(s) or (s^.form in {Sym.fEnum, Sym.fSet})) and (t^.form = Sym.fInt) then - if x.mode = mConst then x.val := cut(x.val, t); - else try value(x); Gen.narrow(INT(t^.size), t^.signed); end; - elsif Sym.isInt(s) and (t^.form = Sym.fEnum) then - if x.mode = mConst then - if (x.val < 0) or (x.val >= t^.len) then - return Scan.markAt(x.pos, Diag.say("{} isn't a position of {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(t))])); - end; - else try value(x); Gen.checkEnum(t^.len, nameChunk(t), x.pos); end; - elsif Sym.isInt(s) and (t^.form = Sym.fSet) then - if x.mode = mConst then - if t^.len < 64 then x.val := x.val & ((I64(1) shl t^.len) - 1); end; - else - try value(x); - if t^.len < 64 then - Gen.pushConst(Gen.kWord, (I64(1) shl t^.len) - 1); - Gen.op(Scan.sAmp, Gen.kWord, 8, false); - end; - end; - elsif Sym.isInt(s) and (t^.form = Sym.fReal) then - if x.mode = mConst then - if (s^.form = Sym.fInt) and not s^.signed then r := F64(U64(x.val)); else r := F64(x.val); end; - makeReal(x, r); - realTo(x, t); - else - try value(x); - Gen.intToReal(Gen.kindOf(t), (s^.form = Sym.fInt) and not s^.signed and (s^.size = 8)); - end; - elsif (s^.form = Sym.fReal) and (t^.form = Sym.fReal) then - (* F32 to F64, F64 to F32, or a real constant to either *) - if x.mode = mConst then realTo(x, t); - else try value(x); Gen.realToReal(Gen.kindOf(s)); end; - elsif (s^.form = Sym.fReal) and (t^.form = Sym.fInt) then - if x.mode = mConst then - 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(MinI64, t); - else x.val := cut(I64(r), t); end; - else - try value(x); Gen.realToInt(Gen.kindOf(s)); Gen.narrow(INT(t^.size), t^.signed); - end; - elsif (isWord(s) or (s^.form in {Sym.fConst, Sym.fPtr, Sym.fProc, Sym.fNil})) and (t^.form in {Sym.fPtr, Sym.fProc}) then - if x.mode # mConst then try value(x); end; - elsif (s^.form in {Sym.fPtr, Sym.fProc}) and isWord(t) then - try value(x); - else - return Scan.markAt(x.pos, say2("can't convert {} to {}", Sym.typeName(s), Sym.typeName(t))); - end; - x.typ := t; - return nil; -end; - -(* Calls *) - -proc beginCall*(var c: Gen.CallInfo; var x: Item): ERROR; -begin - if x.mode = mProc then - c.sig := x.obj^.typ; c.chunk := x.obj^.chunk; c.target := 0; - c.obj := x.obj; c.ext := x.obj^.ext; - else - c.obj := nil; c.ext := false; - if x.typ^.form # Sym.fProc then - return Scan.markAt(x.pos, say1("expected a procedure, found {}", what(x))); - end; - c.sig := x.typ; c.chunk := -1; - c.target := try toSlot(x); - end; - c.param := c.sig^.fields; - c.n := 0; - return nil; -end; - -(* Too many arguments or too few, at p *) -proc wrongCount(var c: Gen.CallInfo; p: Diag.Pos; text: []U8): ERROR; -begin - if c.obj = nil then return Scan.markAt(p, text); end; - Diag.error(p, Diag.say("{}: {} takes {}", [Fmt.str(text), Fmt.str(Scan.nameOf(c.obj^.name)), Fmt.int(c.sig^.len)])); - if c.obj^.home # nil then Diag.note(c.obj^.pos, "the signature is here"); end; - return Scan.Failed; -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. *) -proc pushWords(var x: Item): ERROR; -var adr: Gen.Adr; f: ^Sym.Obj; -begin - if x.mode = mWords then return nil; end; (* 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 {Gen.bFrame, Gen.bGlobal, Gen.bSlot, Gen.bReg}) then - try copyToTemp(x); - end; - adr := adrOf(x); - if x.typ^.form = Sym.fSlice then - Gen.pushVar(adr, 8, false, Gen.kWord); - INC(adr.off, 8); - Gen.pushVar(adr, 8, false, Gen.kWord); - else - f := x.typ^.fields; - while f # nil do - adr.off := adrOf(x).off + f^.val; - Gen.pushVar(adr, scalarSize(f^.typ), signed(f^.typ), Gen.kindOf(f^.typ)); - f := f^.next; - end; - end; - return nil; -end; - -proc passArg*(var c: Gen.CallInfo; var a: Item): ERROR; -var p: ^Sym.Obj; -begin - p := c.param; - if c.n >= LEN(c.isF) - 1 then return Scan.markAt(a.pos, "too many arguments"); end; - if p = nil then - (* 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 return wrongCount(c, a.pos, "too many arguments"); end; - if a.mode = mStr then try coerce(a, Sym.tPtrU8); - elsif a.typ^.form = Sym.fConst then try coerce(a, Sym.tInt); - elsif a.typ = Sym.tRConst then try coerce(a, Sym.tReal); - elsif isF32(a.typ) then return Scan.markAt(a.pos, "an F32 goes to ... as F64(x)"); - elsif not Sym.isScalar(a.typ) then return Scan.markAt(a.pos, "only a single value goes to ..."); end; - c.isF[c.n] := a.typ^.form = Sym.fReal; - c.pair[c.n] := false; - try value(a); - INC(c.n); - return nil; - end; - c.isF[c.n] := (p^.typ^.form = Sym.fReal) and not p^.isVar; - passing := p; - passingAt := a.pos; - if p^.isVar then - try notReadOnly(a); - if (a.mode # mVar) or not a.isVar then return Scan.markAt(a.pos, "a var parameter needs a variable"); end; - if a.odd then return Scan.markAt(a.pos, "a field of a packed record can't be a var parameter"); end; - if not Sym.same(a.typ, p^.typ) then - return mismatch(a, say2("a var parameter needs exactly {}, found {}", Sym.typeName(p^.typ), what(a))); - end; - if a.vol then return Scan.markAt(a.pos, "can't pass through a volatile pointer to a var parameter"); end; - try address(a); - elsif p^.typ^.form = Sym.fSlice then - try coerce(a, p^.typ); - try pushWords(a); - c.pair[c.n] := true; - INC(c.n); - c.isF[c.n] := false; - elsif Sym.isAggregate(p^.typ) then - try coerce(a, p^.typ); - if a.isVar or a.vol or (a.base # Gen.bFrame) then try copyToTemp(a); end; - try address(a); - else - try coerce(a, p^.typ); - try value(a); - end; - c.pair[c.n] := false; - INC(c.n); - c.param := p^.next; - return nil; -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. *) -proc endCall*(var c: Gen.CallInfo; var x: Item): ERROR; -var res: ^Sym.Type; -begin - if c.param # nil then try wrongCount(c, Scan.tokPos(), "too few arguments"); end; - Gen.call(c); - res := c.sig^.base; - x := {}; - if res = nil then - x.mode := mNone; x.typ := Sym.tNone; x.obj := c.obj; - elsif c.ret # 0 then - tempItem(x, res, c.ret); - else - x.mode := mStack; x.typ := res; - if res^.tuple then x.mode := mWords; end; - end; - return nil; -end; - -(* Variants *) - -(* A temporary of type t, all zero: for variants and record literals. *) -proc zeroTemp*(var x: Item; t: ^Sym.Type); -var tmp: I64; -begin - tmp := Gen.allocTemp(t^.size, t^.align); - Gen.zeroVar(frameAdr(tmp), t^.size); - tempItem(x, t, tmp); -end; - -proc construct*(var x: Item; c: ^Sym.Obj); -begin - zeroTemp(x, c^.typ); - Gen.pushConst(Gen.kWord, c^.val); - Gen.popVar(frameAdr(x.off), 8); -end; - -proc setField*(x: Item; f: ^Sym.Obj; var a: Item): ERROR; -begin - try coerce(a, f^.typ); - if Sym.isScalar(f^.typ) then - try value(a); - Gen.popVar(frameAdr(x.off + f^.val), scalarSize(f^.typ)); - else - if a.vol then return Scan.markAt(a.pos, "can't copy through a volatile pointer"); end; - try address(a); - Gen.copyTo(frameAdr(x.off + f^.val), f^.typ^.size); - end; - return nil; -end; - -(* The slot match tests: a variant's address, or an enumeration's or an - integer's value. *) -proc matchBegin*(var x: Item): (I64, ERROR); -var p: I64; -begin - if x.typ^.form in {Sym.fEnum, Sym.fInt} then return toSlot(x); end; - if (x.mode # mVar) or (x.typ^.form # Sym.fVariant) then - return 0, Scan.markAt(x.pos, say1("match needs a variant, an enumeration or an integer, found {}", what(x))); - end; - if x.ro then try copyToTemp(x); end; (* its arms' names stand for a copy's fields *) - try address(x); - p := Gen.allocTemp(8, 8); - Gen.popVar(frameAdr(p), 8); - return p, nil; -end; - -(* To L unless the tag of the variant whose address is in slot p is tag *) -proc matchTag*(p: I64; tag: I64; var L: INT); -var a: Gen.Adr; -begin - Gen.pushVar(frameAdr(p), 8, false, Gen.kWord); - a.base := Gen.bStack; a.chunk := -1; a.off := 0; a.hi := 0; - Gen.pushVar(a, 8, false, Gen.kWord); - Gen.pushConst(Gen.kWord, tag); - Gen.jumpCmp(Scan.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. *) -proc matchRange*(p, lo, hi: I64; var body: INT); -begin - Gen.pushVar(frameAdr(p), 8, false, Gen.kWord); - if lo = hi then - Gen.pushConst(Gen.kWord, lo); - Gen.jumpCmp(Scan.sEql, false, body); - return; - end; - if lo # 0 then - Gen.pushConst(Gen.kWord, lo); - Gen.op(Scan.sMinus, Gen.kWord, 8, false); - end; - Gen.pushConst(Gen.kWord, hi - lo); - Gen.jumpCmp(Scan.sLeq, false, body); -end; - -(* A for loop's variable o, stepped by step, wrapping as its type does *) -proc forStep*(o: ^Sym.Obj; step: I64): ERROR; -var v, w: Item; -begin - try makeItem(v, o); - if v.base = Gen.bReg then - (* a variable in a register is stepped in it *) - Gen.pushConst(Gen.kWord, step); - Gen.incDecReg(v.chunk, intSize(o^.typ), signed(o^.typ), false); - return nil; - end; - try makeItem(w, o); - try value(w); - Gen.pushConst(Gen.kWord, step); - Gen.op(Scan.sPlus, Gen.kWord, intSize(o^.typ), signed(o^.typ)); - return 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 *) -proc forCmp*(o: ^Sym.Obj; lim: Item; op: Scan.Sym; var L: INT): ERROR; -var v, b: Item; -begin - try makeItem(v, o); - try value(v); - b := lim; - try value(b); - Gen.jumpCmp(op, o^.typ^.signed, L); - return nil; -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 chosen 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. *) -proc forNext*(o: ^Sym.Obj; lim: Item; step: I64; var exitL: INT; top, body: INT): ERROR; -var v, b: Item; L, pastL: INT; up: BOOL; before, past, within: Scan.Sym; a: I64; -begin - up := step > 0; - (* by a negative step, by a positive *) - if up then before := Scan.sLss; past := Scan.sGtr; within := Scan.sLeq; - else before := Scan.sGtr; past := Scan.sLss; within := Scan.sGeq; end; - a := step; - if a < 0 then a := -a; end; - L := Gen.NoLabel; - pastL := Gen.NoLabel; - if a = 1 then - try forCmp(o, lim, before, L); - Gen.fixTo(L, top); - try forCmp(o, lim, Scan.sEql, exitL); - else - try forCmp(o, lim, past, pastL); - try makeItem(v, o); - b := lim; - if up then try value(b); try value(v); - else try value(v); try value(b); end; - Gen.op(Scan.sMinus, Gen.kWord, 8, false); - Gen.pushConst(Gen.kWord, a); - Gen.jumpCmp(Scan.sGeq, false, L); - Gen.fixTo(L, top); - Gen.jump(exitL); - end; - Gen.fix(pastL); - try forStep(o, step); - L := Gen.NoLabel; - try forCmp(o, lim, within, L); - Gen.fixTo(L, body); - return nil; -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. *) -proc condJump*(var x: Item; var L: INT): ERROR; -begin - if x.typ^.form # Sym.fBool then - return Scan.markAt(x.pos, say1("a condition is a BOOL, found {}", what(x))); - end; - if x.mode = mCond then - Gen.jumpCmp(negated(x.rel), x.relSigned, L); - L := Gen.joinJumps(L, x.fj); - Gen.fix(x.tj); - return nil; - end; - try value(x); - Gen.jumpIf(L, false); - return nil; -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 *) -proc condJumpTrue*(var x: Item; var L: INT): ERROR; -begin - if x.typ^.form # Sym.fBool then - return Scan.markAt(x.pos, say1("a condition is a BOOL, found {}", what(x))); - end; - if x.mode = mCond then - Gen.jumpCmp(x.rel, x.relSigned, L); - L := Gen.joinJumps(L, x.tj); - Gen.fix(x.fj); - return nil; - end; - try value(x); - Gen.jumpIf(L, true); - return nil; -end; - -(* Procedures *) - -proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj); -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 *) -proc returnValue*(var x: Item): ERROR; -begin - if result = nil then return Scan.markAt(x.pos, "this procedure returns nothing"); end; - try coerce(x, result); - if Sym.inTwoRegs(result) then try pushWords(x); - elsif Sym.isAggregate(result) then - if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end; - try address(x); - Gen.copyResult(0, result^.size); - else try value(x); end; - return nil; -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. *) -proc returnField*(f: ^Sym.Obj; var x: Item): ERROR; -begin - try coerce(x, f^.typ); - if Sym.inTwoRegs(result) then try value(x); - elsif Sym.isScalar(f^.typ) then - try value(x); - Gen.resultTo(f^.val, scalarSize(f^.typ)); - else - if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end; - try address(x); - Gen.copyResult(f^.val, f^.typ^.size); - end; - return nil; -end; - -(* Several results at once, the call's that return f(x) passes on. *) -proc returnAll*(var x: Item): ERROR; -begin - if Sym.inTwoRegs(result) then try pushWords(x); - else - try address(x); - Gen.copyResult(0, result^.size); - end; - return nil; -end; - -proc returnNone*: ERROR; -begin - if result # nil then - return Scan.mark(say1("return needs a result of {}", Sym.typeName(result))); - end; - Gen.returnJump(); - return nil; -end; - -(* Keeps a variable's address in a frame slot, rather than on the stack, - while other code runs. *) -proc pin*(var x: Item): ERROR; -var s: I64; -begin - if (x.mode = mVar) and (x.base = Gen.bStack) then - try address(x); - s := Gen.allocTemp(8, 8); - Gen.popVar(frameAdr(s), 8); - x.base := Gen.bSlot; - x.chunk := INT(s); - end; - return nil; -end; - -(* INC(v, k) or DEC: v's address is on the stack, from address. *) -proc incDec*(var v, k: Item; dec: BOOL): ERROR; -begin - try coerceExact(k, v.typ, ""); - try value(k); - if v.base = Gen.bReg then Gen.incDecReg(v.chunk, scalarSize(v.typ), v.typ^.signed, dec); - else Gen.incDec(scalarSize(v.typ), v.typ^.signed, dec); end; - return nil; -end; - -(* COPY(d, s): d, an array variable or a slice, as a slice in the frame, - before s is read *) -proc copyDest*(var d: Item): ERROR; -begin - if not isSeq(d.typ) or (d.mode = mStr) or ((d.typ^.form = Sym.fArray) and ((d.mode # mVar) or not d.isVar)) then - return Scan.markAt(d.pos, say1("COPY copies into an array variable or a slice, found {}", what(d))); - end; - if d.typ^.form = Sym.fArray then try notReadOnly(d); end; - return seqSlice(d); -end; - -(* ... and the elements of s copied to its start *) -proc copyFrom*(var d, s: Item): ERROR; -begin - if not isSeq(s.typ) or not Sym.same(elemOf(s.typ), d.typ^.base) then - return Scan.markAt(s.pos, say2("COPY copies elements of {}, found {}", Sym.typeName(d.typ^.base), what(s))); - end; - try seqSlice(s); - Gen.copySlice(d.off, s.off, d.typ^.base^.size, checks, s.pos); - return nil; -end; - -(* An error is the address of its length, followed by its message. *) -proc errorChunk*(var x: Item; home, name: INT): (INT, ERROR); -var c, xs, xl: INT; p: ^U8; q: ^I64; -begin - if x.mode # mStr then return 0, Scan.markAt(x.pos, "an error is made from a string"); end; - xl := INT(x.val); - p := Scan.grab(xl + 8); - q := ^I64(p); - q^ := x.val; - xs := Chunk.chunks[x.chunk].start; - COPY(p[8..8 + xl], Chunk.rodata[xs..xs + xl]); - c := Chunk.newChunk(Chunk.secRodata, home, name); - Chunk.setData(c, p, xl + 8, 8); - return c, nil; -end; - -proc msg*(var x: Item): ERROR; -var s: I64; -begin - try coerce(x, Sym.tError); - try value(x); - s := Gen.allocTemp(16, 8); - Gen.errorText(s); - tempItem(x, Sym.tBytes, s); - return nil; -end; - -end Item. diff --git a/self/Link.raz b/self/Link.raz deleted file mode 100644 index 852dce6..0000000 --- a/self/Link.raz +++ /dev/null @@ -1,380 +0,0 @@ -(* Link: 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 writes them - in the room left there. - - Depends on: Chunk for chunks and fixups, Scan for names and memory, - Diag for errors and paths. - Leaves out: the file format; that is Elf. *) -module Link; -import Fmt, Diag, Scan, Chunk; - -const - Base* = 400000H; - Page* = 4096; - -var - textOff*, textSize*: INT; (* file offset and size of text, at Base + textOff *) - roOff*, roSize*: INT; (* rodata, the room for the loader's tables included *) - roAdr*: INT; (* where rodata is loaded *) - extraAdr*: INT; (* that room *) - bssAdr*, bssSize*: INT; (* the writable segment, the loader's table first *) - bssOff*: INT; (* the file offset of that table *) - textImg*, roImg*: ^U8; - placesChunk*: INT; (* the rodata chunk of the places, made by the caller *) - linesOff*, linesSize*: INT; (* the line table, in the places: .debug_line *) - -proc setPlaces*(c: INT); -begin - placesChunk := c; -end; - -(* Marks live each chunk reached from entry through the fixups. *) -proc markLive*(entry: INT); -var stack: ^INT; sp, c, f, t: INT; fx: ^Chunk.Fixup; -begin - stack := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); - Chunk.setLive(entry); - stack[0] := entry; - sp := 1; - while sp > 0 do - DEC(sp); - c := stack[sp]; - if Chunk.chunks[c].size < 0 then - Diag.fatal(Diag.say("{} is declared but never defined", [Fmt.str(Chunk.chunkName(c))])); - end; - (* code and constants have fixups; variables start at zero, holding - no addresses *) - match Chunk.chunks[c].sec of - | secText: fx := Chunk.fixups; - | secRodata: fx := Chunk.dataFixups; - | secBss: fx := nil; - end; - if fx # nil then - for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do - t := fx[f].chunk; - if not Chunk.chunks[t].live then - Chunk.setLive(t); - stack[sp] := t; - INC(sp); - end; - end; - end; - end; -end; - -(* Gives the live chunks of one section their places, from start; - returns the end. *) -proc place(sec: Chunk.Section; start: INT): INT; -var c, a: INT; -begin - a := start; - for c := 0 to Chunk.numChunks - 1 do - if Chunk.chunks[c].live and (Chunk.chunks[c].sec = sec) then - a := (a + Chunk.chunks[c].align - 1) div Chunk.chunks[c].align * Chunk.chunks[c].align; - Chunk.setAdr(c, a); - a := a + Chunk.chunks[c].size; - end; - end; - return 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: ^U8; - lpLen, lpCap: INT; - -proc putB(v: INT); -begin - if lpLen = lpCap then - lp := Scan.regrab(lp, lpLen, lpCap * 2 + 256); - lpCap := lpCap * 2 + 256; - end; - lp[lpLen] := U8(v & 0FFH); - INC(lpLen); -end; - -(* The n low bytes of v, least significant first *) -proc putN(v: INT; n: INT); -var i: INT; -begin - for i := 1 to n do putB(v); v := v shr 8; end; -end; - -(* LEB128, unsigned and signed *) -proc putU(v: INT); -begin - while v >= 80H do putB(v & 7FH | 80H); v := v shr 7; end; - putB(v); -end; - -proc putS(v: INT); -begin - while (v < -64) or (v >= 64) do putB(v & 7FH | 80H); v := v shr 7; end; - putB(v & 7FH); -end; - -(* v as the four bytes at at in p *) -proc patch4(p: ^U8; at, v: INT); -var i: INT; -begin - for i := 0 to 3 do p[at + i] := U8((v shr (8 * i)) & 0FFH); end; -end; - -(* v as the eight bytes at at in p *) -proc patch8(p: ^U8; at, v: INT); -var i: INT; -begin - for i := 0 to 7 do p[at + i] := U8((v shr (8 * i)) & 0FFH); end; -end; - -(* Whether the standard opcode i takes an operand *) -proc takesOperand(i: INT): BOOL; -begin - return (i = 2) or (i = 3) or (i = 4) or (i = 5) or (i = 9) or (i = 12); -end; - -(* The line program of the files paths, nfiles of them, numbered from - 1, as they are written in the table *) -proc makeLines(paths: ^INT; nfiles: INT); -var i, f, c, cf, cl, cc, op, at, da, dl: INT; s: []U8; -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 - if takesOperand(i) then putB(1); else putB(0); end; (* their operands *) - end; - putB(0); (* no include directories *) - for f := 0 to nfiles - 1 do - s := Diag.shownPath(Scan.nameOf(paths[f])); - for i := 0 to LEN(s) - 1 do putB(INT(s[i])); end; - putN(0, 4); (* its end, directory, time, length *) - end; - putB(0); - patch4(lp, 6, lpLen - 10); - i := 0; - while i < Chunk.numLines do - c := Chunk.lines[i].chunk; - if not Chunk.chunks[c].live then - INC(i); - else - putB(0); putU(9); putB(2); (* DW_LNE_set_address *) - putN(Chunk.chunks[c].adr + Chunk.lines[i].at - Chunk.chunks[c].start, 8); - at := Chunk.lines[i].at; cf := 1; cl := 1; cc := 0; - while (i < Chunk.numLines) and (Chunk.lines[i].chunk = c) do - f := 1; - while paths[f - 1] # Chunk.lines[i].path do INC(f); end; - if f # cf then putB(4); putU(f); cf := f; end; (* DW_LNS_set_file *) - if Chunk.lines[i].col # cc then putB(5); putU(Chunk.lines[i].col); cc := Chunk.lines[i].col; end; (* DW_LNS_set_column *) - da := Chunk.lines[i].at - at; - dl := Chunk.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 - if da > 0 then putB(2); putU(da); end; (* DW_LNS_advance_pc *) - if dl # 0 then putB(3); putS(dl); end; (* DW_LNS_advance_line *) - putB(1); (* DW_LNS_copy: a row *) - end; - at := Chunk.lines[i].at; cl := Chunk.lines[i].line; - INC(i); - end; - putB(2); putU(Chunk.chunks[c].start + Chunk.chunks[c].size - at); - putB(0); putU(1); putB(1); (* DW_LNE_end_sequence *) - end; - end; - patch4(lp, 0, lpLen - 4); -end; - -var - buf: ^U8; (* the places, being made *) - at, names, poolAt: INT; (* where the next number goes, the next name, the pool's start *) - -(* The name s, in the pool, and its offset from the pool's start, at at *) -proc putName(s: []U8); -begin - patch4(buf, at, names - poolAt); - COPY(buf[names..names + LEN(s)], s); - buf[names + LEN(s)] := 0; - names := names + LEN(s) + 1; - at := at + 4; -end; - -(* Whether chunk c is a live procedure, whose places Rt knows *) -proc isProc(c: INT): BOOL; -begin - return Chunk.chunks[c].live and (Chunk.chunks[c].sec = Chunk.secText) and (Chunk.chunks[c].home >= 0); -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'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. *) -proc makePlaces(start, stop: INT); -var - files, first, count: ^INT; - i, f, nfiles, np, nv, c, v: INT; -begin - files := ^INT(Scan.grab(Chunk.numLines * SIZE(INT) + SIZE(INT))); - first := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); - count := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); - for c := 0 to Chunk.numChunks - 1 do first[c] := 0; count[c] := 0; end; - for v := Chunk.numVarNotes - 1 to 0 by -1 do - first[Chunk.varNotes[v].chunk] := v; - INC(count[Chunk.varNotes[v].chunk]); - end; - nfiles := 0; poolAt := 0; np := 0; nv := 0; - for i := 0 to Chunk.numLines - 1 do - if Chunk.chunks[Chunk.lines[i].chunk].live then - f := 0; - while (f < nfiles) and (files[f] # Chunk.lines[i].path) do INC(f); end; - if f = nfiles then - files[f] := Chunk.lines[i].path; - INC(nfiles); - end; - end; - end; - makeLines(files, nfiles); - for c := 0 to Chunk.numChunks - 1 do - if isProc(c) then - INC(np); - poolAt := poolAt + LEN(Chunk.chunkName(c)) + 1; - for v := first[c] to first[c] + count[c] - 1 do - poolAt := poolAt + LEN(Scan.nameOf(Chunk.varNotes[v].name)) + 1; - end; - nv := nv + count[c]; - end; - end; - buf := Scan.grab(40 + 28 * np + 12 * nv + poolAt + lpLen); - (* the pool of names starts at poolAt, the line table after it *) - poolAt := 40 + 28 * np + 12 * nv; - names := poolAt; - at := 40; - v := 0; - for c := 0 to Chunk.numChunks - 1 do - if isProc(c) then - patch4(buf, at, Chunk.chunks[c].adr); - patch4(buf, at + 4, Chunk.chunks[c].adr + Chunk.chunks[c].size); - at := at + 8; - putName(Chunk.chunkName(c)); - patch4(buf, at, v); - patch4(buf, at + 4, count[c]); - patch4(buf, at + 8, Chunk.chunks[c].saveMask); - patch4(buf, at + 12, Chunk.chunks[c].saveAt); - at := at + 16; - v := v + count[c]; - end; - end; - for c := 0 to Chunk.numChunks - 1 do - if isProc(c) then - for v := first[c] to first[c] + count[c] - 1 do - putName(Scan.nameOf(Chunk.varNotes[v].name)); - patch4(buf, at, Chunk.varNotes[v].off); - patch4(buf, at + 4, Chunk.varNotes[v].kind); - at := at + 8; - end; - end; - end; - linesOff := names; - linesSize := lpLen; - COPY(buf[names..names + lpLen], lp[0..lpLen]); - patch8(buf, 0, linesOff); - patch8(buf, 8, start); - patch8(buf, 16, stop); - patch8(buf, 24, np); - patch8(buf, 32, nv); - Chunk.setData(placesChunk, buf, names + lpLen, 8); -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. *) -proc linkAll*(headerSize, roExtra, dynSize: INT); -var c, f, at, p, e, v: INT; -begin - textOff := (headerSize + 31) div 32 * 32; (* as each code chunk is *) - e := place(Chunk.secText, Base + textOff); - textSize := e - (Base + textOff); - if placesChunk >= 0 then makePlaces(Base + textOff, e); end; - roOff := (textOff + textSize + 31) div 32 * 32; - roAdr := Base + Page + roOff; - e := place(Chunk.secRodata, roAdr); - extraAdr := (e + 7) div 8 * 8; - if roExtra > 0 then e := extraAdr + roExtra; end; - 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; - end; - e := place(Chunk.secBss, bssAdr + dynSize); - bssSize := e - bssAdr; - - textImg := Scan.grab(textSize + 1); - (* the gaps between code chunks are int3, a trap if ever run *) - for p := 0 to textSize do textImg[p] := 0CCH; end; - roImg := Scan.grab(roSize + 1); - for p := 0 to roSize do roImg[p] := 0; end; - for c := 0 to Chunk.numChunks - 1 do - if Chunk.chunks[c].live then - if Chunk.chunks[c].sec = Chunk.secText then - p := Chunk.chunks[c].adr - (Base + textOff); - COPY(textImg[p..p + Chunk.chunks[c].size], Chunk.text[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]); - for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do - at := Chunk.fixups[f].at - Chunk.chunks[c].start; - (* rel32: from the end of the field to the target *) - v := Chunk.chunks[Chunk.fixups[f].chunk].adr + Chunk.fixups[f].addend - - (Chunk.chunks[c].adr + at + 4); - patch4(textImg, p + at, v); - end; - elsif Chunk.chunks[c].sec = Chunk.secRodata then - p := Chunk.chunks[c].adr - roAdr; - COPY(roImg[p..p + Chunk.chunks[c].size], Chunk.rodata[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]); - for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do - patch8(roImg, p + Chunk.dataFixups[f].at, - Chunk.chunks[Chunk.dataFixups[f].chunk].adr + Chunk.dataFixups[f].addend); - end; - end; - end; - end; -end; - -begin - placesChunk := -1; -end Link. diff --git a/self/Parse.raz b/self/Parse.raz deleted file mode 100644 index c296d85..0000000 --- a/self/Parse.raz +++ /dev/null @@ -1,3775 +0,0 @@ -(* Parse: the parser. - - Reads modules by recursive descent and has Gen 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. - - The seed's errors ended in a jump back to the statement or - declaration being read (Scan.mark, longjmp). Here every routine that - can find an error returns an ERROR as its last result, and the ones - that call it pass it up with try, as Item does; the statement or - declaration that is a recovery point (guard) looks at what comes back - and reads on. What has been made by then is what the seed had made - when it jumped. A seed `var` that only gave a value back is a result - where that is shorter; the others stay as they were. A set of - Scan.Sym is a chain of tests, since it has more names than a set - holds. *) -module Parse; -import Fmt, Diag, Scan, Sym, Chunk, Gen, Item, Sys, Str, Buf, Heap; - -type - PType = ^Sym.Type; - PObj = ^Sym.Obj; - PModule = ^Sym.Module; - TItem = Item.Item; - - (* The innermost loop: the chain of its breaks and the deferred - statements in force outside it *) - Loop = record - brk: INT; - base: INT; - end; - PLoop = ^Loop; - - (* A generic module's import whose instance isn't made yet (deferred, - numDeferred); not to be confused with a defer statement (defers) *) - Deferred = record - o: PObj; (* the name it imports as *) - home: PModule; (* the module that imports it *) - mname: INT; (* the generic module *) - args: Scan.State; (* at the "(" of its arguments *) - at: Diag.Pos; (* the import *) - end; - -const - (* 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 reports once it knows what the program uses. *) - HasReals* = true; - - MaxNames = 64; (* names in one declaration, and the like *) - MaxFwd = 256; (* pointers to types not yet declared *) - MaxDefers = 64; (* defer statements in force *) - MaxDrops = 4096; (* calls that drop results, in one module *) - MaxDeferred = 64; (* generic imports not yet made *) - MaxLabels = 1024; (* labels of one match *) - MaxElements = 1024; (* elements of an array literal *) - MaxFixes = 4096; (* addresses in one constant *) - MaxPending = 64; (* modules being compiled at once *) - Suffixes: [4][]U8 = [".linux-x86_64", ".linux", ".x86_64", ""]; - -var - libDir*, mainDir: []U8; - incDirs*: [16][]U8; - numInc*: INT; - firstModule*, lastModule*: PModule; (* in the order they were finished *) - - checkMode: BOOL; (* reading a file only for its interface *) - inTypes: BOOL; (* in a type section: ^T may name a later type *) - fwdTypes: [MaxFwd]PType; - fwdPos: [MaxFwd]Diag.Pos; (* where each names its type *) - numFwd: INT; - lastCalled: PObj; (* the procedure the last call was of, if it had a name *) - passOn: BOOL; (* the next factor may be a call with several results, for return *) - curProc: PObj; (* the procedure being compiled, or nil *) - declExported: BOOL; (* the export mark of the declaration being read *) - curLoop: PLoop; (* the innermost loop, or nil *) - defers: [MaxDefers]INT; (* the defer statements in force, their code's addresses *) - numDefers: INT; - deferring: BOOL; (* compiling a defer statement's statement *) - directDefer: BOOL; (* ... as the statement itself, not in a list *) - deferSlot: I64; (* keeps a result while deferred statements run *) - curResult: PType; (* the result type of the procedure being compiled *) - inExtern: BOOL; (* reading an extern's signature: ... allowed *) - tArgv, tBodySig: PType; - nameRt, nameFail, nameBody, nameStatic, nameCheck, nameOff, nameAdr: INT; - declaring: [MaxNames]INT; (* the names the declaration being read declares *) - numDeclaring: INT; - skipped: BOOL; (* the last statement had an error and was skipped *) - deferred: [MaxDeferred]Deferred; (* generic imports not yet made, not defer statements *) - numDeferred: INT; - making: BOOL; (* reading an instance's arguments, at its first use *) - stray: BOOL; (* an "end" in this procedure stood left of its statement's line *) - strayAt: Diag.Pos; (* ... the first such statement *) - elseIf: BOOL; (* an "else if" in this procedure *) - drops: [MaxDrops]record - at: Diag.Pos; (* a call standing on its own that drops results *) - n: INT; (* ... how many *) - end; - numDrops: INT; (* the module being compiled has those from its - first one, saved by compileFile, to here *) - ends: BOOL; (* the statements just read never go on past - their end: each way through them returns *) - useAt: Diag.Pos; (* ... which is here *) - guards: INT; (* the recovery points open *) - -proc expression(var x: TItem; want: PType): ERROR; forward; -proc parseType: (PType, ERROR); forward; -proc statements: ERROR; forward; -proc statement: ERROR; forward; - -(* Little helpers *) - -proc setLibDir*(dir: []U8); -begin - libDir := dir; -end; - -proc addIncDir*(dir: []U8); -begin - incDirs[numInc] := dir; - INC(numInc); -end; - -proc nameOf(n: INT): []U8; -begin - return Scan.nameOf(n); -end; - -(* The name number of s, which isn't empty *) -proc internName(s: []U8): INT; -begin - return Scan.intern(ADR(s[0]), LEN(s)); -end; - -proc say1(f, a: []U8): []U8; -begin - return Diag.say(f, [Fmt.str(a)]); -end; - -proc say2(f, a, b: []U8): []U8; -begin - return Diag.say(f, [Fmt.str(a), Fmt.str(b)]); -end; - -proc say3(f, a, b, c: []U8): []U8; -begin - return Diag.say(f, [Fmt.str(a), Fmt.str(b), Fmt.str(c)]); -end; - -(* More than n of what, as a message *) -proc tooMany(n: INT; what: []U8): []U8; -begin - return Diag.say("more than {} {}", [Fmt.int(n), Fmt.str(what)]); -end; - -(* A missing symbol is reported just after the one before it. *) -proc expected(what: []U8): ERROR; -begin - if Scan.tok = Scan.sBlank then - return Scan.mark("_ isn't a name: it is the blank, which stands only left of :="); - end; - return Scan.markAt(Scan.missingPos(), say2("expected {}, found {}", what, Scan.found())); -end; - -proc expect(s: Scan.Sym): ERROR; -begin - if (Scan.tok = Scan.sLbrace) and ((s = Scan.sThen) or (s = Scan.sDo)) then - return Scan.markHelp(Scan.missingPos(), say2("expected {}, found {}", Scan.symText(s), Scan.found()), - say1("a block is written {} ... end", Scan.symText(s))); - end; - if Scan.tok # s then return expected(Scan.symText(s)); end; - Scan.next; - return nil; -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. *) -proc closeEnd(start: Diag.Pos; ind: INT): ERROR; -begin - if (Scan.tok = Scan.sEnd) and not stray and (Scan.indent() < ind) then - stray := true; - strayAt := start; - end; - return expect(Scan.sEnd); -end; - -(* The error of a procedure or module whose own "end" isn't where it - should be, with what closeEnd saw *) -proc endMissing(p: Diag.Pos; msg: []U8): ERROR; -begin - Diag.error(p, msg); - if stray then Diag.note(strayAt, "is this statement's \"end\" missing? one further left closes it"); end; - if elseIf then Diag.help("raz writes elsif: \"else if\" begins an if that needs its own \"end\""); end; - return Scan.Failed; -end; - -(* A name being declared, and whether it is exported; at is the name *) -proc identDef(var n: INT; var exp: BOOL; var at: Diag.Pos): ERROR; -begin - if Scan.tok # Scan.sIdent then return expected("a name"); end; - n := Scan.id; - at := Scan.tokPos(); - Scan.next; - exp := false; - if Scan.tok = Scan.sTimes then - exp := true; - Scan.next; - end; - return nil; -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. *) -proc declare(o: PObj): ERROR; -var m: PModule; -begin - m := Sym.curModule; - try Sym.insert(o, Sym.topScope()); - if Sym.topScope() = m^.scope then - if m^.last = nil then m^.first := o; else m^.last^.chain := o; end; - m^.last := o; - else - if m^.lastLocal = nil then m^.locals := o; else m^.lastLocal^.chain := o; end; - m^.lastLocal := o; - end; - return nil; -end; - -(* o is named: a procedure naming itself doesn't count *) -proc named(o: PObj); -begin - if o # curProc then - 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 when what it read comes back with - an error, 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 - Recover = record - scan: Scan.State; - scopes, depth, pushed, numDefers: INT; - guards: INT; - loop: PLoop; - result: PType; - deferring, directDefer, quiet: BOOL; - end; - -proc guard(var r: Recover); -begin - Scan.saveScan(r.scan); - r.guards := guards; - r.scopes := Sym.scopeDepth(); r.depth := Gen.depth; r.pushed := Gen.pushed; r.numDefers := numDefers; - r.loop := curLoop; r.result := curResult; - r.deferring := deferring; r.directDefer := directDefer; r.quiet := Diag.quiet; - INC(guards); - Diag.setQuiet(false); -end; - -proc unguard(var r: Recover); -begin - guards := r.guards; - Diag.setQuiet(r.quiet); - Scan.setSkipping(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 *) -proc restore(var r: Recover); -begin - Scan.restoreScan(r.scan); - Scan.setSkipping(true); - Sym.cutScopes(r.scopes); - Gen.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: the error - goes on up to the next recovery point, or ends the compile if there - is none *) -proc giveUp(var r: Recover): ERROR; -begin - unguard(r); - if guards = 0 then Diag.finish(); end; - return Scan.Failed; -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. *) -proc skipConstruct: BOOL; -var d, p: INT; prev: Scan.Sym; -begin - d := 0; p := 0; prev := Scan.sSemicolon; - repeat - match Scan.tok of - | sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: INC(d); - | sEnd, sUntil: - if d = 0 then return true; end; - DEC(d); - | sElse, sElsif: if (d = 0) and (p = 0) then return true; end; - | sBar: if (d = 0) and (p = 0) and (prev = Scan.sSemicolon) then return true; end; - | sLparen, sLbrak, sLbrace: INC(p); - | sRparen, sRbrak, sRbrace: if p > 0 then DEC(p); end; - | sSemicolon: if (d = 0) and (p = 0) then return true; end; - | sEof: return false; - | else: - end; - prev := Scan.tok; - Scan.next; - until Scan.atLineStart(); - return false; -end; - -(* Declares n where it is used, after it was reported as not declared, - or after the declaration of it had an error *) -proc poison(n: INT); -var o: PObj; -begin - o := Sym.newObj(Sym.oConst, n, Sym.tPoison); - _ := Sym.insert(o, Sym.topScope()); (* n isn't in this scope, so it can't be twice *) -end; - -proc willDeclare(n: INT); -begin - if numDeclaring < MaxNames then declaring[numDeclaring] := n; end; - INC(numDeclaring); -end; - -(* After a declaration had an error: its names are poison, and reading - goes on after it *) -proc skipDeclaration; -var i: INT; -begin - for i := 0 to numDeclaring - 1 do - if (i < MaxNames) and (Sym.find(Sym.topScope(), declaring[i]) = nil) then - poison(declaring[i]); - end; - end; - if skipConstruct() and (Scan.tok = Scan.sSemicolon) then Scan.next; end; -end; - -proc constValue(var x: TItem): (I64, ERROR); -begin - if x.mode # Item.mConst then return 0, Scan.markAt(x.pos, "expected a constant"); end; - return x.val, nil; -end; - -proc constExpr: (I64, ERROR); -var x: TItem; -begin - try expression(x, nil); - if not Sym.isInt(x.typ) then - return 0, Scan.markAt(x.pos, say1("expected an integer constant, found {}", Item.what(x))); - end; - return constValue(x); -end; - -(* Help after a name that isn't found: o, the closest name in reach *) -proc didYouMean(o: PObj); -begin - if o # nil then Diag.help(say1("did you mean {}?", nameOf(o^.name))); end; -end; - -(* Where module n is found, if it is: dir and the file in it *) -proc moduleFile(n: INT): ([]U8, []U8, BOOL); forward; - -(* name in lower case, in memory that is never freed, as messages are *) -proc lowerCase(s: []U8): []U8; -var p: ^U8; i: INT; -begin - if LEN(s) = 0 then return ""; end; - p := Scan.grab(LEN(s)); - for i := 0 to LEN(s) - 1 do - if (s[i] >= 'A') and (s[i] <= 'Z') then p[i] := s[i] + 32; else p[i] := s[i]; end; - end; - return p[0..LEN(s)]; -end; - -(* Reports name n at p as not declared, with what it may have meant *) -proc notDeclared(p: Diag.Pos; n: INT); -var found: BOOL; low: []U8; -begin - Diag.error(p, say1("{} isn't declared", nameOf(n))); - _, _, found := moduleFile(n); - low := lowerCase(nameOf(n)); - if found then Diag.help(say2("{} is a module: import {}", nameOf(n), nameOf(n))); - elsif (nameOf(n) = "elif") or (nameOf(n) = "elseif") then Diag.help("raz writes elsif"); - elsif Scan.reserved(internName(low)) then Diag.help(say1("a reserved word is written in lower case: {}", low)); - else didYouMean(Sym.closest(n, -1)); - end; -end; - -proc firstUse(o: PObj; at: Diag.Pos): ERROR; forward; -proc instancesFor(wholeRest: BOOL): ERROR; forward; -proc addImport(m, im: PModule); forward; - -proc qualIdent: (PObj, ERROR); -var o: PObj; m: PModule; at: Diag.Pos; -begin - if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; - at := Scan.tokPos(); - o := Sym.lookup(Scan.id); - if o = nil then - if not making then poison(Scan.id); end; (* it may yet be declared *) - Diag.setQuiet(false); - notDeclared(at, Scan.id); - if making then Diag.note(useAt, "the instance is made here, where it is first used"); end; - return nil, Scan.Failed; - end; - if o^.typ = Sym.tPoison then Diag.setQuiet(true); end; - named(o); - Scan.next; - if o^.cls = Sym.oModule then - if o^.home = nil then try firstUse(o, at); end; - try expect(Scan.sPeriod); - if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; - m := o^.home; - o := Sym.find(m^.scope, Scan.id); - if (o = nil) or not o^.exported then - Diag.error(Scan.tokPos(), say2("{} isn't exported by {}", nameOf(Scan.id), nameOf(m^.name))); - if o # nil then Diag.note(o^.pos, say1("{} is declared here, without a *", nameOf(Scan.id))); - else didYouMean(Sym.closest(Scan.id, m^.scope)); - end; - return nil, Scan.Failed; - end; - Scan.next; - end; - return o, nil; -end; - -(* The field of record type t named by the current symbol *) -proc fieldOf(t: PType): (PObj, ERROR); -var f: PObj; -begin - f := Sym.find(t^.scope, Scan.id); - if f = nil then - Diag.error(Scan.tokPos(), say2("{} has no field {}", Sym.typeName(t), nameOf(Scan.id))); - didYouMean(Sym.closest(Scan.id, t^.scope)); - return nil, Scan.Failed; - end; - if not f^.exported and (t^.home # Sym.curModule) then - Diag.error(Scan.tokPos(), say2("field {} of {} isn't exported", nameOf(Scan.id), Sym.typeName(t))); - Diag.note(f^.pos, say1("{} is declared here, without a *", nameOf(Scan.id))); - return nil, Scan.Failed; - end; - return f, nil; -end; - -proc newPtr(base: PType; vol: BOOL): PType; -var t: PType; -begin - t := Sym.newType(Sym.fPtr, 8, 8); - t^.base := base; - t^.vol := vol; - return t; -end; - -(* Types *) - -proc recordType: (PType, ERROR); -var - t, ft: PType; f, last: PObj; names: [MaxNames]INT; - exps: [MaxNames]BOOL; poss: [MaxNames]Diag.Pos; - n, i: INT; off, a, maxA: I64; -begin - t := Sym.newType(Sym.fRecord, 0, 1); - if Scan.tok = Scan.sPacked then t^.packd := true; Scan.next; end; - try expect(Scan.sRecord); - t^.scope := Sym.newScope(); - off := 0; maxA := 1; last := nil; - while Scan.tok = Scan.sIdent do - n := 0; - repeat - if n >= MaxNames then return nil, Scan.mark(tooMany(MaxNames, "names in one declaration")); end; - try identDef(names[n], exps[n], poss[n]); - INC(n); - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - try expect(Scan.sColon); - ft := try parseType(); - if t^.packd then a := 1; else a := ft^.align; end; - for i := 0 to n - 1 do - off := Sym.alignUp(off, a); - f := Sym.newObj(Sym.oField, names[i], ft); - f^.exported := exps[i]; - f^.pos := poss[i]; - f^.val := off; - try Sym.insert(f, t^.scope); - if last = nil then t^.fields := f; else last^.next := f; end; - last := f; - off := off + ft^.size; - end; - if a > maxA then maxA := a; end; - try expect(Scan.sSemicolon); - end; - try expect(Scan.sEnd); - t^.align := maxA; - t^.size := Sym.alignUp(off, maxA); - return t, nil; -end; - -proc variantType: (PType, ERROR); -var t, ft: PType; c, lastC, f, lastF: PObj; tag, off, maxSize: I64; -begin - try expect(Scan.sVariant); - t := Sym.newType(Sym.fVariant, 8, 8); - tag := 0; maxSize := 8; lastC := nil; - while Scan.tok = Scan.sIdent do - c := Sym.newObj(Sym.oCase, Scan.id, t); - c^.val := tag; - c^.exported := declExported; - try declare(c); - if lastC = nil then t^.fields := c; else lastC^.next := c; end; - lastC := c; - Scan.next; - off := 8; - if Scan.tok = Scan.sLparen then - Scan.next; - lastF := nil; - repeat - repeat - if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; - f := Sym.newObj(Sym.oField, Scan.id, nil); - f^.exported := true; - if lastF = nil then c^.fields := f; else lastF^.next := f; end; - lastF := f; - Scan.next; - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - try expect(Scan.sColon); - ft := try parseType(); - f := c^.fields; - while f^.typ # nil do f := f^.next; end; - while f # nil do - f^.typ := ft; - off := Sym.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; end; - if Scan.tok # Scan.sSemicolon then break; end; - Scan.next; - until false; - try expect(Scan.sRparen); - end; - if off > maxSize then maxSize := off; end; - try expect(Scan.sSemicolon); - INC(tag); - end; - try expect(Scan.sEnd); - t^.len := tag; - t^.size := Sym.alignUp(maxSize, t^.align); - return t, nil; -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. *) -proc results: (PType, ERROR); -var t, ft: PType; f, last: PObj; off: I64; -begin - Scan.next; - t := Sym.newType(Sym.fRecord, 0, 1); - t^.tuple := true; - off := 0; last := nil; - repeat - ft := try parseType(); - off := Sym.alignUp(off, ft^.align); - f := Sym.newObj(Sym.oField, -1, ft); - f^.val := off; - off := off + ft^.size; - if ft^.align > t^.align then t^.align := ft^.align; end; - if last = nil then t^.fields := f; else last^.next := f; end; - last := f; - INC(t^.len); - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - try expect(Scan.sRparen); - t^.size := Sym.alignUp(off, t^.align); - if t^.len = 1 then return t^.fields^.typ, nil; end; - return t, nil; -end; - -proc signature: (PType, ERROR); -var - t, pt: PType; p, first, last: PObj; isVar: BOOL; n: INT; -begin - t := Sym.newType(Sym.fProc, 8, 8); - last := nil; n := 0; - if Scan.tok = Scan.sLparen then - Scan.next; - if Scan.tok # Scan.sRparen then - repeat - if Scan.tok = Scan.sEllipsis then - if not inExtern then return nil, Scan.mark("... is only for extern procedures"); end; - Scan.next; t^.variadic := true; break; - end; - isVar := Scan.tok = Scan.sVar; - if isVar then Scan.next; end; - first := nil; - repeat - if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; - p := Sym.newObj(Sym.oVar, Scan.id, nil); - p^.isVar := isVar; - p^.lev := 1; - if last = nil then t^.fields := p; else last^.next := p; end; - last := p; - if first = nil then first := p; end; - INC(n); - Scan.next; - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - try expect(Scan.sColon); - pt := try parseType(); - while first # nil do first^.typ := pt; first := first^.next; end; - if Scan.tok # Scan.sSemicolon then break; end; - Scan.next; - until false; - end; - try expect(Scan.sRparen); - end; - t^.len := n; - if Scan.tok = Scan.sColon then - Scan.next; - if Scan.tok = Scan.sLparen then t^.base := try results(); else t^.base := try parseType(); end; - end; - return t, nil; -end; - -proc enumType: (PType, ERROR); -var t: PType; o, last: PObj; start: Diag.Pos; -begin - start := Scan.tokPos(); - t := Sym.newType(Sym.fEnum, 1, 1); - last := nil; - repeat - Scan.next; - if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; - o := Sym.newObj(Sym.oConst, Scan.id, t); - o^.val := t^.len; - o^.exported := declExported; - o^.used := true; (* an enumeration's names are its type's, warned of with it *) - try declare(o); - if last = nil then t^.fields := o; else last^.next := o; end; - last := o; - INC(t^.len); - Scan.next; - until Scan.tok # Scan.sComma; - try expect(Scan.sRparen); - if t^.len > 256 then return nil, Scan.markAt(Scan.spanFrom(start), "an enumeration has at most 256 names"); end; - return t, nil; -end; - -proc setOf(e: PType; at: Diag.Pos): (PType, ERROR); -var t: PType; -begin - if (e^.form # Sym.fEnum) or (e^.len > 64) then - return nil, Scan.markAt(at, say1("a set needs an enumeration of at most 64 names, found {}", Sym.typeName(e))); - end; - t := Sym.newType(Sym.fSet, 8, 8); - if e^.len <= 8 then t^.size := 1; - elsif e^.len <= 16 then t^.size := 2; - elsif e^.len <= 32 then t^.size := 4; - end; - t^.align := t^.size; - t^.base := e; - t^.len := e^.len; - return t, nil; -end; - -proc parseType: (PType, ERROR); -var t: PType; o: PObj; n: I64; vol: BOOL; start: Diag.Pos; -begin - start := Scan.tokPos(); - match Scan.tok of - | sIdent: - o := try qualIdent(); - if o^.cls # Sym.oType then - return nil, Scan.markAt(Scan.spanFrom(start), say1("{} isn't a type", nameOf(o^.name))); - end; - t := o^.typ; - | sLbrak: - Scan.next; - if Scan.tok = Scan.sRbrak then - Scan.next; - t := Sym.newType(Sym.fSlice, 16, 8); - t^.base := try parseType(); - else - start := Scan.tokPos(); - n := try constExpr(); - if (n <= 0) or (n > (I64(1) shl 40)) then - return nil, Scan.markAt(Scan.spanFrom(start), Diag.say("an array's length is from 1 to 2^40, found {}", [Fmt.int(n)])); - end; - try expect(Scan.sRbrak); - t := Sym.newType(Sym.fArray, 0, 1); - t^.len := n; - t^.base := try parseType(); - t^.size := n * t^.base^.size; - t^.align := t^.base^.align; - end; - | sArrow: - Scan.next; - vol := Scan.tok = Scan.sVolatile; - if vol then Scan.next; end; - if inTypes and (Scan.tok = Scan.sIdent) and (Sym.lookup(Scan.id) = nil) then - (* a type declared later in this section *) - t := newPtr(nil, vol); - t^.fwd := Scan.id; - if numFwd >= MaxFwd then - return nil, Scan.mark(tooMany(MaxFwd, "pointers to types not yet declared")); - end; - fwdTypes[numFwd] := t; - fwdPos[numFwd] := Scan.tokPos(); - INC(numFwd); - Scan.next; - else - t := newPtr(try parseType(), vol); - end; - | sPacked, sRecord: t := try recordType(); - | sVariant: t := try variantType(); - | sProc: Scan.next; t := try signature(); - | sLparen: t := try enumType(); - | sSet: - Scan.next; - try expect(Scan.sOf); - start := Scan.tokPos(); - t := try setOf(try parseType(), start); - | else: return nil, expected("a type"); - end; - return t, nil; -end; - -(* Expressions *) - -proc call(var x: TItem): ERROR; -var c: Gen.CallInfo; a: TItem; want: PType; -begin - try Item.beginCall(c, x); - try expect(Scan.sLparen); - if Scan.tok # Scan.sRparen then - repeat - if c.param # nil then want := c.param^.typ; else want := nil; end; - try expression(a, want); - try Item.passArg(c, a); - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - end; - try expect(Scan.sRparen); - return Item.endCall(c, x); -end; - -proc atomic(var x: TItem; which: INT): ERROR; -var p, a: TItem; t: PType; i, n: INT; -begin - try expression(p, nil); - if p.typ^.form # Sym.fPtr then - return Scan.markAt(p.pos, say1("expected a pointer, found {}", Item.what(p))); - end; - t := p.typ^.base; - if not (Item.isWord(t) or ((t^.form = Sym.fPtr) and (which # Sym.bXadd))) then - if which = Sym.bXadd then - return Scan.markAt(p.pos, say1("expected a pointer to an INT or a UINT, found {}", Sym.typeName(p.typ))); - end; - return Scan.markAt(p.pos, say1("expected a pointer to an INT, a UINT or a pointer, found {}", Sym.typeName(p.typ))); - end; - try Item.value(p); - if which = Sym.bCas then n := 2; else n := 1; end; - for i := 1 to n do - try expect(Scan.sComma); - try expression(a, t); - try Item.coerce(a, t); - try Item.value(a); - end; - Gen.atomic(which); - Item.makeConst(x, t, 0); - if which = Sym.bCas then x.typ := Sym.tBool; end; - x.mode := Item.mStack; - return nil; -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. *) -proc new_(var x: TItem): ERROR; -var y, z: TItem; t: PType; f: PObj; s: I64; c: Gen.CallInfo; -begin - try expression(x, nil); - try Item.notReadOnly(x); - if (x.mode # Item.mVar) or not x.isVar or (x.typ^.form # Sym.fPtr) then - return Scan.markAt(x.pos, "NEW needs a pointer variable"); - end; - t := x.typ^.base; - try expect(Scan.sComma); - try expression(y, nil); - if (y.typ^.form # Sym.fPtr) or (y.typ^.base^.obj = nil) or (y.typ^.base^.obj^.home = nil) - or (nameOf(y.typ^.base^.obj^.name) # "Allocator") - or (nameOf(y.typ^.base^.obj^.home^.name) # "Mem") then - return Scan.markAt(y.pos, say1("NEW needs a ^Mem.Allocator, found {}", Item.what(y))); - end; - f := Sym.find(y.typ^.base^.scope, internName("alloc")); - s := try Item.toSlot(y); - Gen.pushVar(Item.frameAdr(s), 8, false, Gen.kWord); - Item.makeConst(z, f^.typ, 0); - z.mode := Item.mVar; z.base := Gen.bStack; z.off := f^.val; - try Item.beginCall(c, z); - Gen.pushVar(Item.frameAdr(s), 8, false, Gen.kWord); - Item.makeConst(z, y.typ, 0); - z.mode := Item.mStack; - try Item.passArg(c, z); - Item.makeConst(z, Sym.tInt, t^.size); - try Item.passArg(c, z); - Item.makeConst(z, Sym.tInt, t^.align); - try Item.passArg(c, z); - try Item.endCall(c, z); - Gen.zeroNew(t^.size); - z.typ := x.typ; - try Item.assign(x, z); - Item.makeConst(x, Sym.tNone, 0); - x.mode := Item.mNone; - return nil; -end; - -proc incOrDec(which: INT): []U8; -begin - if which = Sym.bDec then return "DEC"; end; - return "INC"; -end; - -proc builtin(var x: TItem): ERROR; -var which, n: INT; y: TItem; t: PType; -begin - which := INT(x.obj^.val); - if (which = Sym.bFence) or (which = Sym.bArgc) or (which = Sym.bArgv) then - if Scan.tok = Scan.sLparen then Scan.next; try expect(Scan.sRparen); end; - Item.makeConst(x, Sym.tNone, 0); - match which of - | Sym.bFence: Gen.fence(); x.mode := Item.mNone; - | Sym.bArgc: - Gen.pushVar(Item.globalAdr(Gen.argcChunk), 8, false, Gen.kWord); - x.typ := Sym.tInt; x.mode := Item.mStack; - | else: - Gen.pushVar(Item.globalAdr(Gen.argvChunk), 8, false, Gen.kWord); - x.typ := tArgv; x.mode := Item.mStack; - end; - return nil; - end; - try expect(Scan.sLparen); - match which of - | Sym.bSize: - t := try parseType(); - Item.makeConst(x, Sym.tConst, t^.size); - | Sym.bAdr: - try expression(y, nil); - try Item.notReadOnly(y); - if (y.mode # Item.mVar) or not y.isVar then return Scan.markAt(y.pos, "ADR needs a variable"); end; - if y.odd then return Scan.markAt(y.pos, "a field of a packed record has no address"); end; - t := newPtr(y.typ, y.vol); - try Item.address(y); - Item.makeConst(x, t, 0); - x.mode := Item.mStack; - | Sym.bLen: - try expression(y, nil); - if y.mode = Item.mStr then - Item.makeConst(x, Sym.tConst, y.val); - elsif y.typ^.form = Sym.fArray then - try Item.discard(y); - Item.makeConst(x, Sym.tConst, y.typ^.len); - elsif (y.typ^.form = Sym.fSlice) and (y.mode = Item.mVar) then - (* its length, the word after its pointer *) - y.off := y.off + 8; - y.typ := Sym.tInt; - try Item.value(y); - x := y; - else - return Scan.markAt(y.pos, say1("LEN needs an array or a slice, found {}", Item.what(y))); - end; - | Sym.bSyscall: - n := 0; - repeat - if n > 0 then Scan.next; end; - try expression(y, nil); - if not (Sym.isScalar(y.typ) and (y.typ^.form # Sym.fReal)) then - return Scan.markAt(y.pos, say1("expected an integer or a pointer, found {}", Item.what(y))); - end; - if y.typ^.form = Sym.fConst then try Item.coerce(y, Sym.tInt); end; - try Item.value(y); - INC(n); - until (Scan.tok # Scan.sComma) or (n = 7); - Gen.sysCall(n); - Item.makeConst(x, Sym.tInt, 0); - x.mode := Item.mStack; - | Sym.bCas, Sym.bXchg, Sym.bXadd: try atomic(x, which); - | Sym.bMsg: - try expression(x, Sym.tError); - try Item.msg(x); - | Sym.bInc, Sym.bDec: - try expression(x, nil); - try Item.notReadOnly(x); - if (x.mode # Item.mVar) or not x.isVar or (x.typ^.form # Sym.fInt) then - return Scan.markAt(x.pos, say1("{} needs an integer variable", incOrDec(which))); - end; - if x.base # Gen.bReg then try Item.address(x); end; - if Scan.tok = Scan.sComma then - Scan.next; - try expression(y, x.typ); - else - Item.makeConst(y, x.typ, 1); - end; - try Item.incDec(x, y, which = Sym.bDec); - Item.makeConst(x, Sym.tNone, 0); - x.mode := Item.mNone; - | Sym.bNew: try new_(x); - | Sym.bCopy: - try expression(x, nil); - try Item.copyDest(x); - try expect(Scan.sComma); - try expression(y, nil); - try Item.copyFrom(x, y); - Item.makeConst(x, Sym.tNone, 0); - x.mode := Item.mNone; - | else: - end; - return expect(Scan.sRparen); -end; - -proc constructCase(var x: TItem; c: PObj; at: Diag.Pos): ERROR; -var f: PObj; a: TItem; -begin - Item.construct(x, c); - f := c^.fields; - if Scan.tok = Scan.sLparen then - Scan.next; - while f # nil do - try expression(a, f^.typ); - try Item.setField(x, f, a); - f := f^.next; - if f # nil then try expect(Scan.sComma); end; - end; - return expect(Scan.sRparen); - elsif f # nil then - return Scan.markAt(at, say1("{} needs its fields", nameOf(c^.name))); - end; - return nil; -end; - -(* x, before ".", has no fields; tok is what follows. Other languages - write p.f through a pointer and s.len for a length. *) -proc fieldOfWhat(x: TItem): ERROR; -var msg, f: []U8; -begin - msg := say1("expected a record, found {}", Item.what(x)); - if Scan.tok = Scan.sIdent then f := nameOf(Scan.id); else f := ""; end; - if (x.typ^.form = Sym.fPtr) and (x.typ^.base^.form = Sym.fRecord) then - return Scan.markHelp(x.pos, msg, say2("through a pointer, write {}^.{}", Diag.source(x.pos), f)); - elsif ((x.typ^.form = Sym.fArray) or (x.typ^.form = Sym.fSlice)) - and ((f = "len") or (f = "length") or (f = "size") or (f = "count")) then - return Scan.markHelp(x.pos, msg, say1("its length is LEN({})", Diag.source(x.pos))); - end; - return Scan.markAt(x.pos, msg); -end; - -(* A designator, with any selectors and calls after it. called tells - whether the last thing done was a call. *) -proc designator(var x: TItem; var called: BOOL): ERROR; -var o, f: PObj; y, z: TItem; t: PType; start: Diag.Pos; -begin - start := Scan.tokPos(); - o := try qualIdent(); - called := false; - if o^.cls = Sym.oModule then - return Scan.markAt(Scan.spanFrom(start), say1("{} is a module, not a value", nameOf(o^.name))); - end; - try Item.makeItem(x, o); - if x.mode = Item.mBuiltin then - try builtin(x); - called := true; - elsif x.mode = Item.mCase then - try constructCase(x, o, Scan.spanFrom(start)); - end; - repeat - x.pos := Scan.spanFrom(start); - match Scan.tok of - | sPeriod: - Scan.next; - if (x.mode # Item.mVar) or (x.typ^.form # Sym.fRecord) then return fieldOfWhat(x); end; - if Scan.tok # Scan.sIdent then return expected("a field"); end; - f := try fieldOf(x.typ); - Scan.next; - try Item.field(x, f); - called := false; - | sArrow: - Scan.next; - try Item.deref(x); - called := false; - | sLbrak: - Scan.next; - try Item.indexPrep(x); - try expression(y, nil); - if Scan.tok = Scan.sUpto then - Scan.next; - try Item.sliceLo(y); - try expression(z, nil); - try Item.slice(x, y, z); - else - try Item.index(x, y); - end; - try expect(Scan.sRbrak); - called := false; - | sLparen: - if x.mode = Item.mType then - t := x.typ; - Scan.next; - try expression(x, nil); - try expect(Scan.sRparen); - try Item.convert(x, t); - else - if x.mode = Item.mProc then lastCalled := x.obj; else lastCalled := nil; end; - try call(x); - called := true; - end; - | else: break; - end; - until false; - x.pos := Scan.spanFrom(start); - Item.nilTest(x); - return nil; -end; - -proc arrayLiteral(var x: TItem; want: PType): ERROR; -var - et, at: PType; e: TItem; slots: [MaxElements]I64; n, i: INT; - off, es: I64; start: Diag.Pos; -begin - start := Scan.tokPos(); - if (want = nil) or not ((want^.form = Sym.fArray) or (want^.form = Sym.fSlice)) then - return Scan.mark("an array literal needs a known array or slice type"); - end; - et := want^.base; - es := et^.size; - Scan.next; - n := 0; - if Scan.tok # Scan.sRbrak then - repeat - if n >= MaxElements then return Scan.mark(tooMany(MaxElements, "elements")); end; - try expression(e, et); - try Item.coerce(e, et); - if Sym.isScalar(et) then - slots[n] := try Item.toSlot(e); - else - if e.isVar or e.vol or (e.mode # Item.mVar) or (e.base # Gen.bFrame) then try Item.copyToTemp(e); end; - slots[n] := e.off; - end; - INC(n); - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - end; - try expect(Scan.sRbrak); - if (want^.form = Sym.fArray) and (I64(n) # want^.len) then - return Scan.markAt(Scan.spanFrom(start), Diag.say("expected {} elements, found {}", [Fmt.int(want^.len), Fmt.int(n)])); - end; - if n = 0 then - Gen.pushConst(Gen.kWord, 0); - Item.sliceOf(x, want, 0); - return nil; - end; - if want^.form = Sym.fArray then - at := want; - off := Gen.allocTemp(at^.size, at^.align); - else - at := Sym.newType(Sym.fArray, I64(n) * es, et^.align); - at^.len := n; - at^.base := et; - off := Gen.allocPerm(at^.size, at^.align); (* lives as long as the call *) - end; - for i := 0 to n - 1 do - if Sym.isScalar(et) then - Gen.pushVar(Item.frameAdr(slots[i]), 8, false, Gen.kindOf(et)); - Gen.popVar(Item.frameAdr(off + I64(i) * es), Item.scalarSize(et)); - else - Gen.pushAdr(Item.frameAdr(slots[i])); - Gen.copyTo(Item.frameAdr(off + I64(i) * es), es); - end; - end; - Item.tempItem(x, at, off); - return nil; -end; - -(* A record literal: a zeroed temporary, with the fields named filled in. *) -proc recordLiteral(var x: TItem; t: PType): ERROR; -var f: PObj; a: TItem; seen: [MaxNames]INT; n, i: INT; -begin - Scan.next; - Item.zeroTemp(x, t); - n := 0; - if Scan.tok # Scan.sRbrace then - repeat - if Scan.tok # Scan.sIdent then return expected("a field"); end; - f := try fieldOf(t); - for i := 0 to n - 1 do - if seen[i] = Scan.id then - return Scan.mark(say1("field {} is given twice", nameOf(Scan.id))); - end; - end; - if n < MaxNames then seen[n] := Scan.id; INC(n); end; - Scan.next; - try expect(Scan.sColon); - try expression(a, f^.typ); - try Item.setField(x, f, a); - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - end; - return expect(Scan.sRbrace); -end; - -(* A set literal: the bits of the constant names, or'd at run time with - those of the others. *) -proc setLiteral(var x: TItem; t: PType): ERROR; -var e: TItem; bits, slot: I64; start: Diag.Pos; s: []U8; -begin - start := Scan.tokPos(); - Scan.next; - if (t # nil) and (t^.form # Sym.fSet) then - return Scan.markAt(Scan.spanFrom(start), say1("expected a set type, found {}", Sym.typeName(t))); - end; - bits := 0; - slot := 0; - if Scan.tok # Scan.sRbrace then - repeat - if t = nil then try expression(e, nil); else try expression(e, t^.base); end; - if t = nil then - if e.typ^.form # Sym.fEnum then - return Scan.markAt(e.pos, say1("a set holds names of an enumeration, found {}", Item.what(e))); - end; - t := try setOf(e.typ, e.pos); - end; - if not Sym.same(e.typ, t^.base) then - if e.obj # nil then s := nameOf(e.obj^.name); else s := Item.what(e); end; - return Scan.markAt(e.pos, say2("{} isn't a name of {}", s, Sym.typeName(t^.base))); - end; - if e.mode = Item.mConst then - bits := bits | (I64(1) shl e.val); - else - if slot = 0 then - slot := Gen.allocTemp(8, 8); - Gen.pushConst(Gen.kWord, 0); - Gen.popVar(Item.frameAdr(slot), 8); - end; - try Item.value(e); - Gen.pushConst(Gen.kWord, 1); - Gen.swap(); - Gen.op(Scan.sShl, Gen.kWord, 8, false); - Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord); - Gen.op(Scan.sBar, Gen.kWord, 8, false); - Gen.popVar(Item.frameAdr(slot), 8); - end; - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - end; - try expect(Scan.sRbrace); - if t = nil then return Scan.markAt(Scan.spanFrom(start), "{} needs a known set type"); end; - Item.makeConst(x, t, bits); - if slot # 0 then - Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord); - Gen.pushConst(Gen.kWord, bits); - Gen.op(Scan.sBar, Gen.kWord, 8, false); - x.mode := Item.mStack; - end; - return nil; -end; - -proc runDefers(base: INT); 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. *) -proc lastResult(t: PType): PType; -var f: PObj; -begin - if not t^.tuple then return t; end; - f := t^.fields; - while f^.next # nil do f := f^.next; end; - return f^.typ; -end; - -(* The results of the tuple t but the last: the same fields, one fewer *) -proc withoutLast(t: PType): PType; -var r: PType; -begin - r := Sym.newType(Sym.fRecord, t^.size, t^.align); - r^.tuple := true; - r^.fields := t^.fields; - r^.len := t^.len - 1; - return 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. *) -proc tryCall(var x: TItem): ERROR; -var - called: BOOL; c: Gen.CallInfo; start, at: Diag.Pos; res: PType; last: PObj; slot: I64; ok: INT; -begin - start := Scan.tokPos(); - Scan.next; - if deferring then return Scan.markAt(Scan.spanFrom(start), "try can't leave a deferred statement"); end; - if curResult = nil then - return Scan.markAt(Scan.spanFrom(start), "try needs a procedure that ends in an ERROR result, and this returns nothing"); - elsif lastResult(curResult) # Sym.tError then - return Scan.markAt(Scan.spanFrom(start), - say1("try needs a procedure that ends in an ERROR result, and this returns {}", Sym.typeName(curResult))); - end; - try designator(x, called); - if not called and ((x.mode = Item.mProc) - or (((x.mode = Item.mVar) or (x.mode = Item.mStack)) and (x.typ^.form = Sym.fProc))) then - (* a procedure without parameters, written without parentheses *) - at := x.pos; - try Item.beginCall(c, x); - try Item.endCall(c, x); - x.pos := at; - called := true; - end; - if not called then return Scan.markAt(x.pos, say1("try needs a call, found {}", Item.what(x))); end; - if x.mode = Item.mNone then - return Scan.markAt(x.pos, "try needs a call that returns an ERROR last, and this returns nothing"); - end; - if lastResult(x.typ) # Sym.tError then - return Scan.markAt(x.pos, say1("try needs a call that returns an ERROR last, and this returns {}", Sym.typeName(x.typ))); - end; - res := x.typ; - if x.mode = Item.mStack then - (* an ERROR alone *) - slot := Gen.allocTemp(8, 8); - Gen.popVar(Item.frameAdr(slot), 8); - x.mode := Item.mNone; x.typ := Sym.tNone; - elsif x.mode = Item.mWords then - (* two words, the error on top *) - slot := Gen.allocTemp(8, 8); - Gen.popVar(Item.frameAdr(slot), 8); - x.mode := Item.mStack; x.typ := res^.fields^.typ; - else - (* several, in a temporary: the error is where it is *) - last := res^.fields; - while last^.next # nil do last := last^.next; end; - slot := x.off + last^.val; - if res^.len = 2 then try Item.field(x, res^.fields); else x.typ := withoutLast(res); end; - end; - ok := Gen.NoLabel; - Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord); - Gen.jumpIf(ok, false); - if numDefers > 0 then Gen.tryAlign(); end; - runDefers(0); - Gen.tryReturn(slot); - Gen.fix(ok); - x.pos := Scan.spanFrom(start); - return nil; -end; - -proc factor(var x: TItem; want: PType): ERROR; -var called, vol, several: BOOL; t: PType; start: Diag.Pos; s: []U8; -begin - several := passOn; - passOn := false; - start := Scan.tokPos(); - match Scan.tok of - | sInt, sChar: - (* only a hex number can be above high(I64), and it is a U64 *) - if Scan.ival < 0 then Item.makeConst(x, Sym.tU64, Scan.ival); else Item.makeConst(x, Sym.tConst, Scan.ival); end; - Scan.next; - | sReal: - Item.makeReal(x, Scan.rval); - Item.usesReals(Scan.tokPos()); - Scan.next; - | sString: - Item.makeStr(x); - Scan.next; - | sIdent: - try designator(x, called); - if x.mode = Item.mNone then - if lastCalled # nil then s := nameOf(lastCalled^.name); else s := "this procedure"; end; - return Scan.markAt(x.pos, say1("{} returns nothing", s)); - end; - if x.typ^.tuple and not several then - if lastCalled # nil then s := nameOf(lastCalled^.name); else s := "this procedure"; end; - return Scan.markHelp(x.pos, say1("{} returns several results", s), - say1("they go to variables: a, b := {}(...)", s)); - end; - | sLparen: - Scan.next; - try expression(x, want); - try expect(Scan.sRparen); - | sTry: - try tryCall(x); - if x.mode = Item.mNone then return Scan.markAt(x.pos, "this try has no value"); end; - if x.typ^.tuple then - return Scan.markHelp(x.pos, "this try has several values", "they go to variables: a, b := try f(...)"); - end; - | sNot: - Scan.next; - try factor(x, nil); - try Item.notOp(x); - | sTilde: - Scan.next; - try factor(x, nil); - try Item.complement(x); - | sLbrak: try arrayLiteral(x, want); - | sLbrace: - if (want # nil) and (want^.form = Sym.fRecord) then try recordLiteral(x, want); - else try setLiteral(x, want); - end; - | sArrow: - Scan.next; - vol := Scan.tok = Scan.sVolatile; - if vol then Scan.next; end; - t := try parseType(); - t := newPtr(t, vol); - try expect(Scan.sLparen); - try expression(x, nil); - try expect(Scan.sRparen); - try Item.convert(x, t); - (* a conversion is a factor, not a designator: nothing selects from it *) - if Scan.tok = Scan.sArrow then - return Scan.markHelp(Scan.tokPos(), "a conversion can't be dereferenced", - "convert into a pointer variable, then dereference that"); - end; - | else: return expected("an expression"); - end; - x.pos := Scan.spanFrom(start); - return nil; -end; - -proc isMulOp: BOOL; -begin - match Scan.tok of - | sTimes, sSlash, sDiv, sMod, sAmp, sShl, sShr: return true; - | else: return false; - end; -end; - -proc isAddOp: BOOL; -begin - match Scan.tok of - | sPlus, sMinus, sBar, sXor: return true; - | else: return false; - end; -end; - -proc isRelOp: BOOL; -begin - match Scan.tok of - | sEql, sNeq, sLss, sLeq, sGtr, sGeq, sIn: return true; - | else: return false; - end; -end; - -proc term(var x: TItem; want: PType): ERROR; -var op: Scan.Sym; y: TItem; L: INT; start: Diag.Pos; -begin - start := Scan.tokPos(); - try factor(x, want); - while isMulOp() do - op := Scan.tok; - Scan.next; - try Item.op1(op, x, L); - try factor(y, nil); - try Item.op2(op, x, y, L); - x.pos := Scan.spanFrom(start); - end; - return nil; -end; - -proc simpleExpr(var x: TItem; want: PType): ERROR; -var op: Scan.Sym; y: TItem; L: INT; start: Diag.Pos; -begin - start := Scan.tokPos(); - if Scan.tok = Scan.sMinus then - Scan.next; - try term(x, nil); - x.pos := Scan.spanFrom(start); - try Item.neg(x); - else - try term(x, want); - end; - while isAddOp() do - op := Scan.tok; - Scan.next; - try Item.op1(op, x, L); - try term(y, nil); - try Item.op2(op, x, y, L); - x.pos := Scan.spanFrom(start); - end; - return nil; -end; - -proc relation(var x: TItem; want: PType): ERROR; -var op: Scan.Sym; y: TItem; L: INT; -begin - try simpleExpr(x, want); - if isRelOp() then - op := Scan.tok; - Scan.next; - try Item.op1(op, x, L); - if op = Scan.sIn then try simpleExpr(y, nil); else try simpleExpr(y, x.typ); end; - try Item.op2(op, x, y, L); - x.pos := Diag.join(x.pos, y.pos); - end; - return nil; -end; - -(* and binds tighter than or, and both below the relations *) -proc conjunct(var x: TItem; want: PType): ERROR; -var y: TItem; L: INT; start: Diag.Pos; -begin - start := Scan.tokPos(); - try relation(x, want); - while Scan.tok = Scan.sAnd do - Scan.next; - try Item.op1(Scan.sAnd, x, L); - try relation(y, nil); - try Item.op2(Scan.sAnd, x, y, L); - x.pos := Scan.spanFrom(start); - end; - return nil; -end; - -proc expression(var x: TItem; want: PType): ERROR; -var y: TItem; L: INT; start: Diag.Pos; -begin - start := Scan.tokPos(); - try conjunct(x, want); - while Scan.tok = Scan.sOr do - Scan.next; - try Item.op1(Scan.sOr, x, L); - try conjunct(y, nil); - try Item.op2(Scan.sOr, x, y, L); - x.pos := Scan.spanFrom(start); - end; - return nil; -end; - -(* Statements *) - -proc enterLoop(var lp: Loop; var old: PLoop); -begin - lp.brk := Gen.NoLabel; - lp.base := numDefers; - old := curLoop; - curLoop := ADR(lp); -end; - -(* Runs the deferred statements in force above base, newest first. *) -proc runDefers(base: INT); -var i: INT; -begin - for i := numDefers - 1 to base by -1 do Gen.runDefer(defers[i]); end; -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. *) -proc loneBreak: BOOL; -var st: Scan.State; lone: BOOL; -begin - if (Scan.tok # Scan.sBreak) or (curLoop = nil) or (numDefers # curLoop^.base) then return false; end; - Scan.saveScan(st); - lone := false; - Scan.next; - if Scan.tok = Scan.sSemicolon then - Scan.next; - lone := (Scan.tok = Scan.sEnd) or (Scan.tok = Scan.sElsif) or (Scan.tok = Scan.sElse); - end; - Scan.restoreScan(st); - return lone; -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. *) -proc thenPart(var x: TItem; var L: INT): ERROR; -begin - try expect(Scan.sThen); - L := Gen.NoLabel; (* stays so with a lone break: there is nothing to skip *) - if loneBreak() then - Chunk.noteLine(Scan.curLine(), Scan.curCol()); (* the jump gets the break's line *) - try Item.condJumpTrue(x, curLoop^.brk); - Scan.next; Scan.next; (* skip "break" and ";" *) - ends := true; - else - try Item.condJump(x, L); - try statements(); - end; - return nil; -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. *) -proc ifStatement(start: Diag.Pos; ind: INT): ERROR; -var x: TItem; L, endL: INT; all: BOOL; -begin - Scan.next; - try expression(x, nil); - try thenPart(x, L); - all := ends; - endL := Gen.NoLabel; - while Scan.tok = Scan.sElsif do - if not ends then Gen.jump(endL); end; - Gen.fix(L); - Scan.next; - try expression(x, nil); - try thenPart(x, L); - all := all and ends; - end; - if Scan.tok = Scan.sElse then - if not ends then Gen.jump(endL); end; - Gen.fix(L); - Scan.next; - if Scan.tok = Scan.sIf then elseIf := true; end; - try statements(); - all := all and ends; - else - Gen.fix(L); - all := false; - end; - try closeEnd(start, ind); - Gen.fix(endL); - ends := all; - return nil; -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). *) -proc whileStatement(start: Diag.Pos; ind: INT): ERROR; -var - x: TItem; top, L, test: INT; lp: Loop; old: PLoop; cond, after: Scan.State; m: Gen.CodeMark; -begin - Scan.next; - Scan.saveScan(cond); - Gen.markCode(m); - try expression(x, nil); - try Item.discard(x); - Gen.rewind(m); - try expect(Scan.sDo); - test := Gen.NoLabel; - Gen.jump(test); - Gen.alignLoop(); - top := Chunk.pc; - enterLoop(lp, old); - try statements(); - curLoop := old; - Scan.saveScan(after); - Scan.restoreScan(cond); - Gen.fix(test); - Chunk.noteLine(Scan.curLine(), Scan.curCol()); - try expression(x, nil); - ends := (x.mode = Item.mConst) and (x.val # 0) and (lp.brk = Gen.NoLabel); (* while true *) - if (x.mode = Item.mConst) and (x.typ^.form = Sym.fBool) then - if x.val # 0 then Gen.jumpBack(top); end; - else - L := Gen.NoLabel; - try Item.condJumpTrue(x, L); - Gen.fixTo(L, top); - end; - Scan.restoreScan(after); - try closeEnd(start, ind); - Gen.fix(lp.brk); - return nil; -end; - -proc repeatStatement: ERROR; -var x: TItem; top, L: INT; lp: Loop; old: PLoop; -begin - Scan.next; - top := Chunk.pc; - enterLoop(lp, old); - try statements(); - curLoop := old; - try expect(Scan.sUntil); - try expression(x, nil); - ends := (x.mode = Item.mConst) and (x.val = 0) and (lp.brk = Gen.NoLabel); (* until false *) - L := Gen.NoLabel; - try Item.condJump(x, L); - Gen.fixTo(L, top); - Gen.fix(lp.brk); - return nil; -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. *) -proc forStatement(start: Diag.Pos; ind: INT): ERROR; -var - o: PObj; v, a, b, s: TItem; step: I64; top, body, bodyL, exitL: INT; - lp: Loop; old: PLoop; f: Sym.Form; slot: I64; -begin - Scan.next; - if Scan.tok # Scan.sIdent then return expected("a name"); end; - o := Sym.lookup(Scan.id); - if o = nil then - notDeclared(Scan.tokPos(), Scan.id); - return Scan.Failed; - end; - named(o); - if o^.cls # Sym.oVar then return Scan.mark(say1("{} isn't a variable", nameOf(Scan.id))); end; - f := o^.typ^.form; - if (f # Sym.fInt) and (f # Sym.fEnum) then - return Scan.mark(say1("a for loop needs an integer or enumeration variable, found {}", Sym.typeName(o^.typ))); - end; - Scan.next; - try expect(Scan.sBecomes); - try Item.makeItem(v, o); - try expression(a, o^.typ); - try Item.coerceExact(a, o^.typ, ""); - try Item.assign(v, a); - try expect(Scan.sTo); - try expression(b, o^.typ); - try Item.coerceExact(b, o^.typ, ""); - (* the limit, evaluated once: a constant as it is, else in a slot *) - if b.mode # Item.mConst then - slot := try Item.toSlot(b); - Item.tempItem(b, b.typ, slot); - end; - step := 1; - if Scan.tok = Scan.sBy then - Scan.next; - try expression(s, nil); - step := try constValue(s); - if step = 0 then return Scan.markAt(s.pos, "the step can't be zero"); end; - end; - try expect(Scan.sDo); - exitL := Gen.NoLabel; - if step > 0 then try Item.forCmp(o, b, Scan.sGtr, exitL); else try Item.forCmp(o, b, Scan.sLss, exitL); end; - bodyL := Gen.NoLabel; - Gen.jump(bodyL); - Gen.alignLoop(); - top := Chunk.pc; - try Item.forStep(o, step); - Gen.fix(bodyL); - body := Chunk.pc; - enterLoop(lp, old); - try statements(); - curLoop := old; - try closeEnd(start, ind); - try Item.forNext(o, b, step, exitL, top, body); - Gen.fix(exitL); - Gen.fix(lp.brk); - return nil; -end; - -type - Labels = record - lo, hi: [MaxLabels]I64; (* the ranges of the labels so far *) - at: [MaxLabels]INT; (* where the arm of each starts *) - n: INT; - end; - -(* a < b, for values of an integer type, unsigned or not *) -proc below(a, b: I64; unsign: BOOL): BOOL; -begin - if unsign then return U64(a) < U64(b); end; - return 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. *) -proc intArm(t: PType; var ls: Labels; var endL: INT): ERROR; -var lo, hi: TItem; first, i: INT; u: BOOL; start: Diag.Pos; -begin - u := not t^.signed; - first := ls.n; - repeat - start := Scan.tokPos(); - try expression(lo, t); - try Item.coerce(lo, t); - _ := try constValue(lo); - hi := lo; - if Scan.tok = Scan.sUpto then - Scan.next; - try expression(hi, t); - try Item.coerce(hi, t); - _ := try constValue(hi); - if below(hi.val, lo.val, u) then return Scan.markAt(Scan.spanFrom(start), "the range is empty"); end; - 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 - return Scan.markAt(Scan.spanFrom(start), say1("{} is in another label too", Diag.source(Scan.spanFrom(start)))); - end; - return Scan.markAt(Scan.spanFrom(start), say1("{} overlaps another label", Diag.source(Scan.spanFrom(start)))); - end; - end; - if ls.n >= MaxLabels then - return Scan.markAt(Scan.spanFrom(start), tooMany(MaxLabels, "labels in one match")); - end; - ls.lo[ls.n] := lo.val; ls.hi[ls.n] := hi.val; - INC(ls.n); - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - try expect(Scan.sColon); - for i := first to ls.n - 1 do ls.at[i] := Chunk.pc; end; - try statements(); - Gen.jump(endL); - return nil; -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. *) -proc dispatch(t: PType; p: I64; var ls: Labels; elseAt: INT; var endL: INT); -var - lo, hi: I64; i, start, v, body: INT; u: BOOL; - entry: [MaxLabels]INT; -begin - u := (t^.form = Sym.fInt) and not t^.signed; - lo := 0; hi := 0; - if ls.n > 0 then - lo := ls.lo[0]; hi := ls.hi[0]; - for i := 1 to ls.n - 1 do - if below(ls.lo[i], lo, u) then lo := ls.lo[i]; end; - if below(hi, ls.hi[i], u) then hi := ls.hi[i]; end; - end; - end; - if (ls.n >= MinTable) and (lo >= -2147483648) and (lo <= 2147483647) - and (U64(hi - lo) < U64(TableDensity * ls.n)) and (hi - lo < MaxLabels) then - start := Gen.jumpTable(p, lo, INT(hi - lo) + 1, elseAt, endL); - for v := 0 to INT(hi - lo) do - if elseAt # Gen.NoLabel then entry[v] := elseAt; else entry[v] := start; end; - end; - for i := 0 to ls.n - 1 do - for v := INT(ls.lo[i] - lo) to INT(ls.hi[i] - lo) do entry[v] := ls.at[i]; end; - end; - for v := 0 to INT(hi - lo) do Gen.tableEntry(start, entry[v]); end; - return; - end; - for i := 0 to ls.n - 1 do - body := Gen.NoLabel; - Item.matchRange(p, ls.lo[i], ls.hi[i], body); - Gen.fixTo(body, ls.at[i]); - end; - if elseAt # Gen.NoLabel then Gen.jumpBack(elseAt); end; -end; - -proc matchStatement(start: Diag.Pos; ind: INT): ERROR; -var - x: TItem; t: PType; c, f, o: PObj; p: I64; L, endL, n, first, disp, elseAt: INT; - seen: [256]BOOL; hasElse, all, byValue: BOOL; endAt: Diag.Pos; ls: Labels; -begin - Scan.next; - try expression(x, nil); - if x.typ^.form = Sym.fConst then try Item.coerce(x, Sym.tI64); end; - p := try Item.matchBegin(x); - t := x.typ; - try expect(Scan.sOf); - hasElse := false; - all := true; - endL := Gen.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 = Sym.fInt) or (t^.form = Sym.fEnum); - disp := Gen.NoLabel; - elseAt := Gen.NoLabel; - if byValue then Gen.jump(disp); end; - while Scan.tok = Scan.sBar do - Scan.next; - if hasElse then return Scan.mark("else must be the last arm"); end; - if Scan.tok = Scan.sElse then - Scan.next; - try expect(Scan.sColon); - elseAt := Chunk.pc; - try statements(); - if byValue then Gen.jump(endL); end; - hasElse := true; - elsif t^.form = Sym.fInt then - try intArm(t, ls, endL); - else - first := ls.n; - L := Gen.NoLabel; - repeat - if Scan.tok # Scan.sIdent then return expected("a case"); end; - c := t^.fields; - while (c # nil) and (c^.name # Scan.id) do c := c^.next; end; - if c = nil then - return Scan.mark(say2("{} isn't a case of {}", nameOf(Scan.id), Sym.typeName(t))); - end; - if (c^.val <= 255) and seen[c^.val] then - return Scan.mark(say1("{} has two arms", nameOf(c^.name))); - end; - if c^.val <= 255 then seen[c^.val] := true; end; - Scan.next; - if t^.form # Sym.fEnum then - Item.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 Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - try Sym.openScope(Sym.newScope()); - if Scan.tok = Scan.sLparen then - Scan.next; - f := c^.fields; - n := 0; - repeat - if Scan.tok # Scan.sIdent then return expected("a name"); end; - if f = nil then - return Scan.mark(say1("more names than {} has fields", nameOf(c^.name))); - end; - o := Sym.newObj(Sym.oVar, Scan.id, f^.typ); - o^.lev := 1; o^.ind := true; o^.isVar := true; - o^.val := p; o^.off := f^.val; - try declare(o); - f := f^.next; - INC(n); - Scan.next; - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - if f # nil then - return Scan.mark(say1("name all the fields of {}, or none", nameOf(c^.name))); - end; - try expect(Scan.sRparen); - end; - try expect(Scan.sColon); - for n := first to ls.n - 1 do ls.at[n] := Chunk.pc; end; - try statements(); - Sym.closeScope(); - Gen.jump(endL); - if t^.form # Sym.fEnum then Gen.fix(L); end; - end; - all := all and ends; - end; - endAt := Scan.tokPos(); - try closeEnd(start, ind); - ends := all; - if (t^.form = Sym.fInt) and not hasElse then - return Scan.markHelp(endAt, "a match on an integer needs an else arm", "it may be empty: | else:"); - end; - if not hasElse then - c := t^.fields; - while c # nil do - if (c^.val > 255) or not seen[c^.val] then - return Scan.markAt(endAt, say1("no arm for {}", nameOf(c^.name))); - end; - c := c^.next; - end; - end; - if byValue then - Gen.fix(disp); - dispatch(t, p, ls, elseAt, endL); - end; - Gen.fix(endL); - return nil; -end; - -(* What a message calls x: its name n when x is just that name, else what - it is. *) -proc subject(x: TItem; n: INT): []U8; -begin - if x.pos.b - x.pos.a = LEN(nameOf(n)) then return nameOf(n); end; - if x.mode = Item.mConst then return "a constant"; end; - return "a value"; -end; - -(* x, named first n, is a variable the program may assign: not an - array constant, nor any part of one. *) -proc assignable(x: TItem; n: INT): ERROR; -begin - if (x.mode = Item.mConst) and (subject(x, n) = nameOf(n)) then - return Scan.markAt(x.pos, say1("{} is a constant, and can't be changed", nameOf(n))); - end; - if (x.mode = Item.mVar) and (x.obj # nil) and (x.obj^.cls = Sym.oConst) then - return Scan.markAt(x.pos, say1("{} is a constant, and can't be changed", nameOf(x.obj^.name))); - end; - if (x.mode # Item.mVar) or not x.isVar then - return Scan.markAt(x.pos, say1("can't assign to {}", subject(x, n))); - end; - return nil; -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. *) -proc leftSide(var x: TItem; var called: BOOL): ERROR; -var o: PObj; wasRead: BOOL; n: INT; -begin - n := Scan.id; - o := Sym.lookup(n); - wasRead := (o # nil) and o^.read; - try designator(x, called); - if ((Scan.tok = Scan.sBecomes) or (Scan.tok = Scan.sComma)) and (x.pos.b - x.pos.a = LEN(nameOf(n))) then - o^.read := wasRead; - end; - return nil; -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 _. *) -proc multiAssign(var x: TItem; first: INT; blank: BOOL): ERROR; -var - d: [16]TItem; dn: [16]INT; blanks: [16]BOOL; - y, z: TItem; n, i: INT; called: BOOL; f: PObj; -begin - n := 0; - d[0] := x; - dn[0] := first; - blanks[0] := blank; - repeat - if not blanks[n] then - try Item.notReadOnly(d[n]); - try assignable(d[n], dn[n]); - try Item.pin(d[n]); (* works out the address now, so that the call can't change it *) - end; - INC(n); - if Scan.tok # Scan.sComma then break; end; - if n > 15 then return Scan.mark(tooMany(16, "variables in one assignment")); end; - Scan.next; - blanks[n] := Scan.tok = Scan.sBlank; - if blanks[n] then - Scan.next; - else - dn[n] := Scan.id; - try leftSide(d[n], called); - end; - until false; - try expect(Scan.sBecomes); - if Scan.tok = Scan.sTry then - try tryCall(y); - called := true; - else - try designator(y, called); - end; - if not called or not y.typ^.tuple or (y.typ^.len # I64(n)) then - return Scan.markAt(y.pos, Diag.say("expected a call with {} results", [Fmt.int(n)])); - 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 = Item.mWords then Gen.swap(); end; - f := y.typ^.fields; - for i := 0 to n - 1 do - z := y; - if y.mode = Item.mWords then - z.mode := Item.mStack; z.typ := f^.typ; - else - try Item.field(z, f); - end; - if blanks[i] then - try Item.discard(z); - else - try Item.coerceExact(z, d[i].typ, "several results go to variables of just their types"); - try Item.assign(d[i], z); - end; - f := f^.next; - end; - return nil; -end; - -(* return a, b; or return f(x); with f's several results passed on *) -proc returnResults: ERROR; -var f: PObj; x: TItem; -begin - f := curResult^.fields; - passOn := true; - while f # nil do - try expression(x, f^.typ); - if x.typ^.tuple then - if not Sym.same(x.typ, curResult) then - return Scan.markAt(x.pos, say2("expected the results {}, found {}", Sym.typeName(curResult), Sym.typeName(x.typ))); - end; - return Item.returnAll(x); - end; - try Item.returnField(f, x); - f := f^.next; - if f # nil then try expect(Scan.sComma); end; - end; - return nil; -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. *) -proc deferStatement: ERROR; -var L, pos, saved: INT; oldLoop: PLoop; oldDeferring: BOOL; start: Diag.Pos; -begin - start := Scan.tokPos(); - Scan.next; - if directDefer then return Scan.markAt(Scan.spanFrom(start), "defer can't be deferred"); end; - if numDefers >= MaxDefers then - return Scan.markAt(Scan.spanFrom(start), tooMany(MaxDefers, "deferred statements in one procedure")); - end; - L := Gen.NoLabel; - pos, saved := Gen.deferBegin(L); - oldLoop := curLoop; oldDeferring := deferring; - curLoop := nil; - deferring := true; - directDefer := true; - try statement(); - directDefer := false; - curLoop := oldLoop; deferring := oldDeferring; - Gen.deferEnd(L, saved); - defers[numDefers] := pos; - INC(numDefers); - return nil; -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). *) -proc changesItself(x: TItem): BOOL; -var st: Scan.State; wasSkipping, changes: BOOL; d: INT; -begin - if (x.mode # Item.mVar) or (x.base # Gen.bReg) or (x.typ^.form = Sym.fSlice) - or (Scan.tok # Scan.sIdent) or (Scan.id # x.obj^.name) then - return false; - end; - changes := false; - Scan.saveScan(st); - wasSkipping := Scan.skipping; - Scan.setSkipping(true); (* its slips are told when it is compiled *) - Scan.next; - if isAddOp() then - changes := true; - d := 0; - while not ((d = 0) and ((Scan.tok = Scan.sSemicolon) or (Scan.tok = Scan.sEnd))) and (Scan.tok # Scan.sEof) do - if (Scan.tok = Scan.sIdent) and (Scan.id = x.obj^.name) then changes := false; end; - match Scan.tok of - | sLparen, sLbrak, sLbrace: INC(d); - | sRparen, sRbrak, sRbrace: DEC(d); - | else: - end; - Scan.next; - end; - end; - Scan.restoreScan(st); - Scan.setSkipping(wasSkipping); - return changes; -end; - -(* A call standing on its own, which drops the results x holds, if any, - to be warned of *) -proc noteDrop(x: TItem); -begin - if (x.mode # Item.mNone) and (numDrops < MaxDrops) then - drops[numDrops].at := x.pos; - if x.typ^.tuple then drops[numDrops].n := INT(x.typ^.len); else drops[numDrops].n := 1; end; - INC(numDrops); - end; -end; - -proc oneStatement: ERROR; -var - x, y: TItem; called: BOOL; m: I64; c: Gen.CallInfo; start: Diag.Pos; first, n, i: INT; k: Gen.Kind; -begin - start := Scan.tokPos(); - first := Scan.id; - Chunk.noteLine(Scan.curLine(), Scan.curCol()); - m := Gen.tempMark(); - ends := false; - match Scan.tok of - | sIdent: - try leftSide(x, called); - if Scan.tok = Scan.sBecomes then - try Item.notReadOnly(x); - try assignable(x, first); - Scan.next; - if changesItself(x) then Gen.setInPlace(x.chunk); end; - try expression(y, x.typ); - Gen.setInPlace(-1); - try Item.assign(x, y); - elsif Scan.tok = Scan.sComma then - try multiAssign(x, first, false); - elsif not called then - if (x.mode = Item.mProc) - or (((x.mode = Item.mVar) or (x.mode = Item.mStack)) and (x.typ^.form = Sym.fProc)) then - try Item.beginCall(c, x); - try Item.endCall(c, x); - try Item.discard(x); - elsif Scan.tok = Scan.sEql then - return Scan.markHelp(x.pos, say1("{} isn't a statement", subject(x, first)), "assignment is written :="); - else - return Scan.markAt(x.pos, say1("{} isn't a statement", subject(x, first))); - end; - else - noteDrop(x); - try Item.discard(x); - end; - | sBlank: - Scan.next; - if Scan.tok = Scan.sComma then - try multiAssign(x, 0, true); - else - try expect(Scan.sBecomes); - try expression(x, nil); - (* evaluated and dropped: a single value is loaded, so that a - volatile one is read *) - if (x.mode = Item.mType) or (x.mode = Item.mBuiltin) or (x.mode = Item.mNone) or (x.mode = Item.mCase) - or ((x.mode # Item.mStr) and not Sym.isAggregate(x.typ)) then - try Item.value(x); - end; - try Item.discard(x); - end; - | sIf: try ifStatement(start, Scan.indent()); - | sWhile: try whileStatement(start, Scan.indent()); - | sRepeat: try repeatStatement(); - | sFor: try forStatement(start, Scan.indent()); - | sMatch: try matchStatement(start, Scan.indent()); - | sReturn: - Scan.next; - if deferring then return Scan.markAt(Scan.spanFrom(start), "return can't leave a deferred statement"); end; - if Scan.tok = Scan.sSemicolon then - runDefers(0); - try Item.returnNone(); - else - if (curResult # nil) and curResult^.tuple then - try returnResults(); - else - try expression(x, curResult); - try Item.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 Sym.behindPointer(curResult) then - n := 1; k := Gen.kindOf(curResult); - if Sym.inTwoRegs(curResult) then n := 2; k := Gen.kWord; end; - if deferSlot = 0 then deferSlot := Gen.allocPerm(16, 8); end; - for i := n - 1 to 0 by -1 do Gen.popVar(Item.frameAdr(deferSlot + I64(8 * i)), 8); end; - runDefers(0); - for i := 0 to n - 1 do Gen.pushVar(Item.frameAdr(deferSlot + I64(8 * i)), 8, false, k); end; - else - runDefers(0); - end; - Gen.returnJump(); - ends := true; - end; - | sBreak: - Scan.next; - if curLoop = nil then return Scan.markAt(Scan.spanFrom(start), "break outside a loop"); end; - runDefers(curLoop^.base); - Gen.jump(curLoop^.brk); - | sDefer: try deferStatement(); - | sTry: - try tryCall(x); - noteDrop(x); - try Item.discard(x); - | sArrow: - return Scan.markHelp(Scan.tokPos(), "a statement starts with a name", - "convert into a pointer variable, then assign through that"); - | else: - if Scan.atLineStart() then - return endMissing(Scan.missingPos(), say1("expected \"end\", found {}", Scan.found())); - end; - return expected("a statement"); - end; - Gen.releaseTemps(m); - return nil; -end; - -proc statement: ERROR; -var r: Recover; m: I64; err: ERROR; -begin - m := Gen.tempMark(); - guard(r); - err := oneStatement(); - if err = nil then - skipped := false; - else - restore(r); - (* a statement never starts a line: this is the next declaration *) - if Scan.atLineStart() or not skipConstruct() then return giveUp(r); end; - Gen.releaseTemps(m); - skipped := true; - end; - unguard(r); - return nil; -end; - -proc endsStatements: BOOL; -begin - match Scan.tok of - | sEnd, sElse, sElsif, sUntil, sBar, sEof: return true; - | else: return false; - end; -end; - -proc statements: ERROR; -var base: INT; old: BOOL; -begin - base := numDefers; - old := directDefer; - directDefer := false; - ends := false; - while not endsStatements() do - try statement(); - if not skipped or (Scan.tok = Scan.sSemicolon) then try expect(Scan.sSemicolon); end; - end; - runDefers(base); - numDefers := base; - directDefer := old; - return nil; -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. *) -proc skipBody: ERROR; -var d: INT; sawBegin: BOOL; -begin - d := 0; - sawBegin := false; - repeat - match Scan.tok of - | sBegin: - if d = 0 then sawBegin := true; end; - INC(d); - | sIf, sWhile, sFor, sMatch, sRecord, sVariant: INC(d); - | sEnd: - DEC(d); - if (d = 0) and sawBegin then - Scan.next; - return nil; - end; - | sEof: return expected("\"end\""); - | else: - end; - Scan.next; - until false; - return nil; -end; - -proc declarations(top: BOOL); 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 ShownRegs[i]; 0 if it isn't shown. *) -proc varKind(o: PObj): INT; -var k, i, v: INT; -begin - match o^.typ^.form of - | fInt: if o^.typ^.signed then k := 1; else k := 2; end; - | fEnum, fSet: k := 2; - | fBool: k := 3; - | fPtr, fProc, fError: k := 4; - | fReal: k := 5; - | else: return 0; - end; - v := k + INT(o^.typ^.size) * 16; - if o^.ind then v := v + 256; end; - for i := 0 to LEN(Gen.ShownRegs) - 1 do - if o^.reg = Gen.ShownRegs[i] then v := k + INT(o^.typ^.size) * 16 + (i + 1) * 512; end; - end; - return v; -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 *) -proc regFit(o: PObj): BOOL; -var f: Sym.Form; -begin - if (o^.cls # Sym.oVar) or o^.ind or o^.ext then return false; end; - f := o^.typ^.form; - return (f = Sym.fInt) or (f = Sym.fBool) or (f = Sym.fEnum) or (f = Sym.fPtr) or (f = Sym.fProc) - or (f = Sym.fError) or (f = Sym.fSlice) or (f = Sym.fReal) - or ((f = Sym.fSet) and (o^.typ^.size <= 8)); -end; - -(* The first local of the procedure being compiled. Locals are chained - by chain 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. *) -proc firstLocal(before: PObj): PObj; -begin - if before = nil then return Sym.curModule^.locals; end; - return before^.chain; -end; - -const MaxCand = 64; (* variables of a procedure that may go in registers *) - -var - cand: [MaxCand]PObj; (* chooseRegs's candidates and their weights *) - weight: [MaxCand]INT; - numCand: INT; - -proc candidate(n: INT): INT; -var j: INT; -begin - for j := 0 to numCand - 1 do - if cand[j]^.name = n then return j; end; - end; - return -1; -end; - -proc addCandidate(o: PObj); -begin - if regFit(o) and (numCand < MaxCand) then - cand[numCand] := o; - weight[numCand] := 0; - INC(numCand); - 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 *) -proc calls(o: PObj): BOOL; -begin - if o = nil then return false; end; - return (o^.cls = Sym.oProc) or ((o^.cls = Sym.oVar) and (o^.typ^.form = Sym.fProc)) - or ((o^.cls = Sym.oBuiltin) and ((o^.val = Sym.bNew) or (o^.val = Sym.bSyscall) or (o^.val = Sym.bCopy))); -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. *) -proc chooseRegs(params, before: PObj); -var - isLoop: [256]BOOL; - i, k, kx, d, loops, best, need: INT; o, q, qual: PObj; st: Scan.State; - afterDot, wasSkipping, leaf: BOOL; -begin - numCand := 0; - o := params; - while o # nil do addCandidate(o); o := o^.next; end; - o := firstLocal(before); - while o # nil do addCandidate(o); o := o^.chain; end; - if numCand = 0 then return; end; - Scan.saveScan(st); - wasSkipping := Scan.skipping; - Scan.setSkipping(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 (Scan.tok = Scan.sIdent) and not afterDot then - q := Sym.lookup(Scan.id); - if calls(q) then leaf := false; end; - qual := nil; - if (q # nil) and (q^.cls = Sym.oModule) then qual := q; end; - elsif (Scan.tok = Scan.sIdent) and (qual # nil) then - if (qual^.home = nil) or calls(Sym.find(qual^.home^.scope, Scan.id)) then leaf := false; end; - qual := nil; - end; - match Scan.tok of - | sBegin, sIf, sMatch, sWhile, sFor, sRepeat: - if d < 255 then - INC(d); - isLoop[d] := (Scan.tok = Scan.sWhile) or (Scan.tok = Scan.sFor) or (Scan.tok = Scan.sRepeat); - if isLoop[d] then INC(loops); end; - end; - | sEnd, sUntil: - if isLoop[d] then DEC(loops); end; - DEC(d); - | sIdent: - if Scan.id = nameAdr then - Scan.next; - if Scan.tok = Scan.sLparen then Scan.next; end; - (* a hugely negative weight bars it from a register, whatever - its uses add *) - if (Scan.tok = Scan.sIdent) and (candidate(Scan.id) >= 0) then weight[candidate(Scan.id)] := -1073741824; end; - elsif not afterDot and (candidate(Scan.id) >= 0) then - k := candidate(Scan.id); - if loops > 2 then INC(weight[k], 64); else INC(weight[k], 1 shl (2 * loops)); end; - end; - | else: - end; - afterDot := Scan.tok = Scan.sPeriod; (* a name after a dot is a field, not a variable *) - if (d > 0) and (Scan.tok # Scan.sEof) then Scan.next; end; - until (d = 0) or (Scan.tok = Scan.sEof); - Scan.restoreScan(st); - Scan.setSkipping(wasSkipping); - if leaf then - o := params; - while o # nil do - k := candidate(o^.name); - if (k >= 0) and (weight[k] >= 0) then Gen.keepArrived(o); end; (* 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 numCand - 1 do - if cand[i]^.typ^.form = Sym.fSlice then weight[i] := weight[i] div 2; end; - end; - (* 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 numCand - 1 do - if (cand[i]^.reg = 0) and (weight[i] >= 3) and ((best < 0) or (weight[i] > weight[best])) then best := i; end; - end; - if best < 0 then break; end; - need := 1; - if cand[best]^.typ^.form = Sym.fSlice then need := 2; end; - if cand[best]^.typ^.form = Sym.fReal then - if kx < 4 then - cand[best]^.reg := Gen.XVarRegs[kx]; - INC(kx); - else - weight[best] := 0; - end; - elsif k + need <= 5 then - cand[best]^.reg := Gen.VarRegs[k]; - if need = 2 then cand[best]^.reg2 := Gen.VarRegs[k + 1]; end; - INC(k, need); - else - weight[best] := 0; (* too big for what is left *) - end; - until false; -end; - -(* The registers the variables of the procedure are in, as bits: bit i - is VarRegs[i], bit XBit + i XVarRegs[i] *) -proc regBits(o: PObj): INT; -var m, k: INT; -begin - m := 0; - for k := 0 to 4 do - if (o^.reg = Gen.VarRegs[k]) or (o^.reg2 = Gen.VarRegs[k]) then m := m | (1 shl k); end; - end; - for k := 0 to 3 do - if o^.reg = Gen.XVarRegs[k] then m := m | (1 shl (Gen.XBit + k)); end; - end; - return m; -end; - -proc regsOf(params, before: PObj): INT; -var o: PObj; m: INT; -begin - m := 0; - o := params; - while o # nil do - m := m | regBits(o); - o := o^.next; - end; - o := firstLocal(before); - while o # nil do - if o^.cls = Sym.oVar then m := m | regBits(o); end; - o := o^.chain; - end; - return 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. *) -proc placeLocals(params, before: PObj); -var o: PObj; -begin - Gen.resetLocals(); - o := firstLocal(before); - while o # nil do - if (o^.cls = Sym.oVar) and (o^.reg = 0) then - o^.val := Gen.allocPerm(o^.typ^.size, o^.typ^.align); - elsif (o^.cls = Sym.oVar) and (o^.reg >= Gen.XmmVar) then - o^.val := Gen.allocPerm(8, 8); - Gen.xHome(o^.reg, o^.val); - end; - o := o^.chain; - end; - o := params; - while o # nil do - if o^.reg >= Gen.XmmVar then Gen.xHome(o^.reg, o^.val); end; - o := o^.next; - end; - Gen.useRegs(regsOf(params, before)); -end; - -proc body(p: PObj; sig: PType; line: INT): ERROR; -var - q, params, last, o, before: PObj; old: PType; st: Scan.State; - mark: Gen.CodeMark; drops0, errs: INT; -begin - try Sym.openScope(Sym.newScope()); - params := nil; last := nil; - q := sig^.fields; - while q # nil do - o := Sym.newObj(Sym.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; end; - last := o; - q := q^.next; - end; - Item.beginProc(sig, params); - deferSlot := 0; - o := params; - while o # nil do - q := o^.next; - try declare(o); - o := q; - end; - curProc := p; - before := Sym.curModule^.lastLocal; - declarations(false); - chooseRegs(params, before); - placeLocals(params, before); - (* the body, made again if a variable in a register must be in memory *) - Scan.saveScan(st); - Gen.markCode(mark); drops0 := numDrops; errs := Diag.errors; - old := curResult; - repeat - Item.setDemoted(false); - try expect(Scan.sBegin); - curResult := sig^.base; - Gen.enterBody(p^.chunk, line); - stray := false; elseIf := false; deferSlot := 0; - try statements(); - p^.openEnd := (curResult # nil) and not ends; - Chunk.noteLine(Scan.curLine(), Scan.curCol()); - try expect(Scan.sEnd); - if not (Item.demoted or Gen.lost) or (Diag.errors # errs) then break; end; - (* a parameter kept where it arrived goes to memory: a call or a copy - wanted its register *) - if Gen.lost then - o := params; - while o # nil do - if Gen.keptIn(o) then o^.reg := 0; o^.reg2 := 0; end; - o := o^.next; - end; - end; - numDrops := drops0; - Gen.redo(mark); - placeLocals(params, before); - Scan.restoreScan(st); - until false; - try Gen.endProc(p^.chunk, p^.openEnd); - (* its parameters and variables, for the trap report *) - o := firstLocal(before); - q := params; - while q # nil do - if varKind(q) # 0 then Chunk.noteVar(p^.chunk, q^.name, INT(q^.val), varKind(q)); end; - q := q^.next; - end; - while o # nil do - if (o^.cls = Sym.oVar) and (varKind(o) # 0) then Chunk.noteVar(p^.chunk, o^.name, INT(o^.val), varKind(o)); end; - o := o^.chain; - end; - curResult := old; - curProc := nil; - Sym.closeScope(); - return nil; -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 *) -proc asmConst(whole: BOOL): (I64, ERROR); -var x: TItem; -begin - if whole then return constExpr(); end; - try factor(x, nil); - if not Sym.isInt(x.typ) then - return 0, Scan.markAt(x.pos, say1("expected an integer constant, found {}", Item.what(x))); - end; - return constValue(x); -end; - -proc codeBody(p: PObj; sig: PType; at: Diag.Pos): ERROR; -var q: PObj; ni, nf: INT; -begin - ni := 0; nf := 0; - q := sig^.fields; - while q # nil do - if not q^.isVar and (q^.typ^.form = Sym.fSlice) then - INC(ni, 2); (* address, then length *) - else - if not q^.isVar and not Sym.isScalar(q^.typ) then - return Scan.markAt(at, "a code procedure takes integers, BOOL, reals, pointers, procedures and slices"); - end; - if (q^.typ^.form = Sym.fReal) and not q^.isVar then INC(nf); else INC(ni); end; - end; - q := q^.next; - end; - if (ni > 6) or (nf > 8) or sig^.variadic then - return Scan.markAt(at, "too many parameters for a code procedure"); - end; - if sig^.base # nil then - if sig^.base^.tuple then - q := sig^.base^.fields; - if (sig^.base^.len # 2) or (q^.typ^.size # 8) or (q^.next^.typ^.size # 8) - or not Sym.isScalar(q^.typ) or not Sym.isScalar(q^.next^.typ) - or (q^.typ^.form = Sym.fReal) or (q^.next^.typ^.form = Sym.fReal) then - return Scan.markAt(at, "a code procedure returns two results only in rax and rdx"); - end; - elsif not Sym.isScalar(sig^.base) and (sig^.base^.form # Sym.fSlice) then - return Scan.markAt(at, "a code procedure returns a single value"); - end; - end; - try Gen.codeProc(p^.chunk, asmConst); - return expect(Scan.sEnd); -end; - -proc procDecl: ERROR; -var n, line: INT; exp: BOOL; sig: PType; p: PObj; at: Diag.Pos; -begin - try instancesFor(false); - line := Scan.curLine(); - Scan.next; - try identDef(n, exp, at); - sig := try signature(); - try expect(Scan.sSemicolon); - p := Sym.find(Sym.topScope(), n); - if (p # nil) and (p^.cls = Sym.oProc) and p^.fwd then - if not Sym.same(p^.typ, sig) then - Diag.error(at, say1("{} doesn't have the signature it was declared forward with", nameOf(n))); - Diag.note(p^.pos, "the signature is here"); - return Scan.Failed; - end; - if Scan.tok = Scan.sForward then return Scan.mark(say1("{} is declared forward twice", nameOf(n))); end; - p^.exported := p^.exported or exp; - else - p := Sym.newObj(Sym.oProc, n, sig); - p^.pos := at; - p^.exported := exp; - if (Sym.curModule^.name = nameRt) and not checkMode and (n = nameFail) then - p^.chunk := Gen.rtFail; - else - p^.chunk := Chunk.newChunk(Chunk.secText, Sym.curModule^.sname, n); - end; - try declare(p); - end; - if Scan.tok = Scan.sForward then - Scan.next; - p^.fwd := true; - return nil; - end; - p^.fwd := false; - if Scan.tok = Scan.sCode then - Scan.next; - p^.isCode := true; - try codeBody(p, sig, at); - elsif checkMode then - try skipBody(); - else - try body(p, sig, line); - end; - if Scan.tok = Scan.sIdent then - if Scan.id = Sym.curModule^.name then - return endMissing(Scan.tokPos(), say1("{} has no \"end\": this one closes the module", nameOf(n))); - elsif Scan.id # n then - return endMissing(Scan.tokPos(), say2("expected {}, found {}", nameOf(n), nameOf(Scan.id))); - end; - Scan.next; - end; - return nil; -end; - -(* An extern procedure or variable: C's, reached through the quadword - that holds its address. *) -proc externDecl: ERROR; -var n: INT; exp: BOOL; o, q: PObj; t: PType; at: Diag.Pos; -begin - Scan.next; - Sym.curModule^.usesC := true; - if Scan.tok = Scan.sProc then - Scan.next; - try identDef(n, exp, at); - willDeclare(n); - inExtern := true; - t := try signature(); - inExtern := false; - q := t^.fields; - while q # nil do - if q^.isVar or not Sym.isScalar(q^.typ) then - return Scan.markAt(at, "C takes integers, BOOL, reals, pointers and procedures"); - end; - q := q^.next; - end; - if (t^.base # nil) and not Sym.isScalar(t^.base) then - return Scan.markAt(at, "C returns a single value"); - end; - o := Sym.newObj(Sym.oProc, n, t); - else - if Scan.tok # Scan.sVar then return expected("\"proc\" or \"var\""); end; - Scan.next; - try identDef(n, exp, at); - willDeclare(n); - try expect(Scan.sColon); - declExported := exp; - t := try parseType(); - declExported := false; - o := Sym.newObj(Sym.oVar, n, t); - end; - o^.pos := at; - o^.exported := exp; - o^.ext := true; - o^.chunk := Chunk.externChunk(n); - return 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: ^U8; - fixes: [MaxFixes]record off, chunk: INT; end; - numFixes: INT; - -proc constFix(off, chunk: INT): ERROR; -begin - if numFixes >= MaxFixes then - return Scan.mark(tooMany(MaxFixes, "addresses in one constant")); - end; - fixes[numFixes].off := off; - fixes[numFixes].chunk := chunk; - INC(numFixes); - return nil; -end; - -(* The n bytes of v, at off in the constant: little-endian, as the machine is *) -proc putBytes(off, n: INT; v: I64); -var src: ^U8; -begin - src := ^U8(ADR(v)); - COPY(constBytes[off..off + n], src[0..n]); -end; - -(* The part of type t at offset off of the constant *) -proc constPart(t: PType; off: INT): ERROR; -var e: TItem; f: PObj; k: INT; r: F32; start: Diag.Pos; src: ^U8; st: INT; -begin - start := Scan.tokPos(); - if (t^.form = Sym.fArray) and (Scan.tok = Scan.sLbrak) then - Scan.next; - k := 0; - if Scan.tok # Scan.sRbrak then - repeat - if I64(k) < t^.len then - try constPart(t^.base, off + k * INT(t^.base^.size)); - else - try constPart(t^.base, off); - end; - INC(k); - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - end; - try expect(Scan.sRbrak); - if I64(k) # t^.len then - return Scan.markAt(Scan.spanFrom(start), Diag.say("expected {} elements, found {}", [Fmt.int(t^.len), Fmt.int(k)])); - end; - return nil; - end; - if (t^.form = Sym.fRecord) and not t^.tuple and (Scan.tok = Scan.sLbrace) then - Scan.next; - if Scan.tok # Scan.sRbrace then - repeat - if Scan.tok # Scan.sIdent then return expected("a field"); end; - f := try fieldOf(t); - Scan.next; - try expect(Scan.sColon); - try constPart(f^.typ, off + INT(f^.val)); - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - end; - return expect(Scan.sRbrace); - end; - try expression(e, t); - if (e.mode = Item.mStr) and ((t^.form = Sym.fSlice) or (t^.form = Sym.fArray)) and (t^.base = Sym.tU8) then - if t^.form = Sym.fSlice then - try constFix(off, e.chunk); - putBytes(off + 8, 8, e.val); - elsif e.val > t^.len then - return Scan.markAt(e.pos, say1("the string is longer than {}", Sym.typeName(t))); - else - st := Chunk.chunks[e.chunk].start; - COPY(constBytes[off..off + INT(e.val)], Chunk.rodata[st..st + INT(e.val)]); - end; - elsif t^.form = Sym.fSlice then - if (e.mode # Item.mVar) or (e.obj = nil) or (e.obj^.cls # Sym.oConst) or (e.typ^.form # Sym.fArray) - or (e.pos.b - e.pos.a # LEN(nameOf(e.obj^.name))) or not Sym.same(e.typ^.base, t^.base) then - return Scan.markAt(e.pos, say1("a constant slice is a string or an array constant of its elements, found {}", Item.what(e))); - end; - try constFix(off, e.chunk); - putBytes(off + 8, 8, e.typ^.len); - elsif t^.form = Sym.fVariant then - return Scan.markAt(e.pos, "a constant holds no variant"); - elsif (t^.form = Sym.fArray) or (t^.form = Sym.fRecord) then - return Scan.markAt(e.pos, say1("expected a literal of {}", Sym.typeName(t))); - else - try Item.coerce(e, t); - if (e.mode = Item.mProc) and not e.obj^.ext then - try constFix(off, e.obj^.chunk); - elsif e.mode # Item.mConst then - return Scan.markAt(e.pos, say1("expected a constant, found {}", Item.what(e))); - elsif (t^.form = Sym.fError) and (e.val > 0) then - try constFix(off, INT(e.val) - 1); - elsif (t^.form = Sym.fPtr) and (e.val # 0) then - return Scan.markAt(e.pos, "a constant pointer is nil"); - elsif (t^.form = Sym.fReal) and (t^.size = 4) then - r := F32(Item.realOf(e)); - src := ^U8(ADR(r)); - COPY(constBytes[off..off + 4], src[0..4]); - else - putBytes(off, INT(t^.size), e.val); - end; - end; - return nil; -end; - -(* The chunk of n, a constant of type t whose literal is next *) -proc aggregateConst(t: PType; n: INT): (INT, ERROR); -var c, i, size: INT; -begin - size := INT(t^.size); - constBytes := Scan.grab(size + 8); - for i := 0 to size + 7 do constBytes[i] := 0; end; - numFixes := 0; - try constPart(t, 0); - c := Chunk.newChunk(Chunk.secRodata, Sym.curModule^.sname, n); - Chunk.setData(c, constBytes, size, INT(t^.align)); - for i := 0 to numFixes - 1 do Chunk.addDataFixup(c, fixes[i].off, fixes[i].chunk, 0); end; - return c, nil; -end; - -proc constDecl(top: BOOL): ERROR; -var n, c: INT; exp: BOOL; x: TItem; o: PObj; t: PType; start, at: Diag.Pos; -begin - try identDef(n, exp, at); - willDeclare(n); - t := nil; - if Scan.tok = Scan.sColon then - Scan.next; - start := Scan.tokPos(); - t := try parseType(); - if (t # Sym.tError) and not ((t^.form = Sym.fArray) or ((t^.form = Sym.fRecord) and not t^.tuple)) then - return Scan.markAt(Scan.spanFrom(start), "only an ERROR, an array or a record constant has a type"); - end; - end; - try expect(Scan.sEql); - if (t # nil) and ((t^.form = Sym.fArray) or (t^.form = Sym.fRecord)) then - o := Sym.newObj(Sym.oConst, n, t); - o^.chunk := try aggregateConst(t, n); - o^.pos := at; - o^.exported := exp and top; - try declare(o); - return expect(Scan.sSemicolon); - end; - try expression(x, nil); - o := Sym.newObj(Sym.oConst, n, x.typ); - o^.pos := at; - o^.exported := exp and top; - if t = Sym.tError then - o^.typ := Sym.tError; - c := try Item.errorChunk(x, Sym.curModule^.sname, n); - o^.val := c + 1; - elsif x.mode = Item.mStr then - o^.val := x.val; - o^.chunk := x.chunk; - else - o^.val := try constValue(x); - end; - try declare(o); - return expect(Scan.sSemicolon); -end; - -proc typeDecl(top: BOOL): ERROR; -var n: INT; exp: BOOL; o: PObj; t: PType; at: Diag.Pos; -begin - try identDef(n, exp, at); - willDeclare(n); - try expect(Scan.sEql); - declExported := exp and top; - inTypes := true; - t := try parseType(); - o := Sym.newObj(Sym.oType, n, t); - o^.pos := at; - o^.exported := exp and top; - if t^.obj = nil then t^.obj := o; end; - try declare(o); - return expect(Scan.sSemicolon); -end; - -proc varDecl(top: BOOL): ERROR; -var - i, k: INT; o: PObj; t: PType; - names: [MaxNames]INT; exps: [MaxNames]BOOL; poss: [MaxNames]Diag.Pos; -begin - k := 0; - repeat - if k >= MaxNames then return Scan.mark(tooMany(MaxNames, "names in one declaration")); end; - try identDef(names[k], exps[k], poss[k]); - willDeclare(names[k]); - INC(k); - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - try expect(Scan.sColon); - declExported := top and exps[0]; - t := try parseType(); - declExported := false; - for i := 0 to k - 1 do - o := Sym.newObj(Sym.oVar, names[i], t); - o^.pos := poss[i]; - o^.exported := exps[i] and top; - o^.isVar := false; - if top then - o^.lev := 0; - o^.chunk := Chunk.newChunk(Chunk.secBss, Sym.curModule^.sname, names[i]); - Chunk.setBss(o^.chunk, INT(t^.size), INT(t^.align)); - else - o^.lev := 1; (* its slot comes from placeLocals, if it needs one *) - end; - try declare(o); - end; - return expect(Scan.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 *) -proc skipProc; -var st: Scan.State; -begin - Scan.next; - if (Scan.tok = Scan.sIdent) and (Sym.find(Sym.topScope(), Scan.id) = nil) then poison(Scan.id); end; - repeat - repeat Scan.next; until Scan.atLineStart() or (Scan.tok = Scan.sEof); - match Scan.tok of - | sProc, sExtern, sEof: return; - | sEnd: - Scan.saveScan(st); - Scan.next; - if Scan.tok = Scan.sIdent then Scan.next; end; - if Scan.tok = Scan.sSemicolon then - Scan.next; - return; - end; - Scan.restoreScan(st); - return; - | else: - end; - until false; -end; - -(* What one declaration, of the kind k, reads *) -proc declarationOf(k: Scan.Sym; top: BOOL): ERROR; -begin - match k of - | sConst: return constDecl(top); - | sType: return typeDecl(top); - | sVar: return varDecl(top); - | sProc: - if not top then return Scan.mark("procedures don't nest"); end; - try procDecl(); - return expect(Scan.sSemicolon); - | sExtern: - if not top then return Scan.mark("extern is only for the top of a module"); end; - try externDecl(); - return expect(Scan.sSemicolon); - | else: return nil; - end; -end; - -(* One declaration, as a recovery point: an error is reported, the - declaration skipped, and reading goes on after it *) -proc declaration(k: Scan.Sym; top: BOOL); -var r: Recover; -begin - guard(r); - numDeclaring := 0; - if declarationOf(k, top) # nil then - restore(r); - if k = Scan.sProc then skipProc(); else skipDeclaration(); end; - end; - unguard(r); -end; - -proc declarations(top: BOOL); -var i: INT; o: PObj; k: Scan.Sym; -begin - repeat - k := Scan.tok; - match k of - | sConst, sVar: - Scan.next; - while Scan.tok = Scan.sIdent do declaration(k, top); end; - | sType: - Scan.next; - numFwd := 0; - while Scan.tok = Scan.sIdent do declaration(Scan.sType, top); end; - inTypes := false; - for i := 0 to numFwd - 1 do - o := Sym.lookup(fwdTypes[i]^.fwd); - if (o = nil) or (o^.cls # Sym.oType) then - notDeclared(fwdPos[i], fwdTypes[i]^.fwd); - fwdTypes[i]^.base := Sym.tPoison; - else - fwdTypes[i]^.base := o^.typ; - named(o); - end; - fwdTypes[i]^.fwd := -1; - end; - | sProc, sExtern: declaration(k, top); - | else: return; - end; - until false; -end; - -(* Modules *) - -(* Whether m is module n with these arguments. *) -proc isModule(m: PModule; n: INT; args: Sym.Args): BOOL; -var i: INT; -begin - if (m^.name # n) or (m^.args.n # args.n) then return false; end; - for i := 0 to args.n - 1 do - if (m^.args.o[i] # args.o[i]) or not Sym.same(m^.args.t[i], args.t[i]) then return false; end; - end; - return true; -end; - -proc findModule(n: INT; args: Sym.Args): PModule; -var m: PModule; -begin - m := firstModule; - while (m # nil) and not isModule(m, n, args) do m := m^.next; end; - return m; -end; - -(* The arguments of an instance: types, or procedures named. *) -proc parseArgs(var args: Sym.Args; mname: []U8): ERROR; -var o: PObj; start: Diag.Pos; -begin - Scan.next; - repeat - if args.n >= 8 then return Scan.mark(say1("too many type arguments for {}", mname)); end; - args.o[args.n] := nil; - start := Scan.tokPos(); - if Scan.tok = Scan.sIdent then - o := try qualIdent(); - if o^.cls = Sym.oProc then - args.o[args.n] := o; - elsif o^.cls # Sym.oType then - return Scan.markAt(Scan.spanFrom(start), say1("{} isn't a type or a procedure", nameOf(o^.name))); - end; - args.t[args.n] := o^.typ; - else - args.t[args.n] := try parseType(); - end; - args.pos[args.n] := Scan.spanFrom(start); - INC(args.n); - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - return expect(Scan.sRparen); -end; - -(* Past an instance's arguments, to be read when it is made *) -proc skipArgs: ERROR; -var p: INT; -begin - p := 0; - repeat - if Scan.tok = Scan.sLparen then - INC(p); - elsif Scan.tok = Scan.sRparen then - DEC(p); - elsif (Scan.tok = Scan.sSemicolon) or (Scan.tok = Scan.sEof) then - return expected("\")\""); - end; - Scan.next; - until p = 0; - return nil; -end; - -(* A generic module's parameters, bound to the instance's arguments: a - type parameter names its type, a procedure parameter its procedure. - The instance's name is the module's with its arguments, List(I64). *) -proc moduleParams(m: PModule): ERROR; -var i: INT; o, a: PObj; sig: PType; s: Buf.Buf; at: Diag.Pos; text: []U8; -begin - Buf.init(ADR(s), Heap.heap); - i := 0; - Buf.str(ADR(s), nameOf(m^.name)); - Buf.add(ADR(s), '('); - Scan.next; - repeat - if Scan.tok # Scan.sIdent then return expected("a name"); end; - if i >= m^.args.n then - return Scan.markAt(m^.args.at, say2("{} needs a type for {}", nameOf(m^.name), nameOf(Scan.id))); - end; - if m^.args.o[i] # nil then - return Scan.markAt(m^.args.pos[i], say2("{} needs a type for {}", nameOf(m^.name), nameOf(Scan.id))); - end; - o := Sym.newObj(Sym.oType, Scan.id, m^.args.t[i]); - o^.used := true; (* a parameter of the module, not a declaration *) - try declare(o); - Buf.str(ADR(s), Sym.typeName(m^.args.t[i])); - Buf.add(ADR(s), ','); - INC(i); - Scan.next; - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - while Scan.tok = Scan.sSemicolon do - Scan.next; - if Scan.tok # Scan.sIdent then return expected("a name"); end; - at := Scan.tokPos(); - o := Sym.newObj(Sym.oProc, Scan.id, nil); - Scan.next; - try expect(Scan.sColon); - try expect(Scan.sProc); - sig := try signature(); - if i >= m^.args.n then - return Scan.markAt(m^.args.at, say2("{} needs a procedure for {}", nameOf(m^.name), nameOf(o^.name))); - end; - a := m^.args.o[i]; - if a = nil then - return Scan.markAt(m^.args.pos[i], say2("{} needs a procedure for {}", nameOf(m^.name), nameOf(o^.name))); - end; - if not Sym.same(a^.typ, sig) then - Diag.error(m^.args.pos[i], say2("{} doesn't have the signature of {}", nameOf(a^.name), nameOf(o^.name))); - Diag.note(at, "the signature is here"); - Diag.finish(); - end; - o^.typ := a^.typ; o^.chunk := a^.chunk; o^.isCode := a^.isCode; o^.ext := a^.ext; - o^.used := true; - try declare(o); - Buf.str(ADR(s), nameOf(a^.home^.name)); - Buf.add(ADR(s), '.'); - Buf.str(ADR(s), nameOf(a^.name)); - Buf.add(ADR(s), ','); - INC(i); - end; - try expect(Scan.sRparen); - if i # m^.args.n then - return Scan.markAt(m^.args.at, say1("too many type arguments for {}", nameOf(m^.name))); - end; - text := Buf.bytes(ADR(s)); - text[LEN(text) - 1] := ')'; - m^.sname := internName(text); - Buf.done(ADR(s)); - return nil; -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. *) -proc warn(o: PObj); -var s, t: []U8; -begin - s := nameOf(o^.name); - if (o^.cls = Sym.oProc) and o^.openEnd then - Diag.warning(o^.pos, say1("{} may reach its end without return, and then returns zero", s)); - end; - if o^.exported or (s[0] = '_') then return; end; - if o^.used and (o^.read or (o^.cls # Sym.oVar) or o^.isVar or o^.ext) then return; end; - match o^.cls of - | oConst: t := say1("constant {}", s); - | oType: t := say1("type {}", s); - | oVar: - if o^.param then t := say1("parameter {}", s); else t := say1("variable {}", s); end; - | oProc: t := say1("procedure {}", s); - | oModule: t := say1("module {}", s); - | else: return; - end; - if o^.used then - Diag.warning(o^.pos, say1("{} is assigned but never read", t)); - elsif o^.cls = Sym.oModule then - Diag.warning(o^.pos, say1("{} is imported but never used", t)); - else - Diag.warning(o^.pos, say1("{} is never used", t)); - end; - if not o^.used and (o^.param or o^.ind) then - Diag.help(say1("if it must be there, call it _{}", s)); - end; -end; - -(* Warns of the call at p, which drops its n results *) -proc dropped(p: Diag.Pos; n: INT); -var s, blanks: []U8; i: INT; -begin - s := Diag.source(p); - i := 0; - while (i < LEN(s)) and (s[i] # '(') do INC(i); end; - if i < LEN(s) then s := s[0..i]; end; - blanks := "_"; - for i := 2 to n do blanks := say1("{}, _", blanks); end; - if n = 1 then - Diag.warning(p, say1("the result of {} is dropped", s)); - else - Diag.warning(p, say1("the results of {} are dropped", s)); - end; - Diag.help(say2("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. *) -proc warnings(m: PModule; firstDrop: INT); -var a, b: PObj; n: PModule; i: INT; -begin - n := firstModule; - while (n # nil) and (n^.name # m^.name) do n := n^.next; end; - if n # nil then return; end; - 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 - dropped(drops[i].at, drops[i].n); - INC(i); - elsif (b = nil) or ((a # nil) and (a^.pos.a < b^.pos.a)) then - warn(a); - a := a^.chain; - else - warn(b); - b := b^.chain; - end; - end; -end; - -(* Modules being compiled, not yet finished: for finding a cycle. *) -var - pending: [MaxPending]PModule; - numPending: INT; - -proc exists(path: []U8): BOOL; -var info: Sys.Info; err: INT; -begin - info, err := Sys.info(path); - return (err = 0) and info.file; -end; - -(* Which file path is, as its device and inode: two names of one file - have the same. Zero for a file that can't be asked about. *) -proc identity(path: []U8): (INT, INT); -var a: [4096]U8; st: [18]INT; (* struct stat: st_dev, then st_ino *) -begin - if LEN(path) >= 4096 then return 0, 0; end; - COPY(a[0..LEN(path)], path); - a[LEN(path)] := 0; - if SYSCALL(4, ADR(a[0]), ADR(st)) < 0 then return 0, 0; end; - return st[0], st[1]; -end; - -(* s, in memory that is never freed, for what must outlast the buffer it is in *) -proc keep(s: []U8): []U8; -var p: ^U8; -begin - if LEN(s) = 0 then return ""; end; - p := Scan.grab(LEN(s)); - COPY(p[0..LEN(s)], s); - return p[0..LEN(s)]; -end; - -proc importModule(name: INT; args: Sym.Args): (PModule, ERROR); forward; - -(* 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. *) -proc compileFile(path: []U8; n: INT; args: Sym.Args; checkOnly: BOOL): (PModule, ERROR); -var - st: Scan.State; saved: [Sym.MaxDepth]INT; d: INT; - oldMod: PModule; oldCheck, oldChecks: BOOL; m: PModule; - lib: ^Sym.Lib; start: Diag.Pos; alias, mname, line, oldPath: INT; o: PObj; bodyChunk: INT; iargs: Sym.Args; - generic: BOOL; argsAt: Scan.State; why: []U8; firstDrop: INT; -begin - firstDrop := numDrops; - Scan.saveScan(st); - d := Sym.saveScopes(saved[0..Sym.MaxDepth]); - oldMod := Sym.curModule; oldCheck := checkMode; oldPath := Chunk.curFilePath(); oldChecks := Item.checks; - Item.setChecks(true); - Chunk.setCurFile(internName(path)); - why := Scan.open(path); - if LEN(why) # 0 then Diag.fatal(say2("can't read {}: {}", path, why)); end; - NEW(m, Heap.heap); - m^.name := n; - m^.sname := n; - m^.args := args; - m^.scope := Sym.newScope(); - m^.path := path; - m^.body := -1; - m^.checkOnly := checkOnly; - Sym.setCurModule(m); - checkMode := checkOnly; - if not checkOnly then - if numPending >= MaxPending then - return nil, Scan.mark(tooMany(MaxPending, "imports nested deep")); - end; - pending[numPending] := m; - INC(numPending); - end; - try Sym.openScope(m^.scope); - Scan.next; - try expect(Scan.sModule); - if (Scan.tok # Scan.sIdent) or (Scan.id # n) then - return nil, Scan.mark(say2("expected module {}, found {}", nameOf(n), Scan.found())); - end; - Scan.next; - (* the module first pending is the one named on the command line, - which nothing imports, so no arguments come with it *) - if (Scan.tok = Scan.sLparen) and not checkOnly and (numPending = 1) then - return nil, Scan.mark(say1("{} is generic: it is compiled where a module imports it", nameOf(n))); - elsif Scan.tok = Scan.sLparen then - try moduleParams(m); - elsif args.n > 0 then - return nil, Scan.markAt(args.at, say1("{} isn't generic", nameOf(n))); - end; - try expect(Scan.sSemicolon); - while Scan.tok = Scan.sImport do - Scan.next; - repeat - if Scan.tok # Scan.sIdent then return nil, expected("a module name"); end; - start := Scan.tokPos(); - alias := Scan.id; - mname := Scan.id; - iargs.n := 0; - generic := false; - Scan.next; - if Scan.tok = Scan.sBecomes then - Scan.next; - if Scan.tok # Scan.sIdent then return nil, expected("a module name"); end; - mname := Scan.id; - Scan.next; - if Scan.tok = Scan.sLparen then - generic := true; - Scan.saveScan(argsAt); - try skipArgs(); - end; - end; - iargs.at := Scan.spanFrom(start); - o := Sym.newObj(Sym.oModule, alias, nil); - o^.pos := start; - try declare(o); - if not generic then - o^.home := try importModule(mname, iargs); - addImport(m, o^.home); - else - o^.home := nil; (* until the instance is made, at its first use *) - if numDeferred >= MaxDeferred then - return nil, Scan.mark(tooMany(MaxDeferred, "generic imports")); - end; - deferred[numDeferred].o := o; - deferred[numDeferred].home := m; - deferred[numDeferred].mname := mname; - deferred[numDeferred].args := argsAt; - deferred[numDeferred].at := iargs.at; - INC(numDeferred); - end; - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - try expect(Scan.sSemicolon); - end; - while Scan.tok = Scan.sLink do - Scan.next; - if (Scan.tok = Scan.sIdent) and (Scan.id = nameStatic) then - m^.linkStatic := true; - elsif Scan.tok = Scan.sString then - NEW(lib, Heap.heap); - lib^.name := internName(Scan.strBytes()); - lib^.next := m^.libs; - m^.libs := lib; - m^.usesC := true; - else - return nil, expected("a library or \"static\""); - end; - Scan.next; - try expect(Scan.sSemicolon); - end; - (* check off;: the module's index and slice checks left out; neither - word is reserved *) - if (Scan.tok = Scan.sIdent) and (Scan.id = nameCheck) then - Scan.next; - if (Scan.tok # Scan.sIdent) or (Scan.id # nameOff) then return nil, expected("\"off\""); end; - Scan.next; - try expect(Scan.sSemicolon); - Item.setChecks(false); - end; - declarations(true); - if Scan.tok = Scan.sBegin then - if checkMode then - try skipBody(); - else - try instancesFor(true); - line := Scan.curLine(); - Scan.next; - bodyChunk := Chunk.newChunk(Chunk.secText, m^.sname, nameBody); - m^.body := bodyChunk; - Item.beginProc(tBodySig, nil); - deferSlot := 0; - curResult := nil; - Gen.enterBody(bodyChunk, line); - stray := false; elseIf := false; - try statements(); - Chunk.noteLine(Scan.curLine(), Scan.curCol()); - try expect(Scan.sEnd); - try Gen.endProc(bodyChunk, false); - end; - else - try expect(Scan.sEnd); - end; - if (Scan.tok # Scan.sIdent) or (Scan.id # n) then - return nil, endMissing(Scan.missingPos(), say2("expected {}, found {}", nameOf(n), Scan.found())); - end; - Scan.next; - if Scan.tok # Scan.sPeriod then return nil, expected("\".\""); end; - o := m^.first; - while o # nil do - if (o^.cls = Sym.oProc) and o^.fwd then - Diag.error(Scan.tokPos(), say1("{} is declared forward but never defined", nameOf(o^.name))); - end; - o := o^.chain; - end; - if (Diag.errors = 0) and not checkOnly then warnings(m, firstDrop); end; - numDrops := firstDrop; - if Diag.errors > 0 then Diag.finish(); end; (* a module with errors stops the compiler after it *) - Sym.closeScope(); - m^.done := true; - if not checkOnly then - DEC(numPending); - if lastModule = nil then firstModule := m; else lastModule^.next := m; end; - lastModule := m; - end; - Sym.setCurModule(oldMod); checkMode := oldCheck; Chunk.setCurFile(oldPath); Item.setChecks(oldChecks); - Sym.restoreScopes(d, saved[0..Sym.MaxDepth]); - Scan.restoreScan(st); - return m, nil; -end; - -(* The interface check: b must export just what a does. *) -proc compareIface(a, b: PModule); -var o, q: PObj; -begin - o := a^.first; - while o # nil do - if o^.exported then - q := Sym.find(b^.scope, o^.name); - if (q = nil) or not q^.exported or (Sym.fingerprint(o) # Sym.fingerprint(q)) then - Diag.fatal(Diag.say("{}: {} isn't exported as in {}", [Fmt.str(b^.path), Fmt.str(nameOf(o^.name)), Fmt.str(a^.path)])); - end; - end; - o := o^.chain; - end; - q := b^.first; - while q # nil do - o := Sym.find(a^.scope, q^.name); - if q^.exported and ((o = nil) or not o^.exported) then - Diag.fatal(Diag.say("{}: {} isn't exported by {}", [Fmt.str(b^.path), Fmt.str(nameOf(q^.name)), Fmt.str(a^.path)])); - end; - q := q^.chain; - end; -end; - -(* Reads every other file of module n in dir, and checks its interface - against m, compiled from the file named chosen. *) -proc checkSiblings(dir, chosen: []U8; n: INT; m: PModule; args: Sym.Args): ERROR; -var - dp: Sys.Dir; e, prefix: []U8; i, numOthers: INT; more: BOOL; sib: PModule; - others: [32][]U8; -begin - prefix := say1("{}.", nameOf(n)); - numOthers := 0; - if Sys.openDir(ADR(dp), dir) # 0 then return nil; end; - repeat - e, more := Sys.nextEntry(ADR(dp)); - if not more then break; end; - if (LEN(e) > 4) and Str.hasPrefix(e, prefix) and (e[LEN(e) - 4..LEN(e)] = ".raz") - and (e # chosen) and (numOthers < 32) then - others[numOthers] := keep(e); - INC(numOthers); - end; - until false; - Sys.closeDir(ADR(dp)); - for i := 0 to numOthers - 1 do - sib := try compileFile(say2("{}/{}", dir, others[i]), n, args, true); - compareIface(m, sib); - end; - return nil; -end; - -(* The directories searched for modules, in order, from -1 to numInc *) -proc searchDir(i: INT): []U8; -begin - if i = -1 then return mainDir; end; - if i = numInc then return libDir; end; - return incDirs[i]; -end; - -(* The file of module n in dir that suffix j says: Name.linux-x86_64.raz - for a file of this target alone, and so on to Name.raz *) -proc fileName(n, j: INT): []U8; -begin - return Diag.say("{}{}.raz", [Fmt.str(nameOf(n)), Fmt.str(Suffixes[j])]); -end; - -proc moduleFile(n: INT): ([]U8, []U8, BOOL); -var i, j: INT; dir, f: []U8; -begin - for i := -1 to numInc do - dir := searchDir(i); - for j := 0 to 3 do - f := fileName(n, j); - if exists(say2("{}/{}", dir, f)) then return dir, f, true; end; - end; - end; - return "", "", 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) *) -proc checkOneModule(n: INT; dir, f: []U8; at: Diag.Pos): ERROR; -var - i, j, dev, ino, mineDev, mineIno: INT; past, chosen: BOOL; g, files, others: []U8; -begin - mineDev, mineIno := identity(say2("{}/{}", dir, f)); - others := ""; - past := false; - for i := -1 to numInc do - if past then - files := ""; - chosen := false; - for j := 0 to 3 do - g := say2("{}/{}", searchDir(i), fileName(n, j)); - if exists(g) then - files := say2("{} and {}", files, Diag.shownPath(g)); - dev, ino := identity(g); - chosen := chosen or ((dev = mineDev) and (ino = mineIno)); - end; - end; - if not chosen then others := say2("{}{}", others, files); end; - end; - past := past or (searchDir(i) = dir); - end; - if LEN(others) = 0 then return nil; end; - Diag.error(at, say3("module {} is in {}{}", nameOf(n), Diag.shownPath(say2("{}/{}", dir, f)), others)); - Diag.help("a program has one module of each name; a symbolic link to one of these files chooses it"); - return Scan.Failed; -end; - -proc importModule(name: INT; args: Sym.Args): (PModule, ERROR); -var m: PModule; i: INT; dir, f, where: []U8; found: BOOL; -begin - m := findModule(name, args); - if m # nil then return m, nil; end; - for i := 0 to numPending - 1 do - if isModule(pending[i], name, args) then - return nil, Scan.markAt(args.at, say1("{} imports itself", nameOf(name))); - end; - end; - dir, f, found := moduleFile(name); - if not found then - Diag.error(args.at, say1("can't find module {}", nameOf(name))); - where := Diag.shownPath(searchDir(-1)); - for i := 0 to numInc do where := say2("{}, {}", where, Diag.shownPath(searchDir(i))); end; - Diag.help(say2("looked for {}.raz in {}", nameOf(name), where)); - return nil, Scan.Failed; - end; - try checkOneModule(name, dir, f, args.at); - m := try compileFile(say2("{}/{}", dir, f), name, args, false); - try checkSiblings(dir, f, name, m, args); - return m, nil; -end; - -proc addImport(m, im: PModule); -var imp: ^Sym.Import; -begin - NEW(imp, Heap.heap); - imp^.home := 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. *) -proc makeInstance(i: INT; at: Diag.Pos): ERROR; -var - d: Deferred; st: Scan.State; args: Sym.Args; types, exported, ext, wasQuiet: BOOL; nf, nd: INT; - ft: [MaxFwd]PType; fp: [MaxFwd]Diag.Pos; decl: [MaxNames]INT; -begin - d := deferred[i]; - DEC(numDeferred); - deferred[i] := deferred[numDeferred]; - Scan.saveScan(st); - Scan.restoreScan(d.args); - args.n := 0; - making := true; useAt := at; - try parseArgs(args, nameOf(d.mname)); - making := false; - Scan.restoreScan(st); - args.at := d.at; - types := inTypes; exported := declExported; ext := inExtern; wasQuiet := Diag.quiet; - nf := numFwd; ft := fwdTypes; fp := fwdPos; nd := numDeclaring; decl := declaring; - d.o^.home := try importModule(d.mname, args); - inTypes := types; declExported := exported; inExtern := ext; Diag.setQuiet(wasQuiet); - numFwd := nf; fwdTypes := ft; fwdPos := fp; numDeclaring := nd; declaring := decl; - addImport(Sym.curModule, d.o^.home); - return nil; -end; - -proc firstUse(o: PObj; at: Diag.Pos): ERROR; -var i: INT; -begin - for i := 0 to numDeferred - 1 do - if deferred[i].o = o then return makeInstance(i, at); end; - end; - return Scan.Failed; (* 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. *) -proc instancesFor(wholeRest: BOOL): ERROR; -var st: Scan.State; d, i: INT; begun: BOOL; -begin - if checkMode then return nil; end; - i := numDeferred - 1; - while (i >= 0) and (deferred[i].home # Sym.curModule) do DEC(i); end; - if i < 0 then return nil; end; - (* 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. *) - Scan.saveScan(st); - d := 0; begun := false; - repeat - match Scan.tok of - | sIdent: - for i := numDeferred - 1 to 0 by -1 do - if (deferred[i].home = Sym.curModule) and (deferred[i].o^.name = Scan.id) then - try makeInstance(i, Scan.tokPos()); - end; - end; - | sBegin: - begun := begun or (d = 0); - INC(d); - | sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: INC(d); - | sEnd, sUntil: DEC(d); - | else: - end; - if not wholeRest and (d = 0) and (begun or (Scan.tok = Scan.sForward) or (Scan.tok = Scan.sCode)) then break; end; - Scan.next; - until Scan.tok = Scan.sEof; - Scan.restoreScan(st); - return nil; -end; - -(* The main module, from the file at path, and Rt, which every program - needs, first *) -proc compileMain*(path: []U8): (PModule, ERROR); -var base: []U8; i, n: INT; none: Sym.Args; m: PModule; -begin - none.n := 0; - i := LEN(path); - while (i > 0) and (path[i - 1] # '/') do DEC(i); end; - if i = 0 then mainDir := "."; else mainDir := path[0..i - 1]; end; - base := path[i..LEN(path)]; - i := 0; - while (i < LEN(base)) and (base[i] # '.') do INC(i); end; - base := base[0..i]; - if LEN(base) = 0 then Diag.fatal(say1("no module in {}", path)); end; - n := internName(base); - none.at := Scan.tokPos(); - if n # nameRt then _ := try importModule(nameRt, none); end; - m := findModule(n, none); - if m # nil then return m, nil; end; - return compileFile(path, n, none, false); -end; - -begin - nameRt := internName("Rt"); - nameFail := internName("fail"); - nameAdr := internName("ADR"); - nameBody := internName("body"); - nameStatic := internName("static"); - nameCheck := internName("check"); - nameOff := internName("off"); - tArgv := newPtr(newPtr(Sym.tU8, false), false); - tBodySig := Sym.newType(Sym.fProc, 8, 8); -end Parse. diff --git a/self/README.md b/self/README.md deleted file mode 100644 index 3e17d74..0000000 --- a/self/README.md +++ /dev/null @@ -1,195 +0,0 @@ -# self: the compiler in raz - -The port of the Pascal compiler, the **seed** in `../src/`, to raz. -`../PLAN.md`, "Self", says what it is for and the order of its units. - -One module to a seed unit, with the seed's name, written to the same -rules: plain code, each module opening with what it is, what it -depends on and what it leaves out. The seed is never edited from here. - - make self # each unit against the seed's, on the same files - make self-bench # the scanner's speed against the seed's - make fixpoint # the seed builds self, that builds self, that builds it again - -`Chunk` and `Sym` have no input files to read, so each has a dumper -pair, `test/ChunkDump` and `test/SymDump`, that runs one fixed -pseudo-random script of calls on its side and prints all it made or -answered (`Sym` also ends, as an argument says, in the error of a name -declared twice or of too many scopes): the output, the messages and -the status must be the same. `Link` and `Elf` are tested by -`test/LinkDump`, which makes a program of chunks by a script and writes -it as a static, a dynamic and a stripped executable, which must be the -same file; `X64` by `test/X64Dump`, every encoder with operands from a -script, bytes, fixups and listing, and by `test/AsmDump` on the files -`test/genasm.py` makes: a long run of every instruction the assembler -knows, and a file for each of its errors. -`Gen` is tested by `test/GenDump`, a script of calls, valid by -construction (an expression pushes its operands and then operates; a -statement leaves the stack as it found it), that compiles 80 procedures -with every kind of expression, statement, call, check, frame and defer, -and the entry point, static and dynamic: the bytes, fixups, line notes -and listing must be the same. -`Item` is tested by `test/ItemDump`, a script of operands and operations -with mistakes among them (a constant, a variable in the frame, a -register, a slot, another module's or C's, a string, a procedure, a -selector through a pointer, a field, an element or a slice, a call, a -`match`, a `for`, `return`, `COPY`, a variant): each step shows what -it gave, or its message, and goes on, as the parser does after an -error. What each step gave, the messages, and the bytes, fixups, line -notes and listing of the code must be the same, over 60 scripts (a -run ends at its 20th error, as a compile does). The text its messages -point into is `test/ItemDump.txt`. - -`Parse` and `Raz`, the last two units, are tested whole: the seed builds -`self/Raz.raz` into `build/self/raz.self`, and each compiler, run as -`build/cmp/raz` (a program holds the paths it was made from, and the -library is found beside the compiler), compiles the library, the -examples, the tools, `self/` itself, every test of `test/` and -`conform/`, and the 348,025-line program of `test/genbench.py`, with the -options each test has. The executable, the messages, and the status -must be the same for every file: 409 of them, 289 of which are errors. -`make self-bench` gives the speed of both. - -`make fixpoint` (`fixpoint.sh`) is the proof that the port is whole: -the seed builds `Raz.raz` (stage 1), stage 1 builds it (stage 2), and -stage 2 builds it again (stage 3). Stages 2 and 3 must be the same -file; they are, and so is stage 1, since the seed and the port make the -same code. Stage 3 then stands in for `./raz`, and `make check` and -`make bench` run on it. Each stage is built by the same command in the -same place, since a program holds the paths it was made from. - -`check.sh` builds a dumper for each side, `test/ScanDump.pas` over the -seed's units and `test/ScanDump.raz` over these, and has both read the -library, the examples, every test of the compiler and a file for each -message the scanner makes (`test/genlex.py`) and for hundreds of reals -that are hard to read exactly (`test/genreals.py`): the output, the -messages and the status must be the same. - -## What the port found - -Not the seed's to mend; for the owner to choose. - -- **Names.** An exported variable is read-only outside its module, so - what the parser sets in the seed's `diag` and `scan` (`quiet`, - `werror`, `recovery`, `skipping`) have setters. The `sbuf` array, - which can't be sliced outside, is `strBytes`. -- **Going on after an error.** raz has no `setjmp`, and the seed's parser - ends its errors in a jump back to the statement or declaration being - read, which is how it reports up to 20 errors in a run. The language - gained `try` (report 2026-10.20) for this: `Scan.mark` and the others - show the error and return `Scan.Failed`, which the parser passes up - with `try` to where it reads on. `test/Recover.raz` is the pattern. -- **`NO_COLOR` set to nothing.** `Sys.env` gives "" for a variable that - is unset and for one that is empty, so the port reads the second as - the first. no-color.org says a variable that is empty doesn't turn - colour off, so the port is the one that follows it and the seed - differs; no test depends on either. -- **Strings are slices.** A message is a `[]U8` made by `Diag.say`, - which keeps what it makes: messages are made only to be shown. A name - from `nameOf` stays valid, since names are kept in chunks that are - never moved; the seed's was a copy. -- **Reserved words as names.** The seed's `code` (the text buffer of - `Chunk`) is `text`; `module` (a record's, an import's) is `home`; an - object's `link` is `chain`. A seed type `TName` is `Name`, and the - procedures begin in lower case, as `Scan`'s do. -- **Errors in `Sym`.** `insert` (a name declared twice) and `openScope` - (too many scopes) show the error and return `Scan.Failed`, as `mark` - does, for the parser to pass up with `try`. `saveScopes` returns what - the seed's `var d` gave. -- **Setters.** What other units set in `Chunk` has one each (`setLive`, - `setAdr`, `setReals`, `setSaves`, `setCurFile`, and `rewindTo` for - gen's `Redo` and `Rewind`), and `Sym` has `setCurModule`. `Scan.grab` - is exported for the memory they all take. -- **No `continue`.** The seed's loops that skip to the next round - (`MarkLive`, the line program, the assembler's statements) have the - rest of the body in an `else`, or in a procedure of its own. -- **`X64`.** `code` of `Chunk` being reserved, its text is `Chunk.text`; - `Say` and the rest of the encoder keep their names, in lower case. - `ConstFn`, the parser's reader of a constant, returns an `ERROR` too, - and `assemble` returns what it passes up. `mem` marks an offset beyond - 32 bits and goes on, since an operand has nowhere to return an error - to; the compile ends with the message shown. The listing's text is - made by `Diag.say`, which keeps it, and only when `-S` asks for it. -- **`Link` and `Elf`.** What `raz.pas` set there has a setter each: - `Link.setPlaces`, `Elf.needLib`, `noLibs`, `setMainPath`, - `setStripped` and `X64.setListing`. The file is written by - `Files.write` and made executable by `Sys.chmod`, in place of one - `open` with mode 755 (which the umask would trim). -- **`Gen`.** The seed's `Mark` in the middle of a push or a check - can't give an error back: `newEntry` (the stack's 256 places) and - `check` (4,096 checks a procedure) show it and go on without doing - what they couldn't, and the parser's `resetStack` makes the stack - right again; `endProc` returns its error ("frame too big") and - `codeProc` the assembler's. A `var` out of the seed became a result - (`topConst`, `operands`, `deferBegin`); the labels, which are chains - that a call extends, stay `var`. `inPlace` has a setter. The seed's - `Call` record is `CallInfo` (the procedure is `call`) and `TLink` is - `Link`. A `match` on an enumeration takes one name to an arm, and a - set holds at most 64 names, so `Scan.Sym` (over 64) has none: the - seed's sets of its names are chains of `=`. -- **`Item`.** The seed's `Mark` ended in a jump, so here every - routine that can find an error returns an `ERROR` as its last result - and the ones that call it pass it up with `try`; `Item` shows the - message and returns what the seed jumped out of, so a script that - goes on after an error sees the same state. The seed's `Mismatch` of - two operands is `mismatchOps`, `demoted` and `checks` have setters, - and `matchBegin`, `toSlot` and `errorChunk` return their value and - the error. `op2` has a parameter it never read, now `_L`. A message - is made by `Diag.say` from strings, with no `shortstring` to add up. - A `Mark` with no place is at the scanner's, as in the seed. -- **No `const` parameter.** The seed's `const x: TItem` is a value - parameter here, so an item of about 130 bytes is copied at each call - of `what`, `adrOf`, `notValue` and the others. The result is the - same; whether the compiler built from this is slower for it is for - the speed test of step 4 to say. A `const` parameter (a hint that - the callee won't change it, so that the caller may pass its address) - would be a language change: it goes on the wish list. -- **`Parse` and the seed's jumps.** The seed's `Guard`, `setjmp` and - `longjmp` are `guard`, a record of what to put back, and the `ERROR` - that comes up through `try` to the statement or declaration that is - the recovery point (`statement`, `declaration`), which looks at it, - puts the state back (`restore`) and skips ahead, as the seed does. - `giveUp`, the seed's `GiveUp`, returns the error on to the next one, - or ends the compile if there is none (`guards` counts them). A routine - that can't fail has no `ERROR` (`declarations`, `declaration`). The - seed's nested procedures (`ChooseRegs`'s three) are procedures of the - module with its candidates in variables. `defer` and `module` being - words, the seed's `Defer` is `deferStatement`. A message is made - from strings with `Diag.say`, which has no shortstring to add up to. - `Scan.skipping` is exported to be read, and `Scan.strWithZero` gives - `Item.makeStr` a pointer to a string that may be empty: the seed's - `@sbuf` indexed nothing, and `ADR(Scan.strBytes()[0])`, which the - port of `Item` had, stopped on `""`. -- **`Raz`.** The program is `proc main*: INT`. Where it is, for the - library beside it, it reads from `/proc/self/exe` as FPC's `ParamStr(0)` - does: `Files.arg(0)` is what the shell was typed, and `./raz` made the - library `./lib`, so the same program held other paths in its file. - `raz run` writes the memfd with `Elf.writeElf` and executes it with - the system call, `execve`, which `Sys` has no procedure for. The - version is the module `Version`, which `check.sh` makes in - `build/self/` from `build/version.inc`, as the seed's `{$I}` is. - Two names of a file, for a module found in two places, are told by - the device and inode `SYSCALL` `stat` gives, which `Sys.info` lacks. -- **Sets of `Scan.Sym`.** It has 76 names and a set holds 64, so the - operators a rule names are chains of `=` or the helpers `oneOf` and - `isRel`. (A `match` arm with several names, which the seed's `case` - has, was added to the report for this: 2026-10.21.) -- **Strings made by the compiler.** A joined string (`"a" + "b"`) and - an error's text are built in memory from `Scan.grab`, which is never - freed, in place of `GetMem` and `FreeMem`; the compiler runs once. -- **No bit cast.** A real's bits and back go through a pointer. -- **Speed.** On the 348,025 lines of `test/genbench.py`, 7.6 MB, the - seed's scanner takes 75 ms and this one 74. It took 121 at first. - What closed the gap, in the source: a byte loop in place of the slice - comparison `a[0..n] = b[0..n]` (97 ms), a 256-entry table for the - bytes of a name (84), and one for the symbols that are a byte each - (75). What is left for the code generator, which would help every - module: the slice comparison is slower than the loop it stands for. - On the whole compiler, the same 348,025 lines take 427 ms with the - seed's and 770 with this one (452,000 lines a second, over the 400,000 - the budget wants): `Scan.tokPos`, a record of three words returned - through a pointer, is 9% of it, and the rest is spread thin; the - `const` parameter of `Item` isn't what stands out. - (The seed's `match` on an integer was a chain of compares, each - loading the selector from the frame and jumping over a `jmp`, where - FPC makes a jump table; now it makes one too.) diff --git a/self/Raz.raz b/self/Raz.raz deleted file mode 100644 index a074f07..0000000 --- a/self/Raz.raz +++ /dev/null @@ -1,273 +0,0 @@ -(* Raz: 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, and Version, a module the build makes - (build/self/Version.raz) from what git describe says, as the seed's - build/version.inc is. - Leaves out: the work itself; the other units compile, link and - write, and this only reads the command line and runs them in order. *) -module Raz; -import Sys, Out, Version, Files, Fmt, Diag, Scan, Sym, Chunk, X64, Gen, Parse, Link, Elf; - -const - Report = "2026-10.21"; (* the version of doc/raz.md it follows *) - MemfdCreate = 319; (* the system call *) - MfdCloexec = 1; (* an ELF still executes: the kernel opens it first *) - Execve = 59; - -var - links: [4]Gen.Link; - numLinks: INT; - -proc say1(f, a: []U8): []U8; -begin - return Diag.say(f, [Fmt.str(a)]); -end; - -(* The number of the name s *) -proc internStr(s: []U8): INT; -begin - return Scan.intern(ADR(s[0]), LEN(s)); -end; - -(* The modules the program uses: the main module, Rt, and every module - they import. A module read only for the interface check is not. *) -proc use(m: ^Sym.Module); -var i: ^Sym.Import; -begin - if m^.used then return; end; - m^.used := true; - i := m^.imports; - while i # nil do - use(i^.home); - i := i^.next; - end; -end; - -(* Whether the program uses C: if so, the libraries it needs go to - Elf, the C library first. *) -proc usesC: BOOL; -var m, st, c: ^Sym.Module; l: ^Sym.Lib; -begin - st := nil; c := nil; - Elf.noLibs(); - _ := Elf.needLib(internStr("libc.so.6")); - m := Parse.firstModule; - while m # nil do - if m^.used and m^.linkStatic then st := m; end; - if m^.used and m^.usesC then c := m; end; - l := m^.libs; - while m^.used and (l # nil) do - if not Elf.needLib(l^.name) then Diag.fatal("more than 32 libraries"); end; - l := l^.next; - end; - m := m^.next; - end; - if (st # nil) and (c # nil) then - Diag.fatal(Diag.say("{} says link static, but {} uses C", [Fmt.str(Scan.nameOf(st^.name)), Fmt.str(Scan.nameOf(c^.name))])); - end; - if c = nil then Elf.noLibs(); end; - return c # nil; -end; - -(* What raz -h says *) -proc usage; -begin - Out.str("usage: raz [option]... Main.raz compiles Main.raz and the modules it imports\n"); - Out.str(" raz run [option]... Main.raz [arg]... compiles it and runs it, with the args\n"); - Out.str("options:\n"); - Out.str(" -o file the program's file, Main without .raz if left out\n"); - Out.str(" -I dir looks for imported modules in dir too, after Main.raz's own\n"); - Out.str(" -Werror a warning counts as an error\n"); - Out.str(" -S lists the main module's code, under each line of source\n"); - Out.str(" -s strips symbols, line numbers, the places a failure is told\n"); - Out.str(" by and the profiler: a failure says only its address\n"); - Out.str(" -noprofile leaves out the profiler, which RAZ_PROFILE turns on\n"); - Out.str(" -h, --help says this\n"); - Out.str(" --version says the version, and the report it follows\n"); - Out.str("see raz(1), and the report, doc/raz.md\n"); - Out.flush(); -end; - -proc rtObj(rt: ^Sym.Module; n: []U8): ^Sym.Obj; -var o: ^Sym.Obj; -begin - o := Sym.find(rt^.scope, internStr(n)); - if o = nil then Diag.fatal(say1("Rt has no {}", n)); end; - return o; -end; - -(* Rt is given the address of chunk, in its variable v *) -proc addLink(chunk: INT; v: ^Sym.Obj); -begin - links[numLinks].chunk := chunk; - links[numLinks].into := v^.chunk; - INC(numLinks); -end; - -(* s as a C string, in memory that is never freed *) -proc cstr(s: []U8): ^U8; -var p: ^U8; -begin - p := Scan.grab(LEN(s) + 1); - if LEN(s) > 0 then COPY(p[0..LEN(s)], s); end; - p[LEN(s)] := 0; - return p; -end; - -proc main*: INT; -var - path, outPath, s: []U8; dir: []U8; - i, first, entry, fd, last, errno: INT; - m, rt: ^Sym.Module; mainObj: ^Sym.Obj; - run, noProfile, listing: BOOL; err: ERROR; -begin - path := ""; - outPath := ""; - noProfile := false; - listing := false; - run := (ARGC() >= 2) and (Files.arg(1) = "run"); - if run then i := 2; else i := 1; end; - while i < ARGC() do - s := Files.arg(i); - if s = "-I" then - INC(i); - if Parse.numInc > 15 then Diag.fatal("more than 16 -I directories"); end; - Parse.addIncDir(Files.arg(i)); - elsif s = "-o" then - INC(i); - outPath := Files.arg(i); - elsif s = "-Werror" then - Diag.setWerror(true); - elsif s = "-S" then - listing := true; - X64.setListing(true); - elsif s = "-s" then - Elf.setStripped(true); - elsif s = "-noprofile" then - noProfile := true; - elsif (s = "-h") or (s = "--help") then - usage(); - return 0; - elsif s = "--version" then - Out.str(Diag.say("raz {}, report {}\n", [Fmt.str(Version.Text), Fmt.str(Report)])); - Out.flush(); - return 0; - elsif (LEN(s) > 0) and (s[0] = '-') then - Diag.fatal(say1("unknown option {}", s)); - else - path := s; - first := i; - if run then break; end; (* the rest are the program's *) - end; - INC(i); - end; - if LEN(path) = 0 then - usage(); - return 1; - end; - if run and (LEN(outPath) > 0) then Diag.fatal("raz run takes no -o"); end; - (* where raz is, as the system says, for the library beside it *) - dir, errno := Sys.readLink("/proc/self/exe"); - if errno # 0 then dir := Files.arg(0); end; - i := LEN(dir); - while (i > 0) and (dir[i - 1] # '/') do DEC(i); end; - if i = 0 then Parse.setLibDir("lib"); else Parse.setLibDir(say1("{}lib", dir[0..i])); end; - if LEN(outPath) = 0 then - outPath := path; - last := LEN(outPath); - if (last >= 4) and (outPath[last - 4..last] = ".raz") then - outPath := outPath[0..last - 4]; - else - outPath := say1("{}.out", outPath); - end; - end; - - m, err := Parse.compileMain(path); - if err # nil then - Diag.finish(); - return 1; - end; - if Diag.errors > 0 then Diag.finish(); end; - - use(m); - rt := Parse.firstModule; - while (rt # nil) and (Scan.nameOf(rt^.name) # "Rt") do rt := rt^.next; end; - if rt # nil then use(rt); end; - - mainObj := Sym.find(m^.scope, internStr("main")); - if mainObj # nil then - if (mainObj^.cls # Sym.oProc) or not mainObj^.exported then - Diag.error(mainObj^.pos, "main must be an exported procedure"); - elsif (mainObj^.typ^.len # 0) or ((mainObj^.typ^.base # nil) and (mainObj^.typ^.base # Sym.tInt)) then - Diag.error(mainObj^.pos, "main must be proc main* or proc main*: INT"); - end; - if Diag.errors > 0 then Diag.finish(); end; - end; - Diag.finish(); - - if rt = nil then Diag.fatal("can't find module Rt"); end; - (* 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 Elf.stripped then - Link.setPlaces(Chunk.newChunk(Chunk.secRodata, -1, -1)); - Chunk.setData(Link.placesChunk, nil, 0, 8); - addLink(Link.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; - end; - entry := Gen.entryPoint(usesC(), Parse.firstModule, mainObj, rtObj(rt, "cExit")^.chunk, - rtObj(rt, "exit")^.chunk, links[0..numLinks], numLinks); - - Link.markLive(entry); - if not Parse.HasReals then - for i := 0 to Chunk.numChunks - 1 do - if Chunk.chunks[i].live and Chunk.chunks[i].reals then - Diag.error(Chunk.chunks[i].realsAt, "this target has no reals"); - end; - end; - end; - if Diag.errors > 0 then Diag.finish(); end; - if listing then - X64.list(m^.sname); - return 0; - end; - - Elf.setMainPath(path); - if run then - (* argv from Main.raz on is the program's, ending in nil as it must *) - fd := SYSCALL(MemfdCreate, cstr("raz"), MfdCloexec); - if fd < 0 then Diag.fatal("can't create a memfd"); end; - outPath := Diag.say("/proc/self/fd/{}", [Fmt.int(fd)]); - Elf.writeElf(outPath, entry); - _ := SYSCALL(Execve, cstr(outPath), ARGV() + first, ARGV() + (ARGC() + 1)); - Diag.fatal(say1("can't run {}", path)); - end; - Elf.writeElf(outPath, entry); - return 0; -end; - -end Raz. diff --git a/self/Scan.raz b/self/Scan.raz deleted file mode 100644 index 7887397..0000000 --- a/self/Scan.raz +++ /dev/null @@ -1,1002 +0,0 @@ -(* Scan: 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: Sys, 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: mark and the others report one and give - back Failed, which it passes up with try to where it can read on. *) -module Scan; -import Sys, Heap, Mem, Fmt, Str, Diag; - -type - NamePtr = ^U8; - - Sym* = (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); - - (* Where the scanner is. Importing a module compiles it in the middle - of another, so the parser saves this and restores it afterwards. *) - State* = record - buf: ^U8; - len, pos, line, lineStart: INT; - tokPos, tokLine, tokLineStart: INT; - prevEnd: INT; (* where the symbol before this one ends *) - tok: Sym; - ival: I64; - rval: F64; - id: INT; - f: INT; (* the file, as Diag knows it *) - end; - -const - Failed*: ERROR = "reported"; (* an error has been shown: the parser returns it *) - MaxIdent* = 63; - MaxStr* = 65536; - NumWords = 43; - NumOps = 28; - words: [NumWords][]U8 = [ - "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"]; - (* sPlus to sBlank *) - ops: [NumOps][]U8 = [ - "+", "-", "*", "/", "=", "#", "<", "<=", ">", ">=", - ":=", ":", ";", ",", ".", "..", "...", - "(", ")", "[", "]", "{", "}", "^", "&", "~", "|", "_"]; - (* the operators that no longer one starts, so that one byte is the symbol *) - alone = "+-*/#;,()[]{}^~"; - PoolChunk = 65536; - -var - tok*: Sym; (* the current symbol *) - ival*: I64; (* sInt, sChar: its value *) - rval*: F64; (* sReal: its value *) - id*: INT; (* sIdent: its name *) - slen*: INT; (* sString: how many bytes *) - sbuf: [MaxStr + 1]U8; (* sString: its bytes, then a zero *) - - (* The parser is skipping what it has read once already, after an - error, so slips in it aren't reported again. *) - skipping*: BOOL; - - (* Whether a byte may be in a name: a letter, a digit or _. A table, - since the loop that reads a name asks it of every byte. *) - nameChar: [256]BOOL; - - (* The symbol a byte is by itself, as + is, or sNull: a table, since - most symbols are of this kind and a match would test them one by one. *) - single: [256]Sym; - - cur: State; (* buf .. f; tok, ival, rval and id live above *) - - (* The name table: every distinct identifier once, found through an - open-addressed hash table. A name's bytes are in a chunk of memory - that is never moved, so that nameOf can hand out a slice of them. *) - chunk: ^U8; (* where names are put; chunkLeft bytes are left *) - chunkLeft: INT; - namePtr: ^NamePtr; - nameLen, nameHash: ^INT; - numNames, nameCap: INT; - table: ^INT; (* name + 1, or 0 for an empty slot *) - tableMask: INT; - -(* Exported variables can't be set from outside, so these do it. *) -proc setSkipping*(yes: BOOL); -begin - skipping := yes; -end; - -(* The bytes of the string just read, without the zero after them *) -proc strBytes*: []U8; -begin - return sbuf[0..slen]; -end; - -(* The string just read and the zero after it, for the code that makes a - chunk of it: an empty string has bytes to point at, though none to index *) -proc strWithZero*: ^U8; -begin - return ADR(sbuf[0]); -end; - -(* Memory, or the end of the compile when there is none *) -proc grab*(size: INT): ^U8; -var p: ^U8; -begin - p := Mem.alloc(Heap.heap, size, 8); - if p = nil then Diag.fatal("out of memory"); end; - return p; -end; - -(* p, which holds used bytes, moved to a block of size bytes *) -proc regrab*(p: ^U8; used, size: INT): ^U8; -var q: ^U8; -begin - q := grab(size); - COPY(q[0..used], p[0..used]); - Mem.free(Heap.heap, p); - return q; -end; - -(* n zeroed words *) -proc words64(n: INT): ^INT; -var p: ^INT; i: INT; -begin - p := ^INT(grab(n * SIZE(INT))); - for i := 0 to n - 1 do p[i] := 0; end; - return p; -end; - -(* Names *) - -proc hash(p: ^U8; n: INT): INT; -var h: U32; i: INT; -begin - h := 2166136261; - for i := 0 to n - 1 do h := (h xor U32(p[i])) * 16777619; end; - return INT(h & 7FFFFFFFH); -end; - -(* A table twice the size, and room for twice the names *) -proc grow; -var i, n, j: INT; ptrs: ^NamePtr; lens, hashes: ^INT; -begin - Mem.free(Heap.heap, ^U8(table)); - tableMask := tableMask * 2 + 1; - table := words64(tableMask + 1); - for n := 0 to numNames - 1 do - i := nameHash[n] & tableMask; - while table[i] # 0 do i := (i + 1) & tableMask; end; - table[i] := n + 1; - end; - j := nameCap * 2; - ptrs := ^NamePtr(grab(j * SIZE(NamePtr))); - lens := ^INT(grab(j * SIZE(INT))); - hashes := ^INT(grab(j * SIZE(INT))); - for n := 0 to numNames - 1 do - ptrs[n] := namePtr[n]; - lens[n] := nameLen[n]; - hashes[n] := nameHash[n]; - end; - Mem.free(Heap.heap, ^U8(namePtr)); - Mem.free(Heap.heap, ^U8(nameLen)); - Mem.free(Heap.heap, ^U8(nameHash)); - namePtr := ptrs; - nameLen := lens; - nameHash := hashes; - nameCap := j; -end; - -(* Whether the n bytes at p and at q are the same *) -proc same(p, q: ^U8; n: INT): BOOL; -var i: INT; -begin - for i := 0 to n - 1 do - if p[i] # q[i] then return false; end; - end; - return true; -end; - -(* The number of the name of the n bytes at p; a new name gets the next *) -proc intern*(p: ^U8; n: INT): INT; -var h, i, k: INT; -begin - h := hash(p, n); - i := h & tableMask; - while table[i] # 0 do - k := table[i] - 1; - if (nameHash[k] = h) and (nameLen[k] = n) and same(namePtr[k], p, n) then - return k; - end; - i := (i + 1) & tableMask; - end; - if n > chunkLeft then - chunk := grab(PoolChunk); - chunkLeft := PoolChunk; - end; - COPY(chunk[0..n], p[0..n]); - k := numNames; - namePtr[k] := chunk; - nameLen[k] := n; - nameHash[k] := h; - chunk := chunk + n; - chunkLeft := chunkLeft - n; - INC(numNames); - table[i] := k + 1; - if numNames * 2 > tableMask then grow; end; - return k; -end; - -(* The name n, which stays as it is *) -proc nameOf*(n: INT): []U8; -begin - return namePtr[n][0..nameLen[n]]; -end; - -(* Errors *) - -(* The current symbol *) -proc tokPos*: Diag.Pos; -begin - return {f: cur.f, a: cur.tokPos, b: cur.pos}; -end; - -(* The place just after the symbol before the current one, where a - missing symbol belongs *) -proc afterPrev*: Diag.Pos; -begin - return {f: cur.f, a: cur.prevEnd, 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 *) -proc missingPos*: Diag.Pos; -var i: INT; p: Diag.Pos; -begin - p := tokPos(); - for i := cur.prevEnd to cur.tokPos - 1 do - if cur.buf[i] = '\n' then p := afterPrev(); end; - end; - return p; -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 *) -proc spanFrom*(p: Diag.Pos): Diag.Pos; -begin - p.b := cur.prevEnd; - return p; -end; - -proc curLine*: INT; -begin - return 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. *) -proc lineCol*(a: INT): (INT, INT); -var i, line, start, col: INT; -begin - line := cur.tokLine; - start := cur.tokLineStart; - while a < start do - DEC(line); - DEC(start); - while (start > 0) and (cur.buf[start - 1] # '\n') do DEC(start); end; - end; - col := 1; - for i := start to a - 1 do - if (cur.buf[i] & 0C0H) # 80H then INC(col); end; - end; - return line, col; -end; - -proc curCol*: INT; -var col: INT; -begin - _, col := lineCol(cur.tokPos); - return col; -end; - -(* An error at p, shown: the parser returns Failed, which try passes up - to where it goes on. *) -proc markAt*(p: Diag.Pos; msg: []U8): ERROR; -begin - Diag.error(p, msg); - return Failed; -end; - -proc mark*(msg: []U8): ERROR; -begin - return markAt(tokPos(), msg); -end; - -(* markAt, with a line of help after the message. *) -proc markHelp*(p: Diag.Pos; msg, hint: []U8): ERROR; -begin - Diag.error(p, msg); - Diag.help(hint); - return Failed; -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. *) -proc markBytes(a, b: INT; msg: []U8); -begin - Diag.setQuiet(false); - Diag.error({f: cur.f, a: a, b: b}, msg); - Diag.finish; -end; - -proc lexError(msg: []U8); -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. *) -proc slip(n: INT; t: Sym; msg: []U8); -begin - if not skipping then Diag.error({f: cur.f, a: cur.pos, b: cur.pos + n}, msg); end; - INC(cur.pos, n); - tok := t; -end; - -(* How an operator or reserved word is written, quoted, for messages. *) -proc symText*(s: Sym): []U8; -begin - if (s >= sPlus) and (s <= sBlank) then - return Diag.say("\"{}\"", [Fmt.str(ops[INT(s) - INT(sPlus)])]); - end; - return Diag.say("\"{}\"", [Fmt.str(words[INT(s) - INT(sAnd)])]); -end; - -(* The current symbol, for "expected ..., found ...": a name as it is, - a literal by its kind, an operator or reserved word quoted. *) -proc found*: []U8; -begin - match tok of - | sIdent: return nameOf(id); - | sInt: return "a number"; - | sReal: return "a number"; - | sChar: return "a character"; - | sString: return "a string"; - | sEof: return "the end of the file"; - | else: return 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. *) -proc atLineStart*: BOOL; -begin - return cur.tokPos = cur.tokLineStart; -end; - -(* The column the current symbol's line is indented to *) -proc indent*: INT; -var i: INT; -begin - i := cur.tokLineStart; - while (cur.buf[i] = ' ') or (cur.buf[i] = '\t') do INC(i); end; - return i - cur.tokLineStart + 1; -end; - -(* Files *) - -(* Name n is a reserved word *) -proc reserved*(n: INT): BOOL; -begin - return n < NumWords; -end; - -(* Reads the file at path to scan it; "" if it can, else why not *) -proc open*(path: []U8): []U8; -var fd, n, got, r, err: INT; info: Sys.Info; -begin - info, err := Sys.info(path); - if err = -2 then return "there is no such file"; end; - if err = -13 then return "permission denied"; end; - if err < 0 then return "it can't be opened"; end; - if not info.file then return "it isn't a file"; end; - fd := Sys.openRead(path); - if fd = -2 then return "there is no such file"; end; - if fd = -13 then return "permission denied"; end; - if fd < 0 then return "it can't be opened"; end; - n := INT(info.size); - cur.buf := grab(n + 1); - got := 0; - while got < n do - r := Sys.read(fd, cur.buf[got..n]); - if r <= 0 then Diag.fatal(Diag.say("can't read {}", [Fmt.str(path)])); end; - got := got + r; - end; - Sys.close(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 := Diag.addFile(path, cur.buf, n); - return ""; -end; - -proc saveScan*(var st: State); -begin - st := cur; - st.tok := tok; - st.ival := ival; - st.rval := rval; - st.id := id; -end; - -proc restoreScan*(st: State); -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. *) -proc utf8(var pos: INT): INT; -var b0, b1, n, i, cp: INT; lo, hi: INT; -begin - b0 := INT(cur.buf[pos]); - lo := 80H; - hi := 0BFH; - n := 0; - cp := 0; - match b0 of - | 0C2H..0DFH: n := 1; cp := b0 & 1FH; - | 0E0H: n := 2; lo := 0A0H; - | 0E1H..0ECH, 0EEH, 0EFH: n := 2; cp := b0 & 0FH; - | 0EDH: n := 2; cp := 0DH; hi := 9FH; (* no surrogates *) - | 0F0H: n := 3; lo := 90H; - | 0F1H..0F3H: n := 3; cp := b0 & 7; - | 0F4H: n := 3; cp := 4; hi := 8FH; (* up to 10FFFFH *) - | else: - cur.tokPos := pos; - lexError("invalid UTF-8"); - end; - for i := 1 to n do - b1 := INT(cur.buf[pos + i]); - if (b1 < lo) or (b1 > hi) or (pos + i >= cur.len) then - cur.tokPos := pos; - lexError("bad UTF-8"); - end; - cp := cp shl 6 | (b1 & 3FH); - lo := 80H; - hi := 0BFH; - end; - pos := pos + n + 1; - return cp; -end; - -proc put(b: INT); -begin - if slen >= MaxStr then - lexError(Diag.say("a string holds at most {} bytes", [Fmt.int(MaxStr)])); - end; - sbuf[slen] := U8(b); - INC(slen); -end; - -proc putUtf8(cp: INT); -begin - if cp < 80H then - put(cp); - elsif cp < 800H then - put(0C0H | cp shr 6); put(80H | cp & 3FH); - elsif cp < 10000H then - put(0E0H | cp shr 12); put(80H | cp shr 6 & 3FH); put(80H | cp & 3FH); - else - put(0F0H | cp shr 18); put(80H | cp shr 12 & 3FH); - put(80H | cp shr 6 & 3FH); put(80H | cp & 3FH); - end; -end; - -proc isDigit(c: U8): BOOL; -begin - return (c >= '0') and (c <= '9'); -end; - -proc isLetter(c: U8): BOOL; -begin - return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z') or (c = '_'); -end; - -proc hexVal(c: U8): INT; -begin - if isDigit(c) then return INT(c) - '0'; - elsif (c >= 'A') and (c <= 'F') then return INT(c) - 'A' + 10; - elsif (c >= 'a') and (c <= 'f') then return INT(c) - 'a' + 10; - end; - return -1; -end; - -(* The text of the file from byte a up to but not including b *) -proc text(a, b: INT): []U8; -begin - return Diag.source({f: cur.f, a: a, b: b}); -end; - -(* One character of a character or string literal, at buf[pos]: its code - point, or for \xHH, minus one minus the byte. *) -proc litChar(inString: BOOL): INT; -var c: U8; v, d, n, esc, digits: INT; -begin - c := cur.buf[cur.pos]; - esc := cur.pos; - v := 0; - if c = '\\' then - INC(cur.pos); - c := cur.buf[cur.pos]; - INC(cur.pos); - match c of - | 'n': v := 10; - | 't': v := 9; - | 'r': v := 13; - | '0': v := 0; - | '\\', '\'', '"': v := INT(c); - | 'x': - if not inString then markBytes(esc, cur.pos, "\\x is only for strings"); end; - 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"); end; - INC(cur.pos, 2); - v := -1 - (d * 16 + n); - | 'u': - if cur.buf[cur.pos] # '{' then markBytes(esc, cur.pos, "expected \"{\" after \\u"); end; - INC(cur.pos); - digits := cur.pos; - v := 0; - n := 0; - while hexVal(cur.buf[cur.pos]) >= 0 do - 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; - end; - if (n = 0) or (cur.buf[cur.pos] # '}') then - markBytes(esc, cur.pos, "expected hex digits and \"}\" after \\u{"); - end; - INC(cur.pos); - if (v > 10FFFFH) or (v >= 0D800H) and (v <= 0DFFFH) then - markBytes(esc, cur.pos, Diag.say("{} isn't a code point", [Fmt.str(text(digits, cur.pos - 1))])); - end; - | else: - markBytes(esc, cur.pos, Diag.say("unknown escape \\{}", [Fmt.char(c)])); - end; - elsif c >= 80H then - v := utf8(cur.pos); - elsif (c < ' ') or (c = 127) then - if inString then lexError("string not closed"); else lexError("character not closed"); end; - else - v := INT(c); - INC(cur.pos); - end; - return v; -end; - -(* Symbols *) - -proc comment; -var depth, open: INT; c: U8; -begin - depth := 1; - open := cur.pos; - INC(cur.pos, 2); - repeat - c := cur.buf[cur.pos]; - if c = 0 then - if cur.pos >= cur.len then markBytes(open, open + 2, "comment not closed"); end; - INC(cur.pos); - elsif (c = '(') and (cur.buf[cur.pos + 1] = '*') then - INC(depth); - INC(cur.pos, 2); - elsif (c = '*') and (cur.buf[cur.pos + 1] = ')') then - DEC(depth); - INC(cur.pos, 2); - elsif c = '\n' then - INC(cur.pos); - INC(cur.line); - cur.lineStart := cur.pos; - elsif c >= 80H then - _ := utf8(cur.pos); - else - INC(cur.pos); - end; - 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 reader 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 - Big = record - n: INT; (* words in use; 0 is zero *) - w: [96]U32; (* least significant first *) - end; -(* 96 words, 3072 bits, are plenty: a string 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 *) -proc bigMul(var a: Big; m, add: U32); -var i: INT; c: U64; -begin - c := U64(add); - for i := 0 to a.n - 1 do - c := U64(a.w[i]) * U64(m) + c; - a.w[i] := U32(c); - c := c shr 32; - end; - if c # 0 then - a.w[a.n] := U32(c); - INC(a.n); - end; -end; - -proc bigShl(var a: Big; k: INT); -var i, ws, bits: INT; -begin - if a.n = 0 then return; end; - ws := k div 32; - bits := k mod 32; - a.w[a.n + ws] := 0; - for i := a.n - 1 to 0 by -1 do - if bits > 0 then a.w[i + ws + 1] := a.w[i + ws + 1] | (a.w[i] shr (32 - bits)); end; - a.w[i + ws] := a.w[i] shl bits; - end; - for i := 0 to ws - 1 do a.w[i] := 0; end; - INC(a.n, ws + 1); - while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end; -end; - -proc bigShr1(var a: Big); -var i: INT; -begin - for i := 0 to a.n - 1 do - a.w[i] := a.w[i] shr 1; - if i + 1 < a.n then a.w[i] := a.w[i] | (a.w[i + 1] shl 31); end; - end; - while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end; -end; - -(* -1, 0 or 1 as a is below, equal to or above b *) -proc bigCmp(a, b: Big): INT; -var i: INT; -begin - if a.n # b.n then - if a.n > b.n then return 1; end; - return -1; - end; - for i := a.n - 1 to 0 by -1 do - if a.w[i] # b.w[i] then - if a.w[i] > b.w[i] then return 1; end; - return -1; - end; - end; - return 0; -end; - -(* a := a - b, b not above a *) -proc bigSub(var a: Big; b: Big); -var i: INT; d: I64; -begin - d := 0; - for i := 0 to a.n - 1 do - d := d + I64(a.w[i]); - if i < b.n then d := d - I64(b.w[i]); end; - a.w[i] := U32(d); - if d < 0 then d := -1; else d := 0; end; (* a borrow *) - end; - while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end; -end; - -proc bigBits(a: Big): INT; -var t: U32; bits: INT; -begin - if a.n = 0 then return 0; end; - bits := (a.n - 1) * 32; - t := a.w[a.n - 1]; - while t # 0 do - INC(bits); - t := t shr 1; - end; - return bits; -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. *) -proc readReal(s: []U8): (F64, BOOL); -var - num, den, d: Big; i, digits, e, ex: INT; neg, half, sticky: BOOL; - q, b: U64; x: F64; bits: ^F64; -begin - num.n := 0; - den.n := 1; - den.w[0] := 1; - digits := 0; - e := 0; - i := 0; - while (i < LEN(s)) and (s[i] # 'E') do - if s[i] = '.' then - e := 1; - else - bigMul(num, 10, U32(INT(s[i]) - '0')); - if num.n > 0 then INC(digits); end; (* counted from the first that isn't 0 *) - if e > 0 then INC(e); end; - end; - INC(i); - end; - if e > 0 then e := 1 - e; end; (* minus the digits after the point *) - ex := 0; - neg := false; - if i < LEN(s) then - INC(i); - neg := s[i] = '-'; - if (s[i] = '+') or (s[i] = '-') then INC(i); end; - while i < LEN(s) do - if ex < 100000 then ex := ex * 10 + INT(s[i]) - '0'; end; - INC(i); - end; - end; - if neg then ex := -ex; end; - INC(e, ex); - x := 0.0; - if num.n = 0 then return x, true; end; - if digits + e > 310 then return x, false; end; (* 10^310 is past every F64 *) - if digits + e < -330 then return x, true; end; (* and 10^-330 below half the least *) - for i := 1 to e do bigMul(num, 10, 0); end; - for i := 1 to -e do bigMul(den, 10, 0); end; - (* 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; end; - if e < 0 then bigShl(num, -e); else bigShl(den, e); end; - (* q, its whole part, by long division; num is left the remainder *) - d := den; - bigShl(d, 53); - q := 0; - for i := 53 to 0 by -1 do - if bigCmp(num, d) >= 0 then - bigSub(num, d); - q := q | (U64(1) shl i); - end; - bigShr1(d); - end; - if q >= U64(1) shl 53 then (* a bit too many: it rounds *) - half := (q & 1) # 0; - sticky := num.n > 0; - q := q shr 1; - INC(e); - else (* 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 ((q & 1) # 0)) then - INC(q); - if q = U64(1) shl 53 then - q := q shr 1; - INC(e); - end; - end; - if e > 971 then return x, false; end; - if q >= U64(1) shl 52 then - b := U64(e + 1075) shl 52 | (q & (U64(1) shl 52 - 1)); - else - b := q; (* below the least normal, e is -1074 *) - end; - bits := ^F64(ADR(b)); - return bits^, true; -end; - -proc number; -var start, i, d: INT; allDec, ok: BOOL; v: U64; -begin - start := cur.pos; - allDec := true; - while isDigit(cur.buf[cur.pos]) or (cur.buf[cur.pos] >= 'A') and (cur.buf[cur.pos] <= 'F') do - if cur.buf[cur.pos] > '9' then allDec := false; end; - INC(cur.pos); - end; - if cur.buf[cur.pos] = 'H' then - v := 0; - for i := start to cur.pos - 1 do - if v shr 60 # 0 then lexError(Diag.say("{} is too big for U64", [Fmt.str(text(start, cur.pos))])); end; - v := v * 16 + U64(hexVal(cur.buf[i])); - end; - INC(cur.pos); - tok := sInt; - ival := I64(v); (* 16 digits are the bits of a 64-bit word *) - elsif (cur.buf[cur.pos] = '.') and isDigit(cur.buf[cur.pos + 1]) then - if not allDec then lexError("a decimal number has only the digits 0 to 9"); end; - INC(cur.pos); - while isDigit(cur.buf[cur.pos]) do INC(cur.pos); end; - if cur.buf[cur.pos] = 'E' then - INC(cur.pos); - if (cur.buf[cur.pos] = '+') or (cur.buf[cur.pos] = '-') then INC(cur.pos); end; - if not isDigit(cur.buf[cur.pos]) then lexError("expected a digit in the exponent"); end; - while isDigit(cur.buf[cur.pos]) do INC(cur.pos); end; - end; - if cur.pos - start > 255 then lexError("a number has at most 255 characters"); end; - rval, ok := readReal(cur.buf[start..cur.pos]); - if not ok then lexError(Diag.say("{} is out of the range of F64", [Fmt.str(text(start, cur.pos))])); end; - tok := sReal; - else - if not allDec then lexError("a hex number ends with H"); end; - v := 0; - for i := start to cur.pos - 1 do - d := INT(cur.buf[i]) - '0'; - if v > (U64(9223372036854775807) - U64(d)) div 10 then - lexError(Diag.say("{} is too big for I64", [Fmt.str(text(start, cur.pos))])); - end; - v := v * 10 + U64(d); - end; - tok := sInt; - ival := I64(v); - end; - if nameChar[cur.buf[cur.pos]] then - lexError("a name can't start with a digit"); - end; -end; - -(* Reads the next symbol *) -proc next*; -var c: U8; start, h, v, i: INT; -begin - cur.prevEnd := cur.pos; - repeat - c := cur.buf[cur.pos]; - while (c = ' ') or (c = '\t') or (c = '\r') or (c = '\n') do - if c = '\n' then - 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 - comment; - c := ' '; - end; - until c # ' '; - cur.tokPos := cur.pos; - cur.tokLine := cur.line; - cur.tokLineStart := cur.lineStart; - if single[c] # sNull then - INC(cur.pos); - tok := single[c]; - return; - end; - match c of - | 'A'..'Z', 'a'..'z', '_': - start := cur.pos; - repeat INC(cur.pos); until not nameChar[cur.buf[cur.pos]]; - if cur.pos - start > MaxIdent then - lexError(Diag.say("a name has at most {} characters", [Fmt.int(MaxIdent)])); - end; - h := intern(cur.buf + start, cur.pos - start); - if (cur.pos - start = 1) and (c = '_') then - tok := sBlank; - elsif h < NumWords then - tok := Sym(INT(sAnd) + h); - else - tok := sIdent; - id := h; - end; - | '0'..'9': number; - | '\'': - INC(cur.pos); - if cur.buf[cur.pos] = '\'' then lexError("empty character"); end; - v := litChar(false); - if cur.buf[cur.pos] # '\'' then - (* 'ab': several characters, as some languages write a string *) - i := cur.pos; - while (cur.buf[i] # '\'') and (cur.buf[i] # '\n') and (cur.buf[i] # 0) do INC(i); end; - if cur.buf[i] = '\'' then - markBytes(cur.tokPos, i + 1, - Diag.say("a character is one character: the string is \"{}\"", [Fmt.str(text(cur.tokPos + 1, i))])); - else - lexError("character not closed"); - end; - end; - INC(cur.pos); - tok := sChar; - ival := I64(v); - | '"': - INC(cur.pos); - slen := 0; - while cur.buf[cur.pos] # '"' do - v := litChar(true); - if v < 0 then put(-1 - v); else putUtf8(v); end; - end; - INC(cur.pos); - sbuf[slen] := 0; - tok := sString; - | '=': - if cur.buf[cur.pos + 1] = '=' then - slip(2, sEql, "comparing is written =, not =="); - else - INC(cur.pos); - tok := sEql; - end; - | '&': - if cur.buf[cur.pos + 1] = '&' then - slip(2, sAnd, "\"and\" is written and, not &&"); - else - INC(cur.pos); - tok := sAmp; - end; - | '<': - INC(cur.pos); - if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sLeq; else tok := sLss; end; - | '>': - INC(cur.pos); - if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sGeq; else tok := sGtr; end; - | ':': - INC(cur.pos); - if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sBecomes; else tok := sColon; end; - | '.': - INC(cur.pos); - if cur.buf[cur.pos] = '.' then - INC(cur.pos); - if cur.buf[cur.pos] = '.' then INC(cur.pos); tok := sEllipsis; else tok := sUpto; end; - else - tok := sPeriod; - end; - | '|': - if cur.buf[cur.pos + 1] = '|' then - slip(2, sOr, "\"or\" is written or, not ||"); - else - INC(cur.pos); - tok := sBar; - 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 !"); - end; - | 0: - if cur.pos < cur.len then markBytes(cur.pos, cur.pos + 1, "NUL byte in the text"); end; - tok := sEof; - | else: - if c >= 80H then lexError("only ASCII outside strings, characters and comments"); end; - markBytes(cur.pos, cur.pos + 1, Diag.say("unexpected character \"{}\"", [Fmt.char(c)])); - end; -end; - -var i: INT; - -begin - for i := 0 to 255 do nameChar[i] := isLetter(U8(i)) or isDigit(U8(i)); end; - for i := 0 to NumOps - 1 do - if (LEN(ops[i]) = 1) and (Str.find(alone, ops[i]) >= 0) then - single[ops[i][0]] := Sym(INT(sPlus) + i); - end; - end; - chunkLeft := 0; - nameCap := 1 shl 12; - namePtr := ^NamePtr(grab(nameCap * SIZE(NamePtr))); - nameLen := ^INT(grab(nameCap * SIZE(INT))); - nameHash := ^INT(grab(nameCap * SIZE(INT))); - tableMask := 2 * nameCap - 1; - table := words64(tableMask + 1); - for i := 0 to NumWords - 1 do _ := intern(ADR(words[i][0]), LEN(words[i])); end; -end Scan. diff --git a/self/Sym.raz b/self/Sym.raz deleted file mode 100644 index b57cd96..0000000 --- a/self/Sym.raz +++ /dev/null @@ -1,684 +0,0 @@ -(* Sym: types, objects and scopes. - - Every name the program declares becomes an object (Obj): a constant, - type, variable, procedure, module, record field, variant case or - built-in. Every type is a Type. 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; Diag, for positions. - Leaves out: code. Where a variable lives is decided here (frame - offsets, chunk numbers), but nothing is emitted. - - Exported variables can't be set from outside, so setCurModule is - how the parser says which module it is in. A name that holds a - reserved word of raz is spelled otherwise: a record's `module` is - its `home`, an object's `link` its `chain`. *) -module Sym; -import Mem, Heap, Buf, Fmt, Diag, Scan; - -type - Form* = (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. *) - - Class* = (oConst, oType, oVar, oProc, oModule, oField, oCase, oBuiltin); - - Type* = record - form*: Form; - size*, align*: I64; - signed*: BOOL; (* fInt *) - vol*: BOOL; (* fPtr: ^VOLATILE *) - packd*: BOOL; (* fRecord *) - variadic*: BOOL; (* fProc: ends in ... *) - tuple*: BOOL; (* fRecord: the results of a procedure that has several *) - base*: ^Type; (* fPtr, fArray, fSlice: what it holds; fProc: result *) - len*: I64; (* fArray: elements; fProc: parameters; fVariant: cases; a tuple: results *) - fields*: ^Obj; (* fRecord: fields; fVariant: cases; fProc: parameters *) - scope*: INT; (* fRecord: the scope of its fields *) - fwd*: INT; (* fPtr whose base isn't declared yet: its name, else -1 *) - obj*: ^Obj; (* the declaration that names it, or nil *) - home*: ^Module; (* the module that built it *) - end; - - Obj* = record - cls*: Class; - name*: INT; - exported*: BOOL; - typ*: ^Type; - next*: ^Obj; (* the next in its list: scope, fields, parameters *) - scope*: INT; (* where it is declared *) - pos*: Diag.Pos; (* where its name is declared, for messages *) - val*: I64; (* oConst: value; oBuiltin: which; oCase: tag; - oField: offset; oVar: frame offset *) - chunk*: INT; (* global oVar, oProc, string oConst: its chunk *) - lev*: INT; (* oVar: 0 for a module variable, 1 for a local *) - ind*: BOOL; (* oVar: the frame slot holds the variable's address *) - off*: I64; (* oVar with ind: added to that address *) - isVar*: BOOL; (* a var parameter *) - param*: BOOL; (* oVar: a parameter *) - used*: BOOL; (* named somewhere but in its own body *) - read*: BOOL; (* oVar: named other than as what := assigns *) - fwd*: BOOL; (* oProc: declared forward, no body yet *) - isCode*: BOOL; (* oProc: a code procedure *) - openEnd*: BOOL; (* oProc: has results, and may reach its end *) - reg*: INT; (* oVar: the register it lives in, or 0 if in memory; - for a slice, the one its pointer is in *) - reg2*: INT; (* oVar: a slice in registers: the one its length is in *) - ext*: BOOL; (* oProc, oVar: C's, reached through its chunk, which - holds its address *) - fields*: ^Obj; (* oCase: its fields *) - home*: ^Module; (* oModule: the module; others: where declared *) - chain*: ^Obj; (* 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. *) - Args* = record - n*: INT; - t*: [8]^Type; - o*: [8]^Obj; - pos*: [8]Diag.Pos; (* where each argument is, for messages *) - at*: Diag.Pos; (* where the import is *) - end; - - Import* = record - home*: ^Module; - next*: ^Import; - end; - - (* A library a module links, by its name, as interned *) - Lib* = record - name*: INT; - next*: ^Lib; - end; - - Module* = record - name*: INT; - sname*: INT; (* the name of its symbols: List(I64) for an instance *) - args*: Args; - scope*: INT; - path*: []U8; - first*, last*: ^Obj; (* its top-level declarations, in order *) - locals*, lastLocal*: ^Obj; (* its procedures' declarations, in order *) - imports*: ^Import; - body*: INT; (* the chunk of its body, or -1 *) - done*: BOOL; (* compiled to the end *) - checkOnly*: BOOL; (* read only to check another file's interface *) - used*: BOOL; (* imported, through others, by the main module *) - usesC*: BOOL; (* has an extern, or links a library *) - linkStatic*: BOOL; (* says link static *) - libs*: ^Lib; (* the libraries it links *) - next*: ^Module; (* 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*: ^Type; - tInt*, tUInt*: ^Type; (* INT and UINT, as big as an address: 8 bytes here *) - tBool*, tF32*, tReal*, tRConst*, tError*, tConst*, tNil*, tStr*, tNone*, tPtrU8*, tBytes*: ^Type; - tPoison*: ^Type; (* of a name reported as not declared *) - curModule*: ^Module; - - scopes: [MaxDepth]INT; - depth: INT; - nextScope: INT; - hashTab: ^^Obj; - hashMask, hashCount: INT; - -proc setCurModule*(m: ^Module); -begin - curModule := m; -end; - -proc newType*(form: Form; size, align: I64): ^Type; -var t: ^Type; -begin - NEW(t, Heap.heap); - if t = nil then Diag.fatal("out of memory"); end; - t^.form := form; - t^.size := size; - t^.align := align; - t^.fwd := -1; - t^.home := curModule; - return t; -end; - -proc newObj*(cls: Class; name: INT; typ: ^Type): ^Obj; -var o: ^Obj; -begin - NEW(o, Heap.heap); - if o = nil then Diag.fatal("out of memory"); end; - o^.cls := cls; - o^.name := name; - o^.typ := typ; - o^.chunk := -1; - o^.home := curModule; - o^.pos := Scan.tokPos(); - return o; -end; - -(* Scopes *) - -proc newScope*: INT; -begin - INC(nextScope); - return nextScope; -end; - -proc openScope*(s: INT): ERROR; -begin - if depth = MaxDepth then - return Scan.mark(Diag.say("scopes nested more than {} deep", [Fmt.int(MaxDepth)])); - end; - scopes[depth] := s; - INC(depth); - return nil; -end; - -proc closeScope*; -begin - DEC(depth); -end; - -(* An imported module is compiled in the middle of another, and must - see only the universe and itself. The scopes open are kept in saved, - and their number is the result. *) -proc saveScopes*(saved: []INT): INT; -var i, d: INT; -begin - d := depth; - for i := 0 to depth - 1 do saved[i] := scopes[i]; end; - depth := 1; - return d; -end; - -proc restoreScopes*(d: INT; saved: []INT); -var i: INT; -begin - depth := d; - for i := 0 to depth - 1 do scopes[i] := saved[i]; end; -end; - -proc scopeDepth*: INT; -begin - return depth; -end; - -(* Closes the scopes opened since there were d, after an error *) -proc cutScopes*(d: INT); -begin - depth := d; -end; - -proc topScope*: INT; -begin - return 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. *) -proc slot(s, name: INT): INT; -begin - return INT(((U32(s & 0FFFFFFFFH) * 2654435761) xor (U32(name & 0FFFFFFFFH) * 40503)) & U32(hashMask)); -end; - -(* A table of n slots, all empty *) -proc emptyTable(n: INT): ^^Obj; -var t: ^^Obj; i: INT; -begin - t := ^^Obj(Scan.grab(n * SIZE(^Obj))); - for i := 0 to n - 1 do t[i] := nil; end; - return t; -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. *) -proc rehash; -var old: ^^Obj; n, i, j: INT; -begin - old := hashTab; - n := hashMask + 1; - hashMask := n * 2 - 1; - hashTab := emptyTable(n * 2); - for i := 0 to n - 1 do - if old[i] # nil then - j := slot(old[i]^.scope, old[i]^.name); - while hashTab[j] # nil do j := (j + 1) & hashMask; end; - hashTab[j] := old[i]; - end; - end; - Mem.free(Heap.heap, ^U8(old)); -end; - -proc insert*(obj: ^Obj; s: INT): ERROR; -var i: INT; o: ^Obj; -begin - i := slot(s, obj^.name); - o := hashTab[i]; - while o # nil do - if (o^.scope = s) and (o^.name = obj^.name) then - Diag.error(obj^.pos, Diag.say("{} is declared twice", [Fmt.str(Scan.nameOf(obj^.name))])); - Diag.note(o^.pos, "the first one is here"); - return Scan.Failed; - end; - i := (i + 1) & hashMask; - o := hashTab[i]; - end; - obj^.scope := s; - hashTab[i] := obj; - INC(hashCount); - if hashCount * 2 > hashMask then rehash; end; - return nil; -end; - -proc find*(s, name: INT): ^Obj; -var i: INT; o: ^Obj; -begin - i := slot(s, name); - o := hashTab[i]; - while o # nil do - if (o^.scope = s) and (o^.name = name) then return o; end; - i := (i + 1) & hashMask; - o := hashTab[i]; - end; - return nil; -end; - -proc lookup*(name: INT): ^Obj; -var i: INT; o: ^Obj; -begin - for i := depth - 1 to 0 by -1 do - o := find(scopes[i], name); - if o # nil then return o; end; - end; - return nil; -end; - -proc min(a, b: INT): INT; -begin - if a < b then return a; end; - return b; -end; - -(* c, in capitals if it is a letter *) -proc up(c: U8): U8; -begin - if (c >= 97) and (c <= 122) then return c - 32; end; - return c; -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. *) -proc distance(a, b: []U8): INT; -var d: [Scan.MaxIdent + 2][Scan.MaxIdent + 2]INT; i, j, c: INT; -begin - for i := 0 to LEN(a) do d[i][0] := i; end; - for j := 0 to LEN(b) do d[0][j] := j; end; - for i := 1 to LEN(a) do - for j := 1 to LEN(b) do - c := 1; - if up(a[i - 1]) = up(b[j - 1]) then c := 0; end; - 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 (up(a[i - 1]) = up(b[j - 2])) - and (up(a[i - 2]) = up(b[j - 1])) then - d[i][j] := min(d[i][j], d[i - 2][j - 2] + 1); - end; - end; - end; - return d[LEN(a)][LEN(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. *) -proc closest*(name, s: INT): ^Obj; -var i, j, d, best: INT; o, found: ^Obj; n: []U8; reach: BOOL; -begin - n := Scan.nameOf(name); - best := LEN(n) div 3 + 1; - found := nil; - for i := 0 to hashMask do - o := hashTab[i]; - if (o = nil) or (o^.name = name) or (o^.name < 0) or (o^.typ = tPoison) then - reach := false; - elsif s >= 0 then - reach := (o^.scope = s) and (o^.exported or (o^.home = curModule)); - else - reach := false; - for j := 0 to depth - 1 do reach := reach or (o^.scope = scopes[j]); end; - end; - if reach then - d := distance(n, Scan.nameOf(o^.name)); - if d < best then best := d; found := o; end; - end; - end; - return found; -end; - -(* Types *) - -proc alignUp*(x, a: I64): I64; -begin - return (x + a - 1) div a * a; -end; - -proc isInt*(t: ^Type): BOOL; -begin - return t^.form in {fInt, fConst}; -end; - -proc isScalar*(t: ^Type): BOOL; -begin - return t^.form in {fBool, fInt, fReal, fConst, fNil, fPtr, fProc, fEnum, fSet, fError}; -end; - -proc isAggregate*(t: ^Type): BOOL; -begin - return t^.form in {fArray, fSlice, fRecord, fVariant}; -end; - -(* Whether a result field f is a single value of at most a word, not a real *) -proc oneWord(f: ^Obj): BOOL; -begin - return isScalar(f^.typ) and (f^.typ^.form # fReal) and (f^.typ^.size <= 8); -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. *) -proc inTwoRegs*(t: ^Type): BOOL; -begin - if t^.form = fSlice then return true; end; - return 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. *) -proc behindPointer*(t: ^Type): BOOL; -begin - return isAggregate(t) and not inTwoRegs(t); -end; - -proc fits*(v: I64; t: ^Type): BOOL; -begin - if t^.form # fInt then return t^.form = fConst; end; - match t^.size of - | 1: - if t^.signed then return (v >= -128) and (v <= 127); end; - return (v >= 0) and (v <= 255); - | 2: - if t^.signed then return (v >= -32768) and (v <= 32767); end; - return (v >= 0) and (v <= 65535); - | 4: - if t^.signed then return (v >= -2147483648) and (v <= 2147483647); end; - return (v >= 0) and (v <= 4294967295); - | else: return t^.signed or (v >= 0); - end; -end; - -proc same*(a, b: ^Type): BOOL; forward; - -(* Whether two procedure types, or two tuples, are alike: the same - results and parameters, in the same modes *) -proc alikeShape(a, b: ^Type): BOOL; -var p, q: ^Obj; -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 return false; end; - if (a^.len # b^.len) or (a^.variadic # b^.variadic) then return false; end; - if (a^.base = nil) # (b^.base = nil) then return false; end; - if (a^.base # nil) and not same(a^.base, b^.base) then return false; end; - p := a^.fields; q := b^.fields; - while p # nil do - if (p^.isVar # q^.isVar) or not same(p^.typ, q^.typ) then return false; end; - p := p^.next; q := q^.next; - end; - return true; -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. *) -proc alike(a, b: ^Type): BOOL; -begin - if a = b then return true; end; - if a^.form # b^.form then return false; end; - match a^.form of - | fPtr: return (a^.vol = b^.vol) and same(a^.base, b^.base); - | fArray: return (a^.len = b^.len) and same(a^.base, b^.base); - | fSlice: return same(a^.base, b^.base); - | fSet: return same(a^.base, b^.base); - | fProc: return alikeShape(a, b); - | fRecord: return alikeShape(a, b); - | else: return false; - end; -end; - -proc same*(a, b: ^Type): BOOL; -begin - if a = b then return true; end; - if (a = nil) or (b = nil) then return false; end; - if (a^.obj # nil) and (b^.obj # nil) then return false; end; - return alike(a, b); -end; - -(* What a type is called, added to b: the names a program gives it, else - what it is made of *) -proc typeText(b: ^Buf.Buf; t: ^Type); -var f: ^Obj; -begin - if t = nil then Buf.str(b, "nothing"); return; end; - if t^.obj # nil then - if (t^.obj^.home # nil) and (t^.obj^.home # curModule) then - Buf.str(b, Scan.nameOf(t^.obj^.home^.sname)); - Buf.str(b, "."); - end; - Buf.str(b, Scan.nameOf(t^.obj^.name)); - return; - end; - match t^.form of - | fConst: Buf.str(b, "an integer constant"); - | fReal: Buf.str(b, "a real constant"); - | fNil: Buf.str(b, "nil"); - | fStr: Buf.str(b, "a string"); - | fPtr: - if t^.vol then Buf.str(b, "^VOLATILE "); else Buf.str(b, "^"); end; - typeText(b, t^.base); - | fArray: - Fmt.write(b, "[{}]", [Fmt.int(t^.len)]); - typeText(b, t^.base); - | fSlice: - Buf.str(b, "[]"); - typeText(b, t^.base); - | fRecord: - if not t^.tuple then - Buf.str(b, "record"); - else - Buf.str(b, "("); - f := t^.fields; - while f # nil do - typeText(b, f^.typ); - f := f^.next; - if f # nil then Buf.str(b, ", "); end; - end; - Buf.str(b, ")"); - end; - | fVariant: Buf.str(b, "variant"); - | fProc: - Buf.str(b, "proc("); - f := t^.fields; - while f # nil do - if f^.isVar then Buf.str(b, "var "); end; - typeText(b, f^.typ); - f := f^.next; - if f # nil then Buf.str(b, ", "); end; - end; - Buf.str(b, ")"); - if t^.base # nil then - Buf.str(b, ": "); - typeText(b, t^.base); - end; - | else: Buf.str(b, "?"); - end; -end; - -(* A name for t, kept for good, as every message is *) -proc typeName*(t: ^Type): []U8; -var b: ^Buf.Buf; -begin - b := ^Buf.Buf(Scan.grab(SIZE(Buf.Buf))); - Buf.init(b, Heap.heap); - typeText(b, t); - return Buf.bytes(b); -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. *) -proc mix(var h: U64; v: I64); -begin - h := (h xor U64(v)) * 1099511628211; (* FNV-1a's 64-bit prime *) -end; - -proc bit(f: BOOL): INT; -begin - if f then return 1; end; - return 0; -end; - -proc shape(var h: U64; t: ^Type; top: BOOL); -var f, g: ^Obj; -begin - if t = nil then mix(h, -1); return; end; - if (t^.obj # nil) and not top then - mix(h, t^.obj^.name); - if t^.obj^.home # nil then mix(h, t^.obj^.home^.sname); end; - return; - end; - mix(h, INT(t^.form)); - mix(h, bit(t^.vol) + 2 * bit(t^.variadic)); - mix(h, t^.len); - if t^.form in {fPtr, fArray, fSlice, fProc, fSet} then shape(h, t^.base, false); end; - f := t^.fields; - while f # nil do - if (t^.form # fRecord) or f^.exported then - mix(h, f^.name); - mix(h, bit(f^.isVar)); - shape(h, f^.typ, false); - g := f^.fields; - while g # nil do shape(h, g^.typ, false); g := g^.next; end; - end; - f := f^.next; - end; -end; - -proc fingerprint*(o: ^Obj): U64; -var h: U64; f: ^Obj; -begin - h := 0CBF29CE484222325H; (* FNV-1a's 64-bit offset basis *) - mix(h, INT(o^.cls)); - if o^.cls = oCase then - mix(h, o^.val); - f := o^.fields; - while f # nil do shape(h, f^.typ, false); f := f^.next; end; - else - shape(h, o^.typ, o^.cls = oType); - end; - return h; -end; - -(* The universe *) - -proc basic(name: []U8; form: Form; size: I64; signed: BOOL): ^Type; -var t: ^Type; o: ^Obj; -begin - t := newType(form, size, size); - t^.signed := signed; - o := newObj(oType, Scan.intern(ADR(name[0]), LEN(name)), t); - o^.exported := true; - t^.obj := o; - _ := insert(o, 0); - return t; -end; - -proc enter(name: []U8; cls: Class; t: ^Type; v: I64); -var o: ^Obj; -begin - o := newObj(cls, Scan.intern(ADR(name[0]), LEN(name)), t); - o^.val := v; - o^.exported := true; - _ := insert(o, 0); -end; - -begin - hashMask := (1 shl 14) - 1; - hashTab := emptyTable(hashMask + 1); - 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 Sym. diff --git a/self/X64.raz b/self/X64.raz deleted file mode 100644 index a9a28bd..0000000 --- a/self/X64.raz +++ /dev/null @@ -1,1472 +0,0 @@ -(* X64: machine code for x86-64. - - The encoder writes the instructions the code generator needs, and - no others, into the text of Chunk. 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 and the assembler's symbols; Diag, for - positions; Chunk for the code buffer and fixups. - Leaves out: choosing instructions; that is Gen. - - The seed's `Mem` that is too large an offset is marked and the code - goes on, since a function that makes an operand has no place to give - an error back from; the compile ends with the error shown. *) -module X64; -import Out, Fmt, Heap, Buf, Str, Diag, Scan, 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 - Mem* = record - base*: INT; (* a register, or RIP *) - index*: INT; (* a register, or NoIndex *) - scale*: INT; (* 1, 2, 4 or 8 *) - disp*: INT; - chunk*: INT; (* with RIP: the chunk addressed *) - end; - - (* The parser's reader of an integer constant in a code procedure: a - whole expression, or, when whole is false, a single factor *) - ConstFn* = proc(whole: BOOL): (I64, ERROR); - - (* The text of the instruction that starts at at, for the listing *) - Said = record - at: INT; - text: []U8; - end; - -var - listing*: BOOL; (* -S: each instruction's text is kept, for list *) - said: ^Said; - numSaid, saidCap: INT; - -proc setListing*(yes: BOOL); -begin - listing := yes; -end; - -(* Operands *) - -proc mem*(base: INT; disp: I64): Mem; -var m: Mem; -begin - if (disp < -2147483648) or (disp > 2147483647) then - _ := Scan.mark("an offset beyond 32 bits"); - end; - m.base := base; m.index := NoIndex; m.scale := 1; - m.disp := INT(disp); m.chunk := -1; - return m; -end; - -proc memRip*(chunk: INT; disp: INT): Mem; -var m: Mem; -begin - m.base := RIP; m.index := NoIndex; m.scale := 1; - m.disp := disp; m.chunk := chunk; - return m; -end; - -proc memIdx*(base, index, scale: INT; disp: I64): Mem; -var m: Mem; -begin - m := mem(base, disp); - m.index := index; - m.scale := scale; - return m; -end; - -(* The address of the code about to be written, as an operand *) -proc here*: Mem; -begin - return memRip(Chunk.curChunk, Chunk.pc - Chunk.chunks[Chunk.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. *) - -proc opcode(op: INT); -begin - repeat - Chunk.put1(op & 0FFH); - 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. *) -proc prefix(pfx: INT; w: BOOL; reg, index, base: INT; byte4: BOOL); -var rex: INT; -begin - if pfx # 0 then Chunk.put1(pfx); end; - rex := 0; - if w then rex := rex | 8; end; - if reg >= 8 then rex := rex | 4; end; - if index >= 8 then rex := rex | 2; end; - if base >= 8 then rex := rex | 1; end; - if (rex # 0) or byte4 then Chunk.put1(40H | rex); end; -end; - -(* op reg, [mem] *) -proc opM(pfx: INT; w: BOOL; op, reg: INT; m: Mem; byteReg: BOOL); -var md, b, sc: INT; -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); - end; - opcode(op); - reg := reg & 7; - if m.base = RIP then - Chunk.put1((reg shl 3) | 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). *) - Chunk.addFixup(Chunk.pc, m.chunk, m.disp); - Chunk.put4(0); - return; - end; - b := m.base & 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; - elsif (m.disp >= -128) and (m.disp <= 127) then - md := 1; - else - md := 2; - end; - (* 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 - Chunk.put1((md shl 6) | (reg shl 3) | 4); - if m.scale = 1 then sc := 0; elsif m.scale = 2 then sc := 1; elsif m.scale = 4 then sc := 2; else sc := 3; end; - if m.index = NoIndex then - Chunk.put1((sc shl 6) | (4 shl 3) | b); - else - Chunk.put1((sc shl 6) | ((m.index & 7) shl 3) | b); - end; - else - Chunk.put1((md shl 6) | (reg shl 3) | b); - end; - if md = 1 then - Chunk.put1(m.disp); - elsif md = 2 then - Chunk.put4(m.disp); - end; -end; - -(* op reg, rm (both registers) *) -proc opR(pfx: INT; w: BOOL; op, reg, rm: INT; byteReg: BOOL); -begin - prefix(pfx, w, reg, NoIndex, rm, byteReg and (((reg >= 4) and (reg <= 7)) or ((rm >= 4) and (rm <= 7)))); - opcode(op); - Chunk.put1(0C0H | ((reg & 7) shl 3) | (rm & 7)); -end; - -(* The listing: the text of each instruction, as it is made *) - -(* How many instructions the listing has, and back to n of them, for - code made again *) -proc saidCount*: INT; -begin - return numSaid; -end; - -proc unsay*(n: INT); -begin - numSaid := n; -end; - -proc sayAt*(at: INT; s: []U8); -begin - if not listing then return; end; - if numSaid = saidCap then - said := ^Said(Scan.regrab(^U8(said), numSaid * SIZE(Said), (saidCap * 2 + 1024) * SIZE(Said))); - saidCap := saidCap * 2 + 1024; - end; - said[numSaid].at := at; - said[numSaid].text := s; - INC(numSaid); -end; - -(* The text of the instruction about to be written *) -proc say*(s: []U8); -begin - sayAt(Chunk.pc, s); -end; - -(* The text of the instruction at at, said again, as when its operand is - patched *) -proc restate*(at: INT; s: []U8); -var i: INT; -begin - i := numSaid - 1; - while (i >= 0) and (said[i].at # at) do DEC(i); end; - if i >= 0 then said[i].text := s; end; -end; - -const - RegNames: [4][16][]U8 = [ - ["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*: [16][]U8 = ["o", "no", "b", "ae", "e", "ne", "be", "a", "s", "ns", "p", "np", "l", "ge", "le", "g"]; - AluNames: [8][]U8 = ["add", "or", "adc", "sbb", "and", "sub", "xor", "cmp"]; - ShiftNames: [8][]U8 = ["rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar"]; - UnaryNames: [8][]U8 = ["", "", "not", "neg", "mul", "imul", "div", "idiv"]; (* from 2 *) - -(* The name of register r, of size bytes *) -proc rnSized(r, size: INT): []U8; -begin - if size = 1 then return RegNames[3][r]; end; - if size = 2 then return RegNames[2][r]; end; - if size = 4 then return RegNames[1][r]; end; - return RegNames[0][r]; -end; - -proc rn(r: INT): []U8; -begin - return RegNames[0][r]; -end; - -proc xn(x: INT): []U8; -begin - return Diag.say("xmm{}", [Fmt.int(x)]); -end; - -(* A memory operand, with the size of what it holds, as the assembler - reads it *) -proc mnSized(m: Mem; size: INT): []U8; -var b: ^Buf.Buf; -begin - b := ^Buf.Buf(Scan.grab(SIZE(Buf.Buf))); - Buf.init(b, Heap.heap); - if size = 1 then Buf.str(b, "byte "); - elsif size = 2 then Buf.str(b, "word "); - elsif size = 4 then Buf.str(b, "dword "); - elsif size = 8 then Buf.str(b, "qword "); - end; - Buf.str(b, "["); - if m.base = RIP then Buf.str(b, Chunk.chunkName(m.chunk)); else Buf.str(b, rn(m.base)); end; - if m.index # NoIndex then Fmt.write(b, " + {} * {}", [Fmt.str(rn(m.index)), Fmt.int(m.scale)]); end; - if m.disp > 0 then - Fmt.write(b, " + {}", [Fmt.int(m.disp)]); - elsif m.disp < 0 then - Fmt.write(b, " - {}", [Fmt.int(-m.disp)]); - end; - Buf.str(b, "]"); - return Buf.bytes(b); -end; - -proc mn(m: Mem): []U8; -begin - return mnSized(m, 0); -end; - -(* "op a, b" and "op a" *) -proc text2(op, a, b: []U8): []U8; -begin - return Diag.say("{} {}, {}", [Fmt.str(op), Fmt.str(a), Fmt.str(b)]); -end; - -proc text1(op, a: []U8): []U8; -begin - return Diag.say("{} {}", [Fmt.str(op), Fmt.str(a)]); -end; - -(* v in decimal *) -proc num(v: INT): []U8; -begin - return Diag.say("{}", [Fmt.int(v)]); -end; - -proc movRR*(dst, src: INT); -begin - if listing then say(text2("mov", rn(dst), rn(src))); end; - opR(0, true, 89H, src, dst, false); -end; - -(* The operand-size prefix a size of 2 bytes takes *) -proc pfx16(size: INT): INT; -begin - if size = 2 then return 66H; end; - return 0; -end; - -(* The immediate of n bytes that ends an instruction *) -proc putImm(v, n: INT); -begin - if n = 4 then - Chunk.put4(v); - else - Chunk.put1(v & 0FFH); - if n = 2 then Chunk.put1((v shr 8) & 0FFH); end; - end; -end; - -(* op [m], v, on size bytes; v fits in them, or in 32 bits for 8 *) -proc aluMI*(op: INT; m: Mem; v, size: INT); -var n: INT; -begin - if listing then say(text2(AluNames[op], mnSized(m, size), num(v))); end; - if (size = 1) or ((v >= -128) and (v <= 127)) then - n := 1; - elsif size = 2 then - n := 2; - else - n := 4; - end; - if m.base = RIP then m.disp := m.disp - n; end; - if size = 1 then - opM(0, false, 80H, op, m, false); - elsif n = 1 then - opM(pfx16(size), size = 8, 83H, op, m, false); - else - opM(pfx16(size), size = 8, 81H, op, m, false); - end; - putImm(v, n); -end; - -(* mov [m], v, of size bytes; v fits in them, or in 32 bits for 8 *) -proc storeI*(m: Mem; v, size: INT); -var n: INT; -begin - if listing then say(text2("mov", mnSized(m, size), num(v))); end; - n := size; - if n > 4 then n := 4; end; - if m.base = RIP then m.disp := m.disp - n; end; - if size = 1 then - opM(0, false, 0C6H, 0, m, false); - else - opM(pfx16(size), size = 8, 0C7H, 0, m, false); - end; - putImm(v, n); -end; - -proc movRI*(r: INT; v: I64); -begin - if listing then - if v = 0 then - say(text2("xor", rnSized(r, 4), rnSized(r, 4))); - else - say(text2("mov", rn(r), Diag.say("{}", [Fmt.int(v)]))); - end; - end; - if (v >= -2147483648) and (v <= 2147483647) then - if v = 0 then - opR(0, false, 31H, r, r, false); (* xor r32, r32 *) - elsif v > 0 then (* mov r32, imm32 *) - prefix(0, false, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put4(INT(v)); - else - opR(0, true, 0C7H, 0, r, false); Chunk.put4(INT(v)); (* sign-extended imm32 *) - end; - elsif (v > 0) and (v <= 0FFFFFFFFH) then - prefix(0, false, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put4(INT(v)); - else - prefix(0, true, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put8(v); - end; -end; - -proc load*(r: INT; m: Mem; size: INT; signed: BOOL); -begin - if listing then - if size = 8 then - say(text2("mov", rn(r), mn(m))); - elsif (size = 4) and not signed then - say(text2("mov", rnSized(r, 4), mn(m))); - elsif size = 4 then - say(text2("movsxd", rn(r), mnSized(m, 4))); - elsif signed then - say(text2("movsx", rn(r), mnSized(m, size))); - else - say(text2("movzx", rnSized(r, 4), mnSized(m, size))); - end; - end; - if size = 1 then - if signed then opM(0, true, 0BE0FH, r, m, false); else opM(0, false, 0B60FH, r, m, false); end; - elsif size = 2 then - if signed then opM(0, true, 0BF0FH, r, m, false); else opM(0, false, 0B70FH, r, m, false); end; - elsif size = 4 then - if signed then opM(0, true, 63H, r, m, false); else opM(0, false, 8BH, r, m, false); end; - else - opM(0, true, 8BH, r, m, false); - end; -end; - -proc store*(m: Mem; r: INT; size: INT); -begin - if listing then say(text2("mov", mn(m), rnSized(r, size))); end; - if size = 1 then - opM(0, false, 88H, r, m, true); - elsif size = 2 then - opM(66H, false, 89H, r, m, false); - elsif size = 4 then - opM(0, false, 89H, r, m, false); - else - opM(0, true, 89H, r, m, false); - end; -end; - -proc lea*(r: INT; m: Mem); -begin - if listing then say(text2("lea", rn(r), mn(m))); end; - opM(0, true, 8DH, r, m, false); -end; - -proc alu*(op, dst, src: INT); -begin - if listing then say(text2(AluNames[op], rn(dst), rn(src))); end; - opR(0, true, (op shl 3) | 1, src, dst, false); -end; - -proc aluI*(op, r: INT; v: INT); -begin - if listing then say(text2(AluNames[op], rn(r), num(v))); end; - if (v >= -128) and (v <= 127) then - opR(0, true, 83H, op, r, false); Chunk.put1(v); - else - opR(0, true, 81H, op, r, false); Chunk.put4(v); - end; -end; - -(* op r, [m] *) -proc aluM*(op, r: INT; m: Mem); -begin - if listing then say(text2(AluNames[op], rn(r), mn(m))); end; - opM(0, true, (op shl 3) | 3, r, m, false); -end; - -proc imul*(dst, src: INT); -begin - if listing then say(text2("imul", rn(dst), rn(src))); end; - opR(0, true, 0AF0FH, dst, src, false); -end; - -proc imulI*(r: INT; v: INT); -begin - if listing then say(Diag.say("imul {}, {}, {}", [Fmt.str(rn(r)), Fmt.str(rn(r)), Fmt.int(v)])); end; - opR(0, true, 69H, r, r, false); - Chunk.put4(v); -end; - -proc shift*(op, r: INT); -begin - if listing then say(text2(ShiftNames[op], rn(r), "cl")); end; - opR(0, true, 0D3H, op, r, false); -end; - -proc shiftI*(op, r, n: INT); -begin - if listing then say(text2(ShiftNames[op], rn(r), num(n))); end; - opR(0, true, 0C1H, op, r, false); - Chunk.put1(n); -end; - -(* F7 /ext: 2 not, 3 neg, 6 div, 7 idiv *) -proc unary*(ext, r: INT); -begin - if listing then say(text1(UnaryNames[ext], rn(r))); end; - opR(0, true, 0F7H, ext, r, false); -end; - -proc cqo*; -begin - if listing then say("cqo"); end; - Chunk.put1(48H); Chunk.put1(99H); -end; - -(* Brings a value of size bytes in r to 64 bits, by its sign or zeros. *) -proc extend*(r, size: INT; signed: BOOL); -begin - if listing then - if size = 4 then - if signed then - say(text2("movsxd", rn(r), rnSized(r, 4))); - else - say(text2("mov", rnSized(r, 4), rnSized(r, 4))); - end; - elsif signed then - say(text2("movsx", rn(r), rnSized(r, size))); - else - say(text2("movzx", rnSized(r, 4), rnSized(r, size))); - end; - end; - if size = 1 then - if signed then opR(0, true, 0BE0FH, r, r, true); else opR(0, false, 0B60FH, r, r, true); end; - elsif size = 2 then - if signed then opR(0, true, 0BF0FH, r, r, false); else opR(0, false, 0B70FH, r, r, false); end; - elsif size = 4 then - if signed then opR(0, true, 63H, r, r, false); else opR(0, false, 89H, r, r, false); end; - end; -end; - -(* r := 1 if the condition holds, else 0 *) -proc setCC*(cc, r: INT); -begin - if listing then say(text1(Diag.say("set{}", [Fmt.str(CondNames[cc])]), rnSized(r, 1))); end; - opR(0, false, 900FH + (cc shl 8), 0, r, true); - if listing then say(text2("movzx", rnSized(r, 4), rnSized(r, 1))); end; - opR(0, false, 0B60FH, r, r, true); -end; - -proc testRR*(a, b: INT); -begin - if listing then say(text2("test", rn(a), rn(b))); end; - opR(0, true, 85H, b, a, false); -end; - -proc push*(r: INT); -begin - if listing then say(text1("push", rn(r))); end; - if r >= 8 then Chunk.put1(41H); end; - Chunk.put1(50H + (r & 7)); -end; - -proc pop*(r: INT); -begin - if listing then say(text1("pop", rn(r))); end; - if r >= 8 then Chunk.put1(41H); end; - Chunk.put1(58H + (r & 7)); -end; - -proc callChunk*(c: INT); -begin - if listing then say(text1("call", Chunk.chunkName(c))); end; - Chunk.put1(0E8H); - Chunk.addFixup(Chunk.pc, c, 0); - Chunk.put4(0); -end; - -proc callBack*(target: INT); -begin - if listing then say("call"); end; - Chunk.put1(0E8H); - Chunk.put4(target - (Chunk.pc + 4)); -end; - -proc callR*(r: INT); -begin - if listing then say(text1("call", rn(r))); end; - opR(0, false, 0FFH, 2, r, false); -end; - -proc jmpR*(r: INT); -begin - if listing then say(text1("jmp", rn(r))); end; - opR(0, false, 0FFH, 4, r, false); -end; - -proc callM*(m: Mem); -begin - if listing then say(text1("call", mn(m))); end; - opM(0, false, 0FFH, 2, m, false); -end; - -proc ret*; -begin - if listing then say("ret"); end; - Chunk.put1(0C3H); -end; - -proc leave*; -begin - say("leave"); Chunk.put1(0C9H); -end; - -proc syscall*; -begin - say("syscall"); Chunk.put1(0FH); Chunk.put1(05H); -end; - -proc mfence*; -begin - say("mfence"); Chunk.put1(0FH); Chunk.put1(0AEH); Chunk.put1(0F0H); -end; - -proc ud2*; -begin - say("ud2"); Chunk.put1(0FH); Chunk.put1(0BH); -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 *) -proc align*(n: INT); -const - Nops: [8][]U8 = ["\x90", "\x66\x90", "\x0F\x1F\x00", "\x0F\x1F\x40\x00", - "\x0F\x1F\x44\x00\x00", "\x66\x0F\x1F\x44\x00\x00", "\x0F\x1F\x80\x00\x00\x00\x00", - "\x0F\x1F\x84\x00\x00\x00\x00\x00"]; -var k, i: INT; -begin - while Chunk.pc mod n # 0 do - k := n - Chunk.pc mod n; - if k > 8 then k := 8; end; - say("nop"); - for i := 0 to k - 1 do Chunk.put1(INT(Nops[k - 1][i])); end; - end; -end; - -proc repMovsb*; -begin - say("rep movsb"); Chunk.put1(0F3H); Chunk.put1(0A4H); -end; - -(* the direction flag, which has rep movsb go down, and back up *) -proc std*; -begin - say("std"); Chunk.put1(0FDH); -end; - -proc cld*; -begin - say("cld"); Chunk.put1(0FCH); -end; - -proc repStosb*; -begin - say("rep stosb"); Chunk.put1(0F3H); Chunk.put1(0AAH); -end; - -proc repeCmpsb*; -begin - say("repe cmpsb"); Chunk.put1(0F3H); Chunk.put1(0A6H); -end; - -proc lockCmpxchg*(m: Mem; r: INT); -begin - if listing then say(text2("lock cmpxchg", mn(m), rn(r))); end; - Chunk.put1(0F0H); - opM(0, true, 0B10FH, r, m, false); -end; - -proc xchg*(m: Mem; r: INT); -begin - if listing then say(text2("xchg", mn(m), rn(r))); end; - opM(0, true, 87H, r, m, false); -end; - -proc lockXadd*(m: Mem; r: INT); -begin - if listing then say(text2("lock xadd", mn(m), rn(r))); end; - Chunk.put1(0F0H); - opM(0, true, 0C10FH, r, m, false); -end; - -proc movqXR*(x, r: INT); -begin - if listing then say(text2("movq", xn(x), rn(r))); end; - opR(66H, true, 6E0FH, x, r, false); -end; - -proc movqRX*(r, x: INT); -begin - if listing then say(text2("movq", rn(r), xn(x))); end; - opR(66H, true, 7E0FH, x, r, false); -end; - -(* movaps: all of xmm y to xmm x, the shortest move between two *) -proc movX*(x, y: INT); -begin - if listing then say(text2("movaps", xn(x), xn(y))); end; - opR(0, false, 280FH, x, y, false); -end; - -(* The prefix of a real instruction, and the end of its name: sd, or ss for single *) -proc realPfx(single: BOOL): INT; -begin - if single then return 0F3H; end; - return 0F2H; -end; - -proc realEnd(single: BOOL): []U8; -begin - if single then return "ss"; end; - return "sd"; -end; - -(* The real instructions take single: F32 (ss) rather than F64 (sd) *) -proc movsXM*(x: INT; m: Mem; single: BOOL); -begin - if listing then say(text2(Diag.say("movs{}", [Fmt.str(realEnd(single)[1..2])]), xn(x), mn(m))); end; - opM(realPfx(single), false, 100FH, x, m, false); -end; - -proc movsMX*(m: Mem; x: INT; single: BOOL); -begin - if listing then say(text2(Diag.say("movs{}", [Fmt.str(realEnd(single)[1..2])]), mn(m), xn(x))); end; - opM(realPfx(single), false, 110FH, x, m, false); -end; - -proc sseName(op: INT; single: BOOL): []U8; -begin - if op = 58H then return Diag.say("add{}", [Fmt.str(realEnd(single))]); end; - if op = 59H then return Diag.say("mul{}", [Fmt.str(realEnd(single))]); end; - if op = 5CH then return Diag.say("sub{}", [Fmt.str(realEnd(single))]); end; - if op = 5EH then return Diag.say("div{}", [Fmt.str(realEnd(single))]); end; - return Diag.say("cvt{}2{}", [Fmt.str(realEnd(single)), Fmt.str(realEnd(not single))]); -end; - -(* 58 add, 59 mul, 5C sub, 5E div, 5A convert *) -proc sse*(op, x, y: INT; single: BOOL); -begin - if listing then say(text2(sseName(op, single), xn(x), xn(y))); end; - opR(realPfx(single), false, 0FH | (op shl 8), x, y, false); -end; - -(* The same, its right operand in memory: addsd x, [m] *) -proc sseM*(op, x: INT; m: Mem; single: BOOL); -begin - if listing then say(text2(sseName(op, single), xn(x), mn(m))); end; - opM(realPfx(single), false, 0FH | (op shl 8), x, m, false); -end; - -proc ucomis*(x, y: INT; single: BOOL); -begin - if listing then say(text2(Diag.say("ucomi{}", [Fmt.str(realEnd(single))]), xn(x), xn(y))); end; - if single then opR(0, false, 2E0FH, x, y, false); else opR(66H, false, 2E0FH, x, y, false); end; -end; - -proc cvtsi2s*(x, r: INT; single: BOOL); -begin - if listing then say(text2(Diag.say("cvtsi2{}", [Fmt.str(realEnd(single))]), xn(x), rn(r))); end; - opR(realPfx(single), true, 2A0FH, x, r, false); -end; - -proc cvtts2si*(r, x: INT; single: BOOL); -begin - if listing then say(text2(Diag.say("cvtt{}2si", [Fmt.str(realEnd(single))]), rn(r), xn(x))); end; - opR(realPfx(single), true, 2C0FH, r, x, false); -end; - -proc btc*(r, bit: INT); -begin - if listing then say(text2("btc", rn(r), num(bit))); end; - opR(0, true, 0BA0FH, 7, r, false); - Chunk.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. *) - -proc jmp*(var L: INT); -begin - if listing then say("jmp"); end; - Chunk.put1(0E9H); - Chunk.put4(L); - L := Chunk.pc - 4; -end; - -proc jcc*(cc: INT; var L: INT); -begin - if listing then say(Diag.say("j{}", [Fmt.str(CondNames[cc])])); end; - Chunk.put1(0FH); Chunk.put1(80H + cc); - Chunk.put4(L); - L := Chunk.pc - 4; -end; - -proc jmpBack*(target: INT); -begin - if listing then say("jmp"); end; - Chunk.put1(0E9H); - Chunk.put4(target - (Chunk.pc + 4)); -end; - -proc jccBack*(cc, target: INT); -begin - if listing then say(Diag.say("j{}", [Fmt.str(CondNames[cc])])); end; - Chunk.put1(0FH); Chunk.put1(80H + cc); - Chunk.put4(target - (Chunk.pc + 4)); -end; - -proc fixLinkTo*(L, target: INT); -var next: INT; -begin - while L # NoLabel do - next := Chunk.get4At(L); - Chunk.put4At(L, target - (L + 4)); - L := next; - end; -end; - -proc fixLink*(L: INT); -begin - fixLinkTo(L, Chunk.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. *) -proc dropJumpTo*(var L: INT); -begin - if (L = NoLabel) or (L # Chunk.pc - 4) or (Chunk.text[L - 1] # 0E9H) then return; end; - L := Chunk.get4At(L); - Chunk.takeBack(5); - if listing and (numSaid > 0) and (said[numSaid - 1].at = Chunk.pc) then DEC(numSaid); end; -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 *) -proc joinLinks*(L1, L2: INT): INT; -var L: INT; -begin - if L2 = NoLabel then return L1; end; - if L1 # NoLabel then - L := L2; - while Chunk.get4At(L) # NoLabel do L := Chunk.get4At(L); end; - Chunk.put4At(L, L1); - end; - return 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 - OpKind = (oReg, oXmm, oMem, oImm); - Operand = record - kind: OpKind; - r, size: INT; (* oReg, oXmm: the register and its size; oMem: its size, or 0 *) - m: Mem; - v: I64; (* oImm *) - end; - -(* The current symbol as a word: an identifier, or a reserved word that - is also an instruction *) -proc asmWord: []U8; -begin - match Scan.tok of - | sIdent: return Scan.nameOf(Scan.id); - | sAnd: return "and"; - | sOr: return "or"; - | sXor: return "xor"; - | sNot: return "not"; - | sDiv: return "div"; - | sShl: return "shl"; - | sShr: return "shr"; - | else: return ""; - end; -end; - -(* Whether w names a register: rax, eax, ax, al and so on, or xmm0 to - xmm15 (size 16); r and size are set if so *) -proc isReg(w: []U8; r, size: ^INT): BOOL; -const Sizes: [4]INT = [8, 4, 2, 1]; -var i, j, n, d: INT; -begin - for i := 0 to 3 do - for j := 0 to 15 do - if RegNames[i][j] = w then r^ := j; size^ := Sizes[i]; return true; end; - end; - end; - size^ := 16; - if not Str.hasPrefix(w, "xmm") or (LEN(w) <= 3) then return false; end; - (* the seed read the two bytes after xmm as a number, whatever follows *) - n := LEN(w) - 3; - if n > 2 then n := 2; end; - r^ := 0; - for i := 0 to n - 1 do - d := INT(w[3 + i]) - 48; - if (d < 0) or (d > 9) then return false; end; - r^ := r^ * 10 + d; - end; - return r^ <= 15; -end; - -(* Which word of list, a list of words each with a space either side, - w is, from 0; -1 if none *) -proc wordIndex(w: []U8; list: []U8): INT; -var i, n, start: INT; -begin - n := 0; - start := 1; - for i := 1 to LEN(list) - 1 do - if list[i] = ' ' then - if (i - start = LEN(w)) and (list[start..i] = w) then return n; end; - INC(n); - start := i + 1; - end; - end; - return -1; -end; - -(* w from byte from on, at most n bytes of it, as copy does *) -proc part(w: []U8; from, n: INT): []U8; -var e: INT; -begin - e := from + n; - if e > LEN(w) then e := LEN(w); end; - if from >= e then return ""; end; - return w[from..e]; -end; - -(* The condition a name ends in: e of je, nz of jnz *) -proc cond(w: []U8): INT; -const - Alias: [12][]U8 = ["c", "nae", "nc", "nb", "z", "nz", "na", "nbe", "nge", "nl", "ng", "nle"]; - AliasCc: [12]INT = [2, 2, 3, 3, 4, 5, 6, 7, 12, 13, 14, 15]; -var i: INT; -begin - for i := 0 to 15 do - if CondNames[i] = w then return i; end; - end; - for i := 0 to 11 do - if Alias[i] = w then return AliasCc[i]; end; - end; - return -1; -end; - -proc operand(o: ^Operand; constExpr: ConstFn): ERROR; -var w: []U8; r, size, sz: INT; st: Scan.State; v: I64; isR, wasMinus: BOOL; -begin - o^ := {}; - w := asmWord(); - sz := 0; - if w = "byte" then sz := 1; - elsif w = "word" then sz := 2; - elsif w = "dword" then sz := 4; - elsif w = "qword" then sz := 8; - end; - if sz # 0 then Scan.next; w := asmWord(); end; - if Scan.tok = Scan.sLbrak then - (* [base + index * scale + disp], the displacement last *) - Scan.next; - o^.kind := oMem; o^.size := sz; - o^.m := mem(NoBase, 0); - repeat - if isReg(asmWord(), ADR(r), ADR(size)) and (size = 8) then - Scan.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 Scan.tok = Scan.sTimes then - Scan.next; - o^.m.index := r; - v := try constExpr(false); - o^.m.scale := INT(v); - elsif o^.m.base = NoBase then - o^.m.base := r; - else - o^.m.index := r; o^.m.scale := 1; - end; - else - v := try constExpr(true); - o^.m.disp := o^.m.disp + INT(v); - end; - if (Scan.tok # Scan.sPlus) and (Scan.tok # Scan.sMinus) then break; end; - wasMinus := Scan.tok = Scan.sMinus; - Scan.saveScan(st); - Scan.next; - isR := isReg(asmWord(), ADR(r), ADR(size)); - if not isR and wasMinus then Scan.restoreScan(st); end; - until false; - if (Scan.tok # Scan.sRbrak) or (o^.m.base = NoBase) - or not ((o^.m.scale = 1) or (o^.m.scale = 2) or (o^.m.scale = 4) or (o^.m.scale = 8)) then - return Scan.mark("expected a memory operand, [base + index * scale + disp]"); - end; - Scan.next; - elsif isReg(w, ADR(o^.r), ADR(o^.size)) then - if o^.size = 16 then o^.kind := oXmm; else o^.kind := oReg; end; - Scan.next; - else - o^.kind := oImm; - o^.v := try constExpr(true); - end; - return nil; -end; - -(* op with register reg and the register or memory operand o *) -proc rm(pfx: INT; w: BOOL; op, reg: INT; o: Operand; byteReg: BOOL); -begin - if o.kind = oMem then opM(pfx, w, op, reg, o.m, byteReg); else opR(pfx, w, op, reg, o.r, byteReg); end; -end; - -proc putImmV(v: I64; size: INT); -begin - if size = 1 then - Chunk.put1(INT(v & 0FFH)); - elsif size = 2 then - Chunk.put1(INT(v & 0FFH)); Chunk.put1(INT((v shr 8) & 0FFH)); - else - Chunk.put4(INT(v & 0FFFFFFFFH)); - end; -end; - -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: [7]INT = [51H, 58H, 59H, 5CH, 5DH, 5EH, 5FH]; - (* 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: [10]INT = [60H, 61H, 74H, 70H, 0DBH, 0DFH, 0EBH, 0EFH, 0FCH, 0F8H]; - (* bit scans and counts: reg, reg or memory, with the prefix and code that tell them *) - BitOps = " bsf bsr tzcnt lzcnt popcnt "; - BitPfx: [5]INT = [0, 0, 0F3H, 0F3H, 0F3H]; - BitCodes: [5]INT = [0BC0FH, 0BD0FH, 0BC0FH, 0BD0FH, 0B80FH]; - Plain: [15][]U8 = ["ret", "leave", "syscall", "cpuid", "rdtsc", - "pause", "nop", "ud2", "int3", "hlt", "cqo", "cdq", "mfence", "lfence", "sfence"]; - PlainOp: [15]INT = [0C3H, 0C9H, 050FH, 0A20FH, 310FH, - 90F3H, 90H, 0B0FH, 0CCH, 0F4H, 9948H, 99H, 0F0AE0FH, 0E8AE0FH, 0F8AE0FH]; - -var - (* the instruction being assembled *) - aw: []U8; (* its word *) - ao: [3]Operand; (* its operands *) - an: INT; (* how many *) - asize, apfx: INT; - awide, abyte: BOOL; - aat: Diag.Pos; (* where it starts *) - (* the labels of the procedure *) - lnames, lplaces, lchains: [64]INT; - lusedAt: [64]Diag.Pos; - numLabels: INT; - -(* The label called n, entered if new *) -proc lab(n: INT): (INT, ERROR); -var i: INT; -begin - for i := 0 to numLabels - 1 do - if lnames[i] = n then return i, nil; end; - end; - if numLabels > 63 then return 0, Scan.mark("more than 64 labels"); end; - lnames[numLabels] := n; lplaces[numLabels] := -1; lchains[numLabels] := NoLabel; - lusedAt[numLabels] := Scan.tokPos(); - numLabels := numLabels + 1; - return numLabels - 1, nil; -end; - -proc bad: ERROR; -begin - return Scan.markAt(aat, Diag.say("can't assemble {} with these operands", [Fmt.str(aw)])); -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) *) -proc two(toRM, fromRM, opImm, digit: INT): ERROR; -var b: INT; -begin - b := 0; - if abyte then b := 1; end; - if an # 2 then return bad(); end; - if ao[1].kind = oImm then - if (ao[0].kind = oImm) or (opImm < 0) then return bad(); end; - if (opImm = 81H) and not abyte and (ao[1].v >= -128) and (ao[1].v <= 127) then - rm(apfx, awide, 83H, digit, ao[0], false); (* a byte, sign-extended *) - Chunk.put1(INT(ao[1].v & 0FFH)); - else - rm(apfx, awide, opImm - b, digit, ao[0], false); - putImmV(ao[1].v, asize); - end; - elsif (ao[1].kind = oReg) and ((ao[0].kind = oReg) or (ao[0].kind = oMem)) then - rm(apfx, awide, toRM - b, ao[1].r, ao[0], abyte); - elsif (ao[0].kind = oReg) and (ao[1].kind = oMem) then - rm(apfx, awide, fromRM - b, ao[0].r, ao[1], abyte); - else - return bad(); - end; - return nil; -end; - -(* whether operand i is an xmm register or a memory operand *) -proc isXM(i: INT): BOOL; -begin - return (ao[i].kind = oXmm) or (ao[i].kind = oMem); -end; - -(* whether operand i is a general register or a memory operand, for an - xmm register's partner *) -proc isRMem(i: INT): BOOL; -begin - return (ao[i].kind = oReg) or (ao[i].kind = oMem); -end; - -(* b as 1 for true *) -proc bit(f: BOOL): INT; -begin - if f then return 1; end; - return 0; -end; - -(* The instruction w with its operands, in ao and an, apart from the - jumps to labels and db, which assemble does *) -proc instruction(): ERROR; -var k: INT; -begin - if wordIndex(aw, Alus) >= 0 then - k := wordIndex(aw, Alus); - return two(k * 8 + 1, k * 8 + 3, 81H, k); - elsif aw = "mov" then - if (an = 2) and (ao[0].kind = oReg) and (ao[1].kind = oImm) and (asize >= 4) then - if awide then - movRI(ao[0].r, ao[1].v); - else - prefix(0, false, 0, NoIndex, ao[0].r, false); Chunk.put1(0B8H + (ao[0].r & 7)); Chunk.put4(INT(ao[1].v & 0FFFFFFFFH)); - end; - return nil; - end; - return two(89H, 8BH, 0C7H, 0); - elsif aw = "test" then - return two(85H, 85H, 0F7H, 0); - elsif aw = "xchg" then - return two(87H, 87H, -1, 0); - elsif (aw = "cmpxchg") or (aw = "xadd") then - if (an # 2) or (ao[1].kind # oReg) then return bad(); end; - if aw = "xadd" then k := 0C10FH; else k := 0B10FH; end; - rm(apfx, awide, k - (bit(abyte) shl 8), ao[1].r, ao[0], abyte); - elsif aw = "lea" then - if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind # oMem) then return bad(); end; - rm(apfx, awide, 8DH, ao[0].r, ao[1], false); - elsif (aw = "movzx") or (aw = "movsx") or (aw = "movsxd") then - if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end; - if aw = "movsxd" then - k := 63H; - elsif ao[1].size = 1 then - k := 0B60FH; - elsif ao[1].size = 2 then - k := 0B70FH; - else - return bad(); - end; - if aw = "movsx" then k := k + 0800H; end; - rm(apfx, awide, k, ao[0].r, ao[1], ao[1].size = 1); - elsif ((wordIndex(aw, Unaries) >= 0) and (an = 1)) or (aw = "inc") or (aw = "dec") then - if ao[0].kind = oImm then return bad(); end; - if aw = "inc" then - rm(apfx, awide, 0FFH - bit(abyte), 0, ao[0], abyte); - elsif aw = "dec" then - rm(apfx, awide, 0FFH - bit(abyte), 1, ao[0], abyte); - else - rm(apfx, awide, 0F7H - bit(abyte), wordIndex(aw, Unaries) + 2, ao[0], abyte); - end; - elsif aw = "imul" then - if (an < 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end; - if an = 2 then - rm(apfx, awide, 0AF0FH, ao[0].r, ao[1], false); - else - rm(apfx, awide, 69H, ao[0].r, ao[1], false); - putImmV(ao[2].v, asize); - end; - elsif wordIndex(aw, Shifts) >= 0 then - k := wordIndex(aw, Shifts); - if k = 6 then k := 4; end; (* sal is shl *) - if (an # 2) or (ao[0].kind = oImm) then return bad(); end; - if ao[1].kind = oImm then - rm(apfx, awide, 0C1H - bit(abyte), k, ao[0], abyte); - Chunk.put1(INT(ao[1].v & 0FFH)); - elsif (ao[1].kind = oReg) and (ao[1].r = RCX) and (ao[1].size = 1) then - rm(apfx, awide, 0D3H - bit(abyte), k, ao[0], abyte); - else - return bad(); - end; - elsif (aw = "push") or (aw = "pop") then - if (an # 1) or (ao[0].kind # oReg) or not awide then return bad(); end; - if aw = "push" then push(ao[0].r); else pop(ao[0].r); end; - elsif (aw = "call") or (aw = "jmp") then - if (an # 1) or (ao[0].kind = oImm) then return bad(); end; - if aw = "call" then rm(0, false, 0FFH, 2, ao[0], false); else rm(0, false, 0FFH, 4, ao[0], false); end; - elsif Str.hasPrefix(aw, "set") and (cond(part(aw, 3, 3)) >= 0) then - if (an # 1) or (ao[0].kind = oImm) or (asize # 1) then return bad(); end; - rm(0, false, 900FH + (cond(part(aw, 3, 3)) shl 8), 0, ao[0], true); - elsif Str.hasPrefix(aw, "cmov") and (cond(part(aw, 4, 3)) >= 0) then - if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end; - rm(apfx, awide, 400FH + (cond(part(aw, 4, 3)) shl 8), ao[0].r, ao[1], false); - elsif (LEN(aw) > 2) and (wordIndex(aw[0..LEN(aw) - 2], SseOps) >= 0) - and ((aw[LEN(aw) - 2..LEN(aw)] = "sd") or (aw[LEN(aw) - 2..LEN(aw)] = "ss")) then - (* sqrtsd, addss and the like: xmm, xmm or memory *) - if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end; - k := 0FH | (SseCodes[wordIndex(aw[0..LEN(aw) - 2], SseOps)] shl 8); - rm(realPfx(aw[LEN(aw) - 1] = 's'), false, k, ao[0].r, ao[1], false); - elsif wordIndex(aw, PackedOps) >= 0 then - if (an < 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end; - k := wordIndex(aw, PackedOps); - rm(66H, false, 0FH | (PackedCodes[k] shl 8), ao[0].r, ao[1], false); - if aw = "pshufd" then - if (an # 3) or (ao[2].kind # oImm) then return bad(); end; - Chunk.put1(INT(ao[2].v & 0FFH)); - elsif an # 2 then - return bad(); - end; - elsif (aw = "movdqu") or (aw = "movdqa") then - (* the load is 6F and the store 7F; movdqu is F3, movdqa 66 *) - if aw = "movdqu" then k := 0F3H; else k := 66H; end; - if (an = 2) and (ao[0].kind = oXmm) and isXM(1) then - rm(k, false, 6F0FH, ao[0].r, ao[1], false); - elsif (an = 2) and (ao[0].kind = oMem) and (ao[1].kind = oXmm) then - rm(k, false, 7F0FH, ao[1].r, ao[0], false); - else - return bad(); - end; - elsif aw = "pmovmskb" then - if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind # oXmm) then return bad(); end; - rm(66H, false, 0D70FH, ao[0].r, ao[1], false); - elsif wordIndex(aw, BitOps) >= 0 then - if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) or (asize < 4) then return bad(); end; - k := wordIndex(aw, BitOps); - rm(BitPfx[k], awide, BitCodes[k], ao[0].r, ao[1], false); - elsif (aw = "movsd") or (aw = "movss") then - if aw = "movsd" then k := 0F2H; else k := 0F3H; end; - if (an = 2) and (ao[0].kind = oXmm) and isXM(1) then - rm(k, false, 100FH, ao[0].r, ao[1], false); - elsif (an = 2) and (ao[0].kind = oMem) and (ao[1].kind = oXmm) then - rm(k, false, 110FH, ao[1].r, ao[0], false); - else - return bad(); - end; - elsif (aw = "movq") or (aw = "movd") then - if (an = 2) and (ao[0].kind = oXmm) and isRMem(1) then - rm(66H, aw = "movq", 6E0FH, ao[0].r, ao[1], false); - elsif (an = 2) and (ao[1].kind = oXmm) and isRMem(0) then - rm(66H, aw = "movq", 7E0FH, ao[1].r, ao[0], false); - else - return bad(); - end; - elsif (aw = "ucomisd") or (aw = "ucomiss") then - if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end; - if aw = "ucomisd" then - rm(66H, false, 2E0FH, ao[0].r, ao[1], false); - else - rm(0, false, 2E0FH, ao[0].r, ao[1], false); - end; - elsif (aw = "cvtsi2sd") or (aw = "cvtsi2ss") then - if (an # 2) or (ao[0].kind # oXmm) or not isRMem(1) then return bad(); end; - rm(realPfx(aw = "cvtsi2ss"), ao[1].size # 4, 2A0FH, ao[0].r, ao[1], false); - elsif (aw = "cvttsd2si") or (aw = "cvttss2si") then - if (an # 2) or (ao[0].kind # oReg) or not isXM(1) then return bad(); end; - rm(realPfx(aw = "cvttss2si"), awide, 2C0FH, ao[0].r, ao[1], false); - elsif (aw = "cvtsd2ss") or (aw = "cvtss2sd") then - if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end; - rm(realPfx(aw = "cvtss2sd"), false, 5A0FH, ao[0].r, ao[1], false); - else - k := 0; - while (k <= 14) and (Plain[k] # aw) do INC(k); end; - if (k > 14) or (an # 0) then - return Scan.markAt(aat, Diag.say("unknown instruction {}", [Fmt.str(aw)])); - end; - opcode(PlainOp[k]); - end; - return nil; -end; - -(* One instruction or label, as assemble reads it *) -proc statement(constExpr: ConstFn): ERROR; -var - i, k, cc, first: INT; wasListing: BOOL; start: Diag.Pos; v: I64; -begin - aat := Scan.tokPos(); - aw := asmWord(); - if LEN(aw) = 0 then return Scan.mark("expected an instruction"); end; - Scan.next; - if Scan.tok = Scan.sColon then - sayAt(Chunk.pc, Diag.say("{}:", [Fmt.str(aw)])); - k := try lab(Scan.intern(ADR(aw[0]), LEN(aw))); - if lplaces[k] >= 0 then - return Scan.markAt(aat, Diag.say("label {} is defined twice", [Fmt.str(aw)])); - end; - lplaces[k] := Chunk.pc; - fixLink(lchains[k]); - Scan.next; - return nil; - end; - first := Chunk.pc; - wasListing := listing; - listing := false; (* the instruction is said as it is written *) - if aw = "lock" then - Chunk.put1(0F0H); - aw := asmWord(); - Scan.next; - end; - cc := -1; - if aw = "db" then - repeat - start := Scan.tokPos(); - v := try constExpr(true); - if (v < -128) or (v > 255) then - return Scan.markAt(Scan.spanFrom(start), Diag.say("expected a byte from 0 to 255, found {}", [Fmt.int(v)])); - end; - Chunk.put1(INT(v & 0FFH)); - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - elsif (aw[0] = 'j') and ((aw = "jmp") or (cond(part(aw, 1, 3)) >= 0)) and (Scan.tok = Scan.sIdent) then - (* a jump to a label *) - k := try lab(Scan.id); - Scan.next; - if aw # "jmp" then cc := cond(part(aw, 1, 3)); end; - if lplaces[k] >= 0 then - if cc < 0 then jmpBack(lplaces[k]); else jccBack(cc, lplaces[k]); end; - elsif cc < 0 then - jmp(lchains[k]); - else - jcc(cc, lchains[k]); - end; - else - an := 0; - if Scan.tok # Scan.sSemicolon then - repeat - if an > 2 then return Scan.mark("too many operands"); end; - try operand(ADR(ao[an]), constExpr); - INC(an); - if Scan.tok # Scan.sComma then break; end; - Scan.next; - until false; - end; - (* the size: a register's, or what the memory operand says *) - asize := 8; - for i := an - 1 to 0 by -1 do - if (ao[i].kind = oReg) or ((ao[i].kind = oMem) and (ao[i].size # 0)) then asize := ao[i].size; end; - end; - if an > 0 then - if (ao[0].kind = oReg) or ((ao[0].kind = oMem) and (ao[0].size # 0)) then asize := ao[0].size; end; - end; - awide := asize = 8; - abyte := asize = 1; - if asize = 2 then apfx := 66H; else apfx := 0; end; - try instruction(); - end; - if Scan.tok # Scan.sSemicolon then return Scan.mark("expected \";\""); end; - listing := wasListing; - sayAt(first, Diag.source(Scan.spanFrom(aat))); - Scan.next; - return nil; -end; - -proc assemble*(constExpr: ConstFn): ERROR; -var k: INT; -begin - numLabels := 0; - while (Scan.tok # Scan.sEnd) and (Scan.tok # Scan.sEof) do - if Scan.tok = Scan.sSemicolon then - Scan.next; - else - try statement(constExpr); - end; - end; - for k := 0 to numLabels - 1 do - if lplaces[k] < 0 then - return Scan.markAt(lusedAt[k], Diag.say("label {} isn't defined", [Fmt.str(Scan.nameOf(lnames[k]))])); - end; - end; - return nil; -end; - -(* Whether s holds a space *) -proc hasSpace(s: []U8): BOOL; -var i: INT; -begin - for i := 0 to LEN(s) - 1 do - if s[i] = ' ' then return true; end; - end; - return false; -end; - -(* n, in decimal, at least w wide, as write(n: w) *) -proc padded(n, w: INT); -var s: []U8; i: INT; -begin - s := Diag.say("{}", [Fmt.int(n)]); - for i := LEN(s) to w - 1 do Out.str(" "); end; - Out.str(s); -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. *) -proc list*(home: INT); -var order: ^INT; n, i, j, k, c, t, line: INT; text: []U8; -begin - order := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); - n := 0; - for c := 0 to Chunk.numChunks - 1 do - if Chunk.chunks[c].live and (Chunk.chunks[c].sec = Chunk.secText) and (Chunk.chunks[c].home = home) then - i := n; - while (i > 0) and (Chunk.chunks[order[i - 1]].start > Chunk.chunks[c].start) do - order[i] := order[i - 1]; - DEC(i); - end; - order[i] := c; - INC(n); - end; - end; - i := 0; j := 0; - for k := 0 to n - 1 do - c := order[k]; - Out.ln; - Out.str(Chunk.chunkName(c)); Out.str(":\n"); - line := -1; - while (i < numSaid) and (said[i].at < Chunk.chunks[c].start) do INC(i); end; - while (i < numSaid) and (said[i].at < Chunk.chunks[c].start + Chunk.chunks[c].size) do - while (j < Chunk.numLines) and (Chunk.lines[j].at <= said[i].at) do - if (Chunk.lines[j].chunk = c) and (Chunk.lines[j].line # line) then - line := Chunk.lines[j].line; - padded(line, 6); - Out.str(" "); - Out.str(Diag.lineText(Scan.nameOf(Chunk.lines[j].path), line)); - Out.ln; - end; - INC(j); - end; - text := said[i].text; - t := said[i].at; - if (text = "jmp") or (text = "call") then - text := Diag.say("{} {}", [Fmt.str(text), Fmt.int(t + 5 + Chunk.get4At(t + 1) - Chunk.chunks[c].start)]); - elsif (text[0] = 'j') and not hasSpace(text) then - text := Diag.say("{} {}", [Fmt.str(text), Fmt.int(t + 6 + Chunk.get4At(t + 2) - Chunk.chunks[c].start)]); - end; - padded(t - Chunk.chunks[c].start, 14); - Out.str(" "); - Out.str(text); - Out.ln; - INC(i); - end; - end; -end; - -begin - listing := false; - numSaid := 0; - saidCap := 0; - said := nil; -end X64. diff --git a/self/bench.sh b/self/bench.sh deleted file mode 100755 index 40c14ad..0000000 --- a/self/bench.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/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 self/check.sh has built the tests. -set -e -b=build/self -python3 test/genbench.py 12000 >$b/Bench.raz -fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/scanbench.seed self/test/ScanBench.pas >/dev/null -./raz -Werror -I self -o $b/scanbench.self self/test/ScanBench.raz -echo "$(wc -l <$b/Bench.raz) lines" -for t in seed self; 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 self; do - if [ $t = seed ]; then cp raz build/cmp/raz; else cp $b/raz.self build/cmp/raz; fi - best=0 - for i in 1 2 3 4 5; do - s=$(date +%s%N); build/cmp/raz -o build/cmp/bench/Bench.$t build/cmp/bench/Bench.raz; e=$(date +%s%N) - d=$(( (e - s) / 1000000 )); if [ $best = 0 ] || [ $d -lt $best ]; then best=$d; fi - done - echo "compile, $t: $best ms" -done diff --git a/self/check.sh b/self/check.sh deleted file mode 100755 index 8fb31b8..0000000 --- a/self/check.sh +++ /dev/null @@ -1,180 +0,0 @@ -#!/bin/sh -# Tests self/'s units against the seed's: each dumper reads the same -# files and must give the same standard output, standard error and -# status. Run from the repository root, after `make raz`; the seed's -# side is built by fpc from src/. -set -e -b=build/self -mkdir -p $b -fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/scandump.seed self/test/ScanDump.pas >/dev/null -./raz -Werror -I self -o $b/scandump.self self/test/ScanDump.raz -python3 self/test/genreals.py > $b/reals.raz -# one small file for each message the scanner makes, and the places -# diag shows them in: a tab, a long line, characters before the place -mkdir -p $b/lex -python3 self/test/genlex.py $b/lex -n=0; bad=0 -for f in $b/lex/*.raz lib/*.raz examples/*.raz tools/*.raz self/*.raz self/test/*.raz test/run/*.raz test/err/*.raz \ - conform/*/*.raz $b/reals.raz; do - [ -f "$f" ] || continue - s1=0; s2=0 - $b/scandump.seed $f >$b/seed.out 2>$b/seed.err || s1=$? - $b/scandump.self $f >$b/self.out 2>$b/self.err || s2=$? - n=$((n + 1)) - if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.err; then - echo "differs: $f (status $s1 and $s2)"; bad=$((bad + 1)) - fi -done -echo "$n files, $bad differ" -test $bad = 0 - -# Jump: a parser's way of going on after an error -./raz -Werror -I self -o $b/recover self/test/Recover.raz -printf 'a bad b bad bad c\nd bad\n' >$b/rec.raz -r=$($b/recover $b/rec.raz 2>/dev/null) || test $? = 1 -test "$r" = "8 names, 4 failed, 4 errors" && echo "recover ok" - -# Chunk and Sym: a fixed pseudo-random script each, run by both sides, -# which print all they have made or answered; Sym also ends, as the -# argument says, in an error, whose message and status must agree -for u in Chunk Sym; do - l=$(echo $u | tr A-Z a-z) - fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/${l}dump.seed self/test/${u}Dump.pas >/dev/null - ./raz -Werror -I self -o $b/${l}dump.self self/test/${u}Dump.raz -done -for a in "" dup deep; do - for s in seed self; do - t=0; $b/chunkdump.$s >$b/chunk.$s 2>/dev/null || t=$? - t2=0; $b/symdump.$s $a >$b/sym.$s.out 2>$b/sym.$s.err || t2=$? - echo "$t $t2" >$b/status.$s - done - cmp $b/status.seed $b/status.self - cmp $b/chunk.seed $b/chunk.self - cmp $b/sym.seed.out $b/sym.self.out - cmp $b/sym.seed.err $b/sym.self.err -done -echo "chunk and sym ok" - -# Link and Elf: a program of chunks made by a script, linked and written -# as a static, a dynamic and a stripped executable, which must be the -# same file from both sides -fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/linkdump.seed self/test/LinkDump.pas >/dev/null -./raz -Werror -I self -o $b/linkdump.self self/test/LinkDump.raz -for m in 0 1 2; do - $b/linkdump.seed $m $b/link.seed - $b/linkdump.self $m $b/link.self - cmp $b/link.seed $b/link.self -done -echo "link and elf ok" - -# X64: every encoder, then the assembler on a long run of instructions -# of every kind and a file for each error it makes; the bytes and the -# listing, or the message and status, must be the same -fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/x64dump.seed self/test/X64Dump.pas >/dev/null -./raz -Werror -I self -o $b/x64dump.self self/test/X64Dump.raz -$b/x64dump.seed >$b/x64.seed -$b/x64dump.self >$b/x64.self -cmp $b/x64.seed $b/x64.self -fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/asmdump.seed self/test/AsmDump.pas >/dev/null -./raz -Werror -I self -o $b/asmdump.self self/test/AsmDump.raz -mkdir -p $b/asm -python3 self/test/genasm.py $b/asm -n=0; bad=0 -for f in $b/asm/*.raz; do - s1=0; s2=0 - $b/asmdump.seed $f >$b/seed.out 2>$b/seed.err || s1=$? - $b/asmdump.self $f >$b/self.out 2>$b/self.err || s2=$? - n=$((n + 1)) - if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.err; then - echo "differs: $f (status $s1 and $s2)"; bad=$((bad + 1)) - fi -done -echo "x64: $n assembler files, $bad differ" -test $bad = 0 - -# Gen: procedures made by a script of calls (expressions, statements, -# calls, frames, checks, defers, the entry point), whose bytes, fixups, -# line notes and listing must be the same; once with the static entry -# point and once with the dynamic one -fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/gendump.seed self/test/GenDump.pas >/dev/null -./raz -Werror -I self -o $b/gendump.self self/test/GenDump.raz -for a in "" dyn; do - $b/gendump.seed $a >$b/gen.seed - $b/gendump.self $a >$b/gen.self - cmp $b/gen.seed $b/gen.self -done -echo "gen ok" - -# Item: operands and operations driven by a script with mistakes in it, -# which show their messages and go on; what each step gave, the code -# made and the messages must be the same. A run ends at the 20th error, -# as a compile does, so the script changes with each argument. -fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fusrc -o$b/itemdump.seed self/test/ItemDump.pas >/dev/null -./raz -Werror -I self -o $b/itemdump.self self/test/ItemDump.raz -n=0; bad=0 -for a in $(seq 0 59); do - s1=0; s2=0 - $b/itemdump.seed $a >$b/seed.out 2>$b/seed.err || s1=$? - $b/itemdump.self $a >$b/self.out 2>$b/self.err || s2=$? - n=$((n + 1)) - if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.err; then - echo "differs: item script $a (status $s1 and $s2)"; bad=$((bad + 1)) - fi -done -echo "item: $n scripts, $bad differ" -test $bad = 0 - -# Parse and Raz: the compiler this makes, built by the seed, compiles -# what the seed compiles, to the same file, with the same messages and -# status: every example, test and tool, and the library, with each -# one's own options. Both sides run as build/cmp/raz, since a program -# holds the paths it was made from and the library is found beside the -# compiler. -printf 'module Version;\nconst Text* = "%s";\nend Version.\n' "$(tr -d "'" < build/version.inc)" >$b/Version.raz -./raz -Werror -I self -I $b -o $b/raz.self self/Raz.raz -c=build/cmp -mkdir -p $c -ln -sfn ../../lib $c/lib -# and the big program that times the compiler, 348,025 lines -mkdir -p $c/bench -python3 test/genbench.py 12000 >$c/bench/Bench.raz -files= -for f in $c/bench/Bench.raz lib/*.raz examples/*.raz tools/*.raz self/*.raz test/run/*.raz test/libc/*.raz test/bench/*.raz \ - conform/run/*.raz test/err/*.raz conform/err/*.raz; do - files="$files $f" -done -for side in seed self; do - rm -rf $c/$side - mkdir -p $c/$side - if [ $side = seed ]; then cp raz $c/raz; else cp $b/raz.self $c/raz; fi - for f in $files; do - dir=$(dirname $f); name=$(basename $f .raz); x=$(echo $dir | tr / _).$name - flags= - case $dir in - examples|tools|lib|self) flags=-Werror ;; - esac - [ -f $dir/$name.args ] && [ $dir = test/err ] && flags="$flags $(cat $dir/$name.args)" - case $dir in - lib) opts= ;; - self|tools) opts="-I self -I build/self" ;; - test/err) opts="-I test/err/mods -I test/run/mods" ;; - *) opts="-I $dir/mods" ;; - esac - s=0 - $c/raz $flags $opts -o $c/$side/$x $f >$c/$side/$x.out 2>$c/$side/$x.err || s=$? - echo $s >$c/$side/$x.status - done -done -n=0; bad=0 -for f in $files; do - x=$(dirname $f | tr / _).$(basename $f .raz) - n=$((n + 1)) - for e in "" .out .err .status; do - [ -f $c/seed/$x$e ] || [ -f $c/self/$x$e ] || continue - if ! cmp -s $c/seed/$x$e $c/self/$x$e; then - echo "differs: $f ($x$e)"; bad=$((bad + 1)); break - fi - done -done -echo "raz: $n files, $bad differ" -test $bad = 0 diff --git a/self/fixpoint.sh b/self/fixpoint.sh deleted file mode 100755 index fdd34f6..0000000 --- a/self/fixpoint.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/sh -# The fixpoint: the seed builds self/ (stage 1), that builds self/ -# (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. -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 raz $d/stage0 -for n in 1 2 3; do - cp $d/stage$((n - 1)) $d/raz - $d/raz -Werror -I self -I $d/v -o $d/stage$n self/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 $d/stage3 raz -make check -make bench diff --git a/self/test/AsmDump.pas b/self/test/AsmDump.pas deleted file mode 100644 index af7ee9d..0000000 --- a/self/test/AsmDump.pas +++ /dev/null @@ -1,46 +0,0 @@ -{ Assembles the instructions in the file of the argument, as the body of - a code procedure that ends in end, and prints the bytes and the - listing: the seed's side of a test of the assembler in self/X64.raz, - whose AsmDump.raz does the same and prints the same. Constants are - numbers, with a minus sign, and sums of them. } -program asmdump; -{$mode objfpc}{$H-} -uses diag, scan, chunk, x64; -var i: longint; path: string; - -function ConstVal(whole: boolean): int64; -var neg: boolean; v: int64; -begin - neg := tok = sMinus; - if neg then Next; - if tok <> sInt then Mark('expected a number'); - v := ival; - Next; - if neg then v := -v; - while whole and (tok in [sPlus, sMinus]) do begin - neg := tok = sMinus; - Next; - if tok <> sInt then Mark('expected a number'); - if neg then v := v - ival else v := v + ival; - Next; - end; - ConstVal := v; -end; - -begin - if Open(ParamStr(1)) <> '' then Fatal('no file'); - path := 'lib/Rt.raz'; - curFile := Intern(@path[1], length(path)); - listing := true; - NewChunk(secText, 0, 0); - BeginChunk(0); - NoteLine(1, 1); - Next; - Assemble(@ConstVal); - EndChunk(0); - chunks^[0].live := true; - for i := 0 to pc - 1 do write(HexStr(code^[i], 2)); - writeln; - List(0); - Finish; -end. diff --git a/self/test/AsmDump.raz b/self/test/AsmDump.raz deleted file mode 100644 index 7f78f98..0000000 --- a/self/test/AsmDump.raz +++ /dev/null @@ -1,55 +0,0 @@ -(* Assembles the instructions in the file of the argument, as the body of - a code procedure that ends in end, and prints the bytes and the - listing: self/X64.raz's assembler's side of a test against the seed's, - AsmDump.pas, which prints the same. Constants are numbers, with a - minus sign, and sums of them. *) -module AsmDump; -import Out, Files, Diag, Scan, Chunk, X64; - -proc number(neg: BOOL): (I64, ERROR); -var v: I64; -begin - if Scan.tok # Scan.sInt then return 0, Scan.mark("expected a number"); end; - v := Scan.ival; - Scan.next; - if neg then v := -v; end; - return v, nil; -end; - -proc constant(whole: BOOL): (I64, ERROR); -var neg: BOOL; v, w: I64; -begin - neg := Scan.tok = Scan.sMinus; - if neg then Scan.next; end; - v := try number(neg); - while whole and ((Scan.tok = Scan.sPlus) or (Scan.tok = Scan.sMinus)) do - neg := Scan.tok = Scan.sMinus; - Scan.next; - w := try number(neg); - v := v + w; - end; - return v, nil; -end; - -proc main*; -var i: INT; path: []U8; err: ERROR; -begin - if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end; - path := "lib/Rt.raz"; - Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path))); - X64.setListing(true); - _ := Chunk.newChunk(Chunk.secText, 0, 0); - Chunk.beginChunk(0); - Chunk.noteLine(1, 1); - Scan.next; - err := X64.assemble(constant); - if err # nil then Diag.finish; end; - Chunk.endChunk(0); - Chunk.setLive(0); - for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end; - Out.ln; - X64.list(0); - Diag.finish; -end; - -end AsmDump. diff --git a/self/test/ChunkDump.pas b/self/test/ChunkDump.pas deleted file mode 100644 index 9200df4..0000000 --- a/self/test/ChunkDump.pas +++ /dev/null @@ -1,89 +0,0 @@ -{ Makes a program of chunks by a fixed pseudo-random script and prints - all of it: the seed's side of a test of self/Chunk.raz, whose - ChunkDump.raz does the same and prints the same. } -program chunkdump; -{$mode objfpc}{$H-} -uses diag, scan, chunk; -var - seed: int64; - names: array[0..7] of longint; - i, k, n, op, c, sum, open, x, y, z: longint; - b: array[0..63] of byte; - -function Rnd(n: longint): longint; -begin - seed := (seed * 1103515245 + 12345) and $7FFFFFFF; - Rnd := (seed shr 8) mod n; -end; - -begin - seed := 7; - for i := 0 to 7 do begin b[0] := 97 + i; names[i] := Intern(@b[0], 1) end; - open := -1; - sum := 0; - for k := 1 to 30000 do begin - op := Rnd(16); - case op of - 0..3: Put1(Rnd(256)); - 4: begin x := Rnd(1 shl 30); y := Rnd(1 shl 30); Put4(x - y) end; - 5: begin x := Rnd(1 shl 30); y := Rnd(1 shl 30); Put8(int64(x) * 4096 - y) end; - 6: begin - if open >= 0 then EndChunk(open); - x := Rnd(5); y := Rnd(9); - open := NewChunk(secText, x - 1, y - 1); - BeginChunk(open); - end; - 7: begin x := Rnd(8); curFile := names[x]; x := Rnd(300); y := Rnd(80); NoteLine(x, y) end; - 8: if numChunks > 0 then begin x := Rnd(numChunks); y := Rnd(100); AddFixup(pc, x, y - 50) end; - 9: if (open >= 0) and (pc - chunks^[open].start > 8) then begin x := Rnd(6); TakeBack(x) end; - 10: begin - x := Rnd(5); y := Rnd(9); - c := NewChunk(secRodata, x - 1, y - 1); - n := Rnd(64); - for i := 0 to n - 1 do b[i] := Rnd(256); - x := Rnd(4); - SetData(c, @b[0], n, 1 shl x); - n := Rnd(4); - for i := 1 to n do begin x := Rnd(8); y := Rnd(numChunks); z := Rnd(10); AddDataFixup(c, x * 8, y, z) end; - end; - 11: begin - x := Rnd(5); y := Rnd(9); - c := NewChunk(secBss, x - 1, y - 1); - x := Rnd(100); y := Rnd(4); - SetBss(c, x, 1 shl y); - end; - 12: begin x := Rnd(8); c := ExternChunk(names[x]) end; - 13: if numChunks > 0 then begin - x := Rnd(numChunks); y := Rnd(8); z := Rnd(200); n := Rnd(5); - NoteVar(x, names[y], z - 100, n); - end; - 14: if pc >= 8 then begin - x := Rnd(1 shl 30); y := Rnd(1 shl 30); - Put4At(pc - 8, x - y); - sum := (sum + Get4At(pc - 8)) and $FFFFFF; - end; - 15: if numChunks > 0 then begin - x := Rnd(numChunks); chunks^[x].live := true; - x := Rnd(numChunks); y := Rnd(1 shl 30); chunks^[x].adr := y; - end; - end; - end; - if open >= 0 then EndChunk(open); - writeln('sum ', sum, ' pc ', pc, ' rolen ', rolen); - for i := 0 to numChunks - 1 do - with chunks^[i] do - writeln('C ', i, ' ', ord(sec), ' ', start, ' ', size, ' ', align, ' ', firstFix, ' ', numFix, ' ', - module, ' ', name, ' ', adr, ' ', ord(live), ' ', ord(ext), ' ', ChunkName(i)); - for i := 0 to numFixups - 1 do - writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend); - for i := 0 to numDataFixups - 1 do - writeln('D ', dataFixups^[i].at, ' ', dataFixups^[i].chunk, ' ', dataFixups^[i].addend); - for i := 0 to numLines - 1 do - writeln('L ', lines^[i].at, ' ', lines^[i].chunk, ' ', lines^[i].path, ' ', lines^[i].line, ' ', lines^[i].col); - for i := 0 to numVarNotes - 1 do - writeln('V ', varNotes[i].chunk, ' ', varNotes[i].name, ' ', varNotes[i].off, ' ', varNotes[i].kind); - for i := 0 to pc - 1 do write(HexStr(code^[i], 2)); - writeln; - for i := 0 to rolen - 1 do write(HexStr(rodata^[i], 2)); - writeln; -end. diff --git a/self/test/ChunkDump.raz b/self/test/ChunkDump.raz deleted file mode 100644 index dc52cee..0000000 --- a/self/test/ChunkDump.raz +++ /dev/null @@ -1,118 +0,0 @@ -(* Makes a program of chunks by a fixed pseudo-random script and prints - all of it: self/Chunk.raz's side of a test against the seed's, - ChunkDump.pas, which prints the same. *) -module ChunkDump; -import Out, Fmt, Scan, Chunk; - -var seed: I64; - -proc rnd(n: INT): INT; -begin - seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; - return INT((seed shr 8) mod I64(n)); -end; - -(* a flag, as the number the seed's side prints for it *) -proc bit(f: BOOL): INT; -begin - if f then return 1; end; - return 0; -end; - -proc main*; -var - names: [8]INT; b: [64]U8; - i, k, n, op, c, sum, open, x, y, z: INT; -begin - seed := 7; - for i := 0 to 7 do b[0] := U8(97 + i); names[i] := Scan.intern(ADR(b[0]), 1); end; - open := -1; - sum := 0; - for k := 1 to 30000 do - op := rnd(16); - match op of - | 0..3: Chunk.put1(rnd(256)); - | 4: x := rnd(1 shl 30); y := rnd(1 shl 30); Chunk.put4(x - y); - | 5: x := rnd(1 shl 30); y := rnd(1 shl 30); Chunk.put8(I64(x) * 4096 - I64(y)); - | 6: - if open >= 0 then Chunk.endChunk(open); end; - x := rnd(5); y := rnd(9); - open := Chunk.newChunk(Chunk.secText, x - 1, y - 1); - Chunk.beginChunk(open); - | 7: - x := rnd(8); Chunk.setCurFile(names[x]); - x := rnd(300); y := rnd(80); Chunk.noteLine(x, y); - | 8: - if Chunk.numChunks > 0 then - x := rnd(Chunk.numChunks); y := rnd(100); Chunk.addFixup(Chunk.pc, x, y - 50); - end; - | 9: - if (open >= 0) and (Chunk.pc - Chunk.chunks[open].start > 8) then - x := rnd(6); Chunk.takeBack(x); - end; - | 10: - x := rnd(5); y := rnd(9); - c := Chunk.newChunk(Chunk.secRodata, x - 1, y - 1); - n := rnd(64); - for i := 0 to n - 1 do b[i] := U8(rnd(256)); end; - x := rnd(4); - Chunk.setData(c, ADR(b[0]), n, 1 shl x); - n := rnd(4); - for i := 1 to n do - x := rnd(8); y := rnd(Chunk.numChunks); z := rnd(10); - Chunk.addDataFixup(c, x * 8, y, z); - end; - | 11: - x := rnd(5); y := rnd(9); - c := Chunk.newChunk(Chunk.secBss, x - 1, y - 1); - x := rnd(100); y := rnd(4); - Chunk.setBss(c, x, 1 shl y); - | 12: x := rnd(8); c := Chunk.externChunk(names[x]); - | 13: - if Chunk.numChunks > 0 then - x := rnd(Chunk.numChunks); y := rnd(8); z := rnd(200); n := rnd(5); - Chunk.noteVar(x, names[y], z - 100, n); - end; - | 14: - if Chunk.pc >= 8 then - x := rnd(1 shl 30); y := rnd(1 shl 30); - Chunk.put4At(Chunk.pc - 8, x - y); - sum := (sum + Chunk.get4At(Chunk.pc - 8)) & 0FFFFFFH; - end; - | else: - if Chunk.numChunks > 0 then - x := rnd(Chunk.numChunks); Chunk.setLive(x); - x := rnd(Chunk.numChunks); y := rnd(1 shl 30); Chunk.setAdr(x, y); - end; - end; - end; - if open >= 0 then Chunk.endChunk(open); end; - Fmt.print("sum {} pc {} rolen {}\n", [Fmt.int(sum), Fmt.int(Chunk.pc), Fmt.int(Chunk.rolen)]); - for i := 0 to Chunk.numChunks - 1 do - Fmt.print("C {} {} {} {} {} {} {} {} {} {} {} {} {}\n", [Fmt.int(i), Fmt.int(INT(Chunk.chunks[i].sec)), - Fmt.int(Chunk.chunks[i].start), Fmt.int(Chunk.chunks[i].size), Fmt.int(Chunk.chunks[i].align), - Fmt.int(Chunk.chunks[i].firstFix), Fmt.int(Chunk.chunks[i].numFix), Fmt.int(Chunk.chunks[i].home), - Fmt.int(Chunk.chunks[i].name), Fmt.int(Chunk.chunks[i].adr), - Fmt.int(bit(Chunk.chunks[i].live)), Fmt.int(bit(Chunk.chunks[i].ext)), Fmt.str(Chunk.chunkName(i))]); - end; - for i := 0 to Chunk.numFixups - 1 do - Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]); - end; - for i := 0 to Chunk.numDataFixups - 1 do - Fmt.print("D {} {} {}\n", [Fmt.int(Chunk.dataFixups[i].at), Fmt.int(Chunk.dataFixups[i].chunk), Fmt.int(Chunk.dataFixups[i].addend)]); - end; - for i := 0 to Chunk.numLines - 1 do - Fmt.print("L {} {} {} {} {}\n", [Fmt.int(Chunk.lines[i].at), Fmt.int(Chunk.lines[i].chunk), - Fmt.int(Chunk.lines[i].path), Fmt.int(Chunk.lines[i].line), Fmt.int(Chunk.lines[i].col)]); - end; - for i := 0 to Chunk.numVarNotes - 1 do - Fmt.print("V {} {} {} {}\n", [Fmt.int(Chunk.varNotes[i].chunk), Fmt.int(Chunk.varNotes[i].name), - Fmt.int(Chunk.varNotes[i].off), Fmt.int(Chunk.varNotes[i].kind)]); - end; - for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end; - Out.ln; - for i := 0 to Chunk.rolen - 1 do Out.hex(U64(Chunk.rodata[i]), 2); end; - Out.ln; -end; - -end ChunkDump. diff --git a/self/test/GenDump.pas b/self/test/GenDump.pas deleted file mode 100644 index 86680b7..0000000 --- a/self/test/GenDump.pas +++ /dev/null @@ -1,708 +0,0 @@ -{ Compiles procedures made by a fixed pseudo-random script of calls to - Gen, valid by construction, then prints the bytes, the fixups and the - listing (raz -S) of what it made: the seed's side of a test of - self/Gen.raz, whose GenDump.raz makes and prints the same. With an - argument, the entry point is the dynamic one. } -program gendump; -{$mode objfpc}{$H-} -uses diag, scan, sym, chunk, x64, gen; - -const - FirstProc = 3; - NumProcs = 80; - FirstGlob = FirstProc + NumProcs; - NumGlobs = 4; - Arith: array[0..9] of TSym = (sPlus, sMinus, sTimes, sDiv, sMod, sAmp, sBar, sXor, sShl, sShr); - Cmps: array[0..5] of TSym = (sEql, sNeq, sLss, sLeq, sGtr, sGeq); - RealOps: array[0..3] of TSym = (sPlus, sMinus, sTimes, sSlash); - -var - seed: int64; - slots: array[0..5] of int64; - regs: array[0..4] of longint; - numRegs: longint; - xregs: array[0..3] of longint; - numX: longint; - tuple2, tuple3, record3, sliceT: PType; - results: array[0..8] of PType; - curRes: longint; - -function Rnd(n: longint): longint; -begin - seed := (seed * 1103515245 + 12345) and $7FFFFFFF; - Rnd := (seed shr 8) mod n; -end; - -function Pos: TPos; -var p: TPos; -begin - p.f := 0; p.a := Rnd(400); p.b := p.a + 1; - Pos := p; -end; - -function Size: longint; -begin - Size := 1 shl Rnd(4); -end; - -function Slot: int64; -begin - Slot := slots[Rnd(6)]; -end; - -function Bit(f: boolean): longint; -begin - if f then Bit := 1 else Bit := 0; -end; - -function Flag: boolean; -begin - Flag := Rnd(2) = 0; -end; - -function ConstVal: int64; -var x: longint; r: int64; -begin - x := Rnd(1 shl 30); - case Rnd(7) of - 0: r := x mod 10; - 1: r := -(x mod 100); - 2: r := int64(1) shl (x mod 20); - 3: r := x; - 4: r := int64(x) * 4096 * 4096 * 9 - 7; - 5: r := -int64(x) * 8; - else r := x mod 1000 - 500; - end; - ConstVal := r; -end; - -function NewObjs(t: PType; n: longint): PObj; -var first, o, last: PObj; i: longint; -begin - first := nil; last := nil; - for i := 0 to n - 1 do begin - o := NewObj(oVar, 0, t); - o^.val := 8 * i; - if last = nil then first := o else last^.next := o; - last := o; - end; - NewObjs := first; -end; - -procedure MakeTypes; -begin - tuple2 := NewType(fRecord, 16, 8); - tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := NewObjs(tInt, 2); - tuple3 := NewType(fRecord, 24, 8); - tuple3^.tuple := true; tuple3^.len := 3; tuple3^.fields := NewObjs(tInt, 3); - record3 := NewType(fRecord, 24, 8); - record3^.fields := NewObjs(tReal, 3); - sliceT := NewType(fSlice, 16, 8); - sliceT^.base := tU8; - results[0] := nil; - results[1] := tInt; - results[2] := tReal; - results[3] := sliceT; - results[4] := tuple2; - results[5] := tuple3; - results[6] := tF32; - results[7] := tI16; - results[8] := record3; -end; - -function MemAdr: TAdr; -var a: TAdr; c: longint; -begin - c := Rnd(3); - if c = 0 then begin - a.base := bFrame; a.chunk := 0; a.hi := 0; a.off := Slot; if Flag then a.off := a.off + 8; - end else if c = 1 then begin - a.base := bGlobal; a.chunk := FirstGlob + Rnd(NumGlobs); a.hi := 0; a.off := 8 * Rnd(3); - end else begin - a.base := bSlot; a.chunk := Slot; a.hi := 0; a.off := 8 * Rnd(3); - end; - MemAdr := a; -end; - -function PushableAdr: TAdr; -var a: TAdr; -begin - a.chunk := 0; a.hi := 0; - if Flag then begin - a.base := bFrame; a.off := Slot; if Flag then a.off := a.off + 8; - end else begin - a.base := bGlobal; a.chunk := FirstGlob + Rnd(NumGlobs); a.off := 8 * Rnd(3); - end; - PushableAdr := a; -end; - -function RegAdr(r: longint): TAdr; -var a: TAdr; -begin - a.base := bReg; a.chunk := r; a.hi := 0; a.off := 0; - RegAdr := a; -end; - -function StackAdr: TAdr; -var a: TAdr; -begin - a.base := bStack; a.chunk := 0; a.hi := 0; a.off := 8 * Rnd(3); - StackAdr := a; -end; - -procedure PushIntVar; -var a: TAdr; sz, c: longint; -begin - sz := Size; - c := Rnd(5); - if (c = 0) and (numRegs > 0) then begin - if Flag then inPlace := regs[Rnd(numRegs)]; - PushVar(RegAdr(regs[Rnd(numRegs)]), 8, false, kWord); - end else if c = 1 then begin - PushAdr(PushableAdr); - a := StackAdr; - PushVar(a, sz, Flag, kWord); - end else begin - a := MemAdr; - PushVar(a, sz, Flag, kWord); - end; -end; - -procedure IntExpr(b: longint); forward; -procedure RealExpr(k: TKind; b: longint); forward; -procedure CallExpr(want, b: longint); forward; - -function RealKind: TKind; -begin - if Flag then RealKind := kF64 else RealKind := kF32; -end; - -procedure IntExpr(b: longint); -var c, sz, n: longint; sg, f: boolean; k: TKind; sy: TSym; a: TAdr; -begin - if b > 0 then c := Rnd(14) else c := Rnd(3); - case c of - 0: PushConst(kWord, ConstVal); - 1: PushIntVar; - 2: PushIntVar; - 3, 4, 5: begin - IntExpr(b - 1); IntExpr(b - 1); - sy := Arith[Rnd(10)]; sz := Size; sg := Flag; - Op(sy, kWord, sz, sg); - end; - 6: - if Flag then begin - IntExpr(b - 1); IntExpr(b - 1); - sy := Cmps[Rnd(6)]; sg := Flag; - Compare(sy, kWord, sg); - end else begin - k := RealKind; - RealExpr(k, b - 1); RealExpr(k, b - 1); - sy := Cmps[Rnd(6)]; - Compare(sy, k, false); - end; - 7: begin - IntExpr(b - 1); - n := Rnd(4); sz := Size; sg := Flag; - if n = 0 then Neg(kWord, sz, sg) - else if n = 1 then Complement(sz, sg) - else if n = 2 then NotBool - else Narrow(sz, sg); - end; - 8: begin - IntExpr(b - 1); - a := PushableAdr; - sz := Size; sg := Flag; - n := 10 + Rnd(100); - CheckIndex(n, Pos); - IndexArray(a, sz); - a := StackAdr; a.off := 0; - PushVar(a, sz, sg, kWord); - end; - 9: begin - n := Rnd(3); - sz := Size; sg := Flag; - if n = 0 then begin - a := MemAdr; - if a.base = bGlobal then a.base := bFrame; - IntExpr(b - 1); - f := Flag; - IndexSlice(a, sz, f, Pos); - end else if n = 1 then begin - PushAdr(PushableAdr); - IntExpr(b - 1); - a := StackAdr; a.off := 0; - f := Flag; - IndexSlice(a, sz, f, Pos); - end else begin - a.base := bReg; a.chunk := R13; a.hi := R14; a.off := 0; - IntExpr(b - 1); - f := Flag; - IndexSlice(a, sz, f, Pos); - end; - a := StackAdr; a.off := 0; - PushVar(a, sz, sg, kWord); - end; - 10: begin - k := RealKind; - RealExpr(k, b - 1); - RealToInt(k); - end; - 11: CallExpr(1, b - 1); - 12: begin - IntExpr(b - 1); - PushConst(kWord, Rnd(100) - 50); - Op(sPlus, kWord, 8, false); - end; - else begin - IntExpr(b - 1); - PushConst(kWord, ConstVal); - sy := Arith[Rnd(10)]; sz := Size; sg := Flag; - Op(sy, kWord, sz, sg); - end; - end; -end; - -procedure RealExpr(k: TKind; b: longint); -var c, n: longint; sy: TSym; a: TAdr; k2: TKind; v: int64; -begin - if b > 0 then c := Rnd(9) else c := Rnd(3); - case c of - 0: begin - n := Rnd(4); - if n = 0 then v := $3FF0000000000000 - else if n = 1 then v := $4000000000000000 - else if n = 2 then v := 0 - else v := $3FE0000000000000; - PushConst(k, v); - end; - 1: begin - a := MemAdr; - if k = kF32 then PushVar(a, 4, false, k) else PushVar(a, 8, false, k); - end; - 2: - if numX > 0 then begin - if Flag then inPlace := xregs[Rnd(numX)]; - PushVar(RegAdr(xregs[Rnd(numX)]), 8, false, k); - end else begin - PushAdr(PushableAdr); - a := StackAdr; - PushVar(a, 8, false, k); - end; - 3, 4: begin - RealExpr(k, b - 1); RealExpr(k, b - 1); - sy := RealOps[Rnd(4)]; - Op(sy, k, 8, false); - end; - 5: begin - IntExpr(b - 1); - IntToReal(k, Flag); - end; - 6: begin - RealExpr(k, b - 1); - Neg(k, 8, false); - end; - 7: begin - if k = kF32 then k2 := kF64 else k2 := kF32; - RealExpr(k2, b - 1); - RealToReal(k2); - end; - else CallExpr(2, b - 1); - end; -end; - -procedure CallExpr(want, b: longint); -var - c: TCall; sig: PType; i, n, kind, r, ni: longint; k: TKind; -begin - sig := NewType(fProc, 8, 8); - sig^.variadic := Rnd(5) = 0; - if want = 1 then begin - r := Rnd(5); - if r = 0 then sig^.base := tBool - else if r = 1 then sig^.base := tI8 - else if r = 2 then sig^.base := tU32 - else if r = 3 then sig^.base := tuple2 - else sig^.base := tInt; - end else if want = 2 then begin - if Flag then sig^.base := tReal else sig^.base := tF32; - end else - sig^.base := results[Rnd(9)]; - c.sig := sig; c.param := nil; c.obj := nil; c.ext := Rnd(4) = 0; - c.n := 0; c.target := 0; - c.chunk := FirstProc + Rnd(NumProcs); - if Rnd(5) = 0 then begin c.chunk := -1; c.ext := false; c.target := Slot end; - n := Rnd(8); - for i := 0 to n - 1 do begin - kind := Rnd(4); - if kind = 0 then begin - k := RealKind; - RealExpr(k, b); - c.isF[c.n] := true; c.pair[c.n] := false; - inc(c.n); - end else if kind = 1 then begin - IntExpr(b); IntExpr(b); - c.isF[c.n] := false; c.pair[c.n] := true; - c.isF[c.n + 1] := false; c.pair[c.n + 1] := false; - inc(c.n, 2); - end else begin - IntExpr(b); - c.isF[c.n] := false; c.pair[c.n] := false; - inc(c.n); - end; - end; - Call(c); - ni := 0; - if sig^.base <> nil then begin - if sig^.base^.form = fSlice then ni := 0 - else if sig^.base = tuple2 then ni := 2 - else if BehindPointer(sig^.base) then ni := 0 - else ni := 1; - end; - if want = 0 then begin - for i := 1 to ni do Drop; - end else if ni = 2 then - Drop; -end; - -procedure BoolExpr(b: longint); -var sy: TSym; sg: boolean; -begin - if Flag then begin - IntExpr(b); IntExpr(b); - sy := Cmps[Rnd(6)]; sg := Flag; - Compare(sy, kWord, sg); - end else - IntExpr(b); -end; - -procedure Stmt(b: longint); forward; - -procedure Assign(b: longint); -var a: TAdr; c, sz: longint; k: TKind; -begin - c := Rnd(6); - sz := Size; - if c = 0 then begin - a := MemAdr; - IntExpr(b); - PopVar(a, sz); - end else if c = 1 then begin - PushAdr(PushableAdr); - a := StackAdr; - IntExpr(b); - PopVar(a, sz); - end else if (c = 2) and (numRegs > 0) then begin - a := RegAdr(regs[Rnd(numRegs)]); - inPlace := a.chunk; - PushVar(a, 8, false, kWord); - IntExpr(b); - Op(Arith[Rnd(3)], kWord, 8, false); - PopVar(a, 8); - end else if (c = 3) and (numX > 0) then begin - k := RealKind; - a := RegAdr(xregs[Rnd(numX)]); - RealExpr(k, b); - PopVar(a, 8); - end else if c = 4 then begin - k := RealKind; - a := MemAdr; - RealExpr(k, b); - if k = kF32 then PopVar(a, 4) else PopVar(a, 8); - end else begin - a := MemAdr; - PushConst(kWord, ConstVal); - PopVar(a, sz); - end; -end; - -procedure RetStmt(b: longint); -var i: longint; -begin - if curRes = 1 then IntExpr(b) - else if curRes = 7 then IntExpr(b) - else if curRes = 2 then RealExpr(kF64, b) - else if curRes = 6 then RealExpr(kF32, b) - else if (curRes = 3) or (curRes = 4) then begin IntExpr(b); IntExpr(b) end - else if curRes = 5 then begin - for i := 0 to 2 do begin IntExpr(b); ResultTo(8 * i, 8) end; - end else if curRes = 8 then begin - PushAdr(PushableAdr); - CopyResult(0, 24); - end; - ReturnJump; -end; - -procedure Stmt(b: longint); -var - c, n, lo, i, start, saved, sz, tmp: longint; L, E, S, fj, tj: longint; a, a2: TAdr; sy: TSym; sg: boolean; - mk: int64; f: boolean; -begin - mk := TempMark; - if b <= 0 then c := Rnd(4) else c := Rnd(22); - case c of - 0, 1, 2, 3: Assign(b); - 4: begin - L := NoLabel; - BoolExpr(b); - JumpIf(L, false); - Stmt(b - 1); - Fix(L); - end; - 5: begin - L := NoLabel; - AlignLoop; - start := pc; - BoolExpr(b); - JumpIf(L, false); - Stmt(b - 1); - JumpBack(start); - Fix(L); - end; - 6: begin - L := NoLabel; - IntExpr(b); IntExpr(b); - sy := Cmps[Rnd(6)]; sg := Flag; - if Flag then JumpCmp(sy, sg, L) else JumpOut(sy, sg, L); - Stmt(b - 1); - Fix(L); - end; - 7: begin - fj := NoLabel; tj := NoLabel; - IntExpr(b); IntExpr(b); - sy := Cmps[Rnd(6)]; sg := Flag; - CondValue(sy, sg, fj, tj); - a := MemAdr; - PopVar(a, 1); - end; - 8: CallExpr(0, b); - 9: begin - a := MemAdr; - if a.base = bSlot then begin a.base := bFrame; a.off := slots[0] end; - IntExpr(b); - PopVar(a, 8); - E := NoLabel; - n := 2 + Rnd(4); lo := Rnd(5) - 2; - if Flag then S := NoLabel else S := pc; - start := JumpTable(a.off, lo, n, S, E); - for i := 0 to n - 1 do TableEntry(start, pc + 4 * (n - i)); - for i := 0 to n - 1 do - Stmt(b - 1); - Fix(E); - end; - 10: begin - PushAdr(PushableAdr); PushAdr(PushableAdr); - n := 1 + Rnd(150); lo := 8 * Rnd(3); - CopyBlock(n, lo); - end; - 11: begin - PushAdr(PushableAdr); - a := MemAdr; - if Flag and (numRegs > 1) then begin - a.base := bReg; a.chunk := regs[0]; a.hi := regs[1]; a.off := 0; - end; - n := 1 + Rnd(150); - CopyTo(a, n); - end; - 12: begin - a := MemAdr; - n := 1 + Rnd(100); - ZeroVar(a, n); - end; - 13: begin - tmp := AllocTemp(16, 8); - n := Rnd(3); - sz := Size; sg := Flag; - if n = 0 then begin - a := PushableAdr; - PushAdr(a); IntExpr(b); IntExpr(b); - a := StackAdr; a.off := 0; - f := Flag; n := 10 + Rnd(50); - Slice(a, f, n, sz, tmp, sg, Pos); - end else if n = 1 then begin - a := MemAdr; - if a.base = bGlobal then a.base := bFrame; - IntExpr(b); IntExpr(b); - Slice(a, false, 0, sz, tmp, sg, Pos); - end else begin - IntExpr(b); IntExpr(b); IntExpr(b); - SlicePtr(sz, tmp, sg, Pos); - end; - end; - 14: begin - a.off := Slot; a2.off := Slot; sz := Size; f := Flag; - CopySlice(a.off, a2.off, sz, f, Pos); - end; - 15: begin - n := Rnd(4); sz := Size; sg := Flag; - if n = 0 then begin - PushAdr(PushableAdr); IntExpr(b); - f := Flag; - IncDec(sz, sg, f); - end else if (n = 1) and (numRegs > 0) then begin - IntExpr(b); - IncDecReg(regs[0], sz, sg, Flag); - end else if n = 2 then begin - IntExpr(b); - n := 3 + Rnd(6); lo := FirstGlob + Rnd(NumGlobs); - CheckEnum(n, lo, Pos); - Drop; - end else begin - IntExpr(b); - n := Rnd(8000); - CheckNil(n, Pos); - Drop; - end; - end; - 16: begin - n := Rnd(3); - if n = 0 then begin - a.off := Slot; a2.off := Slot; n := Rnd(4); f := Flag; - CompareSeq(a.off, a2.off, n, f); - Drop; - end else if n = 1 then begin - IntExpr(b); - ErrorText(AllocTemp(16, 8)); - end else begin - IntExpr(b); - n := 1 + Rnd(200); - ZeroNew(n); - Drop; - end; - end; - 17: begin - n := Rnd(3); - if n = 0 then begin - IntExpr(b); IntExpr(b); IntExpr(b); - Atomic(bCas); - end else if n = 1 then begin - IntExpr(b); IntExpr(b); - Atomic(bXchg); - end else begin - IntExpr(b); IntExpr(b); - Atomic(bXadd); - end; - Drop; - end; - 18: begin - n := Rnd(7); - for i := 1 to n do IntExpr(b); - SysCall(n); - Drop; - if Flag then Fence; - end; - 19: begin - L := NoLabel; - start := DeferBegin(L, saved); - Stmt(b - 1); - DeferEnd(L, saved); - RunDefer(start); - end; - 20: if curRes <> 0 then RetStmt(b) else Assign(b); - else - if curRes <> 0 then begin - TryAlign; - TryReturn(Slot); - end else - Assign(b); - end; - ReleaseTemps(mk); -end; - -procedure GenProc(c: longint); -var - sig: PType; params, p, last: PObj; i, n, kind, mask, j, ns, line: longint; t: PType; - mk: TCodeMark; open: boolean; -begin - sig := NewType(fProc, 8, 8); - curRes := Rnd(9); - sig^.base := results[curRes]; - params := nil; last := nil; - n := Rnd(8); - for i := 0 to n - 1 do begin - kind := Rnd(5); - if kind = 0 then t := tReal - else if kind = 1 then t := sliceT - else if kind = 2 then t := tI32 - else t := tInt; - p := NewObj(oVar, 0, t); - p^.param := true; - p^.isVar := kind = 4; - if last = nil then params := p else last^.next := p; - last := p; - end; - BeginProc(sig, params); - for i := 0 to 5 do slots[i] := AllocPerm(8, 8); - mask := Rnd(32); - j := Rnd(16); - mask := mask or (j shl XBit); - if Rnd(3) = 0 then mask := 0; - numRegs := 0; numX := 0; - for j := 0 to 4 do - if mask and (1 shl j) <> 0 then begin regs[numRegs] := VarRegs[j]; inc(numRegs) end; - for j := 0 to 3 do - if mask and (1 shl (XBit + j)) <> 0 then begin - xregs[numX] := XVarRegs[j]; inc(numX); - XHome(XVarRegs[j], AllocPerm(8, 8)); - end; - j := 0; - p := params; - while p <> nil do begin - if (p^.typ = tInt) and (not p^.isVar) and (j < numRegs) and Flag then begin - p^.reg := regs[j]; inc(j); - end else if (p^.typ = tReal) and (numX > 0) and Flag then begin - p^.reg := xregs[0]; - end else if Flag then - KeepArrived(p); - p := p^.next; - end; - UseRegs(mask); - line := 1 + Rnd(40); - EnterBody(c, line); - MarkCode(mk); - if Flag then begin - Stmt(2); - Rewind(mk); - Redo(mk); - end; - ns := 2 + Rnd(8); - for i := 1 to ns do Stmt(3); - open := Flag and (sig^.base <> nil); - if (sig^.base <> nil) and (not open) then RetStmt(2); - EndProc(c, open); - writeln('proc ', c, ' lost ', Bit(lost), ' regs ', mask, ' saves ', chunks^[c].saveMask, ' at ', chunks^[c].saveAt); -end; - -function ChunkNameOf(i: longint): longint; -var s: string; -begin - s := 'p' + chr(48 + i div 10) + chr(48 + i mod 10); - ChunkNameOf := Intern(@s[1], 3); -end; - -var - i, c, entry: longint; path: string; links: array[0..1] of TLink; dyn: boolean; -begin - seed := 5; - path := 'lib/Rt.raz'; - if Open(path) <> '' then Fatal('no file'); - dyn := ParamCount >= 1; - listing := true; - curFile := Intern(@path[1], length(path)); - for i := 0 to NumProcs - 1 do begin c := NewChunk(secText, -1, ChunkNameOf(i)); chunks^[c].live := true end; - for i := 0 to NumGlobs - 1 do begin - c := NewChunk(secBss, -1, ChunkNameOf(NumProcs + i)); - SetBss(c, 64, 8); - end; - MakeTypes; - for i := 0 to NumProcs - 1 do GenProc(FirstProc + i); - links[0].chunk := FirstProc; links[0].into := FirstGlob; - links[1].chunk := FirstProc + 1; links[1].into := FirstGlob + 1; - entry := EntryPoint(dyn, nil, nil, FirstProc + 2, FirstProc + 3, links, 2); - writeln('entry ', entry, ' pc ', pc, ' fixups ', numFixups, ' lines ', numLines, ' said ', SaidCount); - for i := 0 to pc - 1 do write(HexStr(code^[i], 2)); - writeln; - for i := 0 to numFixups - 1 do writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend); - for i := 0 to numLines - 1 do writeln('L ', lines^[i].at, ' ', lines^[i].chunk, ' ', lines^[i].line, ' ', lines^[i].col); - List(-1); -end. diff --git a/self/test/GenDump.raz b/self/test/GenDump.raz deleted file mode 100644 index 2528060..0000000 --- a/self/test/GenDump.raz +++ /dev/null @@ -1,732 +0,0 @@ -(* Compiles procedures made by a fixed pseudo-random script of calls to - Gen, valid by construction (an expression pushes its operands, then - operates on them; a statement leaves the stack as it found it), then - prints the bytes, the fixups, the line notes and the listing (raz -S) - of what it made: self/Gen.raz's side of a test against the seed's, - GenDump.pas, which makes and prints the same. With the argument dyn, - the entry point is the dynamic one. *) -module GenDump; -import Out, Fmt, Diag, Scan, Sym, Chunk, X := X64, Gen; - -const - FirstProc = 3; (* chunks 0 to 2 are Gen's own *) - NumProcs = 80; - FirstGlob = FirstProc + NumProcs; - NumGlobs = 4; - Arith: [10]Scan.Sym = [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod, - Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr]; - Cmps: [6]Scan.Sym = [Scan.sEql, Scan.sNeq, Scan.sLss, Scan.sLeq, Scan.sGtr, Scan.sGeq]; - RealOps: [4]Scan.Sym = [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sSlash]; - -var - seed: I64; - slots: [6]I64; (* frame slots of the procedure *) - regs: [5]INT; (* the registers of variables it keeps *) - numRegs: INT; - xregs: [4]INT; (* ... of reals, as numbered from XmmVar *) - numX: INT; - tuple2, tuple3, record3, sliceT: ^Sym.Type; - results: [9]^Sym.Type; - curRes: INT; (* the procedure's result: an index of results *) - -proc rnd(n: INT): INT; -begin - seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; - return INT((seed shr 8) mod I64(n)); -end; - -proc pos: Diag.Pos; -var p: Diag.Pos; -begin - p.f := 0; p.a := rnd(400); p.b := p.a + 1; - return p; -end; - -(* a size of 1, 2, 4 or 8 bytes *) -proc size: INT; -begin - return 1 shl rnd(4); -end; - -(* a slot of the procedure's frame *) -proc slot: I64; -begin - return slots[rnd(6)]; -end; - -proc bit(f: BOOL): INT; -begin - if f then return 1; end; - return 0; -end; - -proc flag: BOOL; -begin - return rnd(2) = 0; -end; - -proc constVal: I64; -var x: INT; r: I64; -begin - x := rnd(1 shl 30); - match rnd(7) of - | 0: r := x mod 10; - | 1: r := -(x mod 100); - | 2: r := I64(1) shl (x mod 20); - | 3: r := x; - | 4: r := I64(x) * 4096 * 4096 * 9 - 7; - | 5: r := -I64(x) * 8; - | else: r := x mod 1000 - 500; - end; - return r; -end; - -proc newObjs(t: ^Sym.Type; n: INT): ^Sym.Obj; -var first, o, last: ^Sym.Obj; i: INT; -begin - first := nil; last := nil; - for i := 0 to n - 1 do - o := Sym.newObj(Sym.oVar, 0, t); - o^.val := 8 * i; - if last = nil then first := o; else last^.next := o; end; - last := o; - end; - return first; -end; - -proc makeTypes; -begin - tuple2 := Sym.newType(Sym.fRecord, 16, 8); - tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := newObjs(Sym.tInt, 2); - tuple3 := Sym.newType(Sym.fRecord, 24, 8); - tuple3^.tuple := true; tuple3^.len := 3; tuple3^.fields := newObjs(Sym.tInt, 3); - record3 := Sym.newType(Sym.fRecord, 24, 8); - record3^.fields := newObjs(Sym.tReal, 3); - sliceT := Sym.newType(Sym.fSlice, 16, 8); - sliceT^.base := Sym.tU8; - results[0] := nil; - results[1] := Sym.tInt; - results[2] := Sym.tReal; - results[3] := sliceT; - results[4] := tuple2; - results[5] := tuple3; - results[6] := Sym.tF32; - results[7] := Sym.tI16; - results[8] := record3; -end; - -(* Variables *) - -(* the address of a variable of the procedure that has one: in the frame, - a chunk, or a slot holding its address *) -proc memAdr: Gen.Adr; -var a: Gen.Adr; c: INT; -begin - c := rnd(3); - if c = 0 then - a.base := Gen.bFrame; a.chunk := 0; a.hi := 0; a.off := slot(); if flag() then a.off := a.off + 8; end; - elsif c = 1 then - a.base := Gen.bGlobal; a.chunk := FirstGlob + rnd(NumGlobs); a.hi := 0; a.off := 8 * rnd(3); - else - a.base := Gen.bSlot; a.chunk := INT(slot()); a.hi := 0; a.off := 8 * rnd(3); - end; - return a; -end; - -(* an address that can go on the stack: frame or chunk *) -proc pushableAdr: Gen.Adr; -var a: Gen.Adr; -begin - a.chunk := 0; a.hi := 0; - if flag() then - a.base := Gen.bFrame; a.off := slot(); if flag() then a.off := a.off + 8; end; - else - a.base := Gen.bGlobal; a.chunk := FirstGlob + rnd(NumGlobs); a.off := 8 * rnd(3); - end; - return a; -end; - -proc regAdr(r: INT): Gen.Adr; -var a: Gen.Adr; -begin - a.base := Gen.bReg; a.chunk := r; a.hi := 0; a.off := 0; - return a; -end; - -proc stackAdr: Gen.Adr; -var a: Gen.Adr; -begin - a.base := Gen.bStack; a.chunk := 0; a.hi := 0; a.off := 8 * rnd(3); - return a; -end; - -proc pushIntVar; -var a: Gen.Adr; sz: INT; c: INT; -begin - sz := size(); - c := rnd(5); - if (c = 0) and (numRegs > 0) then - if flag() then Gen.setInPlace(regs[rnd(numRegs)]); end; - Gen.pushVar(regAdr(regs[rnd(numRegs)]), 8, false, Gen.kWord); - elsif c = 1 then - Gen.pushAdr(pushableAdr()); - a := stackAdr(); - Gen.pushVar(a, sz, flag(), Gen.kWord); - else - a := memAdr(); - Gen.pushVar(a, sz, flag(), Gen.kWord); - end; -end; - -proc intExpr(b: INT); forward; -proc realExpr(k: Gen.Kind; b: INT); forward; -proc callExpr(want, b: INT); forward; - -proc realKind: Gen.Kind; -begin - if flag() then return Gen.kF64; end; - return Gen.kF32; -end; - -proc intExpr(b: INT); -var c, sz, n: INT; sg, f: BOOL; k: Gen.Kind; sy: Scan.Sym; a: Gen.Adr; -begin - if b > 0 then c := rnd(14); else c := rnd(3); end; - match c of - | 0: Gen.pushConst(Gen.kWord, constVal()); - | 1: pushIntVar(); - | 2: pushIntVar(); - | 3, 4, 5: - intExpr(b - 1); intExpr(b - 1); - sy := Arith[rnd(10)]; sz := size(); sg := flag(); - Gen.op(sy, Gen.kWord, sz, sg); - | 6: - if flag() then - intExpr(b - 1); intExpr(b - 1); - sy := Cmps[rnd(6)]; sg := flag(); - Gen.compare(sy, Gen.kWord, sg); - else - k := realKind(); - realExpr(k, b - 1); realExpr(k, b - 1); - sy := Cmps[rnd(6)]; - Gen.compare(sy, k, false); - end; - | 7: - intExpr(b - 1); - n := rnd(4); sz := size(); sg := flag(); - if n = 0 then Gen.neg(Gen.kWord, sz, sg); - elsif n = 1 then Gen.complement(sz, sg); - elsif n = 2 then Gen.notBool(); - else Gen.narrow(sz, sg); end; - | 8: - (* an element of an array in the frame or a chunk *) - intExpr(b - 1); - a := pushableAdr(); - sz := size(); sg := flag(); - n := 10 + rnd(100); - Gen.checkIndex(n, pos()); - Gen.indexArray(a, sz); - a := stackAdr(); a.off := 0; - Gen.pushVar(a, sz, sg, Gen.kWord); - | 9: - (* an element of a slice, in a frame slot or on the stack, or in registers *) - n := rnd(3); - sz := size(); sg := flag(); - if n = 0 then - a := memAdr(); - if a.base = Gen.bGlobal then a.base := Gen.bFrame; end; - intExpr(b - 1); - f := flag(); - Gen.indexSlice(a, sz, f, pos()); - elsif n = 1 then - Gen.pushAdr(pushableAdr()); - intExpr(b - 1); - a := stackAdr(); a.off := 0; - f := flag(); - Gen.indexSlice(a, sz, f, pos()); - else - a.base := Gen.bReg; a.chunk := X.R13; a.hi := X.R14; a.off := 0; - intExpr(b - 1); - f := flag(); - Gen.indexSlice(a, sz, f, pos()); - end; - a := stackAdr(); a.off := 0; - Gen.pushVar(a, sz, sg, Gen.kWord); - | 10: - k := realKind(); - realExpr(k, b - 1); - Gen.realToInt(k); - | 11: callExpr(1, b - 1); - | 12: - (* x + 1, and the offset noted on a word *) - intExpr(b - 1); - Gen.pushConst(Gen.kWord, rnd(100) - 50); - Gen.op(Scan.sPlus, Gen.kWord, 8, false); - | else: - intExpr(b - 1); - Gen.pushConst(Gen.kWord, constVal()); - sy := Arith[rnd(10)]; sz := size(); sg := flag(); - Gen.op(sy, Gen.kWord, sz, sg); - end; -end; - -proc realExpr(k: Gen.Kind; b: INT); -var c, n: INT; sy: Scan.Sym; a: Gen.Adr; k2: Gen.Kind; v: I64; -begin - if b > 0 then c := rnd(9); else c := rnd(3); end; - match c of - | 0: - n := rnd(4); - if n = 0 then v := 3FF0000000000000H; - elsif n = 1 then v := 4000000000000000H; - elsif n = 2 then v := 0; - else v := 3FE0000000000000H; end; - Gen.pushConst(k, v); - | 1: - a := memAdr(); - if k = Gen.kF32 then Gen.pushVar(a, 4, false, k); else Gen.pushVar(a, 8, false, k); end; - | 2: - if numX > 0 then - if flag() then Gen.setInPlace(xregs[rnd(numX)]); end; - Gen.pushVar(regAdr(xregs[rnd(numX)]), 8, false, k); - else - Gen.pushAdr(pushableAdr()); - a := stackAdr(); - Gen.pushVar(a, 8, false, k); - end; - | 3, 4: - realExpr(k, b - 1); realExpr(k, b - 1); - sy := RealOps[rnd(4)]; - Gen.op(sy, k, 8, false); - | 5: - intExpr(b - 1); - Gen.intToReal(k, flag()); - | 6: - realExpr(k, b - 1); - Gen.neg(k, 8, false); - | 7: - if k = Gen.kF32 then k2 := Gen.kF64; else k2 := Gen.kF32; end; - realExpr(k2, b - 1); - Gen.realToReal(k2); - | else: callExpr(2, b - 1); - end; -end; - -(* A call of one of the procedures, with arguments of all kinds. want: 0 - for a statement, any result; 1 an integer is left on the stack, 2 a - real. *) -proc callExpr(want, b: INT); -var - c: Gen.CallInfo; sig: ^Sym.Type; i, n, kind, r, ni: INT; k: Gen.Kind; -begin - sig := Sym.newType(Sym.fProc, 8, 8); - sig^.variadic := rnd(5) = 0; - if want = 1 then - r := rnd(5); - if r = 0 then sig^.base := Sym.tBool; - elsif r = 1 then sig^.base := Sym.tI8; - elsif r = 2 then sig^.base := Sym.tU32; - elsif r = 3 then sig^.base := tuple2; - else sig^.base := Sym.tInt; end; - elsif want = 2 then - if flag() then sig^.base := Sym.tReal; else sig^.base := Sym.tF32; end; - else - sig^.base := results[rnd(9)]; - end; - c.sig := sig; c.param := nil; c.obj := nil; c.ext := rnd(4) = 0; - c.n := 0; c.target := 0; - c.chunk := FirstProc + rnd(NumProcs); - if rnd(5) = 0 then c.chunk := -1; c.ext := false; c.target := slot(); end; - n := rnd(8); - for i := 0 to n - 1 do - kind := rnd(4); - if kind = 0 then - k := realKind(); - realExpr(k, b); - c.isF[c.n] := true; c.pair[c.n] := false; - INC(c.n); - elsif kind = 1 then - intExpr(b); intExpr(b); - c.isF[c.n] := false; c.pair[c.n] := true; - c.isF[c.n + 1] := false; c.pair[c.n + 1] := false; - INC(c.n, 2); - else - intExpr(b); - c.isF[c.n] := false; c.pair[c.n] := false; - INC(c.n); - end; - end; - Gen.call(c); - (* what comes back: a value or two, or nothing, or a temporary *) - ni := 0; - if sig^.base # nil then - if sig^.base^.form = Sym.fSlice then ni := 0; - elsif sig^.base = tuple2 then ni := 2; - elsif Sym.behindPointer(sig^.base) then ni := 0; - else ni := 1; end; - end; - if want = 0 then - for i := 1 to ni do Gen.drop(); end; - elsif ni = 2 then - Gen.drop(); (* the second; the first is the value *) - end; -end; - -(* A condition, left as a BOOL on the stack *) -proc boolExpr(b: INT); -var sy: Scan.Sym; sg: BOOL; -begin - if flag() then - intExpr(b); intExpr(b); - sy := Cmps[rnd(6)]; sg := flag(); - Gen.compare(sy, Gen.kWord, sg); - else - intExpr(b); - end; -end; - -proc stmt(b: INT); forward; - -(* a variable assigned the value on top: its address, if on the stack, - having been pushed first *) -proc assign(b: INT); -var a: Gen.Adr; c, sz: INT; k: Gen.Kind; -begin - c := rnd(6); - sz := size(); - if c = 0 then - a := memAdr(); - intExpr(b); - Gen.popVar(a, sz); - elsif c = 1 then - Gen.pushAdr(pushableAdr()); - a := stackAdr(); - intExpr(b); - Gen.popVar(a, sz); - elsif (c = 2) and (numRegs > 0) then - a := regAdr(regs[rnd(numRegs)]); - Gen.setInPlace(a.chunk); - Gen.pushVar(a, 8, false, Gen.kWord); - intExpr(b); - Gen.op(Arith[rnd(3)], Gen.kWord, 8, false); - Gen.popVar(a, 8); - elsif (c = 3) and (numX > 0) then - k := realKind(); - a := regAdr(xregs[rnd(numX)]); - realExpr(k, b); - Gen.popVar(a, 8); - elsif c = 4 then - k := realKind(); - a := memAdr(); - realExpr(k, b); - if k = Gen.kF32 then Gen.popVar(a, 4); else Gen.popVar(a, 8); end; - else - a := memAdr(); - Gen.pushConst(Gen.kWord, constVal()); - Gen.popVar(a, sz); - end; -end; - -proc retStmt(b: INT); -var i: INT; -begin - if curRes = 1 then intExpr(b); - elsif curRes = 7 then intExpr(b); - elsif curRes = 2 then realExpr(Gen.kF64, b); - elsif curRes = 6 then realExpr(Gen.kF32, b); - elsif (curRes = 3) or (curRes = 4) then intExpr(b); intExpr(b); - elsif curRes = 5 then - for i := 0 to 2 do intExpr(b); Gen.resultTo(8 * i, 8); end; - elsif curRes = 8 then - Gen.pushAdr(pushableAdr()); - Gen.copyResult(0, 24); - end; - Gen.returnJump(); -end; - -proc stmt(b: INT); -var - c, n, lo, i, start, saved, sz, tmp: INT; L, E, S, fj, tj: INT; a, a2: Gen.Adr; sy: Scan.Sym; sg: BOOL; - mk: I64; f: BOOL; -begin - mk := Gen.tempMark(); - if b <= 0 then c := rnd(4); else c := rnd(22); end; - match c of - | 0, 1, 2, 3: assign(b); - | 4: - (* if cond then s end *) - L := Gen.NoLabel; - boolExpr(b); - Gen.jumpIf(L, false); - stmt(b - 1); - Gen.fix(L); - | 5: - (* while cond do s end *) - L := Gen.NoLabel; - Gen.alignLoop(); - start := Chunk.pc; - boolExpr(b); - Gen.jumpIf(L, false); - stmt(b - 1); - Gen.jumpBack(start); - Gen.fix(L); - | 6: - (* if a < b then s end, with a jump on the comparison *) - L := Gen.NoLabel; - intExpr(b); intExpr(b); - sy := Cmps[rnd(6)]; sg := flag(); - if flag() then Gen.jumpCmp(sy, sg, L); else Gen.jumpOut(sy, sg, L); end; - stmt(b - 1); - Gen.fix(L); - | 7: - (* v := a < b and c, a condition worked out into a BOOL *) - fj := Gen.NoLabel; tj := Gen.NoLabel; - intExpr(b); intExpr(b); - sy := Cmps[rnd(6)]; sg := flag(); - Gen.condValue(sy, sg, fj, tj); - a := memAdr(); - Gen.popVar(a, 1); - | 8: callExpr(0, b); - | 9: - (* a match through a jump table *) - a := memAdr(); - if a.base = Gen.bSlot then a.base := Gen.bFrame; a.off := slots[0]; end; - intExpr(b); - Gen.popVar(a, 8); - E := Gen.NoLabel; - n := 2 + rnd(4); lo := rnd(5) - 2; - if flag() then S := Gen.NoLabel; else S := Chunk.pc; end; - start := Gen.jumpTable(a.off, lo, n, S, E); - for i := 0 to n - 1 do Gen.tableEntry(start, Chunk.pc + 4 * (n - i)); end; - for i := 0 to n - 1 do - stmt(b - 1); - end; - Gen.fix(E); - | 10: - Gen.pushAdr(pushableAdr()); Gen.pushAdr(pushableAdr()); - n := 1 + rnd(150); lo := 8 * rnd(3); - Gen.copyBlock(n, lo); - | 11: - Gen.pushAdr(pushableAdr()); - a := memAdr(); - if flag() and (numRegs > 1) then - a.base := Gen.bReg; a.chunk := regs[0]; a.hi := regs[1]; a.off := 0; - end; - n := 1 + rnd(150); - Gen.copyTo(a, n); - | 12: - a := memAdr(); - n := 1 + rnd(100); - Gen.zeroVar(a, n); - | 13: - (* a slice of an array, of a slice, of a pointer *) - tmp := INT(Gen.allocTemp(16, 8)); - n := rnd(3); - sz := size(); sg := flag(); - if n = 0 then - a := pushableAdr(); - Gen.pushAdr(a); intExpr(b); intExpr(b); - a := stackAdr(); a.off := 0; - f := flag(); n := 10 + rnd(50); - Gen.slice(a, f, n, sz, tmp, sg, pos()); - elsif n = 1 then - a := memAdr(); - if a.base = Gen.bGlobal then a.base := Gen.bFrame; end; - intExpr(b); intExpr(b); - Gen.slice(a, false, 0, sz, tmp, sg, pos()); - else - intExpr(b); intExpr(b); intExpr(b); - Gen.slicePtr(sz, tmp, sg, pos()); - end; - | 14: - a.off := slot(); a2.off := slot(); sz := size(); f := flag(); - Gen.copySlice(a.off, a2.off, sz, f, pos()); - | 15: - n := rnd(4); sz := size(); sg := flag(); - if n = 0 then - Gen.pushAdr(pushableAdr()); intExpr(b); - f := flag(); - Gen.incDec(sz, sg, f); - elsif (n = 1) and (numRegs > 0) then - intExpr(b); - Gen.incDecReg(regs[0], sz, sg, flag()); - elsif n = 2 then - intExpr(b); - n := 3 + rnd(6); lo := FirstGlob + rnd(NumGlobs); - Gen.checkEnum(n, lo, pos()); - Gen.drop(); - else - intExpr(b); - n := rnd(8000); - Gen.checkNil(n, pos()); - Gen.drop(); - end; - | 16: - n := rnd(3); - if n = 0 then - a.off := slot(); a2.off := slot(); n := rnd(4); f := flag(); - Gen.compareSeq(a.off, a2.off, n, f); - Gen.drop(); - elsif n = 1 then - intExpr(b); - Gen.errorText(Gen.allocTemp(16, 8)); - else - intExpr(b); - n := 1 + rnd(200); - Gen.zeroNew(n); - Gen.drop(); - end; - | 17: - n := rnd(3); - if n = 0 then - intExpr(b); intExpr(b); intExpr(b); - Gen.atomic(Sym.bCas); - elsif n = 1 then - intExpr(b); intExpr(b); - Gen.atomic(Sym.bXchg); - else - intExpr(b); intExpr(b); - Gen.atomic(Sym.bXadd); - end; - Gen.drop(); - | 18: - n := rnd(7); - for i := 1 to n do intExpr(b); end; - Gen.sysCall(n); - Gen.drop(); - if flag() then Gen.fence(); end; - | 19: - (* defer s *) - L := Gen.NoLabel; - start, saved := Gen.deferBegin(L); - stmt(b - 1); - Gen.deferEnd(L, saved); - Gen.runDefer(start); - | 20: - if curRes # 0 then retStmt(b); else assign(b); end; - | else: - if curRes # 0 then - Gen.tryAlign(); - Gen.tryReturn(slot()); - else - assign(b); - end; - end; - Gen.releaseTemps(mk); -end; - -(* Each statement may be preceded by a few that are made and taken back, - as the parser does when it compiles a body a second time *) -proc genProc(c: INT); -var - sig: ^Sym.Type; params, p, last: ^Sym.Obj; i, n, kind, mask, j, ns, line: INT; t: ^Sym.Type; - mk: Gen.CodeMark; open: BOOL; -begin - sig := Sym.newType(Sym.fProc, 8, 8); - curRes := rnd(9); - sig^.base := results[curRes]; - params := nil; last := nil; - n := rnd(8); - for i := 0 to n - 1 do - kind := rnd(5); - if kind = 0 then t := Sym.tReal; - elsif kind = 1 then t := sliceT; - elsif kind = 2 then t := Sym.tI32; - else t := Sym.tInt; end; - p := Sym.newObj(Sym.oVar, 0, t); - p^.param := true; - p^.isVar := kind = 4; - if last = nil then params := p; else last^.next := p; end; - last := p; - end; - Gen.beginProc(sig, params); - for i := 0 to 5 do slots[i] := Gen.allocPerm(8, 8); end; - mask := rnd(32); - j := rnd(16); - mask := mask | (j shl Gen.XBit); - if rnd(3) = 0 then mask := 0; end; - numRegs := 0; numX := 0; - for j := 0 to 4 do - if (mask & (1 shl j)) # 0 then regs[numRegs] := Gen.VarRegs[j]; INC(numRegs); end; - end; - for j := 0 to 3 do - if (mask & (1 shl (Gen.XBit + j))) # 0 then - xregs[numX] := Gen.XVarRegs[j]; INC(numX); - Gen.xHome(Gen.XVarRegs[j], Gen.allocPerm(8, 8)); - end; - end; - (* some parameters live in registers: a register variable's, or kept - where they arrived *) - j := 0; - p := params; - while p # nil do - if (p^.typ = Sym.tInt) and (not p^.isVar) and (j < numRegs) and flag() then - p^.reg := regs[j]; INC(j); - elsif (p^.typ = Sym.tReal) and (numX > 0) and flag() then - p^.reg := xregs[0]; - elsif flag() then - Gen.keepArrived(p); - end; - p := p^.next; - end; - Gen.useRegs(mask); - line := 1 + rnd(40); - Gen.enterBody(c, line); - Gen.markCode(mk); - (* a body made and taken back *) - if flag() then - stmt(2); - Gen.rewind(mk); - Gen.redo(mk); (* the jumps to the exit went with the code *) - end; - ns := 2 + rnd(8); - for i := 1 to ns do stmt(3); end; - open := flag() and (sig^.base # nil); - if (sig^.base # nil) and (not open) then retStmt(2); end; - _ := Gen.endProc(c, open); - Fmt.print("proc {} lost {} regs {} saves {} at {}\n", [Fmt.int(c), Fmt.int(bit(Gen.lost)), Fmt.int(mask), - Fmt.int(Chunk.chunks[c].saveMask), Fmt.int(Chunk.chunks[c].saveAt)]); -end; - -(* The name p0, p1, ... of chunk i, interned *) -proc chunkNameOf(i: INT): INT; -var s: [3]U8; -begin - s[0] := 'p'; s[1] := U8(48 + i div 10); s[2] := U8(48 + i mod 10); - return Scan.intern(ADR(s[0]), 3); -end; - -proc main*; -var i, c: INT; path: []U8; links: [2]Gen.Link; entry: INT; dyn: BOOL; -begin - seed := 5; - path := "lib/Rt.raz"; - if LEN(Scan.open(path)) # 0 then Diag.fatal("no file"); end; - dyn := ARGC > 1; - X.setListing(true); - Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path))); - for i := 0 to NumProcs - 1 do c := Chunk.newChunk(Chunk.secText, -1, chunkNameOf(i)); Chunk.setLive(c); end; - for i := 0 to NumGlobs - 1 do - c := Chunk.newChunk(Chunk.secBss, -1, chunkNameOf(NumProcs + i)); - Chunk.setBss(c, 64, 8); - end; - makeTypes(); - for i := 0 to NumProcs - 1 do genProc(FirstProc + i); end; - links[0].chunk := FirstProc; links[0].into := FirstGlob; - links[1].chunk := FirstProc + 1; links[1].into := FirstGlob + 1; - entry := Gen.entryPoint(dyn, nil, nil, FirstProc + 2, FirstProc + 3, links, 2); - Fmt.print("entry {} pc {} fixups {} lines {} said {}\n", [Fmt.int(entry), Fmt.int(Chunk.pc), - Fmt.int(Chunk.numFixups), Fmt.int(Chunk.numLines), Fmt.int(X.saidCount())]); - for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end; - Out.ln; - for i := 0 to Chunk.numFixups - 1 do - Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]); - end; - for i := 0 to Chunk.numLines - 1 do - Fmt.print("L {} {} {} {}\n", [Fmt.int(Chunk.lines[i].at), Fmt.int(Chunk.lines[i].chunk), - Fmt.int(Chunk.lines[i].line), Fmt.int(Chunk.lines[i].col)]); - end; - X.list(-1); -end; - -end GenDump. diff --git a/self/test/ItemDump.pas b/self/test/ItemDump.pas deleted file mode 100644 index 627ad28..0000000 --- a/self/test/ItemDump.pas +++ /dev/null @@ -1,665 +0,0 @@ -{ Drives item with a fixed pseudo-random script of operands and - operations, with mistakes among them, and prints what each step gave - (the item, or that it failed, whose message goes to standard error), - then the bytes, fixups, line notes and listing (raz -S) of the code - it made: the seed's side of a test of self/Item.raz, whose - ItemDump.raz does and prints the same. The argument, a number, - changes the script. A run ends at the 20th error, as a compile does, - so several scripts are run. } -program itemdump; -{$mode objfpc}{$H-} -uses diag, scan, sym, chunk, x64, gen, item; - -const - FirstProc = 3; - NumProcs = 30; - FirstGlob = FirstProc + NumProcs; - NumGlobs = 4; - Steps = 14; - YInt = 0; YI64 = 1; YI32 = 2; YU8 = 3; YU16 = 4; YU32 = 5; YU64 = 6; YBool = 7; - YReal = 8; YF32 = 9; YI8 = 10; YEnum = 11; YSet = 12; YPtr = 13; YVptr = 14; - YPtrArr = 15; YArr = 16; YArrU8 = 17; YSlice = 18; YBytes = 19; YRec = 20; - YPacked = 21; YVariant = 22; YProc0 = 23; YProc1 = 24; YProc2 = 25; - YPtrRec = 26; YErr = 27; YVrec = 28; YVarr = 29; - NumT = 30; - IntTypes: array[0..7] of longint = (YInt, YI64, YI32, YU8, YU16, YU32, YU64, YI8); - Ops: array[0..19] of TSym = (sPlus, sMinus, sTimes, sDiv, sMod, - sAmp, sBar, sXor, sShl, sShr, - sEql, sNeq, sLss, sLeq, sGtr, sGeq, - sSlash, sIn, sPlus, sMinus); - Cmps: array[0..5] of TSym = (sEql, sNeq, sLss, sLeq, sGtr, sGeq); - -var - Letters: string[9]; - seed: int64; - ty: array[0..NumT - 1] of PType; - vars: array[0..NumT - 1] of PObj; - procs: array[0..5] of PObj; - strs: array[0..2] of PObj; - arrConst, typeObj, builtinObj, caseObj: PObj; - mod0, mod1: PModule; - tuple2, record3, packedR, variantT: PType; - results: array[0..8] of PType; - curRes: longint; - call: TCall; - jb: jmp_buf; - gK: longint; - gX: TItem; - gOk: boolean; - -function Rnd(n: longint): longint; -begin - seed := (seed * 1103515245 + 12345) and $7FFFFFFF; - Rnd := (seed shr 8) mod n; -end; - -function Flag: boolean; -begin - Flag := Rnd(2) = 0; -end; - -function Bit(f: boolean): longint; -begin - if f then Bit := 1 else Bit := 0; -end; - -function Pos: TPos; -var p: TPos; -begin - p.f := 0; p.a := Rnd(400); p.b := p.a + 1 + Rnd(12); - Pos := p; -end; - -function ConstVal: int64; -var x: longint; r: int64; -begin - x := Rnd(1 shl 30); - case Rnd(7) of - 0: r := x mod 10; - 1: r := -(x mod 100); - 2: r := int64(1) shl (x mod 20); - 3: r := x; - 4: r := int64(x) * 4096 * 4096 * 9 - 7; - 5: r := -int64(x) * 8; - else r := x mod 1000 - 500; - end; - ConstVal := r; -end; - -function InternStr(const s: shortstring): longint; -begin - InternStr := Intern(@s[1], length(s)); -end; - -{ A name v00, v01, ... , interned } -function NameOf(i: longint): longint; -var s: string[3]; -begin - s := 'v' + chr(48 + i div 10) + chr(48 + i mod 10); - NameOf := Intern(@s[1], 3); -end; - -function NewObjs(cls: TClass; t: PType; n: longint; step: int64; at: longint): PObj; -var first, o, last: PObj; i: longint; -begin - first := nil; last := nil; - for i := 0 to n - 1 do begin - o := NewObj(cls, NameOf(at + i), t); - o^.val := step * i; - if last = nil then first := o else last^.next := o; - last := o; - end; - NewObjs := first; -end; - -function ProcType(res: PType; params: PObj; n: longint): PType; -var t: PType; -begin - t := NewType(fProc, 8, 8); - t^.base := res; - t^.fields := params; - t^.len := n; - ProcType := t; -end; - -function Param(t: PType; isVar: boolean; at: longint): PObj; -var o: PObj; -begin - o := NewObj(oVar, NameOf(at), t); - o^.param := true; - o^.isVar := isVar; - Param := o; -end; - -procedure MakeTypes; -var t: PType; p, q, r: PObj; i: longint; -begin - ty[YInt] := tInt; ty[YI64] := tI64; ty[YI32] := tI32; ty[YU8] := tU8; - ty[YU16] := tU16; ty[YU32] := tU32; ty[YU64] := tU64; ty[YBool] := tBool; - ty[YReal] := tReal; ty[YF32] := tF32; ty[YI8] := tI8; ty[YErr] := tError; - ty[YBytes] := tBytes; - t := NewType(fEnum, 1, 1); t^.len := 5; ty[YEnum] := t; - t := NewType(fSet, 8, 8); t^.len := 5; t^.base := ty[YEnum]; ty[YSet] := t; - t := NewType(fPtr, 8, 8); t^.base := tI64; ty[YPtr] := t; - t := NewType(fPtr, 8, 8); t^.base := tI64; t^.vol := true; ty[YVptr] := t; - t := NewType(fArray, 48, 8); t^.base := tI64; t^.len := 6; ty[YArr] := t; - t := NewType(fPtr, 8, 8); t^.base := ty[YArr]; ty[YPtrArr] := t; - t := NewType(fPtr, 8, 8); t^.base := ty[YArr]; t^.vol := true; ty[YVarr] := t; - t := NewType(fArray, 8, 1); t^.base := tU8; t^.len := 8; ty[YArrU8] := t; - t := NewType(fSlice, 16, 8); t^.base := tI64; ty[YSlice] := t; - record3 := NewType(fRecord, 24, 8); - p := NewObj(oField, NameOf(40), tI64); p^.val := 0; - q := NewObj(oField, NameOf(41), tReal); q^.val := 8; p^.next := q; - r := NewObj(oField, NameOf(42), tI32); r^.val := 16; q^.next := r; - record3^.fields := p; - ty[YRec] := record3; - t := NewType(fPtr, 8, 8); t^.base := record3; ty[YPtrRec] := t; - t := NewType(fPtr, 8, 8); t^.base := record3; t^.vol := true; ty[YVrec] := t; - packedR := NewType(fRecord, 53, 1); - packedR^.packd := true; - p := NewObj(oField, NameOf(43), tU8); p^.val := 0; - q := NewObj(oField, NameOf(44), tI32); q^.val := 1; p^.next := q; - r := NewObj(oField, NameOf(46), ty[YArr]); r^.val := 5; q^.next := r; - packedR^.fields := p; - ty[YPacked] := packedR; - variantT := NewType(fVariant, 16, 8); - ty[YVariant] := variantT; - tuple2 := NewType(fRecord, 16, 8); - tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := NewObjs(oVar, tInt, 2, 8, 45); - p := Param(tInt, false, 46); p^.next := Param(tReal, false, 47); - ty[YProc0] := ProcType(tInt, p, 2); - ty[YProc1] := ProcType(nil, nil, 0); - p := Param(tI64, true, 48); p^.next := Param(ty[YSlice], false, 49); - ty[YProc2] := ProcType(tuple2, p, 2); - results[0] := nil; results[1] := tInt; results[2] := tReal; results[3] := ty[YSlice]; - results[4] := tuple2; results[5] := record3; results[6] := tF32; results[7] := tI16; - results[8] := ty[YBytes]; - for i := 0 to NumT - 1 do - if ty[i] = nil then Fatal('a type is missing'); -end; - -procedure MakeObjs; -var i, c: longint; o: PObj; -begin - New(mod0); mod0^.name := InternStr('Zero'); - New(mod1); mod1^.name := InternStr('Other'); - curModule := mod0; - for i := 0 to 5 do begin - o := NewObj(oProc, NameOf(50 + i), ty[YProc0 + i mod 3]); - o^.chunk := FirstProc + Rnd(NumProcs); - o^.ext := i >= 4; - o^.isCode := i = 3; - procs[i] := o; - end; - for i := 0 to 2 do begin - o := NewObj(oConst, NameOf(60 + i), tStr); - o^.val := 2 + 3 * i; - c := NewChunk(secRodata, -1, -1); - SetData(c, @Letters[1], o^.val + 1, 1); - o^.chunk := c; - strs[i] := o; - end; - arrConst := NewObj(oConst, NameOf(63), ty[YArr]); - arrConst^.chunk := NewChunk(secRodata, -1, -1); - SetData(arrConst^.chunk, @Letters[1], 8, 8); - typeObj := NewObj(oType, NameOf(64), ty[YRec]); - builtinObj := NewObj(oBuiltin, NameOf(65), tNone); - caseObj := NewObj(oCase, NameOf(66), variantT); - caseObj^.val := 3; - caseObj^.fields := NewObjs(oField, tInt, 2, 8, 67); - caseObj^.fields^.val := 8; -end; - -procedure MakeVars; -var i, k: longint; o: PObj; t: PType; -begin - for i := 0 to NumT - 1 do begin - t := ty[i]; - o := NewObj(oVar, NameOf(i), t); - o^.lev := 1; - k := Rnd(9); - if k = 2 then begin - o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs); - end else if k = 3 then begin - o^.ind := true; o^.val := AllocPerm(8, 8); o^.off := 8 * Rnd(3); - end else if k = 4 then begin - if (t^.form in [fInt, fPtr]) and (t^.size = 8) then - o^.reg := VarRegs[Rnd(5)] - else if t^.form = fReal then - o^.reg := XVarRegs[Rnd(4)] - else if t^.form = fSlice then begin - o^.reg := VarRegs[Rnd(3)]; o^.reg2 := VarRegs[3 + Rnd(2)]; - end; - if o^.reg = 0 then o^.val := AllocPerm(t^.size, 8); - end else if k = 5 then begin - o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs); o^.module := mod1; - end else if k = 6 then begin - o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs); o^.ext := true; - end else - o^.val := AllocPerm(t^.size + 8, 8); - vars[i] := o; - end; -end; - -{ Operands } - -function IntType: PType; -begin - IntType := ty[IntTypes[Rnd(8)]]; -end; - -procedure VarItem(var x: TItem; t: PType); -var i, k: longint; -begin - k := Rnd(NumT); - for i := 0 to NumT - 1 do - if ty[i] = t then k := i; - FillChar(x, SizeOf(x), 0); - x.pos := Pos; - MakeItem(x, vars[k]); -end; - -procedure Operand(var x: TItem; t: PType); -var k: longint; r: double; v: int64; -begin - FillChar(x, SizeOf(x), 0); - x.pos := Pos; - if t = nil then begin - case Rnd(14) of - 0: MakeConst(x, tConst, ConstVal); - 1: MakeConst(x, tConst, ConstVal mod 200); - 2: begin t := IntType; v := ConstVal mod 100; MakeConst(x, t, v) end; - 3: begin r := (ConstVal mod 1000) / 8.0; MakeReal(x, r) end; - 4: MakeConst(x, tBool, Rnd(2)); - 5: MakeItem(x, strs[Rnd(3)]); - 6: MakeConst(x, tNil, 0); - 7: MakeItem(x, procs[Rnd(6)]); - 8: begin - if Rnd(4) = 0 then begin - case Rnd(3) of - 0: MakeItem(x, typeObj); - 1: MakeItem(x, builtinObj); - else MakeItem(x, caseObj); - end; - end else - MakeItem(x, arrConst); - end; - 13: begin MakeItem(x, vars[Rnd(NumT)]); Value(x) end; - else VarItem(x, ty[Rnd(NumT)]); - end; - exit; - end; - k := Rnd(10); - if IsInt(t) then begin - if k < 3 then begin MakeConst(x, tConst, ConstVal mod 100); exit end; - if k = 3 then begin MakeConst(x, t, ConstVal mod 100); exit end; - end else if t^.form = fReal then begin - if k < 3 then begin r := (ConstVal mod 1000) / 8.0; MakeReal(x, r); exit end; - end else if t^.form = fBool then begin - if k < 3 then begin MakeConst(x, tBool, Rnd(2)); exit end; - end else if t^.form = fPtr then begin - if k < 2 then begin MakeConst(x, tNil, 0); exit end; - end else if (t^.form = fSlice) and (t^.base = tU8) then begin - if k < 3 then begin MakeItem(x, strs[Rnd(3)]); exit end; - end; - VarItem(x, t); -end; - -procedure CondItem(var x: TItem); -var y: TItem; L: longint; op: TSym; t: PType; -begin - t := IntType; - op := Cmps[Rnd(6)]; - Operand(x, t); - Op1(op, x, L); - Operand(y, t); - Op2(op, x, y, L); -end; - -procedure Place(var x: TItem); -var i, k: longint; f: PObj; y, lo, hi: TItem; -begin - VarItem(x, ty[Rnd(NumT)]); - for i := 1 to 3 do begin - if Rnd(3) <> 0 then begin - k := Rnd(6); - if (k = 0) or (x.typ^.form = fPtr) then - Deref(x) - else if x.typ^.form = fRecord then begin - f := x.typ^.fields; - k := Rnd(3); - while (k > 0) and (f^.next <> nil) do begin f := f^.next; dec(k) end; - Field(x, f); - end else if x.typ^.form in [fArray, fSlice, fStr] then begin - IndexPrep(x); - if k < 4 then begin - Operand(y, IntType); - Index(x, y); - end else begin - Operand(lo, IntType); - SliceLo(lo); - Operand(hi, IntType); - Slice(x, lo, hi); - end; - end; - end; - end; -end; - -procedure Dump(var x: TItem); -var name: shortstring; flags: longint; -begin - name := '-'; - if x.typ <> nil then name := TypeName(x.typ); - flags := Bit(x.vol) + 2 * Bit(x.isVar) + 4 * Bit(x.odd) + 8 * Bit(x.ro) + 16 * Bit(x.deref); - write('I ', ord(x.mode), ' ', name, ' ', ord(x.rel), ' ', Bit(x.relSigned), ' ', x.fj, ' ', x.tj, ' ', x.val); - writeln(' ', ord(x.base), ' ', x.chunk, ' ', x.off, ' ', flags, ' depth ', depth, ' pushed ', pushed); -end; - -procedure DoCall(var x: TItem); -var f, a: TItem; p: PObj; n: longint; -begin - FillChar(f, SizeOf(f), 0); - f.pos := Pos; - if Rnd(5) = 0 then MakeItem(f, vars[YProc0 + Rnd(3)]) - else MakeItem(f, procs[Rnd(6)]); - BeginCall(call, f); - p := call.param; - n := Rnd(4) - 1; - while (p <> nil) or (n > 0) do begin - if p <> nil then begin - if p^.isVar and (Rnd(2) = 0) then begin - VarItem(a, ty[YVptr]); - Deref(a); - end else if Rnd(6) = 0 then Operand(a, nil) - else Operand(a, p^.typ); - p := p^.next; - end else begin - Operand(a, nil); - n := n - 1; - end; - PassArg(call, a); - if (p = nil) and (n < 0) then n := 0; - if (p <> nil) and (n < 0) and (Rnd(4) = 0) then begin p := nil; n := 0 end; - end; - EndCall(call, x); -end; - -procedure Binary(var x: TItem); -var y: TItem; L, M: longint; op: TSym; t: PType; -begin - L := NoLabel; - M := NoLabel; - op := Ops[Rnd(20)]; - case Rnd(8) of - 0, 1: t := IntType; - 2: t := ty[YReal + Rnd(2)]; - 3: t := ty[YBool]; - 4: t := ty[YEnum + Rnd(2)]; - else t := ty[Rnd(NumT)]; - end; - if Rnd(6) = 0 then begin - if Flag then op := sAnd else op := sOr; - CondItem(x); - Op1(op, x, L); - CondItem(y); - end else if op = sIn then begin - Operand(x, ty[YEnum]); - Op1(op, x, L); - Operand(y, ty[YSet]); - end else begin - Operand(x, t); - Op1(op, x, L); - if Rnd(5) = 0 then Operand(y, nil) else Operand(y, t); - end; - Op2(op, x, y, L); - if (x.mode = mCond) and (Rnd(3) <> 0) then begin - if Flag then CondJump(x, M) else CondJumpTrue(x, M); - Fix(M); - x.mode := mNone; - end; -end; - -procedure Unary(var x: TItem); -begin - Operand(x, nil); - case Rnd(3) of - 0: Neg(x); - 1: NotOp(x); - else Complement(x); - end; -end; - -procedure DoMatch(var x: TItem); -var p, lo, hi: int64; L: longint; -begin - L := NoLabel; - case Rnd(3) of - 0: VarItem(x, ty[YVariant]); - 1: VarItem(x, ty[YEnum]); - else Operand(x, nil); - end; - p := MatchBegin(x); - MatchTag(p, ConstVal mod 10, L); - lo := ConstVal mod 10; - hi := ConstVal mod 10 + 10; - MatchRange(p, lo, hi, L); - MatchRange(p, 3, 3, L); - Fix(L); -end; - -procedure DoFor(var x: TItem); -var o: PObj; lim: TItem; step: int64; exitL: longint; -begin - o := vars[IntTypes[Rnd(8)]]; - step := ConstVal mod 5; - if step = 0 then step := 1; - if Rnd(2) = 0 then step := -step; - FillChar(lim, SizeOf(lim), 0); - lim.pos := Pos; - MakeConst(lim, o^.typ, ConstVal mod 50); - exitL := NoLabel; - ForStep(o, step); - ForNext(o, lim, step, exitL, pc, pc); - Fix(exitL); - x := lim; -end; - -procedure DoMisc(var x: TItem); -var y: TItem; -begin - case Rnd(5) of - 0: begin - Place(x); - Address(x); - Operand(y, x.typ); - IncDec(x, y, Flag); - end; - 1: begin - Place(x); - Pin(x); - end; - 2: begin - Place(x); - CopyDest(x); - Place(y); - CopyFrom(x, y); - end; - 3: begin - Operand(x, nil); - MakeStr(y); - Coerce(y, ty[YBytes]); - end; - else begin - Operand(x, nil); - NilTest(x); - UsesReals(x.pos); - Discard(x); - end; - end; -end; - -procedure DoTemp(var x: TItem); -var a: TItem; c, h, n: longint; f: PObj; -begin - FillChar(x, SizeOf(x), 0); - x.pos := Pos; - case Rnd(5) of - 0: ZeroTemp(x, ty[YVariant]); - 1: begin - Construct(x, caseObj); - f := caseObj^.fields; - Operand(a, f^.typ); - SetField(x, f, a); - end; - 2: begin - ZeroTemp(x, ty[YRec]); - f := ty[YRec]^.fields; - if Flag then f := f^.next; - Operand(a, f^.typ); - SetField(x, f, a); - end; - 3: begin - Operand(a, nil); - h := Rnd(3) - 1; - n := Rnd(3) - 1; - c := ErrorChunk(a, h, n); - MakeConst(x, tError, int64(c) + 1); - end; - else begin - Operand(x, ty[YErr]); - Msg(x); - end; - end; -end; - -procedure DoReturn(var x: TItem); -var f: PObj; -begin - if (curRes = 4) and Flag then begin - f := tuple2^.fields; - if Flag then f := f^.next; - if Flag then begin - Operand(x, f^.typ); - ReturnField(f, x); - exit; - end; - DoCall(x); - ReturnAll(x); - exit; - end; - if Rnd(4) = 0 then begin ReturnNone; exit end; - Operand(x, results[curRes]); - ReturnValue(x); -end; - -procedure Step(k: longint; var x: TItem); -var y: TItem; -begin - FillChar(x, SizeOf(x), 0); - case k of - 0: begin Operand(x, nil); Value(x) end; - 1: begin Operand(x, nil); Address(x) end; - 2: begin Operand(x, nil); Coerce(x, ty[Rnd(NumT)]) end; - 3: begin Operand(x, nil); CoerceExact(x, IntType, '') end; - 4: begin - Place(x); - Operand(y, x.typ); - Assign(x, y); - end; - 5: Unary(x); - 6: Binary(x); - 7: begin Operand(x, nil); Convert(x, ty[Rnd(NumT)]) end; - 8: Place(x); - 9: DoCall(x); - 10: DoMatch(x); - 11: DoFor(x); - 12: DoMisc(x); - 13: DoTemp(x); - 14: DoReturn(x); - else Binary(x); - end; -end; - -{ A step, and what it leaves, each a recovery point as the parser's - statements are } -procedure RunStep; -begin - gOk := false; - recovery := @jb; - if setjmp(jb) = 0 then begin - Step(gK, gX); - gOk := true; - end; - recovery := nil; -end; - -procedure RunDiscard; -begin - recovery := @jb; - if setjmp(jb) = 0 then Discard(gX); - recovery := nil; -end; - -procedure GenProc(c: longint); -var sig: PType; i, line: longint; -begin - curRes := Rnd(9); - sig := ProcType(results[curRes], nil, 0); - BeginProc(sig, nil); - for i := 0 to 5 do AllocPerm(8, 8); - MakeVars; - checks := Flag; - line := 1 + Rnd(40); - EnterBody(c, line); - for i := 1 to Steps do begin - if errors >= 19 then break; - gK := Rnd(17); - demoted := false; - RunStep; - if not gOk then - writeln('S ', c, ' ', gK, ' failed') - else begin - writeln('S ', c, ' ', gK, ' ok'); - Dump(gX); - if (gK < 4) or ((gK >= 5) and (gK <= 9)) then RunDiscard; - end; - writeln('demoted ', Bit(demoted)); - ResetStack(0, 0); - end; - EndProc(c, sig^.base <> nil); -end; - -function ChunkNameOf(i: longint): longint; -var s: string; -begin - s := 'p' + chr(48 + i div 10) + chr(48 + i mod 10); - ChunkNameOf := Intern(@s[1], 3); -end; - -var - i, c: longint; path: string; -begin - seed := 5; - for i := 1 to length(ParamStr(1)) do seed := seed * 10 + ord(ParamStr(1)[i]) - 48; - Letters := 'abcdefgh' + #0; - path := 'self/test/ItemDump.txt'; - if Open(path) <> '' then Fatal('no file'); - Next; - listing := true; - curFile := Intern(@path[1], length(path)); - for i := 0 to NumProcs - 1 do begin c := NewChunk(secText, -1, ChunkNameOf(i)); chunks^[c].live := true end; - for i := 0 to NumGlobs - 1 do begin - c := NewChunk(secBss, -1, ChunkNameOf(NumProcs + i)); - SetBss(c, 64, 8); - end; - MakeTypes; - MakeObjs; - for i := 0 to NumProcs - 1 do GenProc(FirstProc + i); - writeln('pc ', pc, ' fixups ', numFixups, ' lines ', numLines, ' said ', SaidCount); - for i := 0 to pc - 1 do write(HexStr(code^[i], 2)); - writeln; - for i := 0 to numFixups - 1 do writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend); - for i := 0 to numLines - 1 do writeln('L ', lines^[i].at, ' ', lines^[i].chunk, ' ', lines^[i].line, ' ', lines^[i].col); - List(-1); -end. diff --git a/self/test/ItemDump.raz b/self/test/ItemDump.raz deleted file mode 100644 index 7be8bf4..0000000 --- a/self/test/ItemDump.raz +++ /dev/null @@ -1,679 +0,0 @@ -(* Drives Item with a fixed pseudo-random script of operands and - operations, with mistakes among them, and prints what each step gave - (the item, or that it failed, whose message goes to standard error), - then the bytes, fixups, line notes and listing (raz -S) of the code - it made: self/Item.raz's side of a test against the seed's, - ItemDump.pas, which does and prints the same. The argument, a digit, - changes the script. A run ends at the 20th error, as a compile does, - so several scripts are run. *) -module ItemDump; -import Out, Fmt, Files, Heap, Diag, Scan, Sym, Chunk, X := X64, Gen, Item; - -const - FirstProc = 3; (* chunks 0 to 2 are Gen's own *) - NumProcs = 30; - FirstGlob = FirstProc + NumProcs; - NumGlobs = 4; - Steps = 14; - (* the types of the script, by number *) - YInt = 0; YI64 = 1; YI32 = 2; YU8 = 3; YU16 = 4; YU32 = 5; YU64 = 6; YBool = 7; - YReal = 8; YF32 = 9; YI8 = 10; YEnum = 11; YSet = 12; YPtr = 13; YVptr = 14; - YPtrArr = 15; YArr = 16; YArrU8 = 17; YSlice = 18; YBytes = 19; YRec = 20; - YPacked = 21; YVariant = 22; YProc0 = 23; YProc1 = 24; YProc2 = 25; - YPtrRec = 26; YErr = 27; YVrec = 28; YVarr = 29; - NumT = 30; - IntTypes: [8]INT = [YInt, YI64, YI32, YU8, YU16, YU32, YU64, YI8]; - Ops: [20]Scan.Sym = [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod, - Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr, - Scan.sEql, Scan.sNeq, Scan.sLss, Scan.sLeq, Scan.sGtr, Scan.sGeq, - Scan.sSlash, Scan.sIn, Scan.sPlus, Scan.sMinus]; - Cmps: [6]Scan.Sym = [Scan.sEql, Scan.sNeq, Scan.sLss, Scan.sLeq, Scan.sGtr, Scan.sGeq]; - -var - Letters: []U8; - seed: I64; - ty: [NumT]^Sym.Type; - vars: [NumT]^Sym.Obj; (* a variable of each type, placed anew for each procedure *) - procs: [6]^Sym.Obj; - strs: [3]^Sym.Obj; - arrConst, typeObj, builtinObj, caseObj: ^Sym.Obj; - mod0, mod1: ^Sym.Module; - tuple2, record3, packedR, variantT: ^Sym.Type; - results: [9]^Sym.Type; - curRes: INT; (* the result of the procedure, an index of results *) - call: Gen.CallInfo; - -proc rnd(n: INT): INT; -begin - seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; - return INT((seed shr 8) mod I64(n)); -end; - -proc flag: BOOL; -begin - return rnd(2) = 0; -end; - -proc bit(f: BOOL): INT; -begin - if f then return 1; end; - return 0; -end; - -proc pos: Diag.Pos; -var p: Diag.Pos; -begin - p.f := 0; p.a := rnd(400); p.b := p.a + 1 + rnd(12); - return p; -end; - -proc constVal: I64; -var x: INT; r: I64; -begin - x := rnd(1 shl 30); - match rnd(7) of - | 0: r := x mod 10; - | 1: r := -(x mod 100); - | 2: r := I64(1) shl (x mod 20); - | 3: r := x; - | 4: r := I64(x) * 4096 * 4096 * 9 - 7; - | 5: r := -I64(x) * 8; - | else: r := x mod 1000 - 500; - end; - return r; -end; - -(* A name, interned *) -proc intern(s: []U8): INT; -begin - return Scan.intern(ADR(s[0]), LEN(s)); -end; - -(* A name v00, v01, ... , interned *) -proc nameOf(i: INT): INT; -var s: [3]U8; -begin - s[0] := 'v'; s[1] := U8(48 + i div 10); s[2] := U8(48 + i mod 10); - return Scan.intern(ADR(s[0]), 3); -end; - -proc newObjs(cls: Sym.Class; t: ^Sym.Type; n: INT; step: I64; at: INT): ^Sym.Obj; -var first, o, last: ^Sym.Obj; i: INT; -begin - first := nil; last := nil; - for i := 0 to n - 1 do - o := Sym.newObj(cls, nameOf(at + i), t); - o^.val := step * I64(i); - if last = nil then first := o; else last^.next := o; end; - last := o; - end; - return first; -end; - -proc newType(form: Sym.Form; size, align: I64): ^Sym.Type; -begin - return Sym.newType(form, size, align); -end; - -proc procType(res: ^Sym.Type; params: ^Sym.Obj; n: INT): ^Sym.Type; -var t: ^Sym.Type; -begin - t := newType(Sym.fProc, 8, 8); - t^.base := res; - t^.fields := params; - t^.len := n; - return t; -end; - -proc param(t: ^Sym.Type; isVar: BOOL; at: INT): ^Sym.Obj; -var o: ^Sym.Obj; -begin - o := Sym.newObj(Sym.oVar, nameOf(at), t); - o^.param := true; - o^.isVar := isVar; - return o; -end; - -proc makeTypes; -var t: ^Sym.Type; p, q, r: ^Sym.Obj; i: INT; -begin - ty[YInt] := Sym.tInt; ty[YI64] := Sym.tI64; ty[YI32] := Sym.tI32; ty[YU8] := Sym.tU8; - ty[YU16] := Sym.tU16; ty[YU32] := Sym.tU32; ty[YU64] := Sym.tU64; ty[YBool] := Sym.tBool; - ty[YReal] := Sym.tReal; ty[YF32] := Sym.tF32; ty[YI8] := Sym.tI8; ty[YErr] := Sym.tError; - ty[YBytes] := Sym.tBytes; - t := newType(Sym.fEnum, 1, 1); t^.len := 5; ty[YEnum] := t; - t := newType(Sym.fSet, 8, 8); t^.len := 5; t^.base := ty[YEnum]; ty[YSet] := t; - t := newType(Sym.fPtr, 8, 8); t^.base := Sym.tI64; ty[YPtr] := t; - t := newType(Sym.fPtr, 8, 8); t^.base := Sym.tI64; t^.vol := true; ty[YVptr] := t; - t := newType(Sym.fArray, 48, 8); t^.base := Sym.tI64; t^.len := 6; ty[YArr] := t; - t := newType(Sym.fPtr, 8, 8); t^.base := ty[YArr]; ty[YPtrArr] := t; - t := newType(Sym.fPtr, 8, 8); t^.base := ty[YArr]; t^.vol := true; ty[YVarr] := t; - t := newType(Sym.fArray, 8, 1); t^.base := Sym.tU8; t^.len := 8; ty[YArrU8] := t; - t := newType(Sym.fSlice, 16, 8); t^.base := Sym.tI64; ty[YSlice] := t; - (* a record of an I64, an F64 and an I32 *) - record3 := newType(Sym.fRecord, 24, 8); - p := Sym.newObj(Sym.oField, nameOf(40), Sym.tI64); p^.val := 0; - q := Sym.newObj(Sym.oField, nameOf(41), Sym.tReal); q^.val := 8; p^.next := q; - r := Sym.newObj(Sym.oField, nameOf(42), Sym.tI32); r^.val := 16; q^.next := r; - record3^.fields := p; - ty[YRec] := record3; - t := newType(Sym.fPtr, 8, 8); t^.base := record3; ty[YPtrRec] := t; - t := newType(Sym.fPtr, 8, 8); t^.base := record3; t^.vol := true; ty[YVrec] := t; - (* a packed record: a byte, then an I32 that may be misaligned *) - packedR := newType(Sym.fRecord, 53, 1); - packedR^.packd := true; - p := Sym.newObj(Sym.oField, nameOf(43), Sym.tU8); p^.val := 0; - q := Sym.newObj(Sym.oField, nameOf(44), Sym.tI32); q^.val := 1; p^.next := q; - r := Sym.newObj(Sym.oField, nameOf(46), ty[YArr]); r^.val := 5; q^.next := r; - packedR^.fields := p; - ty[YPacked] := packedR; - variantT := newType(Sym.fVariant, 16, 8); - ty[YVariant] := variantT; - tuple2 := newType(Sym.fRecord, 16, 8); - tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := newObjs(Sym.oVar, Sym.tInt, 2, 8, 45); - (* procedures: (I64, F64) I64; (); (var I64, []I64) of two results *) - p := param(Sym.tInt, false, 46); p^.next := param(Sym.tReal, false, 47); - ty[YProc0] := procType(Sym.tInt, p, 2); - ty[YProc1] := procType(nil, nil, 0); - p := param(Sym.tI64, true, 48); p^.next := param(ty[YSlice], false, 49); - ty[YProc2] := procType(tuple2, p, 2); - results[0] := nil; results[1] := Sym.tInt; results[2] := Sym.tReal; results[3] := ty[YSlice]; - results[4] := tuple2; results[5] := record3; results[6] := Sym.tF32; results[7] := Sym.tI16; - results[8] := ty[YBytes]; - for i := 0 to NumT - 1 do - if ty[i] = nil then Diag.fatal("a type is missing"); end; - end; -end; - -(* The objects named by the script: procedures, strings, constants of - an array, a type, a built-in, a case of a variant *) -proc makeObjs; -var i, c: INT; o: ^Sym.Obj; -begin - NEW(mod0, Heap.heap); mod0^.name := intern("Zero"); - NEW(mod1, Heap.heap); mod1^.name := intern("Other"); - Sym.setCurModule(mod0); - for i := 0 to 5 do - o := Sym.newObj(Sym.oProc, nameOf(50 + i), ty[YProc0 + i mod 3]); - o^.chunk := FirstProc + rnd(NumProcs); - o^.ext := i >= 4; - o^.isCode := i = 3; - procs[i] := o; - end; - for i := 0 to 2 do - o := Sym.newObj(Sym.oConst, nameOf(60 + i), Sym.tStr); - o^.val := 2 + 3 * i; - c := Chunk.newChunk(Chunk.secRodata, -1, -1); - Chunk.setData(c, ADR(Letters[0]), INT(o^.val) + 1, 1); - o^.chunk := c; - strs[i] := o; - end; - arrConst := Sym.newObj(Sym.oConst, nameOf(63), ty[YArr]); - arrConst^.chunk := Chunk.newChunk(Chunk.secRodata, -1, -1); - Chunk.setData(arrConst^.chunk, ADR(Letters[0]), 8, 8); - typeObj := Sym.newObj(Sym.oType, nameOf(64), ty[YRec]); - builtinObj := Sym.newObj(Sym.oBuiltin, nameOf(65), Sym.tNone); - caseObj := Sym.newObj(Sym.oCase, nameOf(66), variantT); - caseObj^.val := 3; - caseObj^.fields := newObjs(Sym.oField, Sym.tInt, 2, 8, 67); - caseObj^.fields^.val := 8; -end; - -(* The variable of each type, in the frame, a chunk, a slot, a register, - another module or C's, as the procedure compiled has them *) -proc makeVars; -var i, k: INT; o: ^Sym.Obj; t: ^Sym.Type; -begin - for i := 0 to NumT - 1 do - t := ty[i]; - o := Sym.newObj(Sym.oVar, nameOf(i), t); - o^.lev := 1; - k := rnd(9); - if k = 2 then - o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs); - elsif k = 3 then - o^.ind := true; o^.val := Gen.allocPerm(8, 8); o^.off := 8 * rnd(3); - elsif k = 4 then - if (t^.form in {Sym.fInt, Sym.fPtr}) and (t^.size = 8) then - o^.reg := Gen.VarRegs[rnd(5)]; - elsif t^.form = Sym.fReal then - o^.reg := Gen.XVarRegs[rnd(4)]; - elsif t^.form = Sym.fSlice then - o^.reg := Gen.VarRegs[rnd(3)]; o^.reg2 := Gen.VarRegs[3 + rnd(2)]; - end; - if o^.reg = 0 then o^.val := Gen.allocPerm(t^.size, 8); end; - elsif k = 5 then - o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs); o^.home := mod1; - elsif k = 6 then - o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs); o^.ext := true; - else - o^.val := Gen.allocPerm(t^.size + 8, 8); - end; - vars[i] := o; - end; -end; - -(* Operands *) - -proc intType: ^Sym.Type; -begin - return ty[IntTypes[rnd(8)]]; -end; - -proc varItem(var x: Item.Item; t: ^Sym.Type): ERROR; -var i, k: INT; -begin - k := rnd(NumT); - for i := 0 to NumT - 1 do - if ty[i] = t then k := i; end; - end; - x := {}; - x.pos := pos(); - return Item.makeItem(x, vars[k]); -end; - -(* An operand of type t, or of any if t is nil *) -proc operand(var x: Item.Item; t: ^Sym.Type): ERROR; -var k: INT; r: F64; v: I64; -begin - x := {}; - x.pos := pos(); - if t = nil then - match rnd(14) of - | 0: Item.makeConst(x, Sym.tConst, constVal()); - | 1: Item.makeConst(x, Sym.tConst, constVal() mod 200); - | 2: t := intType(); v := constVal() mod 100; Item.makeConst(x, t, v); - | 3: r := F64(constVal() mod 1000) / 8.0; Item.makeReal(x, r); - | 4: Item.makeConst(x, Sym.tBool, I64(rnd(2))); - | 5: return Item.makeItem(x, strs[rnd(3)]); - | 6: Item.makeConst(x, Sym.tNil, 0); - | 7: return Item.makeItem(x, procs[rnd(6)]); - | 8: if rnd(4) = 0 then - match rnd(3) of - | 0: return Item.makeItem(x, typeObj); - | 1: return Item.makeItem(x, builtinObj); - | else: return Item.makeItem(x, caseObj); - end; - end; - return Item.makeItem(x, arrConst); - | 13: try Item.makeItem(x, vars[rnd(NumT)]); return Item.value(x); - | else: return varItem(x, ty[rnd(NumT)]); - end; - return nil; - end; - k := rnd(10); - if Sym.isInt(t) then - if k < 3 then Item.makeConst(x, Sym.tConst, constVal() mod 100); return nil; end; - if k = 3 then Item.makeConst(x, t, constVal() mod 100); return nil; end; - elsif t^.form = Sym.fReal then - if k < 3 then r := F64(constVal() mod 1000) / 8.0; Item.makeReal(x, r); return nil; end; - elsif t^.form = Sym.fBool then - if k < 3 then Item.makeConst(x, Sym.tBool, I64(rnd(2))); return nil; end; - elsif t^.form = Sym.fPtr then - if k < 2 then Item.makeConst(x, Sym.tNil, 0); return nil; end; - elsif (t^.form = Sym.fSlice) and (t^.base = Sym.tU8) then - if k < 3 then return Item.makeItem(x, strs[rnd(3)]); end; - end; - return varItem(x, t); -end; - -(* A condition, left as one: a comparison of two integers *) -proc condItem(var x: Item.Item): ERROR; -var y: Item.Item; L: INT; op: Scan.Sym; t: ^Sym.Type; -begin - t := intType(); - op := Cmps[rnd(6)]; - try operand(x, t); - try Item.op1(op, x, L); - try operand(y, t); - return Item.op2(op, x, y, L); -end; - -(* A variable, or part of one: through a pointer, a field, an element, a slice *) -proc place(var x: Item.Item): ERROR; -var i, k: INT; f: ^Sym.Obj; y, lo, hi: Item.Item; -begin - try varItem(x, ty[rnd(NumT)]); - for i := 1 to 3 do - if rnd(3) # 0 then - k := rnd(6); - if (k = 0) or (x.typ^.form = Sym.fPtr) then - try Item.deref(x); - elsif x.typ^.form = Sym.fRecord then - f := x.typ^.fields; - k := rnd(3); - while (k > 0) and (f^.next # nil) do f := f^.next; DEC(k); end; - try Item.field(x, f); - elsif (x.typ^.form in {Sym.fArray, Sym.fSlice, Sym.fStr}) then - try Item.indexPrep(x); - if k < 4 then - try operand(y, intType()); - try Item.index(x, y); - else - try operand(lo, intType()); - try Item.sliceLo(lo); - try operand(hi, intType()); - try Item.slice(x, lo, hi); - end; - end; - end; - end; - return nil; -end; - -(* The state of an item *) -proc dump(var x: Item.Item); -var name: []U8; flags: INT; -begin - name := "-"; - if x.typ # nil then name := Sym.typeName(x.typ); end; - flags := bit(x.vol) + 2 * bit(x.isVar) + 4 * bit(x.odd) + 8 * bit(x.ro) + 16 * bit(x.deref); - Fmt.print("I {} {} {} {} {} {} {}", [Fmt.int(INT(x.mode)), Fmt.str(name), Fmt.int(INT(x.rel)), - Fmt.int(bit(x.relSigned)), Fmt.int(x.fj), Fmt.int(x.tj), Fmt.int(x.val)]); - Fmt.print(" {} {} {} {} depth {} pushed {}\n", [Fmt.int(INT(x.base)), Fmt.int(x.chunk), Fmt.int(x.off), - Fmt.int(flags), Fmt.int(Gen.depth), Fmt.int(Gen.pushed)]); -end; - -(* A call: of a procedure of the script or a variable of a procedure - type, with arguments that mostly fit its parameters *) -proc doCall(var x: Item.Item): ERROR; -var f, a: Item.Item; p: ^Sym.Obj; n: INT; -begin - f := {}; - f.pos := pos(); - if rnd(5) = 0 then try Item.makeItem(f, vars[YProc0 + rnd(3)]); - else try Item.makeItem(f, procs[rnd(6)]); end; - try Item.beginCall(call, f); - p := call.param; - n := rnd(4) - 1; - while (p # nil) or (n > 0) do - if p # nil then - if p^.isVar and (rnd(2) = 0) then - try varItem(a, ty[YVptr]); - try Item.deref(a); - elsif rnd(6) = 0 then try operand(a, nil); - else try operand(a, p^.typ); end; - p := p^.next; - else - try operand(a, nil); - n := n - 1; - end; - try Item.passArg(call, a); - if (p = nil) and (n < 0) then n := 0; end; - if (p # nil) and (n < 0) and (rnd(4) = 0) then p := nil; n := 0; end; - end; - return Item.endCall(call, x); -end; - -(* A binary operation, with a condition's jumps made after it, sometimes *) -proc binary(var x: Item.Item): ERROR; -var y: Item.Item; L, M: INT; op: Scan.Sym; t: ^Sym.Type; -begin - L := Gen.NoLabel; - M := Gen.NoLabel; - op := Ops[rnd(20)]; - match rnd(8) of - | 0, 1: t := intType(); - | 2: t := ty[YReal + rnd(2)]; - | 3: t := ty[YBool]; - | 4: t := ty[YEnum + rnd(2)]; - | else: t := ty[rnd(NumT)]; - end; - if rnd(6) = 0 then - (* and, or *) - if flag() then op := Scan.sAnd; else op := Scan.sOr; end; - try condItem(x); - try Item.op1(op, x, L); - try condItem(y); - elsif op = Scan.sIn then - try operand(x, ty[YEnum]); - try Item.op1(op, x, L); - try operand(y, ty[YSet]); - else - try operand(x, t); - try Item.op1(op, x, L); - if rnd(5) = 0 then try operand(y, nil); else try operand(y, t); end; - end; - try Item.op2(op, x, y, L); - if (x.mode = Item.mCond) and (rnd(3) # 0) then - if flag() then try Item.condJump(x, M); else try Item.condJumpTrue(x, M); end; - Gen.fix(M); - x.mode := Item.mNone; (* its values are used *) - end; - return nil; -end; - -proc unary(var x: Item.Item): ERROR; -begin - try operand(x, nil); - match rnd(3) of - | 0: return Item.neg(x); - | 1: return Item.notOp(x); - | else: return Item.complement(x); - end; -end; - -(* match: the slot of a variant, an enumeration or an integer, and - tests of it *) -proc doMatch(var x: Item.Item): ERROR; -var p, lo, hi: I64; L: INT; -begin - L := Gen.NoLabel; - match rnd(3) of - | 0: try varItem(x, ty[YVariant]); - | 1: try varItem(x, ty[YEnum]); - | else: try operand(x, nil); - end; - p := try Item.matchBegin(x); - Item.matchTag(p, constVal() mod 10, L); - lo := constVal() mod 10; - hi := constVal() mod 10 + 10; - Item.matchRange(p, lo, hi, L); - Item.matchRange(p, 3, 3, L); - Gen.fix(L); - return nil; -end; - -(* A for loop's variable stepped and tested *) -proc doFor(var x: Item.Item): ERROR; -var o: ^Sym.Obj; lim: Item.Item; step: I64; exitL: INT; -begin - o := vars[IntTypes[rnd(8)]]; - step := constVal() mod 5; - if step = 0 then step := 1; end; - if rnd(2) = 0 then step := -step; end; - lim := {}; - lim.pos := pos(); - Item.makeConst(lim, o^.typ, constVal() mod 50); - exitL := Gen.NoLabel; - try Item.forStep(o, step); - try Item.forNext(o, lim, step, exitL, Chunk.pc, Chunk.pc); - Gen.fix(exitL); - x := lim; - return nil; -end; - -(* INC and DEC, pin, COPY *) -proc doMisc(var x: Item.Item): ERROR; -var y: Item.Item; -begin - match rnd(5) of - | 0: - try place(x); - try Item.address(x); - try operand(y, x.typ); - return Item.incDec(x, y, flag()); - | 1: - try place(x); - return Item.pin(x); - | 2: - try place(x); - try Item.copyDest(x); - try place(y); - return Item.copyFrom(x, y); - | 3: - try operand(x, nil); - Item.makeStr(y); - return Item.coerce(y, ty[YBytes]); - | else: - try operand(x, nil); - Item.nilTest(x); - Item.usesReals(x.pos); - return Item.discard(x); - end; -end; - -(* A variant, a record's fields, an error's chunk, the message of one *) -proc doTemp(var x: Item.Item): ERROR; -var a: Item.Item; c, h, n: INT; f: ^Sym.Obj; -begin - x := {}; - x.pos := pos(); - match rnd(5) of - | 0: Item.zeroTemp(x, ty[YVariant]); - | 1: - Item.construct(x, caseObj); - f := caseObj^.fields; - try operand(a, f^.typ); - return Item.setField(x, f, a); - | 2: - Item.zeroTemp(x, ty[YRec]); - f := ty[YRec]^.fields; - if flag() then f := f^.next; end; - try operand(a, f^.typ); - return Item.setField(x, f, a); - | 3: - try operand(a, nil); - h := rnd(3) - 1; - n := rnd(3) - 1; - c := try Item.errorChunk(a, h, n); - Item.makeConst(x, Sym.tError, I64(c) + 1); - return nil; - | else: - try operand(x, ty[YErr]); - return Item.msg(x); - end; - return nil; -end; - -proc doReturn(var x: Item.Item): ERROR; -var f: ^Sym.Obj; -begin - if (curRes = 4) and flag() then - (* several results *) - f := tuple2^.fields; - if flag() then f := f^.next; end; - if flag() then - try operand(x, f^.typ); - return Item.returnField(f, x); - end; - try doCall(x); - return Item.returnAll(x); - end; - if rnd(4) = 0 then return Item.returnNone(); end; - try operand(x, results[curRes]); - return Item.returnValue(x); -end; - -(* One step of the script, whose item is x *) -proc step(k: INT; var x: Item.Item): ERROR; -var y: Item.Item; -begin - x := {}; - match k of - | 0: try operand(x, nil); return Item.value(x); - | 1: try operand(x, nil); return Item.address(x); - | 2: try operand(x, nil); return Item.coerce(x, ty[rnd(NumT)]); - | 3: try operand(x, nil); return Item.coerceExact(x, intType(), ""); - | 4: - try place(x); - try operand(y, x.typ); - return Item.assign(x, y); - | 5: return unary(x); - | 6: return binary(x); - | 7: try operand(x, nil); return Item.convert(x, ty[rnd(NumT)]); - | 8: return place(x); - | 9: return doCall(x); - | 10: return doMatch(x); - | 11: return doFor(x); - | 12: return doMisc(x); - | 13: return doTemp(x); - | 14: return doReturn(x); - | else: return binary(x); - end; -end; - -(* One procedure of Steps steps *) -proc genProc(c: INT); -var - sig: ^Sym.Type; i, k, line: INT; x: Item.Item; err: ERROR; -begin - curRes := rnd(9); - sig := procType(results[curRes], nil, 0); - Item.beginProc(sig, nil); - for i := 0 to 5 do _ := Gen.allocPerm(8, 8); end; - makeVars(); - Item.setChecks(flag()); - line := 1 + rnd(40); - Gen.enterBody(c, line); - for i := 1 to Steps do - if Diag.errors >= 19 then break; end; (* the 20th would end the run *) - k := rnd(17); - Item.setDemoted(false); - err := step(k, x); - if err # nil then - Fmt.print("S {} {} failed\n", [Fmt.int(c), Fmt.int(k)]); - else - Fmt.print("S {} {} ok\n", [Fmt.int(c), Fmt.int(k)]); - dump(x); - (* the items of these steps are as an operand is, on the stack *) - if (k < 4) or ((k >= 5) and (k <= 9)) then _ := Item.discard(x); end; - end; - Fmt.print("demoted {}\n", [Fmt.int(bit(Item.demoted))]); - Gen.resetStack(0, 0); - end; - _ := Gen.endProc(c, sig^.base # nil); -end; - -proc chunkNameOf(i: INT): INT; -var s: [3]U8; -begin - s[0] := 'p'; s[1] := U8(48 + i div 10); s[2] := U8(48 + i mod 10); - return Scan.intern(ADR(s[0]), 3); -end; - -proc main*; -var i, c: INT; path: []U8; arg: []U8; -begin - arg := Files.arg(1); - seed := 5; - for i := 0 to LEN(arg) - 1 do seed := seed * 10 + I64(arg[i]) - 48; end; - Letters := "abcdefgh\0"; - path := "self/test/ItemDump.txt"; - if LEN(Scan.open(path)) # 0 then Diag.fatal("no file"); end; - Scan.next; (* the string the file starts with *) - X.setListing(true); - Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path))); - for i := 0 to NumProcs - 1 do c := Chunk.newChunk(Chunk.secText, -1, chunkNameOf(i)); Chunk.setLive(c); end; - for i := 0 to NumGlobs - 1 do - c := Chunk.newChunk(Chunk.secBss, -1, chunkNameOf(NumProcs + i)); - Chunk.setBss(c, 64, 8); - end; - makeTypes(); - makeObjs(); - for i := 0 to NumProcs - 1 do genProc(FirstProc + i); end; - Fmt.print("pc {} fixups {} lines {} said {}\n", [Fmt.int(Chunk.pc), - Fmt.int(Chunk.numFixups), Fmt.int(Chunk.numLines), Fmt.int(X.saidCount())]); - for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end; - Out.ln; - for i := 0 to Chunk.numFixups - 1 do - Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]); - end; - for i := 0 to Chunk.numLines - 1 do - Fmt.print("L {} {} {} {}\n", [Fmt.int(Chunk.lines[i].at), Fmt.int(Chunk.lines[i].chunk), - Fmt.int(Chunk.lines[i].line), Fmt.int(Chunk.lines[i].col)]); - end; - X.list(-1); -end; - -end ItemDump. diff --git a/self/test/ItemDump.txt b/self/test/ItemDump.txt deleted file mode 100644 index 5be0a4c..0000000 --- a/self/test/ItemDump.txt +++ /dev/null @@ -1,41 +0,0 @@ -"item test" - x value sum alpha beta; - next beta items len alpha next count alpha beta; - value beta count beta next value; - len beta count; - sum len alpha len len value alpha count; - next x n; - x next beta len n next; - sum x beta len len sum count items beta; - tmp beta len alpha len count p; - next value items p len p items n; - x tmp count beta; - n next p items tmp p n; - beta beta next value x items x; - value alpha sum beta next len; - items items tmp items len p len p beta; - beta n p tmp sum beta alpha tmp tmp; - sum len sum p n; - value sum items alpha p items x len; - p alpha count; - n x tmp count value value p beta x; - value next n x value next; - tmp value items sum value; - x beta x x; - sum count alpha p; - len x n n alpha x value next items; - len items x tmp next len sum; - tmp alpha p sum next value value value; - beta p sum value alpha count; - count p x; - items len alpha; - alpha len x; - beta items len alpha beta count len; - x sum n items len items; - beta beta p p p p; - beta x beta tmp items; - n p tmp x next alpha count next; - x tmp next alpha next; - sum beta tmp n next; - x items count next next; - next items sum count len count count value tmp; diff --git a/self/test/LinkDump.pas b/self/test/LinkDump.pas deleted file mode 100644 index 47e1db4..0000000 --- a/self/test/LinkDump.pas +++ /dev/null @@ -1,91 +0,0 @@ -{ Makes a program of chunks by a fixed pseudo-random script, links it and - writes it as an executable to the file of the second argument, in the - way the first says (0 static, 1 dynamic, 2 stripped): the seed's side - of a test of self/Link.raz and self/Elf.raz, whose LinkDump.raz does - the same and writes the same file. } -program linkdump; -{$mode objfpc}{$H-} -uses diag, scan, chunk, link, elf; -const NumC = 200; -var - seed: int64; - names: array[0..7] of longint; - i, j, k, kind, n, x, y, z, mode: longint; - b: array[0..63] of byte; - -function Rnd(n: longint): longint; -begin - seed := (seed * 1103515245 + 12345) and $7FFFFFFF; - Rnd := (seed shr 8) mod n; -end; - -var c, e, line, col: longint; -begin - seed := 5; - mode := ord(ParamStr(1)[1]) - 48; - for i := 0 to 7 do begin b[0] := 97 + i; names[i] := Intern(@b[0], 1) end; - placesChunk := NewChunk(secRodata, -1, -1); - SetData(placesChunk, @b[0], 0, 8); - for i := 0 to NumC - 1 do begin - if i = 0 then kind := 0 else kind := Rnd(10); - x := Rnd(4); y := Rnd(8); - case kind of - 0..5: begin - c := NewChunk(secText, x - 1, y); - BeginChunk(c); - z := Rnd(3); curFile := names[z]; - line := Rnd(300); col := Rnd(60); - NoteLine(line, col); - if i = 0 then begin AddFixup(pc, placesChunk, 0); Put4(0) end; - n := 2 + Rnd(10); - for j := 1 to n do begin - z := Rnd(5); - if z <= 1 then begin - e := Rnd(NumC); y := Rnd(8); - AddFixup(pc, e, y); - Put4(0); - end else if z = 2 then begin - z := Rnd(3); curFile := names[z]; - line := Rnd(300); col := Rnd(60); - NoteLine(line, col); - end else begin x := Rnd(1 shl 30); Put4(x); x := Rnd(256); Put1(x) end; - end; - EndChunk(c); - n := Rnd(3); - for j := 1 to n do begin - x := Rnd(8); y := Rnd(200); z := Rnd(6); - NoteVar(c, names[x], y - 100, z); - end; - end; - 6, 7: begin - c := NewChunk(secRodata, x - 1, y); - n := 8 * (1 + Rnd(4)); - for j := 0 to n - 1 do b[j] := Rnd(256); - SetData(c, @b[0], n, 8); - for j := 0 to n div 8 - 1 do begin - z := Rnd(2); - if z = 0 then begin e := Rnd(NumC); y := Rnd(8); AddDataFixup(c, j * 8, e, y) end; - end; - end; - 8: begin - c := NewChunk(secBss, x - 1, y); - z := Rnd(200); e := Rnd(4); - SetBss(c, 1 + z, 1 shl e); - end; - 9: begin z := Rnd(8); c := ExternChunk(names[z]) end; - end; - end; - { every chunk a fixup names must exist, and be defined if it is reached } - while numChunks < NumC do begin c := NewChunk(secBss, -1, -1); SetBss(c, 8, 8) end; - for i := 0 to numChunks - 1 do - if chunks^[i].size < 0 then SetBss(i, 8, 8); - mainPath := 'some/main.raz'; - if mode = 1 then begin - numNeeded := 2; - needed[0] := names[0]; needed[1] := names[1]; - end; - stripped := mode = 2; - if mode = 2 then placesChunk := -1; - MarkLive(1); - WriteElf(ParamStr(2), 1); -end. diff --git a/self/test/LinkDump.raz b/self/test/LinkDump.raz deleted file mode 100644 index 961abd6..0000000 --- a/self/test/LinkDump.raz +++ /dev/null @@ -1,103 +0,0 @@ -(* Makes a program of chunks by a fixed pseudo-random script, links it - and writes it as an executable to the file of the second argument, - in the way the first says (0 static, 1 dynamic, 2 stripped): - self/Link.raz's and self/Elf.raz's side of a test against the seed's, - LinkDump.pas, which writes the same file. *) -module LinkDump; -import Files, Diag, Scan, Chunk, Link, Elf; - -const NumC = 200; - -var seed: I64; - -proc rnd(n: INT): INT; -begin - seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; - return INT((seed shr 8) mod I64(n)); -end; - -(* a library that must be taken *) -proc ok(taken: BOOL); -begin - if not taken then Diag.fatal("too many libraries"); end; -end; - -proc main*; -var - names: [8]INT; b: [64]U8; arg: []U8; - i, j, kind, n, x, y, z, c, e, line, col, mode: INT; -begin - seed := 5; - arg := Files.arg(1); - mode := INT(arg[0]) - 48; - for i := 0 to 7 do b[0] := U8(97 + i); names[i] := Scan.intern(ADR(b[0]), 1); end; - Link.setPlaces(Chunk.newChunk(Chunk.secRodata, -1, -1)); - Chunk.setData(Link.placesChunk, ADR(b[0]), 0, 8); - for i := 0 to NumC - 1 do - if i = 0 then kind := 0; else kind := rnd(10); end; - x := rnd(4); y := rnd(8); - match kind of - | 0..5: - c := Chunk.newChunk(Chunk.secText, x - 1, y); - Chunk.beginChunk(c); - z := rnd(3); Chunk.setCurFile(names[z]); - line := rnd(300); col := rnd(60); - Chunk.noteLine(line, col); - if i = 0 then Chunk.addFixup(Chunk.pc, Link.placesChunk, 0); Chunk.put4(0); end; - n := 2 + rnd(10); - for j := 1 to n do - z := rnd(5); - if z <= 1 then - e := rnd(NumC); y := rnd(8); - Chunk.addFixup(Chunk.pc, e, y); - Chunk.put4(0); - elsif z = 2 then - z := rnd(3); Chunk.setCurFile(names[z]); - line := rnd(300); col := rnd(60); - Chunk.noteLine(line, col); - else - x := rnd(1 shl 30); Chunk.put4(x); x := rnd(256); Chunk.put1(x); - end; - end; - Chunk.endChunk(c); - n := rnd(3); - for j := 1 to n do - x := rnd(8); y := rnd(200); z := rnd(6); - Chunk.noteVar(c, names[x], y - 100, z); - end; - | 6, 7: - c := Chunk.newChunk(Chunk.secRodata, x - 1, y); - n := 8 * (1 + rnd(4)); - for j := 0 to n - 1 do b[j] := U8(rnd(256)); end; - Chunk.setData(c, ADR(b[0]), n, 8); - for j := 0 to n div 8 - 1 do - z := rnd(2); - if z = 0 then e := rnd(NumC); y := rnd(8); Chunk.addDataFixup(c, j * 8, e, y); end; - end; - | 8: - c := Chunk.newChunk(Chunk.secBss, x - 1, y); - z := rnd(200); e := rnd(4); - Chunk.setBss(c, 1 + z, 1 shl e); - | else: z := rnd(8); c := Chunk.externChunk(names[z]); - end; - end; - (* every chunk a fixup names must exist, and be defined if it is reached *) - while Chunk.numChunks < NumC do - c := Chunk.newChunk(Chunk.secBss, -1, -1); - Chunk.setBss(c, 8, 8); - end; - for i := 0 to Chunk.numChunks - 1 do - if Chunk.chunks[i].size < 0 then Chunk.setBss(i, 8, 8); end; - end; - Elf.setMainPath("some/main.raz"); - if mode = 1 then - ok(Elf.needLib(names[0])); - ok(Elf.needLib(names[1])); - end; - Elf.setStripped(mode = 2); - if mode = 2 then Link.setPlaces(-1); end; - Link.markLive(1); - Elf.writeElf(Files.arg(2), 1); -end; - -end LinkDump. diff --git a/self/test/Recover.raz b/self/test/Recover.raz deleted file mode 100644 index cf0ae41..0000000 --- a/self/test/Recover.raz +++ /dev/null @@ -1,38 +0,0 @@ -(* Tests going on after an error, as the parser does with try: a driver - reads a file's symbols and reports each name `bad` as an error, - several calls deep; the error comes back up through them, and the - driver reads on from the next symbol. *) -module Recover; -import Out, Files, Diag, Scan; - -var failed, names: INT; - -proc deep(n: INT): ERROR; -begin - if n > 0 then - try deep(n - 1); - return nil; - end; - return Scan.mark("a bad name"); -end; - -proc main*; -var err: ERROR; -begin - if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end; - while Scan.tok # Scan.sEof do - Scan.next; - if Scan.tok = Scan.sIdent then - INC(names); - if Scan.nameOf(Scan.id) = "bad" then - err := deep(5); - if err # nil then INC(failed); end; - end; - end; - end; - Out.int(names); Out.str(" names, "); Out.int(failed); Out.str(" failed, "); - Out.int(Diag.errors); Out.str(" errors\n"); - Diag.finish; -end; - -end Recover. diff --git a/self/test/ScanBench.pas b/self/test/ScanBench.pas deleted file mode 100644 index 861f7a0..0000000 --- a/self/test/ScanBench.pas +++ /dev/null @@ -1,12 +0,0 @@ -{ Counts the symbols of a file and nothing else, for timing scan.pas - against self/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/self/test/ScanBench.raz b/self/test/ScanBench.raz deleted file mode 100644 index a49e516..0000000 --- a/self/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/self/test/ScanDump.pas b/self/test/ScanDump.pas deleted file mode 100644 index b184002..0000000 --- a/self/test/ScanDump.pas +++ /dev/null @@ -1,21 +0,0 @@ -{ Prints the symbols of a file, one per line: the seed's side of a test - of self/Scan.raz, which prints the same. A real is shown by its bits, - so that no formatting library decides what is the same. } -program scandump; -{$mode objfpc}{$H-} -uses diag, scan; -var i: longint; bits: int64; -begin - if Open(ParamStr(1)) <> '' then Fatal('no file'); - repeat - Next; - write(LineOf(TokPos), ':', TokPos.a, ':', TokPos.b, ' ', CurLine, ':', CurCol, ' ', ord(tok)); - case tok of - sIdent: write(' ', NameOf(id), ' ', id); - sInt, sChar: write(' ', ival); - sReal: begin Move(rval, bits, 8); write(' ', HexStr(bits, 16)) end; - sString: begin write(' "'); for i := 0 to slen - 1 do write(sbuf[i], ','); write('"') end; - end; - writeln; - until tok = sEof; -end. diff --git a/self/test/ScanDump.raz b/self/test/ScanDump.raz deleted file mode 100644 index dbf9075..0000000 --- a/self/test/ScanDump.raz +++ /dev/null @@ -1,35 +0,0 @@ -(* Prints the symbols of a file, one per line: self/Scan.raz's side of a - test against the seed's, ScanDump.pas, which prints the same. *) -module ScanDump; -import Out, Fmt, Files, Diag, Scan; - -proc main*; -var p: Diag.Pos; bits: ^U64; i: INT; str: []U8; r: F64; -begin - if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end; - repeat - Scan.next; - p := Scan.tokPos(); - Fmt.print("{}:{}:{} {}:{} {}", [Fmt.int(Diag.lineOf(p)), Fmt.int(p.a), Fmt.int(p.b), - Fmt.int(Scan.curLine()), Fmt.int(Scan.curCol()), Fmt.int(INT(Scan.tok))]); - match Scan.tok of - | sIdent: Fmt.print(" {} {}", [Fmt.str(Scan.nameOf(Scan.id)), Fmt.int(Scan.id)]); - | sInt: Fmt.print(" {}", [Fmt.int(Scan.ival)]); - | sChar: Fmt.print(" {}", [Fmt.int(Scan.ival)]); - | sReal: - r := Scan.rval; - bits := ^U64(ADR(r)); - Out.str(" "); - Out.hex(bits^, 16); - | sString: - Out.str(" \""); - str := Scan.strBytes(); - for i := 0 to LEN(str) - 1 do Fmt.print("{},", [Fmt.int(INT(str[i]))]); end; - Out.str("\""); - | else: - end; - Out.ln; - until Scan.tok = Scan.sEof; -end; - -end ScanDump. diff --git a/self/test/SymDump.pas b/self/test/SymDump.pas deleted file mode 100644 index eb58ef7..0000000 --- a/self/test/SymDump.pas +++ /dev/null @@ -1,185 +0,0 @@ -{ Builds types and objects by a fixed pseudo-random script, asks of them - what the parser asks of sym, and prints the answers: the seed's side - of a test of self/Sym.raz, whose SymDump.raz does the same and prints - the same. With the argument dup or deep it ends in the error of a name - declared twice, or of too many scopes. } -program symdump; -{$mode objfpc}{$H-} -uses diag, scan, sym; -const - Words: array[0..19] of string = ('alpha', 'alpho', 'beta', 'bet', 'gamma', 'gama', 'delta', 'Delta', - 'eps', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi', 'omicron', 'pi'); -var - seed: int64; - names: array[0..19] of longint; - mods: array[0..2] of PModule; - base: array[0..11] of PType; - pool: array[0..299] of PType; - objs: array[0..299] of PObj; - numPool, numObjs, i, k, n, op, x, y, z: longint; - t, o2: PType; - o: PObj; - saved: array[0..MaxDepth - 1] of longint; - d: longint; - v: int64; - -function Rnd(n: longint): longint; -begin - seed := (seed * 1103515245 + 12345) and $7FFFFFFF; - Rnd := (seed shr 8) mod n; -end; - -function Fields(m: longint; allowVar: boolean): PObj; -var f, first, last: PObj; j, x, y, z: longint; -begin - first := nil; last := nil; - for j := 1 to m do begin - x := Rnd(20); y := Rnd(numPool); - f := NewObj(oField, names[x], pool[y]); - z := Rnd(2); f^.exported := z = 0; - z := Rnd(3); f^.isVar := allowVar and (z = 0); - f^.val := j * 8; - if first = nil then first := f else last^.next := f; - last := f; - end; - Fields := first; -end; - -procedure Add(t: PType); -begin - if numPool <= High(pool) then begin pool[numPool] := t; inc(numPool) end; -end; - -procedure MakeType; -var t: PType; r, m, x: longint; f: PObj; -begin - r := Rnd(11); - case r of - 0: t := NewType(fPtr, 8, 8); - 1: t := NewType(fArray, 0, 1); - 2: t := NewType(fSlice, 16, 8); - 3: t := NewType(fRecord, 0, 8); - 4: t := NewType(fProc, 8, 8); - 5: t := NewType(fSet, 8, 8); - 6: t := NewType(fVariant, 16, 8); - 7: t := NewType(fEnum, 1, 1); - 8: t := NewType(fRecord, 16, 8); - 9: t := NewType(fProc, 8, 8); - else t := NewType(fPtr, 8, 8); - end; - x := Rnd(numPool); t^.base := pool[x]; - t^.len := Rnd(5); - x := Rnd(4); t^.vol := x = 0; - x := Rnd(4); t^.variadic := (t^.form = fProc) and (x = 0); - x := Rnd(2); t^.tuple := (t^.form = fRecord) and (x = 0); - if t^.form in [fRecord, fProc, fVariant] then begin - m := Rnd(4); - t^.fields := Fields(m, t^.form = fProc); - t^.len := m; - if t^.form = fRecord then t^.base := nil; - x := Rnd(2); - if (t^.form = fProc) and (x = 0) then t^.base := nil; - if t^.form = fVariant then begin - f := t^.fields; - while f <> nil do begin f^.cls := oCase; x := Rnd(3); f^.fields := Fields(x, false); f := f^.next end; - end; - end; - x := Rnd(3); - if x = 0 then begin - x := Rnd(20); t^.obj := NewObj(oType, names[x], t); - x := Rnd(3); t^.obj^.module := mods[x]; - end; - Add(t); -end; - -begin - seed := 11; - for i := 0 to 19 do names[i] := Intern(@Words[i][1], length(Words[i])); - for i := 0 to 2 do begin - New(mods[i]); FillChar(mods[i]^, SizeOf(TModule), 0); - mods[i]^.sname := names[i * 5]; - end; - curModule := mods[0]; - base[0] := tI8; base[1] := tI16; base[2] := tI32; base[3] := tI64; base[4] := tU8; - base[5] := tU16; base[6] := tU32; base[7] := tU64; base[8] := tBool; base[9] := tF32; - base[10] := tReal; base[11] := tInt; - for i := 0 to 11 do Add(base[i]); - if ParamCount >= 1 then begin if Open('lib/Rt.raz') <> '' then Fatal('no file'); Next; Next end; - numObjs := 0; - for k := 1 to 4000 do begin - op := Rnd(14); - case op of - 0, 1, 2: MakeType; - 3, 4: if numObjs <= High(objs) then begin - x := Rnd(8); y := Rnd(20); - if Find(x, names[y]) = nil then begin - z := Rnd(8); n := Rnd(numPool); - o := NewObj(TClass(z), names[y], pool[n]); - z := Rnd(2); o^.exported := z = 0; - z := Rnd(3); o^.module := mods[z]; - Insert(o, x); - objs[numObjs] := o; inc(numObjs); - writeln('I ', x, ' ', NameOf(names[y]), ' ', o^.scope); - end; - end; - 5: begin x := Rnd(8); y := Rnd(20); o := Find(x, names[y]); - write('F ', x, ' ', NameOf(names[y]), ' '); - if o = nil then writeln('-') else writeln(ord(o^.cls), ' ', o^.scope); - end; - 6: begin - x := Rnd(8); y := Rnd(20); - if ScopeDepth < 6 then OpenScope(x); - o := Lookup(names[y]); - write('L ', ScopeDepth, ' ', NameOf(names[y]), ' '); - if o = nil then writeln('-') else writeln(ord(o^.cls), ' ', o^.scope); - z := Rnd(2); - if (ScopeDepth > 1) and (z = 0) then CloseScope; - end; - 7: begin - y := Rnd(20); x := Rnd(9) - 1; z := Rnd(3); curModule := mods[z]; - o := Closest(names[y], x); - write('C ', NameOf(names[y]), ' ', x, ' '); - if o = nil then writeln('-') else writeln(NameOf(o^.name), ' ', o^.scope); - end; - 8: begin - x := Rnd(numPool); z := Rnd(3); curModule := mods[z]; - writeln('T ', TypeName(pool[x])); - end; - 9: begin - x := Rnd(numPool); y := Rnd(numPool); - writeln('S ', ord(Same(pool[x], pool[y])), ' ', ord(Same(pool[x], pool[x]))); - t := NewType(fPtr, 8, 8); t^.base := pool[x]; - o2 := t; t := NewType(fPtr, 8, 8); t^.base := pool[x]; - writeln('S ', ord(Same(o2, t))); - end; - 10: if numObjs > 0 then begin x := Rnd(numObjs); writeln('P ', HexStr(Fingerprint(objs[x]), 16)) end; - 11: begin - x := Rnd(numPool); y := Rnd(1 shl 20); z := Rnd(2); n := Rnd(2); - v := int64(y) * 4096 * z - y * n; - t := pool[x]; - writeln('B ', ord(Fits(v, t)), ' ', ord(IsInt(t)), ' ', ord(IsScalar(t)), ' ', ord(IsAggregate(t)), ' ', - ord(InTwoRegs(t)), ' ', ord(BehindPointer(t)), ' ', AlignUp(y, 1 shl z)); - end; - 12: if (ScopeDepth > 1) and (ScopeDepth < 6) then begin - d := ScopeDepth; SaveScopes(d, saved); - writeln('V ', ScopeDepth, ' ', TopScope); - RestoreScopes(d, saved); - writeln('V ', ScopeDepth, ' ', TopScope); - x := NewScope; writeln('N ', x); - end; - 13: begin x := ScopeDepth; if x > 3 then CutScopes(2); writeln('X ', x, ' ', ScopeDepth) end; - end; - end; - { the universe, and the sizes it made } - for i := 0 to 11 do writeln('U ', ord(base[i]^.form), ' ', base[i]^.size, ' ', ord(base[i]^.signed), ' ', NameOf(base[i]^.obj^.name)); - if ParamCount >= 1 then begin - if ParamStr(1) = 'dup' then begin - o := NewObj(oVar, names[3], tI8); - Insert(o, 100); Insert(o, 100); - end; - if ParamStr(1) = 'deep' then begin - CutScopes(1); - for i := 1 to MaxDepth + 1 do OpenScope(i); - end; - end; -end. diff --git a/self/test/SymDump.raz b/self/test/SymDump.raz deleted file mode 100644 index 9d3610a..0000000 --- a/self/test/SymDump.raz +++ /dev/null @@ -1,225 +0,0 @@ -(* Builds types and objects by a fixed pseudo-random script, asks of them - what the parser asks of Sym, and prints the answers: self/Sym.raz's - side of a test against the seed's, SymDump.pas, which prints the same. - With the argument dup or deep it ends in the error of a name declared - twice, or of too many scopes. *) -module SymDump; -import Out, Fmt, Files, Heap, Diag, Scan, Sym; - -const - Words: [20][]U8 = ["alpha", "alpho", "beta", "bet", "gamma", "gama", "delta", "Delta", - "eps", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu", "nu", "xi", "omicron", "pi"]; - -var - seed: I64; - names: [20]INT; - mods: [3]^Sym.Module; - base: [12]^Sym.Type; - pool: [300]^Sym.Type; - objs: [300]^Sym.Obj; - classes: [8]Sym.Class; - numPool, numObjs: INT; - -proc rnd(n: INT): INT; -begin - seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; - return INT((seed shr 8) mod I64(n)); -end; - -proc bit(f: BOOL): INT; -begin - if f then return 1; end; - return 0; -end; - -proc nm(i: INT): []U8; -begin - return Scan.nameOf(names[i]); -end; - -(* The result of a call that must succeed *) -proc ok(e: ERROR); -begin - if e # nil then Diag.finish; end; -end; - -proc fields(m: INT; allowVar: BOOL): ^Sym.Obj; -var f, first, last: ^Sym.Obj; j, x, y, z: INT; -begin - first := nil; last := nil; - for j := 1 to m do - x := rnd(20); y := rnd(numPool); - f := Sym.newObj(Sym.oField, names[x], pool[y]); - z := rnd(2); f^.exported := z = 0; - z := rnd(3); f^.isVar := allowVar and (z = 0); - f^.val := j * 8; - if first = nil then first := f; else last^.next := f; end; - last := f; - end; - return first; -end; - -proc add(t: ^Sym.Type); -begin - if numPool < 300 then pool[numPool] := t; INC(numPool); end; -end; - -proc makeType; -var t: ^Sym.Type; r, m, x: INT; f: ^Sym.Obj; -begin - r := rnd(11); - match r of - | 0: t := Sym.newType(Sym.fPtr, 8, 8); - | 1: t := Sym.newType(Sym.fArray, 0, 1); - | 2: t := Sym.newType(Sym.fSlice, 16, 8); - | 3: t := Sym.newType(Sym.fRecord, 0, 8); - | 4: t := Sym.newType(Sym.fProc, 8, 8); - | 5: t := Sym.newType(Sym.fSet, 8, 8); - | 6: t := Sym.newType(Sym.fVariant, 16, 8); - | 7: t := Sym.newType(Sym.fEnum, 1, 1); - | 8: t := Sym.newType(Sym.fRecord, 16, 8); - | 9: t := Sym.newType(Sym.fProc, 8, 8); - | else: t := Sym.newType(Sym.fPtr, 8, 8); - end; - x := rnd(numPool); t^.base := pool[x]; - t^.len := rnd(5); - x := rnd(4); t^.vol := x = 0; - x := rnd(4); t^.variadic := (t^.form = Sym.fProc) and (x = 0); - x := rnd(2); t^.tuple := (t^.form = Sym.fRecord) and (x = 0); - if (t^.form = Sym.fRecord) or (t^.form = Sym.fProc) or (t^.form = Sym.fVariant) then - m := rnd(4); - t^.fields := fields(m, t^.form = Sym.fProc); - t^.len := m; - if t^.form = Sym.fRecord then t^.base := nil; end; - x := rnd(2); - if (t^.form = Sym.fProc) and (x = 0) then t^.base := nil; end; - if t^.form = Sym.fVariant then - f := t^.fields; - while f # nil do - f^.cls := Sym.oCase; - x := rnd(3); f^.fields := fields(x, false); - f := f^.next; - end; - end; - end; - x := rnd(3); - if x = 0 then - x := rnd(20); t^.obj := Sym.newObj(Sym.oType, names[x], t); - x := rnd(3); t^.obj^.home := mods[x]; - end; - add(t); -end; - -proc main*; -var - i, k, op, x, y, z, n, d: INT; t, o2: ^Sym.Type; o: ^Sym.Obj; v: I64; - saved: [Sym.MaxDepth]INT; arg: []U8; -begin - seed := 11; - classes := [Sym.oConst, Sym.oType, Sym.oVar, Sym.oProc, Sym.oModule, Sym.oField, Sym.oCase, Sym.oBuiltin]; - for i := 0 to 19 do names[i] := Scan.intern(ADR(Words[i][0]), LEN(Words[i])); end; - for i := 0 to 2 do - NEW(mods[i], Heap.heap); - mods[i]^.sname := names[i * 5]; - end; - Sym.setCurModule(mods[0]); - base[0] := Sym.tI8; base[1] := Sym.tI16; base[2] := Sym.tI32; base[3] := Sym.tI64; base[4] := Sym.tU8; - base[5] := Sym.tU16; base[6] := Sym.tU32; base[7] := Sym.tU64; base[8] := Sym.tBool; base[9] := Sym.tF32; - base[10] := Sym.tReal; base[11] := Sym.tInt; - for i := 0 to 11 do add(base[i]); end; - arg := ""; - if ARGC > 1 then arg := Files.arg(1); end; - if LEN(arg) > 0 then - if LEN(Scan.open("lib/Rt.raz")) # 0 then Diag.fatal("no file"); end; - Scan.next; Scan.next; - end; - numObjs := 0; - for k := 1 to 4000 do - op := rnd(14); - match op of - | 0, 1, 2: makeType; - | 3, 4: - if numObjs < 300 then - x := rnd(8); y := rnd(20); - if Sym.find(x, names[y]) = nil then - z := rnd(8); n := rnd(numPool); - o := Sym.newObj(classes[z], names[y], pool[n]); - z := rnd(2); o^.exported := z = 0; - z := rnd(3); o^.home := mods[z]; - ok(Sym.insert(o, x)); - objs[numObjs] := o; INC(numObjs); - Fmt.print("I {} {} {}\n", [Fmt.int(x), Fmt.str(nm(y)), Fmt.int(o^.scope)]); - end; - end; - | 5: - x := rnd(8); y := rnd(20); o := Sym.find(x, names[y]); - Fmt.print("F {} {} ", [Fmt.int(x), Fmt.str(nm(y))]); - if o = nil then Out.str("-\n"); - else Fmt.print("{} {}\n", [Fmt.int(INT(o^.cls)), Fmt.int(o^.scope)]); end; - | 6: - x := rnd(8); y := rnd(20); - if Sym.scopeDepth() < 6 then ok(Sym.openScope(x)); end; - o := Sym.lookup(names[y]); - Fmt.print("L {} {} ", [Fmt.int(Sym.scopeDepth()), Fmt.str(nm(y))]); - if o = nil then Out.str("-\n"); - else Fmt.print("{} {}\n", [Fmt.int(INT(o^.cls)), Fmt.int(o^.scope)]); end; - z := rnd(2); - if (Sym.scopeDepth() > 1) and (z = 0) then Sym.closeScope; end; - | 7: - y := rnd(20); x := rnd(9) - 1; z := rnd(3); Sym.setCurModule(mods[z]); - o := Sym.closest(names[y], x); - Fmt.print("C {} {} ", [Fmt.str(nm(y)), Fmt.int(x)]); - if o = nil then Out.str("-\n"); - else Fmt.print("{} {}\n", [Fmt.str(Scan.nameOf(o^.name)), Fmt.int(o^.scope)]); end; - | 8: - x := rnd(numPool); z := rnd(3); Sym.setCurModule(mods[z]); - Fmt.print("T {}\n", [Fmt.str(Sym.typeName(pool[x]))]); - | 9: - x := rnd(numPool); y := rnd(numPool); - Fmt.print("S {} {}\n", [Fmt.int(bit(Sym.same(pool[x], pool[y]))), Fmt.int(bit(Sym.same(pool[x], pool[x])))]); - t := Sym.newType(Sym.fPtr, 8, 8); t^.base := pool[x]; - o2 := t; t := Sym.newType(Sym.fPtr, 8, 8); t^.base := pool[x]; - Fmt.print("S {}\n", [Fmt.int(bit(Sym.same(o2, t)))]); - | 10: - if numObjs > 0 then - x := rnd(numObjs); - Out.str("P "); Out.hex(Sym.fingerprint(objs[x]), 16); Out.ln; - end; - | 11: - x := rnd(numPool); y := rnd(1 shl 20); z := rnd(2); n := rnd(2); - v := I64(y) * 4096 * I64(z) - I64(y) * I64(n); - t := pool[x]; - Fmt.print("B {} {} {} {} {} {} {}\n", [Fmt.int(bit(Sym.fits(v, t))), Fmt.int(bit(Sym.isInt(t))), - Fmt.int(bit(Sym.isScalar(t))), Fmt.int(bit(Sym.isAggregate(t))), Fmt.int(bit(Sym.inTwoRegs(t))), - Fmt.int(bit(Sym.behindPointer(t))), Fmt.int(Sym.alignUp(y, 1 shl z))]); - | 12: - if (Sym.scopeDepth() > 1) and (Sym.scopeDepth() < 6) then - d := Sym.saveScopes(saved); - Fmt.print("V {} {}\n", [Fmt.int(Sym.scopeDepth()), Fmt.int(Sym.topScope())]); - Sym.restoreScopes(d, saved); - Fmt.print("V {} {}\n", [Fmt.int(Sym.scopeDepth()), Fmt.int(Sym.topScope())]); - x := Sym.newScope(); - Fmt.print("N {}\n", [Fmt.int(x)]); - end; - | else: - x := Sym.scopeDepth(); - if x > 3 then Sym.cutScopes(2); end; - Fmt.print("X {} {}\n", [Fmt.int(x), Fmt.int(Sym.scopeDepth())]); - end; - end; - for i := 0 to 11 do - Fmt.print("U {} {} {} {}\n", [Fmt.int(INT(base[i]^.form)), Fmt.int(base[i]^.size), - Fmt.int(bit(base[i]^.signed)), Fmt.str(Scan.nameOf(base[i]^.obj^.name))]); - end; - if arg = "dup" then - o := Sym.newObj(Sym.oVar, names[3], Sym.tI8); - ok(Sym.insert(o, 100)); - ok(Sym.insert(o, 100)); - end; - if arg = "deep" then - Sym.cutScopes(1); - for i := 1 to Sym.MaxDepth + 1 do ok(Sym.openScope(i)); end; - end; -end; - -end SymDump. diff --git a/self/test/X64Dump.pas b/self/test/X64Dump.pas deleted file mode 100644 index 7d44a09..0000000 --- a/self/test/X64Dump.pas +++ /dev/null @@ -1,160 +0,0 @@ -{ Writes every instruction the encoder makes, with operands drawn by a - fixed pseudo-random script, then prints the bytes, the fixups and the - listing (raz -S) of what it made: the seed's side of a test of - self/X64.raz, whose X64Dump.raz does the same and prints the same. } -program x64dump; -{$mode objfpc}{$H-} -uses diag, scan, chunk, x64; -var - seed: int64; - i, k, op, a, b, c, d, lab1, lab2: longint; - m: TMem; - path: string; - -function Rnd(n: longint): longint; -begin - seed := (seed * 1103515245 + 12345) and $7FFFFFFF; - Rnd := (seed shr 8) mod n; -end; - -{ a register, with the stack and base pointers and the high ones often enough } -function Reg: longint; -begin - Reg := Rnd(16); -end; - -{ a size of 1, 2, 4 or 8 bytes } -function Size: longint; -begin - Size := 1 shl Rnd(4); -end; - -{ a value that fits size bytes, of 8 as 32 bits } -function Imm(sz: longint): longint; -var x: longint; -begin - x := Rnd(1 shl 30); - case Rnd(3) of - 0: Imm := x mod 100 - 50; - 1: Imm := x - (1 shl 29); - else Imm := x mod 20000 - 10000; - end; - if sz = 1 then Imm := Imm mod 128 - else if sz = 2 then Imm := Imm mod 32768; -end; - -function RandMem: TMem; -var kind, base, idx, sc, disp, x: longint; -begin - kind := Rnd(6); - base := Reg; idx := Reg; sc := 1 shl Rnd(4); x := Rnd(5); - case x of - 0: disp := 0; - 1: disp := Rnd(250) - 125; - 2: disp := Rnd(1 shl 20) - (1 shl 19); - 3: disp := 127 + Rnd(3) - 1; - else disp := -128 + Rnd(3) - 1; - end; - case kind of - 0, 1: RandMem := Mem(base, disp); - 2: RandMem := MemRip(Rnd(5), disp); - 3, 4: RandMem := MemIdx(base, idx, sc, disp); - else RandMem := Mem(base, 0); - end; -end; - -begin - seed := 3; - path := 'lib/Rt.raz'; - if Open(path) <> '' then Fatal('no file'); - listing := true; - for i := 0 to 4 do NewChunk(secText, i - 1, i); - curFile := Intern(@path[1], length(path)); - BeginChunk(0); - lab1 := NoLabel; lab2 := NoLabel; - for k := 1 to 3000 do begin - if k mod 7 = 0 then begin a := Rnd(300); b := Rnd(60); NoteLine(1 + a, b) end; - op := Rnd(50); - case op of - 0: begin a := Reg; b := Reg; MovRR(a, b) end; - 1: begin - a := Reg; b := Rnd(6); c := Rnd(1 shl 30); - case b of - 0: MovRI(a, 0); - 1: MovRI(a, c); - 2: MovRI(a, -c); - 3: MovRI(a, int64(c) * 8 + 5); - 4: MovRI(a, int64(c) * 4096 * 4096 * 9 - 7); - else MovRI(a, 0); - end; - end; - 2: begin a := Rnd(8); m := RandMem; b := Size; c := Imm(b); AluMI(a, m, c, b) end; - 3: begin m := RandMem; b := Size; c := Imm(b); StoreI(m, c, b) end; - 4: begin a := Reg; m := RandMem; b := Size; c := Rnd(2); Load(a, m, b, c = 0) end; - 5: begin m := RandMem; a := Reg; b := Size; Store(m, a, b) end; - 6: begin a := Reg; m := RandMem; Lea(a, m) end; - 7: begin a := Rnd(8); b := Reg; c := Reg; Alu(a, b, c) end; - 8: begin a := Rnd(8); b := Reg; c := Imm(8); AluI(a, b, c) end; - 9: begin a := Rnd(8); b := Reg; m := RandMem; AluM(a, b, m) end; - 10: begin a := Reg; b := Reg; Imul(a, b) end; - 11: begin a := Reg; c := Imm(8); ImulI(a, c) end; - 12: begin a := Rnd(3); b := Reg; if a = 0 then a := shShl else if a = 1 then a := shShr else a := shSar; Shift(a, b) end; - 13: begin a := Rnd(3); b := Reg; c := Rnd(64); if a = 0 then a := shShl else if a = 1 then a := shShr else a := shSar; ShiftI(a, b, c) end; - 14: begin a := Rnd(4); b := Reg; if a < 2 then a := a + 2 else a := a + 4; Unary(a, b) end; - 15: Cqo; - 16: begin a := Reg; b := 1 shl Rnd(3); c := Rnd(2); Extend(a, b, c = 0) end; - 17: begin a := Rnd(16); b := Reg; SetCC(a, b) end; - 18: begin a := Reg; b := Reg; TestRR(a, b) end; - 19: begin a := Reg; Push(a) end; - 20: begin a := Reg; Pop(a) end; - 21: begin a := Rnd(5); CallChunk(a) end; - 22: begin a := Rnd(1000); CallBack(a) end; - 23: begin a := Reg; CallR(a) end; - 24: begin a := Reg; JmpR(a) end; - 25: begin m := RandMem; CallM(m) end; - 26: begin a := Rnd(5); case a of 0: Ret; 1: Leave; 2: Syscall; 3: Mfence; else Ud2 end end; - 27: begin a := 8 shl Rnd(3); Align(a) end; - 28: begin a := Rnd(5); case a of 0: RepMovsb; 1: Std; 2: Cld; 3: RepStosb; else RepeCmpsb end end; - 29: begin m := RandMem; a := Reg; LockCmpxchg(m, a) end; - 30: begin m := RandMem; a := Reg; Xchg(m, a) end; - 31: begin m := RandMem; a := Reg; LockXadd(m, a) end; - 32: begin a := Reg; b := Reg; MovqXR(a, b) end; - 33: begin a := Reg; b := Reg; MovqRX(a, b) end; - 34: begin a := Reg; b := Reg; MovX(a, b) end; - 35: begin a := Reg; m := RandMem; b := Rnd(2); MovsXM(a, m, b = 0) end; - 36: begin m := RandMem; a := Reg; b := Rnd(2); MovsMX(m, a, b = 0) end; - 37: begin - d := Rnd(5); a := Reg; b := Reg; c := Rnd(2); - case d of 0: d := $58; 1: d := $59; 2: d := $5C; 3: d := $5E; else d := $5A end; - Sse(d, a, b, c = 0); - end; - 38: begin - d := Rnd(5); a := Reg; m := RandMem; c := Rnd(2); - case d of 0: d := $58; 1: d := $59; 2: d := $5C; 3: d := $5E; else d := $5A end; - SseM(d, a, m, c = 0); - end; - 39: begin a := Reg; b := Reg; c := Rnd(2); Ucomis(a, b, c = 0) end; - 40: begin a := Reg; b := Reg; c := Rnd(2); Cvtsi2s(a, b, c = 0) end; - 41: begin a := Reg; b := Reg; c := Rnd(2); Cvtts2si(a, b, c = 0) end; - 42: begin a := Reg; b := Rnd(64); Btc(a, b) end; - 43: begin - a := Rnd(16); b := Rnd(2); - if b = 0 then Jmp(lab1) else Jcc(a, lab2); - end; - 44: begin a := Rnd(16); b := Rnd(2); c := pc - Rnd(200); if b = 0 then JmpBack(c) else JccBack(a, c) end; - 45: if Rnd(3) = 0 then begin FixLink(lab1); lab1 := NoLabel end - else begin FixLinkTo(lab2, pc - 20); lab2 := NoLabel end; - 46: begin Jmp(lab1); DropJumpTo(lab1) end; - 47: begin a := JoinLinks(lab1, lab2); lab1 := a; lab2 := NoLabel end; - else begin a := Rnd(256); Put1(a) end; - end; - end; - FixLink(lab1); FixLink(lab2); - EndChunk(0); - chunks^[0].live := true; - writeln('pc ', pc, ' fixups ', numFixups, ' lines ', numLines, ' said ', SaidCount); - for i := 0 to pc - 1 do write(HexStr(code^[i], 2)); - writeln; - for i := 0 to numFixups - 1 do writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend); - List(-1); -end. diff --git a/self/test/X64Dump.raz b/self/test/X64Dump.raz deleted file mode 100644 index 6747ce6..0000000 --- a/self/test/X64Dump.raz +++ /dev/null @@ -1,208 +0,0 @@ -(* Writes every instruction the encoder makes, with operands drawn by a - fixed pseudo-random script, then prints the bytes, the fixups and the - listing (raz -S) of what it made: self/X64.raz's side of a test - against the seed's, X64Dump.pas, which prints the same. *) -module X64Dump; -import Out, Fmt, Diag, Scan, Chunk, X64; - -var seed: I64; - -proc rnd(n: INT): INT; -begin - seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; - return INT((seed shr 8) mod I64(n)); -end; - -(* a register *) -proc reg: INT; -begin - return rnd(16); -end; - -(* a size of 1, 2, 4 or 8 bytes *) -proc size: INT; -begin - return 1 shl rnd(4); -end; - -(* a value that fits sz bytes, of 8 as 32 bits *) -proc imm(sz: INT): INT; -var x, r: INT; -begin - x := rnd(1 shl 30); - match rnd(3) of - | 0: r := x mod 100 - 50; - | 1: r := x - (1 shl 29); - | else: r := x mod 20000 - 10000; - end; - if sz = 1 then - r := r mod 128; - elsif sz = 2 then - r := r mod 32768; - end; - return r; -end; - -proc randMem: X64.Mem; -var kind, base, idx, sc, disp, x: INT; -begin - kind := rnd(6); - base := reg(); idx := reg(); sc := 1 shl rnd(4); x := rnd(5); - match x of - | 0: disp := 0; - | 1: disp := rnd(250) - 125; - | 2: disp := rnd(1 shl 20) - (1 shl 19); - | 3: disp := 127 + rnd(3) - 1; - | else: disp := -128 + rnd(3) - 1; - end; - match kind of - | 0, 1: return X64.mem(base, disp); - | 2: return X64.memRip(rnd(5), disp); - | 3, 4: return X64.memIdx(base, idx, sc, disp); - | else: return X64.mem(base, 0); - end; -end; - -proc main*; -var - i, k, op, a, b, c, d, lab1, lab2: INT; m: X64.Mem; path: []U8; -begin - seed := 3; - path := "lib/Rt.raz"; - if LEN(Scan.open(path)) # 0 then Diag.fatal("no file"); end; - X64.setListing(true); - for i := 0 to 4 do c := Chunk.newChunk(Chunk.secText, i - 1, i); end; - Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path))); - Chunk.beginChunk(0); - lab1 := X64.NoLabel; lab2 := X64.NoLabel; - for k := 1 to 3000 do - if k mod 7 = 0 then a := rnd(300); b := rnd(60); Chunk.noteLine(1 + a, b); end; - op := rnd(50); - match op of - | 0: a := reg(); b := reg(); X64.movRR(a, b); - | 1: - a := reg(); b := rnd(6); c := rnd(1 shl 30); - match b of - | 0: X64.movRI(a, 0); - | 1: X64.movRI(a, c); - | 2: X64.movRI(a, -c); - | 3: X64.movRI(a, I64(c) * 8 + 5); - | 4: X64.movRI(a, I64(c) * 4096 * 4096 * 9 - 7); - | else: X64.movRI(a, 0); - end; - | 2: a := rnd(8); m := randMem(); b := size(); c := imm(b); X64.aluMI(a, m, c, b); - | 3: m := randMem(); b := size(); c := imm(b); X64.storeI(m, c, b); - | 4: a := reg(); m := randMem(); b := size(); c := rnd(2); X64.load(a, m, b, c = 0); - | 5: m := randMem(); a := reg(); b := size(); X64.store(m, a, b); - | 6: a := reg(); m := randMem(); X64.lea(a, m); - | 7: a := rnd(8); b := reg(); c := reg(); X64.alu(a, b, c); - | 8: a := rnd(8); b := reg(); c := imm(8); X64.aluI(a, b, c); - | 9: a := rnd(8); b := reg(); m := randMem(); X64.aluM(a, b, m); - | 10: a := reg(); b := reg(); X64.imul(a, b); - | 11: a := reg(); c := imm(8); X64.imulI(a, c); - | 12: - a := rnd(3); b := reg(); - if a = 0 then a := X64.shShl; elsif a = 1 then a := X64.shShr; else a := X64.shSar; end; - X64.shift(a, b); - | 13: - a := rnd(3); b := reg(); c := rnd(64); - if a = 0 then a := X64.shShl; elsif a = 1 then a := X64.shShr; else a := X64.shSar; end; - X64.shiftI(a, b, c); - | 14: - a := rnd(4); b := reg(); - if a < 2 then a := a + 2; else a := a + 4; end; - X64.unary(a, b); - | 15: X64.cqo; - | 16: a := reg(); b := 1 shl rnd(3); c := rnd(2); X64.extend(a, b, c = 0); - | 17: a := rnd(16); b := reg(); X64.setCC(a, b); - | 18: a := reg(); b := reg(); X64.testRR(a, b); - | 19: a := reg(); X64.push(a); - | 20: a := reg(); X64.pop(a); - | 21: a := rnd(5); X64.callChunk(a); - | 22: a := rnd(1000); X64.callBack(a); - | 23: a := reg(); X64.callR(a); - | 24: a := reg(); X64.jmpR(a); - | 25: m := randMem(); X64.callM(m); - | 26: - a := rnd(5); - match a of - | 0: X64.ret; - | 1: X64.leave; - | 2: X64.syscall; - | 3: X64.mfence; - | else: X64.ud2; - end; - | 27: a := 8 shl rnd(3); X64.align(a); - | 28: - a := rnd(5); - match a of - | 0: X64.repMovsb; - | 1: X64.std; - | 2: X64.cld; - | 3: X64.repStosb; - | else: X64.repeCmpsb; - end; - | 29: m := randMem(); a := reg(); X64.lockCmpxchg(m, a); - | 30: m := randMem(); a := reg(); X64.xchg(m, a); - | 31: m := randMem(); a := reg(); X64.lockXadd(m, a); - | 32: a := reg(); b := reg(); X64.movqXR(a, b); - | 33: a := reg(); b := reg(); X64.movqRX(a, b); - | 34: a := reg(); b := reg(); X64.movX(a, b); - | 35: a := reg(); m := randMem(); b := rnd(2); X64.movsXM(a, m, b = 0); - | 36: m := randMem(); a := reg(); b := rnd(2); X64.movsMX(m, a, b = 0); - | 37: - d := rnd(5); a := reg(); b := reg(); c := rnd(2); - match d of - | 0: d := 58H; - | 1: d := 59H; - | 2: d := 5CH; - | 3: d := 5EH; - | else: d := 5AH; - end; - X64.sse(d, a, b, c = 0); - | 38: - d := rnd(5); a := reg(); m := randMem(); c := rnd(2); - match d of - | 0: d := 58H; - | 1: d := 59H; - | 2: d := 5CH; - | 3: d := 5EH; - | else: d := 5AH; - end; - X64.sseM(d, a, m, c = 0); - | 39: a := reg(); b := reg(); c := rnd(2); X64.ucomis(a, b, c = 0); - | 40: a := reg(); b := reg(); c := rnd(2); X64.cvtsi2s(a, b, c = 0); - | 41: a := reg(); b := reg(); c := rnd(2); X64.cvtts2si(a, b, c = 0); - | 42: a := reg(); b := rnd(64); X64.btc(a, b); - | 43: - a := rnd(16); b := rnd(2); - if b = 0 then X64.jmp(lab1); else X64.jcc(a, lab2); end; - | 44: - a := rnd(16); b := rnd(2); c := Chunk.pc - rnd(200); - if b = 0 then X64.jmpBack(c); else X64.jccBack(a, c); end; - | 45: - a := rnd(3); - if a = 0 then - X64.fixLink(lab1); lab1 := X64.NoLabel; - else - X64.fixLinkTo(lab2, Chunk.pc - 20); lab2 := X64.NoLabel; - end; - | 46: X64.jmp(lab1); X64.dropJumpTo(lab1); - | 47: a := X64.joinLinks(lab1, lab2); lab1 := a; lab2 := X64.NoLabel; - | else: a := rnd(256); Chunk.put1(a); - end; - end; - X64.fixLink(lab1); X64.fixLink(lab2); - Chunk.endChunk(0); - Chunk.setLive(0); - Fmt.print("pc {} fixups {} lines {} said {}\n", [Fmt.int(Chunk.pc), Fmt.int(Chunk.numFixups), - Fmt.int(Chunk.numLines), Fmt.int(X64.saidCount())]); - for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end; - Out.ln; - for i := 0 to Chunk.numFixups - 1 do - Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]); - end; - X64.list(-1); -end; - -end X64Dump. diff --git a/self/test/genasm.py b/self/test/genasm.py deleted file mode 100644 index 5749c55..0000000 --- a/self/test/genasm.py +++ /dev/null @@ -1,244 +0,0 @@ -#!/usr/bin/env python3 -"""Writes the files the assembler of X64 is tested on, into the directory -given: valid.raz, a long run of instructions of every kind the assembler -knows, and one small file for each error it reports. Each ends in `end`, -as a code procedure's body does. Fixed seed: the same files each run.""" -import random, sys, os - -random.seed(7) -out = sys.argv[1] -os.makedirs(out, exist_ok=True) - -R64 = "rax rcx rdx rbx rsp rbp rsi rdi r8 r9 r10 r11 r12 r13 r14 r15".split() -R32 = "eax ecx edx ebx esp ebp esi edi r8d r9d r10d r11d r12d r13d r14d r15d".split() -R16 = "ax cx dx bx sp bp si di r8w r9w r10w r11w r12w r13w r14w r15w".split() -R8 = "al cl dl bl spl bpl sil dil r8b r9b r10b r11b r12b r13b r14b r15b".split() -BY = {8: R64, 4: R32, 2: R16, 1: R8} -PRE = {8: "qword ", 4: "dword ", 2: "word ", 1: "byte "} -XM = ["xmm%d" % i for i in range(16)] -CC = "o no b ae e ne be a s ns p np l ge le g c nae nc nb z nz na nbe nge nl ng nle".split() - - -def reg(size=8): - return random.choice(BY[size]) - - -def mem(size=0): - k = random.randrange(8) - b = random.choice(R64) - i = random.choice([r for r in R64 if r != "rsp"]) - d = random.choice([0, 8, -8, 127, -128, 128, 4096, -4096, 100000]) - s = random.choice([1, 2, 4, 8]) - p = PRE[size] if size else "" - if k == 0: - t = "[%s]" % b - elif k == 1: - t = "[%s + %d]" % (b, abs(d)) if d >= 0 else "[%s - %d]" % (b, -d) - elif k == 2: - t = "[%s + %s * %d]" % (b, i, s) - elif k == 3: - t = "[%s + %s * %d + %d]" % (b, i, s, abs(d)) if d >= 0 else "[%s + %s * %d - %d]" % (b, i, s, -d) - elif k == 4: - t = "[%s + %s]" % (b, i) - elif k == 5: - t = "[%s + 0]" % b - elif k == 6: - t = "[rsp + %d]" % abs(d) - else: - t = "[%s - %d]" % (b, abs(d) + 1) - return p + t - - -def imm(size): - if size == 1: - return str(random.choice([0, 1, -1, 127, 255, -128, 77])) - if size == 2: - return str(random.choice([0, 1, -1, 300, 32767, -32768, 255, 65535])) - return str(random.choice([0, 1, -1, 127, 128, -128, -129, 100000, -100000, 2147483647, -2147483648, 4294967295])) - - -def size(): - return random.choice([1, 2, 4, 8]) - - -lines = [] - - -def emit(s): - lines.append(" " + s + ";") - - -for n in range(900): - k = random.randrange(40) - sz = size() - if k < 6: - op = random.choice("add or adc sbb and sub xor cmp".split()) - f = random.randrange(5) - if f == 0: - emit("%s %s, %s" % (op, reg(sz), reg(sz))) - elif f == 1: - emit("%s %s, %s" % (op, reg(sz), mem(sz if random.random() < .5 else 0))) - elif f == 2: - emit("%s %s, %s" % (op, mem(sz if random.random() < .5 else 0), reg(sz))) - elif f == 3: - emit("%s %s, %s" % (op, reg(sz), imm(sz))) - else: - emit("%s %s, %s" % (op, mem(sz), imm(sz))) - elif k < 10: - f = random.randrange(5) - if f == 0: - emit("mov %s, %s" % (reg(sz), reg(sz))) - elif f == 1: - emit("mov %s, %s" % (reg(sz), mem())) - elif f == 2: - emit("mov %s, %s" % (mem(), reg(sz))) - elif f == 3: - v = random.choice([0, 5, -5, 2147483647, 4294967295, 4294967296, -2147483649, 123456789012345]) - emit("mov %s, %d" % (reg(8 if sz >= 4 else sz) if sz >= 4 else reg(sz), v if sz == 8 else (v % 65536 if sz == 2 else v % 256 if sz == 1 else v % 4294967296))) - else: - emit("mov %s, %s" % (mem(sz), imm(sz))) - elif k == 10: - emit("test %s, %s" % (reg(sz), random.choice([reg(sz), imm(sz) if sz != 1 else "1"]))) - elif k == 11: - emit("xchg %s, %s" % (random.choice([reg(sz), mem()]), reg(sz))) - elif k == 12: - emit("%slock %s %s, %s" % ("", random.choice(["cmpxchg", "xadd"]), mem(), reg(sz))) - elif k == 13: - emit("lea %s, %s" % (reg(random.choice([2, 4, 8])), mem())) - elif k == 14: - op = random.choice(["movzx", "movsx"]) - emit("%s %s, %s" % (op, reg(random.choice([2, 4, 8])), random.choice([mem(random.choice([1, 2])), reg(random.choice([1, 2]))]))) - elif k == 15: - emit("movsxd %s, %s" % (reg(8), random.choice([mem(4), reg(4)]))) - elif k == 16: - emit("%s %s" % (random.choice("not neg mul imul div idiv inc dec".split()), random.choice([reg(sz), mem(sz)]))) - elif k == 17: - emit("imul %s" % ", ".join([reg(sz if sz > 1 else 4), random.choice([reg(sz if sz > 1 else 4)] * 1 + [mem()])] + ([imm(sz if sz > 1 else 4)] if random.random() < .4 else [])).replace("%", "%")) - elif k == 18: - op = random.choice("rol ror rcl rcr shl shr sal sar".split()) - emit("%s %s, %s" % (op, random.choice([reg(sz), mem(sz)]), random.choice([str(random.randrange(64)), "cl"]))) - elif k == 19: - emit("%s %s" % (random.choice(["push", "pop"]), reg(8))) - elif k == 20: - op = random.choice(["call", "jmp"]) - emit("%s %s" % (op, random.choice([reg(8), mem()]) if op == "call" else mem())) - elif k == 21: - emit("set%s %s" % (random.choice(CC), random.choice([reg(1), mem(1)]))) - elif k == 22: - emit("cmov%s %s, %s" % (random.choice(CC), reg(random.choice([2, 4, 8])), random.choice([reg(8), mem()]))) - elif k == 23: - op = random.choice("sqrt add mul sub min div max".split()) + random.choice(["sd", "ss"]) - emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()]))) - elif k == 24: - op = random.choice("punpcklbw punpcklwd pcmpeqb pand pandn por pxor paddb psubb".split()) - emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()]))) - elif k == 25: - emit("pshufd %s, %s, %d" % (random.choice(XM), random.choice([random.choice(XM), mem()]), random.randrange(256))) - elif k == 26: - op = random.choice(["movdqu", "movdqa"]) - if random.random() < .5: - emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()]))) - else: - emit("%s %s, %s" % (op, mem(), random.choice(XM))) - elif k == 27: - emit("pmovmskb %s, %s" % (reg(4), random.choice(XM))) - elif k == 28: - emit("%s %s, %s" % (random.choice("bsf bsr tzcnt lzcnt popcnt".split()), reg(random.choice([4, 8])), random.choice([reg(8), mem()]))) - elif k == 29: - op = random.choice(["movsd", "movss"]) - if random.random() < .5: - emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()]))) - else: - emit("%s %s, %s" % (op, mem(), random.choice(XM))) - elif k == 30: - op = random.choice(["movq", "movd"]) - if random.random() < .5: - emit("%s %s, %s" % (op, random.choice(XM), random.choice([reg(8), mem()]))) - else: - emit("%s %s, %s" % (op, random.choice([reg(8), mem()]), random.choice(XM))) - elif k == 31: - emit("%s %s, %s" % (random.choice(["ucomisd", "ucomiss"]), random.choice(XM), random.choice([random.choice(XM), mem()]))) - elif k == 32: - emit("%s %s, %s" % (random.choice(["cvtsi2sd", "cvtsi2ss"]), random.choice(XM), random.choice([reg(random.choice([4, 8])), mem(random.choice([4, 8]))]))) - elif k == 33: - emit("%s %s, %s" % (random.choice(["cvttsd2si", "cvttss2si"]), reg(random.choice([4, 8])), random.choice([random.choice(XM), mem()]))) - elif k == 34: - emit("%s %s, %s" % (random.choice(["cvtsd2ss", "cvtss2sd"]), random.choice(XM), random.choice([random.choice(XM), mem()]))) - elif k == 35: - emit(random.choice("ret leave syscall cpuid rdtsc pause nop ud2 int3 hlt cqo cdq mfence lfence sfence".split())) - elif k == 36: - emit("db " + ", ".join(str(random.choice([0, 1, 255, 128, 77, -1, -128])) for _ in range(random.randrange(1, 6)))) - elif k == 37: - lines.append(" L%d:" % n) - lines.append(" add rax, 1;") - lines.append(" j%s L%d;" % (random.choice(CC), n)) - lines.append(" jmp L%d;" % n) - elif k == 38: - lines.append(" jmp F%d;" % n) - lines.append(" nop;") - lines.append(" j%s F%d;" % (random.choice(CC), n)) - lines.append(" F%d:" % n) - else: - emit("lock add %s, %s" % (mem(sz), reg(sz))) - -open(os.path.join(out, "valid.raz"), "w").write("\n".join(lines) + "\n end\n") - -errors = { - "empty": "", - "badop": "foo rax;", - "noinsn": "42;", - "nosemi": "nop", - "undefined": "jmp nowhere;", - "twice": "a: nop; a: nop;", - "toomany": "add rax, rbx, rcx, rdx;", - "movimm": "mov 1, 2;", - "movmm": "mov [rax], [rbx];", - "addimm": "add 1, rax;", - "pushmem": "push [rax];", - "pushsmall": "push eax;", - "badmem": "mov rax, [rsi * 4];", - "badscale": "mov rax, [rsi + rdi * 3];", - "nomem": "mov rax, [];", - "unclosed": "mov rax, [rbx;", - "shiftcl": "shl rax, dl;", - "shiftimm": "shl 3, 1;", - "lea": "lea rax, rbx;", - "movzx": "movzx rax, rbx;", - "movzx4": "movzx rax, dword [rbx];", - "setsize": "sete rax;", - "cmovimm": "cmove rax, 5;", - "sse": "addsd rax, xmm1;", - "sse1": "addsd xmm1;", - "pshufd": "pshufd xmm1, xmm2;", - "pand3": "pand xmm1, xmm2, 3;", - "movdq": "movdqu rax, xmm1;", - "pmov": "pmovmskb xmm1, rax;", - "bits": "popcnt ax, bx;", - "movsd": "movsd rax, xmm1;", - "movq": "movq rax, rbx;", - "ucomi": "ucomisd rax, xmm1;", - "cvtsi": "cvtsi2sd rax, xmm1;", - "cvtt": "cvttsd2si xmm1, xmm2;", - "cvtss": "cvtss2sd rax, xmm1;", - "plainops": "ret rax;", - "dbrange": "db 256;", - "dbneg": "db -129;", - "imul1": "imul rax, 5;", - "imulmem": "imul [rax], rbx;", - "unary2": "not rax, rbx;", - "unaryimm": "neg 5;", - "inc": "inc 5;", - "xchgimm": "xchg rax, 5;", - "cmpxchg": "cmpxchg rax, 5;", - "calli": "call 5;", - "jmpimm": "jmp 5;", - "labels65": "".join("l%d: nop; " % i for i in range(65)), - "xmm16": "addsd xmm16, xmm1;", - "noend": None, -} -for name, body in errors.items(): - if body is None: - text = " nop;\n" - else: - text = " " + body + "\n end\n" - open(os.path.join(out, "err_%s.raz" % name), "w").write(text) diff --git a/self/test/genlex.py b/self/test/genlex.py deleted file mode 100644 index f2607ea..0000000 --- a/self/test/genlex.py +++ /dev/null @@ -1,29 +0,0 @@ -# Writes into the directory given a file for each message the scanner -# makes, with the places diag shows them in: after a tab, in a long -# line, after characters of several bytes, in a CRLF file. -import sys -d = sys.argv[1] -cases = { - "slip1": "x == y;\n", "slip2": "a && b;\n", "slip3": "a || b;\n", "slip4": "a != b;\n", "slip5": "!a;\n", - "str": "x := \"abc\n", "chr": "x := 'a\n", "chr2": "x := 'ab';\n", "chr3": "x := '';\n", - "esc": "x := \"\\q\";\n", "esc2": "x := 'a\\x41';\n", "esc3": "x := \"\\x4\";\n", - "esc4": "x := \"\\u41\";\n", "esc5": "x := \"\\u{110000}\";\n", "esc6": "x := \"\\u{D800}\";\n", - "esc7": "x := \"\\u{1234567}\";\n", "esc8": "x := \"\\u{}\";\n", "esc9": "x := \"\\u{41\";\n", - "esc10": "x := \"\\u{1F600}\\u{e9}\\x00\\xff\\n\\t\\r\\0\\\\\\'\\\"\";\n", - "cmt": "x := 1; (* open (* nested *)\n", "nul": "x := 1;\0 y;\n", "hexbad": "x := 12AB;\n", - "hexbig": "x := 1FFFFFFFFFFFFFFFFH;\n", "hexok": "x := 0FFFFFFFFFFFFFFFFH; y := 7FFFFFFFFFFFFFFFH;\n", - "decbig": "x := 9223372036854775808;\n", "decmax": "x := 9223372036854775807;\n", - "realhex": "x := 1A.5;\n", "realexp": "x := 1.5E;\n", "realexp2": "x := 1.5E+;\n", "realbig": "x := 1.0E309;\n", - "realmax": "x := 1.7976931348623159E308;\n", "reallong": "x := " + "1" * 254 + ".5;\n", - "digname": "x := 12abc;\n", "uni": "x := \u00e9;\n", "badutf": b"x := \"a\xc3(\";\n", "badutf2": b"x := \"\xed\xa0\x80\";\n", - "badutf3": b"x := \"\xc0\x80\";\n", "badutf4": b"x := \"\xf5\x80\x80\x80\";\n", "badutf5": b"x := \"\xe2\x82\";\n", - "okutf": "x := \"h\u00e9llo \u20ac \U0001F600\"; y := '\u00e9'; (* \u00e9 *)\n", - "unexp": "x := @;\n", "long": "x := " + "a + " * 60 + "@;\n", "longmid": "x := " + "a + " * 40 + "@ " + "+ b" * 40 + ";\n", - "tab": "\t\tx := @;\n", "multi": "x := \"\u00e9\u00e9\u00e9\" + @;\n", "ident64": "x" * 64 + ";\n", "ident63": "x" * 63 + ";\n", - "bigstr": "x := \"" + "a" * 70000 + "\";\n", "empty": "", "nonl": "x := y", - "ops": "+ - * / = # < <= > >= := : ; , . .. ... ( ) [ ] { } ^ & ~ | _ __ _a\n", - "words": "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 Volatile\n", -} -for k, v in cases.items(): - open(f"{d}/{k}.raz", "wb").write(v.encode("utf-8", "surrogateescape") if isinstance(v, str) else v) -open(f"{d}/crlf.raz", "wb").write(b"x := 1;\r\ny := @;\r\n") diff --git a/self/test/genreals.py b/self/test/genreals.py deleted file mode 100644 index 3074392..0000000 --- a/self/test/genreals.py +++ /dev/null @@ -1,19 +0,0 @@ -# Prints a raz module of reals that are hard to read exactly: the -# extremes, halves between neighbours, and many random ones. -import random -random.seed(7) -v = ["0.0", "1.0", "0.1", "4.9E-324", "2.4703282292062327E-324", "2.4703282292062328E-324", - "2.2250738585072014E-308", "2.2250738585072011E-308", "1.7976931348623157E308", - "9007199254740993.0", "9007199254740992.5", "9007199254740993.5", "0.000001E+3", - "123456789012345678901234567890.0E-10", "1.0E-400", "0.5E1", "5.0E-1"] -for _ in range(3000): - d = random.randint(1, 10 ** random.randint(1, 30)) - e = random.randint(-320, 300) - s = str(d) - v.append(s[0] + "." + (s[1:] or "0") + "E" + ("%+d" % e if random.random() < .5 else str(e))) -for _ in range(500): - v.append("%d.%d" % (random.randint(0, 10 ** 6), random.randint(0, 10 ** 12))) -print("module Reals;\nvar x: F64;\nbegin") -for s in v: - print(" x := " + s + ";") -print("end Reals.") diff --git a/src/Chunk.raz b/src/Chunk.raz new file mode 100644 index 0000000..3078ac5 --- /dev/null +++ b/src/Chunk.raz @@ -0,0 +1,354 @@ +(* Chunk: 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). + + Depends on: Scan, for names and memory; Diag, for positions. + Leaves out: the instructions; that is X64. + + Exported variables can't be set from outside, so the setters at the + end do what the seed's other units do to these. *) +module Chunk; +import Fmt, Diag, Scan; + +type + Section* = (secText, secRodata, secBss); + + Chunk* = record + sec*: Section; + start*, size*, align*: INT; (* in its section's buffer *) + firstFix*, numFix*: INT; (* its fixups: text's in fixups, rodata's in dataFixups *) + home*, name*: INT; (* its module and its name, for the symbol table; -1 if none *) + adr*: INT; (* its address, set by the linker *) + live*: BOOL; (* reached from the entry point *) + ext*: BOOL; (* bss: the address of a C symbol, its name *) + reals*: BOOL; (* code: computes with reals, first at realsAt *) + realsAt*: Diag.Pos; + saveMask*: INT; (* code: the registers of variables it saves, as bits of Gen's VarRegs *) + saveAt*: INT; (* ... 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 *) + Line* = record + at*, chunk*: INT; (* the place in text, and its chunk *) + path*, line*, col*: INT; (* 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 *) + VarNote* = record + chunk*, name*: INT; + off*: INT; (* from the frame pointer *) + kind*: INT; (* how Rt shows it: see Link *) + end; + + Fixup* = record + at*: INT; (* the 32-bit field, as an offset in text; in + dataFixups, the 64-bit one, from its chunk's start *) + chunk*: INT; (* the chunk it refers to *) + addend*: INT; (* added to the chunk's address *) + end; + +var + text*: ^U8; (* text *) + pc*: INT; (* its length *) + rodata*: ^U8; + rolen*: INT; + chunks*: ^Chunk; + numChunks*: INT; + fixups*: ^Fixup; + numFixups*: INT; + (* 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*: ^Fixup; + numDataFixups*: INT; + lines*: ^Line; + numLines*: INT; + curFile: INT; (* the file being compiled, for noteLine *) + curChunk*: INT; (* the chunk of code being written *) + varNotes*: ^VarNote; + numVarNotes*: INT; + + codeCap, roCap, chunkCap, fixCap, dataFixCap, lineCap, noteCap: INT; + +(* Room for n more bytes of code *) +proc room(n: INT); +begin + if pc + n > codeCap then + text := Scan.regrab(text, pc, codeCap * 2 + n); + codeCap := codeCap * 2 + n; + end; +end; + +proc put1*(b: INT); +begin + if pc + 16 > codeCap then room(16); end; + text[pc] := U8(b & 0FFH); + INC(pc); +end; + +(* The low 32 bits of v, least significant byte first *) +proc put4*(v: INT); +var i: INT; +begin + if pc + 16 > codeCap then room(16); end; + for i := 0 to 3 do text[pc + i] := U8((v shr (8 * i)) & 0FFH); end; + INC(pc, 4); +end; + +proc put4At*(at, v: INT); +var i: INT; +begin + for i := 0 to 3 do text[at + i] := U8((v shr (8 * i)) & 0FFH); end; +end; + +(* The 32 bits at at, as a signed number *) +proc get4At*(at: INT): INT; +var u, i: INT; +begin + u := 0; + for i := 0 to 3 do u := u * 256 + INT(text[at + 3 - i]); end; + if u >= 80000000H then u := u - 100000000H; end; + return u; +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. *) +proc takeBack*(n: INT); +begin + DEC(pc, n); + if (numLines > 0) and (lines[numLines - 1].at > pc) then + lines[numLines - 1].at := pc; + if (numLines > 1) and (lines[numLines - 2].at = pc) then + lines[numLines - 2] := lines[numLines - 1]; + DEC(numLines); + end; + end; +end; + +proc put8*(v: I64); +begin + put4(INT(v & 0FFFFFFFFH)); + put4(INT((v shr 32) & 0FFFFFFFFH)); +end; + +proc newChunk*(sec: Section; home, name: INT): INT; +var c: ^Chunk; +begin + if numChunks = chunkCap then + chunks := ^Chunk(Scan.regrab(^U8(chunks), numChunks * SIZE(Chunk), chunkCap * 2 * SIZE(Chunk))); + chunkCap := chunkCap * 2; + end; + c := ADR(chunks[numChunks]); + c^ := {}; + c^.sec := sec; + c^.home := home; + c^.name := name; + c^.align := 1; + c^.size := -1; (* not yet defined *) + INC(numChunks); + return numChunks - 1; +end; + +proc beginChunk*(c: INT); +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 & 31 # 0 do put1(0CCH); end; + curChunk := c; + chunks[c].start := pc; + chunks[c].align := 32; + chunks[c].firstFix := numFixups; +end; + +proc endChunk*(c: INT); +begin + chunks[c].size := pc - chunks[c].start; + chunks[c].numFix := numFixups - chunks[c].firstFix; +end; + +(* The n bytes at p are the data of rodata chunk c *) +proc setData*(c: INT; p: ^U8; n, align: INT); +begin + if rolen + n > roCap then + rodata := Scan.regrab(rodata, rolen, roCap * 2 + n); + roCap := roCap * 2 + n; + end; + COPY(rodata[rolen..rolen + n], p[0..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; + +proc setBss*(c: INT; size, align: INT); +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. *) +proc noteLine*(line, col: INT); +begin + if (numLines > 0) and (lines[numLines - 1].at = pc) then DEC(numLines); end; + 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 + return; + end; + if numLines = lineCap then + lines := ^Line(Scan.regrab(^U8(lines), numLines * SIZE(Line), lineCap * 2 * SIZE(Line))); + lineCap := lineCap * 2; + 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. *) +proc externChunk*(name: INT): INT; +var c: INT; +begin + for c := 0 to numChunks - 1 do + if chunks[c].ext and (chunks[c].name = name) then return c; end; + end; + c := newChunk(secBss, -1, name); + setBss(c, 8, 8); + chunks[c].ext := true; + return c; +end; + +proc addFixup*(at, chunk, addend: INT); +begin + if numFixups = fixCap then + fixups := ^Fixup(Scan.regrab(^U8(fixups), numFixups * SIZE(Fixup), fixCap * 2 * SIZE(Fixup))); + fixCap := fixCap * 2; + 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. *) +proc addDataFixup*(c, at, chunk, addend: INT); +begin + if numDataFixups = dataFixCap then + dataFixups := ^Fixup(Scan.regrab(^U8(dataFixups), numDataFixups * SIZE(Fixup), dataFixCap * 2 * SIZE(Fixup))); + dataFixCap := dataFixCap * 2; + end; + dataFixups[numDataFixups].at := at; + dataFixups[numDataFixups].chunk := chunk; + dataFixups[numDataFixups].addend := addend; + INC(numDataFixups); + INC(chunks[c].numFix); +end; + +proc noteVar*(chunk, name, off, kind: INT); +begin + if numVarNotes = noteCap then + varNotes := ^VarNote(Scan.regrab(^U8(varNotes), numVarNotes * SIZE(VarNote), noteCap * 2 * SIZE(VarNote))); + noteCap := noteCap * 2; + end; + 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 *) +proc chunkName*(c: INT): []U8; +begin + if chunks[c].name < 0 then return Diag.say("literal{}", [Fmt.int(c)]); end; + if chunks[c].home < 0 then return Scan.nameOf(chunks[c].name); end; + return Diag.say("{}.{}", [Fmt.str(Scan.nameOf(chunks[c].home)), Fmt.str(Scan.nameOf(chunks[c].name))]); +end; + +(* What Gen's Redo and Rewind put back: the code, fixups and lines made + since are forgotten *) +proc rewindTo*(atPc, atFixups, atLines: INT); +begin + pc := atPc; + numFixups := atFixups; + numLines := atLines; +end; + +(* The file the code is being made from, as its path interned *) +proc setCurFile*(path: INT); +begin + curFile := path; +end; + +proc curFilePath*: INT; +begin + return curFile; +end; + +proc setLive*(c: INT); +begin + chunks[c].live := true; +end; + +proc setAdr*(c: INT; a: INT); +begin + chunks[c].adr := a; +end; + +(* Chunk c computes with reals, the first of them at p *) +proc setReals*(c: INT; p: Diag.Pos); +begin + chunks[c].reals := true; + chunks[c].realsAt := p; +end; + +proc setSaves*(c, mask, at: INT); +begin + chunks[c].saveMask := mask; + chunks[c].saveAt := at; +end; + +begin + codeCap := 1 shl 20; + text := Scan.grab(codeCap); + pc := 0; + roCap := 1 shl 16; + rodata := Scan.grab(roCap); + rolen := 0; + chunkCap := 1 shl 10; + chunks := ^Chunk(Scan.grab(chunkCap * SIZE(Chunk))); + numChunks := 0; + fixCap := 1 shl 12; + fixups := ^Fixup(Scan.grab(fixCap * SIZE(Fixup))); + numFixups := 0; + dataFixCap := 1 shl 8; + dataFixups := ^Fixup(Scan.grab(dataFixCap * SIZE(Fixup))); + numDataFixups := 0; + lineCap := 1 shl 12; + lines := ^Line(Scan.grab(lineCap * SIZE(Line))); + numLines := 0; + noteCap := 1 shl 8; + varNotes := ^VarNote(Scan.grab(noteCap * SIZE(VarNote))); + numVarNotes := 0; +end Chunk. diff --git a/src/Diag.raz b/src/Diag.raz new file mode 100644 index 0000000..fc1ab64 --- /dev/null +++ b/src/Diag.raz @@ -0,0 +1,410 @@ +(* Diag: 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: Sys, to write and to ask about the terminal; Buf and Fmt, + to build what it writes. + Leaves out: wording. The callers say what is wrong, with say; a + message is at most 255 characters, which every message so far keeps + well within. A message made by say is kept for good, since it is + made only where it is about to be shown. *) +module Diag; +import Sys, Rt, Heap, Mem, Buf, Fmt, Str; + +type + (* A stretch of a source file: bytes a up to but not including b. + a = b marks the place between two characters. *) + Pos* = record f*, a*, b*: INT; end; + + File = record + path: []U8; + buf: ^U8; + len: INT; + end; + +const + MaxErrors* = 20; + Bold = "\x1B[1m"; Red = "\x1B[1;31m"; Yellow = "\x1B[1;33m"; + Cyan = "\x1B[1;36m"; Green = "\x1B[1;32m"; Blue = "\x1B[1;34m"; + Plain = "\x1B[0m"; + (* A long line is shown cut to this many bytes around the place, its + cut ends marked ... *) + ShownBytes = 100; + +var + errors*, warnings*: INT; + werror*: BOOL; (* -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*: BOOL; + + files: ^File; (* numFiles of them, in room for cap *) + numFiles, cap: INT; + colour, colourKnown, cwdKnown: BOOL; + cwd: Buf.Buf; (* the working directory and a /, or empty if unknown *) + out: Buf.Buf; (* the message being made *) + lastError: Pos; (* where the last error was *) + shown: BOOL; (* whether it was shown: its notes and help are only then *) + +(* Exported variables can't be set from outside, so these do it. *) +proc setWerror*(yes: BOOL); +begin + werror := yes; +end; + +proc setQuiet*(yes: BOOL); +begin + quiet := yes; +end; + +(* Paths are shown from the working directory where they are under it, + so messages read the same wherever the compiler or its library is. *) +proc shownPath*(path: []U8): []U8; +var d: []U8; err: INT; c: []U8; +begin + if not cwdKnown then + d, err := Sys.workDir(); + if err = 0 then + Buf.str(ADR(cwd), d); + Buf.add(ADR(cwd), '/'); + end; + cwdKnown := true; + end; + c := Buf.bytes(ADR(cwd)); + if (LEN(c) > 0) and Str.hasPrefix(path, c) then return path[LEN(c)..LEN(path)]; end; + return path; +end; + +proc fatal*(msg: []U8); forward; + +(* Memory, or the end of the compile when there is none *) +proc grab(size: INT): ^U8; +var p: ^U8; +begin + p := Mem.alloc(Heap.heap, size, 8); + if p = nil then fatal("out of memory"); end; + return p; +end; + +(* Keeps buf, len bytes of a file, under a number, which it gives back; + buf stays as it is, and its path is copied. *) +proc addFile*(path: []U8; buf: ^U8; len: INT): INT; +var more: ^File; i: INT; p: []U8; ok: BOOL; +begin + if numFiles = cap then + more := ^File(grab((2 * cap + 8) * SIZE(File))); + for i := 0 to numFiles - 1 do more[i] := files[i]; end; + if files # nil then Mem.free(Heap.heap, ^U8(files)); end; + files := more; + cap := 2 * cap + 8; + end; + p, ok := Str.copy(Heap.heap, shownPath(path)); + if not ok then fatal("out of memory"); end; + files[numFiles] := {path: p, buf: buf, len: len}; + INC(numFiles); + return numFiles - 1; +end; + +proc pathOf*(f: INT): []U8; +begin + return files[f].path; +end; + +(* Writing *) + +(* Whether NO_COLOR is set. The library can't tell it set to nothing + from not set, so that counts as not set, as no-color.org has it. *) +proc noColour: BOOL; +begin + return LEN(Sys.env("NO_COLOR")) > 0; +end; + +proc put(s: []U8); +begin + Buf.str(ADR(out), s); +end; + +proc putc(c: U8); +begin + Buf.add(ADR(out), c); +end; + +proc putNum(n: INT); +begin + Fmt.write(ADR(out), "{}", [Fmt.int(n)]); +end; + +(* The text of a number *) +proc say*(f: []U8; args: []Fmt.Arg): []U8; +var b: ^Buf.Buf; +begin + b := ^Buf.Buf(grab(SIZE(Buf.Buf))); + Buf.init(b, Heap.heap); + Fmt.write(b, f, args); + return Buf.bytes(b); +end; + +(* c, when colour is on *) +proc paintOn(c: []U8); +begin + if not colourKnown then + colour := Sys.isTerminal(2) and not noColour(); + colourKnown := true; + end; + if colour then put(c); end; +end; + +(* s in colour c, when colour is on *) +proc paint(c, s: []U8); +begin + paintOn(c); + put(s); + paintOn(Plain); +end; + +(* What has been made, written to standard error *) +proc flush; +var s: []U8; n: INT; +begin + s := Buf.bytes(ADR(out)); + while LEN(s) > 0 do + n := Sys.write(Sys.stderr, s); + if n <= 0 then break; end; + s := s[n..LEN(s)]; + end; + Buf.reset(ADR(out)); +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. *) +proc locate(p: Pos): (INT, INT); +var i, line, start: INT; buf: ^U8; +begin + buf := files[p.f].buf; + line := 1; + start := 0; + for i := 0 to p.a - 1 do + if buf[i] = 10 then INC(line); start := i + 1; end; + end; + return line, start; +end; + +proc lineOf*(p: Pos): INT; +var line: INT; +begin + line, _ := locate(p); + return line; +end; + +(* A byte that starts a character: every one but a UTF-8 continuation *) +proc starts(c: U8): BOOL; +begin + return (c & 0C0H) # 80H; +end; + +(* Characters from byte i to byte j of buf *) +proc chars(buf: ^U8; i, j: INT): INT; +var n: INT; +begin + n := 0; + while i < j do + if starts(buf[i]) then INC(n); end; + INC(i); + end; + return 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. *) +proc show(p: Pos; kind, kindColour, msg: []U8); +var line, start, stop, lo, hi, i, n: INT; buf: ^U8; f: ^File; digits: []U8; +begin + if p.f >= numFiles then + (* about no place in a file, as for Rt, which the compiler + imports before it reads one *) + paint(Bold, "raz:"); + put(" "); + paintOn(kindColour); put(kind); put(":"); paintOn(Plain); + put(" "); + paint(Bold, msg); + putc('\n'); + flush; + return; + end; + line, start := locate(p); + f := ADR(files[p.f]); + buf := f^.buf; + paintOn(Bold); + put(f^.path); put(":"); putNum(line); put(":"); putNum(chars(buf, start, p.a) + 1); put(":"); + paintOn(Plain); + put(" "); + paintOn(kindColour); put(kind); put(":"); paintOn(Plain); + put(" "); + paint(Bold, msg); + putc('\n'); + stop := start; + while (stop < f^.len) and (buf[stop] # 10) do INC(stop); end; + lo := start; + hi := stop; + if hi - lo > ShownBytes then + if p.a - lo > ShownBytes div 2 then lo := p.a - ShownBytes div 2; end; + while not starts(buf[lo]) do INC(lo); end; + if hi - lo > ShownBytes then hi := lo + ShownBytes; end; + while (hi < stop) and not starts(buf[hi]) do INC(hi); end; + end; + paintOn(Blue); + digits := say("{}", [Fmt.int(line)]); + for i := LEN(digits) to 4 do put(" "); end; + put(digits); put(" |"); + paintOn(Plain); + put(" "); + if lo > start then put("..."); end; + put(buf[lo..hi]); + if hi < stop then put("..."); end; + putc('\n'); + paint(Blue, " |"); + put(" "); + if lo > start then put(" "); end; + for i := lo to p.a - 1 do + if buf[i] = '\t' then putc('\t'); elsif starts(buf[i]) then putc(' '); end; + end; + if p.b < hi then n := chars(buf, p.a, p.b); else n := chars(buf, p.a, hi); end; + if n < 1 then n := 1; end; + paintOn(kindColour); + for i := 1 to n do putc('^'); end; + paintOn(Plain); + putc('\n'); + flush; +end; + +(* From the start of p to the end of q *) +proc join*(p, q: Pos): Pos; +begin + p.b := q.b; + return p; +end; + +(* The text at p, at most the 255 bytes a message can hold *) +proc source*(p: Pos): []U8; +var n: INT; +begin + n := p.b - p.a; + if n > 255 then n := 255; end; + return files[p.f].buf[p.a..p.a + n]; +end; + +(* Messages *) + +(* Line line of the file at path, as written, to at most 255 bytes *) +proc lineText*(path: []U8; line: INT): []U8; +var i, k, n, j: INT; f: ^File; want: []U8; +begin + want := shownPath(path); + for i := 0 to numFiles - 1 do + f := ADR(files[i]); + if f^.path = want then + k := 0; + n := 1; + while (n < line) and (k < f^.len) do + if f^.buf[k] = 10 then INC(n); end; + INC(k); + end; + j := k; + while (j < f^.len) and (f^.buf[j] # 10) and (j - k < 255) do INC(j); end; + return f^.buf[k..j]; + end; + end; + return ""; +end; + +proc error*(p: Pos; msg: []U8); +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 return; end; + lastError := p; + show(p, "error", Red, msg); + INC(errors); + if errors >= MaxErrors then + put("raz: stopping after "); + putNum(MaxErrors); + put(" errors\n"); + flush; + Rt.exit(1); + end; +end; + +proc warning*(p: Pos; msg: []U8); +begin + if werror then + error(p, msg); + else + 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 *) +proc note*(p: Pos; msg: []U8); +begin + if shown then show(p, "note", Cyan, msg); end; +end; + +proc help*(msg: []U8); +begin + if shown then + paint(Green, "help:"); + put(" "); + put(msg); + putc('\n'); + flush; + end; +end; + +(* An error with no place in the source, such as a file that can't be + read: it stops the compiler at once. *) +proc fatal*(msg: []U8); +begin + put("raz: "); + put(msg); + putc('\n'); + flush; + Rt.exit(1); +end; + +proc count(n: INT; what: []U8): []U8; +begin + if n = 1 then return say("1 {}", [Fmt.str(what)]); end; + return say("{} {}s", [Fmt.int(n), Fmt.str(what)]); +end; + +(* Says how many errors and warnings there were, and stops the compiler + if there were errors. *) +proc finish*; +begin + if (errors > 0) and (warnings > 0) then + put("raz: "); put(count(errors, "error")); put(", "); put(count(warnings, "warning")); putc('\n'); + elsif errors > 0 then + put("raz: "); put(count(errors, "error")); putc('\n'); + elsif warnings > 0 then + put("raz: "); put(count(warnings, "warning")); putc('\n'); + end; + flush; + if errors > 0 then Rt.exit(1); end; +end; + +begin + Buf.init(ADR(cwd), Heap.heap); + Buf.init(ADR(out), Heap.heap); +end Diag. diff --git a/src/Elf.raz b/src/Elf.raz new file mode 100644 index 0000000..19defdb --- /dev/null +++ b/src/Elf.raz @@ -0,0 +1,431 @@ +(* Elf: 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 memory, Diag for errors, Sys and Files to write + the file. + Leaves out: position independent executables, symbol versions, the + rest of DWARF. + + Exported variables can't be set from outside, so needLib, setMainPath + and setStripped do it. *) +module Elf; +import Sys, Files, Fmt, Diag, Scan, Chunk, Link; + +var + needed: [32]INT; (* the libraries to load, names interned *) + numNeeded*: INT; (* none: a static program *) + mainPath: []U8; (* the main module's file, for gdb *) + stripped*: BOOL; (* -s: no symbols and no line numbers; the sections are there, empty *) + + buf: ^U8; + len, cap: INT; + +(* The library name, to be loaded, unless it is already: false if there + are too many *) +proc needLib*(name: INT): BOOL; +var i: INT; +begin + for i := 0 to numNeeded - 1 do + if needed[i] = name then return true; end; + end; + if numNeeded = 32 then return false; end; + needed[numNeeded] := name; + INC(numNeeded); + return true; +end; + +(* A static program again *) +proc noLibs*; +begin + numNeeded := 0; +end; + +proc setMainPath*(path: []U8); +begin + mainPath := path; +end; + +proc setStripped*(yes: BOOL); +begin + stripped := yes; +end; + +proc room(n: INT); +begin + if len + n > cap then + buf := Scan.regrab(buf, len, cap * 2 + n); + cap := cap * 2 + n; + end; +end; + +(* The n low bytes of v, least significant first *) +proc putN(v: INT; n: INT); +var i: INT; +begin + room(n); + for i := 0 to n - 1 do + buf[len] := U8(v & 0FFH); + v := v shr 8; + INC(len); + end; +end; + +proc putBytes(p: ^U8; n: INT); +begin + room(n); + if n > 0 then COPY(buf[len..len + n], p[0..n]); end; + len := len + n; +end; + +proc padTo(off: INT); +begin + while len < off do putN(0, 1); end; +end; + +proc patch(at: INT; v: INT; n: INT); +var i: INT; +begin + for i := 0 to n - 1 do + buf[at + i] := U8(v & 0FFH); + v := v shr 8; + end; +end; + +proc phdr(typ, flags: INT; off, adr, filesz, memsz, align: INT); +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"; + +(* Where in ShNames the name is: the byte after a zero that starts it and + is followed by one; the empty name, found nowhere, is 0 *) +proc nameAt(name: []U8): INT; +var i, k: INT; same: BOOL; +begin + for i := 1 to LEN(ShNames) - LEN(name) - 1 do + if ShNames[i - 1] = 0 then + same := ShNames[i + LEN(name)] = 0; + for k := 0 to LEN(name) - 1 do + if ShNames[i + k] # name[k] then same := false; end; + end; + if same and (LEN(name) > 0) then return i; end; + end; + end; + return 0; +end; + +(* A section header. Its name is stored as its offset in ShNames. *) +proc shdr(name: []U8; typ: INT; flags, adr, off, size: INT; lnk, info: INT; align, entsize: INT); +begin + putN(nameAt(name), 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; + +proc putStr(s: []U8); +begin + putBytes(ADR(s[0]), LEN(s)); + putN(0, 1); +end; + +(* LEB128, unsigned *) +proc putU(v: INT); +begin + while v >= 80H do + putN(v & 7FH | 80H, 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). Section + offsets go in off, sizes in size: line, info, abbrev. *) +proc putDebug(off, size: []INT); +var cwd: []U8; err: INT; +begin + off[0] := Chunk.chunks[Link.placesChunk].adr - Link.roAdr + Link.roOff + Link.linesOff; + size[0] := Link.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); + cwd, err := Sys.workDir(); + if err # 0 then cwd := ""; end; + putStr(cwd); + putStr("raz"); + putN(0, 4); (* the line table, at 0 *) + putN(Link.Base + Link.textOff, 8); putN(Link.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(11H); putN(0, 1); (* 1: a compile unit, no children *) + putU(03H); putU(08H); (* name, a string *) + putU(1BH); putU(08H); (* comp_dir, a string *) + putU(25H); putU(08H); (* producer, a string *) + putU(10H); putU(17H); (* stmt_list, a section offset *) + putU(11H); putU(01H); (* low_pc, an address *) + putU(12H); putU(07H); (* 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 = 6474E551H; + +var + (* in the room at the end of rodata: where each of the loader's + tables starts, from extraAdr *) + symAt, relaAt, hashAt, strAt: INT; + nsym, strLen: INT; + +(* Whether chunk c is a C symbol the program uses *) +proc isExt(c: INT): BOOL; +begin + return Chunk.chunks[c].live and Chunk.chunks[c].ext; +end; + +(* The sizes of the loader's tables: what linkAll must leave room for. *) +proc sizeTables(roExtra, dynSize: ^INT); +var c, i: INT; +begin + nsym := 1; + strLen := 1; + for i := 0 to numNeeded - 1 do strLen := strLen + LEN(Scan.nameOf(needed[i])) + 1; end; + for c := 0 to Chunk.numChunks - 1 do + if isExt(c) then + INC(nsym); + strLen := strLen + LEN(Scan.nameOf(Chunk.chunks[c].name)) + 1; + end; + end; + symAt := (LEN(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. *) +proc putTables; +var c, k, i, at, name: INT; +begin + len := Link.extraAdr - Link.roAdr + Link.roOff; + putStr(Interp); + padTo(Link.extraAdr - Link.roAdr + Link.roOff + symAt); + putN(0, 24); + name := strLen; + for c := Chunk.numChunks - 1 to 0 by -1 do (* names go last in the string table *) + if isExt(c) then name := name - LEN(Scan.nameOf(Chunk.chunks[c].name)) - 1; end; + end; + for c := 0 to Chunk.numChunks - 1 do + if isExt(c) then + putN(name, 4); putN(10H, 1); putN(0, 1); putN(0, 2); (* global, undefined *) + putN(0, 8); putN(0, 8); + name := name + LEN(Scan.nameOf(Chunk.chunks[c].name)) + 1; + end; + end; + k := 1; + for c := 0 to Chunk.numChunks - 1 do + if isExt(c) then + putN(Chunk.chunks[c].adr, 8); + putN((k shl 32) | 6, 8); (* R_X86_64_GLOB_DAT *) + putN(0, 8); + INC(k); + end; + 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); end; + putN(0, 1); + for i := 0 to numNeeded - 1 do putStr(Scan.nameOf(needed[i])); end; + for c := 0 to Chunk.numChunks - 1 do + if isExt(c) then putStr(Scan.nameOf(Chunk.chunks[c].name)); end; + end; + len := Link.roOff + Link.roSize; + + (* the dynamic table, at the start of the writable segment *) + padTo(Link.bssOff); + at := 1; + for i := 0 to numNeeded - 1 do + putN(1, 8); putN(at, 8); (* DT_NEEDED *) + at := at + LEN(Scan.nameOf(needed[i])) + 1; + end; + putN(4, 8); putN(Link.extraAdr + hashAt, 8); (* DT_HASH *) + putN(5, 8); putN(Link.extraAdr + strAt, 8); (* DT_STRTAB *) + putN(6, 8); putN(Link.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(Link.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; + +proc writeElf*(path: []U8; entry: INT); +var + nph, nsh, c, nsyms, sec, strsCap: INT; + roExtra, dynSize, symOff, strOff, shstrOff, shOff, strsLen: INT; + dbgOff, dbgSize: [3]INT; + strs: ^U8; + s: []U8; + dyn: BOOL; +begin + cap := 1 shl 16; + buf := Scan.grab(cap); + len := 0; + dyn := numNeeded > 0; + roExtra := 0; dynSize := 0; + if dyn then sizeTables(ADR(roExtra), ADR(dynSize)); end; + (* room for the most program headers either kind of program has *) + Link.linkAll(64 + 6 * 56, roExtra, dynSize); + if dyn then + nph := 6; + else + nph := 2; + if Link.roSize > 0 then INC(nph); end; + if Link.bssSize > 0 then INC(nph); end; + end; + + (* ELF header *) + putN(464C457FH, 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(Chunk.chunks[entry].adr, 8); + putN(64, 8); (* program headers follow *) + putN(0, 8); (* section headers: patched below *) + putN(0, 4); + nsh := 10; + if dyn then nsh := 13; end; + 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 dyn then + phdr(PtInterp, 4, Link.extraAdr - Link.roAdr + Link.roOff, Link.extraAdr, LEN(Interp) + 1, LEN(Interp) + 1, 1); + end; + (* the first segment maps the headers too, so text can follow them *) + phdr(PtLoad, 5, 0, Link.Base, Link.textOff + Link.textSize, Link.textOff + Link.textSize, Link.Page); + if Link.roSize > 0 then phdr(PtLoad, 4, Link.roOff, Link.roAdr, Link.roSize, Link.roSize, Link.Page); end; + if dyn then + phdr(PtLoad, 6, Link.bssOff, Link.bssAdr, dynSize, Link.bssSize, Link.Page); + phdr(PtDynamic, 6, Link.bssOff, Link.bssAdr, dynSize, dynSize, 8); + elsif Link.bssSize > 0 then + phdr(PtLoad, 6, 0, Link.bssAdr, 0, Link.bssSize, Link.Page); + end; + phdr(PtGnuStack, 6, 0, 0, 0, 0, 16); (* a stack that can't run code *) + + padTo(Link.textOff); + putBytes(Link.textImg, Link.textSize); + padTo(Link.roOff); (* even when empty, so that every section lies in the file *) + putBytes(Link.roImg, Link.roSize); + if dyn then putTables; end; + + (* the symbol table: one local symbol for each named live chunk *) + padTo((len + 7) div 8 * 8); + symOff := len; + strsCap := 1 shl 16; + strs := Scan.grab(strsCap); + strsLen := 1; + strs[0] := 0; + putN(0, 24); + nsyms := 1; + for c := 0 to Chunk.numChunks - 1 do + if not stripped and Chunk.chunks[c].live and (Chunk.chunks[c].name >= 0) and not Chunk.chunks[c].ext then + s := Chunk.chunkName(c); + if strsLen + LEN(s) + 1 > strsCap then + strs := Scan.regrab(strs, strsLen, strsLen * 2 + 256); + strsCap := strsLen * 2 + 256; + end; + COPY(strs[strsLen..strsLen + LEN(s)], s); + strs[strsLen + LEN(s)] := 0; + if Chunk.chunks[c].sec = Chunk.secText then (* the section's index in the headers below *) + sec := 1; + elsif Chunk.chunks[c].sec = Chunk.secRodata then + sec := 2; + else + sec := 3; + end; + putN(strsLen, 4); + if sec = 1 then putN(2, 1); else putN(1, 1); end; (* STT_FUNC, STT_OBJECT *) + putN(0, 1); + putN(sec, 2); + putN(Chunk.chunks[c].adr, 8); + putN(Chunk.chunks[c].size, 8); + strsLen := strsLen + LEN(s) + 1; + INC(nsyms); + end; + end; + strOff := len; + putBytes(strs, strsLen); + shstrOff := len; + putBytes(ADR(ShNames[0]), LEN(ShNames)); + if stripped or (Link.placesChunk < 0) then + for c := 0 to 2 do dbgOff[c] := len; dbgSize[c] := 0; end; + else + putDebug(dbgOff, dbgSize); + end; + + 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, Link.Base + Link.textOff, Link.textOff, Link.textSize, 0, 0, 16, 0); + shdr(".rodata", 1, 2, Link.roAdr, Link.roOff, Link.roSize, 0, 0, 16, 0); + shdr(".bss", 8, 3, Link.bssAdr + dynSize, Link.roOff + Link.roSize, Link.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, LEN(ShNames), 0, 0, 1, 0); + if dyn then (* the loader's tables, for readelf and objdump *) + shdr(".dynamic", 6, 3, Link.bssAdr, Link.bssOff, dynSize, 8, 0, 8, 16); + shdr(".dynstr", 3, 2, Link.extraAdr + strAt, Link.extraAdr + strAt - Link.roAdr + Link.roOff, strLen, 0, 0, 1, 0); + shdr(".dynsym", 11, 2, Link.extraAdr + symAt, Link.extraAdr + symAt - Link.roAdr + Link.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); + + if not Files.write(path, buf[0..len]) or (Sys.chmod(path, 1EDH) < 0) then + Diag.fatal(Diag.say("can't write {}", [Fmt.str(path)])); + end; +end; + +begin + mainPath := ""; +end Elf. diff --git a/src/Gen.raz b/src/Gen.raz new file mode 100644 index 0000000..a1aa224 --- /dev/null +++ b/src/Gen.raz @@ -0,0 +1,2350 @@ +(* Gen: the code generator, for x86-64. + + Item and Parse 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, 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. + + The seed's `Mark` in the middle of a push or a check can't give an + error back, so it is shown and the call goes on without doing what + it could not (see newEntry and check): the compile ends with the + message, and the parser's recovery makes the stack right again with + resetStack. endProc returns its error, for the parser to pass up. + + What the parser sets, `inPlace`, has a setter, as the exported + variables can't be set from outside. The seed's types lose their T + (`TAdr` is `Adr`), and its `Call` record, which the procedure `call` + takes, is `CallInfo`. *) +module Gen; +import Fmt, Diag, Scan, Sym, Chunk, X := 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; + + RAX = X.RAX; RCX = X.RCX; RDX = X.RDX; RSP = X.RSP; RBP = X.RBP; + RSI = X.RSI; RDI = X.RDI; R8 = X.R8; R9 = X.R9; R10 = X.R10; R11 = X.R11; + +type + Kind* = (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 *) + Base* = (bFrame, bGlobal, bStack, bSlot, bReg); + Adr* = record + base*: Base; + chunk*: INT; (* bGlobal: the chunk; bSlot: the frame slot; bReg: the register *) + off*: I64; (* added to the address; for bReg, which word, 0 or 8 *) + hi*: INT; (* 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 *) + CodeMark* = record pc*, fixups*, lines*, said*, fails*: INT; end; + + (* For entryPoint: the address of chunk, put in the variable whose + chunk is into before the program starts *) + Link* = record chunk*, into*: INT; end; + + CallInfo* = record + sig*: ^Sym.Type; + param*: ^Sym.Obj; (* the parameter the next argument is for *) + obj*: ^Sym.Obj; (* the procedure called, if it has a name *) + n*: INT; (* the arguments *) + isF*: [64]BOOL; (* ... goes in an xmm register *) + pair*: [64]BOOL; (* ... is a slice's first word, the next its second *) + target*: I64; (* the frame slot of a procedure value, if chunk < 0 *) + chunk*: INT; (* else the procedure's chunk *) + ext*: BOOL; (* C's: called through the chunk holding its address *) + ret*: I64; (* 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*: [5]INT = [X.RBX, X.R12, X.R13, X.R14, X.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*: [7]INT = [X.RBX, X.R12, X.R13, X.R14, X.R15, X.RDI, X.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*: [4]INT = [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*: INT; + (* the stubs that check's code calls, one for each kind of failure, + made by entryPoint for those used *) + failStubs: [6]INT; + lost*: BOOL; (* a parameter kept where it arrived was wanted + for other work: the procedure is compiled again, + the parameter in memory *) + inPlace: INT; (* 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*: INT; (* the values on the stack *) + pushed*: INT; (* quadwords pushed on the machine's stack *) + codeChunk*: INT; (* the procedure or body being compiled, or -1 *) + +type + (* where a value on the stack is *) + Loc = (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 *) + + Entry = record + loc: Loc; + val: I64; (* lConst: the value; lHeld: the register; lAdr: the + offset; lFrame: the frame slot *) + chunk: INT; (* lAdr: the chunk, or -1 for the frame *) + m: X.Mem; (* lIdx, lMem *) + size: INT; (* lMem *) + signed: BOOL; (* lMem *) + k: Kind; + off: I64; (* 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; + + (* a check of the procedure, whose failure endFails makes *) + Fail = record + L, what, ra, name, at: INT; + m: X.Mem; + n: I64; + end; + +const + StubNames: [6][]U8 = ["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: [NumRegs]INT = [R8, R9, R10, R11]; + XRegs: [NumRegs]INT = [8, 9, 10, 11]; (* xmm8 to xmm11 *) + IntRegs: [6]INT = [RDI, RSI, RDX, RCX, R8, R9]; + +var + stack: [256]Entry; + owner: [NumRegs]INT; (* the value in each register, or -1 *) + frameTop, frameMax, permTop: I64; + frameFix: INT; (* where the frame size is patched in *) + paramTop: I64; (* the parameters' slots end here *) + zeroTop: I64; (* the locals the prologue zeroes end here *) + retSlot: I64; (* holds the hidden result pointer *) + resType: ^Sym.Type; (* the procedure's result, or nil *) + exitL: INT; + (* parameters arriving in registers: where each is stored on entry *) + inReg: [14]INT; + inSlot: [14]I64; + inSize: [14]INT; + inObj: [14]^Sym.Obj; + numIn: INT; + procParams: ^Sym.Obj; (* the parameters, for enterBody *) + regMask: INT; (* the registers of variables, as bits (XBit) *) + kept: INT; (* bit r: register r holds a parameter, as it arrived *) + saveAt: I64; (* where they are saved, a quadword each *) + homes: [4]I64; (* the slots of the variables in XVarRegs *) + frameAt: [3]I64; (* frameTop, frameMax, permTop after the declarations *) + fails: [4096]Fail; + numFails: INT; + +proc setInPlace*(r: INT); +begin + inPlace := r; +end; + +proc kindOf*(t: ^Sym.Type): Kind; +begin + if t^.form = Sym.fReal then + if t^.size = 4 then return kF32; end; + return kF64; + end; + if t^.size > WordSize then return kLong; end; + return 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. *) + +proc fits32(v: I64): BOOL; +begin + return (v >= -2147483648) and (v <= 2147483647); +end; + +(* The register of kind k for the value at depth i *) +proc regIn(k: Kind; i: INT): INT; +begin + if k in {kF32, kF64} then return XRegs[i mod NumRegs]; end; + return Regs[i mod NumRegs]; +end; + +proc regOf(i: INT): INT; +begin + return regIn(stack[i].k, i); +end; + +proc isReal(i: INT): BOOL; +begin + return 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 *) +proc realConst(v: I64): X.Mem; +var c: INT; +begin + c := Chunk.newChunk(Chunk.secRodata, -1, -1); + Chunk.setData(c, ^U8(ADR(v)), 8, 8); + return X.memRip(c, 0); +end; + +(* The real i into xmm register x, from wherever it is, as valueTo does + for an integer register *) +proc xValueTo(i, x: INT); +begin + match stack[i].loc of + | lConst: X.movsXM(x, realConst(stack[i].val), stack[i].k = kF32); + | lMem: X.movsXM(x, stack[i].m, stack[i].size = 4); + | lHeld: if INT(stack[i].val) # x then X.movX(x, INT(stack[i].val)); end; + | lInto: if INT(stack[i].val) # x then X.movX(x, INT(stack[i].val)); end; + | lReg: if regOf(i) # x then X.movX(x, regOf(i)); end; + | else: X.movsXM(x, X.mem(RBP, stack[i].val), false); (* spilled, as 8 bytes *) + end; +end; + +proc loaded(i: INT): INT; forward; +proc allocTemp*(size, align: I64): I64; 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 *) +proc spill(i: INT); +var s: I64; +begin + if (stack[i].loc # lReg) or (stack[i].off # 0) then _ := loaded(i); end; + s := allocTemp(8, 8); + if isReal(i) then X.movsMX(X.mem(RBP, s), regOf(i), false); + else X.store(X.mem(RBP, s), regOf(i), 8); end; + 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 *) +proc readMems(d: INT); +var i: INT; +begin + for i := 0 to d - 1 do + if stack[i].loc = lMem then _ := loaded(i); end; + end; +end; + +(* Every value below depth d in a register, spilled; one noted in memory + is read first, as a call may change it *) +proc spillBelow(d: INT); +var r: INT; +begin + readMems(d); + for r := 0 to NumRegs - 1 do + if (owner[r] >= 0) and (owner[r] < d) then spill(owner[r]); end; + end; +end; + +(* The register of kind k of value i, for it to hold: a lower value at + its depth's registers is spilled. *) +proc claim(i: INT; k: Kind): INT; +var r: INT; +begin + r := i mod NumRegs; + if (owner[r] >= 0) and (owner[r] # i) then spill(owner[r]); end; + owner[r] := i; + return regIn(k, i); +end; + +(* The memory at the noted address i, plus off *) +proc adrMem(i: INT; off: I64): X.Mem; +begin + if stack[i].chunk < 0 then return X.mem(RBP, stack[i].val + off); end; + return X.memRip(stack[i].chunk, INT(stack[i].val + off)); +end; + +(* The value i, in its register *) +proc loaded(i: INT): INT; +var r: INT; +begin + if stack[i].loc = lInto then return INT(stack[i].val); end; + if (stack[i].loc # lReg) and isReal(i) then + xValueTo(i, claim(i, stack[i].k)); + stack[i].loc := lReg; + elsif stack[i].loc # lReg then + r := claim(i, kWord); + match stack[i].loc of + | lConst: X.movRI(r, stack[i].val); + | lHeld: X.movRR(r, INT(stack[i].val)); + | lAdr: X.lea(r, adrMem(i, 0)); + | lIdx: X.lea(r, stack[i].m); + | lMem: X.load(r, stack[i].m, stack[i].size, stack[i].signed); + | else: X.load(r, X.mem(RBP, stack[i].val), 8, false); + end; + stack[i].loc := lReg; + end; + if stack[i].off # 0 then + X.lea(regOf(i), X.mem(regOf(i), stack[i].off)); + stack[i].off := 0; + end; + return regOf(i); +end; + +(* The register value i is in, only to be read: a variable's own, or + its register *) +proc peek(i: INT): INT; +begin + if (stack[i].loc = lHeld) and (stack[i].off = 0) then return INT(stack[i].val); end; + return loaded(i); +end; + +(* The offset of value i, taken from it, for the caller to add or to + make a displacement of *) +proc takeOff(i: INT): I64; +var o: I64; +begin + o := stack[i].off; + stack[i].off := 0; + return o; +end; + +(* The word on top, in a register, has o added: noted, if o can be a + displacement, else added now *) +proc putOff(o: I64); +begin + if fits32(stack[depth - 1].off + o) then + stack[depth - 1].off := stack[depth - 1].off + o; + else + X.movRI(RCX, o); + X.alu(X.aluAdd, loaded(depth - 1), RCX); + end; +end; + +proc top: INT; +begin + if depth = 0 then Diag.fatal("internal error: the stack is empty"); end; + return loaded(depth - 1); +end; + +(* A value on the stack's top. At the stack's last place it is shown as + an error and nothing is pushed: see the head of this unit. *) +proc newEntry(k: Kind; loc: Loc; v: I64); +begin + if depth > LEN(stack) - 1 then + _ := Scan.mark("the expression is too deep"); + return; + end; + 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. *) +proc newMem(loc: Loc; m: X.Mem; k: Kind; size: INT; signed: BOOL); +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; +end; + +(* The register a new value on top is to be computed in *) +proc target: INT; +begin + return claim(depth, kWord); +end; + +(* The xmm register a new real on top is to be computed in *) +proc xTarget: INT; +begin + return claim(depth, kF64); +end; + +(* The value just computed in target goes on top *) +proc computed(k: Kind); +begin + newEntry(k, lReg, 0); +end; + +proc drop*; +begin + DEC(depth); + if owner[depth mod NumRegs] = depth then owner[depth mod NumRegs] := -1; end; +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). *) +proc clobberArgs; +begin + if kept # 0 then lost := true; end; +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. *) +proc valueTo(i, r: INT); +begin + if isReal(i) and (stack[i].loc in {lHeld, lInto}) then + X.movqRX(r, INT(stack[i].val)); + else + match stack[i].loc of + | lConst: X.movRI(r, stack[i].val); + | lHeld: X.movRR(r, INT(stack[i].val)); + | lInto: X.movRR(r, INT(stack[i].val)); + | lAdr: X.lea(r, adrMem(i, 0)); + | lIdx: X.lea(r, stack[i].m); + | lMem: X.load(r, stack[i].m, stack[i].size, stack[i].signed); + | lReg: + if isReal(i) then X.movqRX(r, regOf(i)); + elsif regOf(i) # r then X.movRR(r, regOf(i)); end; + | else: X.load(r, X.mem(RBP, stack[i].val), 8, false); + end; + end; + if stack[i].off # 0 then X.lea(r, X.mem(r, stack[i].off)); end; +end; + +(* The value on top, popped into register r *) +proc popTo(r: INT); +begin + valueTo(depth - 1, r); + drop(); +end; + +(* Whether the value on top is a constant, and if so, which *) +proc topConst: (BOOL, I64); +begin + return stack[depth - 1].loc = lConst, stack[depth - 1].val; +end; + +proc resetStack*(d, p: INT); +var r: INT; +begin + depth := d; + pushed := p; + for r := 0 to NumRegs - 1 do owner[r] := -1; end; +end; + +proc pushConst*(k: Kind; v: I64); +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) *) +proc regAt(a: Adr): INT; +var r: INT; +begin + if a.off = 0 then r := a.chunk; else r := a.hi; end; + if r >= XmmVar then r := r - XmmVar; end; (* an xmm register, XVarRegs *) + return r; +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. *) +proc place(a: Adr; r: INT): X.Mem; +var m: X.Mem; ra: INT; o: I64; +begin + if a.base = bReg then Diag.fatal("internal error: a register has no address"); end; + match a.base of + | bFrame: return X.mem(RBP, a.off); + | bGlobal: return X.memRip(a.chunk, INT(a.off)); + | bStack: + if stack[depth - 1].loc = lAdr then + m := adrMem(depth - 1, a.off); + drop(); + return m; + elsif stack[depth - 1].loc = lIdx then + m := stack[depth - 1].m; + m.disp := m.disp + INT(a.off); + drop(); + return m; + end; + (* 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; end; + ra := peek(depth - 1); + drop(); + return X.mem(ra, a.off + o); + | else: (* bSlot: the address is in the frame slot a.chunk *) + X.load(r, X.mem(RBP, a.chunk), 8, false); + return X.mem(r, a.off); + end; +end; + +(* The address a names, on top of the stack *) +proc pushAdr*(a: Adr); +var m: X.Mem; r: INT; +begin + if (a.base = bStack) and (a.off = 0) then return; end; (* it is on top already *) + if a.base in {bFrame, bGlobal} then + newEntry(kWord, lAdr, a.off); + if a.base = bGlobal then stack[depth - 1].chunk := a.chunk; end; + return; + 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 + m := place(a, -1); r := target(); + else + r := target(); m := place(a, r); + end; + X.lea(r, m); + computed(kWord); +end; + +proc pushVar*(a: Adr; size: INT; signed: BOOL; k: Kind); +var m: X.Mem; r: INT; +begin + r := inPlace; + inPlace := -1; + if r >= XmmVar then r := r - XmmVar; end; + if (a.base = bReg) and (regAt(a) = r) then + newEntry(k, lInto, r); + return; + end; + if a.base = bReg then + newEntry(k, lHeld, regAt(a)); + return; + 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 + m := place(a, -1); + newMem(lMem, m, k, size, signed); + return; + end; + (* in the order pushAdr explains *) + if a.base = bStack then + m := place(a, -1); r := target(); + else + r := target(); m := place(a, r); + end; + if k in {kF32, kF64} then X.movsXM(xTarget(), m, size = 4); + else X.load(r, m, size, signed); end; + computed(k); +end; + +proc pushProc*(c: INT; ext: BOOL); +var r: INT; +begin + r := target(); + if ext then X.load(r, X.memRip(c, 0), 8, false); + else X.lea(r, X.memRip(c, 0)); end; + computed(kWord); +end; + +(* The slot of the variable in xmm register x *) +proc homeOf(x: INT): X.Mem; +begin + return X.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. *) +proc popVar*(a: Adr; size: INT); +var r: INT; v: I64; c, fl: BOOL; +begin + if (a.base = bReg) and isReal(depth - 1) then + xValueTo(depth - 1, regAt(a)); + drop(); + X.movsMX(homeOf(regAt(a)), regAt(a), false); (* written through, as xHome says *) + return; + end; + if a.base = bReg then + c, v := topConst(); + if c then X.movRI(regAt(a), v); + elsif peek(depth - 1) # regAt(a) then X.movRR(regAt(a), peek(depth - 1)); end; (* else it is there, lInto *) + drop(); + return; + end; + c, v := topConst(); + if c and fits32(v) then + drop(); + X.storeI(place(a, RCX), INT(v), size); + return; + end; + if c then r := RAX; X.movRI(RAX, v); + else r := peek(depth - 1); end; + fl := (stack[depth - 1].loc # lConst) and isReal(depth - 1); + drop(); + if fl then X.movsMX(place(a, RCX), r, size = 4); + else X.store(place(a, RCX), r, size); end; +end; + +(* Register src to dst, an xmm register's if fl *) +proc movReg(fl: BOOL; dst, src: INT); +begin + if fl then X.movX(dst, src); else X.movRR(dst, src); end; +end; + +(* The two values on top, of one kind, change places. *) +proc swap*; +var e: Entry; x, y, t: INT; rx, ry, fl: BOOL; +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); end; + if stack[y].loc in {lIdx, lMem} then _ := loaded(y); end; + rx := stack[x].loc = lReg; + ry := stack[y].loc = lReg; + fl := isReal(y); + if fl then t := 0; else t := RAX; end; (* xmm0, or rax *) + if rx and ry then + movReg(fl, t, regOf(x)); + movReg(fl, regOf(x), regOf(y)); + movReg(fl, regOf(y), t); + elsif rx then + owner[x mod NumRegs] := -1; + movReg(fl, claim(y, stack[y].k), regOf(x)); + elsif ry then + owner[y mod NumRegs] := -1; + movReg(fl, 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. *) +proc copyBytes(size: I64); +var o, n: I64; +begin + if size > 64 then + X.movRI(RCX, size); + X.repMovsb(); + return; + end; + o := 0; + while o < size do + n := 8; + while n > size - o do n := n div 2; end; + X.load(RCX, X.mem(RSI, o), INT(n), false); + X.store(X.mem(RDI, o), RCX, INT(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. *) +proc copyBlock*(size, off: I64); +begin + clobberArgs(); + popTo(RSI); + popTo(RDI); + if off # 0 then X.lea(RDI, X.mem(RDI, off)); end; + copyBytes(size); +end; + +(* Pops a source's address, and copies size bytes to a: for a slice in + registers, its two words into them. *) +proc copyTo*(a: Adr; size: I64); +begin + clobberArgs(); + popTo(RSI); + if a.base = bReg then + X.load(a.chunk, X.mem(RSI, 0), 8, false); + X.load(a.hi, X.mem(RSI, 8), 8, false); + return; + end; + X.lea(RDI, place(a, RDI)); + copyBytes(size); +end; + +proc zeroVar*(a: Adr; size: I64); +begin + clobberArgs(); + X.lea(RDI, place(a, RDI)); + X.movRI(RCX, size); + X.movRI(RAX, 0); + X.repStosb(); +end; + +(* Operations *) + +(* n if v is 2^n, which is 0 for 1; -1 if v isn't a power of two *) +proc exactLog2(v: I64): INT; +var n: INT; +begin + n := 0; + while (v > 1) and ((v & 1) = 0) do v := v shr 1; INC(n); end; + if v # 1 then n := -1; end; + return 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 *) +proc mulI(r: INT; v: I64); +begin + if exactLog2(v) > 0 then X.shiftI(X.shShl, r, exactLog2(v)); + elsif v # 1 then X.imulI(r, INT(v)); end; +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 *) +proc cmpI(r: INT; v: I64); +begin + if v = 0 then X.testRR(r, r); + elsif fits32(v) then X.aluI(X.aluCmp, r, INT(v)); + else X.movRI(RDX, v); X.alu(X.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). *) +proc divPow2(sy: Scan.Sym; r, k: INT; unsign: BOOL); +begin + (* unsigned: div shifts right; mod keeps the low k bits, by shifting + them up to the top and back down *) + if unsign then + if sy = Scan.sDiv then X.shiftI(X.shShr, r, k); + else X.shiftI(X.shShl, r, 64 - k); X.shiftI(X.shShr, r, 64 - k); end; + return; + 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. *) + X.movRR(RCX, r); + X.shiftI(X.shSar, RCX, 63); + X.shiftI(X.shShr, RCX, 64 - k); + X.alu(X.aluAdd, RCX, r); + X.shiftI(X.shSar, RCX, k); + if sy = Scan.sDiv then X.movRR(r, RCX); + else X.shiftI(X.shShl, RCX, k); X.alu(X.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. *) +proc divTrap(bits, y: INT); +var L: INT; +begin + L := NoLabel; + cmpI(y, -1); + X.jcc(X.ccNE, L); + cmpI(RAX, I64(-1) shl (bits - 1)); + X.jcc(X.ccNE, L); + X.shiftI(X.shShl, RAX, 64 - bits); + X.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] *) +proc topInMem: BOOL; +begin + return (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 with y. *) +proc operands: (INT, INT); +var v: I64; c: BOOL; y: INT; +begin + c, v := topConst(); + if c then X.movRI(RCX, v); y := RCX; else y := peek(depth - 1); end; + drop(); + return top(), y; +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]. *) +proc realOp(sy: Scan.Sym; k: Kind); +var f: BOOL; c, x, y: INT; m: X.Mem; +begin + f := k = kF32; + match sy of + | sPlus: c := 58H; (* addsd, or addss for an F32 *) + | sMinus: c := 5CH; (* subsd, subss *) + | sTimes: c := 59H; (* mulsd, mulss *) + | else: c := 5EH; (* divsd, divss *) + end; + if stack[depth - 1].loc in {lConst, lMem, lFrame} then + match stack[depth - 1].loc of + | lConst: m := realConst(stack[depth - 1].val); + | lMem: m := stack[depth - 1].m; + | else: m := X.mem(RBP, stack[depth - 1].val); + end; + drop(); + X.sseM(c, top(), m, f); + else + y := peek(depth - 1); + drop(); + x := top(); + X.sse(c, x, y, f); + end; +end; + +(* The group 1 operation of +, -, &, | and xor *) +proc aluOf(sy: Scan.Sym): INT; +begin + match sy of + | sPlus: return X.aluAdd; + | sMinus: return X.aluSub; + | sAmp: return X.aluAnd; + | sBar: return X.aluOr; + | else: return X.aluXor; + end; +end; + +const + (* the condition codes of the comparisons, from sEql: = # < <= > >= *) + CcSigned: [6]INT = [X.ccE, X.ccNE, X.ccL, X.ccLE, X.ccG, X.ccGE]; + CcUnsigned: [6]INT = [X.ccE, X.ccNE, X.ccB, X.ccBE, X.ccA, X.ccAE]; + +(* The two values on top, the left op the right, an integer of size + bytes, signed or not, brought back to its width. *) +proc op*(sy: Scan.Sym; k: Kind; size: INT; signed: BOOL); +var v, o: I64; r, y, sh, bits: INT; c: BOOL; m: X.Mem; +begin + if k in {kF32, kF64} then realOp(sy, k); return; 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 (((sy = Scan.sPlus) or (sy = Scan.sTimes) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor))) and (stack[depth - 2].loc = lConst) + and (stack[depth - 1].loc # lConst) then swap(); end; + c, v := topConst(); + (* A word's offset (see Entry) 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 ((((sy = Scan.sPlus) or (sy = Scan.sMinus))) or ((sy = Scan.sTimes) and c and fits32(v))) then + o := takeOff(depth - 2); + if sy = Scan.sTimes then o := o * v; + elsif c and fits32(v) then + if sy = Scan.sPlus then o := o + v; else o := o - v; end; + drop(); + if not (stack[depth - 1].loc in {lReg, lHeld}) then _ := top(); end; + putOff(o); + return; + elsif sy = Scan.sPlus then o := o + takeOff(depth - 1); + else o := o - takeOff(depth - 1); end; + end; + sh := -1; + if c and (((sy = Scan.sTimes) or (sy = Scan.sDiv) or (sy = Scan.sMod))) then sh := exactLog2(v); end; + if c and (sh >= 1) then + drop(); + r := top(); + if sy = Scan.sTimes then X.shiftI(X.shShl, r, sh); else divPow2(sy, r, sh, not signed); end; + elsif c and fits32(v) and (((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sBar) or (sy = Scan.sXor) or (sy = Scan.sAmp) or (sy = Scan.sTimes) or (sy = Scan.sShl) or (sy = Scan.sShr))) then + drop(); + r := top(); + match sy of + | sTimes: X.imulI(r, INT(v)); + | sShl: X.shiftI(X.shShl, r, INT(v & I64(bits - 1))); + | sShr: + if signed then X.shiftI(X.shSar, r, INT(v & I64(bits - 1))); + else X.shiftI(X.shShr, r, INT(v & I64(bits - 1))); end; + | else: X.aluI(aluOf(sy), r, INT(v)); + end; + elsif topInMem() and (((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor))) then + m := stack[depth - 1].m; + drop(); + r := top(); + X.aluM(aluOf(sy), r, m); + else + r, y := operands(); + if ((sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor)) then + X.alu(aluOf(sy), r, y); + elsif sy = Scan.sTimes then + X.imul(r, y); + elsif ((sy = Scan.sDiv) or (sy = Scan.sMod)) then + X.movRR(RAX, r); + if not signed then + X.movRI(RDX, 0); X.unary(6, y); (* div *) + else + (* 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); end; + X.cqo(); X.unary(7, y); (* idiv, of rdx:rax, which cqo made from rax *) + end; + if sy = Scan.sDiv then X.movRR(r, RAX); else X.movRR(r, RDX); end; + else (* sShl, sShr *) + (* the count modulo the width: the machine takes it modulo 64 *) + if y # RCX then X.movRR(RCX, y); end; + if bits < 64 then X.aluI(X.aluAnd, RCX, bits - 1); end; + if sy = Scan.sShl then X.shift(X.shShl, r); + elsif signed then X.shift(X.shSar, r); + else X.shift(X.shShr, r); end; + end; + end; + if bits < 64 then X.extend(r, size, signed); end; + stack[depth - 1].k := k; + if o # 0 then putOff(o); end; +end; + +(* The left op the right of the two values on top, as a BOOL *) +proc compare*(sy: Scan.Sym; k: Kind; signed: BOOL); +var f: BOOL; r, x, y, i: INT; v: I64; c: BOOL; m: X.Mem; +begin + i := INT(sy) - INT(Scan.sEql); + if k in {kF32, kF64} then + 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. *) + match sy of + | sEql: X.ucomis(x, y, f); X.setCC(X.ccE, r); X.setCC(X.ccNP, RCX); X.alu(X.aluAnd, r, RCX); + | sNeq: X.ucomis(x, y, f); X.setCC(X.ccNE, r); X.setCC(X.ccP, RCX); X.alu(X.aluOr, r, RCX); + | sLss: X.ucomis(y, x, f); X.setCC(X.ccA, r); + | sLeq: X.ucomis(y, x, f); X.setCC(X.ccAE, r); + | sGtr: X.ucomis(x, y, f); X.setCC(X.ccA, r); + | else: X.ucomis(x, y, f); X.setCC(X.ccAE, r); + end; + computed(kWord); + else + c, v := topConst(); + if c then + drop(); r := top(); cmpI(r, v); + elsif topInMem() then + m := stack[depth - 1].m; drop(); r := top(); X.aluM(X.aluCmp, r, m); + else + r, y := operands(); X.alu(X.aluCmp, r, y); + end; + if signed then X.setCC(CcSigned[i], r); else X.setCC(CcUnsigned[i], r); end; + end; + stack[depth - 1].k := kWord; +end; + +(* A real is negated by flipping its sign bit, in rax *) +proc neg*(k: Kind; size: INT; signed: BOOL); +var r: INT; +begin + r := top(); + if k in {kF32, kF64} then + X.movqRX(RAX, r); + if k = kF32 then X.btc(RAX, 31); else X.btc(RAX, 63); end; + X.movqXR(r, RAX); + else + X.unary(3, r); (* neg *) + if size < 8 then X.extend(r, size, signed); end; + end; +end; + +proc complement*(size: INT; signed: BOOL); +var r: INT; +begin + r := top(); + X.unary(2, r); (* not *) + if size < 8 then X.extend(r, size, signed); end; +end; + +proc notBool*; +begin + X.aluI(X.aluXor, top(), 1); +end; + +(* The integer on top, brought to size bytes *) +proc narrow*(size: INT; signed: BOOL); +var r: INT; +begin + r := top(); + if size < 8 then X.extend(r, size, signed); end; + 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 *) +proc intToReal*(k: Kind; big: BOOL); +var L1, L2, r, x: INT; f: BOOL; +begin + f := k = kF32; + r := top(); + x := regIn(k, depth - 1); (* its xmm register *) + if big then + (* above high(I64): halve, keeping the low bit, and double *) + L1 := NoLabel; L2 := NoLabel; + X.testRR(r, r); + X.jcc(X.ccS, L1); + X.cvtsi2s(x, r, f); + X.jmp(L2); + X.fixLink(L1); + X.movRR(RCX, r); + X.shiftI(X.shShr, RCX, 1); + X.aluI(X.aluAnd, r, 1); + X.alu(X.aluOr, RCX, r); + X.cvtsi2s(x, RCX, f); + X.sse(58H, x, x, f); (* adds it to itself: doubles *) + X.fixLink(L2); + else + X.cvtsi2s(x, r, f); + end; + stack[depth - 1].k := k; +end; + +(* The real of kind k on top, truncated to an integer *) +proc realToInt*(k: Kind); +var x: INT; +begin + x := top(); + X.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 *) +proc realToReal*(k: Kind); +var x: INT; +begin + x := top(); + X.sse(5AH, x, x, k = kF32); (* cvtss2sd, or cvtsd2ss *) + if k = kF32 then stack[depth - 1].k := kF64; else stack[depth - 1].k := kF32; end; +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. *) +proc compareSeq*(a, b: I64; shift: INT; eq: BOOL); +var differ, r: INT; +begin + clobberArgs(); + r := target(); + X.load(RCX, X.mem(RBP, b + 8), 8, false); + X.aluM(X.aluCmp, RCX, X.mem(RBP, a + 8)); + differ := NoLabel; + X.jcc(X.ccNE, differ); + X.load(RSI, X.mem(RBP, b), 8, false); + X.load(RDI, X.mem(RBP, a), 8, false); + if shift > 0 then X.shiftI(X.shShl, RCX, shift); end; + (* repe cmpsb with rcx = 0 leaves the flags alone, so make them say + equal first, which is right if there are no bytes *) + X.alu(X.aluCmp, RCX, RCX); + X.repeCmpsb(); + X.fixLink(differ); + if eq then X.setCC(X.ccE, r); else X.setCC(X.ccNE, r); end; + 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. *) +proc errorText*(tmp: I64); +var L: INT; +begin + popTo(RAX); + X.movRI(RCX, 0); + L := NoLabel; + X.testRR(RAX, RAX); + X.jcc(X.ccE, L); + X.load(RCX, X.mem(RAX, 0), 8, false); + X.lea(RAX, X.mem(RAX, 8)); + X.fixLink(L); + X.store(X.mem(RBP, tmp), RAX, 8); + X.store(X.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. *) +proc incDec*(size: INT; signed, dec: BOOL); +var r, y, o: INT; v: I64; a: Adr; c: BOOL; +begin + c, v := topConst(); + if dec then o := X.aluSub; else o := X.aluAdd; end; + if c and fits32(v) then + drop(); + a.base := bStack; a.off := 0; + X.aluMI(o, place(a, RCX), INT(v), size); + return; + end; + r, y := operands(); + drop(); + X.load(RAX, X.mem(r, 0), size, signed); + X.alu(o, RAX, y); + X.store(X.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 *) +proc incDecReg*(r, size: INT; signed, dec: BOOL); +var y, o: INT; v: I64; c: BOOL; +begin + if dec then o := X.aluSub; else o := X.aluAdd; end; + c, v := topConst(); + if c and fits32(v) then X.aluI(o, r, INT(v)); + else y := top(); X.alu(o, r, y); end; + drop(); + if size < 8 then X.extend(r, size, signed); end; +end; + +(* The pointer on top, which NEW got, to size zero bytes unless nil *) +proc zeroNew*(size: I64); +var L, r: INT; +begin + clobberArgs(); + r := top(); + L := NoLabel; + X.testRR(r, r); + X.jcc(X.ccE, L); + X.movRR(RDI, r); + X.movRI(RCX, size); + X.movRI(RAX, 0); + X.repStosb(); + X.fixLink(L); +end; + +(* CAS(p, old, new), XCHG(p, v) or XADD(p, v), from the stack: the + result where p was *) +proc atomic*(which: INT); +var r, n: INT; +begin + if which = Sym.bCas then readMems(depth - 3); else readMems(depth - 2); end; (* what it writes may be one *) + if which = Sym.bCas then n := top(); drop(); end; + popTo(RAX); (* cmpxchg compares with rax, so CAS's old value goes there *) + r := top(); + match which of + | Sym.bCas: X.lockCmpxchg(X.mem(r, 0), n); X.setCC(X.ccE, r); + | Sym.bXchg: X.xchg(X.mem(r, 0), RAX); X.movRR(r, RAX); + | else: X.lockXadd(X.mem(r, 0), RAX); X.movRR(r, RAX); + 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. *) +proc sysCall*(n: INT); +const SysRegs: [7]INT = [RAX, RDI, RSI, RDX, R10, R8, R9]; +var i: INT; +begin + clobberArgs(); + spillBelow(depth); + for i := 0 to n - 1 do valueTo(depth - n + i, SysRegs[i]); end; + for i := 1 to n do drop(); end; + X.syscall(); + X.movRR(target(), RAX); + computed(kWord); +end; + +proc fence*; +begin + X.mfence(); +end; + +(* Jumps. A label is the chain of the jumps to it, until it is placed. *) + +proc jump*(var L: INT); +begin + X.jmp(L); +end; + +(* Pops a BOOL, and jumps if it is when *) +proc jumpIf*(var L: INT; when: BOOL); +var r: INT; +begin + r := peek(depth - 1); + drop(); + X.testRR(r, r); + if when then X.jcc(X.ccNE, L); else X.jcc(X.ccE, L); end; +end; + +(* Pops two integers, and jumps if the left op the right *) +proc jumpCmp*(sy: Scan.Sym; signed: BOOL; var L: INT); +var r, y, i: INT; v: I64; c: BOOL; m: X.Mem; +begin + i := INT(sy) - INT(Scan.sEql); + (* a comparison changes neither: a variable's register will do *) + c, v := topConst(); + if c then + drop(); r := peek(depth - 1); cmpI(r, v); + elsif topInMem() then + m := stack[depth - 1].m; drop(); r := peek(depth - 1); X.aluM(X.aluCmp, r, m); + else + y := peek(depth - 1); drop(); r := peek(depth - 1); X.alu(X.aluCmp, r, y); + end; + drop(); + if signed then X.jcc(CcSigned[i], L); else X.jcc(CcUnsigned[i], L); end; +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. *) +proc jumpOut*(sy: Scan.Sym; signed: BOOL; var L: INT); +begin + spillBelow(depth - 2); + jumpCmp(sy, 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. *) +proc condValue*(notOp: Scan.Sym; signed: BOOL; fj, tj: INT); +var r, e: INT; +begin + jumpOut(notOp, signed, fj); + X.fixLink(tj); + r := target(); + X.movRI(r, 1); + e := NoLabel; + X.jmp(e); + X.fixLink(fj); + X.movRI(r, 0); + X.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. *) +proc jumpBack*(top: INT); +begin + X.jmpBack(top); +end; + +proc fix*(L: INT); +begin + X.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. *) +proc jumpTable*(slot, lo: I64; n, elseAt: INT; var endL: INT): INT; +const TableAt = 17; +var start: INT; +begin + X.load(RAX, X.mem(RBP, slot), 8, false); + if lo # 0 then X.aluI(X.aluSub, RAX, INT(lo)); end; + X.aluI(X.aluCmp, RAX, n - 1); + if elseAt # NoLabel then X.jccBack(X.ccA, elseAt); else X.jcc(X.ccA, endL); end; + start := Chunk.pc; + X.lea(RCX, X.here()); + X.load(RAX, X.memIdx(RCX, RAX, 4, TableAt), 4, true); + X.alu(X.aluAdd, RAX, RCX); + X.jmpR(RAX); + if Chunk.pc # start + TableAt then Diag.fatal("internal error: the jump table is not where it was said"); end; + return start; +end; + +(* The next entry of the table that jumpTable started at table: the + code at target *) +proc tableEntry*(table, target: INT); +begin + Chunk.put4(target - table); +end; + +proc alignLoop*; +begin + X.align(32); +end; + +proc joinJumps*(L1, L2: INT): INT; +begin + return X.joinLinks(L1, L2); +end; + +proc fixTo*(L, top: INT); +begin + X.fixLinkTo(L, top); +end; + +(* Checks *) + +const + NoBase = -2; (* a Mem that is no memory *) + ARegister = -3; (* a Mem that is no memory but a register, its index *) + +(* The name s, interned *) +proc internStr(s: []U8): INT; +begin + return Scan.intern(ADR(s[0]), LEN(s)); +end; + +(* 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. *) +proc check(cc, what: INT; p: Diag.Pos; ra: INT; m: X.Mem; n: I64; name: INT); +begin + if numFails > LEN(fails) - 1 then + _ := Scan.mark(Diag.say("more than {} checks in one procedure", [Fmt.int(LEN(fails))])); + return; + end; + fails[numFails].L := NoLabel; + X.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 *) +proc endFails; +var i, line, col: INT; f: Fail; +begin + for i := 0 to numFails - 1 do + f := fails[i]; + X.fixLink(f.L); + line, col := Scan.lineCol(f.at); + Chunk.noteLine(line, col); + if f.ra # RAX then X.movRR(RAX, f.ra); end; + if f.m.base = NoBase then X.movRI(RCX, f.n); + elsif f.m.base = ARegister then X.movRR(RCX, f.m.index); + else X.load(RCX, f.m, 8, false); end; + if f.name >= 0 then X.lea(R9, X.memRip(f.name, 0)); end; + if failStubs[f.what] < 0 then + failStubs[f.what] := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr(StubNames[f.what])); + end; + X.callChunk(failStubs[f.what]); + end; + numFails := 0; +end; + +(* For check: a length known here, not in memory *) +proc noMem: X.Mem; +begin + return X.mem(NoBase, 0); +end; + +(* For check: a length in register r, a slice's in registers *) +proc inRegister(r: INT): X.Mem; +var m: X.Mem; +begin + m := X.mem(ARegister, 0); + m.index := r; + return m; +end; + +(* The index on top is below n, unsigned *) +proc checkIndex*(n: I64; p: Diag.Pos); +var r: INT; +begin + r := peek(depth - 1); + cmpI(r, n); + check(X.ccB, 0, p, r, noMem(), n, -1); +end; + +(* The integer on top is a position of an enumeration of n names *) +proc checkEnum*(n: I64; name: INT; p: Diag.Pos); +var r: INT; +begin + r := top(); + cmpI(r, n); + check(X.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. *) +proc checkNil*(reach: I64; p: Diag.Pos); +var r: INT; +begin + if reach <= NilPage then return; end; + r := top(); + X.testRR(r, r); + check(X.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] *) +proc indexOff(size, disp: I64): I64; +begin + if fits32(disp + stack[depth - 1].off * size) then return disp + takeOff(depth - 1) * size; end; + return disp; +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). *) +proc indexSlice*(a: Adr; size: I64; checked: BOOL; p: Diag.Pos); +var m, ml: X.Mem; r: INT; inRax: BOOL; o: I64; +begin + if (a.base = bReg) and (((size = 1) or (size = 2) or (size = 4) or (size = 8))) then + o := 0; + if not checked then o := indexOff(size, 0); end; + r := peek(depth - 1); + if checked then + X.alu(X.aluCmp, r, a.hi); + check(X.ccB, 0, p, r, inRegister(a.hi), 0, -1); + end; + drop(); + newMem(lIdx, X.memIdx(a.chunk, r, INT(size), o), kWord, 8, false); + return; + end; + inRax := a.base = bStack; + if inRax then r := RAX; popTo(RAX); + else r := top(); drop(); end; + if a.base = bReg then + if checked then + X.alu(X.aluCmp, r, a.hi); + check(X.ccB, 0, p, r, inRegister(a.hi), 0, -1); + end; + mulI(r, size); + X.alu(X.aluAdd, r, a.chunk); + else + m := place(a, RCX); + ml := m; ml.disp := ml.disp + 8; + if checked then + X.aluM(X.aluCmp, r, ml); + check(X.ccB, 0, p, r, ml, 0, -1); + end; + mulI(r, size); + X.aluM(X.aluAdd, r, m); + end; + if inRax then X.movRR(target(), RAX); + else _ := claim(depth, kWord); end; (* 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. *) +proc indexArray*(a: Adr; size: I64); +var r, b: INT; o: I64; +begin + if (((size = 1) or (size = 2) or (size = 4) or (size = 8))) and (a.base = bFrame) then + o := indexOff(size, a.off); + r := peek(depth - 1); + drop(); + newMem(lIdx, X.memIdx(RBP, r, INT(size), o), kWord, 8, false); + elsif (((size = 1) or (size = 2) or (size = 4) or (size = 8))) and (a.base = bGlobal) and (stack[depth - 1].loc = lHeld) then + o := indexOff(size, 0); + r := peek(depth - 1); + drop(); + b := target(); + X.lea(b, X.memRip(a.chunk, INT(a.off))); + newMem(lIdx, X.memIdx(b, r, INT(size), o), kWord, 8, false); + else + mulI(top(), size); + pushAdr(a); + op(Scan.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. *) +proc slice*(a: Adr; isArray: BOOL; n, size, tmp: I64; checked: BOOL; p: Diag.Pos); +var m, ml: X.Mem; +begin + popTo(RDX); + popTo(RCX); + if a.base = bSlot then clobberArgs(); end; (* place loads its slot into rdi *) + if a.base = bReg then + ml := inRegister(a.hi); (* a slice in registers *) + else + m := place(a, RDI); + ml := m; ml.disp := ml.disp + 8; + end; + if checked then + (* two checks, both unsigned, so that a negative bound fails too: + hi against the length, then lo against hi *) + if isArray then cmpI(RDX, n); ml := noMem(); + elsif a.base = bReg then X.alu(X.aluCmp, RDX, a.hi); + else X.aluM(X.aluCmp, RDX, ml); end; + check(X.ccBE, 1, p, RCX, ml, n, -1); + X.alu(X.aluCmp, RCX, RDX); + check(X.ccBE, 1, p, RCX, ml, n, -1); + end; + X.movRR(RAX, RDX); + X.alu(X.aluSub, RAX, RCX); + X.store(X.mem(RBP, tmp + 8), RAX, 8); + mulI(RCX, size); + if isArray then X.lea(RAX, m); + elsif a.base = bReg then X.movRR(RAX, a.chunk); + else X.load(RAX, m, 8, false); end; + X.alu(X.aluAdd, RAX, RCX); + X.store(X.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. *) +proc copySlice*(dOff, sOff, size: I64; checked: BOOL; p: Diag.Pos); +var ml: X.Mem; L, E: INT; +begin + clobberArgs(); + X.load(RDX, X.mem(RBP, sOff + 8), 8, false); + if checked then + ml := X.mem(RBP, dOff + 8); + X.movRI(RAX, 0); + X.aluM(X.aluCmp, RDX, ml); + check(X.ccBE, 1, p, RAX, ml, 0, -1); + end; + X.movRR(RCX, RDX); + mulI(RCX, size); + X.load(RSI, X.mem(RBP, sOff), 8, false); + X.load(RDI, X.mem(RBP, dOff), 8, false); + X.alu(X.aluCmp, RDI, RSI); + L := NoLabel; + X.jcc(X.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 *) + X.lea(RSI, X.memIdx(RSI, RCX, 1, -1)); + X.lea(RDI, X.memIdx(RDI, RCX, 1, -1)); + X.std(); + X.repMovsb(); + X.cld(); + E := NoLabel; + X.jmp(E); + X.fixLink(L); + X.repMovsb(); + X.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. *) +proc slicePtr*(size, tmp: I64; checked: BOOL; p: Diag.Pos); +begin + clobberArgs(); + popTo(RDX); + popTo(RCX); + popTo(RDI); + if checked then + X.alu(X.aluCmp, RCX, RDX); + check(X.ccLE, 3, p, RCX, noMem(), 0, -1); + end; + X.movRR(RAX, RDX); + X.alu(X.aluSub, RAX, RCX); + X.store(X.mem(RBP, tmp + 8), RAX, 8); + mulI(RCX, size); + X.alu(X.aluAdd, RCX, RDI); + X.store(X.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. *) + +proc call*(var c: CallInfo); +var + res: ^Sym.Type; i, ni, nf, k, pad, r, first: INT; + onStack: [64]BOOL; late: [2]INT; (* late: the values for r8 and r9 *) +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 (Sym.behindPointer(res) or (res^.form = Sym.fSlice)) then + c.ret := allocTemp(res^.size, res^.align); + if Sym.behindPointer(res) then ni := 1; end; + 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 + if c.isF[i] then + onStack[i] := nf >= 8; + if nf < 8 then INC(nf); end; + else + (* 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]; + elsif c.pair[i] then onStack[i] := ni > 4; + else onStack[i] := ni >= 6; end; + if not onStack[i] then INC(ni); end; + end; + if onStack[i] then INC(k); end; + 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 := 0; + if ((pushed + k) & 1) # 0 then pad := 1; end; + if pad # 0 then X.aluI(X.aluSub, RSP, 8); end; + for i := c.n - 1 to 0 by -1 do + if onStack[i] then + valueTo(first + i, RAX); + X.push(RAX); + end; + end; + ni := 0; nf := 0; + late[0] := -1; late[1] := -1; + if (c.ret # 0) and Sym.behindPointer(res) then X.lea(RDI, X.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 + xValueTo(first + i, nf); + INC(nf); + else + if ni < 4 then valueTo(first + i, IntRegs[ni]); else late[ni - 4] := first + i; end; + INC(ni); + end; + end; + end; + if late[0] >= 0 then valueTo(late[0], RAX); end; + if late[1] >= 0 then valueTo(late[1], R9); end; + if late[0] >= 0 then X.movRR(R8, RAX); end; + for i := 1 to c.n do drop(); end; + (* a procedure taking ... is told in al how many xmm registers it got *) + if c.sig^.variadic then X.movRI(RAX, nf); end; + if c.ext then X.callM(X.memRip(c.chunk, 0)); + elsif c.chunk >= 0 then X.callChunk(c.chunk); + else + (* r11 is scratch: caller-saved, carrying no argument, and free, + as the value stack was spilled above *) + X.load(R11, X.mem(RBP, c.target), 8, false); + X.callR(R11); + end; + if k + pad > 0 then X.aluI(X.aluAdd, RSP, 8 * (k + pad)); end; + (* the variables in xmm registers, which the call may have changed, + from their slots *) + for i := 0 to 3 do + if (regMask & (1 shl (XBit + i))) # 0 then + X.movsXM(XVarRegs[i] - XmmVar, X.mem(RBP, homes[i]), false); + end; + end; + (* 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 + if res^.form = Sym.fSlice then + X.store(X.mem(RBP, c.ret), RAX, 8); + X.store(X.mem(RBP, c.ret + 8), RDX, 8); + elsif Sym.inTwoRegs(res) then + X.movRR(target(), RAX); computed(kWord); + X.movRR(target(), RDX); computed(kWord); + elsif (c.ret = 0) and (res^.form = Sym.fReal) then + X.movX(xTarget(), 0); + computed(kindOf(res)); + elsif c.ret = 0 then + r := target(); + X.movRR(r, RAX); + if res^.form = Sym.fBool then X.extend(r, 1, false); + elsif (res^.form = Sym.fInt) and (res^.size < 8) then X.extend(r, INT(res^.size), res^.signed); end; + computed(kindOf(res)); + end; + 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. *) +proc allocTemp*(size, align: I64): I64; +begin + if align < 1 then align := 1; end; + frameTop := Sym.alignUp(frameTop + size, align); + if frameTop > frameMax then frameMax := frameTop; end; + return -frameTop; +end; + +proc allocPerm*(size, align: I64): I64; +var s: I64; +begin + s := allocTemp(size, align); + permTop := frameTop; + return s; +end; + +proc tempMark*: I64; +begin + return frameTop; +end; + +(* The slots allocated since the mark m are free again, but those + allocPerm made stay *) +proc releaseTemps*(m: I64); +begin + if m < permTop then m := permTop; end; + 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. *) +proc 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). *) +proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj); +var p: ^Sym.Obj; ni, nf, k: INT; stackOff: I64; f: BOOL; +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 Sym.behindPointer(resType) then + 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 + p^.ind := p^.isVar or (Sym.isAggregate(p^.typ) and (p^.typ^.form # Sym.fSlice)); + f := (p^.typ^.form = Sym.fReal) and not p^.isVar; + if (p^.typ^.form = Sym.fSlice) and not p^.isVar then + (* its two words, in two registers or both on the stack *) + if ni <= 4 then + p^.val := allocPerm(16, 8); + for k := 0 to 1 do + inReg[numIn] := IntRegs[ni]; inSlot[numIn] := p^.val + I64(8 * k); + inSize[numIn] := 8; inObj[numIn] := p; + INC(numIn); INC(ni); + end; + else + p^.val := stackOff; + INC(stackOff, 16); + end; + elsif (f and (nf < 8)) or (not f and (ni < 6)) then + 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 + inReg[numIn] := -1 - nf; INC(nf); + else + inReg[numIn] := IntRegs[ni]; INC(ni); + end; + inSlot[numIn] := p^.val; + inObj[numIn] := p; + if p^.ind then inSize[numIn] := 8; + elsif p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fReal} then inSize[numIn] := INT(p^.typ^.size); + else inSize[numIn] := 8; end; + INC(numIn); + else + 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. *) +proc 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 *) +proc arrivesIn(o: ^Sym.Obj; word: INT): INT; +var i, r: INT; +begin + r := -1; + for i := 0 to numIn - 1 do + if (inObj[i] = o) and (inSlot[i] = o^.val + I64(8 * word)) and (inReg[i] >= 0) then r := inReg[i]; end; + end; + return r; +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. *) +proc keepArrived*(o: ^Sym.Obj); +var r: INT; +begin + r := arrivesIn(o, 0); + if o^.typ^.form = Sym.fSlice then + if (r = RDI) and (arrivesIn(o, 1) = RSI) then o^.reg := RDI; o^.reg2 := RSI; end; + elsif (r = RDI) or (r = RSI) then o^.reg := r; end; +end; + +(* Whether parameter o is kept where it arrived *) +proc keptIn*(o: ^Sym.Obj): BOOL; +begin + return (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. *) +proc useRegs*(mask: INT); +var i, k: INT; p: ^Sym.Obj; +begin + zeroTop := permTop; + regMask := mask; + (* the parameters left in rdi and rsi, as they arrived *) + kept := 0; + p := procParams; + while p # nil do + if ((p^.reg = RDI) or (p^.reg = RSI)) then kept := kept | (1 shl p^.reg); end; + if ((p^.reg2 = RDI) or (p^.reg2 = RSI)) then kept := kept | (1 shl p^.reg2); end; + p := p^.next; + end; + k := 0; + for i := 0 to 4 do + if (mask & (1 shl i)) # 0 then INC(k); end; + end; + if k > 0 then saveAt := allocPerm(8 * k, 8); end; + 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 *) +proc xHome*(r: INT; slot: I64); +begin + homes[r - XVarRegs[0]] := slot; +end; + +proc markCode*(var m: CodeMark); +begin + m.pc := Chunk.pc; m.fixups := Chunk.numFixups; m.lines := Chunk.numLines; m.said := X.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 *) +proc rewind*(m: CodeMark); +begin + Chunk.rewindTo(m.pc, m.fixups, m.lines); + X.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 *) +proc redo*(m: CodeMark); +begin + Chunk.rewindTo(m.pc, m.fixups, m.lines); + X.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. *) +proc enterBody*(c, line: INT); +var i, loop, r: INT; n: I64; p: ^Sym.Obj; +begin + Chunk.beginChunk(c); + codeChunk := c; + Chunk.noteLine(line, 1); (* a declaration starts a line *) + X.push(RBP); + X.movRR(RBP, RSP); + X.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 *) + Chunk.put1(48H); Chunk.put1(81H); Chunk.put1(0ECH); + frameFix := Chunk.pc; Chunk.put4(0); + n := (Sym.alignUp(zeroTop, 8) - paramTop) div 8; + if n > 0 then X.movRI(RAX, 0); end; + if n <= 4 then + for i := 1 to INT(n) do X.store(X.mem(RBP, -paramTop - I64(8 * i)), RAX, 8); end; + else + (* a quadword at a time: r10 runs from -n up to 0, and the store's + address is scaled by it *) + X.movRI(R10, -n); + loop := Chunk.pc; + X.store(X.memIdx(RBP, R10, 8, -paramTop), RAX, 8); + X.aluI(X.aluAdd, R10, 1); + X.jccBack(X.ccNE, loop); + end; + (* each register that holds a variable is saved, for the caller, and + zeroed, as a variable starts at zero *) + Chunk.setSaves(c, regMask & ((1 shl XBit) - 1), INT(saveAt)); + n := 0; + for i := 0 to 4 do + if (regMask & (1 shl i)) # 0 then + X.store(X.mem(RBP, saveAt + 8 * n), VarRegs[i], 8); + X.movRI(VarRegs[i], 0); + INC(n); + end; + 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 & (1 shl (XBit + i))) # 0 then + X.movRI(RAX, 0); + X.movqXR(XVarRegs[i] - XmmVar, RAX); + end; + 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 + X.movsMX(X.mem(RBP, inSlot[i]), -1 - inReg[i], false); + if inObj[i]^.reg # 0 then X.movX(inObj[i]^.reg - XmmVar, -1 - inReg[i]); end; + elsif (inObj[i] # nil) and (inObj[i]^.reg # 0) then + r := inObj[i]^.reg; + if inSlot[i] # inObj[i]^.val then r := inObj[i]^.reg2; end; + if r # inReg[i] then X.movRR(r, inReg[i]); end; (* else it is kept where it is *) + if inSize[i] < 8 then X.extend(r, inSize[i], inObj[i]^.typ^.signed); end; + else + X.store(X.mem(RBP, inSlot[i]), inReg[i], inSize[i]); + end; + end; + (* 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 + if (p^.reg # 0) and (p^.val > 0) then + if p^.typ^.form = Sym.fReal then + X.movsXM(p^.reg - XmmVar, X.mem(RBP, p^.val), p^.typ^.size = 4); + elsif p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet} then + X.load(p^.reg, X.mem(RBP, p^.val), INT(p^.typ^.size), p^.typ^.signed); + else + X.load(p^.reg, X.mem(RBP, p^.val), 8, false); + if p^.typ^.form = Sym.fSlice then X.load(p^.reg2, X.mem(RBP, p^.val + 8), 8, false); end; + end; + 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. *) +proc resultTo*(off: I64; size: INT); +var r: INT; fl: BOOL; +begin + r := top(); + fl := isReal(depth - 1); + drop(); + X.load(RCX, X.mem(RBP, retSlot), 8, false); + if fl then X.movsMX(X.mem(RCX, off), r, size = 4); + else X.store(X.mem(RCX, off), r, size); end; +end; + +(* Pops an address, and copies size bytes from it to the result, off + bytes into it. *) +proc copyResult*(off, size: I64); +begin + clobberArgs(); + popTo(RSI); + X.load(RDI, X.mem(RBP, retSlot), 8, false); + if off # 0 then X.lea(RDI, X.mem(RDI, off)); end; + 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. *) +proc returnJump*; +begin + if resType # nil then + if Sym.behindPointer(resType) then + X.load(RAX, X.mem(RBP, retSlot), 8, false); + elsif Sym.inTwoRegs(resType) then + popTo(RDX); + popTo(RAX); + elsif resType^.form = Sym.fReal then + xValueTo(depth - 1, 0); + drop(); + else + popTo(RAX); + end; + end; + X.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. *) +proc tryAlign*; +begin + X.aluI(X.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. *) +proc tryReturn*(slot: I64); +var f: ^Sym.Obj; +begin + if Sym.behindPointer(resType) then + X.load(RDI, X.mem(RBP, retSlot), 8, false); + X.movRI(RCX, resType^.size); + X.movRI(RAX, 0); + X.repStosb(); + f := resType^.fields; + while f^.next # nil do f := f^.next; end; + X.load(RCX, X.mem(RBP, slot), 8, false); + X.load(RDX, X.mem(RBP, retSlot), 8, false); + X.store(X.mem(RDX, f^.val), RCX, 8); + X.load(RAX, X.mem(RBP, retSlot), 8, false); + elsif Sym.inTwoRegs(resType) then + X.load(RDX, X.mem(RBP, slot), 8, false); + X.movRI(RAX, 0); + else + X.load(RAX, X.mem(RBP, slot), 8, false); + end; + X.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. *) +proc endProc*(c: INT; open: BOOL): ERROR; +var n: I64; i: INT; +begin + codeChunk := -1; + if (depth # 0) or (pushed # 0) then Diag.fatal("internal error: stack depth"); end; + if open then + if Sym.behindPointer(resType) then + X.load(RDI, X.mem(RBP, retSlot), 8, false); + X.movRI(RCX, resType^.size); + X.movRI(RAX, 0); + X.repStosb(); + X.load(RAX, X.mem(RBP, retSlot), 8, false); + else + X.movRI(RAX, 0); + if Sym.inTwoRegs(resType) then X.movRI(RDX, 0); end; + X.movqXR(0, RAX); + end; + else + X.dropJumpTo(exitL); + end; + X.fixLink(exitL); + n := 0; + for i := 0 to 4 do + if (regMask & (1 shl i)) # 0 then + X.load(VarRegs[i], X.mem(RBP, saveAt + 8 * n), 8, false); + INC(n); + end; + end; + X.leave(); + X.ret(); + endFails(); + n := Sym.alignUp(frameMax, 16); + if n < 16 then n := 16; end; + if n > 2147483647 then return Scan.mark("frame too big"); end; + Chunk.put4At(frameFix, INT(n)); + (* the listing's text for the sub, which starts 3 bytes (REX.W, opcode, + ModRM) before its immediate *) + if X.listing then X.restate(frameFix - 3, Diag.say("sub rsp, {}", [Fmt.int(INT(n))])); end; + Chunk.endChunk(c); + return nil; +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 what pushed was, and starts it, with the return address + pushed. The stack is empty where it is called, and where it begins. *) +proc deferBegin*(var L: INT): (INT, INT); +var saved: INT; +begin + X.jmp(L); + saved := pushed; + pushed := 1; + return Chunk.pc, saved; +end; + +proc deferEnd*(L, saved: INT); +begin + keepTemps(); + X.ret(); + X.fixLink(L); + pushed := saved; +end; + +proc runDefer*(at: INT); +begin + X.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. mainObj: 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. *) +proc entryPoint*(dynamic: BOOL; first: ^Sym.Module; mainObj: ^Sym.Obj; cExit, exitProc: INT; links: []Link; numLinks: INT): INT; +var entry, start, i: INT; m: ^Sym.Module; +begin + entry := Chunk.newChunk(Chunk.secText, -1, internStr("_start")); + if dynamic then + start := Chunk.newChunk(Chunk.secText, -1, internStr("main")); + Chunk.beginChunk(entry); + (* at the start rdx holds rtld_fini, from the dynamic loader, and the + stack argc, then argv *) + X.movRI(X.RBP, 0); (* no frame above, where a trace stops *) + X.movRR(R9, RDX); (* rtld_fini, the sixth argument *) + X.pop(RSI); (* argc, the second *) + X.movRR(RDX, RSP); (* argv, the third *) + X.aluI(X.aluAnd, RSP, -16); + X.push(RAX); (* padding, so that the next push, the seventh *) + X.push(RSP); (* argument, stack_end, leaves rsp aligned *) + X.movRI(R8, 0); (* fini and init: none *) + X.movRI(RCX, 0); + X.lea(RDI, X.memRip(start, 0)); (* main, the first argument *) + X.callM(X.memRip(Chunk.externChunk(internStr("__libc_start_main")), 0)); + X.ud2(); (* it never returns *) + Chunk.endChunk(entry); + Chunk.beginChunk(start); + X.push(RBP); (* aligns the stack again *) + X.store(X.memRip(argcChunk, 0), RDI, 8); + X.store(X.memRip(argvChunk, 0), RSI, 8); + X.load(RAX, X.memRip(Chunk.externChunk(internStr("exit")), 0), 8, false); + X.store(X.memRip(cExit, 0), RAX, 8); + else + start := entry; + Chunk.beginChunk(entry); + X.load(RAX, X.mem(RSP, 0), 8, false); + X.store(X.memRip(argcChunk, 0), RAX, 8); + X.lea(RAX, X.mem(RSP, 8)); + X.store(X.memRip(argvChunk, 0), RAX, 8); + end; + for i := 0 to numLinks - 1 do + X.lea(RAX, X.memRip(links[i].chunk, 0)); + X.store(X.memRip(links[i].into, 0), RAX, 8); + end; + m := first; + while m # nil do + if m^.used and (m^.body >= 0) then X.callChunk(m^.body); end; + m := m^.next; + end; + if mainObj # nil then X.callChunk(mainObj^.chunk); end; + if (mainObj # nil) and (mainObj^.typ^.base # nil) then X.movRR(RDI, RAX); else X.movRI(RDI, 0); end; + X.callChunk(exitProc); + X.ud2(); (* exit never returns: trap if it does *) + Chunk.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 LEN(failStubs) - 1 do + if failStubs[i] >= 0 then + Chunk.beginChunk(failStubs[i]); + X.load(R8, X.mem(RSP, 0), 8, false); + X.aluI(X.aluSub, R8, 1); + X.aluI(X.aluAnd, RSP, -16); + X.push(RSI); + X.push(RDI); + X.movRR(RSI, RAX); + X.movRI(RDI, i); + X.callChunk(rtFail); + X.ud2(); + Chunk.endChunk(failStubs[i]); + end; + end; + return entry; +end; + +(* A code procedure: its instructions, read by the assembler (X64), + are the whole of chunk c *) +proc codeProc*(c: INT; constExpr: X.ConstFn): ERROR; +begin + Chunk.beginChunk(c); + try X.assemble(constExpr); + Chunk.endChunk(c); + return nil; +end; + +var i: INT; +begin + for i := 0 to LEN(failStubs) - 1 do failStubs[i] := -1; end; + inPlace := -1; + codeChunk := -1; + resetStack(0, 0); + rtFail := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr("fail")); + argcChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argc")); + Chunk.setBss(argcChunk, 8, 8); + argvChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argv")); + Chunk.setBss(argvChunk, 8, 8); +end Gen. diff --git a/src/Item.raz b/src/Item.raz new file mode 100644 index 0000000..25e0303 --- /dev/null +++ b/src/Item.raz @@ -0,0 +1,1729 @@ +(* Item: operands, their types, and what they mean. + + The parser describes each operand as an item, 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 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; the machine, which + is Gen. + + An error the seed's `Mark` ended in a jump back to the parser's + recovery point. Here the routine that finds it shows it and returns + `Scan.Failed`, and every routine that calls one passes it up with + `try`, to where the parser reads on: what has been made by then is + what the seed had made when it jumped. So most routines here return an + ERROR, as the last of their results. + + The seed's `Mismatch` of two operands is `mismatchOps` (raz has no + overloading), and what the parser sets, `demoted` and `checks`, has a + setter each, as an exported variable is read-only outside its module. + The seed's `TItem` is `Item` and `TMode` is `Mode`; its procedures begin + in lower case. *) +module Item; +import Fmt, Diag, Scan, Sym, Chunk, Gen; + +type + Mode* = (mConst, mVar, mStack, mProc, mType, mStr, mBuiltin, mCase, mNone, mCond, + mWords); (* two results of a call, on the stack, the first under the second *) + + Item* = record + mode*: Mode; + typ*: ^Sym.Type; + rel*: Scan.Sym; (* mCond: the comparison of the two integers on + the stack, not yet made, as Wirth's compilers + keep a condition *) + relSigned*: BOOL; + fj*, tj*: INT; (* 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*: I64; (* mConst: the value, an F64's bits; mStr: its length *) + base*: Gen.Base; (* mVar: what the address is relative to *) + chunk*: INT; (* mVar with bGlobal, mStr: the chunk; bSlot: the slot *) + off*: I64; (* mVar: added to the base *) + vol*: BOOL; (* mVar: reached through ^VOLATILE *) + isVar*: BOOL; (* mVar: a variable of the program, not a temporary *) + odd*: BOOL; (* mVar: in a packed record, so maybe misaligned *) + ro*: BOOL; (* mVar: another module's exported variable, or part + of one, which only that module changes *) + deref*: BOOL; (* mVar: at an address from a pointer, which may be + nil and isn't tested yet (nilTest) *) + obj*: ^Sym.Obj; (* mProc, mBuiltin, mCase; mVar: the variable named *) + pos*: Diag.Pos; (* where it is in the source, for messages *) + end; + +const + (* the comparison that holds when the one at the same place doesn't, for integers *) + NegatedOps: [6]Scan.Sym = [Scan.sNeq, Scan.sEql, Scan.sGeq, Scan.sGtr, Scan.sLeq, Scan.sLss]; + +const + MaxI64 = 9223372036854775807; + MinI64 = -9223372036854775807 - 1; + +var + demoted*: BOOL; (* address wanted a register variable's address: its + procedure is compiled again, the variable in memory *) + checks*: BOOL; (* the module's index and slice checks are made: it + doesn't say check off *) + result: ^Sym.Type; (* the result of the procedure being compiled, or nil *) + passing: ^Sym.Obj; (* the parameter the argument at passingAt goes to *) + passingAt: Diag.Pos; + +proc setDemoted*(yes: BOOL); +begin + demoted := yes; +end; + +proc setChecks*(yes: BOOL); +begin + checks := yes; +end; + +(* The comparison that holds when op doesn't *) +proc negated(op: Scan.Sym): Scan.Sym; +begin + return NegatedOps[INT(op) - INT(Scan.sEql)]; +end; + +proc isRel(op: Scan.Sym): BOOL; +begin + return (op >= Scan.sEql) and (op <= Scan.sGeq); +end; + +(* Whether op is one of the list: Scan.Sym has too many names for a set *) +proc oneOf(op: Scan.Sym; list: []Scan.Sym): BOOL; +var i: INT; +begin + for i := 0 to LEN(list) - 1 do + if list[i] = op then return true; end; + end; + return false; +end; + +proc bit(f: BOOL): I64; +begin + if f then return 1; end; + return 0; +end; + +(* A message, from a format and the strings that fill it *) +proc say1(f, a: []U8): []U8; +begin + return Diag.say(f, [Fmt.str(a)]); +end; + +proc say2(f, a, b: []U8): []U8; +begin + return Diag.say(f, [Fmt.str(a), Fmt.str(b)]); +end; + +(* Items *) + +proc makeConst*(var x: Item; t: ^Sym.Type; v: I64); +var p: Diag.Pos; +begin + p := x.pos; + x := {}; + 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. *) +proc makeReal*(var x: Item; r: F64); +var p: ^F64; +begin + makeConst(x, Sym.tRConst, 0); + p := ^F64(ADR(x.val)); + p^ := r; +end; + +proc isF32(t: ^Sym.Type): BOOL; +begin + return (t^.form = Sym.fReal) and (t^.size = 4); +end; + +proc realOf*(x: Item): F64; +var v: I64; p: ^F64; +begin + v := x.val; + p := ^F64(ADR(v)); + return p^; +end; + +(* Gives a real constant the real type t, rounded to it. *) +proc realTo(var x: Item; t: ^Sym.Type); +var r: F64; +begin + r := realOf(x); + if isF32(t) then makeReal(x, F64(F32(r))); else makeReal(x, r); end; + x.typ := t; +end; + +(* The current string literal, as an item of its own chunk. *) +proc makeStr*(var x: Item); +begin + x := {}; + x.mode := mStr; + x.typ := Sym.tStr; + x.val := Scan.slen; + x.chunk := Chunk.newChunk(Chunk.secRodata, -1, -1); + Chunk.setData(x.chunk, Scan.strWithZero(), Scan.slen + 1, 1); +end; + +proc frameAdr*(off: I64): Gen.Adr; +var a: Gen.Adr; +begin + a.base := Gen.bFrame; + a.chunk := -1; + a.off := off; + a.hi := 0; + return a; +end; + +proc globalAdr*(c: INT): Gen.Adr; +var a: Gen.Adr; +begin + a.base := Gen.bGlobal; + a.chunk := c; + a.off := 0; + a.hi := 0; + return a; +end; + +(* Where the variable x is, for Gen; a slice in registers has two *) +proc adrOf*(x: Item): Gen.Adr; +var a: Gen.Adr; +begin + a.base := x.base; + a.chunk := x.chunk; + a.off := x.off; + a.hi := 0; + if x.base = Gen.bReg then a.hi := x.obj^.reg2; end; + return a; +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. *) +proc what*(x: Item): []U8; +begin + if (x.mode = mConst) and ((x.typ = Sym.tConst) or (x.typ = Sym.tRConst)) then + return Diag.source(x.pos); + end; + return Sym.typeName(x.typ); +end; + +(* Two operands of different types. Numbers convert, so say how. *) +proc mismatchOps(x, y: Item; xt, yt: ^Sym.Type): ERROR; +var text: []U8; +begin + text := say2("{} and {} are different types", Sym.typeName(xt), Sym.typeName(yt)); + if (Sym.isInt(xt) or (xt^.form = Sym.fReal)) and (Sym.isInt(yt) or (yt^.form = Sym.fReal)) + and (xt # Sym.tConst) and (xt # Sym.tRConst) then + return Scan.markHelp(Diag.join(x.pos, y.pos), text, + say2("convert one to the other's type, as in {}({})", Sym.typeName(xt), Diag.source(y.pos))); + end; + return Scan.markAt(Diag.join(x.pos, y.pos), text); +end; + +(* An item that is not a value, by what it is. *) +proc notValue(x: Item): ERROR; +begin + match x.mode of + | mType: return Scan.markAt(x.pos, say1("{} is a type, not a value", Sym.typeName(x.typ))); + | mBuiltin: return Scan.markAt(x.pos, say1("{} is a built-in procedure, not a value", Scan.nameOf(x.obj^.name))); + | mCase: return Scan.markAt(x.pos, say1("{} is a case, not a value", Scan.nameOf(x.obj^.name))); + | mNone: + if x.obj # nil then return Scan.markAt(x.pos, say1("{} returns nothing", Scan.nameOf(x.obj^.name))); end; + return Scan.markAt(x.pos, "the procedure returns nothing"); + | else: return Scan.markAt(x.pos, "a string can't be an operand"); + end; +end; + +proc makeItem*(var x: Item; o: ^Sym.Obj): ERROR; +begin + x := {}; + x.typ := o^.typ; + x.obj := o; + match o^.cls of + | oConst: + if o^.typ = Sym.tStr then + x.mode := mStr; x.val := o^.val; x.chunk := o^.chunk; + elsif o^.typ^.form in {Sym.fArray, Sym.fRecord} then + (* 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 := Gen.bGlobal; x.chunk := o^.chunk; + else + x.mode := mConst; x.val := o^.val; + end; + | oVar: + x.mode := mVar; + x.ro := (o^.lev = 0) and (o^.home # Sym.curModule); + x.isVar := not x.ro; + if o^.ext then + Gen.pushVar(globalAdr(o^.chunk), 8, false, Gen.kWord); + x.base := Gen.bStack; + elsif o^.lev = 0 then + x.base := Gen.bGlobal; x.chunk := o^.chunk; + elsif o^.ind then + x.base := Gen.bSlot; x.chunk := INT(o^.val); x.off := o^.off; + elsif o^.reg # 0 then + x.base := Gen.bReg; x.chunk := o^.reg; + else + x.base := Gen.bFrame; x.off := o^.val; + end; + | oProc: x.mode := mProc; + | oType: x.mode := mType; + | oBuiltin: x.mode := mBuiltin; + | oCase: x.mode := mCase; + | else: return Scan.mark(say1("{} is not a value", Scan.nameOf(o^.name))); + end; + return nil; +end; + +proc scalarSize*(t: ^Sym.Type): INT; +begin + if t^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fReal} then return INT(t^.size); end; + return 8; +end; + +(* The width an operation on t is brought back to, and whether signed *) +proc intSize(t: ^Sym.Type): INT; +begin + if t^.form = Sym.fInt then return INT(t^.size); end; + return 8; +end; + +proc signed(t: ^Sym.Type): BOOL; +begin + return ((t^.form = Sym.fInt) and t^.signed) or (t^.form = Sym.fConst); +end; + +proc cut(v: I64; t: ^Sym.Type): I64; +begin + if t^.form # Sym.fInt then return v; end; + match t^.size of + | 1: if t^.signed then return I64(I8(v)); end; return I64(U8(v)); + | 2: if t^.signed then return I64(I16(v)); end; return I64(U16(v)); + | 4: if t^.signed then return I64(I32(v)); end; return I64(U32(v)); + | else: return 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. *) +proc usesReals*(p: Diag.Pos); +begin + if (Gen.codeChunk >= 0) and not Chunk.chunks[Gen.codeChunk].reals then + Chunk.setReals(Gen.codeChunk, 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. *) +proc nilTest*(var x: Item); +begin + if (x.mode = mVar) and x.deref then Gen.checkNil(x.off + x.typ^.size, x.pos); end; + x.deref := false; +end; + +(* x's value, on top of the stack *) +proc value*(var x: Item): ERROR; +var f: F32; p: ^U32; +begin + if x.mode = mCond then + if (x.fj = Gen.NoLabel) and (x.tj = Gen.NoLabel) then Gen.compare(x.rel, Gen.kWord, x.relSigned); + else Gen.condValue(negated(x.rel), x.relSigned, x.fj, x.tj); end; + x.mode := mStack; + return nil; + end; + if x.typ^.form = Sym.fReal then usesReals(x.pos); end; + nilTest(x); + match x.mode of + | mConst: + if (x.typ^.form = Sym.fError) and (x.val > 0) then Gen.pushAdr(globalAdr(INT(x.val) - 1)); + elsif isF32(x.typ) then + f := F32(realOf(x)); + p := ^U32(ADR(f)); + Gen.pushConst(Gen.kF32, I64(p^)); + else Gen.pushConst(Gen.kindOf(x.typ), x.val); end; + | mVar: + if not Sym.isScalar(x.typ) then + return Scan.markAt(x.pos, say1("expected a single value, found {}", what(x))); + end; + Gen.pushVar(adrOf(x), scalarSize(x.typ), (x.typ^.form = Sym.fInt) and x.typ^.signed, Gen.kindOf(x.typ)); + | mStack: x.mode := mStack; + | mProc: + if x.obj^.isCode and (x.obj^.typ^.base # nil) and x.obj^.typ^.base^.tuple then + return Scan.markAt(x.pos, "a code procedure with two results can only be called"); + end; + Gen.pushProc(x.obj^.chunk, x.obj^.ext); + | else: return notValue(x); + end; + x.mode := mStack; + return nil; +end; + +(* The address of the variable or string x, on top of the stack *) +proc address*(var x: Item): ERROR; +begin + nilTest(x); + if (x.mode = mVar) and (x.base = Gen.bReg) then + (* 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 := Gen.bFrame; + x.off := x.obj^.val; + end; + if x.mode = mStr then Gen.pushAdr(globalAdr(x.chunk)); + elsif x.mode = mVar then + Gen.pushAdr(adrOf(x)); + x.base := Gen.bStack; x.off := 0; + else return Scan.markAt(x.pos, "expected a variable"); end; + return nil; +end; + +(* x isn't wanted: what it has on the stack is dropped *) +proc discard*(x: Item): ERROR; +var y: Item; +begin + if x.mode = mCond then + y := x; + try value(y); + Gen.drop(); + return nil; + end; + if (x.mode = mStack) or ((x.mode = mVar) and (x.base = Gen.bStack)) then Gen.drop(); end; + if x.mode = mWords then Gen.drop(); Gen.drop(); end; + return nil; +end; + +(* Frames *) + +proc tempItem*(var x: Item; t: ^Sym.Type; off: I64); +var p: Diag.Pos; +begin + p := x.pos; + x := {}; + x.pos := p; + x.mode := mVar; x.typ := t; x.base := Gen.bFrame; x.off := off; +end; + +proc toSlot*(var x: Item): (I64, ERROR); +var s: I64; +begin + try value(x); + s := Gen.allocTemp(8, 8); + Gen.popVar(frameAdr(s), 8); + return s, nil; +end; + +(* Copying *) + +(* x, copied to a temporary *) +proc copyToTemp*(var x: Item): ERROR; +var t: I64; f, g: ^Sym.Obj; a: Gen.Adr; +begin + if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end; + t := Gen.allocTemp(x.typ^.size, x.typ^.align); + if (x.mode = mVar) and (x.base = Gen.bReg) then + (* a slice in registers, which has no address: its words stored *) + a := adrOf(x); + Gen.pushVar(a, 8, false, Gen.kWord); + Gen.popVar(frameAdr(t), 8); + a.off := 8; + Gen.pushVar(a, 8, false, Gen.kWord); + Gen.popVar(frameAdr(t + 8), 8); + tempItem(x, x.typ, t); + return nil; + end; + if x.mode = mWords then + (* the second result is on top, so it is popped first *) + f := x.typ^.fields; g := f^.next; + Gen.popVar(frameAdr(t + g^.val), scalarSize(g^.typ)); + Gen.popVar(frameAdr(t + f^.val), scalarSize(f^.typ)); + tempItem(x, x.typ, t); + return nil; + end; + try address(x); + Gen.copyTo(frameAdr(t), x.typ^.size); + tempItem(x, x.typ, t); + return nil; +end; + +(* A slice made from an address on the stack and a length. *) +proc sliceOf*(var x: Item; t: ^Sym.Type; len: I64); +var s: I64; +begin + s := Gen.allocTemp(16, 8); + Gen.popVar(frameAdr(s), 8); + Gen.pushConst(Gen.kWord, len); + Gen.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). *) +proc widens(s, t: ^Sym.Type): BOOL; +begin + return ((s = Sym.tInt) and Sym.same(t, Sym.tI64)) or ((s = Sym.tUInt) and Sym.same(t, Sym.tU64)); +end; + +(* Another module's exported variable can be read, not changed, nor + handed to anything that could change it (report section 3). *) +proc notReadOnly*(x: Item): ERROR; +begin + if x.ro then + return Scan.markAt(x.pos, Diag.say("{} is {}'s, and can't be changed outside it", + [Fmt.str(Diag.source(x.pos)), Fmt.str(Scan.nameOf(x.obj^.home^.name))])); + end; + return nil; +end; + +(* An error in x's type; if x is an argument, a note at the parameter + it goes to. *) +proc mismatch(x: Item; text: []U8): ERROR; +begin + Diag.error(x.pos, text); + if (passing # nil) and (x.pos.f = passingAt.f) and (x.pos.a = passingAt.a) and (x.pos.b = passingAt.b) then + Diag.note(passing^.pos, say1("it goes to {}, declared here", Scan.nameOf(passing^.name))); + end; + return Scan.Failed; +end; + +proc coerce*(var x: Item; t: ^Sym.Type): ERROR; +var s: ^Sym.Type; tmp: I64; +begin + if x.mode = mCond then try value(x); end; + s := x.typ; + if x.mode = mStr then + if (t^.form = Sym.fSlice) and (t^.base = Sym.tU8) then + try address(x); sliceOf(x, t, x.val); + elsif (t^.form = Sym.fPtr) and (t^.base = Sym.tU8) then + try address(x); x.mode := mStack; x.typ := t; + elsif (t^.form = Sym.fArray) and (t^.base = Sym.tU8) and (t^.len >= x.val) then + tmp := Gen.allocTemp(t^.size, 1); + try address(x); + Gen.copyTo(frameAdr(tmp), x.val); + if t^.len > x.val then Gen.zeroVar(frameAdr(tmp + x.val), t^.len - x.val); end; + tempItem(x, t, tmp); + else return mismatch(x, say1("can't use a string as {}", Sym.typeName(t))); end; + return nil; + end; + if x.mode in {mType, mBuiltin, mNone, mCase} then return notValue(x); end; + if Sym.same(s, t) then return nil; end; + if widens(s, t) then x.typ := t; (* the same bits, on a 64-bit target *) + elsif (s = Sym.tRConst) and (t^.form = Sym.fReal) then realTo(x, t); + elsif (s^.form = Sym.fConst) and (t^.form = Sym.fInt) then + if (x.mode = mConst) and not Sym.fits(x.val, t) then + return Scan.markAt(x.pos, Diag.say("{} doesn't fit {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(t))])); + end; + x.typ := t; + elsif (s^.form = Sym.fNil) and (t^.form in {Sym.fPtr, Sym.fProc, Sym.fError}) then + x.typ := t; + elsif (s^.form = Sym.fPtr) and (t^.form = Sym.fPtr) and t^.vol and not s^.vol + and Sym.same(s^.base, t^.base) then + x.typ := t; + elsif (s^.form = Sym.fArray) and (t^.form = Sym.fSlice) and Sym.same(s^.base, t^.base) then + try notReadOnly(x); + if x.vol then return Scan.markAt(x.pos, "can't make a slice through a volatile pointer"); end; + if x.odd then return Scan.markAt(x.pos, "can't make a slice of a field of a packed record"); end; + try address(x); + sliceOf(x, t, s^.len); + elsif (x.mode = mProc) and (t^.form # Sym.fProc) and (s^.base = nil) then + return Scan.markAt(x.pos, say1("{} is a procedure, and returns nothing", Diag.source(x.pos))); + elsif (x.mode = mProc) and (t^.form # Sym.fProc) then + return Scan.markHelp(x.pos, + say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t)), + say1("to call it, write {}()", Diag.source(x.pos))); + else + return mismatch(x, say2("can't use {} as {}", Sym.typeName(s), Sym.typeName(t))); + end; + return nil; +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. *) +proc coerceExact*(var x: Item; t: ^Sym.Type; help: []U8): ERROR; +var h: []U8; +begin + if widens(x.typ, t) then + h := help; + if LEN(h) = 0 then + h := say2("they don't mix here: write {}({})", Sym.typeName(t), Diag.source(x.pos)); + end; + return Scan.markHelp(x.pos, say2("expected {}, found {}", Sym.typeName(t), what(x)), h); + end; + return coerce(x, t); +end; + +(* dst := src. The address of dst, if it has to be computed, is on the + stack already, under src's. *) +proc assign*(var dst, src: Item): ERROR; +begin + try coerce(src, dst.typ); + if Sym.isScalar(dst.typ) then + try value(src); + Gen.popVar(adrOf(dst), scalarSize(dst.typ)); + else + if dst.vol or src.vol then return Scan.markAt(src.pos, "can't copy through a volatile pointer"); end; + if (src.mode = mVar) and (src.base = Gen.bReg) then try copyToTemp(src); end; (* a slice in registers *) + try address(src); + if dst.base = Gen.bStack then Gen.copyBlock(dst.typ^.size, dst.off); + else Gen.copyTo(adrOf(dst), dst.typ^.size); end; + end; + return nil; +end; + +(* t's name, ending in a zero byte, for Rt.fail *) +proc nameChunk(t: ^Sym.Type): INT; +var s: []U8; p: ^U8; n, c: INT; +begin + s := Sym.typeName(t); + n := LEN(s); + p := Scan.grab(n + 1); + COPY(p[0..n], s); + p[n] := 0; + c := Chunk.newChunk(Chunk.secRodata, -1, -1); + Chunk.setData(c, p, n + 1, 1); + return c; +end; + +(* Selectors *) + +proc deref*(var x: Item): ERROR; +var t: ^Sym.Type; +begin + t := x.typ; + if t^.form # Sym.fPtr then + return Scan.markAt(x.pos, say1("expected a pointer, found {}", Sym.typeName(t))); + end; + if t^.base = nil then + return Scan.markAt(x.pos, say1("{} points to a type never declared", Sym.typeName(t))); + end; + try value(x); + x.mode := mVar; x.base := Gen.bStack; x.off := 0; x.deref := true; + x.typ := t^.base; x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false; + return nil; +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). *) +proc field*(var x: Item; f: ^Sym.Obj): ERROR; +begin + if x.typ^.packd and (f^.typ^.align > 1) then + if x.vol then return Scan.markAt(x.pos, "a field of a packed record can't be volatile"); end; + x.odd := true; + end; + x.off := x.off + f^.val; + x.typ := f^.typ; + return nil; +end; + +proc indexPrep*(var x: Item): ERROR; +begin + nilTest(x); + if x.mode = mStr then try coerce(x, Sym.tBytes); end; + if (x.typ^.form = Sym.fPtr) and (x.typ^.base^.form = Sym.fArray) then + return Scan.markAt(x.pos, "a pointer to an array is indexed as p^[i]"); + end; + if x.typ^.form = Sym.fPtr then try value(x); + elsif not ((x.mode = mVar) and (x.typ^.form in {Sym.fArray, Sym.fSlice})) then + return Scan.markAt(x.pos, say1("expected an array, a slice or a pointer, found {}", what(x))); + end; + return nil; +end; + +(* The index on top, times the size of an element *) +proc scaleBy(s: I64); +begin + if s # 1 then + Gen.pushConst(Gen.kWord, s); + Gen.op(Scan.sTimes, Gen.kWord, 8, true); + end; +end; + +proc index*(var x, y: Item): ERROR; +var t: ^Sym.Type; s: I64; +begin + t := x.typ; + s := t^.base^.size; + if not Sym.isInt(y.typ) then + return Scan.markAt(y.pos, say1("an index is an integer, found {}", what(y))); + end; + if t^.form = Sym.fPtr then + try value(y); + scaleBy(s); + Gen.op(Scan.sPlus, Gen.kWord, 8, false); + x.mode := mVar; x.base := Gen.bStack; x.off := 0; + x.vol := t^.vol; x.isVar := true; x.odd := false; x.ro := false; + elsif (t^.form = Sym.fArray) and (y.mode = mConst) then + if (y.val < 0) or (y.val >= t^.len) then + return Scan.markAt(y.pos, Diag.say("index {} is out of range for a length of {}", [Fmt.int(y.val), Fmt.int(t^.len)])); + end; + x.off := x.off + y.val * s; + elsif t^.form = Sym.fArray then + try value(y); + if checks then Gen.checkIndex(t^.len, y.pos); end; + if x.base = Gen.bStack then scaleBy(s); Gen.op(Scan.sPlus, Gen.kWord, 8, false); + else Gen.indexArray(adrOf(x), s); x.off := 0; end; + x.base := Gen.bStack; + else + try value(y); + Gen.indexSlice(adrOf(x), s, checks, y.pos); + x.base := Gen.bStack; x.off := 0; x.isVar := true; x.vol := false; x.ro := false; + end; + x.typ := t^.base; + return nil; +end; + +proc sliceLo*(var lo: Item): ERROR; +begin + if not Sym.isInt(lo.typ) then + return Scan.markAt(lo.pos, say1("an index is an integer, found {}", what(lo))); + end; + return value(lo); +end; + +proc slice*(var x, lo, hi: Item): ERROR; +var t, st: ^Sym.Type; tmp: I64; +begin + t := x.typ; + if not Sym.isInt(hi.typ) then + return Scan.markAt(hi.pos, say1("an index is an integer, found {}", what(hi))); + end; + if x.vol then return Scan.markAt(x.pos, "can't make a slice through a volatile pointer"); end; + if x.odd then return Scan.markAt(x.pos, "can't make a slice of a field of a packed record"); end; + if t^.form = Sym.fArray then try notReadOnly(x); end; + try value(hi); + tmp := Gen.allocTemp(16, 8); + if t^.form = Sym.fPtr then Gen.slicePtr(t^.base^.size, tmp, checks, lo.pos); + else Gen.slice(adrOf(x), t^.form = Sym.fArray, t^.len, t^.base^.size, tmp, checks, lo.pos); end; + st := Sym.newType(Sym.fSlice, 16, 8); + st^.base := t^.base; + tempItem(x, st, tmp); + return nil; +end; + +(* Operators *) + +proc neg*(var x: Item): ERROR; +begin + if x.typ^.form = Sym.fReal then + if x.mode = mConst then x.val := x.val xor MinI64; + else try value(x); Gen.neg(Gen.kindOf(x.typ), 8, false); end; + elsif Sym.isInt(x.typ) then + if (x.mode = mConst) and (x.typ^.form = Sym.fConst) and (x.val = MinI64) then + return Scan.markAt(x.pos, "the constant is too big for I64"); + elsif x.mode = mConst then x.val := cut(-x.val, x.typ); + else try value(x); Gen.neg(Gen.kWord, intSize(x.typ), signed(x.typ)); end; + else return Scan.markAt(x.pos, say1("can't negate {}", Sym.typeName(x.typ))); end; + return nil; +end; + +proc notOp*(var x: Item): ERROR; +var L: INT; +begin + if Sym.isInt(x.typ) then + return Scan.markHelp(x.pos, say1("\"not\" needs a BOOL, found {}", what(x)), "the bits of an integer flip with ~"); + end; + if x.typ^.form # Sym.fBool then + return Scan.markAt(x.pos, say1("\"not\" needs a BOOL, found {}", what(x))); + end; + if x.mode = mConst then x.val := 1 - x.val; + elsif x.mode = mCond then + x.rel := negated(x.rel); + L := x.fj; x.fj := x.tj; x.tj := L; + else try value(x); Gen.notBool(); end; + return nil; +end; + +proc complement*(var x: Item): ERROR; +begin + if x.typ^.form = Sym.fBool then + return Scan.markHelp(x.pos, say1("\"~\" needs an integer, found {}", what(x)), "a BOOL is negated with not"); + end; + if not Sym.isInt(x.typ) then + return Scan.markAt(x.pos, say1("\"~\" needs an integer, found {}", what(x))); + end; + if x.mode = mConst then x.val := cut(~x.val, x.typ); + else try value(x); Gen.complement(intSize(x.typ), signed(x.typ)); end; + return nil; +end; + +(* Arrays, slices and strings, which = and # compare element by element *) +proc isSeq(t: ^Sym.Type): BOOL; +begin + return t^.form in {Sym.fStr, Sym.fArray, Sym.fSlice}; +end; + +proc elemOf(t: ^Sym.Type): ^Sym.Type; +begin + if t^.form = Sym.fStr then return Sym.tU8; end; + return t^.base; +end; + +(* An array, slice or string as a slice in a temporary, for comparing. *) +proc seqSlice(var x: Item): ERROR; +var t: ^Sym.Type; +begin + t := Sym.newType(Sym.fSlice, 16, 8); + t^.base := elemOf(x.typ); + if x.typ^.form = Sym.fSlice then + x.typ := t; try copyToTemp(x); + elsif x.mode = mStr then + try address(x); sliceOf(x, t, x.val); + else + if x.vol then return Scan.markAt(x.pos, "can't compare through a volatile pointer"); end; + try address(x); sliceOf(x, t, x.typ^.len); + end; + return nil; +end; + +(* x, a BOOL, as a condition: a value compared with 0 if it isn't one *) +proc makeCond(var x: Item): ERROR; +begin + if x.mode = mCond then return nil; end; + try value(x); + Gen.pushConst(Gen.kWord, 0); + x.mode := mCond; + x.rel := Scan.sNeq; + x.relSigned := false; + x.fj := Gen.NoLabel; + x.tj := Gen.NoLabel; + return nil; +end; + +proc op1*(op: Scan.Sym; var x: Item; var L: INT): ERROR; +begin + L := Gen.NoLabel; + if ((op = Scan.sAnd) or (op = Scan.sOr)) and (x.typ^.form = Sym.fBool) then + if x.mode = mConst then return nil; end; (* folded by op2 *) + try makeCond(x); + if op = Scan.sAnd then + Gen.jumpOut(negated(x.rel), x.relSigned, x.fj); + Gen.fix(x.tj); + x.tj := Gen.NoLabel; + else + Gen.jumpOut(x.rel, x.relSigned, x.tj); + Gen.fix(x.fj); + x.fj := Gen.NoLabel; + end; + elsif ((op = Scan.sEql) or (op = Scan.sNeq)) and isSeq(x.typ) then + try seqSlice(x); + elsif (op = Scan.sPlus) and (x.mode = mStr) then + (* two string constants to be joined: nothing to compute *) + elsif (op = Scan.sPlus) and isSeq(x.typ) then + return Scan.markHelp(x.pos, say1("+ doesn't join {}", what(x)), "strings are joined in a Buf: Buf.str(b, s)"); + elsif x.mode in {mType, mBuiltin, mNone, mCase, mStr} then + return notValue(x); + elsif x.mode # mConst then + try value(x); + end; + return nil; +end; + +proc log2(v: I64): INT; +var n: INT; +begin + n := 0; + while (v > 1) and ((v & 1) = 0) do v := v shr 1; INC(n); end; + if v # 1 then n := -1; end; + return n; +end; + +(* Whether a op b, for + - *, overflows an I64: an untyped constant + doesn't wrap, it is an error (report section 4). *) +proc overflows(op: Scan.Sym; a, b: I64): BOOL; +begin + match op of + | sPlus: return ((b > 0) and (a > MaxI64 - b)) or ((b < 0) and (a < MinI64 - b)); + | sMinus: return ((b < 0) and (a > MaxI64 + b)) or ((b > 0) and (a < MinI64 + b)); + | sTimes: + if (a = 0) or (b = 0) then return false; end; + if a = -1 then return b = MinI64; end; + if b = -1 then return a = MinI64; end; + return (a * b) div b # a; + | else: return false; + end; +end; + +(* A type's width in bits; an untyped constant's is an I64's *) +proc bits(t: ^Sym.Type): I64; +begin + return t^.size * 8; +end; + +proc foldInt(op: Scan.Sym; a, b: I64; t: ^Sym.Type; p: Diag.Pos): (I64, ERROR); +var u: BOOL; +begin + u := (t^.form = Sym.fInt) and not t^.signed; + if (t^.form = Sym.fConst) and overflows(op, a, b) then + return 0, Scan.markAt(p, "the constant is too big for I64"); + end; + match op of + | sPlus: return a + b, nil; + | sMinus: return a - b, nil; + | sTimes: return a * b, nil; + | sDiv, sMod: + if b = 0 then return 0, Scan.markAt(p, "division by zero"); end; + if u then + if op = Scan.sDiv then return I64(U64(a) div U64(b)), nil; end; + return I64(U64(a) mod U64(b)), nil; + end; + if (b = -1) and (a = I64(-1) shl (bits(t) - 1)) then return 0, Scan.markAt(p, "division overflows"); end; + if op = Scan.sDiv then return a div b, nil; end; + return a mod b, nil; + | sAmp: return a & b, nil; + | sBar: return a | b, nil; + | sXor: return a xor b, nil; + | sShl: return a shl (b & (bits(t) - 1)), nil; + | sShr: + if u then return I64(U64(a) shr (b & (bits(t) - 1))), nil; end; + return a shr (b & (bits(t) - 1)), nil; + | sEql: return bit(a = b), nil; + | sNeq: return bit(a # b), nil; + | sLss: + if u then return bit(U64(a) < U64(b)), nil; end; + return bit(a < b), nil; + | sLeq: + if u then return bit(U64(a) <= U64(b)), nil; end; + return bit(a <= b), nil; + | sGtr: + if u then return bit(U64(a) > U64(b)), nil; end; + return bit(a > b), nil; + | sGeq: + if u then return bit(U64(a) >= U64(b)), nil; end; + return bit(a >= b), nil; + | else: return 0, Scan.markAt(p, "bad operator"); + end; +end; + +(* Folds x op y, of the real type t: an F32 rounded at each step, as + the machine would. *) +proc foldReal(op: Scan.Sym; x, y: Item; t: ^Sym.Type; var r: Item): BOOL; +var a, b: F64; ok: BOOL; +begin + a := realOf(x); b := realOf(y); + ok := true; + match 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, Sym.tBool, bit(a = b)); + | sNeq: makeConst(r, Sym.tBool, bit(a # b)); + | sLss: makeConst(r, Sym.tBool, bit(a < b)); + | sLeq: makeConst(r, Sym.tBool, bit(a <= b)); + | sGtr: makeConst(r, Sym.tBool, bit(a > b)); + | sGeq: makeConst(r, Sym.tBool, bit(a >= b)); + | else: ok := false; + end; + if r.typ^.form = Sym.fReal then realTo(r, t); end; + return ok; +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 *) +proc wrongLogic(op: Scan.Sym; var x: Item): ERROR; +var bitsOf: []U8; +begin + bitsOf := "the bits of integers take "; + if (op = Scan.sAnd) and Sym.isInt(x.typ) then + return Scan.markHelp(x.pos, say1("\"and\" needs BOOLs, found {}", what(x)), say1("{}&", bitsOf)); + elsif (op = Scan.sOr) and Sym.isInt(x.typ) then + return Scan.markHelp(x.pos, say1("\"or\" needs BOOLs, found {}", what(x)), say1("{}|", bitsOf)); + elsif op = Scan.sAmp then + return Scan.markHelp(x.pos, say1("\"&\" needs integers, found {}", what(x)), "BOOLs take and"); + elsif op = Scan.sBar then + return Scan.markHelp(x.pos, say1("\"|\" needs integers, found {}", what(x)), "BOOLs take or"); + elsif op = Scan.sXor then + return Scan.markHelp(x.pos, say1("\"xor\" needs integers, found {}", what(x)), "BOOLs that differ are #"); + end; + return Scan.markAt(x.pos, say2("{} needs BOOLs, found {}", Scan.symText(op), what(x))); +end; + +(* x + y, of two string constants: one string, in a chunk of its own + (report section 4) *) +proc joinStr(var x, y: Item): ERROR; +var p: ^U8; c, xs, ys, xl, yl: INT; +begin + if y.mode # mStr then + return Scan.markAt(y.pos, say1("\"+\" joins two strings, found {}", what(y))); + end; + xs := Chunk.chunks[x.chunk].start; + ys := Chunk.chunks[y.chunk].start; + xl := INT(x.val); + yl := INT(y.val); + p := Scan.grab(xl + yl + 1); + COPY(p[0..xl], Chunk.rodata[xs..xs + xl]); + COPY(p[xl..xl + yl + 1], Chunk.rodata[ys..ys + yl + 1]); + c := Chunk.newChunk(Chunk.secRodata, -1, -1); + Chunk.setData(c, p, xl + yl + 1, 1); + x.chunk := c; + x.val := x.val + y.val; + return nil; +end; + +(* A set's operations, as operations on its bits: the two values on top *) +proc setOp(op: Scan.Sym); +begin + match op of + | sPlus: Gen.op(Scan.sBar, Gen.kWord, 8, false); + | sTimes: Gen.op(Scan.sAmp, Gen.kWord, 8, false); + | sMinus: Gen.complement(8, false); Gen.op(Scan.sAmp, Gen.kWord, 8, false); + | sLeq, sGeq: + (* x <= y has no bit of x outside y *) + if op = Scan.sGeq then Gen.swap(); end; + Gen.complement(8, false); + Gen.op(Scan.sAmp, Gen.kWord, 8, false); + Gen.pushConst(Gen.kWord, 0); + Gen.compare(Scan.sEql, Gen.kWord, false); + | sIn: + Gen.swap(); + Gen.op(Scan.sShr, Gen.kWord, 8, false); + Gen.pushConst(Gen.kWord, 1); + Gen.op(Scan.sAmp, Gen.kWord, 8, false); + | else: Gen.compare(op, Gen.kWord, false); + end; +end; + +(* The operators the arithmetic of integers, of reals and of sets + stand for, and the comparisons *) +proc intOp(op: Scan.Sym): BOOL; +begin + return isRel(op) or oneOf(op, [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod, + Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr]); +end; + +proc doesntApply(op: Scan.Sym; x, y: Item; t: ^Sym.Type): ERROR; +begin + return Scan.markAt(Diag.join(x.pos, y.pos), say2("{} doesn't apply to {}", Scan.symText(op), Sym.typeName(t))); +end; + +proc op2*(op: Scan.Sym; var x, y: Item; _L: INT): ERROR; +var xt, yt, t, e: ^Sym.Type; r: Item; scale: INT; isPtr: BOOL; a, b, v: I64; +begin + xt := x.typ; yt := y.typ; + if y.mode in {mType, mBuiltin, mNone, mCase} then return notValue(y); end; + if (op = Scan.sPlus) and (x.mode = mStr) then return joinStr(x, y); end; + + if (op = Scan.sAnd) or (op = Scan.sOr) then + if xt^.form # Sym.fBool then return wrongLogic(op, x); end; + if yt^.form # Sym.fBool then return wrongLogic(op, y); end; + if (x.mode = mConst) and (y.mode = mConst) then + if op = Scan.sAnd then x.val := x.val & y.val; else x.val := x.val | y.val; end; + elsif x.mode = mConst then + (* true and y, false or y: y; else x, y computed and dropped *) + if (x.val = 1) = (op = Scan.sAnd) then x := y; + else try discard(y); end; + else + try makeCond(y); + if op = Scan.sAnd then x.fj := Gen.joinJumps(x.fj, y.fj); x.tj := y.tj; + else x.tj := Gen.joinJumps(x.tj, y.tj); x.fj := y.fj; end; + x.rel := y.rel; + x.relSigned := y.relSigned; + end; + return nil; + end; + + if oneOf(op, [Scan.sAmp, Scan.sBar, Scan.sXor]) and (xt^.form = Sym.fBool) then return wrongLogic(op, x); end; + if oneOf(op, [Scan.sAmp, Scan.sBar, Scan.sXor]) and (yt^.form = Sym.fBool) then return wrongLogic(op, y); end; + + (* 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 = Scan.sEql) or (op = Scan.sNeq)) and isSeq(xt) then + e := elemOf(xt); + if not isSeq(yt) then + return Scan.markAt(Diag.join(x.pos, y.pos), say1("can't compare an array with {}", Sym.typeName(yt))); + elsif not Sym.same(e, elemOf(yt)) then + return Scan.markAt(Diag.join(x.pos, y.pos), + say2("can't compare an array of {} with one of {}", Sym.typeName(e), Sym.typeName(elemOf(yt)))); + end; + if e^.form = Sym.fReal then + return Scan.markHelp(Diag.join(x.pos, y.pos), + say1("can't compare arrays of reals with {}", Scan.symText(op)), + "-0.0 = 0.0 and a NaN equals nothing, though their bytes say otherwise: write a loop"); + elsif not (e^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet, Sym.fPtr}) then + return Scan.markHelp(Diag.join(x.pos, y.pos), + say2("can't compare arrays of {} with {}", Sym.typeName(e), Scan.symText(op)), "write a loop"); + end; + try seqSlice(y); + Gen.compareSeq(x.off, y.off, log2(e^.size), op = Scan.sEql); + makeConst(x, Sym.tBool, 0); + x.mode := mStack; + return nil; + end; + + (* the type of the result, and the checks *) + t := nil; scale := 1; isPtr := false; + if Sym.isInt(xt) and Sym.isInt(yt) then + if op = Scan.sSlash then + return Scan.markHelp(Diag.join(x.pos, y.pos), "\"/\" divides reals, not integers", + say2("to divide integers, write {} div {}", Diag.source(x.pos), Diag.source(y.pos))); + end; + if (op = Scan.sShl) or (op = Scan.sShr) then + if xt^.form = Sym.fConst then t := Sym.tConst; else t := xt; end; + elsif (xt^.form = Sym.fConst) and (yt^.form = Sym.fConst) then t := Sym.tConst; + elsif xt^.form = Sym.fConst then + if (x.mode = mConst) and not Sym.fits(x.val, yt) then + return Scan.markAt(x.pos, Diag.say("{} doesn't fit {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(yt))])); + end; + t := yt; + elsif yt^.form = Sym.fConst then + if (y.mode = mConst) and not Sym.fits(y.val, xt) then + return Scan.markAt(y.pos, Diag.say("{} doesn't fit {}", [Fmt.int(y.val), Fmt.str(Sym.typeName(xt))])); + end; + t := xt; + elsif Sym.same(xt, yt) then t := xt; + else return mismatchOps(x, y, xt, yt); end; + if not intOp(op) then return doesntApply(op, x, y, t); end; + elsif (xt^.form = Sym.fReal) and (yt^.form = Sym.fReal) then + if not (isRel(op) or oneOf(op, [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sSlash])) then + return doesntApply(op, x, y, xt); + end; + if xt = Sym.tRConst then t := yt; + elsif (yt = Sym.tRConst) or Sym.same(xt, yt) then t := xt; + else return mismatchOps(x, y, xt, yt); end; + if (x.mode = mConst) and (x.typ # t) then realTo(x, t); end; + if (y.mode = mConst) and (y.typ # t) then realTo(y, t); end; + elsif (xt^.form = Sym.fBool) and (yt^.form = Sym.fBool) then + if (op # Scan.sEql) and (op # Scan.sNeq) then return doesntApply(op, x, y, xt); end; + t := Sym.tBool; + elsif (xt^.form = Sym.fPtr) and Sym.isInt(yt) and ((op = Scan.sPlus) or (op = Scan.sMinus)) then + t := xt; scale := INT(xt^.base^.size); isPtr := true; + if y.mode = mConst then y.typ := Sym.tInt; end; + elsif (xt^.form = Sym.fPtr) and (yt^.form = Sym.fPtr) and (op = Scan.sMinus) then + if not Sym.same(xt, yt) then return mismatchOps(x, y, xt, yt); end; + t := Sym.tInt; scale := INT(xt^.base^.size); isPtr := true; + elsif (xt^.form in {Sym.fPtr, Sym.fProc, Sym.fNil, Sym.fError}) and (yt^.form in {Sym.fPtr, Sym.fProc, Sym.fNil, Sym.fError}) then + if not isRel(op) then return doesntApply(op, x, y, xt); end; + if (xt^.form in {Sym.fProc, Sym.fError}) or (yt^.form in {Sym.fProc, Sym.fError}) then + if (op # Scan.sEql) and (op # Scan.sNeq) then return doesntApply(op, x, y, xt); end; + end; + if (xt^.form # Sym.fNil) and (yt^.form # Sym.fNil) and not Sym.same(xt, yt) then + if not ((xt^.form = Sym.fPtr) and (yt^.form = Sym.fPtr) and Sym.same(xt^.base, yt^.base)) then + return mismatchOps(x, y, xt, yt); + end; + end; + t := Sym.tU64; + elsif (xt^.form = Sym.fEnum) and Sym.same(xt, yt) then + if not isRel(op) then return doesntApply(op, x, y, xt); end; + t := xt; + elsif (xt^.form = Sym.fSet) and Sym.same(xt, yt) then + if not oneOf(op, [Scan.sPlus, Scan.sTimes, Scan.sMinus, Scan.sEql, Scan.sNeq, Scan.sLeq, Scan.sGeq]) then + return doesntApply(op, x, y, xt); + end; + t := xt; + elsif (op = Scan.sIn) and (yt^.form = Sym.fSet) and Sym.same(xt, yt^.base) then + t := yt; + else + return mismatchOps(x, y, xt, yt); + end; + + (* constants *) + if (x.mode = mConst) and (y.mode = mConst) and not isPtr then + if t^.form = Sym.fReal then + if not foldReal(op, x, y, t, r) then return doesntApply(op, x, y, xt); end; + x := r; + elsif t^.form = Sym.fSet then + a := x.val; b := y.val; + match op of + | sPlus: makeConst(x, t, a | b); + | sTimes: makeConst(x, t, a & b); + | sMinus: makeConst(x, t, a & ~b); + | sIn: makeConst(x, Sym.tBool, (b shr a) & 1); + | sLeq: makeConst(x, Sym.tBool, bit((a & ~b) = 0)); + | sGeq: makeConst(x, Sym.tBool, bit((b & ~a) = 0)); + | else: makeConst(x, Sym.tBool, bit((a = b) = (op = Scan.sEql))); + end; + elsif isRel(op) then + v := try foldInt(op, x.val, y.val, t, Diag.join(x.pos, y.pos)); + makeConst(x, Sym.tBool, v); + else + v := try foldInt(op, x.val, y.val, t, Diag.join(x.pos, y.pos)); + makeConst(x, t, cut(v, t)); + end; + return nil; + 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] *) + try value(y); + if x.mode = mConst then + try value(x); + if not oneOf(op, [Scan.sPlus, Scan.sTimes, Scan.sAmp, Scan.sBar, Scan.sXor]) or isPtr then Gen.swap(); end; + end; + + if t^.form = Sym.fReal then + if isRel(op) then Gen.compare(op, Gen.kindOf(t), false); + else Gen.op(op, Gen.kindOf(t), 8, false); end; + elsif t^.form = Sym.fSet then + setOp(op); + elsif isRel(op) then + x.mode := mCond; + x.rel := op; + x.relSigned := signed(t); + x.fj := Gen.NoLabel; + x.tj := Gen.NoLabel; + x.typ := Sym.tBool; + return nil; + elsif isPtr then + if t # Sym.tInt then scaleBy(scale); end; + Gen.op(op, Gen.kWord, 8, false); + if (t = Sym.tInt) and (scale # 1) then + Gen.pushConst(Gen.kWord, scale); + Gen.op(Scan.sDiv, Gen.kWord, 8, true); + end; + else + Gen.op(op, Gen.kindOf(t), intSize(t), signed(t)); + end; + x.mode := mStack; + if isRel(op) or (op = Scan.sIn) then x.typ := Sym.tBool; else x.typ := t; end; + return nil; +end; + +(* INT and UINT, the integers as big as an address, through which + integers and pointers convert (report section 6.7) *) +proc isWord*(t: ^Sym.Type): BOOL; +begin + return Sym.same(t, Sym.tInt) or Sym.same(t, Sym.tUInt); +end; + +proc convert*(var x: Item; t: ^Sym.Type): ERROR; +var s: ^Sym.Type; r: F64; +begin + s := x.typ; + if x.mode in {mType, mBuiltin, mNone, mCase, mStr} then + if x.mode = mStr then return Scan.markAt(x.pos, "can't convert a string"); end; + return notValue(x); + end; + if Sym.same(s, t) then return nil; end; + if (Sym.isInt(s) or (s^.form in {Sym.fEnum, Sym.fSet})) and (t^.form = Sym.fInt) then + if x.mode = mConst then x.val := cut(x.val, t); + else try value(x); Gen.narrow(INT(t^.size), t^.signed); end; + elsif Sym.isInt(s) and (t^.form = Sym.fEnum) then + if x.mode = mConst then + if (x.val < 0) or (x.val >= t^.len) then + return Scan.markAt(x.pos, Diag.say("{} isn't a position of {}", [Fmt.int(x.val), Fmt.str(Sym.typeName(t))])); + end; + else try value(x); Gen.checkEnum(t^.len, nameChunk(t), x.pos); end; + elsif Sym.isInt(s) and (t^.form = Sym.fSet) then + if x.mode = mConst then + if t^.len < 64 then x.val := x.val & ((I64(1) shl t^.len) - 1); end; + else + try value(x); + if t^.len < 64 then + Gen.pushConst(Gen.kWord, (I64(1) shl t^.len) - 1); + Gen.op(Scan.sAmp, Gen.kWord, 8, false); + end; + end; + elsif Sym.isInt(s) and (t^.form = Sym.fReal) then + if x.mode = mConst then + if (s^.form = Sym.fInt) and not s^.signed then r := F64(U64(x.val)); else r := F64(x.val); end; + makeReal(x, r); + realTo(x, t); + else + try value(x); + Gen.intToReal(Gen.kindOf(t), (s^.form = Sym.fInt) and not s^.signed and (s^.size = 8)); + end; + elsif (s^.form = Sym.fReal) and (t^.form = Sym.fReal) then + (* F32 to F64, F64 to F32, or a real constant to either *) + if x.mode = mConst then realTo(x, t); + else try value(x); Gen.realToReal(Gen.kindOf(s)); end; + elsif (s^.form = Sym.fReal) and (t^.form = Sym.fInt) then + if x.mode = mConst then + 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(MinI64, t); + else x.val := cut(I64(r), t); end; + else + try value(x); Gen.realToInt(Gen.kindOf(s)); Gen.narrow(INT(t^.size), t^.signed); + end; + elsif (isWord(s) or (s^.form in {Sym.fConst, Sym.fPtr, Sym.fProc, Sym.fNil})) and (t^.form in {Sym.fPtr, Sym.fProc}) then + if x.mode # mConst then try value(x); end; + elsif (s^.form in {Sym.fPtr, Sym.fProc}) and isWord(t) then + try value(x); + else + return Scan.markAt(x.pos, say2("can't convert {} to {}", Sym.typeName(s), Sym.typeName(t))); + end; + x.typ := t; + return nil; +end; + +(* Calls *) + +proc beginCall*(var c: Gen.CallInfo; var x: Item): ERROR; +begin + if x.mode = mProc then + c.sig := x.obj^.typ; c.chunk := x.obj^.chunk; c.target := 0; + c.obj := x.obj; c.ext := x.obj^.ext; + else + c.obj := nil; c.ext := false; + if x.typ^.form # Sym.fProc then + return Scan.markAt(x.pos, say1("expected a procedure, found {}", what(x))); + end; + c.sig := x.typ; c.chunk := -1; + c.target := try toSlot(x); + end; + c.param := c.sig^.fields; + c.n := 0; + return nil; +end; + +(* Too many arguments or too few, at p *) +proc wrongCount(var c: Gen.CallInfo; p: Diag.Pos; text: []U8): ERROR; +begin + if c.obj = nil then return Scan.markAt(p, text); end; + Diag.error(p, Diag.say("{}: {} takes {}", [Fmt.str(text), Fmt.str(Scan.nameOf(c.obj^.name)), Fmt.int(c.sig^.len)])); + if c.obj^.home # nil then Diag.note(c.obj^.pos, "the signature is here"); end; + return Scan.Failed; +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. *) +proc pushWords(var x: Item): ERROR; +var adr: Gen.Adr; f: ^Sym.Obj; +begin + if x.mode = mWords then return nil; end; (* 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 {Gen.bFrame, Gen.bGlobal, Gen.bSlot, Gen.bReg}) then + try copyToTemp(x); + end; + adr := adrOf(x); + if x.typ^.form = Sym.fSlice then + Gen.pushVar(adr, 8, false, Gen.kWord); + INC(adr.off, 8); + Gen.pushVar(adr, 8, false, Gen.kWord); + else + f := x.typ^.fields; + while f # nil do + adr.off := adrOf(x).off + f^.val; + Gen.pushVar(adr, scalarSize(f^.typ), signed(f^.typ), Gen.kindOf(f^.typ)); + f := f^.next; + end; + end; + return nil; +end; + +proc passArg*(var c: Gen.CallInfo; var a: Item): ERROR; +var p: ^Sym.Obj; +begin + p := c.param; + if c.n >= LEN(c.isF) - 1 then return Scan.markAt(a.pos, "too many arguments"); end; + if p = nil then + (* 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 return wrongCount(c, a.pos, "too many arguments"); end; + if a.mode = mStr then try coerce(a, Sym.tPtrU8); + elsif a.typ^.form = Sym.fConst then try coerce(a, Sym.tInt); + elsif a.typ = Sym.tRConst then try coerce(a, Sym.tReal); + elsif isF32(a.typ) then return Scan.markAt(a.pos, "an F32 goes to ... as F64(x)"); + elsif not Sym.isScalar(a.typ) then return Scan.markAt(a.pos, "only a single value goes to ..."); end; + c.isF[c.n] := a.typ^.form = Sym.fReal; + c.pair[c.n] := false; + try value(a); + INC(c.n); + return nil; + end; + c.isF[c.n] := (p^.typ^.form = Sym.fReal) and not p^.isVar; + passing := p; + passingAt := a.pos; + if p^.isVar then + try notReadOnly(a); + if (a.mode # mVar) or not a.isVar then return Scan.markAt(a.pos, "a var parameter needs a variable"); end; + if a.odd then return Scan.markAt(a.pos, "a field of a packed record can't be a var parameter"); end; + if not Sym.same(a.typ, p^.typ) then + return mismatch(a, say2("a var parameter needs exactly {}, found {}", Sym.typeName(p^.typ), what(a))); + end; + if a.vol then return Scan.markAt(a.pos, "can't pass through a volatile pointer to a var parameter"); end; + try address(a); + elsif p^.typ^.form = Sym.fSlice then + try coerce(a, p^.typ); + try pushWords(a); + c.pair[c.n] := true; + INC(c.n); + c.isF[c.n] := false; + elsif Sym.isAggregate(p^.typ) then + try coerce(a, p^.typ); + if a.isVar or a.vol or (a.base # Gen.bFrame) then try copyToTemp(a); end; + try address(a); + else + try coerce(a, p^.typ); + try value(a); + end; + c.pair[c.n] := false; + INC(c.n); + c.param := p^.next; + return nil; +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. *) +proc endCall*(var c: Gen.CallInfo; var x: Item): ERROR; +var res: ^Sym.Type; +begin + if c.param # nil then try wrongCount(c, Scan.tokPos(), "too few arguments"); end; + Gen.call(c); + res := c.sig^.base; + x := {}; + if res = nil then + x.mode := mNone; x.typ := Sym.tNone; x.obj := c.obj; + elsif c.ret # 0 then + tempItem(x, res, c.ret); + else + x.mode := mStack; x.typ := res; + if res^.tuple then x.mode := mWords; end; + end; + return nil; +end; + +(* Variants *) + +(* A temporary of type t, all zero: for variants and record literals. *) +proc zeroTemp*(var x: Item; t: ^Sym.Type); +var tmp: I64; +begin + tmp := Gen.allocTemp(t^.size, t^.align); + Gen.zeroVar(frameAdr(tmp), t^.size); + tempItem(x, t, tmp); +end; + +proc construct*(var x: Item; c: ^Sym.Obj); +begin + zeroTemp(x, c^.typ); + Gen.pushConst(Gen.kWord, c^.val); + Gen.popVar(frameAdr(x.off), 8); +end; + +proc setField*(x: Item; f: ^Sym.Obj; var a: Item): ERROR; +begin + try coerce(a, f^.typ); + if Sym.isScalar(f^.typ) then + try value(a); + Gen.popVar(frameAdr(x.off + f^.val), scalarSize(f^.typ)); + else + if a.vol then return Scan.markAt(a.pos, "can't copy through a volatile pointer"); end; + try address(a); + Gen.copyTo(frameAdr(x.off + f^.val), f^.typ^.size); + end; + return nil; +end; + +(* The slot match tests: a variant's address, or an enumeration's or an + integer's value. *) +proc matchBegin*(var x: Item): (I64, ERROR); +var p: I64; +begin + if x.typ^.form in {Sym.fEnum, Sym.fInt} then return toSlot(x); end; + if (x.mode # mVar) or (x.typ^.form # Sym.fVariant) then + return 0, Scan.markAt(x.pos, say1("match needs a variant, an enumeration or an integer, found {}", what(x))); + end; + if x.ro then try copyToTemp(x); end; (* its arms' names stand for a copy's fields *) + try address(x); + p := Gen.allocTemp(8, 8); + Gen.popVar(frameAdr(p), 8); + return p, nil; +end; + +(* To L unless the tag of the variant whose address is in slot p is tag *) +proc matchTag*(p: I64; tag: I64; var L: INT); +var a: Gen.Adr; +begin + Gen.pushVar(frameAdr(p), 8, false, Gen.kWord); + a.base := Gen.bStack; a.chunk := -1; a.off := 0; a.hi := 0; + Gen.pushVar(a, 8, false, Gen.kWord); + Gen.pushConst(Gen.kWord, tag); + Gen.jumpCmp(Scan.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. *) +proc matchRange*(p, lo, hi: I64; var body: INT); +begin + Gen.pushVar(frameAdr(p), 8, false, Gen.kWord); + if lo = hi then + Gen.pushConst(Gen.kWord, lo); + Gen.jumpCmp(Scan.sEql, false, body); + return; + end; + if lo # 0 then + Gen.pushConst(Gen.kWord, lo); + Gen.op(Scan.sMinus, Gen.kWord, 8, false); + end; + Gen.pushConst(Gen.kWord, hi - lo); + Gen.jumpCmp(Scan.sLeq, false, body); +end; + +(* A for loop's variable o, stepped by step, wrapping as its type does *) +proc forStep*(o: ^Sym.Obj; step: I64): ERROR; +var v, w: Item; +begin + try makeItem(v, o); + if v.base = Gen.bReg then + (* a variable in a register is stepped in it *) + Gen.pushConst(Gen.kWord, step); + Gen.incDecReg(v.chunk, intSize(o^.typ), signed(o^.typ), false); + return nil; + end; + try makeItem(w, o); + try value(w); + Gen.pushConst(Gen.kWord, step); + Gen.op(Scan.sPlus, Gen.kWord, intSize(o^.typ), signed(o^.typ)); + return 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 *) +proc forCmp*(o: ^Sym.Obj; lim: Item; op: Scan.Sym; var L: INT): ERROR; +var v, b: Item; +begin + try makeItem(v, o); + try value(v); + b := lim; + try value(b); + Gen.jumpCmp(op, o^.typ^.signed, L); + return nil; +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 chosen 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. *) +proc forNext*(o: ^Sym.Obj; lim: Item; step: I64; var exitL: INT; top, body: INT): ERROR; +var v, b: Item; L, pastL: INT; up: BOOL; before, past, within: Scan.Sym; a: I64; +begin + up := step > 0; + (* by a negative step, by a positive *) + if up then before := Scan.sLss; past := Scan.sGtr; within := Scan.sLeq; + else before := Scan.sGtr; past := Scan.sLss; within := Scan.sGeq; end; + a := step; + if a < 0 then a := -a; end; + L := Gen.NoLabel; + pastL := Gen.NoLabel; + if a = 1 then + try forCmp(o, lim, before, L); + Gen.fixTo(L, top); + try forCmp(o, lim, Scan.sEql, exitL); + else + try forCmp(o, lim, past, pastL); + try makeItem(v, o); + b := lim; + if up then try value(b); try value(v); + else try value(v); try value(b); end; + Gen.op(Scan.sMinus, Gen.kWord, 8, false); + Gen.pushConst(Gen.kWord, a); + Gen.jumpCmp(Scan.sGeq, false, L); + Gen.fixTo(L, top); + Gen.jump(exitL); + end; + Gen.fix(pastL); + try forStep(o, step); + L := Gen.NoLabel; + try forCmp(o, lim, within, L); + Gen.fixTo(L, body); + return nil; +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. *) +proc condJump*(var x: Item; var L: INT): ERROR; +begin + if x.typ^.form # Sym.fBool then + return Scan.markAt(x.pos, say1("a condition is a BOOL, found {}", what(x))); + end; + if x.mode = mCond then + Gen.jumpCmp(negated(x.rel), x.relSigned, L); + L := Gen.joinJumps(L, x.fj); + Gen.fix(x.tj); + return nil; + end; + try value(x); + Gen.jumpIf(L, false); + return nil; +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 *) +proc condJumpTrue*(var x: Item; var L: INT): ERROR; +begin + if x.typ^.form # Sym.fBool then + return Scan.markAt(x.pos, say1("a condition is a BOOL, found {}", what(x))); + end; + if x.mode = mCond then + Gen.jumpCmp(x.rel, x.relSigned, L); + L := Gen.joinJumps(L, x.tj); + Gen.fix(x.fj); + return nil; + end; + try value(x); + Gen.jumpIf(L, true); + return nil; +end; + +(* Procedures *) + +proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj); +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 *) +proc returnValue*(var x: Item): ERROR; +begin + if result = nil then return Scan.markAt(x.pos, "this procedure returns nothing"); end; + try coerce(x, result); + if Sym.inTwoRegs(result) then try pushWords(x); + elsif Sym.isAggregate(result) then + if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end; + try address(x); + Gen.copyResult(0, result^.size); + else try value(x); end; + return nil; +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. *) +proc returnField*(f: ^Sym.Obj; var x: Item): ERROR; +begin + try coerce(x, f^.typ); + if Sym.inTwoRegs(result) then try value(x); + elsif Sym.isScalar(f^.typ) then + try value(x); + Gen.resultTo(f^.val, scalarSize(f^.typ)); + else + if x.vol then return Scan.markAt(x.pos, "can't copy through a volatile pointer"); end; + try address(x); + Gen.copyResult(f^.val, f^.typ^.size); + end; + return nil; +end; + +(* Several results at once, the call's that return f(x) passes on. *) +proc returnAll*(var x: Item): ERROR; +begin + if Sym.inTwoRegs(result) then try pushWords(x); + else + try address(x); + Gen.copyResult(0, result^.size); + end; + return nil; +end; + +proc returnNone*: ERROR; +begin + if result # nil then + return Scan.mark(say1("return needs a result of {}", Sym.typeName(result))); + end; + Gen.returnJump(); + return nil; +end; + +(* Keeps a variable's address in a frame slot, rather than on the stack, + while other code runs. *) +proc pin*(var x: Item): ERROR; +var s: I64; +begin + if (x.mode = mVar) and (x.base = Gen.bStack) then + try address(x); + s := Gen.allocTemp(8, 8); + Gen.popVar(frameAdr(s), 8); + x.base := Gen.bSlot; + x.chunk := INT(s); + end; + return nil; +end; + +(* INC(v, k) or DEC: v's address is on the stack, from address. *) +proc incDec*(var v, k: Item; dec: BOOL): ERROR; +begin + try coerceExact(k, v.typ, ""); + try value(k); + if v.base = Gen.bReg then Gen.incDecReg(v.chunk, scalarSize(v.typ), v.typ^.signed, dec); + else Gen.incDec(scalarSize(v.typ), v.typ^.signed, dec); end; + return nil; +end; + +(* COPY(d, s): d, an array variable or a slice, as a slice in the frame, + before s is read *) +proc copyDest*(var d: Item): ERROR; +begin + if not isSeq(d.typ) or (d.mode = mStr) or ((d.typ^.form = Sym.fArray) and ((d.mode # mVar) or not d.isVar)) then + return Scan.markAt(d.pos, say1("COPY copies into an array variable or a slice, found {}", what(d))); + end; + if d.typ^.form = Sym.fArray then try notReadOnly(d); end; + return seqSlice(d); +end; + +(* ... and the elements of s copied to its start *) +proc copyFrom*(var d, s: Item): ERROR; +begin + if not isSeq(s.typ) or not Sym.same(elemOf(s.typ), d.typ^.base) then + return Scan.markAt(s.pos, say2("COPY copies elements of {}, found {}", Sym.typeName(d.typ^.base), what(s))); + end; + try seqSlice(s); + Gen.copySlice(d.off, s.off, d.typ^.base^.size, checks, s.pos); + return nil; +end; + +(* An error is the address of its length, followed by its message. *) +proc errorChunk*(var x: Item; home, name: INT): (INT, ERROR); +var c, xs, xl: INT; p: ^U8; q: ^I64; +begin + if x.mode # mStr then return 0, Scan.markAt(x.pos, "an error is made from a string"); end; + xl := INT(x.val); + p := Scan.grab(xl + 8); + q := ^I64(p); + q^ := x.val; + xs := Chunk.chunks[x.chunk].start; + COPY(p[8..8 + xl], Chunk.rodata[xs..xs + xl]); + c := Chunk.newChunk(Chunk.secRodata, home, name); + Chunk.setData(c, p, xl + 8, 8); + return c, nil; +end; + +proc msg*(var x: Item): ERROR; +var s: I64; +begin + try coerce(x, Sym.tError); + try value(x); + s := Gen.allocTemp(16, 8); + Gen.errorText(s); + tempItem(x, Sym.tBytes, s); + return nil; +end; + +end Item. diff --git a/src/Link.raz b/src/Link.raz new file mode 100644 index 0000000..852dce6 --- /dev/null +++ b/src/Link.raz @@ -0,0 +1,380 @@ +(* Link: 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 writes them + in the room left there. + + Depends on: Chunk for chunks and fixups, Scan for names and memory, + Diag for errors and paths. + Leaves out: the file format; that is Elf. *) +module Link; +import Fmt, Diag, Scan, Chunk; + +const + Base* = 400000H; + Page* = 4096; + +var + textOff*, textSize*: INT; (* file offset and size of text, at Base + textOff *) + roOff*, roSize*: INT; (* rodata, the room for the loader's tables included *) + roAdr*: INT; (* where rodata is loaded *) + extraAdr*: INT; (* that room *) + bssAdr*, bssSize*: INT; (* the writable segment, the loader's table first *) + bssOff*: INT; (* the file offset of that table *) + textImg*, roImg*: ^U8; + placesChunk*: INT; (* the rodata chunk of the places, made by the caller *) + linesOff*, linesSize*: INT; (* the line table, in the places: .debug_line *) + +proc setPlaces*(c: INT); +begin + placesChunk := c; +end; + +(* Marks live each chunk reached from entry through the fixups. *) +proc markLive*(entry: INT); +var stack: ^INT; sp, c, f, t: INT; fx: ^Chunk.Fixup; +begin + stack := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); + Chunk.setLive(entry); + stack[0] := entry; + sp := 1; + while sp > 0 do + DEC(sp); + c := stack[sp]; + if Chunk.chunks[c].size < 0 then + Diag.fatal(Diag.say("{} is declared but never defined", [Fmt.str(Chunk.chunkName(c))])); + end; + (* code and constants have fixups; variables start at zero, holding + no addresses *) + match Chunk.chunks[c].sec of + | secText: fx := Chunk.fixups; + | secRodata: fx := Chunk.dataFixups; + | secBss: fx := nil; + end; + if fx # nil then + for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do + t := fx[f].chunk; + if not Chunk.chunks[t].live then + Chunk.setLive(t); + stack[sp] := t; + INC(sp); + end; + end; + end; + end; +end; + +(* Gives the live chunks of one section their places, from start; + returns the end. *) +proc place(sec: Chunk.Section; start: INT): INT; +var c, a: INT; +begin + a := start; + for c := 0 to Chunk.numChunks - 1 do + if Chunk.chunks[c].live and (Chunk.chunks[c].sec = sec) then + a := (a + Chunk.chunks[c].align - 1) div Chunk.chunks[c].align * Chunk.chunks[c].align; + Chunk.setAdr(c, a); + a := a + Chunk.chunks[c].size; + end; + end; + return 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: ^U8; + lpLen, lpCap: INT; + +proc putB(v: INT); +begin + if lpLen = lpCap then + lp := Scan.regrab(lp, lpLen, lpCap * 2 + 256); + lpCap := lpCap * 2 + 256; + end; + lp[lpLen] := U8(v & 0FFH); + INC(lpLen); +end; + +(* The n low bytes of v, least significant first *) +proc putN(v: INT; n: INT); +var i: INT; +begin + for i := 1 to n do putB(v); v := v shr 8; end; +end; + +(* LEB128, unsigned and signed *) +proc putU(v: INT); +begin + while v >= 80H do putB(v & 7FH | 80H); v := v shr 7; end; + putB(v); +end; + +proc putS(v: INT); +begin + while (v < -64) or (v >= 64) do putB(v & 7FH | 80H); v := v shr 7; end; + putB(v & 7FH); +end; + +(* v as the four bytes at at in p *) +proc patch4(p: ^U8; at, v: INT); +var i: INT; +begin + for i := 0 to 3 do p[at + i] := U8((v shr (8 * i)) & 0FFH); end; +end; + +(* v as the eight bytes at at in p *) +proc patch8(p: ^U8; at, v: INT); +var i: INT; +begin + for i := 0 to 7 do p[at + i] := U8((v shr (8 * i)) & 0FFH); end; +end; + +(* Whether the standard opcode i takes an operand *) +proc takesOperand(i: INT): BOOL; +begin + return (i = 2) or (i = 3) or (i = 4) or (i = 5) or (i = 9) or (i = 12); +end; + +(* The line program of the files paths, nfiles of them, numbered from + 1, as they are written in the table *) +proc makeLines(paths: ^INT; nfiles: INT); +var i, f, c, cf, cl, cc, op, at, da, dl: INT; s: []U8; +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 + if takesOperand(i) then putB(1); else putB(0); end; (* their operands *) + end; + putB(0); (* no include directories *) + for f := 0 to nfiles - 1 do + s := Diag.shownPath(Scan.nameOf(paths[f])); + for i := 0 to LEN(s) - 1 do putB(INT(s[i])); end; + putN(0, 4); (* its end, directory, time, length *) + end; + putB(0); + patch4(lp, 6, lpLen - 10); + i := 0; + while i < Chunk.numLines do + c := Chunk.lines[i].chunk; + if not Chunk.chunks[c].live then + INC(i); + else + putB(0); putU(9); putB(2); (* DW_LNE_set_address *) + putN(Chunk.chunks[c].adr + Chunk.lines[i].at - Chunk.chunks[c].start, 8); + at := Chunk.lines[i].at; cf := 1; cl := 1; cc := 0; + while (i < Chunk.numLines) and (Chunk.lines[i].chunk = c) do + f := 1; + while paths[f - 1] # Chunk.lines[i].path do INC(f); end; + if f # cf then putB(4); putU(f); cf := f; end; (* DW_LNS_set_file *) + if Chunk.lines[i].col # cc then putB(5); putU(Chunk.lines[i].col); cc := Chunk.lines[i].col; end; (* DW_LNS_set_column *) + da := Chunk.lines[i].at - at; + dl := Chunk.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 + if da > 0 then putB(2); putU(da); end; (* DW_LNS_advance_pc *) + if dl # 0 then putB(3); putS(dl); end; (* DW_LNS_advance_line *) + putB(1); (* DW_LNS_copy: a row *) + end; + at := Chunk.lines[i].at; cl := Chunk.lines[i].line; + INC(i); + end; + putB(2); putU(Chunk.chunks[c].start + Chunk.chunks[c].size - at); + putB(0); putU(1); putB(1); (* DW_LNE_end_sequence *) + end; + end; + patch4(lp, 0, lpLen - 4); +end; + +var + buf: ^U8; (* the places, being made *) + at, names, poolAt: INT; (* where the next number goes, the next name, the pool's start *) + +(* The name s, in the pool, and its offset from the pool's start, at at *) +proc putName(s: []U8); +begin + patch4(buf, at, names - poolAt); + COPY(buf[names..names + LEN(s)], s); + buf[names + LEN(s)] := 0; + names := names + LEN(s) + 1; + at := at + 4; +end; + +(* Whether chunk c is a live procedure, whose places Rt knows *) +proc isProc(c: INT): BOOL; +begin + return Chunk.chunks[c].live and (Chunk.chunks[c].sec = Chunk.secText) and (Chunk.chunks[c].home >= 0); +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'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. *) +proc makePlaces(start, stop: INT); +var + files, first, count: ^INT; + i, f, nfiles, np, nv, c, v: INT; +begin + files := ^INT(Scan.grab(Chunk.numLines * SIZE(INT) + SIZE(INT))); + first := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); + count := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); + for c := 0 to Chunk.numChunks - 1 do first[c] := 0; count[c] := 0; end; + for v := Chunk.numVarNotes - 1 to 0 by -1 do + first[Chunk.varNotes[v].chunk] := v; + INC(count[Chunk.varNotes[v].chunk]); + end; + nfiles := 0; poolAt := 0; np := 0; nv := 0; + for i := 0 to Chunk.numLines - 1 do + if Chunk.chunks[Chunk.lines[i].chunk].live then + f := 0; + while (f < nfiles) and (files[f] # Chunk.lines[i].path) do INC(f); end; + if f = nfiles then + files[f] := Chunk.lines[i].path; + INC(nfiles); + end; + end; + end; + makeLines(files, nfiles); + for c := 0 to Chunk.numChunks - 1 do + if isProc(c) then + INC(np); + poolAt := poolAt + LEN(Chunk.chunkName(c)) + 1; + for v := first[c] to first[c] + count[c] - 1 do + poolAt := poolAt + LEN(Scan.nameOf(Chunk.varNotes[v].name)) + 1; + end; + nv := nv + count[c]; + end; + end; + buf := Scan.grab(40 + 28 * np + 12 * nv + poolAt + lpLen); + (* the pool of names starts at poolAt, the line table after it *) + poolAt := 40 + 28 * np + 12 * nv; + names := poolAt; + at := 40; + v := 0; + for c := 0 to Chunk.numChunks - 1 do + if isProc(c) then + patch4(buf, at, Chunk.chunks[c].adr); + patch4(buf, at + 4, Chunk.chunks[c].adr + Chunk.chunks[c].size); + at := at + 8; + putName(Chunk.chunkName(c)); + patch4(buf, at, v); + patch4(buf, at + 4, count[c]); + patch4(buf, at + 8, Chunk.chunks[c].saveMask); + patch4(buf, at + 12, Chunk.chunks[c].saveAt); + at := at + 16; + v := v + count[c]; + end; + end; + for c := 0 to Chunk.numChunks - 1 do + if isProc(c) then + for v := first[c] to first[c] + count[c] - 1 do + putName(Scan.nameOf(Chunk.varNotes[v].name)); + patch4(buf, at, Chunk.varNotes[v].off); + patch4(buf, at + 4, Chunk.varNotes[v].kind); + at := at + 8; + end; + end; + end; + linesOff := names; + linesSize := lpLen; + COPY(buf[names..names + lpLen], lp[0..lpLen]); + patch8(buf, 0, linesOff); + patch8(buf, 8, start); + patch8(buf, 16, stop); + patch8(buf, 24, np); + patch8(buf, 32, nv); + Chunk.setData(placesChunk, buf, names + lpLen, 8); +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. *) +proc linkAll*(headerSize, roExtra, dynSize: INT); +var c, f, at, p, e, v: INT; +begin + textOff := (headerSize + 31) div 32 * 32; (* as each code chunk is *) + e := place(Chunk.secText, Base + textOff); + textSize := e - (Base + textOff); + if placesChunk >= 0 then makePlaces(Base + textOff, e); end; + roOff := (textOff + textSize + 31) div 32 * 32; + roAdr := Base + Page + roOff; + e := place(Chunk.secRodata, roAdr); + extraAdr := (e + 7) div 8 * 8; + if roExtra > 0 then e := extraAdr + roExtra; end; + 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; + end; + e := place(Chunk.secBss, bssAdr + dynSize); + bssSize := e - bssAdr; + + textImg := Scan.grab(textSize + 1); + (* the gaps between code chunks are int3, a trap if ever run *) + for p := 0 to textSize do textImg[p] := 0CCH; end; + roImg := Scan.grab(roSize + 1); + for p := 0 to roSize do roImg[p] := 0; end; + for c := 0 to Chunk.numChunks - 1 do + if Chunk.chunks[c].live then + if Chunk.chunks[c].sec = Chunk.secText then + p := Chunk.chunks[c].adr - (Base + textOff); + COPY(textImg[p..p + Chunk.chunks[c].size], Chunk.text[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]); + for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do + at := Chunk.fixups[f].at - Chunk.chunks[c].start; + (* rel32: from the end of the field to the target *) + v := Chunk.chunks[Chunk.fixups[f].chunk].adr + Chunk.fixups[f].addend + - (Chunk.chunks[c].adr + at + 4); + patch4(textImg, p + at, v); + end; + elsif Chunk.chunks[c].sec = Chunk.secRodata then + p := Chunk.chunks[c].adr - roAdr; + COPY(roImg[p..p + Chunk.chunks[c].size], Chunk.rodata[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]); + for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do + patch8(roImg, p + Chunk.dataFixups[f].at, + Chunk.chunks[Chunk.dataFixups[f].chunk].adr + Chunk.dataFixups[f].addend); + end; + end; + end; + end; +end; + +begin + placesChunk := -1; +end Link. diff --git a/src/Parse.raz b/src/Parse.raz new file mode 100644 index 0000000..c296d85 --- /dev/null +++ b/src/Parse.raz @@ -0,0 +1,3775 @@ +(* Parse: the parser. + + Reads modules by recursive descent and has Gen 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. + + The seed's errors ended in a jump back to the statement or + declaration being read (Scan.mark, longjmp). Here every routine that + can find an error returns an ERROR as its last result, and the ones + that call it pass it up with try, as Item does; the statement or + declaration that is a recovery point (guard) looks at what comes back + and reads on. What has been made by then is what the seed had made + when it jumped. A seed `var` that only gave a value back is a result + where that is shorter; the others stay as they were. A set of + Scan.Sym is a chain of tests, since it has more names than a set + holds. *) +module Parse; +import Fmt, Diag, Scan, Sym, Chunk, Gen, Item, Sys, Str, Buf, Heap; + +type + PType = ^Sym.Type; + PObj = ^Sym.Obj; + PModule = ^Sym.Module; + TItem = Item.Item; + + (* The innermost loop: the chain of its breaks and the deferred + statements in force outside it *) + Loop = record + brk: INT; + base: INT; + end; + PLoop = ^Loop; + + (* A generic module's import whose instance isn't made yet (deferred, + numDeferred); not to be confused with a defer statement (defers) *) + Deferred = record + o: PObj; (* the name it imports as *) + home: PModule; (* the module that imports it *) + mname: INT; (* the generic module *) + args: Scan.State; (* at the "(" of its arguments *) + at: Diag.Pos; (* the import *) + end; + +const + (* 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 reports once it knows what the program uses. *) + HasReals* = true; + + MaxNames = 64; (* names in one declaration, and the like *) + MaxFwd = 256; (* pointers to types not yet declared *) + MaxDefers = 64; (* defer statements in force *) + MaxDrops = 4096; (* calls that drop results, in one module *) + MaxDeferred = 64; (* generic imports not yet made *) + MaxLabels = 1024; (* labels of one match *) + MaxElements = 1024; (* elements of an array literal *) + MaxFixes = 4096; (* addresses in one constant *) + MaxPending = 64; (* modules being compiled at once *) + Suffixes: [4][]U8 = [".linux-x86_64", ".linux", ".x86_64", ""]; + +var + libDir*, mainDir: []U8; + incDirs*: [16][]U8; + numInc*: INT; + firstModule*, lastModule*: PModule; (* in the order they were finished *) + + checkMode: BOOL; (* reading a file only for its interface *) + inTypes: BOOL; (* in a type section: ^T may name a later type *) + fwdTypes: [MaxFwd]PType; + fwdPos: [MaxFwd]Diag.Pos; (* where each names its type *) + numFwd: INT; + lastCalled: PObj; (* the procedure the last call was of, if it had a name *) + passOn: BOOL; (* the next factor may be a call with several results, for return *) + curProc: PObj; (* the procedure being compiled, or nil *) + declExported: BOOL; (* the export mark of the declaration being read *) + curLoop: PLoop; (* the innermost loop, or nil *) + defers: [MaxDefers]INT; (* the defer statements in force, their code's addresses *) + numDefers: INT; + deferring: BOOL; (* compiling a defer statement's statement *) + directDefer: BOOL; (* ... as the statement itself, not in a list *) + deferSlot: I64; (* keeps a result while deferred statements run *) + curResult: PType; (* the result type of the procedure being compiled *) + inExtern: BOOL; (* reading an extern's signature: ... allowed *) + tArgv, tBodySig: PType; + nameRt, nameFail, nameBody, nameStatic, nameCheck, nameOff, nameAdr: INT; + declaring: [MaxNames]INT; (* the names the declaration being read declares *) + numDeclaring: INT; + skipped: BOOL; (* the last statement had an error and was skipped *) + deferred: [MaxDeferred]Deferred; (* generic imports not yet made, not defer statements *) + numDeferred: INT; + making: BOOL; (* reading an instance's arguments, at its first use *) + stray: BOOL; (* an "end" in this procedure stood left of its statement's line *) + strayAt: Diag.Pos; (* ... the first such statement *) + elseIf: BOOL; (* an "else if" in this procedure *) + drops: [MaxDrops]record + at: Diag.Pos; (* a call standing on its own that drops results *) + n: INT; (* ... how many *) + end; + numDrops: INT; (* the module being compiled has those from its + first one, saved by compileFile, to here *) + ends: BOOL; (* the statements just read never go on past + their end: each way through them returns *) + useAt: Diag.Pos; (* ... which is here *) + guards: INT; (* the recovery points open *) + +proc expression(var x: TItem; want: PType): ERROR; forward; +proc parseType: (PType, ERROR); forward; +proc statements: ERROR; forward; +proc statement: ERROR; forward; + +(* Little helpers *) + +proc setLibDir*(dir: []U8); +begin + libDir := dir; +end; + +proc addIncDir*(dir: []U8); +begin + incDirs[numInc] := dir; + INC(numInc); +end; + +proc nameOf(n: INT): []U8; +begin + return Scan.nameOf(n); +end; + +(* The name number of s, which isn't empty *) +proc internName(s: []U8): INT; +begin + return Scan.intern(ADR(s[0]), LEN(s)); +end; + +proc say1(f, a: []U8): []U8; +begin + return Diag.say(f, [Fmt.str(a)]); +end; + +proc say2(f, a, b: []U8): []U8; +begin + return Diag.say(f, [Fmt.str(a), Fmt.str(b)]); +end; + +proc say3(f, a, b, c: []U8): []U8; +begin + return Diag.say(f, [Fmt.str(a), Fmt.str(b), Fmt.str(c)]); +end; + +(* More than n of what, as a message *) +proc tooMany(n: INT; what: []U8): []U8; +begin + return Diag.say("more than {} {}", [Fmt.int(n), Fmt.str(what)]); +end; + +(* A missing symbol is reported just after the one before it. *) +proc expected(what: []U8): ERROR; +begin + if Scan.tok = Scan.sBlank then + return Scan.mark("_ isn't a name: it is the blank, which stands only left of :="); + end; + return Scan.markAt(Scan.missingPos(), say2("expected {}, found {}", what, Scan.found())); +end; + +proc expect(s: Scan.Sym): ERROR; +begin + if (Scan.tok = Scan.sLbrace) and ((s = Scan.sThen) or (s = Scan.sDo)) then + return Scan.markHelp(Scan.missingPos(), say2("expected {}, found {}", Scan.symText(s), Scan.found()), + say1("a block is written {} ... end", Scan.symText(s))); + end; + if Scan.tok # s then return expected(Scan.symText(s)); end; + Scan.next; + return nil; +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. *) +proc closeEnd(start: Diag.Pos; ind: INT): ERROR; +begin + if (Scan.tok = Scan.sEnd) and not stray and (Scan.indent() < ind) then + stray := true; + strayAt := start; + end; + return expect(Scan.sEnd); +end; + +(* The error of a procedure or module whose own "end" isn't where it + should be, with what closeEnd saw *) +proc endMissing(p: Diag.Pos; msg: []U8): ERROR; +begin + Diag.error(p, msg); + if stray then Diag.note(strayAt, "is this statement's \"end\" missing? one further left closes it"); end; + if elseIf then Diag.help("raz writes elsif: \"else if\" begins an if that needs its own \"end\""); end; + return Scan.Failed; +end; + +(* A name being declared, and whether it is exported; at is the name *) +proc identDef(var n: INT; var exp: BOOL; var at: Diag.Pos): ERROR; +begin + if Scan.tok # Scan.sIdent then return expected("a name"); end; + n := Scan.id; + at := Scan.tokPos(); + Scan.next; + exp := false; + if Scan.tok = Scan.sTimes then + exp := true; + Scan.next; + end; + return nil; +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. *) +proc declare(o: PObj): ERROR; +var m: PModule; +begin + m := Sym.curModule; + try Sym.insert(o, Sym.topScope()); + if Sym.topScope() = m^.scope then + if m^.last = nil then m^.first := o; else m^.last^.chain := o; end; + m^.last := o; + else + if m^.lastLocal = nil then m^.locals := o; else m^.lastLocal^.chain := o; end; + m^.lastLocal := o; + end; + return nil; +end; + +(* o is named: a procedure naming itself doesn't count *) +proc named(o: PObj); +begin + if o # curProc then + 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 when what it read comes back with + an error, 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 + Recover = record + scan: Scan.State; + scopes, depth, pushed, numDefers: INT; + guards: INT; + loop: PLoop; + result: PType; + deferring, directDefer, quiet: BOOL; + end; + +proc guard(var r: Recover); +begin + Scan.saveScan(r.scan); + r.guards := guards; + r.scopes := Sym.scopeDepth(); r.depth := Gen.depth; r.pushed := Gen.pushed; r.numDefers := numDefers; + r.loop := curLoop; r.result := curResult; + r.deferring := deferring; r.directDefer := directDefer; r.quiet := Diag.quiet; + INC(guards); + Diag.setQuiet(false); +end; + +proc unguard(var r: Recover); +begin + guards := r.guards; + Diag.setQuiet(r.quiet); + Scan.setSkipping(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 *) +proc restore(var r: Recover); +begin + Scan.restoreScan(r.scan); + Scan.setSkipping(true); + Sym.cutScopes(r.scopes); + Gen.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: the error + goes on up to the next recovery point, or ends the compile if there + is none *) +proc giveUp(var r: Recover): ERROR; +begin + unguard(r); + if guards = 0 then Diag.finish(); end; + return Scan.Failed; +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. *) +proc skipConstruct: BOOL; +var d, p: INT; prev: Scan.Sym; +begin + d := 0; p := 0; prev := Scan.sSemicolon; + repeat + match Scan.tok of + | sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: INC(d); + | sEnd, sUntil: + if d = 0 then return true; end; + DEC(d); + | sElse, sElsif: if (d = 0) and (p = 0) then return true; end; + | sBar: if (d = 0) and (p = 0) and (prev = Scan.sSemicolon) then return true; end; + | sLparen, sLbrak, sLbrace: INC(p); + | sRparen, sRbrak, sRbrace: if p > 0 then DEC(p); end; + | sSemicolon: if (d = 0) and (p = 0) then return true; end; + | sEof: return false; + | else: + end; + prev := Scan.tok; + Scan.next; + until Scan.atLineStart(); + return false; +end; + +(* Declares n where it is used, after it was reported as not declared, + or after the declaration of it had an error *) +proc poison(n: INT); +var o: PObj; +begin + o := Sym.newObj(Sym.oConst, n, Sym.tPoison); + _ := Sym.insert(o, Sym.topScope()); (* n isn't in this scope, so it can't be twice *) +end; + +proc willDeclare(n: INT); +begin + if numDeclaring < MaxNames then declaring[numDeclaring] := n; end; + INC(numDeclaring); +end; + +(* After a declaration had an error: its names are poison, and reading + goes on after it *) +proc skipDeclaration; +var i: INT; +begin + for i := 0 to numDeclaring - 1 do + if (i < MaxNames) and (Sym.find(Sym.topScope(), declaring[i]) = nil) then + poison(declaring[i]); + end; + end; + if skipConstruct() and (Scan.tok = Scan.sSemicolon) then Scan.next; end; +end; + +proc constValue(var x: TItem): (I64, ERROR); +begin + if x.mode # Item.mConst then return 0, Scan.markAt(x.pos, "expected a constant"); end; + return x.val, nil; +end; + +proc constExpr: (I64, ERROR); +var x: TItem; +begin + try expression(x, nil); + if not Sym.isInt(x.typ) then + return 0, Scan.markAt(x.pos, say1("expected an integer constant, found {}", Item.what(x))); + end; + return constValue(x); +end; + +(* Help after a name that isn't found: o, the closest name in reach *) +proc didYouMean(o: PObj); +begin + if o # nil then Diag.help(say1("did you mean {}?", nameOf(o^.name))); end; +end; + +(* Where module n is found, if it is: dir and the file in it *) +proc moduleFile(n: INT): ([]U8, []U8, BOOL); forward; + +(* name in lower case, in memory that is never freed, as messages are *) +proc lowerCase(s: []U8): []U8; +var p: ^U8; i: INT; +begin + if LEN(s) = 0 then return ""; end; + p := Scan.grab(LEN(s)); + for i := 0 to LEN(s) - 1 do + if (s[i] >= 'A') and (s[i] <= 'Z') then p[i] := s[i] + 32; else p[i] := s[i]; end; + end; + return p[0..LEN(s)]; +end; + +(* Reports name n at p as not declared, with what it may have meant *) +proc notDeclared(p: Diag.Pos; n: INT); +var found: BOOL; low: []U8; +begin + Diag.error(p, say1("{} isn't declared", nameOf(n))); + _, _, found := moduleFile(n); + low := lowerCase(nameOf(n)); + if found then Diag.help(say2("{} is a module: import {}", nameOf(n), nameOf(n))); + elsif (nameOf(n) = "elif") or (nameOf(n) = "elseif") then Diag.help("raz writes elsif"); + elsif Scan.reserved(internName(low)) then Diag.help(say1("a reserved word is written in lower case: {}", low)); + else didYouMean(Sym.closest(n, -1)); + end; +end; + +proc firstUse(o: PObj; at: Diag.Pos): ERROR; forward; +proc instancesFor(wholeRest: BOOL): ERROR; forward; +proc addImport(m, im: PModule); forward; + +proc qualIdent: (PObj, ERROR); +var o: PObj; m: PModule; at: Diag.Pos; +begin + if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; + at := Scan.tokPos(); + o := Sym.lookup(Scan.id); + if o = nil then + if not making then poison(Scan.id); end; (* it may yet be declared *) + Diag.setQuiet(false); + notDeclared(at, Scan.id); + if making then Diag.note(useAt, "the instance is made here, where it is first used"); end; + return nil, Scan.Failed; + end; + if o^.typ = Sym.tPoison then Diag.setQuiet(true); end; + named(o); + Scan.next; + if o^.cls = Sym.oModule then + if o^.home = nil then try firstUse(o, at); end; + try expect(Scan.sPeriod); + if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; + m := o^.home; + o := Sym.find(m^.scope, Scan.id); + if (o = nil) or not o^.exported then + Diag.error(Scan.tokPos(), say2("{} isn't exported by {}", nameOf(Scan.id), nameOf(m^.name))); + if o # nil then Diag.note(o^.pos, say1("{} is declared here, without a *", nameOf(Scan.id))); + else didYouMean(Sym.closest(Scan.id, m^.scope)); + end; + return nil, Scan.Failed; + end; + Scan.next; + end; + return o, nil; +end; + +(* The field of record type t named by the current symbol *) +proc fieldOf(t: PType): (PObj, ERROR); +var f: PObj; +begin + f := Sym.find(t^.scope, Scan.id); + if f = nil then + Diag.error(Scan.tokPos(), say2("{} has no field {}", Sym.typeName(t), nameOf(Scan.id))); + didYouMean(Sym.closest(Scan.id, t^.scope)); + return nil, Scan.Failed; + end; + if not f^.exported and (t^.home # Sym.curModule) then + Diag.error(Scan.tokPos(), say2("field {} of {} isn't exported", nameOf(Scan.id), Sym.typeName(t))); + Diag.note(f^.pos, say1("{} is declared here, without a *", nameOf(Scan.id))); + return nil, Scan.Failed; + end; + return f, nil; +end; + +proc newPtr(base: PType; vol: BOOL): PType; +var t: PType; +begin + t := Sym.newType(Sym.fPtr, 8, 8); + t^.base := base; + t^.vol := vol; + return t; +end; + +(* Types *) + +proc recordType: (PType, ERROR); +var + t, ft: PType; f, last: PObj; names: [MaxNames]INT; + exps: [MaxNames]BOOL; poss: [MaxNames]Diag.Pos; + n, i: INT; off, a, maxA: I64; +begin + t := Sym.newType(Sym.fRecord, 0, 1); + if Scan.tok = Scan.sPacked then t^.packd := true; Scan.next; end; + try expect(Scan.sRecord); + t^.scope := Sym.newScope(); + off := 0; maxA := 1; last := nil; + while Scan.tok = Scan.sIdent do + n := 0; + repeat + if n >= MaxNames then return nil, Scan.mark(tooMany(MaxNames, "names in one declaration")); end; + try identDef(names[n], exps[n], poss[n]); + INC(n); + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + try expect(Scan.sColon); + ft := try parseType(); + if t^.packd then a := 1; else a := ft^.align; end; + for i := 0 to n - 1 do + off := Sym.alignUp(off, a); + f := Sym.newObj(Sym.oField, names[i], ft); + f^.exported := exps[i]; + f^.pos := poss[i]; + f^.val := off; + try Sym.insert(f, t^.scope); + if last = nil then t^.fields := f; else last^.next := f; end; + last := f; + off := off + ft^.size; + end; + if a > maxA then maxA := a; end; + try expect(Scan.sSemicolon); + end; + try expect(Scan.sEnd); + t^.align := maxA; + t^.size := Sym.alignUp(off, maxA); + return t, nil; +end; + +proc variantType: (PType, ERROR); +var t, ft: PType; c, lastC, f, lastF: PObj; tag, off, maxSize: I64; +begin + try expect(Scan.sVariant); + t := Sym.newType(Sym.fVariant, 8, 8); + tag := 0; maxSize := 8; lastC := nil; + while Scan.tok = Scan.sIdent do + c := Sym.newObj(Sym.oCase, Scan.id, t); + c^.val := tag; + c^.exported := declExported; + try declare(c); + if lastC = nil then t^.fields := c; else lastC^.next := c; end; + lastC := c; + Scan.next; + off := 8; + if Scan.tok = Scan.sLparen then + Scan.next; + lastF := nil; + repeat + repeat + if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; + f := Sym.newObj(Sym.oField, Scan.id, nil); + f^.exported := true; + if lastF = nil then c^.fields := f; else lastF^.next := f; end; + lastF := f; + Scan.next; + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + try expect(Scan.sColon); + ft := try parseType(); + f := c^.fields; + while f^.typ # nil do f := f^.next; end; + while f # nil do + f^.typ := ft; + off := Sym.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; end; + if Scan.tok # Scan.sSemicolon then break; end; + Scan.next; + until false; + try expect(Scan.sRparen); + end; + if off > maxSize then maxSize := off; end; + try expect(Scan.sSemicolon); + INC(tag); + end; + try expect(Scan.sEnd); + t^.len := tag; + t^.size := Sym.alignUp(maxSize, t^.align); + return t, nil; +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. *) +proc results: (PType, ERROR); +var t, ft: PType; f, last: PObj; off: I64; +begin + Scan.next; + t := Sym.newType(Sym.fRecord, 0, 1); + t^.tuple := true; + off := 0; last := nil; + repeat + ft := try parseType(); + off := Sym.alignUp(off, ft^.align); + f := Sym.newObj(Sym.oField, -1, ft); + f^.val := off; + off := off + ft^.size; + if ft^.align > t^.align then t^.align := ft^.align; end; + if last = nil then t^.fields := f; else last^.next := f; end; + last := f; + INC(t^.len); + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + try expect(Scan.sRparen); + t^.size := Sym.alignUp(off, t^.align); + if t^.len = 1 then return t^.fields^.typ, nil; end; + return t, nil; +end; + +proc signature: (PType, ERROR); +var + t, pt: PType; p, first, last: PObj; isVar: BOOL; n: INT; +begin + t := Sym.newType(Sym.fProc, 8, 8); + last := nil; n := 0; + if Scan.tok = Scan.sLparen then + Scan.next; + if Scan.tok # Scan.sRparen then + repeat + if Scan.tok = Scan.sEllipsis then + if not inExtern then return nil, Scan.mark("... is only for extern procedures"); end; + Scan.next; t^.variadic := true; break; + end; + isVar := Scan.tok = Scan.sVar; + if isVar then Scan.next; end; + first := nil; + repeat + if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; + p := Sym.newObj(Sym.oVar, Scan.id, nil); + p^.isVar := isVar; + p^.lev := 1; + if last = nil then t^.fields := p; else last^.next := p; end; + last := p; + if first = nil then first := p; end; + INC(n); + Scan.next; + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + try expect(Scan.sColon); + pt := try parseType(); + while first # nil do first^.typ := pt; first := first^.next; end; + if Scan.tok # Scan.sSemicolon then break; end; + Scan.next; + until false; + end; + try expect(Scan.sRparen); + end; + t^.len := n; + if Scan.tok = Scan.sColon then + Scan.next; + if Scan.tok = Scan.sLparen then t^.base := try results(); else t^.base := try parseType(); end; + end; + return t, nil; +end; + +proc enumType: (PType, ERROR); +var t: PType; o, last: PObj; start: Diag.Pos; +begin + start := Scan.tokPos(); + t := Sym.newType(Sym.fEnum, 1, 1); + last := nil; + repeat + Scan.next; + if Scan.tok # Scan.sIdent then return nil, expected("a name"); end; + o := Sym.newObj(Sym.oConst, Scan.id, t); + o^.val := t^.len; + o^.exported := declExported; + o^.used := true; (* an enumeration's names are its type's, warned of with it *) + try declare(o); + if last = nil then t^.fields := o; else last^.next := o; end; + last := o; + INC(t^.len); + Scan.next; + until Scan.tok # Scan.sComma; + try expect(Scan.sRparen); + if t^.len > 256 then return nil, Scan.markAt(Scan.spanFrom(start), "an enumeration has at most 256 names"); end; + return t, nil; +end; + +proc setOf(e: PType; at: Diag.Pos): (PType, ERROR); +var t: PType; +begin + if (e^.form # Sym.fEnum) or (e^.len > 64) then + return nil, Scan.markAt(at, say1("a set needs an enumeration of at most 64 names, found {}", Sym.typeName(e))); + end; + t := Sym.newType(Sym.fSet, 8, 8); + if e^.len <= 8 then t^.size := 1; + elsif e^.len <= 16 then t^.size := 2; + elsif e^.len <= 32 then t^.size := 4; + end; + t^.align := t^.size; + t^.base := e; + t^.len := e^.len; + return t, nil; +end; + +proc parseType: (PType, ERROR); +var t: PType; o: PObj; n: I64; vol: BOOL; start: Diag.Pos; +begin + start := Scan.tokPos(); + match Scan.tok of + | sIdent: + o := try qualIdent(); + if o^.cls # Sym.oType then + return nil, Scan.markAt(Scan.spanFrom(start), say1("{} isn't a type", nameOf(o^.name))); + end; + t := o^.typ; + | sLbrak: + Scan.next; + if Scan.tok = Scan.sRbrak then + Scan.next; + t := Sym.newType(Sym.fSlice, 16, 8); + t^.base := try parseType(); + else + start := Scan.tokPos(); + n := try constExpr(); + if (n <= 0) or (n > (I64(1) shl 40)) then + return nil, Scan.markAt(Scan.spanFrom(start), Diag.say("an array's length is from 1 to 2^40, found {}", [Fmt.int(n)])); + end; + try expect(Scan.sRbrak); + t := Sym.newType(Sym.fArray, 0, 1); + t^.len := n; + t^.base := try parseType(); + t^.size := n * t^.base^.size; + t^.align := t^.base^.align; + end; + | sArrow: + Scan.next; + vol := Scan.tok = Scan.sVolatile; + if vol then Scan.next; end; + if inTypes and (Scan.tok = Scan.sIdent) and (Sym.lookup(Scan.id) = nil) then + (* a type declared later in this section *) + t := newPtr(nil, vol); + t^.fwd := Scan.id; + if numFwd >= MaxFwd then + return nil, Scan.mark(tooMany(MaxFwd, "pointers to types not yet declared")); + end; + fwdTypes[numFwd] := t; + fwdPos[numFwd] := Scan.tokPos(); + INC(numFwd); + Scan.next; + else + t := newPtr(try parseType(), vol); + end; + | sPacked, sRecord: t := try recordType(); + | sVariant: t := try variantType(); + | sProc: Scan.next; t := try signature(); + | sLparen: t := try enumType(); + | sSet: + Scan.next; + try expect(Scan.sOf); + start := Scan.tokPos(); + t := try setOf(try parseType(), start); + | else: return nil, expected("a type"); + end; + return t, nil; +end; + +(* Expressions *) + +proc call(var x: TItem): ERROR; +var c: Gen.CallInfo; a: TItem; want: PType; +begin + try Item.beginCall(c, x); + try expect(Scan.sLparen); + if Scan.tok # Scan.sRparen then + repeat + if c.param # nil then want := c.param^.typ; else want := nil; end; + try expression(a, want); + try Item.passArg(c, a); + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + end; + try expect(Scan.sRparen); + return Item.endCall(c, x); +end; + +proc atomic(var x: TItem; which: INT): ERROR; +var p, a: TItem; t: PType; i, n: INT; +begin + try expression(p, nil); + if p.typ^.form # Sym.fPtr then + return Scan.markAt(p.pos, say1("expected a pointer, found {}", Item.what(p))); + end; + t := p.typ^.base; + if not (Item.isWord(t) or ((t^.form = Sym.fPtr) and (which # Sym.bXadd))) then + if which = Sym.bXadd then + return Scan.markAt(p.pos, say1("expected a pointer to an INT or a UINT, found {}", Sym.typeName(p.typ))); + end; + return Scan.markAt(p.pos, say1("expected a pointer to an INT, a UINT or a pointer, found {}", Sym.typeName(p.typ))); + end; + try Item.value(p); + if which = Sym.bCas then n := 2; else n := 1; end; + for i := 1 to n do + try expect(Scan.sComma); + try expression(a, t); + try Item.coerce(a, t); + try Item.value(a); + end; + Gen.atomic(which); + Item.makeConst(x, t, 0); + if which = Sym.bCas then x.typ := Sym.tBool; end; + x.mode := Item.mStack; + return nil; +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. *) +proc new_(var x: TItem): ERROR; +var y, z: TItem; t: PType; f: PObj; s: I64; c: Gen.CallInfo; +begin + try expression(x, nil); + try Item.notReadOnly(x); + if (x.mode # Item.mVar) or not x.isVar or (x.typ^.form # Sym.fPtr) then + return Scan.markAt(x.pos, "NEW needs a pointer variable"); + end; + t := x.typ^.base; + try expect(Scan.sComma); + try expression(y, nil); + if (y.typ^.form # Sym.fPtr) or (y.typ^.base^.obj = nil) or (y.typ^.base^.obj^.home = nil) + or (nameOf(y.typ^.base^.obj^.name) # "Allocator") + or (nameOf(y.typ^.base^.obj^.home^.name) # "Mem") then + return Scan.markAt(y.pos, say1("NEW needs a ^Mem.Allocator, found {}", Item.what(y))); + end; + f := Sym.find(y.typ^.base^.scope, internName("alloc")); + s := try Item.toSlot(y); + Gen.pushVar(Item.frameAdr(s), 8, false, Gen.kWord); + Item.makeConst(z, f^.typ, 0); + z.mode := Item.mVar; z.base := Gen.bStack; z.off := f^.val; + try Item.beginCall(c, z); + Gen.pushVar(Item.frameAdr(s), 8, false, Gen.kWord); + Item.makeConst(z, y.typ, 0); + z.mode := Item.mStack; + try Item.passArg(c, z); + Item.makeConst(z, Sym.tInt, t^.size); + try Item.passArg(c, z); + Item.makeConst(z, Sym.tInt, t^.align); + try Item.passArg(c, z); + try Item.endCall(c, z); + Gen.zeroNew(t^.size); + z.typ := x.typ; + try Item.assign(x, z); + Item.makeConst(x, Sym.tNone, 0); + x.mode := Item.mNone; + return nil; +end; + +proc incOrDec(which: INT): []U8; +begin + if which = Sym.bDec then return "DEC"; end; + return "INC"; +end; + +proc builtin(var x: TItem): ERROR; +var which, n: INT; y: TItem; t: PType; +begin + which := INT(x.obj^.val); + if (which = Sym.bFence) or (which = Sym.bArgc) or (which = Sym.bArgv) then + if Scan.tok = Scan.sLparen then Scan.next; try expect(Scan.sRparen); end; + Item.makeConst(x, Sym.tNone, 0); + match which of + | Sym.bFence: Gen.fence(); x.mode := Item.mNone; + | Sym.bArgc: + Gen.pushVar(Item.globalAdr(Gen.argcChunk), 8, false, Gen.kWord); + x.typ := Sym.tInt; x.mode := Item.mStack; + | else: + Gen.pushVar(Item.globalAdr(Gen.argvChunk), 8, false, Gen.kWord); + x.typ := tArgv; x.mode := Item.mStack; + end; + return nil; + end; + try expect(Scan.sLparen); + match which of + | Sym.bSize: + t := try parseType(); + Item.makeConst(x, Sym.tConst, t^.size); + | Sym.bAdr: + try expression(y, nil); + try Item.notReadOnly(y); + if (y.mode # Item.mVar) or not y.isVar then return Scan.markAt(y.pos, "ADR needs a variable"); end; + if y.odd then return Scan.markAt(y.pos, "a field of a packed record has no address"); end; + t := newPtr(y.typ, y.vol); + try Item.address(y); + Item.makeConst(x, t, 0); + x.mode := Item.mStack; + | Sym.bLen: + try expression(y, nil); + if y.mode = Item.mStr then + Item.makeConst(x, Sym.tConst, y.val); + elsif y.typ^.form = Sym.fArray then + try Item.discard(y); + Item.makeConst(x, Sym.tConst, y.typ^.len); + elsif (y.typ^.form = Sym.fSlice) and (y.mode = Item.mVar) then + (* its length, the word after its pointer *) + y.off := y.off + 8; + y.typ := Sym.tInt; + try Item.value(y); + x := y; + else + return Scan.markAt(y.pos, say1("LEN needs an array or a slice, found {}", Item.what(y))); + end; + | Sym.bSyscall: + n := 0; + repeat + if n > 0 then Scan.next; end; + try expression(y, nil); + if not (Sym.isScalar(y.typ) and (y.typ^.form # Sym.fReal)) then + return Scan.markAt(y.pos, say1("expected an integer or a pointer, found {}", Item.what(y))); + end; + if y.typ^.form = Sym.fConst then try Item.coerce(y, Sym.tInt); end; + try Item.value(y); + INC(n); + until (Scan.tok # Scan.sComma) or (n = 7); + Gen.sysCall(n); + Item.makeConst(x, Sym.tInt, 0); + x.mode := Item.mStack; + | Sym.bCas, Sym.bXchg, Sym.bXadd: try atomic(x, which); + | Sym.bMsg: + try expression(x, Sym.tError); + try Item.msg(x); + | Sym.bInc, Sym.bDec: + try expression(x, nil); + try Item.notReadOnly(x); + if (x.mode # Item.mVar) or not x.isVar or (x.typ^.form # Sym.fInt) then + return Scan.markAt(x.pos, say1("{} needs an integer variable", incOrDec(which))); + end; + if x.base # Gen.bReg then try Item.address(x); end; + if Scan.tok = Scan.sComma then + Scan.next; + try expression(y, x.typ); + else + Item.makeConst(y, x.typ, 1); + end; + try Item.incDec(x, y, which = Sym.bDec); + Item.makeConst(x, Sym.tNone, 0); + x.mode := Item.mNone; + | Sym.bNew: try new_(x); + | Sym.bCopy: + try expression(x, nil); + try Item.copyDest(x); + try expect(Scan.sComma); + try expression(y, nil); + try Item.copyFrom(x, y); + Item.makeConst(x, Sym.tNone, 0); + x.mode := Item.mNone; + | else: + end; + return expect(Scan.sRparen); +end; + +proc constructCase(var x: TItem; c: PObj; at: Diag.Pos): ERROR; +var f: PObj; a: TItem; +begin + Item.construct(x, c); + f := c^.fields; + if Scan.tok = Scan.sLparen then + Scan.next; + while f # nil do + try expression(a, f^.typ); + try Item.setField(x, f, a); + f := f^.next; + if f # nil then try expect(Scan.sComma); end; + end; + return expect(Scan.sRparen); + elsif f # nil then + return Scan.markAt(at, say1("{} needs its fields", nameOf(c^.name))); + end; + return nil; +end; + +(* x, before ".", has no fields; tok is what follows. Other languages + write p.f through a pointer and s.len for a length. *) +proc fieldOfWhat(x: TItem): ERROR; +var msg, f: []U8; +begin + msg := say1("expected a record, found {}", Item.what(x)); + if Scan.tok = Scan.sIdent then f := nameOf(Scan.id); else f := ""; end; + if (x.typ^.form = Sym.fPtr) and (x.typ^.base^.form = Sym.fRecord) then + return Scan.markHelp(x.pos, msg, say2("through a pointer, write {}^.{}", Diag.source(x.pos), f)); + elsif ((x.typ^.form = Sym.fArray) or (x.typ^.form = Sym.fSlice)) + and ((f = "len") or (f = "length") or (f = "size") or (f = "count")) then + return Scan.markHelp(x.pos, msg, say1("its length is LEN({})", Diag.source(x.pos))); + end; + return Scan.markAt(x.pos, msg); +end; + +(* A designator, with any selectors and calls after it. called tells + whether the last thing done was a call. *) +proc designator(var x: TItem; var called: BOOL): ERROR; +var o, f: PObj; y, z: TItem; t: PType; start: Diag.Pos; +begin + start := Scan.tokPos(); + o := try qualIdent(); + called := false; + if o^.cls = Sym.oModule then + return Scan.markAt(Scan.spanFrom(start), say1("{} is a module, not a value", nameOf(o^.name))); + end; + try Item.makeItem(x, o); + if x.mode = Item.mBuiltin then + try builtin(x); + called := true; + elsif x.mode = Item.mCase then + try constructCase(x, o, Scan.spanFrom(start)); + end; + repeat + x.pos := Scan.spanFrom(start); + match Scan.tok of + | sPeriod: + Scan.next; + if (x.mode # Item.mVar) or (x.typ^.form # Sym.fRecord) then return fieldOfWhat(x); end; + if Scan.tok # Scan.sIdent then return expected("a field"); end; + f := try fieldOf(x.typ); + Scan.next; + try Item.field(x, f); + called := false; + | sArrow: + Scan.next; + try Item.deref(x); + called := false; + | sLbrak: + Scan.next; + try Item.indexPrep(x); + try expression(y, nil); + if Scan.tok = Scan.sUpto then + Scan.next; + try Item.sliceLo(y); + try expression(z, nil); + try Item.slice(x, y, z); + else + try Item.index(x, y); + end; + try expect(Scan.sRbrak); + called := false; + | sLparen: + if x.mode = Item.mType then + t := x.typ; + Scan.next; + try expression(x, nil); + try expect(Scan.sRparen); + try Item.convert(x, t); + else + if x.mode = Item.mProc then lastCalled := x.obj; else lastCalled := nil; end; + try call(x); + called := true; + end; + | else: break; + end; + until false; + x.pos := Scan.spanFrom(start); + Item.nilTest(x); + return nil; +end; + +proc arrayLiteral(var x: TItem; want: PType): ERROR; +var + et, at: PType; e: TItem; slots: [MaxElements]I64; n, i: INT; + off, es: I64; start: Diag.Pos; +begin + start := Scan.tokPos(); + if (want = nil) or not ((want^.form = Sym.fArray) or (want^.form = Sym.fSlice)) then + return Scan.mark("an array literal needs a known array or slice type"); + end; + et := want^.base; + es := et^.size; + Scan.next; + n := 0; + if Scan.tok # Scan.sRbrak then + repeat + if n >= MaxElements then return Scan.mark(tooMany(MaxElements, "elements")); end; + try expression(e, et); + try Item.coerce(e, et); + if Sym.isScalar(et) then + slots[n] := try Item.toSlot(e); + else + if e.isVar or e.vol or (e.mode # Item.mVar) or (e.base # Gen.bFrame) then try Item.copyToTemp(e); end; + slots[n] := e.off; + end; + INC(n); + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + end; + try expect(Scan.sRbrak); + if (want^.form = Sym.fArray) and (I64(n) # want^.len) then + return Scan.markAt(Scan.spanFrom(start), Diag.say("expected {} elements, found {}", [Fmt.int(want^.len), Fmt.int(n)])); + end; + if n = 0 then + Gen.pushConst(Gen.kWord, 0); + Item.sliceOf(x, want, 0); + return nil; + end; + if want^.form = Sym.fArray then + at := want; + off := Gen.allocTemp(at^.size, at^.align); + else + at := Sym.newType(Sym.fArray, I64(n) * es, et^.align); + at^.len := n; + at^.base := et; + off := Gen.allocPerm(at^.size, at^.align); (* lives as long as the call *) + end; + for i := 0 to n - 1 do + if Sym.isScalar(et) then + Gen.pushVar(Item.frameAdr(slots[i]), 8, false, Gen.kindOf(et)); + Gen.popVar(Item.frameAdr(off + I64(i) * es), Item.scalarSize(et)); + else + Gen.pushAdr(Item.frameAdr(slots[i])); + Gen.copyTo(Item.frameAdr(off + I64(i) * es), es); + end; + end; + Item.tempItem(x, at, off); + return nil; +end; + +(* A record literal: a zeroed temporary, with the fields named filled in. *) +proc recordLiteral(var x: TItem; t: PType): ERROR; +var f: PObj; a: TItem; seen: [MaxNames]INT; n, i: INT; +begin + Scan.next; + Item.zeroTemp(x, t); + n := 0; + if Scan.tok # Scan.sRbrace then + repeat + if Scan.tok # Scan.sIdent then return expected("a field"); end; + f := try fieldOf(t); + for i := 0 to n - 1 do + if seen[i] = Scan.id then + return Scan.mark(say1("field {} is given twice", nameOf(Scan.id))); + end; + end; + if n < MaxNames then seen[n] := Scan.id; INC(n); end; + Scan.next; + try expect(Scan.sColon); + try expression(a, f^.typ); + try Item.setField(x, f, a); + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + end; + return expect(Scan.sRbrace); +end; + +(* A set literal: the bits of the constant names, or'd at run time with + those of the others. *) +proc setLiteral(var x: TItem; t: PType): ERROR; +var e: TItem; bits, slot: I64; start: Diag.Pos; s: []U8; +begin + start := Scan.tokPos(); + Scan.next; + if (t # nil) and (t^.form # Sym.fSet) then + return Scan.markAt(Scan.spanFrom(start), say1("expected a set type, found {}", Sym.typeName(t))); + end; + bits := 0; + slot := 0; + if Scan.tok # Scan.sRbrace then + repeat + if t = nil then try expression(e, nil); else try expression(e, t^.base); end; + if t = nil then + if e.typ^.form # Sym.fEnum then + return Scan.markAt(e.pos, say1("a set holds names of an enumeration, found {}", Item.what(e))); + end; + t := try setOf(e.typ, e.pos); + end; + if not Sym.same(e.typ, t^.base) then + if e.obj # nil then s := nameOf(e.obj^.name); else s := Item.what(e); end; + return Scan.markAt(e.pos, say2("{} isn't a name of {}", s, Sym.typeName(t^.base))); + end; + if e.mode = Item.mConst then + bits := bits | (I64(1) shl e.val); + else + if slot = 0 then + slot := Gen.allocTemp(8, 8); + Gen.pushConst(Gen.kWord, 0); + Gen.popVar(Item.frameAdr(slot), 8); + end; + try Item.value(e); + Gen.pushConst(Gen.kWord, 1); + Gen.swap(); + Gen.op(Scan.sShl, Gen.kWord, 8, false); + Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord); + Gen.op(Scan.sBar, Gen.kWord, 8, false); + Gen.popVar(Item.frameAdr(slot), 8); + end; + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + end; + try expect(Scan.sRbrace); + if t = nil then return Scan.markAt(Scan.spanFrom(start), "{} needs a known set type"); end; + Item.makeConst(x, t, bits); + if slot # 0 then + Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord); + Gen.pushConst(Gen.kWord, bits); + Gen.op(Scan.sBar, Gen.kWord, 8, false); + x.mode := Item.mStack; + end; + return nil; +end; + +proc runDefers(base: INT); 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. *) +proc lastResult(t: PType): PType; +var f: PObj; +begin + if not t^.tuple then return t; end; + f := t^.fields; + while f^.next # nil do f := f^.next; end; + return f^.typ; +end; + +(* The results of the tuple t but the last: the same fields, one fewer *) +proc withoutLast(t: PType): PType; +var r: PType; +begin + r := Sym.newType(Sym.fRecord, t^.size, t^.align); + r^.tuple := true; + r^.fields := t^.fields; + r^.len := t^.len - 1; + return 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. *) +proc tryCall(var x: TItem): ERROR; +var + called: BOOL; c: Gen.CallInfo; start, at: Diag.Pos; res: PType; last: PObj; slot: I64; ok: INT; +begin + start := Scan.tokPos(); + Scan.next; + if deferring then return Scan.markAt(Scan.spanFrom(start), "try can't leave a deferred statement"); end; + if curResult = nil then + return Scan.markAt(Scan.spanFrom(start), "try needs a procedure that ends in an ERROR result, and this returns nothing"); + elsif lastResult(curResult) # Sym.tError then + return Scan.markAt(Scan.spanFrom(start), + say1("try needs a procedure that ends in an ERROR result, and this returns {}", Sym.typeName(curResult))); + end; + try designator(x, called); + if not called and ((x.mode = Item.mProc) + or (((x.mode = Item.mVar) or (x.mode = Item.mStack)) and (x.typ^.form = Sym.fProc))) then + (* a procedure without parameters, written without parentheses *) + at := x.pos; + try Item.beginCall(c, x); + try Item.endCall(c, x); + x.pos := at; + called := true; + end; + if not called then return Scan.markAt(x.pos, say1("try needs a call, found {}", Item.what(x))); end; + if x.mode = Item.mNone then + return Scan.markAt(x.pos, "try needs a call that returns an ERROR last, and this returns nothing"); + end; + if lastResult(x.typ) # Sym.tError then + return Scan.markAt(x.pos, say1("try needs a call that returns an ERROR last, and this returns {}", Sym.typeName(x.typ))); + end; + res := x.typ; + if x.mode = Item.mStack then + (* an ERROR alone *) + slot := Gen.allocTemp(8, 8); + Gen.popVar(Item.frameAdr(slot), 8); + x.mode := Item.mNone; x.typ := Sym.tNone; + elsif x.mode = Item.mWords then + (* two words, the error on top *) + slot := Gen.allocTemp(8, 8); + Gen.popVar(Item.frameAdr(slot), 8); + x.mode := Item.mStack; x.typ := res^.fields^.typ; + else + (* several, in a temporary: the error is where it is *) + last := res^.fields; + while last^.next # nil do last := last^.next; end; + slot := x.off + last^.val; + if res^.len = 2 then try Item.field(x, res^.fields); else x.typ := withoutLast(res); end; + end; + ok := Gen.NoLabel; + Gen.pushVar(Item.frameAdr(slot), 8, false, Gen.kWord); + Gen.jumpIf(ok, false); + if numDefers > 0 then Gen.tryAlign(); end; + runDefers(0); + Gen.tryReturn(slot); + Gen.fix(ok); + x.pos := Scan.spanFrom(start); + return nil; +end; + +proc factor(var x: TItem; want: PType): ERROR; +var called, vol, several: BOOL; t: PType; start: Diag.Pos; s: []U8; +begin + several := passOn; + passOn := false; + start := Scan.tokPos(); + match Scan.tok of + | sInt, sChar: + (* only a hex number can be above high(I64), and it is a U64 *) + if Scan.ival < 0 then Item.makeConst(x, Sym.tU64, Scan.ival); else Item.makeConst(x, Sym.tConst, Scan.ival); end; + Scan.next; + | sReal: + Item.makeReal(x, Scan.rval); + Item.usesReals(Scan.tokPos()); + Scan.next; + | sString: + Item.makeStr(x); + Scan.next; + | sIdent: + try designator(x, called); + if x.mode = Item.mNone then + if lastCalled # nil then s := nameOf(lastCalled^.name); else s := "this procedure"; end; + return Scan.markAt(x.pos, say1("{} returns nothing", s)); + end; + if x.typ^.tuple and not several then + if lastCalled # nil then s := nameOf(lastCalled^.name); else s := "this procedure"; end; + return Scan.markHelp(x.pos, say1("{} returns several results", s), + say1("they go to variables: a, b := {}(...)", s)); + end; + | sLparen: + Scan.next; + try expression(x, want); + try expect(Scan.sRparen); + | sTry: + try tryCall(x); + if x.mode = Item.mNone then return Scan.markAt(x.pos, "this try has no value"); end; + if x.typ^.tuple then + return Scan.markHelp(x.pos, "this try has several values", "they go to variables: a, b := try f(...)"); + end; + | sNot: + Scan.next; + try factor(x, nil); + try Item.notOp(x); + | sTilde: + Scan.next; + try factor(x, nil); + try Item.complement(x); + | sLbrak: try arrayLiteral(x, want); + | sLbrace: + if (want # nil) and (want^.form = Sym.fRecord) then try recordLiteral(x, want); + else try setLiteral(x, want); + end; + | sArrow: + Scan.next; + vol := Scan.tok = Scan.sVolatile; + if vol then Scan.next; end; + t := try parseType(); + t := newPtr(t, vol); + try expect(Scan.sLparen); + try expression(x, nil); + try expect(Scan.sRparen); + try Item.convert(x, t); + (* a conversion is a factor, not a designator: nothing selects from it *) + if Scan.tok = Scan.sArrow then + return Scan.markHelp(Scan.tokPos(), "a conversion can't be dereferenced", + "convert into a pointer variable, then dereference that"); + end; + | else: return expected("an expression"); + end; + x.pos := Scan.spanFrom(start); + return nil; +end; + +proc isMulOp: BOOL; +begin + match Scan.tok of + | sTimes, sSlash, sDiv, sMod, sAmp, sShl, sShr: return true; + | else: return false; + end; +end; + +proc isAddOp: BOOL; +begin + match Scan.tok of + | sPlus, sMinus, sBar, sXor: return true; + | else: return false; + end; +end; + +proc isRelOp: BOOL; +begin + match Scan.tok of + | sEql, sNeq, sLss, sLeq, sGtr, sGeq, sIn: return true; + | else: return false; + end; +end; + +proc term(var x: TItem; want: PType): ERROR; +var op: Scan.Sym; y: TItem; L: INT; start: Diag.Pos; +begin + start := Scan.tokPos(); + try factor(x, want); + while isMulOp() do + op := Scan.tok; + Scan.next; + try Item.op1(op, x, L); + try factor(y, nil); + try Item.op2(op, x, y, L); + x.pos := Scan.spanFrom(start); + end; + return nil; +end; + +proc simpleExpr(var x: TItem; want: PType): ERROR; +var op: Scan.Sym; y: TItem; L: INT; start: Diag.Pos; +begin + start := Scan.tokPos(); + if Scan.tok = Scan.sMinus then + Scan.next; + try term(x, nil); + x.pos := Scan.spanFrom(start); + try Item.neg(x); + else + try term(x, want); + end; + while isAddOp() do + op := Scan.tok; + Scan.next; + try Item.op1(op, x, L); + try term(y, nil); + try Item.op2(op, x, y, L); + x.pos := Scan.spanFrom(start); + end; + return nil; +end; + +proc relation(var x: TItem; want: PType): ERROR; +var op: Scan.Sym; y: TItem; L: INT; +begin + try simpleExpr(x, want); + if isRelOp() then + op := Scan.tok; + Scan.next; + try Item.op1(op, x, L); + if op = Scan.sIn then try simpleExpr(y, nil); else try simpleExpr(y, x.typ); end; + try Item.op2(op, x, y, L); + x.pos := Diag.join(x.pos, y.pos); + end; + return nil; +end; + +(* and binds tighter than or, and both below the relations *) +proc conjunct(var x: TItem; want: PType): ERROR; +var y: TItem; L: INT; start: Diag.Pos; +begin + start := Scan.tokPos(); + try relation(x, want); + while Scan.tok = Scan.sAnd do + Scan.next; + try Item.op1(Scan.sAnd, x, L); + try relation(y, nil); + try Item.op2(Scan.sAnd, x, y, L); + x.pos := Scan.spanFrom(start); + end; + return nil; +end; + +proc expression(var x: TItem; want: PType): ERROR; +var y: TItem; L: INT; start: Diag.Pos; +begin + start := Scan.tokPos(); + try conjunct(x, want); + while Scan.tok = Scan.sOr do + Scan.next; + try Item.op1(Scan.sOr, x, L); + try conjunct(y, nil); + try Item.op2(Scan.sOr, x, y, L); + x.pos := Scan.spanFrom(start); + end; + return nil; +end; + +(* Statements *) + +proc enterLoop(var lp: Loop; var old: PLoop); +begin + lp.brk := Gen.NoLabel; + lp.base := numDefers; + old := curLoop; + curLoop := ADR(lp); +end; + +(* Runs the deferred statements in force above base, newest first. *) +proc runDefers(base: INT); +var i: INT; +begin + for i := numDefers - 1 to base by -1 do Gen.runDefer(defers[i]); end; +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. *) +proc loneBreak: BOOL; +var st: Scan.State; lone: BOOL; +begin + if (Scan.tok # Scan.sBreak) or (curLoop = nil) or (numDefers # curLoop^.base) then return false; end; + Scan.saveScan(st); + lone := false; + Scan.next; + if Scan.tok = Scan.sSemicolon then + Scan.next; + lone := (Scan.tok = Scan.sEnd) or (Scan.tok = Scan.sElsif) or (Scan.tok = Scan.sElse); + end; + Scan.restoreScan(st); + return lone; +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. *) +proc thenPart(var x: TItem; var L: INT): ERROR; +begin + try expect(Scan.sThen); + L := Gen.NoLabel; (* stays so with a lone break: there is nothing to skip *) + if loneBreak() then + Chunk.noteLine(Scan.curLine(), Scan.curCol()); (* the jump gets the break's line *) + try Item.condJumpTrue(x, curLoop^.brk); + Scan.next; Scan.next; (* skip "break" and ";" *) + ends := true; + else + try Item.condJump(x, L); + try statements(); + end; + return nil; +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. *) +proc ifStatement(start: Diag.Pos; ind: INT): ERROR; +var x: TItem; L, endL: INT; all: BOOL; +begin + Scan.next; + try expression(x, nil); + try thenPart(x, L); + all := ends; + endL := Gen.NoLabel; + while Scan.tok = Scan.sElsif do + if not ends then Gen.jump(endL); end; + Gen.fix(L); + Scan.next; + try expression(x, nil); + try thenPart(x, L); + all := all and ends; + end; + if Scan.tok = Scan.sElse then + if not ends then Gen.jump(endL); end; + Gen.fix(L); + Scan.next; + if Scan.tok = Scan.sIf then elseIf := true; end; + try statements(); + all := all and ends; + else + Gen.fix(L); + all := false; + end; + try closeEnd(start, ind); + Gen.fix(endL); + ends := all; + return nil; +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). *) +proc whileStatement(start: Diag.Pos; ind: INT): ERROR; +var + x: TItem; top, L, test: INT; lp: Loop; old: PLoop; cond, after: Scan.State; m: Gen.CodeMark; +begin + Scan.next; + Scan.saveScan(cond); + Gen.markCode(m); + try expression(x, nil); + try Item.discard(x); + Gen.rewind(m); + try expect(Scan.sDo); + test := Gen.NoLabel; + Gen.jump(test); + Gen.alignLoop(); + top := Chunk.pc; + enterLoop(lp, old); + try statements(); + curLoop := old; + Scan.saveScan(after); + Scan.restoreScan(cond); + Gen.fix(test); + Chunk.noteLine(Scan.curLine(), Scan.curCol()); + try expression(x, nil); + ends := (x.mode = Item.mConst) and (x.val # 0) and (lp.brk = Gen.NoLabel); (* while true *) + if (x.mode = Item.mConst) and (x.typ^.form = Sym.fBool) then + if x.val # 0 then Gen.jumpBack(top); end; + else + L := Gen.NoLabel; + try Item.condJumpTrue(x, L); + Gen.fixTo(L, top); + end; + Scan.restoreScan(after); + try closeEnd(start, ind); + Gen.fix(lp.brk); + return nil; +end; + +proc repeatStatement: ERROR; +var x: TItem; top, L: INT; lp: Loop; old: PLoop; +begin + Scan.next; + top := Chunk.pc; + enterLoop(lp, old); + try statements(); + curLoop := old; + try expect(Scan.sUntil); + try expression(x, nil); + ends := (x.mode = Item.mConst) and (x.val = 0) and (lp.brk = Gen.NoLabel); (* until false *) + L := Gen.NoLabel; + try Item.condJump(x, L); + Gen.fixTo(L, top); + Gen.fix(lp.brk); + return nil; +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. *) +proc forStatement(start: Diag.Pos; ind: INT): ERROR; +var + o: PObj; v, a, b, s: TItem; step: I64; top, body, bodyL, exitL: INT; + lp: Loop; old: PLoop; f: Sym.Form; slot: I64; +begin + Scan.next; + if Scan.tok # Scan.sIdent then return expected("a name"); end; + o := Sym.lookup(Scan.id); + if o = nil then + notDeclared(Scan.tokPos(), Scan.id); + return Scan.Failed; + end; + named(o); + if o^.cls # Sym.oVar then return Scan.mark(say1("{} isn't a variable", nameOf(Scan.id))); end; + f := o^.typ^.form; + if (f # Sym.fInt) and (f # Sym.fEnum) then + return Scan.mark(say1("a for loop needs an integer or enumeration variable, found {}", Sym.typeName(o^.typ))); + end; + Scan.next; + try expect(Scan.sBecomes); + try Item.makeItem(v, o); + try expression(a, o^.typ); + try Item.coerceExact(a, o^.typ, ""); + try Item.assign(v, a); + try expect(Scan.sTo); + try expression(b, o^.typ); + try Item.coerceExact(b, o^.typ, ""); + (* the limit, evaluated once: a constant as it is, else in a slot *) + if b.mode # Item.mConst then + slot := try Item.toSlot(b); + Item.tempItem(b, b.typ, slot); + end; + step := 1; + if Scan.tok = Scan.sBy then + Scan.next; + try expression(s, nil); + step := try constValue(s); + if step = 0 then return Scan.markAt(s.pos, "the step can't be zero"); end; + end; + try expect(Scan.sDo); + exitL := Gen.NoLabel; + if step > 0 then try Item.forCmp(o, b, Scan.sGtr, exitL); else try Item.forCmp(o, b, Scan.sLss, exitL); end; + bodyL := Gen.NoLabel; + Gen.jump(bodyL); + Gen.alignLoop(); + top := Chunk.pc; + try Item.forStep(o, step); + Gen.fix(bodyL); + body := Chunk.pc; + enterLoop(lp, old); + try statements(); + curLoop := old; + try closeEnd(start, ind); + try Item.forNext(o, b, step, exitL, top, body); + Gen.fix(exitL); + Gen.fix(lp.brk); + return nil; +end; + +type + Labels = record + lo, hi: [MaxLabels]I64; (* the ranges of the labels so far *) + at: [MaxLabels]INT; (* where the arm of each starts *) + n: INT; + end; + +(* a < b, for values of an integer type, unsigned or not *) +proc below(a, b: I64; unsign: BOOL): BOOL; +begin + if unsign then return U64(a) < U64(b); end; + return 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. *) +proc intArm(t: PType; var ls: Labels; var endL: INT): ERROR; +var lo, hi: TItem; first, i: INT; u: BOOL; start: Diag.Pos; +begin + u := not t^.signed; + first := ls.n; + repeat + start := Scan.tokPos(); + try expression(lo, t); + try Item.coerce(lo, t); + _ := try constValue(lo); + hi := lo; + if Scan.tok = Scan.sUpto then + Scan.next; + try expression(hi, t); + try Item.coerce(hi, t); + _ := try constValue(hi); + if below(hi.val, lo.val, u) then return Scan.markAt(Scan.spanFrom(start), "the range is empty"); end; + 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 + return Scan.markAt(Scan.spanFrom(start), say1("{} is in another label too", Diag.source(Scan.spanFrom(start)))); + end; + return Scan.markAt(Scan.spanFrom(start), say1("{} overlaps another label", Diag.source(Scan.spanFrom(start)))); + end; + end; + if ls.n >= MaxLabels then + return Scan.markAt(Scan.spanFrom(start), tooMany(MaxLabels, "labels in one match")); + end; + ls.lo[ls.n] := lo.val; ls.hi[ls.n] := hi.val; + INC(ls.n); + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + try expect(Scan.sColon); + for i := first to ls.n - 1 do ls.at[i] := Chunk.pc; end; + try statements(); + Gen.jump(endL); + return nil; +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. *) +proc dispatch(t: PType; p: I64; var ls: Labels; elseAt: INT; var endL: INT); +var + lo, hi: I64; i, start, v, body: INT; u: BOOL; + entry: [MaxLabels]INT; +begin + u := (t^.form = Sym.fInt) and not t^.signed; + lo := 0; hi := 0; + if ls.n > 0 then + lo := ls.lo[0]; hi := ls.hi[0]; + for i := 1 to ls.n - 1 do + if below(ls.lo[i], lo, u) then lo := ls.lo[i]; end; + if below(hi, ls.hi[i], u) then hi := ls.hi[i]; end; + end; + end; + if (ls.n >= MinTable) and (lo >= -2147483648) and (lo <= 2147483647) + and (U64(hi - lo) < U64(TableDensity * ls.n)) and (hi - lo < MaxLabels) then + start := Gen.jumpTable(p, lo, INT(hi - lo) + 1, elseAt, endL); + for v := 0 to INT(hi - lo) do + if elseAt # Gen.NoLabel then entry[v] := elseAt; else entry[v] := start; end; + end; + for i := 0 to ls.n - 1 do + for v := INT(ls.lo[i] - lo) to INT(ls.hi[i] - lo) do entry[v] := ls.at[i]; end; + end; + for v := 0 to INT(hi - lo) do Gen.tableEntry(start, entry[v]); end; + return; + end; + for i := 0 to ls.n - 1 do + body := Gen.NoLabel; + Item.matchRange(p, ls.lo[i], ls.hi[i], body); + Gen.fixTo(body, ls.at[i]); + end; + if elseAt # Gen.NoLabel then Gen.jumpBack(elseAt); end; +end; + +proc matchStatement(start: Diag.Pos; ind: INT): ERROR; +var + x: TItem; t: PType; c, f, o: PObj; p: I64; L, endL, n, first, disp, elseAt: INT; + seen: [256]BOOL; hasElse, all, byValue: BOOL; endAt: Diag.Pos; ls: Labels; +begin + Scan.next; + try expression(x, nil); + if x.typ^.form = Sym.fConst then try Item.coerce(x, Sym.tI64); end; + p := try Item.matchBegin(x); + t := x.typ; + try expect(Scan.sOf); + hasElse := false; + all := true; + endL := Gen.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 = Sym.fInt) or (t^.form = Sym.fEnum); + disp := Gen.NoLabel; + elseAt := Gen.NoLabel; + if byValue then Gen.jump(disp); end; + while Scan.tok = Scan.sBar do + Scan.next; + if hasElse then return Scan.mark("else must be the last arm"); end; + if Scan.tok = Scan.sElse then + Scan.next; + try expect(Scan.sColon); + elseAt := Chunk.pc; + try statements(); + if byValue then Gen.jump(endL); end; + hasElse := true; + elsif t^.form = Sym.fInt then + try intArm(t, ls, endL); + else + first := ls.n; + L := Gen.NoLabel; + repeat + if Scan.tok # Scan.sIdent then return expected("a case"); end; + c := t^.fields; + while (c # nil) and (c^.name # Scan.id) do c := c^.next; end; + if c = nil then + return Scan.mark(say2("{} isn't a case of {}", nameOf(Scan.id), Sym.typeName(t))); + end; + if (c^.val <= 255) and seen[c^.val] then + return Scan.mark(say1("{} has two arms", nameOf(c^.name))); + end; + if c^.val <= 255 then seen[c^.val] := true; end; + Scan.next; + if t^.form # Sym.fEnum then + Item.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 Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + try Sym.openScope(Sym.newScope()); + if Scan.tok = Scan.sLparen then + Scan.next; + f := c^.fields; + n := 0; + repeat + if Scan.tok # Scan.sIdent then return expected("a name"); end; + if f = nil then + return Scan.mark(say1("more names than {} has fields", nameOf(c^.name))); + end; + o := Sym.newObj(Sym.oVar, Scan.id, f^.typ); + o^.lev := 1; o^.ind := true; o^.isVar := true; + o^.val := p; o^.off := f^.val; + try declare(o); + f := f^.next; + INC(n); + Scan.next; + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + if f # nil then + return Scan.mark(say1("name all the fields of {}, or none", nameOf(c^.name))); + end; + try expect(Scan.sRparen); + end; + try expect(Scan.sColon); + for n := first to ls.n - 1 do ls.at[n] := Chunk.pc; end; + try statements(); + Sym.closeScope(); + Gen.jump(endL); + if t^.form # Sym.fEnum then Gen.fix(L); end; + end; + all := all and ends; + end; + endAt := Scan.tokPos(); + try closeEnd(start, ind); + ends := all; + if (t^.form = Sym.fInt) and not hasElse then + return Scan.markHelp(endAt, "a match on an integer needs an else arm", "it may be empty: | else:"); + end; + if not hasElse then + c := t^.fields; + while c # nil do + if (c^.val > 255) or not seen[c^.val] then + return Scan.markAt(endAt, say1("no arm for {}", nameOf(c^.name))); + end; + c := c^.next; + end; + end; + if byValue then + Gen.fix(disp); + dispatch(t, p, ls, elseAt, endL); + end; + Gen.fix(endL); + return nil; +end; + +(* What a message calls x: its name n when x is just that name, else what + it is. *) +proc subject(x: TItem; n: INT): []U8; +begin + if x.pos.b - x.pos.a = LEN(nameOf(n)) then return nameOf(n); end; + if x.mode = Item.mConst then return "a constant"; end; + return "a value"; +end; + +(* x, named first n, is a variable the program may assign: not an + array constant, nor any part of one. *) +proc assignable(x: TItem; n: INT): ERROR; +begin + if (x.mode = Item.mConst) and (subject(x, n) = nameOf(n)) then + return Scan.markAt(x.pos, say1("{} is a constant, and can't be changed", nameOf(n))); + end; + if (x.mode = Item.mVar) and (x.obj # nil) and (x.obj^.cls = Sym.oConst) then + return Scan.markAt(x.pos, say1("{} is a constant, and can't be changed", nameOf(x.obj^.name))); + end; + if (x.mode # Item.mVar) or not x.isVar then + return Scan.markAt(x.pos, say1("can't assign to {}", subject(x, n))); + end; + return nil; +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. *) +proc leftSide(var x: TItem; var called: BOOL): ERROR; +var o: PObj; wasRead: BOOL; n: INT; +begin + n := Scan.id; + o := Sym.lookup(n); + wasRead := (o # nil) and o^.read; + try designator(x, called); + if ((Scan.tok = Scan.sBecomes) or (Scan.tok = Scan.sComma)) and (x.pos.b - x.pos.a = LEN(nameOf(n))) then + o^.read := wasRead; + end; + return nil; +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 _. *) +proc multiAssign(var x: TItem; first: INT; blank: BOOL): ERROR; +var + d: [16]TItem; dn: [16]INT; blanks: [16]BOOL; + y, z: TItem; n, i: INT; called: BOOL; f: PObj; +begin + n := 0; + d[0] := x; + dn[0] := first; + blanks[0] := blank; + repeat + if not blanks[n] then + try Item.notReadOnly(d[n]); + try assignable(d[n], dn[n]); + try Item.pin(d[n]); (* works out the address now, so that the call can't change it *) + end; + INC(n); + if Scan.tok # Scan.sComma then break; end; + if n > 15 then return Scan.mark(tooMany(16, "variables in one assignment")); end; + Scan.next; + blanks[n] := Scan.tok = Scan.sBlank; + if blanks[n] then + Scan.next; + else + dn[n] := Scan.id; + try leftSide(d[n], called); + end; + until false; + try expect(Scan.sBecomes); + if Scan.tok = Scan.sTry then + try tryCall(y); + called := true; + else + try designator(y, called); + end; + if not called or not y.typ^.tuple or (y.typ^.len # I64(n)) then + return Scan.markAt(y.pos, Diag.say("expected a call with {} results", [Fmt.int(n)])); + 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 = Item.mWords then Gen.swap(); end; + f := y.typ^.fields; + for i := 0 to n - 1 do + z := y; + if y.mode = Item.mWords then + z.mode := Item.mStack; z.typ := f^.typ; + else + try Item.field(z, f); + end; + if blanks[i] then + try Item.discard(z); + else + try Item.coerceExact(z, d[i].typ, "several results go to variables of just their types"); + try Item.assign(d[i], z); + end; + f := f^.next; + end; + return nil; +end; + +(* return a, b; or return f(x); with f's several results passed on *) +proc returnResults: ERROR; +var f: PObj; x: TItem; +begin + f := curResult^.fields; + passOn := true; + while f # nil do + try expression(x, f^.typ); + if x.typ^.tuple then + if not Sym.same(x.typ, curResult) then + return Scan.markAt(x.pos, say2("expected the results {}, found {}", Sym.typeName(curResult), Sym.typeName(x.typ))); + end; + return Item.returnAll(x); + end; + try Item.returnField(f, x); + f := f^.next; + if f # nil then try expect(Scan.sComma); end; + end; + return nil; +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. *) +proc deferStatement: ERROR; +var L, pos, saved: INT; oldLoop: PLoop; oldDeferring: BOOL; start: Diag.Pos; +begin + start := Scan.tokPos(); + Scan.next; + if directDefer then return Scan.markAt(Scan.spanFrom(start), "defer can't be deferred"); end; + if numDefers >= MaxDefers then + return Scan.markAt(Scan.spanFrom(start), tooMany(MaxDefers, "deferred statements in one procedure")); + end; + L := Gen.NoLabel; + pos, saved := Gen.deferBegin(L); + oldLoop := curLoop; oldDeferring := deferring; + curLoop := nil; + deferring := true; + directDefer := true; + try statement(); + directDefer := false; + curLoop := oldLoop; deferring := oldDeferring; + Gen.deferEnd(L, saved); + defers[numDefers] := pos; + INC(numDefers); + return nil; +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). *) +proc changesItself(x: TItem): BOOL; +var st: Scan.State; wasSkipping, changes: BOOL; d: INT; +begin + if (x.mode # Item.mVar) or (x.base # Gen.bReg) or (x.typ^.form = Sym.fSlice) + or (Scan.tok # Scan.sIdent) or (Scan.id # x.obj^.name) then + return false; + end; + changes := false; + Scan.saveScan(st); + wasSkipping := Scan.skipping; + Scan.setSkipping(true); (* its slips are told when it is compiled *) + Scan.next; + if isAddOp() then + changes := true; + d := 0; + while not ((d = 0) and ((Scan.tok = Scan.sSemicolon) or (Scan.tok = Scan.sEnd))) and (Scan.tok # Scan.sEof) do + if (Scan.tok = Scan.sIdent) and (Scan.id = x.obj^.name) then changes := false; end; + match Scan.tok of + | sLparen, sLbrak, sLbrace: INC(d); + | sRparen, sRbrak, sRbrace: DEC(d); + | else: + end; + Scan.next; + end; + end; + Scan.restoreScan(st); + Scan.setSkipping(wasSkipping); + return changes; +end; + +(* A call standing on its own, which drops the results x holds, if any, + to be warned of *) +proc noteDrop(x: TItem); +begin + if (x.mode # Item.mNone) and (numDrops < MaxDrops) then + drops[numDrops].at := x.pos; + if x.typ^.tuple then drops[numDrops].n := INT(x.typ^.len); else drops[numDrops].n := 1; end; + INC(numDrops); + end; +end; + +proc oneStatement: ERROR; +var + x, y: TItem; called: BOOL; m: I64; c: Gen.CallInfo; start: Diag.Pos; first, n, i: INT; k: Gen.Kind; +begin + start := Scan.tokPos(); + first := Scan.id; + Chunk.noteLine(Scan.curLine(), Scan.curCol()); + m := Gen.tempMark(); + ends := false; + match Scan.tok of + | sIdent: + try leftSide(x, called); + if Scan.tok = Scan.sBecomes then + try Item.notReadOnly(x); + try assignable(x, first); + Scan.next; + if changesItself(x) then Gen.setInPlace(x.chunk); end; + try expression(y, x.typ); + Gen.setInPlace(-1); + try Item.assign(x, y); + elsif Scan.tok = Scan.sComma then + try multiAssign(x, first, false); + elsif not called then + if (x.mode = Item.mProc) + or (((x.mode = Item.mVar) or (x.mode = Item.mStack)) and (x.typ^.form = Sym.fProc)) then + try Item.beginCall(c, x); + try Item.endCall(c, x); + try Item.discard(x); + elsif Scan.tok = Scan.sEql then + return Scan.markHelp(x.pos, say1("{} isn't a statement", subject(x, first)), "assignment is written :="); + else + return Scan.markAt(x.pos, say1("{} isn't a statement", subject(x, first))); + end; + else + noteDrop(x); + try Item.discard(x); + end; + | sBlank: + Scan.next; + if Scan.tok = Scan.sComma then + try multiAssign(x, 0, true); + else + try expect(Scan.sBecomes); + try expression(x, nil); + (* evaluated and dropped: a single value is loaded, so that a + volatile one is read *) + if (x.mode = Item.mType) or (x.mode = Item.mBuiltin) or (x.mode = Item.mNone) or (x.mode = Item.mCase) + or ((x.mode # Item.mStr) and not Sym.isAggregate(x.typ)) then + try Item.value(x); + end; + try Item.discard(x); + end; + | sIf: try ifStatement(start, Scan.indent()); + | sWhile: try whileStatement(start, Scan.indent()); + | sRepeat: try repeatStatement(); + | sFor: try forStatement(start, Scan.indent()); + | sMatch: try matchStatement(start, Scan.indent()); + | sReturn: + Scan.next; + if deferring then return Scan.markAt(Scan.spanFrom(start), "return can't leave a deferred statement"); end; + if Scan.tok = Scan.sSemicolon then + runDefers(0); + try Item.returnNone(); + else + if (curResult # nil) and curResult^.tuple then + try returnResults(); + else + try expression(x, curResult); + try Item.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 Sym.behindPointer(curResult) then + n := 1; k := Gen.kindOf(curResult); + if Sym.inTwoRegs(curResult) then n := 2; k := Gen.kWord; end; + if deferSlot = 0 then deferSlot := Gen.allocPerm(16, 8); end; + for i := n - 1 to 0 by -1 do Gen.popVar(Item.frameAdr(deferSlot + I64(8 * i)), 8); end; + runDefers(0); + for i := 0 to n - 1 do Gen.pushVar(Item.frameAdr(deferSlot + I64(8 * i)), 8, false, k); end; + else + runDefers(0); + end; + Gen.returnJump(); + ends := true; + end; + | sBreak: + Scan.next; + if curLoop = nil then return Scan.markAt(Scan.spanFrom(start), "break outside a loop"); end; + runDefers(curLoop^.base); + Gen.jump(curLoop^.brk); + | sDefer: try deferStatement(); + | sTry: + try tryCall(x); + noteDrop(x); + try Item.discard(x); + | sArrow: + return Scan.markHelp(Scan.tokPos(), "a statement starts with a name", + "convert into a pointer variable, then assign through that"); + | else: + if Scan.atLineStart() then + return endMissing(Scan.missingPos(), say1("expected \"end\", found {}", Scan.found())); + end; + return expected("a statement"); + end; + Gen.releaseTemps(m); + return nil; +end; + +proc statement: ERROR; +var r: Recover; m: I64; err: ERROR; +begin + m := Gen.tempMark(); + guard(r); + err := oneStatement(); + if err = nil then + skipped := false; + else + restore(r); + (* a statement never starts a line: this is the next declaration *) + if Scan.atLineStart() or not skipConstruct() then return giveUp(r); end; + Gen.releaseTemps(m); + skipped := true; + end; + unguard(r); + return nil; +end; + +proc endsStatements: BOOL; +begin + match Scan.tok of + | sEnd, sElse, sElsif, sUntil, sBar, sEof: return true; + | else: return false; + end; +end; + +proc statements: ERROR; +var base: INT; old: BOOL; +begin + base := numDefers; + old := directDefer; + directDefer := false; + ends := false; + while not endsStatements() do + try statement(); + if not skipped or (Scan.tok = Scan.sSemicolon) then try expect(Scan.sSemicolon); end; + end; + runDefers(base); + numDefers := base; + directDefer := old; + return nil; +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. *) +proc skipBody: ERROR; +var d: INT; sawBegin: BOOL; +begin + d := 0; + sawBegin := false; + repeat + match Scan.tok of + | sBegin: + if d = 0 then sawBegin := true; end; + INC(d); + | sIf, sWhile, sFor, sMatch, sRecord, sVariant: INC(d); + | sEnd: + DEC(d); + if (d = 0) and sawBegin then + Scan.next; + return nil; + end; + | sEof: return expected("\"end\""); + | else: + end; + Scan.next; + until false; + return nil; +end; + +proc declarations(top: BOOL); 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 ShownRegs[i]; 0 if it isn't shown. *) +proc varKind(o: PObj): INT; +var k, i, v: INT; +begin + match o^.typ^.form of + | fInt: if o^.typ^.signed then k := 1; else k := 2; end; + | fEnum, fSet: k := 2; + | fBool: k := 3; + | fPtr, fProc, fError: k := 4; + | fReal: k := 5; + | else: return 0; + end; + v := k + INT(o^.typ^.size) * 16; + if o^.ind then v := v + 256; end; + for i := 0 to LEN(Gen.ShownRegs) - 1 do + if o^.reg = Gen.ShownRegs[i] then v := k + INT(o^.typ^.size) * 16 + (i + 1) * 512; end; + end; + return v; +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 *) +proc regFit(o: PObj): BOOL; +var f: Sym.Form; +begin + if (o^.cls # Sym.oVar) or o^.ind or o^.ext then return false; end; + f := o^.typ^.form; + return (f = Sym.fInt) or (f = Sym.fBool) or (f = Sym.fEnum) or (f = Sym.fPtr) or (f = Sym.fProc) + or (f = Sym.fError) or (f = Sym.fSlice) or (f = Sym.fReal) + or ((f = Sym.fSet) and (o^.typ^.size <= 8)); +end; + +(* The first local of the procedure being compiled. Locals are chained + by chain 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. *) +proc firstLocal(before: PObj): PObj; +begin + if before = nil then return Sym.curModule^.locals; end; + return before^.chain; +end; + +const MaxCand = 64; (* variables of a procedure that may go in registers *) + +var + cand: [MaxCand]PObj; (* chooseRegs's candidates and their weights *) + weight: [MaxCand]INT; + numCand: INT; + +proc candidate(n: INT): INT; +var j: INT; +begin + for j := 0 to numCand - 1 do + if cand[j]^.name = n then return j; end; + end; + return -1; +end; + +proc addCandidate(o: PObj); +begin + if regFit(o) and (numCand < MaxCand) then + cand[numCand] := o; + weight[numCand] := 0; + INC(numCand); + 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 *) +proc calls(o: PObj): BOOL; +begin + if o = nil then return false; end; + return (o^.cls = Sym.oProc) or ((o^.cls = Sym.oVar) and (o^.typ^.form = Sym.fProc)) + or ((o^.cls = Sym.oBuiltin) and ((o^.val = Sym.bNew) or (o^.val = Sym.bSyscall) or (o^.val = Sym.bCopy))); +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. *) +proc chooseRegs(params, before: PObj); +var + isLoop: [256]BOOL; + i, k, kx, d, loops, best, need: INT; o, q, qual: PObj; st: Scan.State; + afterDot, wasSkipping, leaf: BOOL; +begin + numCand := 0; + o := params; + while o # nil do addCandidate(o); o := o^.next; end; + o := firstLocal(before); + while o # nil do addCandidate(o); o := o^.chain; end; + if numCand = 0 then return; end; + Scan.saveScan(st); + wasSkipping := Scan.skipping; + Scan.setSkipping(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 (Scan.tok = Scan.sIdent) and not afterDot then + q := Sym.lookup(Scan.id); + if calls(q) then leaf := false; end; + qual := nil; + if (q # nil) and (q^.cls = Sym.oModule) then qual := q; end; + elsif (Scan.tok = Scan.sIdent) and (qual # nil) then + if (qual^.home = nil) or calls(Sym.find(qual^.home^.scope, Scan.id)) then leaf := false; end; + qual := nil; + end; + match Scan.tok of + | sBegin, sIf, sMatch, sWhile, sFor, sRepeat: + if d < 255 then + INC(d); + isLoop[d] := (Scan.tok = Scan.sWhile) or (Scan.tok = Scan.sFor) or (Scan.tok = Scan.sRepeat); + if isLoop[d] then INC(loops); end; + end; + | sEnd, sUntil: + if isLoop[d] then DEC(loops); end; + DEC(d); + | sIdent: + if Scan.id = nameAdr then + Scan.next; + if Scan.tok = Scan.sLparen then Scan.next; end; + (* a hugely negative weight bars it from a register, whatever + its uses add *) + if (Scan.tok = Scan.sIdent) and (candidate(Scan.id) >= 0) then weight[candidate(Scan.id)] := -1073741824; end; + elsif not afterDot and (candidate(Scan.id) >= 0) then + k := candidate(Scan.id); + if loops > 2 then INC(weight[k], 64); else INC(weight[k], 1 shl (2 * loops)); end; + end; + | else: + end; + afterDot := Scan.tok = Scan.sPeriod; (* a name after a dot is a field, not a variable *) + if (d > 0) and (Scan.tok # Scan.sEof) then Scan.next; end; + until (d = 0) or (Scan.tok = Scan.sEof); + Scan.restoreScan(st); + Scan.setSkipping(wasSkipping); + if leaf then + o := params; + while o # nil do + k := candidate(o^.name); + if (k >= 0) and (weight[k] >= 0) then Gen.keepArrived(o); end; (* 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 numCand - 1 do + if cand[i]^.typ^.form = Sym.fSlice then weight[i] := weight[i] div 2; end; + end; + (* 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 numCand - 1 do + if (cand[i]^.reg = 0) and (weight[i] >= 3) and ((best < 0) or (weight[i] > weight[best])) then best := i; end; + end; + if best < 0 then break; end; + need := 1; + if cand[best]^.typ^.form = Sym.fSlice then need := 2; end; + if cand[best]^.typ^.form = Sym.fReal then + if kx < 4 then + cand[best]^.reg := Gen.XVarRegs[kx]; + INC(kx); + else + weight[best] := 0; + end; + elsif k + need <= 5 then + cand[best]^.reg := Gen.VarRegs[k]; + if need = 2 then cand[best]^.reg2 := Gen.VarRegs[k + 1]; end; + INC(k, need); + else + weight[best] := 0; (* too big for what is left *) + end; + until false; +end; + +(* The registers the variables of the procedure are in, as bits: bit i + is VarRegs[i], bit XBit + i XVarRegs[i] *) +proc regBits(o: PObj): INT; +var m, k: INT; +begin + m := 0; + for k := 0 to 4 do + if (o^.reg = Gen.VarRegs[k]) or (o^.reg2 = Gen.VarRegs[k]) then m := m | (1 shl k); end; + end; + for k := 0 to 3 do + if o^.reg = Gen.XVarRegs[k] then m := m | (1 shl (Gen.XBit + k)); end; + end; + return m; +end; + +proc regsOf(params, before: PObj): INT; +var o: PObj; m: INT; +begin + m := 0; + o := params; + while o # nil do + m := m | regBits(o); + o := o^.next; + end; + o := firstLocal(before); + while o # nil do + if o^.cls = Sym.oVar then m := m | regBits(o); end; + o := o^.chain; + end; + return 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. *) +proc placeLocals(params, before: PObj); +var o: PObj; +begin + Gen.resetLocals(); + o := firstLocal(before); + while o # nil do + if (o^.cls = Sym.oVar) and (o^.reg = 0) then + o^.val := Gen.allocPerm(o^.typ^.size, o^.typ^.align); + elsif (o^.cls = Sym.oVar) and (o^.reg >= Gen.XmmVar) then + o^.val := Gen.allocPerm(8, 8); + Gen.xHome(o^.reg, o^.val); + end; + o := o^.chain; + end; + o := params; + while o # nil do + if o^.reg >= Gen.XmmVar then Gen.xHome(o^.reg, o^.val); end; + o := o^.next; + end; + Gen.useRegs(regsOf(params, before)); +end; + +proc body(p: PObj; sig: PType; line: INT): ERROR; +var + q, params, last, o, before: PObj; old: PType; st: Scan.State; + mark: Gen.CodeMark; drops0, errs: INT; +begin + try Sym.openScope(Sym.newScope()); + params := nil; last := nil; + q := sig^.fields; + while q # nil do + o := Sym.newObj(Sym.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; end; + last := o; + q := q^.next; + end; + Item.beginProc(sig, params); + deferSlot := 0; + o := params; + while o # nil do + q := o^.next; + try declare(o); + o := q; + end; + curProc := p; + before := Sym.curModule^.lastLocal; + declarations(false); + chooseRegs(params, before); + placeLocals(params, before); + (* the body, made again if a variable in a register must be in memory *) + Scan.saveScan(st); + Gen.markCode(mark); drops0 := numDrops; errs := Diag.errors; + old := curResult; + repeat + Item.setDemoted(false); + try expect(Scan.sBegin); + curResult := sig^.base; + Gen.enterBody(p^.chunk, line); + stray := false; elseIf := false; deferSlot := 0; + try statements(); + p^.openEnd := (curResult # nil) and not ends; + Chunk.noteLine(Scan.curLine(), Scan.curCol()); + try expect(Scan.sEnd); + if not (Item.demoted or Gen.lost) or (Diag.errors # errs) then break; end; + (* a parameter kept where it arrived goes to memory: a call or a copy + wanted its register *) + if Gen.lost then + o := params; + while o # nil do + if Gen.keptIn(o) then o^.reg := 0; o^.reg2 := 0; end; + o := o^.next; + end; + end; + numDrops := drops0; + Gen.redo(mark); + placeLocals(params, before); + Scan.restoreScan(st); + until false; + try Gen.endProc(p^.chunk, p^.openEnd); + (* its parameters and variables, for the trap report *) + o := firstLocal(before); + q := params; + while q # nil do + if varKind(q) # 0 then Chunk.noteVar(p^.chunk, q^.name, INT(q^.val), varKind(q)); end; + q := q^.next; + end; + while o # nil do + if (o^.cls = Sym.oVar) and (varKind(o) # 0) then Chunk.noteVar(p^.chunk, o^.name, INT(o^.val), varKind(o)); end; + o := o^.chain; + end; + curResult := old; + curProc := nil; + Sym.closeScope(); + return nil; +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 *) +proc asmConst(whole: BOOL): (I64, ERROR); +var x: TItem; +begin + if whole then return constExpr(); end; + try factor(x, nil); + if not Sym.isInt(x.typ) then + return 0, Scan.markAt(x.pos, say1("expected an integer constant, found {}", Item.what(x))); + end; + return constValue(x); +end; + +proc codeBody(p: PObj; sig: PType; at: Diag.Pos): ERROR; +var q: PObj; ni, nf: INT; +begin + ni := 0; nf := 0; + q := sig^.fields; + while q # nil do + if not q^.isVar and (q^.typ^.form = Sym.fSlice) then + INC(ni, 2); (* address, then length *) + else + if not q^.isVar and not Sym.isScalar(q^.typ) then + return Scan.markAt(at, "a code procedure takes integers, BOOL, reals, pointers, procedures and slices"); + end; + if (q^.typ^.form = Sym.fReal) and not q^.isVar then INC(nf); else INC(ni); end; + end; + q := q^.next; + end; + if (ni > 6) or (nf > 8) or sig^.variadic then + return Scan.markAt(at, "too many parameters for a code procedure"); + end; + if sig^.base # nil then + if sig^.base^.tuple then + q := sig^.base^.fields; + if (sig^.base^.len # 2) or (q^.typ^.size # 8) or (q^.next^.typ^.size # 8) + or not Sym.isScalar(q^.typ) or not Sym.isScalar(q^.next^.typ) + or (q^.typ^.form = Sym.fReal) or (q^.next^.typ^.form = Sym.fReal) then + return Scan.markAt(at, "a code procedure returns two results only in rax and rdx"); + end; + elsif not Sym.isScalar(sig^.base) and (sig^.base^.form # Sym.fSlice) then + return Scan.markAt(at, "a code procedure returns a single value"); + end; + end; + try Gen.codeProc(p^.chunk, asmConst); + return expect(Scan.sEnd); +end; + +proc procDecl: ERROR; +var n, line: INT; exp: BOOL; sig: PType; p: PObj; at: Diag.Pos; +begin + try instancesFor(false); + line := Scan.curLine(); + Scan.next; + try identDef(n, exp, at); + sig := try signature(); + try expect(Scan.sSemicolon); + p := Sym.find(Sym.topScope(), n); + if (p # nil) and (p^.cls = Sym.oProc) and p^.fwd then + if not Sym.same(p^.typ, sig) then + Diag.error(at, say1("{} doesn't have the signature it was declared forward with", nameOf(n))); + Diag.note(p^.pos, "the signature is here"); + return Scan.Failed; + end; + if Scan.tok = Scan.sForward then return Scan.mark(say1("{} is declared forward twice", nameOf(n))); end; + p^.exported := p^.exported or exp; + else + p := Sym.newObj(Sym.oProc, n, sig); + p^.pos := at; + p^.exported := exp; + if (Sym.curModule^.name = nameRt) and not checkMode and (n = nameFail) then + p^.chunk := Gen.rtFail; + else + p^.chunk := Chunk.newChunk(Chunk.secText, Sym.curModule^.sname, n); + end; + try declare(p); + end; + if Scan.tok = Scan.sForward then + Scan.next; + p^.fwd := true; + return nil; + end; + p^.fwd := false; + if Scan.tok = Scan.sCode then + Scan.next; + p^.isCode := true; + try codeBody(p, sig, at); + elsif checkMode then + try skipBody(); + else + try body(p, sig, line); + end; + if Scan.tok = Scan.sIdent then + if Scan.id = Sym.curModule^.name then + return endMissing(Scan.tokPos(), say1("{} has no \"end\": this one closes the module", nameOf(n))); + elsif Scan.id # n then + return endMissing(Scan.tokPos(), say2("expected {}, found {}", nameOf(n), nameOf(Scan.id))); + end; + Scan.next; + end; + return nil; +end; + +(* An extern procedure or variable: C's, reached through the quadword + that holds its address. *) +proc externDecl: ERROR; +var n: INT; exp: BOOL; o, q: PObj; t: PType; at: Diag.Pos; +begin + Scan.next; + Sym.curModule^.usesC := true; + if Scan.tok = Scan.sProc then + Scan.next; + try identDef(n, exp, at); + willDeclare(n); + inExtern := true; + t := try signature(); + inExtern := false; + q := t^.fields; + while q # nil do + if q^.isVar or not Sym.isScalar(q^.typ) then + return Scan.markAt(at, "C takes integers, BOOL, reals, pointers and procedures"); + end; + q := q^.next; + end; + if (t^.base # nil) and not Sym.isScalar(t^.base) then + return Scan.markAt(at, "C returns a single value"); + end; + o := Sym.newObj(Sym.oProc, n, t); + else + if Scan.tok # Scan.sVar then return expected("\"proc\" or \"var\""); end; + Scan.next; + try identDef(n, exp, at); + willDeclare(n); + try expect(Scan.sColon); + declExported := exp; + t := try parseType(); + declExported := false; + o := Sym.newObj(Sym.oVar, n, t); + end; + o^.pos := at; + o^.exported := exp; + o^.ext := true; + o^.chunk := Chunk.externChunk(n); + return 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: ^U8; + fixes: [MaxFixes]record off, chunk: INT; end; + numFixes: INT; + +proc constFix(off, chunk: INT): ERROR; +begin + if numFixes >= MaxFixes then + return Scan.mark(tooMany(MaxFixes, "addresses in one constant")); + end; + fixes[numFixes].off := off; + fixes[numFixes].chunk := chunk; + INC(numFixes); + return nil; +end; + +(* The n bytes of v, at off in the constant: little-endian, as the machine is *) +proc putBytes(off, n: INT; v: I64); +var src: ^U8; +begin + src := ^U8(ADR(v)); + COPY(constBytes[off..off + n], src[0..n]); +end; + +(* The part of type t at offset off of the constant *) +proc constPart(t: PType; off: INT): ERROR; +var e: TItem; f: PObj; k: INT; r: F32; start: Diag.Pos; src: ^U8; st: INT; +begin + start := Scan.tokPos(); + if (t^.form = Sym.fArray) and (Scan.tok = Scan.sLbrak) then + Scan.next; + k := 0; + if Scan.tok # Scan.sRbrak then + repeat + if I64(k) < t^.len then + try constPart(t^.base, off + k * INT(t^.base^.size)); + else + try constPart(t^.base, off); + end; + INC(k); + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + end; + try expect(Scan.sRbrak); + if I64(k) # t^.len then + return Scan.markAt(Scan.spanFrom(start), Diag.say("expected {} elements, found {}", [Fmt.int(t^.len), Fmt.int(k)])); + end; + return nil; + end; + if (t^.form = Sym.fRecord) and not t^.tuple and (Scan.tok = Scan.sLbrace) then + Scan.next; + if Scan.tok # Scan.sRbrace then + repeat + if Scan.tok # Scan.sIdent then return expected("a field"); end; + f := try fieldOf(t); + Scan.next; + try expect(Scan.sColon); + try constPart(f^.typ, off + INT(f^.val)); + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + end; + return expect(Scan.sRbrace); + end; + try expression(e, t); + if (e.mode = Item.mStr) and ((t^.form = Sym.fSlice) or (t^.form = Sym.fArray)) and (t^.base = Sym.tU8) then + if t^.form = Sym.fSlice then + try constFix(off, e.chunk); + putBytes(off + 8, 8, e.val); + elsif e.val > t^.len then + return Scan.markAt(e.pos, say1("the string is longer than {}", Sym.typeName(t))); + else + st := Chunk.chunks[e.chunk].start; + COPY(constBytes[off..off + INT(e.val)], Chunk.rodata[st..st + INT(e.val)]); + end; + elsif t^.form = Sym.fSlice then + if (e.mode # Item.mVar) or (e.obj = nil) or (e.obj^.cls # Sym.oConst) or (e.typ^.form # Sym.fArray) + or (e.pos.b - e.pos.a # LEN(nameOf(e.obj^.name))) or not Sym.same(e.typ^.base, t^.base) then + return Scan.markAt(e.pos, say1("a constant slice is a string or an array constant of its elements, found {}", Item.what(e))); + end; + try constFix(off, e.chunk); + putBytes(off + 8, 8, e.typ^.len); + elsif t^.form = Sym.fVariant then + return Scan.markAt(e.pos, "a constant holds no variant"); + elsif (t^.form = Sym.fArray) or (t^.form = Sym.fRecord) then + return Scan.markAt(e.pos, say1("expected a literal of {}", Sym.typeName(t))); + else + try Item.coerce(e, t); + if (e.mode = Item.mProc) and not e.obj^.ext then + try constFix(off, e.obj^.chunk); + elsif e.mode # Item.mConst then + return Scan.markAt(e.pos, say1("expected a constant, found {}", Item.what(e))); + elsif (t^.form = Sym.fError) and (e.val > 0) then + try constFix(off, INT(e.val) - 1); + elsif (t^.form = Sym.fPtr) and (e.val # 0) then + return Scan.markAt(e.pos, "a constant pointer is nil"); + elsif (t^.form = Sym.fReal) and (t^.size = 4) then + r := F32(Item.realOf(e)); + src := ^U8(ADR(r)); + COPY(constBytes[off..off + 4], src[0..4]); + else + putBytes(off, INT(t^.size), e.val); + end; + end; + return nil; +end; + +(* The chunk of n, a constant of type t whose literal is next *) +proc aggregateConst(t: PType; n: INT): (INT, ERROR); +var c, i, size: INT; +begin + size := INT(t^.size); + constBytes := Scan.grab(size + 8); + for i := 0 to size + 7 do constBytes[i] := 0; end; + numFixes := 0; + try constPart(t, 0); + c := Chunk.newChunk(Chunk.secRodata, Sym.curModule^.sname, n); + Chunk.setData(c, constBytes, size, INT(t^.align)); + for i := 0 to numFixes - 1 do Chunk.addDataFixup(c, fixes[i].off, fixes[i].chunk, 0); end; + return c, nil; +end; + +proc constDecl(top: BOOL): ERROR; +var n, c: INT; exp: BOOL; x: TItem; o: PObj; t: PType; start, at: Diag.Pos; +begin + try identDef(n, exp, at); + willDeclare(n); + t := nil; + if Scan.tok = Scan.sColon then + Scan.next; + start := Scan.tokPos(); + t := try parseType(); + if (t # Sym.tError) and not ((t^.form = Sym.fArray) or ((t^.form = Sym.fRecord) and not t^.tuple)) then + return Scan.markAt(Scan.spanFrom(start), "only an ERROR, an array or a record constant has a type"); + end; + end; + try expect(Scan.sEql); + if (t # nil) and ((t^.form = Sym.fArray) or (t^.form = Sym.fRecord)) then + o := Sym.newObj(Sym.oConst, n, t); + o^.chunk := try aggregateConst(t, n); + o^.pos := at; + o^.exported := exp and top; + try declare(o); + return expect(Scan.sSemicolon); + end; + try expression(x, nil); + o := Sym.newObj(Sym.oConst, n, x.typ); + o^.pos := at; + o^.exported := exp and top; + if t = Sym.tError then + o^.typ := Sym.tError; + c := try Item.errorChunk(x, Sym.curModule^.sname, n); + o^.val := c + 1; + elsif x.mode = Item.mStr then + o^.val := x.val; + o^.chunk := x.chunk; + else + o^.val := try constValue(x); + end; + try declare(o); + return expect(Scan.sSemicolon); +end; + +proc typeDecl(top: BOOL): ERROR; +var n: INT; exp: BOOL; o: PObj; t: PType; at: Diag.Pos; +begin + try identDef(n, exp, at); + willDeclare(n); + try expect(Scan.sEql); + declExported := exp and top; + inTypes := true; + t := try parseType(); + o := Sym.newObj(Sym.oType, n, t); + o^.pos := at; + o^.exported := exp and top; + if t^.obj = nil then t^.obj := o; end; + try declare(o); + return expect(Scan.sSemicolon); +end; + +proc varDecl(top: BOOL): ERROR; +var + i, k: INT; o: PObj; t: PType; + names: [MaxNames]INT; exps: [MaxNames]BOOL; poss: [MaxNames]Diag.Pos; +begin + k := 0; + repeat + if k >= MaxNames then return Scan.mark(tooMany(MaxNames, "names in one declaration")); end; + try identDef(names[k], exps[k], poss[k]); + willDeclare(names[k]); + INC(k); + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + try expect(Scan.sColon); + declExported := top and exps[0]; + t := try parseType(); + declExported := false; + for i := 0 to k - 1 do + o := Sym.newObj(Sym.oVar, names[i], t); + o^.pos := poss[i]; + o^.exported := exps[i] and top; + o^.isVar := false; + if top then + o^.lev := 0; + o^.chunk := Chunk.newChunk(Chunk.secBss, Sym.curModule^.sname, names[i]); + Chunk.setBss(o^.chunk, INT(t^.size), INT(t^.align)); + else + o^.lev := 1; (* its slot comes from placeLocals, if it needs one *) + end; + try declare(o); + end; + return expect(Scan.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 *) +proc skipProc; +var st: Scan.State; +begin + Scan.next; + if (Scan.tok = Scan.sIdent) and (Sym.find(Sym.topScope(), Scan.id) = nil) then poison(Scan.id); end; + repeat + repeat Scan.next; until Scan.atLineStart() or (Scan.tok = Scan.sEof); + match Scan.tok of + | sProc, sExtern, sEof: return; + | sEnd: + Scan.saveScan(st); + Scan.next; + if Scan.tok = Scan.sIdent then Scan.next; end; + if Scan.tok = Scan.sSemicolon then + Scan.next; + return; + end; + Scan.restoreScan(st); + return; + | else: + end; + until false; +end; + +(* What one declaration, of the kind k, reads *) +proc declarationOf(k: Scan.Sym; top: BOOL): ERROR; +begin + match k of + | sConst: return constDecl(top); + | sType: return typeDecl(top); + | sVar: return varDecl(top); + | sProc: + if not top then return Scan.mark("procedures don't nest"); end; + try procDecl(); + return expect(Scan.sSemicolon); + | sExtern: + if not top then return Scan.mark("extern is only for the top of a module"); end; + try externDecl(); + return expect(Scan.sSemicolon); + | else: return nil; + end; +end; + +(* One declaration, as a recovery point: an error is reported, the + declaration skipped, and reading goes on after it *) +proc declaration(k: Scan.Sym; top: BOOL); +var r: Recover; +begin + guard(r); + numDeclaring := 0; + if declarationOf(k, top) # nil then + restore(r); + if k = Scan.sProc then skipProc(); else skipDeclaration(); end; + end; + unguard(r); +end; + +proc declarations(top: BOOL); +var i: INT; o: PObj; k: Scan.Sym; +begin + repeat + k := Scan.tok; + match k of + | sConst, sVar: + Scan.next; + while Scan.tok = Scan.sIdent do declaration(k, top); end; + | sType: + Scan.next; + numFwd := 0; + while Scan.tok = Scan.sIdent do declaration(Scan.sType, top); end; + inTypes := false; + for i := 0 to numFwd - 1 do + o := Sym.lookup(fwdTypes[i]^.fwd); + if (o = nil) or (o^.cls # Sym.oType) then + notDeclared(fwdPos[i], fwdTypes[i]^.fwd); + fwdTypes[i]^.base := Sym.tPoison; + else + fwdTypes[i]^.base := o^.typ; + named(o); + end; + fwdTypes[i]^.fwd := -1; + end; + | sProc, sExtern: declaration(k, top); + | else: return; + end; + until false; +end; + +(* Modules *) + +(* Whether m is module n with these arguments. *) +proc isModule(m: PModule; n: INT; args: Sym.Args): BOOL; +var i: INT; +begin + if (m^.name # n) or (m^.args.n # args.n) then return false; end; + for i := 0 to args.n - 1 do + if (m^.args.o[i] # args.o[i]) or not Sym.same(m^.args.t[i], args.t[i]) then return false; end; + end; + return true; +end; + +proc findModule(n: INT; args: Sym.Args): PModule; +var m: PModule; +begin + m := firstModule; + while (m # nil) and not isModule(m, n, args) do m := m^.next; end; + return m; +end; + +(* The arguments of an instance: types, or procedures named. *) +proc parseArgs(var args: Sym.Args; mname: []U8): ERROR; +var o: PObj; start: Diag.Pos; +begin + Scan.next; + repeat + if args.n >= 8 then return Scan.mark(say1("too many type arguments for {}", mname)); end; + args.o[args.n] := nil; + start := Scan.tokPos(); + if Scan.tok = Scan.sIdent then + o := try qualIdent(); + if o^.cls = Sym.oProc then + args.o[args.n] := o; + elsif o^.cls # Sym.oType then + return Scan.markAt(Scan.spanFrom(start), say1("{} isn't a type or a procedure", nameOf(o^.name))); + end; + args.t[args.n] := o^.typ; + else + args.t[args.n] := try parseType(); + end; + args.pos[args.n] := Scan.spanFrom(start); + INC(args.n); + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + return expect(Scan.sRparen); +end; + +(* Past an instance's arguments, to be read when it is made *) +proc skipArgs: ERROR; +var p: INT; +begin + p := 0; + repeat + if Scan.tok = Scan.sLparen then + INC(p); + elsif Scan.tok = Scan.sRparen then + DEC(p); + elsif (Scan.tok = Scan.sSemicolon) or (Scan.tok = Scan.sEof) then + return expected("\")\""); + end; + Scan.next; + until p = 0; + return nil; +end; + +(* A generic module's parameters, bound to the instance's arguments: a + type parameter names its type, a procedure parameter its procedure. + The instance's name is the module's with its arguments, List(I64). *) +proc moduleParams(m: PModule): ERROR; +var i: INT; o, a: PObj; sig: PType; s: Buf.Buf; at: Diag.Pos; text: []U8; +begin + Buf.init(ADR(s), Heap.heap); + i := 0; + Buf.str(ADR(s), nameOf(m^.name)); + Buf.add(ADR(s), '('); + Scan.next; + repeat + if Scan.tok # Scan.sIdent then return expected("a name"); end; + if i >= m^.args.n then + return Scan.markAt(m^.args.at, say2("{} needs a type for {}", nameOf(m^.name), nameOf(Scan.id))); + end; + if m^.args.o[i] # nil then + return Scan.markAt(m^.args.pos[i], say2("{} needs a type for {}", nameOf(m^.name), nameOf(Scan.id))); + end; + o := Sym.newObj(Sym.oType, Scan.id, m^.args.t[i]); + o^.used := true; (* a parameter of the module, not a declaration *) + try declare(o); + Buf.str(ADR(s), Sym.typeName(m^.args.t[i])); + Buf.add(ADR(s), ','); + INC(i); + Scan.next; + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + while Scan.tok = Scan.sSemicolon do + Scan.next; + if Scan.tok # Scan.sIdent then return expected("a name"); end; + at := Scan.tokPos(); + o := Sym.newObj(Sym.oProc, Scan.id, nil); + Scan.next; + try expect(Scan.sColon); + try expect(Scan.sProc); + sig := try signature(); + if i >= m^.args.n then + return Scan.markAt(m^.args.at, say2("{} needs a procedure for {}", nameOf(m^.name), nameOf(o^.name))); + end; + a := m^.args.o[i]; + if a = nil then + return Scan.markAt(m^.args.pos[i], say2("{} needs a procedure for {}", nameOf(m^.name), nameOf(o^.name))); + end; + if not Sym.same(a^.typ, sig) then + Diag.error(m^.args.pos[i], say2("{} doesn't have the signature of {}", nameOf(a^.name), nameOf(o^.name))); + Diag.note(at, "the signature is here"); + Diag.finish(); + end; + o^.typ := a^.typ; o^.chunk := a^.chunk; o^.isCode := a^.isCode; o^.ext := a^.ext; + o^.used := true; + try declare(o); + Buf.str(ADR(s), nameOf(a^.home^.name)); + Buf.add(ADR(s), '.'); + Buf.str(ADR(s), nameOf(a^.name)); + Buf.add(ADR(s), ','); + INC(i); + end; + try expect(Scan.sRparen); + if i # m^.args.n then + return Scan.markAt(m^.args.at, say1("too many type arguments for {}", nameOf(m^.name))); + end; + text := Buf.bytes(ADR(s)); + text[LEN(text) - 1] := ')'; + m^.sname := internName(text); + Buf.done(ADR(s)); + return nil; +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. *) +proc warn(o: PObj); +var s, t: []U8; +begin + s := nameOf(o^.name); + if (o^.cls = Sym.oProc) and o^.openEnd then + Diag.warning(o^.pos, say1("{} may reach its end without return, and then returns zero", s)); + end; + if o^.exported or (s[0] = '_') then return; end; + if o^.used and (o^.read or (o^.cls # Sym.oVar) or o^.isVar or o^.ext) then return; end; + match o^.cls of + | oConst: t := say1("constant {}", s); + | oType: t := say1("type {}", s); + | oVar: + if o^.param then t := say1("parameter {}", s); else t := say1("variable {}", s); end; + | oProc: t := say1("procedure {}", s); + | oModule: t := say1("module {}", s); + | else: return; + end; + if o^.used then + Diag.warning(o^.pos, say1("{} is assigned but never read", t)); + elsif o^.cls = Sym.oModule then + Diag.warning(o^.pos, say1("{} is imported but never used", t)); + else + Diag.warning(o^.pos, say1("{} is never used", t)); + end; + if not o^.used and (o^.param or o^.ind) then + Diag.help(say1("if it must be there, call it _{}", s)); + end; +end; + +(* Warns of the call at p, which drops its n results *) +proc dropped(p: Diag.Pos; n: INT); +var s, blanks: []U8; i: INT; +begin + s := Diag.source(p); + i := 0; + while (i < LEN(s)) and (s[i] # '(') do INC(i); end; + if i < LEN(s) then s := s[0..i]; end; + blanks := "_"; + for i := 2 to n do blanks := say1("{}, _", blanks); end; + if n = 1 then + Diag.warning(p, say1("the result of {} is dropped", s)); + else + Diag.warning(p, say1("the results of {} are dropped", s)); + end; + Diag.help(say2("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. *) +proc warnings(m: PModule; firstDrop: INT); +var a, b: PObj; n: PModule; i: INT; +begin + n := firstModule; + while (n # nil) and (n^.name # m^.name) do n := n^.next; end; + if n # nil then return; end; + 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 + dropped(drops[i].at, drops[i].n); + INC(i); + elsif (b = nil) or ((a # nil) and (a^.pos.a < b^.pos.a)) then + warn(a); + a := a^.chain; + else + warn(b); + b := b^.chain; + end; + end; +end; + +(* Modules being compiled, not yet finished: for finding a cycle. *) +var + pending: [MaxPending]PModule; + numPending: INT; + +proc exists(path: []U8): BOOL; +var info: Sys.Info; err: INT; +begin + info, err := Sys.info(path); + return (err = 0) and info.file; +end; + +(* Which file path is, as its device and inode: two names of one file + have the same. Zero for a file that can't be asked about. *) +proc identity(path: []U8): (INT, INT); +var a: [4096]U8; st: [18]INT; (* struct stat: st_dev, then st_ino *) +begin + if LEN(path) >= 4096 then return 0, 0; end; + COPY(a[0..LEN(path)], path); + a[LEN(path)] := 0; + if SYSCALL(4, ADR(a[0]), ADR(st)) < 0 then return 0, 0; end; + return st[0], st[1]; +end; + +(* s, in memory that is never freed, for what must outlast the buffer it is in *) +proc keep(s: []U8): []U8; +var p: ^U8; +begin + if LEN(s) = 0 then return ""; end; + p := Scan.grab(LEN(s)); + COPY(p[0..LEN(s)], s); + return p[0..LEN(s)]; +end; + +proc importModule(name: INT; args: Sym.Args): (PModule, ERROR); forward; + +(* 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. *) +proc compileFile(path: []U8; n: INT; args: Sym.Args; checkOnly: BOOL): (PModule, ERROR); +var + st: Scan.State; saved: [Sym.MaxDepth]INT; d: INT; + oldMod: PModule; oldCheck, oldChecks: BOOL; m: PModule; + lib: ^Sym.Lib; start: Diag.Pos; alias, mname, line, oldPath: INT; o: PObj; bodyChunk: INT; iargs: Sym.Args; + generic: BOOL; argsAt: Scan.State; why: []U8; firstDrop: INT; +begin + firstDrop := numDrops; + Scan.saveScan(st); + d := Sym.saveScopes(saved[0..Sym.MaxDepth]); + oldMod := Sym.curModule; oldCheck := checkMode; oldPath := Chunk.curFilePath(); oldChecks := Item.checks; + Item.setChecks(true); + Chunk.setCurFile(internName(path)); + why := Scan.open(path); + if LEN(why) # 0 then Diag.fatal(say2("can't read {}: {}", path, why)); end; + NEW(m, Heap.heap); + m^.name := n; + m^.sname := n; + m^.args := args; + m^.scope := Sym.newScope(); + m^.path := path; + m^.body := -1; + m^.checkOnly := checkOnly; + Sym.setCurModule(m); + checkMode := checkOnly; + if not checkOnly then + if numPending >= MaxPending then + return nil, Scan.mark(tooMany(MaxPending, "imports nested deep")); + end; + pending[numPending] := m; + INC(numPending); + end; + try Sym.openScope(m^.scope); + Scan.next; + try expect(Scan.sModule); + if (Scan.tok # Scan.sIdent) or (Scan.id # n) then + return nil, Scan.mark(say2("expected module {}, found {}", nameOf(n), Scan.found())); + end; + Scan.next; + (* the module first pending is the one named on the command line, + which nothing imports, so no arguments come with it *) + if (Scan.tok = Scan.sLparen) and not checkOnly and (numPending = 1) then + return nil, Scan.mark(say1("{} is generic: it is compiled where a module imports it", nameOf(n))); + elsif Scan.tok = Scan.sLparen then + try moduleParams(m); + elsif args.n > 0 then + return nil, Scan.markAt(args.at, say1("{} isn't generic", nameOf(n))); + end; + try expect(Scan.sSemicolon); + while Scan.tok = Scan.sImport do + Scan.next; + repeat + if Scan.tok # Scan.sIdent then return nil, expected("a module name"); end; + start := Scan.tokPos(); + alias := Scan.id; + mname := Scan.id; + iargs.n := 0; + generic := false; + Scan.next; + if Scan.tok = Scan.sBecomes then + Scan.next; + if Scan.tok # Scan.sIdent then return nil, expected("a module name"); end; + mname := Scan.id; + Scan.next; + if Scan.tok = Scan.sLparen then + generic := true; + Scan.saveScan(argsAt); + try skipArgs(); + end; + end; + iargs.at := Scan.spanFrom(start); + o := Sym.newObj(Sym.oModule, alias, nil); + o^.pos := start; + try declare(o); + if not generic then + o^.home := try importModule(mname, iargs); + addImport(m, o^.home); + else + o^.home := nil; (* until the instance is made, at its first use *) + if numDeferred >= MaxDeferred then + return nil, Scan.mark(tooMany(MaxDeferred, "generic imports")); + end; + deferred[numDeferred].o := o; + deferred[numDeferred].home := m; + deferred[numDeferred].mname := mname; + deferred[numDeferred].args := argsAt; + deferred[numDeferred].at := iargs.at; + INC(numDeferred); + end; + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + try expect(Scan.sSemicolon); + end; + while Scan.tok = Scan.sLink do + Scan.next; + if (Scan.tok = Scan.sIdent) and (Scan.id = nameStatic) then + m^.linkStatic := true; + elsif Scan.tok = Scan.sString then + NEW(lib, Heap.heap); + lib^.name := internName(Scan.strBytes()); + lib^.next := m^.libs; + m^.libs := lib; + m^.usesC := true; + else + return nil, expected("a library or \"static\""); + end; + Scan.next; + try expect(Scan.sSemicolon); + end; + (* check off;: the module's index and slice checks left out; neither + word is reserved *) + if (Scan.tok = Scan.sIdent) and (Scan.id = nameCheck) then + Scan.next; + if (Scan.tok # Scan.sIdent) or (Scan.id # nameOff) then return nil, expected("\"off\""); end; + Scan.next; + try expect(Scan.sSemicolon); + Item.setChecks(false); + end; + declarations(true); + if Scan.tok = Scan.sBegin then + if checkMode then + try skipBody(); + else + try instancesFor(true); + line := Scan.curLine(); + Scan.next; + bodyChunk := Chunk.newChunk(Chunk.secText, m^.sname, nameBody); + m^.body := bodyChunk; + Item.beginProc(tBodySig, nil); + deferSlot := 0; + curResult := nil; + Gen.enterBody(bodyChunk, line); + stray := false; elseIf := false; + try statements(); + Chunk.noteLine(Scan.curLine(), Scan.curCol()); + try expect(Scan.sEnd); + try Gen.endProc(bodyChunk, false); + end; + else + try expect(Scan.sEnd); + end; + if (Scan.tok # Scan.sIdent) or (Scan.id # n) then + return nil, endMissing(Scan.missingPos(), say2("expected {}, found {}", nameOf(n), Scan.found())); + end; + Scan.next; + if Scan.tok # Scan.sPeriod then return nil, expected("\".\""); end; + o := m^.first; + while o # nil do + if (o^.cls = Sym.oProc) and o^.fwd then + Diag.error(Scan.tokPos(), say1("{} is declared forward but never defined", nameOf(o^.name))); + end; + o := o^.chain; + end; + if (Diag.errors = 0) and not checkOnly then warnings(m, firstDrop); end; + numDrops := firstDrop; + if Diag.errors > 0 then Diag.finish(); end; (* a module with errors stops the compiler after it *) + Sym.closeScope(); + m^.done := true; + if not checkOnly then + DEC(numPending); + if lastModule = nil then firstModule := m; else lastModule^.next := m; end; + lastModule := m; + end; + Sym.setCurModule(oldMod); checkMode := oldCheck; Chunk.setCurFile(oldPath); Item.setChecks(oldChecks); + Sym.restoreScopes(d, saved[0..Sym.MaxDepth]); + Scan.restoreScan(st); + return m, nil; +end; + +(* The interface check: b must export just what a does. *) +proc compareIface(a, b: PModule); +var o, q: PObj; +begin + o := a^.first; + while o # nil do + if o^.exported then + q := Sym.find(b^.scope, o^.name); + if (q = nil) or not q^.exported or (Sym.fingerprint(o) # Sym.fingerprint(q)) then + Diag.fatal(Diag.say("{}: {} isn't exported as in {}", [Fmt.str(b^.path), Fmt.str(nameOf(o^.name)), Fmt.str(a^.path)])); + end; + end; + o := o^.chain; + end; + q := b^.first; + while q # nil do + o := Sym.find(a^.scope, q^.name); + if q^.exported and ((o = nil) or not o^.exported) then + Diag.fatal(Diag.say("{}: {} isn't exported by {}", [Fmt.str(b^.path), Fmt.str(nameOf(q^.name)), Fmt.str(a^.path)])); + end; + q := q^.chain; + end; +end; + +(* Reads every other file of module n in dir, and checks its interface + against m, compiled from the file named chosen. *) +proc checkSiblings(dir, chosen: []U8; n: INT; m: PModule; args: Sym.Args): ERROR; +var + dp: Sys.Dir; e, prefix: []U8; i, numOthers: INT; more: BOOL; sib: PModule; + others: [32][]U8; +begin + prefix := say1("{}.", nameOf(n)); + numOthers := 0; + if Sys.openDir(ADR(dp), dir) # 0 then return nil; end; + repeat + e, more := Sys.nextEntry(ADR(dp)); + if not more then break; end; + if (LEN(e) > 4) and Str.hasPrefix(e, prefix) and (e[LEN(e) - 4..LEN(e)] = ".raz") + and (e # chosen) and (numOthers < 32) then + others[numOthers] := keep(e); + INC(numOthers); + end; + until false; + Sys.closeDir(ADR(dp)); + for i := 0 to numOthers - 1 do + sib := try compileFile(say2("{}/{}", dir, others[i]), n, args, true); + compareIface(m, sib); + end; + return nil; +end; + +(* The directories searched for modules, in order, from -1 to numInc *) +proc searchDir(i: INT): []U8; +begin + if i = -1 then return mainDir; end; + if i = numInc then return libDir; end; + return incDirs[i]; +end; + +(* The file of module n in dir that suffix j says: Name.linux-x86_64.raz + for a file of this target alone, and so on to Name.raz *) +proc fileName(n, j: INT): []U8; +begin + return Diag.say("{}{}.raz", [Fmt.str(nameOf(n)), Fmt.str(Suffixes[j])]); +end; + +proc moduleFile(n: INT): ([]U8, []U8, BOOL); +var i, j: INT; dir, f: []U8; +begin + for i := -1 to numInc do + dir := searchDir(i); + for j := 0 to 3 do + f := fileName(n, j); + if exists(say2("{}/{}", dir, f)) then return dir, f, true; end; + end; + end; + return "", "", 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) *) +proc checkOneModule(n: INT; dir, f: []U8; at: Diag.Pos): ERROR; +var + i, j, dev, ino, mineDev, mineIno: INT; past, chosen: BOOL; g, files, others: []U8; +begin + mineDev, mineIno := identity(say2("{}/{}", dir, f)); + others := ""; + past := false; + for i := -1 to numInc do + if past then + files := ""; + chosen := false; + for j := 0 to 3 do + g := say2("{}/{}", searchDir(i), fileName(n, j)); + if exists(g) then + files := say2("{} and {}", files, Diag.shownPath(g)); + dev, ino := identity(g); + chosen := chosen or ((dev = mineDev) and (ino = mineIno)); + end; + end; + if not chosen then others := say2("{}{}", others, files); end; + end; + past := past or (searchDir(i) = dir); + end; + if LEN(others) = 0 then return nil; end; + Diag.error(at, say3("module {} is in {}{}", nameOf(n), Diag.shownPath(say2("{}/{}", dir, f)), others)); + Diag.help("a program has one module of each name; a symbolic link to one of these files chooses it"); + return Scan.Failed; +end; + +proc importModule(name: INT; args: Sym.Args): (PModule, ERROR); +var m: PModule; i: INT; dir, f, where: []U8; found: BOOL; +begin + m := findModule(name, args); + if m # nil then return m, nil; end; + for i := 0 to numPending - 1 do + if isModule(pending[i], name, args) then + return nil, Scan.markAt(args.at, say1("{} imports itself", nameOf(name))); + end; + end; + dir, f, found := moduleFile(name); + if not found then + Diag.error(args.at, say1("can't find module {}", nameOf(name))); + where := Diag.shownPath(searchDir(-1)); + for i := 0 to numInc do where := say2("{}, {}", where, Diag.shownPath(searchDir(i))); end; + Diag.help(say2("looked for {}.raz in {}", nameOf(name), where)); + return nil, Scan.Failed; + end; + try checkOneModule(name, dir, f, args.at); + m := try compileFile(say2("{}/{}", dir, f), name, args, false); + try checkSiblings(dir, f, name, m, args); + return m, nil; +end; + +proc addImport(m, im: PModule); +var imp: ^Sym.Import; +begin + NEW(imp, Heap.heap); + imp^.home := 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. *) +proc makeInstance(i: INT; at: Diag.Pos): ERROR; +var + d: Deferred; st: Scan.State; args: Sym.Args; types, exported, ext, wasQuiet: BOOL; nf, nd: INT; + ft: [MaxFwd]PType; fp: [MaxFwd]Diag.Pos; decl: [MaxNames]INT; +begin + d := deferred[i]; + DEC(numDeferred); + deferred[i] := deferred[numDeferred]; + Scan.saveScan(st); + Scan.restoreScan(d.args); + args.n := 0; + making := true; useAt := at; + try parseArgs(args, nameOf(d.mname)); + making := false; + Scan.restoreScan(st); + args.at := d.at; + types := inTypes; exported := declExported; ext := inExtern; wasQuiet := Diag.quiet; + nf := numFwd; ft := fwdTypes; fp := fwdPos; nd := numDeclaring; decl := declaring; + d.o^.home := try importModule(d.mname, args); + inTypes := types; declExported := exported; inExtern := ext; Diag.setQuiet(wasQuiet); + numFwd := nf; fwdTypes := ft; fwdPos := fp; numDeclaring := nd; declaring := decl; + addImport(Sym.curModule, d.o^.home); + return nil; +end; + +proc firstUse(o: PObj; at: Diag.Pos): ERROR; +var i: INT; +begin + for i := 0 to numDeferred - 1 do + if deferred[i].o = o then return makeInstance(i, at); end; + end; + return Scan.Failed; (* 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. *) +proc instancesFor(wholeRest: BOOL): ERROR; +var st: Scan.State; d, i: INT; begun: BOOL; +begin + if checkMode then return nil; end; + i := numDeferred - 1; + while (i >= 0) and (deferred[i].home # Sym.curModule) do DEC(i); end; + if i < 0 then return nil; end; + (* 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. *) + Scan.saveScan(st); + d := 0; begun := false; + repeat + match Scan.tok of + | sIdent: + for i := numDeferred - 1 to 0 by -1 do + if (deferred[i].home = Sym.curModule) and (deferred[i].o^.name = Scan.id) then + try makeInstance(i, Scan.tokPos()); + end; + end; + | sBegin: + begun := begun or (d = 0); + INC(d); + | sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: INC(d); + | sEnd, sUntil: DEC(d); + | else: + end; + if not wholeRest and (d = 0) and (begun or (Scan.tok = Scan.sForward) or (Scan.tok = Scan.sCode)) then break; end; + Scan.next; + until Scan.tok = Scan.sEof; + Scan.restoreScan(st); + return nil; +end; + +(* The main module, from the file at path, and Rt, which every program + needs, first *) +proc compileMain*(path: []U8): (PModule, ERROR); +var base: []U8; i, n: INT; none: Sym.Args; m: PModule; +begin + none.n := 0; + i := LEN(path); + while (i > 0) and (path[i - 1] # '/') do DEC(i); end; + if i = 0 then mainDir := "."; else mainDir := path[0..i - 1]; end; + base := path[i..LEN(path)]; + i := 0; + while (i < LEN(base)) and (base[i] # '.') do INC(i); end; + base := base[0..i]; + if LEN(base) = 0 then Diag.fatal(say1("no module in {}", path)); end; + n := internName(base); + none.at := Scan.tokPos(); + if n # nameRt then _ := try importModule(nameRt, none); end; + m := findModule(n, none); + if m # nil then return m, nil; end; + return compileFile(path, n, none, false); +end; + +begin + nameRt := internName("Rt"); + nameFail := internName("fail"); + nameAdr := internName("ADR"); + nameBody := internName("body"); + nameStatic := internName("static"); + nameCheck := internName("check"); + nameOff := internName("off"); + tArgv := newPtr(newPtr(Sym.tU8, false), false); + tBodySig := Sym.newType(Sym.fProc, 8, 8); +end Parse. diff --git a/src/README.md b/src/README.md new file mode 100644 index 0000000..d6a2cc6 --- /dev/null +++ b/src/README.md @@ -0,0 +1,195 @@ +# src: the compiler in raz + +The port of the Pascal compiler, the **seed** in `../seed/`, to raz. +`../PLAN.md`, "Self", says what it is for and the order of its units. + +One module to a seed unit, with the seed's name, written to the same +rules: plain code, each module opening with what it is, what it +depends on and what it leaves out. The seed is never edited from here. + + make self # each unit against the seed's, on the same files + make self-bench # the scanner's speed against the seed's + make fixpoint # the seed builds self, that builds self, that builds it again + +`Chunk` and `Sym` have no input files to read, so each has a dumper +pair, `test/ChunkDump` and `test/SymDump`, that runs one fixed +pseudo-random script of calls on its side and prints all it made or +answered (`Sym` also ends, as an argument says, in the error of a name +declared twice or of too many scopes): the output, the messages and +the status must be the same. `Link` and `Elf` are tested by +`test/LinkDump`, which makes a program of chunks by a script and writes +it as a static, a dynamic and a stripped executable, which must be the +same file; `X64` by `test/X64Dump`, every encoder with operands from a +script, bytes, fixups and listing, and by `test/AsmDump` on the files +`test/genasm.py` makes: a long run of every instruction the assembler +knows, and a file for each of its errors. +`Gen` is tested by `test/GenDump`, a script of calls, valid by +construction (an expression pushes its operands and then operates; a +statement leaves the stack as it found it), that compiles 80 procedures +with every kind of expression, statement, call, check, frame and defer, +and the entry point, static and dynamic: the bytes, fixups, line notes +and listing must be the same. +`Item` is tested by `test/ItemDump`, a script of operands and operations +with mistakes among them (a constant, a variable in the frame, a +register, a slot, another module's or C's, a string, a procedure, a +selector through a pointer, a field, an element or a slice, a call, a +`match`, a `for`, `return`, `COPY`, a variant): each step shows what +it gave, or its message, and goes on, as the parser does after an +error. What each step gave, the messages, and the bytes, fixups, line +notes and listing of the code must be the same, over 60 scripts (a +run ends at its 20th error, as a compile does). The text its messages +point into is `test/ItemDump.txt`. + +`Parse` and `Raz`, the last two units, are tested whole: the seed builds +`src/Raz.raz` into `build/self/raz.self`, and each compiler, run as +`build/cmp/raz` (a program holds the paths it was made from, and the +library is found beside the compiler), compiles the library, the +examples, the tools, `src/` itself, every test of `test/` and +`conform/`, and the 348,025-line program of `test/genbench.py`, with the +options each test has. The executable, the messages, and the status +must be the same for every file: 409 of them, 289 of which are errors. +`make self-bench` gives the speed of both. + +`make fixpoint` (`fixpoint.sh`) is the proof that the port is whole: +the seed builds `Raz.raz` (stage 1), stage 1 builds it (stage 2), and +stage 2 builds it again (stage 3). Stages 2 and 3 must be the same +file; they are, and so is stage 1, since the seed and the port make the +same code. Stage 3 then stands in for `./raz`, and `make check` and +`make bench` run on it. Each stage is built by the same command in the +same place, since a program holds the paths it was made from. + +`check.sh` builds a dumper for each side, `test/ScanDump.pas` over the +seed's units and `test/ScanDump.raz` over these, and has both read the +library, the examples, every test of the compiler and a file for each +message the scanner makes (`test/genlex.py`) and for hundreds of reals +that are hard to read exactly (`test/genreals.py`): the output, the +messages and the status must be the same. + +## What the port found + +Not the seed's to mend; for the owner to choose. + +- **Names.** An exported variable is read-only outside its module, so + what the parser sets in the seed's `diag` and `scan` (`quiet`, + `werror`, `recovery`, `skipping`) have setters. The `sbuf` array, + which can't be sliced outside, is `strBytes`. +- **Going on after an error.** raz has no `setjmp`, and the seed's parser + ends its errors in a jump back to the statement or declaration being + read, which is how it reports up to 20 errors in a run. The language + gained `try` (report 2026-10.20) for this: `Scan.mark` and the others + show the error and return `Scan.Failed`, which the parser passes up + with `try` to where it reads on. `test/Recover.raz` is the pattern. +- **`NO_COLOR` set to nothing.** `Sys.env` gives "" for a variable that + is unset and for one that is empty, so the port reads the second as + the first. no-color.org says a variable that is empty doesn't turn + colour off, so the port is the one that follows it and the seed + differs; no test depends on either. +- **Strings are slices.** A message is a `[]U8` made by `Diag.say`, + which keeps what it makes: messages are made only to be shown. A name + from `nameOf` stays valid, since names are kept in chunks that are + never moved; the seed's was a copy. +- **Reserved words as names.** The seed's `code` (the text buffer of + `Chunk`) is `text`; `module` (a record's, an import's) is `home`; an + object's `link` is `chain`. A seed type `TName` is `Name`, and the + procedures begin in lower case, as `Scan`'s do. +- **Errors in `Sym`.** `insert` (a name declared twice) and `openScope` + (too many scopes) show the error and return `Scan.Failed`, as `mark` + does, for the parser to pass up with `try`. `saveScopes` returns what + the seed's `var d` gave. +- **Setters.** What other units set in `Chunk` has one each (`setLive`, + `setAdr`, `setReals`, `setSaves`, `setCurFile`, and `rewindTo` for + gen's `Redo` and `Rewind`), and `Sym` has `setCurModule`. `Scan.grab` + is exported for the memory they all take. +- **No `continue`.** The seed's loops that skip to the next round + (`MarkLive`, the line program, the assembler's statements) have the + rest of the body in an `else`, or in a procedure of its own. +- **`X64`.** `code` of `Chunk` being reserved, its text is `Chunk.text`; + `Say` and the rest of the encoder keep their names, in lower case. + `ConstFn`, the parser's reader of a constant, returns an `ERROR` too, + and `assemble` returns what it passes up. `mem` marks an offset beyond + 32 bits and goes on, since an operand has nowhere to return an error + to; the compile ends with the message shown. The listing's text is + made by `Diag.say`, which keeps it, and only when `-S` asks for it. +- **`Link` and `Elf`.** What `raz.pas` set there has a setter each: + `Link.setPlaces`, `Elf.needLib`, `noLibs`, `setMainPath`, + `setStripped` and `X64.setListing`. The file is written by + `Files.write` and made executable by `Sys.chmod`, in place of one + `open` with mode 755 (which the umask would trim). +- **`Gen`.** The seed's `Mark` in the middle of a push or a check + can't give an error back: `newEntry` (the stack's 256 places) and + `check` (4,096 checks a procedure) show it and go on without doing + what they couldn't, and the parser's `resetStack` makes the stack + right again; `endProc` returns its error ("frame too big") and + `codeProc` the assembler's. A `var` out of the seed became a result + (`topConst`, `operands`, `deferBegin`); the labels, which are chains + that a call extends, stay `var`. `inPlace` has a setter. The seed's + `Call` record is `CallInfo` (the procedure is `call`) and `TLink` is + `Link`. A `match` on an enumeration takes one name to an arm, and a + set holds at most 64 names, so `Scan.Sym` (over 64) has none: the + seed's sets of its names are chains of `=`. +- **`Item`.** The seed's `Mark` ended in a jump, so here every + routine that can find an error returns an `ERROR` as its last result + and the ones that call it pass it up with `try`; `Item` shows the + message and returns what the seed jumped out of, so a script that + goes on after an error sees the same state. The seed's `Mismatch` of + two operands is `mismatchOps`, `demoted` and `checks` have setters, + and `matchBegin`, `toSlot` and `errorChunk` return their value and + the error. `op2` has a parameter it never read, now `_L`. A message + is made by `Diag.say` from strings, with no `shortstring` to add up. + A `Mark` with no place is at the scanner's, as in the seed. +- **No `const` parameter.** The seed's `const x: TItem` is a value + parameter here, so an item of about 130 bytes is copied at each call + of `what`, `adrOf`, `notValue` and the others. The result is the + same; whether the compiler built from this is slower for it is for + the speed test of step 4 to say. A `const` parameter (a hint that + the callee won't change it, so that the caller may pass its address) + would be a language change: it goes on the wish list. +- **`Parse` and the seed's jumps.** The seed's `Guard`, `setjmp` and + `longjmp` are `guard`, a record of what to put back, and the `ERROR` + that comes up through `try` to the statement or declaration that is + the recovery point (`statement`, `declaration`), which looks at it, + puts the state back (`restore`) and skips ahead, as the seed does. + `giveUp`, the seed's `GiveUp`, returns the error on to the next one, + or ends the compile if there is none (`guards` counts them). A routine + that can't fail has no `ERROR` (`declarations`, `declaration`). The + seed's nested procedures (`ChooseRegs`'s three) are procedures of the + module with its candidates in variables. `defer` and `module` being + words, the seed's `Defer` is `deferStatement`. A message is made + from strings with `Diag.say`, which has no shortstring to add up to. + `Scan.skipping` is exported to be read, and `Scan.strWithZero` gives + `Item.makeStr` a pointer to a string that may be empty: the seed's + `@sbuf` indexed nothing, and `ADR(Scan.strBytes()[0])`, which the + port of `Item` had, stopped on `""`. +- **`Raz`.** The program is `proc main*: INT`. Where it is, for the + library beside it, it reads from `/proc/self/exe` as FPC's `ParamStr(0)` + does: `Files.arg(0)` is what the shell was typed, and `./raz` made the + library `./lib`, so the same program held other paths in its file. + `raz run` writes the memfd with `Elf.writeElf` and executes it with + the system call, `execve`, which `Sys` has no procedure for. The + version is the module `Version`, which `check.sh` makes in + `build/self/` from `build/version.inc`, as the seed's `{$I}` is. + Two names of a file, for a module found in two places, are told by + the device and inode `SYSCALL` `stat` gives, which `Sys.info` lacks. +- **Sets of `Scan.Sym`.** It has 76 names and a set holds 64, so the + operators a rule names are chains of `=` or the helpers `oneOf` and + `isRel`. (A `match` arm with several names, which the seed's `case` + has, was added to the report for this: 2026-10.21.) +- **Strings made by the compiler.** A joined string (`"a" + "b"`) and + an error's text are built in memory from `Scan.grab`, which is never + freed, in place of `GetMem` and `FreeMem`; the compiler runs once. +- **No bit cast.** A real's bits and back go through a pointer. +- **Speed.** On the 348,025 lines of `test/genbench.py`, 7.6 MB, the + seed's scanner takes 75 ms and this one 74. It took 121 at first. + What closed the gap, in the source: a byte loop in place of the slice + comparison `a[0..n] = b[0..n]` (97 ms), a 256-entry table for the + bytes of a name (84), and one for the symbols that are a byte each + (75). What is left for the code generator, which would help every + module: the slice comparison is slower than the loop it stands for. + On the whole compiler, the same 348,025 lines take 427 ms with the + seed's and 770 with this one (452,000 lines a second, over the 400,000 + the budget wants): `Scan.tokPos`, a record of three words returned + through a pointer, is 9% of it, and the rest is spread thin; the + `const` parameter of `Item` isn't what stands out. + (The seed's `match` on an integer was a chain of compares, each + loading the selector from the frame and jumping over a `jmp`, where + FPC makes a jump table; now it makes one too.) diff --git a/src/Raz.raz b/src/Raz.raz new file mode 100644 index 0000000..a074f07 --- /dev/null +++ b/src/Raz.raz @@ -0,0 +1,273 @@ +(* Raz: 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, and Version, a module the build makes + (build/self/Version.raz) from what git describe says, as the seed's + build/version.inc is. + Leaves out: the work itself; the other units compile, link and + write, and this only reads the command line and runs them in order. *) +module Raz; +import Sys, Out, Version, Files, Fmt, Diag, Scan, Sym, Chunk, X64, Gen, Parse, Link, Elf; + +const + Report = "2026-10.21"; (* the version of doc/raz.md it follows *) + MemfdCreate = 319; (* the system call *) + MfdCloexec = 1; (* an ELF still executes: the kernel opens it first *) + Execve = 59; + +var + links: [4]Gen.Link; + numLinks: INT; + +proc say1(f, a: []U8): []U8; +begin + return Diag.say(f, [Fmt.str(a)]); +end; + +(* The number of the name s *) +proc internStr(s: []U8): INT; +begin + return Scan.intern(ADR(s[0]), LEN(s)); +end; + +(* The modules the program uses: the main module, Rt, and every module + they import. A module read only for the interface check is not. *) +proc use(m: ^Sym.Module); +var i: ^Sym.Import; +begin + if m^.used then return; end; + m^.used := true; + i := m^.imports; + while i # nil do + use(i^.home); + i := i^.next; + end; +end; + +(* Whether the program uses C: if so, the libraries it needs go to + Elf, the C library first. *) +proc usesC: BOOL; +var m, st, c: ^Sym.Module; l: ^Sym.Lib; +begin + st := nil; c := nil; + Elf.noLibs(); + _ := Elf.needLib(internStr("libc.so.6")); + m := Parse.firstModule; + while m # nil do + if m^.used and m^.linkStatic then st := m; end; + if m^.used and m^.usesC then c := m; end; + l := m^.libs; + while m^.used and (l # nil) do + if not Elf.needLib(l^.name) then Diag.fatal("more than 32 libraries"); end; + l := l^.next; + end; + m := m^.next; + end; + if (st # nil) and (c # nil) then + Diag.fatal(Diag.say("{} says link static, but {} uses C", [Fmt.str(Scan.nameOf(st^.name)), Fmt.str(Scan.nameOf(c^.name))])); + end; + if c = nil then Elf.noLibs(); end; + return c # nil; +end; + +(* What raz -h says *) +proc usage; +begin + Out.str("usage: raz [option]... Main.raz compiles Main.raz and the modules it imports\n"); + Out.str(" raz run [option]... Main.raz [arg]... compiles it and runs it, with the args\n"); + Out.str("options:\n"); + Out.str(" -o file the program's file, Main without .raz if left out\n"); + Out.str(" -I dir looks for imported modules in dir too, after Main.raz's own\n"); + Out.str(" -Werror a warning counts as an error\n"); + Out.str(" -S lists the main module's code, under each line of source\n"); + Out.str(" -s strips symbols, line numbers, the places a failure is told\n"); + Out.str(" by and the profiler: a failure says only its address\n"); + Out.str(" -noprofile leaves out the profiler, which RAZ_PROFILE turns on\n"); + Out.str(" -h, --help says this\n"); + Out.str(" --version says the version, and the report it follows\n"); + Out.str("see raz(1), and the report, doc/raz.md\n"); + Out.flush(); +end; + +proc rtObj(rt: ^Sym.Module; n: []U8): ^Sym.Obj; +var o: ^Sym.Obj; +begin + o := Sym.find(rt^.scope, internStr(n)); + if o = nil then Diag.fatal(say1("Rt has no {}", n)); end; + return o; +end; + +(* Rt is given the address of chunk, in its variable v *) +proc addLink(chunk: INT; v: ^Sym.Obj); +begin + links[numLinks].chunk := chunk; + links[numLinks].into := v^.chunk; + INC(numLinks); +end; + +(* s as a C string, in memory that is never freed *) +proc cstr(s: []U8): ^U8; +var p: ^U8; +begin + p := Scan.grab(LEN(s) + 1); + if LEN(s) > 0 then COPY(p[0..LEN(s)], s); end; + p[LEN(s)] := 0; + return p; +end; + +proc main*: INT; +var + path, outPath, s: []U8; dir: []U8; + i, first, entry, fd, last, errno: INT; + m, rt: ^Sym.Module; mainObj: ^Sym.Obj; + run, noProfile, listing: BOOL; err: ERROR; +begin + path := ""; + outPath := ""; + noProfile := false; + listing := false; + run := (ARGC() >= 2) and (Files.arg(1) = "run"); + if run then i := 2; else i := 1; end; + while i < ARGC() do + s := Files.arg(i); + if s = "-I" then + INC(i); + if Parse.numInc > 15 then Diag.fatal("more than 16 -I directories"); end; + Parse.addIncDir(Files.arg(i)); + elsif s = "-o" then + INC(i); + outPath := Files.arg(i); + elsif s = "-Werror" then + Diag.setWerror(true); + elsif s = "-S" then + listing := true; + X64.setListing(true); + elsif s = "-s" then + Elf.setStripped(true); + elsif s = "-noprofile" then + noProfile := true; + elsif (s = "-h") or (s = "--help") then + usage(); + return 0; + elsif s = "--version" then + Out.str(Diag.say("raz {}, report {}\n", [Fmt.str(Version.Text), Fmt.str(Report)])); + Out.flush(); + return 0; + elsif (LEN(s) > 0) and (s[0] = '-') then + Diag.fatal(say1("unknown option {}", s)); + else + path := s; + first := i; + if run then break; end; (* the rest are the program's *) + end; + INC(i); + end; + if LEN(path) = 0 then + usage(); + return 1; + end; + if run and (LEN(outPath) > 0) then Diag.fatal("raz run takes no -o"); end; + (* where raz is, as the system says, for the library beside it *) + dir, errno := Sys.readLink("/proc/self/exe"); + if errno # 0 then dir := Files.arg(0); end; + i := LEN(dir); + while (i > 0) and (dir[i - 1] # '/') do DEC(i); end; + if i = 0 then Parse.setLibDir("lib"); else Parse.setLibDir(say1("{}lib", dir[0..i])); end; + if LEN(outPath) = 0 then + outPath := path; + last := LEN(outPath); + if (last >= 4) and (outPath[last - 4..last] = ".raz") then + outPath := outPath[0..last - 4]; + else + outPath := say1("{}.out", outPath); + end; + end; + + m, err := Parse.compileMain(path); + if err # nil then + Diag.finish(); + return 1; + end; + if Diag.errors > 0 then Diag.finish(); end; + + use(m); + rt := Parse.firstModule; + while (rt # nil) and (Scan.nameOf(rt^.name) # "Rt") do rt := rt^.next; end; + if rt # nil then use(rt); end; + + mainObj := Sym.find(m^.scope, internStr("main")); + if mainObj # nil then + if (mainObj^.cls # Sym.oProc) or not mainObj^.exported then + Diag.error(mainObj^.pos, "main must be an exported procedure"); + elsif (mainObj^.typ^.len # 0) or ((mainObj^.typ^.base # nil) and (mainObj^.typ^.base # Sym.tInt)) then + Diag.error(mainObj^.pos, "main must be proc main* or proc main*: INT"); + end; + if Diag.errors > 0 then Diag.finish(); end; + end; + Diag.finish(); + + if rt = nil then Diag.fatal("can't find module Rt"); end; + (* 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 Elf.stripped then + Link.setPlaces(Chunk.newChunk(Chunk.secRodata, -1, -1)); + Chunk.setData(Link.placesChunk, nil, 0, 8); + addLink(Link.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; + end; + entry := Gen.entryPoint(usesC(), Parse.firstModule, mainObj, rtObj(rt, "cExit")^.chunk, + rtObj(rt, "exit")^.chunk, links[0..numLinks], numLinks); + + Link.markLive(entry); + if not Parse.HasReals then + for i := 0 to Chunk.numChunks - 1 do + if Chunk.chunks[i].live and Chunk.chunks[i].reals then + Diag.error(Chunk.chunks[i].realsAt, "this target has no reals"); + end; + end; + end; + if Diag.errors > 0 then Diag.finish(); end; + if listing then + X64.list(m^.sname); + return 0; + end; + + Elf.setMainPath(path); + if run then + (* argv from Main.raz on is the program's, ending in nil as it must *) + fd := SYSCALL(MemfdCreate, cstr("raz"), MfdCloexec); + if fd < 0 then Diag.fatal("can't create a memfd"); end; + outPath := Diag.say("/proc/self/fd/{}", [Fmt.int(fd)]); + Elf.writeElf(outPath, entry); + _ := SYSCALL(Execve, cstr(outPath), ARGV() + first, ARGV() + (ARGC() + 1)); + Diag.fatal(say1("can't run {}", path)); + end; + Elf.writeElf(outPath, entry); + return 0; +end; + +end Raz. diff --git a/src/Scan.raz b/src/Scan.raz new file mode 100644 index 0000000..7887397 --- /dev/null +++ b/src/Scan.raz @@ -0,0 +1,1002 @@ +(* Scan: 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: Sys, 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: mark and the others report one and give + back Failed, which it passes up with try to where it can read on. *) +module Scan; +import Sys, Heap, Mem, Fmt, Str, Diag; + +type + NamePtr = ^U8; + + Sym* = (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); + + (* Where the scanner is. Importing a module compiles it in the middle + of another, so the parser saves this and restores it afterwards. *) + State* = record + buf: ^U8; + len, pos, line, lineStart: INT; + tokPos, tokLine, tokLineStart: INT; + prevEnd: INT; (* where the symbol before this one ends *) + tok: Sym; + ival: I64; + rval: F64; + id: INT; + f: INT; (* the file, as Diag knows it *) + end; + +const + Failed*: ERROR = "reported"; (* an error has been shown: the parser returns it *) + MaxIdent* = 63; + MaxStr* = 65536; + NumWords = 43; + NumOps = 28; + words: [NumWords][]U8 = [ + "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"]; + (* sPlus to sBlank *) + ops: [NumOps][]U8 = [ + "+", "-", "*", "/", "=", "#", "<", "<=", ">", ">=", + ":=", ":", ";", ",", ".", "..", "...", + "(", ")", "[", "]", "{", "}", "^", "&", "~", "|", "_"]; + (* the operators that no longer one starts, so that one byte is the symbol *) + alone = "+-*/#;,()[]{}^~"; + PoolChunk = 65536; + +var + tok*: Sym; (* the current symbol *) + ival*: I64; (* sInt, sChar: its value *) + rval*: F64; (* sReal: its value *) + id*: INT; (* sIdent: its name *) + slen*: INT; (* sString: how many bytes *) + sbuf: [MaxStr + 1]U8; (* sString: its bytes, then a zero *) + + (* The parser is skipping what it has read once already, after an + error, so slips in it aren't reported again. *) + skipping*: BOOL; + + (* Whether a byte may be in a name: a letter, a digit or _. A table, + since the loop that reads a name asks it of every byte. *) + nameChar: [256]BOOL; + + (* The symbol a byte is by itself, as + is, or sNull: a table, since + most symbols are of this kind and a match would test them one by one. *) + single: [256]Sym; + + cur: State; (* buf .. f; tok, ival, rval and id live above *) + + (* The name table: every distinct identifier once, found through an + open-addressed hash table. A name's bytes are in a chunk of memory + that is never moved, so that nameOf can hand out a slice of them. *) + chunk: ^U8; (* where names are put; chunkLeft bytes are left *) + chunkLeft: INT; + namePtr: ^NamePtr; + nameLen, nameHash: ^INT; + numNames, nameCap: INT; + table: ^INT; (* name + 1, or 0 for an empty slot *) + tableMask: INT; + +(* Exported variables can't be set from outside, so these do it. *) +proc setSkipping*(yes: BOOL); +begin + skipping := yes; +end; + +(* The bytes of the string just read, without the zero after them *) +proc strBytes*: []U8; +begin + return sbuf[0..slen]; +end; + +(* The string just read and the zero after it, for the code that makes a + chunk of it: an empty string has bytes to point at, though none to index *) +proc strWithZero*: ^U8; +begin + return ADR(sbuf[0]); +end; + +(* Memory, or the end of the compile when there is none *) +proc grab*(size: INT): ^U8; +var p: ^U8; +begin + p := Mem.alloc(Heap.heap, size, 8); + if p = nil then Diag.fatal("out of memory"); end; + return p; +end; + +(* p, which holds used bytes, moved to a block of size bytes *) +proc regrab*(p: ^U8; used, size: INT): ^U8; +var q: ^U8; +begin + q := grab(size); + COPY(q[0..used], p[0..used]); + Mem.free(Heap.heap, p); + return q; +end; + +(* n zeroed words *) +proc words64(n: INT): ^INT; +var p: ^INT; i: INT; +begin + p := ^INT(grab(n * SIZE(INT))); + for i := 0 to n - 1 do p[i] := 0; end; + return p; +end; + +(* Names *) + +proc hash(p: ^U8; n: INT): INT; +var h: U32; i: INT; +begin + h := 2166136261; + for i := 0 to n - 1 do h := (h xor U32(p[i])) * 16777619; end; + return INT(h & 7FFFFFFFH); +end; + +(* A table twice the size, and room for twice the names *) +proc grow; +var i, n, j: INT; ptrs: ^NamePtr; lens, hashes: ^INT; +begin + Mem.free(Heap.heap, ^U8(table)); + tableMask := tableMask * 2 + 1; + table := words64(tableMask + 1); + for n := 0 to numNames - 1 do + i := nameHash[n] & tableMask; + while table[i] # 0 do i := (i + 1) & tableMask; end; + table[i] := n + 1; + end; + j := nameCap * 2; + ptrs := ^NamePtr(grab(j * SIZE(NamePtr))); + lens := ^INT(grab(j * SIZE(INT))); + hashes := ^INT(grab(j * SIZE(INT))); + for n := 0 to numNames - 1 do + ptrs[n] := namePtr[n]; + lens[n] := nameLen[n]; + hashes[n] := nameHash[n]; + end; + Mem.free(Heap.heap, ^U8(namePtr)); + Mem.free(Heap.heap, ^U8(nameLen)); + Mem.free(Heap.heap, ^U8(nameHash)); + namePtr := ptrs; + nameLen := lens; + nameHash := hashes; + nameCap := j; +end; + +(* Whether the n bytes at p and at q are the same *) +proc same(p, q: ^U8; n: INT): BOOL; +var i: INT; +begin + for i := 0 to n - 1 do + if p[i] # q[i] then return false; end; + end; + return true; +end; + +(* The number of the name of the n bytes at p; a new name gets the next *) +proc intern*(p: ^U8; n: INT): INT; +var h, i, k: INT; +begin + h := hash(p, n); + i := h & tableMask; + while table[i] # 0 do + k := table[i] - 1; + if (nameHash[k] = h) and (nameLen[k] = n) and same(namePtr[k], p, n) then + return k; + end; + i := (i + 1) & tableMask; + end; + if n > chunkLeft then + chunk := grab(PoolChunk); + chunkLeft := PoolChunk; + end; + COPY(chunk[0..n], p[0..n]); + k := numNames; + namePtr[k] := chunk; + nameLen[k] := n; + nameHash[k] := h; + chunk := chunk + n; + chunkLeft := chunkLeft - n; + INC(numNames); + table[i] := k + 1; + if numNames * 2 > tableMask then grow; end; + return k; +end; + +(* The name n, which stays as it is *) +proc nameOf*(n: INT): []U8; +begin + return namePtr[n][0..nameLen[n]]; +end; + +(* Errors *) + +(* The current symbol *) +proc tokPos*: Diag.Pos; +begin + return {f: cur.f, a: cur.tokPos, b: cur.pos}; +end; + +(* The place just after the symbol before the current one, where a + missing symbol belongs *) +proc afterPrev*: Diag.Pos; +begin + return {f: cur.f, a: cur.prevEnd, 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 *) +proc missingPos*: Diag.Pos; +var i: INT; p: Diag.Pos; +begin + p := tokPos(); + for i := cur.prevEnd to cur.tokPos - 1 do + if cur.buf[i] = '\n' then p := afterPrev(); end; + end; + return p; +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 *) +proc spanFrom*(p: Diag.Pos): Diag.Pos; +begin + p.b := cur.prevEnd; + return p; +end; + +proc curLine*: INT; +begin + return 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. *) +proc lineCol*(a: INT): (INT, INT); +var i, line, start, col: INT; +begin + line := cur.tokLine; + start := cur.tokLineStart; + while a < start do + DEC(line); + DEC(start); + while (start > 0) and (cur.buf[start - 1] # '\n') do DEC(start); end; + end; + col := 1; + for i := start to a - 1 do + if (cur.buf[i] & 0C0H) # 80H then INC(col); end; + end; + return line, col; +end; + +proc curCol*: INT; +var col: INT; +begin + _, col := lineCol(cur.tokPos); + return col; +end; + +(* An error at p, shown: the parser returns Failed, which try passes up + to where it goes on. *) +proc markAt*(p: Diag.Pos; msg: []U8): ERROR; +begin + Diag.error(p, msg); + return Failed; +end; + +proc mark*(msg: []U8): ERROR; +begin + return markAt(tokPos(), msg); +end; + +(* markAt, with a line of help after the message. *) +proc markHelp*(p: Diag.Pos; msg, hint: []U8): ERROR; +begin + Diag.error(p, msg); + Diag.help(hint); + return Failed; +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. *) +proc markBytes(a, b: INT; msg: []U8); +begin + Diag.setQuiet(false); + Diag.error({f: cur.f, a: a, b: b}, msg); + Diag.finish; +end; + +proc lexError(msg: []U8); +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. *) +proc slip(n: INT; t: Sym; msg: []U8); +begin + if not skipping then Diag.error({f: cur.f, a: cur.pos, b: cur.pos + n}, msg); end; + INC(cur.pos, n); + tok := t; +end; + +(* How an operator or reserved word is written, quoted, for messages. *) +proc symText*(s: Sym): []U8; +begin + if (s >= sPlus) and (s <= sBlank) then + return Diag.say("\"{}\"", [Fmt.str(ops[INT(s) - INT(sPlus)])]); + end; + return Diag.say("\"{}\"", [Fmt.str(words[INT(s) - INT(sAnd)])]); +end; + +(* The current symbol, for "expected ..., found ...": a name as it is, + a literal by its kind, an operator or reserved word quoted. *) +proc found*: []U8; +begin + match tok of + | sIdent: return nameOf(id); + | sInt: return "a number"; + | sReal: return "a number"; + | sChar: return "a character"; + | sString: return "a string"; + | sEof: return "the end of the file"; + | else: return 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. *) +proc atLineStart*: BOOL; +begin + return cur.tokPos = cur.tokLineStart; +end; + +(* The column the current symbol's line is indented to *) +proc indent*: INT; +var i: INT; +begin + i := cur.tokLineStart; + while (cur.buf[i] = ' ') or (cur.buf[i] = '\t') do INC(i); end; + return i - cur.tokLineStart + 1; +end; + +(* Files *) + +(* Name n is a reserved word *) +proc reserved*(n: INT): BOOL; +begin + return n < NumWords; +end; + +(* Reads the file at path to scan it; "" if it can, else why not *) +proc open*(path: []U8): []U8; +var fd, n, got, r, err: INT; info: Sys.Info; +begin + info, err := Sys.info(path); + if err = -2 then return "there is no such file"; end; + if err = -13 then return "permission denied"; end; + if err < 0 then return "it can't be opened"; end; + if not info.file then return "it isn't a file"; end; + fd := Sys.openRead(path); + if fd = -2 then return "there is no such file"; end; + if fd = -13 then return "permission denied"; end; + if fd < 0 then return "it can't be opened"; end; + n := INT(info.size); + cur.buf := grab(n + 1); + got := 0; + while got < n do + r := Sys.read(fd, cur.buf[got..n]); + if r <= 0 then Diag.fatal(Diag.say("can't read {}", [Fmt.str(path)])); end; + got := got + r; + end; + Sys.close(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 := Diag.addFile(path, cur.buf, n); + return ""; +end; + +proc saveScan*(var st: State); +begin + st := cur; + st.tok := tok; + st.ival := ival; + st.rval := rval; + st.id := id; +end; + +proc restoreScan*(st: State); +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. *) +proc utf8(var pos: INT): INT; +var b0, b1, n, i, cp: INT; lo, hi: INT; +begin + b0 := INT(cur.buf[pos]); + lo := 80H; + hi := 0BFH; + n := 0; + cp := 0; + match b0 of + | 0C2H..0DFH: n := 1; cp := b0 & 1FH; + | 0E0H: n := 2; lo := 0A0H; + | 0E1H..0ECH, 0EEH, 0EFH: n := 2; cp := b0 & 0FH; + | 0EDH: n := 2; cp := 0DH; hi := 9FH; (* no surrogates *) + | 0F0H: n := 3; lo := 90H; + | 0F1H..0F3H: n := 3; cp := b0 & 7; + | 0F4H: n := 3; cp := 4; hi := 8FH; (* up to 10FFFFH *) + | else: + cur.tokPos := pos; + lexError("invalid UTF-8"); + end; + for i := 1 to n do + b1 := INT(cur.buf[pos + i]); + if (b1 < lo) or (b1 > hi) or (pos + i >= cur.len) then + cur.tokPos := pos; + lexError("bad UTF-8"); + end; + cp := cp shl 6 | (b1 & 3FH); + lo := 80H; + hi := 0BFH; + end; + pos := pos + n + 1; + return cp; +end; + +proc put(b: INT); +begin + if slen >= MaxStr then + lexError(Diag.say("a string holds at most {} bytes", [Fmt.int(MaxStr)])); + end; + sbuf[slen] := U8(b); + INC(slen); +end; + +proc putUtf8(cp: INT); +begin + if cp < 80H then + put(cp); + elsif cp < 800H then + put(0C0H | cp shr 6); put(80H | cp & 3FH); + elsif cp < 10000H then + put(0E0H | cp shr 12); put(80H | cp shr 6 & 3FH); put(80H | cp & 3FH); + else + put(0F0H | cp shr 18); put(80H | cp shr 12 & 3FH); + put(80H | cp shr 6 & 3FH); put(80H | cp & 3FH); + end; +end; + +proc isDigit(c: U8): BOOL; +begin + return (c >= '0') and (c <= '9'); +end; + +proc isLetter(c: U8): BOOL; +begin + return (c >= 'a') and (c <= 'z') or (c >= 'A') and (c <= 'Z') or (c = '_'); +end; + +proc hexVal(c: U8): INT; +begin + if isDigit(c) then return INT(c) - '0'; + elsif (c >= 'A') and (c <= 'F') then return INT(c) - 'A' + 10; + elsif (c >= 'a') and (c <= 'f') then return INT(c) - 'a' + 10; + end; + return -1; +end; + +(* The text of the file from byte a up to but not including b *) +proc text(a, b: INT): []U8; +begin + return Diag.source({f: cur.f, a: a, b: b}); +end; + +(* One character of a character or string literal, at buf[pos]: its code + point, or for \xHH, minus one minus the byte. *) +proc litChar(inString: BOOL): INT; +var c: U8; v, d, n, esc, digits: INT; +begin + c := cur.buf[cur.pos]; + esc := cur.pos; + v := 0; + if c = '\\' then + INC(cur.pos); + c := cur.buf[cur.pos]; + INC(cur.pos); + match c of + | 'n': v := 10; + | 't': v := 9; + | 'r': v := 13; + | '0': v := 0; + | '\\', '\'', '"': v := INT(c); + | 'x': + if not inString then markBytes(esc, cur.pos, "\\x is only for strings"); end; + 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"); end; + INC(cur.pos, 2); + v := -1 - (d * 16 + n); + | 'u': + if cur.buf[cur.pos] # '{' then markBytes(esc, cur.pos, "expected \"{\" after \\u"); end; + INC(cur.pos); + digits := cur.pos; + v := 0; + n := 0; + while hexVal(cur.buf[cur.pos]) >= 0 do + 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; + end; + if (n = 0) or (cur.buf[cur.pos] # '}') then + markBytes(esc, cur.pos, "expected hex digits and \"}\" after \\u{"); + end; + INC(cur.pos); + if (v > 10FFFFH) or (v >= 0D800H) and (v <= 0DFFFH) then + markBytes(esc, cur.pos, Diag.say("{} isn't a code point", [Fmt.str(text(digits, cur.pos - 1))])); + end; + | else: + markBytes(esc, cur.pos, Diag.say("unknown escape \\{}", [Fmt.char(c)])); + end; + elsif c >= 80H then + v := utf8(cur.pos); + elsif (c < ' ') or (c = 127) then + if inString then lexError("string not closed"); else lexError("character not closed"); end; + else + v := INT(c); + INC(cur.pos); + end; + return v; +end; + +(* Symbols *) + +proc comment; +var depth, open: INT; c: U8; +begin + depth := 1; + open := cur.pos; + INC(cur.pos, 2); + repeat + c := cur.buf[cur.pos]; + if c = 0 then + if cur.pos >= cur.len then markBytes(open, open + 2, "comment not closed"); end; + INC(cur.pos); + elsif (c = '(') and (cur.buf[cur.pos + 1] = '*') then + INC(depth); + INC(cur.pos, 2); + elsif (c = '*') and (cur.buf[cur.pos + 1] = ')') then + DEC(depth); + INC(cur.pos, 2); + elsif c = '\n' then + INC(cur.pos); + INC(cur.line); + cur.lineStart := cur.pos; + elsif c >= 80H then + _ := utf8(cur.pos); + else + INC(cur.pos); + end; + 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 reader 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 + Big = record + n: INT; (* words in use; 0 is zero *) + w: [96]U32; (* least significant first *) + end; +(* 96 words, 3072 bits, are plenty: a string 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 *) +proc bigMul(var a: Big; m, add: U32); +var i: INT; c: U64; +begin + c := U64(add); + for i := 0 to a.n - 1 do + c := U64(a.w[i]) * U64(m) + c; + a.w[i] := U32(c); + c := c shr 32; + end; + if c # 0 then + a.w[a.n] := U32(c); + INC(a.n); + end; +end; + +proc bigShl(var a: Big; k: INT); +var i, ws, bits: INT; +begin + if a.n = 0 then return; end; + ws := k div 32; + bits := k mod 32; + a.w[a.n + ws] := 0; + for i := a.n - 1 to 0 by -1 do + if bits > 0 then a.w[i + ws + 1] := a.w[i + ws + 1] | (a.w[i] shr (32 - bits)); end; + a.w[i + ws] := a.w[i] shl bits; + end; + for i := 0 to ws - 1 do a.w[i] := 0; end; + INC(a.n, ws + 1); + while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end; +end; + +proc bigShr1(var a: Big); +var i: INT; +begin + for i := 0 to a.n - 1 do + a.w[i] := a.w[i] shr 1; + if i + 1 < a.n then a.w[i] := a.w[i] | (a.w[i + 1] shl 31); end; + end; + while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end; +end; + +(* -1, 0 or 1 as a is below, equal to or above b *) +proc bigCmp(a, b: Big): INT; +var i: INT; +begin + if a.n # b.n then + if a.n > b.n then return 1; end; + return -1; + end; + for i := a.n - 1 to 0 by -1 do + if a.w[i] # b.w[i] then + if a.w[i] > b.w[i] then return 1; end; + return -1; + end; + end; + return 0; +end; + +(* a := a - b, b not above a *) +proc bigSub(var a: Big; b: Big); +var i: INT; d: I64; +begin + d := 0; + for i := 0 to a.n - 1 do + d := d + I64(a.w[i]); + if i < b.n then d := d - I64(b.w[i]); end; + a.w[i] := U32(d); + if d < 0 then d := -1; else d := 0; end; (* a borrow *) + end; + while (a.n > 0) and (a.w[a.n - 1] = 0) do DEC(a.n); end; +end; + +proc bigBits(a: Big): INT; +var t: U32; bits: INT; +begin + if a.n = 0 then return 0; end; + bits := (a.n - 1) * 32; + t := a.w[a.n - 1]; + while t # 0 do + INC(bits); + t := t shr 1; + end; + return bits; +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. *) +proc readReal(s: []U8): (F64, BOOL); +var + num, den, d: Big; i, digits, e, ex: INT; neg, half, sticky: BOOL; + q, b: U64; x: F64; bits: ^F64; +begin + num.n := 0; + den.n := 1; + den.w[0] := 1; + digits := 0; + e := 0; + i := 0; + while (i < LEN(s)) and (s[i] # 'E') do + if s[i] = '.' then + e := 1; + else + bigMul(num, 10, U32(INT(s[i]) - '0')); + if num.n > 0 then INC(digits); end; (* counted from the first that isn't 0 *) + if e > 0 then INC(e); end; + end; + INC(i); + end; + if e > 0 then e := 1 - e; end; (* minus the digits after the point *) + ex := 0; + neg := false; + if i < LEN(s) then + INC(i); + neg := s[i] = '-'; + if (s[i] = '+') or (s[i] = '-') then INC(i); end; + while i < LEN(s) do + if ex < 100000 then ex := ex * 10 + INT(s[i]) - '0'; end; + INC(i); + end; + end; + if neg then ex := -ex; end; + INC(e, ex); + x := 0.0; + if num.n = 0 then return x, true; end; + if digits + e > 310 then return x, false; end; (* 10^310 is past every F64 *) + if digits + e < -330 then return x, true; end; (* and 10^-330 below half the least *) + for i := 1 to e do bigMul(num, 10, 0); end; + for i := 1 to -e do bigMul(den, 10, 0); end; + (* 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; end; + if e < 0 then bigShl(num, -e); else bigShl(den, e); end; + (* q, its whole part, by long division; num is left the remainder *) + d := den; + bigShl(d, 53); + q := 0; + for i := 53 to 0 by -1 do + if bigCmp(num, d) >= 0 then + bigSub(num, d); + q := q | (U64(1) shl i); + end; + bigShr1(d); + end; + if q >= U64(1) shl 53 then (* a bit too many: it rounds *) + half := (q & 1) # 0; + sticky := num.n > 0; + q := q shr 1; + INC(e); + else (* 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 ((q & 1) # 0)) then + INC(q); + if q = U64(1) shl 53 then + q := q shr 1; + INC(e); + end; + end; + if e > 971 then return x, false; end; + if q >= U64(1) shl 52 then + b := U64(e + 1075) shl 52 | (q & (U64(1) shl 52 - 1)); + else + b := q; (* below the least normal, e is -1074 *) + end; + bits := ^F64(ADR(b)); + return bits^, true; +end; + +proc number; +var start, i, d: INT; allDec, ok: BOOL; v: U64; +begin + start := cur.pos; + allDec := true; + while isDigit(cur.buf[cur.pos]) or (cur.buf[cur.pos] >= 'A') and (cur.buf[cur.pos] <= 'F') do + if cur.buf[cur.pos] > '9' then allDec := false; end; + INC(cur.pos); + end; + if cur.buf[cur.pos] = 'H' then + v := 0; + for i := start to cur.pos - 1 do + if v shr 60 # 0 then lexError(Diag.say("{} is too big for U64", [Fmt.str(text(start, cur.pos))])); end; + v := v * 16 + U64(hexVal(cur.buf[i])); + end; + INC(cur.pos); + tok := sInt; + ival := I64(v); (* 16 digits are the bits of a 64-bit word *) + elsif (cur.buf[cur.pos] = '.') and isDigit(cur.buf[cur.pos + 1]) then + if not allDec then lexError("a decimal number has only the digits 0 to 9"); end; + INC(cur.pos); + while isDigit(cur.buf[cur.pos]) do INC(cur.pos); end; + if cur.buf[cur.pos] = 'E' then + INC(cur.pos); + if (cur.buf[cur.pos] = '+') or (cur.buf[cur.pos] = '-') then INC(cur.pos); end; + if not isDigit(cur.buf[cur.pos]) then lexError("expected a digit in the exponent"); end; + while isDigit(cur.buf[cur.pos]) do INC(cur.pos); end; + end; + if cur.pos - start > 255 then lexError("a number has at most 255 characters"); end; + rval, ok := readReal(cur.buf[start..cur.pos]); + if not ok then lexError(Diag.say("{} is out of the range of F64", [Fmt.str(text(start, cur.pos))])); end; + tok := sReal; + else + if not allDec then lexError("a hex number ends with H"); end; + v := 0; + for i := start to cur.pos - 1 do + d := INT(cur.buf[i]) - '0'; + if v > (U64(9223372036854775807) - U64(d)) div 10 then + lexError(Diag.say("{} is too big for I64", [Fmt.str(text(start, cur.pos))])); + end; + v := v * 10 + U64(d); + end; + tok := sInt; + ival := I64(v); + end; + if nameChar[cur.buf[cur.pos]] then + lexError("a name can't start with a digit"); + end; +end; + +(* Reads the next symbol *) +proc next*; +var c: U8; start, h, v, i: INT; +begin + cur.prevEnd := cur.pos; + repeat + c := cur.buf[cur.pos]; + while (c = ' ') or (c = '\t') or (c = '\r') or (c = '\n') do + if c = '\n' then + 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 + comment; + c := ' '; + end; + until c # ' '; + cur.tokPos := cur.pos; + cur.tokLine := cur.line; + cur.tokLineStart := cur.lineStart; + if single[c] # sNull then + INC(cur.pos); + tok := single[c]; + return; + end; + match c of + | 'A'..'Z', 'a'..'z', '_': + start := cur.pos; + repeat INC(cur.pos); until not nameChar[cur.buf[cur.pos]]; + if cur.pos - start > MaxIdent then + lexError(Diag.say("a name has at most {} characters", [Fmt.int(MaxIdent)])); + end; + h := intern(cur.buf + start, cur.pos - start); + if (cur.pos - start = 1) and (c = '_') then + tok := sBlank; + elsif h < NumWords then + tok := Sym(INT(sAnd) + h); + else + tok := sIdent; + id := h; + end; + | '0'..'9': number; + | '\'': + INC(cur.pos); + if cur.buf[cur.pos] = '\'' then lexError("empty character"); end; + v := litChar(false); + if cur.buf[cur.pos] # '\'' then + (* 'ab': several characters, as some languages write a string *) + i := cur.pos; + while (cur.buf[i] # '\'') and (cur.buf[i] # '\n') and (cur.buf[i] # 0) do INC(i); end; + if cur.buf[i] = '\'' then + markBytes(cur.tokPos, i + 1, + Diag.say("a character is one character: the string is \"{}\"", [Fmt.str(text(cur.tokPos + 1, i))])); + else + lexError("character not closed"); + end; + end; + INC(cur.pos); + tok := sChar; + ival := I64(v); + | '"': + INC(cur.pos); + slen := 0; + while cur.buf[cur.pos] # '"' do + v := litChar(true); + if v < 0 then put(-1 - v); else putUtf8(v); end; + end; + INC(cur.pos); + sbuf[slen] := 0; + tok := sString; + | '=': + if cur.buf[cur.pos + 1] = '=' then + slip(2, sEql, "comparing is written =, not =="); + else + INC(cur.pos); + tok := sEql; + end; + | '&': + if cur.buf[cur.pos + 1] = '&' then + slip(2, sAnd, "\"and\" is written and, not &&"); + else + INC(cur.pos); + tok := sAmp; + end; + | '<': + INC(cur.pos); + if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sLeq; else tok := sLss; end; + | '>': + INC(cur.pos); + if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sGeq; else tok := sGtr; end; + | ':': + INC(cur.pos); + if cur.buf[cur.pos] = '=' then INC(cur.pos); tok := sBecomes; else tok := sColon; end; + | '.': + INC(cur.pos); + if cur.buf[cur.pos] = '.' then + INC(cur.pos); + if cur.buf[cur.pos] = '.' then INC(cur.pos); tok := sEllipsis; else tok := sUpto; end; + else + tok := sPeriod; + end; + | '|': + if cur.buf[cur.pos + 1] = '|' then + slip(2, sOr, "\"or\" is written or, not ||"); + else + INC(cur.pos); + tok := sBar; + 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 !"); + end; + | 0: + if cur.pos < cur.len then markBytes(cur.pos, cur.pos + 1, "NUL byte in the text"); end; + tok := sEof; + | else: + if c >= 80H then lexError("only ASCII outside strings, characters and comments"); end; + markBytes(cur.pos, cur.pos + 1, Diag.say("unexpected character \"{}\"", [Fmt.char(c)])); + end; +end; + +var i: INT; + +begin + for i := 0 to 255 do nameChar[i] := isLetter(U8(i)) or isDigit(U8(i)); end; + for i := 0 to NumOps - 1 do + if (LEN(ops[i]) = 1) and (Str.find(alone, ops[i]) >= 0) then + single[ops[i][0]] := Sym(INT(sPlus) + i); + end; + end; + chunkLeft := 0; + nameCap := 1 shl 12; + namePtr := ^NamePtr(grab(nameCap * SIZE(NamePtr))); + nameLen := ^INT(grab(nameCap * SIZE(INT))); + nameHash := ^INT(grab(nameCap * SIZE(INT))); + tableMask := 2 * nameCap - 1; + table := words64(tableMask + 1); + for i := 0 to NumWords - 1 do _ := intern(ADR(words[i][0]), LEN(words[i])); end; +end Scan. diff --git a/src/Sym.raz b/src/Sym.raz new file mode 100644 index 0000000..b57cd96 --- /dev/null +++ b/src/Sym.raz @@ -0,0 +1,684 @@ +(* Sym: types, objects and scopes. + + Every name the program declares becomes an object (Obj): a constant, + type, variable, procedure, module, record field, variant case or + built-in. Every type is a Type. 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; Diag, for positions. + Leaves out: code. Where a variable lives is decided here (frame + offsets, chunk numbers), but nothing is emitted. + + Exported variables can't be set from outside, so setCurModule is + how the parser says which module it is in. A name that holds a + reserved word of raz is spelled otherwise: a record's `module` is + its `home`, an object's `link` its `chain`. *) +module Sym; +import Mem, Heap, Buf, Fmt, Diag, Scan; + +type + Form* = (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. *) + + Class* = (oConst, oType, oVar, oProc, oModule, oField, oCase, oBuiltin); + + Type* = record + form*: Form; + size*, align*: I64; + signed*: BOOL; (* fInt *) + vol*: BOOL; (* fPtr: ^VOLATILE *) + packd*: BOOL; (* fRecord *) + variadic*: BOOL; (* fProc: ends in ... *) + tuple*: BOOL; (* fRecord: the results of a procedure that has several *) + base*: ^Type; (* fPtr, fArray, fSlice: what it holds; fProc: result *) + len*: I64; (* fArray: elements; fProc: parameters; fVariant: cases; a tuple: results *) + fields*: ^Obj; (* fRecord: fields; fVariant: cases; fProc: parameters *) + scope*: INT; (* fRecord: the scope of its fields *) + fwd*: INT; (* fPtr whose base isn't declared yet: its name, else -1 *) + obj*: ^Obj; (* the declaration that names it, or nil *) + home*: ^Module; (* the module that built it *) + end; + + Obj* = record + cls*: Class; + name*: INT; + exported*: BOOL; + typ*: ^Type; + next*: ^Obj; (* the next in its list: scope, fields, parameters *) + scope*: INT; (* where it is declared *) + pos*: Diag.Pos; (* where its name is declared, for messages *) + val*: I64; (* oConst: value; oBuiltin: which; oCase: tag; + oField: offset; oVar: frame offset *) + chunk*: INT; (* global oVar, oProc, string oConst: its chunk *) + lev*: INT; (* oVar: 0 for a module variable, 1 for a local *) + ind*: BOOL; (* oVar: the frame slot holds the variable's address *) + off*: I64; (* oVar with ind: added to that address *) + isVar*: BOOL; (* a var parameter *) + param*: BOOL; (* oVar: a parameter *) + used*: BOOL; (* named somewhere but in its own body *) + read*: BOOL; (* oVar: named other than as what := assigns *) + fwd*: BOOL; (* oProc: declared forward, no body yet *) + isCode*: BOOL; (* oProc: a code procedure *) + openEnd*: BOOL; (* oProc: has results, and may reach its end *) + reg*: INT; (* oVar: the register it lives in, or 0 if in memory; + for a slice, the one its pointer is in *) + reg2*: INT; (* oVar: a slice in registers: the one its length is in *) + ext*: BOOL; (* oProc, oVar: C's, reached through its chunk, which + holds its address *) + fields*: ^Obj; (* oCase: its fields *) + home*: ^Module; (* oModule: the module; others: where declared *) + chain*: ^Obj; (* 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. *) + Args* = record + n*: INT; + t*: [8]^Type; + o*: [8]^Obj; + pos*: [8]Diag.Pos; (* where each argument is, for messages *) + at*: Diag.Pos; (* where the import is *) + end; + + Import* = record + home*: ^Module; + next*: ^Import; + end; + + (* A library a module links, by its name, as interned *) + Lib* = record + name*: INT; + next*: ^Lib; + end; + + Module* = record + name*: INT; + sname*: INT; (* the name of its symbols: List(I64) for an instance *) + args*: Args; + scope*: INT; + path*: []U8; + first*, last*: ^Obj; (* its top-level declarations, in order *) + locals*, lastLocal*: ^Obj; (* its procedures' declarations, in order *) + imports*: ^Import; + body*: INT; (* the chunk of its body, or -1 *) + done*: BOOL; (* compiled to the end *) + checkOnly*: BOOL; (* read only to check another file's interface *) + used*: BOOL; (* imported, through others, by the main module *) + usesC*: BOOL; (* has an extern, or links a library *) + linkStatic*: BOOL; (* says link static *) + libs*: ^Lib; (* the libraries it links *) + next*: ^Module; (* 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*: ^Type; + tInt*, tUInt*: ^Type; (* INT and UINT, as big as an address: 8 bytes here *) + tBool*, tF32*, tReal*, tRConst*, tError*, tConst*, tNil*, tStr*, tNone*, tPtrU8*, tBytes*: ^Type; + tPoison*: ^Type; (* of a name reported as not declared *) + curModule*: ^Module; + + scopes: [MaxDepth]INT; + depth: INT; + nextScope: INT; + hashTab: ^^Obj; + hashMask, hashCount: INT; + +proc setCurModule*(m: ^Module); +begin + curModule := m; +end; + +proc newType*(form: Form; size, align: I64): ^Type; +var t: ^Type; +begin + NEW(t, Heap.heap); + if t = nil then Diag.fatal("out of memory"); end; + t^.form := form; + t^.size := size; + t^.align := align; + t^.fwd := -1; + t^.home := curModule; + return t; +end; + +proc newObj*(cls: Class; name: INT; typ: ^Type): ^Obj; +var o: ^Obj; +begin + NEW(o, Heap.heap); + if o = nil then Diag.fatal("out of memory"); end; + o^.cls := cls; + o^.name := name; + o^.typ := typ; + o^.chunk := -1; + o^.home := curModule; + o^.pos := Scan.tokPos(); + return o; +end; + +(* Scopes *) + +proc newScope*: INT; +begin + INC(nextScope); + return nextScope; +end; + +proc openScope*(s: INT): ERROR; +begin + if depth = MaxDepth then + return Scan.mark(Diag.say("scopes nested more than {} deep", [Fmt.int(MaxDepth)])); + end; + scopes[depth] := s; + INC(depth); + return nil; +end; + +proc closeScope*; +begin + DEC(depth); +end; + +(* An imported module is compiled in the middle of another, and must + see only the universe and itself. The scopes open are kept in saved, + and their number is the result. *) +proc saveScopes*(saved: []INT): INT; +var i, d: INT; +begin + d := depth; + for i := 0 to depth - 1 do saved[i] := scopes[i]; end; + depth := 1; + return d; +end; + +proc restoreScopes*(d: INT; saved: []INT); +var i: INT; +begin + depth := d; + for i := 0 to depth - 1 do scopes[i] := saved[i]; end; +end; + +proc scopeDepth*: INT; +begin + return depth; +end; + +(* Closes the scopes opened since there were d, after an error *) +proc cutScopes*(d: INT); +begin + depth := d; +end; + +proc topScope*: INT; +begin + return 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. *) +proc slot(s, name: INT): INT; +begin + return INT(((U32(s & 0FFFFFFFFH) * 2654435761) xor (U32(name & 0FFFFFFFFH) * 40503)) & U32(hashMask)); +end; + +(* A table of n slots, all empty *) +proc emptyTable(n: INT): ^^Obj; +var t: ^^Obj; i: INT; +begin + t := ^^Obj(Scan.grab(n * SIZE(^Obj))); + for i := 0 to n - 1 do t[i] := nil; end; + return t; +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. *) +proc rehash; +var old: ^^Obj; n, i, j: INT; +begin + old := hashTab; + n := hashMask + 1; + hashMask := n * 2 - 1; + hashTab := emptyTable(n * 2); + for i := 0 to n - 1 do + if old[i] # nil then + j := slot(old[i]^.scope, old[i]^.name); + while hashTab[j] # nil do j := (j + 1) & hashMask; end; + hashTab[j] := old[i]; + end; + end; + Mem.free(Heap.heap, ^U8(old)); +end; + +proc insert*(obj: ^Obj; s: INT): ERROR; +var i: INT; o: ^Obj; +begin + i := slot(s, obj^.name); + o := hashTab[i]; + while o # nil do + if (o^.scope = s) and (o^.name = obj^.name) then + Diag.error(obj^.pos, Diag.say("{} is declared twice", [Fmt.str(Scan.nameOf(obj^.name))])); + Diag.note(o^.pos, "the first one is here"); + return Scan.Failed; + end; + i := (i + 1) & hashMask; + o := hashTab[i]; + end; + obj^.scope := s; + hashTab[i] := obj; + INC(hashCount); + if hashCount * 2 > hashMask then rehash; end; + return nil; +end; + +proc find*(s, name: INT): ^Obj; +var i: INT; o: ^Obj; +begin + i := slot(s, name); + o := hashTab[i]; + while o # nil do + if (o^.scope = s) and (o^.name = name) then return o; end; + i := (i + 1) & hashMask; + o := hashTab[i]; + end; + return nil; +end; + +proc lookup*(name: INT): ^Obj; +var i: INT; o: ^Obj; +begin + for i := depth - 1 to 0 by -1 do + o := find(scopes[i], name); + if o # nil then return o; end; + end; + return nil; +end; + +proc min(a, b: INT): INT; +begin + if a < b then return a; end; + return b; +end; + +(* c, in capitals if it is a letter *) +proc up(c: U8): U8; +begin + if (c >= 97) and (c <= 122) then return c - 32; end; + return c; +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. *) +proc distance(a, b: []U8): INT; +var d: [Scan.MaxIdent + 2][Scan.MaxIdent + 2]INT; i, j, c: INT; +begin + for i := 0 to LEN(a) do d[i][0] := i; end; + for j := 0 to LEN(b) do d[0][j] := j; end; + for i := 1 to LEN(a) do + for j := 1 to LEN(b) do + c := 1; + if up(a[i - 1]) = up(b[j - 1]) then c := 0; end; + 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 (up(a[i - 1]) = up(b[j - 2])) + and (up(a[i - 2]) = up(b[j - 1])) then + d[i][j] := min(d[i][j], d[i - 2][j - 2] + 1); + end; + end; + end; + return d[LEN(a)][LEN(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. *) +proc closest*(name, s: INT): ^Obj; +var i, j, d, best: INT; o, found: ^Obj; n: []U8; reach: BOOL; +begin + n := Scan.nameOf(name); + best := LEN(n) div 3 + 1; + found := nil; + for i := 0 to hashMask do + o := hashTab[i]; + if (o = nil) or (o^.name = name) or (o^.name < 0) or (o^.typ = tPoison) then + reach := false; + elsif s >= 0 then + reach := (o^.scope = s) and (o^.exported or (o^.home = curModule)); + else + reach := false; + for j := 0 to depth - 1 do reach := reach or (o^.scope = scopes[j]); end; + end; + if reach then + d := distance(n, Scan.nameOf(o^.name)); + if d < best then best := d; found := o; end; + end; + end; + return found; +end; + +(* Types *) + +proc alignUp*(x, a: I64): I64; +begin + return (x + a - 1) div a * a; +end; + +proc isInt*(t: ^Type): BOOL; +begin + return t^.form in {fInt, fConst}; +end; + +proc isScalar*(t: ^Type): BOOL; +begin + return t^.form in {fBool, fInt, fReal, fConst, fNil, fPtr, fProc, fEnum, fSet, fError}; +end; + +proc isAggregate*(t: ^Type): BOOL; +begin + return t^.form in {fArray, fSlice, fRecord, fVariant}; +end; + +(* Whether a result field f is a single value of at most a word, not a real *) +proc oneWord(f: ^Obj): BOOL; +begin + return isScalar(f^.typ) and (f^.typ^.form # fReal) and (f^.typ^.size <= 8); +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. *) +proc inTwoRegs*(t: ^Type): BOOL; +begin + if t^.form = fSlice then return true; end; + return 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. *) +proc behindPointer*(t: ^Type): BOOL; +begin + return isAggregate(t) and not inTwoRegs(t); +end; + +proc fits*(v: I64; t: ^Type): BOOL; +begin + if t^.form # fInt then return t^.form = fConst; end; + match t^.size of + | 1: + if t^.signed then return (v >= -128) and (v <= 127); end; + return (v >= 0) and (v <= 255); + | 2: + if t^.signed then return (v >= -32768) and (v <= 32767); end; + return (v >= 0) and (v <= 65535); + | 4: + if t^.signed then return (v >= -2147483648) and (v <= 2147483647); end; + return (v >= 0) and (v <= 4294967295); + | else: return t^.signed or (v >= 0); + end; +end; + +proc same*(a, b: ^Type): BOOL; forward; + +(* Whether two procedure types, or two tuples, are alike: the same + results and parameters, in the same modes *) +proc alikeShape(a, b: ^Type): BOOL; +var p, q: ^Obj; +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 return false; end; + if (a^.len # b^.len) or (a^.variadic # b^.variadic) then return false; end; + if (a^.base = nil) # (b^.base = nil) then return false; end; + if (a^.base # nil) and not same(a^.base, b^.base) then return false; end; + p := a^.fields; q := b^.fields; + while p # nil do + if (p^.isVar # q^.isVar) or not same(p^.typ, q^.typ) then return false; end; + p := p^.next; q := q^.next; + end; + return true; +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. *) +proc alike(a, b: ^Type): BOOL; +begin + if a = b then return true; end; + if a^.form # b^.form then return false; end; + match a^.form of + | fPtr: return (a^.vol = b^.vol) and same(a^.base, b^.base); + | fArray: return (a^.len = b^.len) and same(a^.base, b^.base); + | fSlice: return same(a^.base, b^.base); + | fSet: return same(a^.base, b^.base); + | fProc: return alikeShape(a, b); + | fRecord: return alikeShape(a, b); + | else: return false; + end; +end; + +proc same*(a, b: ^Type): BOOL; +begin + if a = b then return true; end; + if (a = nil) or (b = nil) then return false; end; + if (a^.obj # nil) and (b^.obj # nil) then return false; end; + return alike(a, b); +end; + +(* What a type is called, added to b: the names a program gives it, else + what it is made of *) +proc typeText(b: ^Buf.Buf; t: ^Type); +var f: ^Obj; +begin + if t = nil then Buf.str(b, "nothing"); return; end; + if t^.obj # nil then + if (t^.obj^.home # nil) and (t^.obj^.home # curModule) then + Buf.str(b, Scan.nameOf(t^.obj^.home^.sname)); + Buf.str(b, "."); + end; + Buf.str(b, Scan.nameOf(t^.obj^.name)); + return; + end; + match t^.form of + | fConst: Buf.str(b, "an integer constant"); + | fReal: Buf.str(b, "a real constant"); + | fNil: Buf.str(b, "nil"); + | fStr: Buf.str(b, "a string"); + | fPtr: + if t^.vol then Buf.str(b, "^VOLATILE "); else Buf.str(b, "^"); end; + typeText(b, t^.base); + | fArray: + Fmt.write(b, "[{}]", [Fmt.int(t^.len)]); + typeText(b, t^.base); + | fSlice: + Buf.str(b, "[]"); + typeText(b, t^.base); + | fRecord: + if not t^.tuple then + Buf.str(b, "record"); + else + Buf.str(b, "("); + f := t^.fields; + while f # nil do + typeText(b, f^.typ); + f := f^.next; + if f # nil then Buf.str(b, ", "); end; + end; + Buf.str(b, ")"); + end; + | fVariant: Buf.str(b, "variant"); + | fProc: + Buf.str(b, "proc("); + f := t^.fields; + while f # nil do + if f^.isVar then Buf.str(b, "var "); end; + typeText(b, f^.typ); + f := f^.next; + if f # nil then Buf.str(b, ", "); end; + end; + Buf.str(b, ")"); + if t^.base # nil then + Buf.str(b, ": "); + typeText(b, t^.base); + end; + | else: Buf.str(b, "?"); + end; +end; + +(* A name for t, kept for good, as every message is *) +proc typeName*(t: ^Type): []U8; +var b: ^Buf.Buf; +begin + b := ^Buf.Buf(Scan.grab(SIZE(Buf.Buf))); + Buf.init(b, Heap.heap); + typeText(b, t); + return Buf.bytes(b); +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. *) +proc mix(var h: U64; v: I64); +begin + h := (h xor U64(v)) * 1099511628211; (* FNV-1a's 64-bit prime *) +end; + +proc bit(f: BOOL): INT; +begin + if f then return 1; end; + return 0; +end; + +proc shape(var h: U64; t: ^Type; top: BOOL); +var f, g: ^Obj; +begin + if t = nil then mix(h, -1); return; end; + if (t^.obj # nil) and not top then + mix(h, t^.obj^.name); + if t^.obj^.home # nil then mix(h, t^.obj^.home^.sname); end; + return; + end; + mix(h, INT(t^.form)); + mix(h, bit(t^.vol) + 2 * bit(t^.variadic)); + mix(h, t^.len); + if t^.form in {fPtr, fArray, fSlice, fProc, fSet} then shape(h, t^.base, false); end; + f := t^.fields; + while f # nil do + if (t^.form # fRecord) or f^.exported then + mix(h, f^.name); + mix(h, bit(f^.isVar)); + shape(h, f^.typ, false); + g := f^.fields; + while g # nil do shape(h, g^.typ, false); g := g^.next; end; + end; + f := f^.next; + end; +end; + +proc fingerprint*(o: ^Obj): U64; +var h: U64; f: ^Obj; +begin + h := 0CBF29CE484222325H; (* FNV-1a's 64-bit offset basis *) + mix(h, INT(o^.cls)); + if o^.cls = oCase then + mix(h, o^.val); + f := o^.fields; + while f # nil do shape(h, f^.typ, false); f := f^.next; end; + else + shape(h, o^.typ, o^.cls = oType); + end; + return h; +end; + +(* The universe *) + +proc basic(name: []U8; form: Form; size: I64; signed: BOOL): ^Type; +var t: ^Type; o: ^Obj; +begin + t := newType(form, size, size); + t^.signed := signed; + o := newObj(oType, Scan.intern(ADR(name[0]), LEN(name)), t); + o^.exported := true; + t^.obj := o; + _ := insert(o, 0); + return t; +end; + +proc enter(name: []U8; cls: Class; t: ^Type; v: I64); +var o: ^Obj; +begin + o := newObj(cls, Scan.intern(ADR(name[0]), LEN(name)), t); + o^.val := v; + o^.exported := true; + _ := insert(o, 0); +end; + +begin + hashMask := (1 shl 14) - 1; + hashTab := emptyTable(hashMask + 1); + 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 Sym. diff --git a/src/X64.raz b/src/X64.raz new file mode 100644 index 0000000..a9a28bd --- /dev/null +++ b/src/X64.raz @@ -0,0 +1,1472 @@ +(* X64: machine code for x86-64. + + The encoder writes the instructions the code generator needs, and + no others, into the text of Chunk. 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 and the assembler's symbols; Diag, for + positions; Chunk for the code buffer and fixups. + Leaves out: choosing instructions; that is Gen. + + The seed's `Mem` that is too large an offset is marked and the code + goes on, since a function that makes an operand has no place to give + an error back from; the compile ends with the error shown. *) +module X64; +import Out, Fmt, Heap, Buf, Str, Diag, Scan, 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 + Mem* = record + base*: INT; (* a register, or RIP *) + index*: INT; (* a register, or NoIndex *) + scale*: INT; (* 1, 2, 4 or 8 *) + disp*: INT; + chunk*: INT; (* with RIP: the chunk addressed *) + end; + + (* The parser's reader of an integer constant in a code procedure: a + whole expression, or, when whole is false, a single factor *) + ConstFn* = proc(whole: BOOL): (I64, ERROR); + + (* The text of the instruction that starts at at, for the listing *) + Said = record + at: INT; + text: []U8; + end; + +var + listing*: BOOL; (* -S: each instruction's text is kept, for list *) + said: ^Said; + numSaid, saidCap: INT; + +proc setListing*(yes: BOOL); +begin + listing := yes; +end; + +(* Operands *) + +proc mem*(base: INT; disp: I64): Mem; +var m: Mem; +begin + if (disp < -2147483648) or (disp > 2147483647) then + _ := Scan.mark("an offset beyond 32 bits"); + end; + m.base := base; m.index := NoIndex; m.scale := 1; + m.disp := INT(disp); m.chunk := -1; + return m; +end; + +proc memRip*(chunk: INT; disp: INT): Mem; +var m: Mem; +begin + m.base := RIP; m.index := NoIndex; m.scale := 1; + m.disp := disp; m.chunk := chunk; + return m; +end; + +proc memIdx*(base, index, scale: INT; disp: I64): Mem; +var m: Mem; +begin + m := mem(base, disp); + m.index := index; + m.scale := scale; + return m; +end; + +(* The address of the code about to be written, as an operand *) +proc here*: Mem; +begin + return memRip(Chunk.curChunk, Chunk.pc - Chunk.chunks[Chunk.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. *) + +proc opcode(op: INT); +begin + repeat + Chunk.put1(op & 0FFH); + 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. *) +proc prefix(pfx: INT; w: BOOL; reg, index, base: INT; byte4: BOOL); +var rex: INT; +begin + if pfx # 0 then Chunk.put1(pfx); end; + rex := 0; + if w then rex := rex | 8; end; + if reg >= 8 then rex := rex | 4; end; + if index >= 8 then rex := rex | 2; end; + if base >= 8 then rex := rex | 1; end; + if (rex # 0) or byte4 then Chunk.put1(40H | rex); end; +end; + +(* op reg, [mem] *) +proc opM(pfx: INT; w: BOOL; op, reg: INT; m: Mem; byteReg: BOOL); +var md, b, sc: INT; +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); + end; + opcode(op); + reg := reg & 7; + if m.base = RIP then + Chunk.put1((reg shl 3) | 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). *) + Chunk.addFixup(Chunk.pc, m.chunk, m.disp); + Chunk.put4(0); + return; + end; + b := m.base & 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; + elsif (m.disp >= -128) and (m.disp <= 127) then + md := 1; + else + md := 2; + end; + (* 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 + Chunk.put1((md shl 6) | (reg shl 3) | 4); + if m.scale = 1 then sc := 0; elsif m.scale = 2 then sc := 1; elsif m.scale = 4 then sc := 2; else sc := 3; end; + if m.index = NoIndex then + Chunk.put1((sc shl 6) | (4 shl 3) | b); + else + Chunk.put1((sc shl 6) | ((m.index & 7) shl 3) | b); + end; + else + Chunk.put1((md shl 6) | (reg shl 3) | b); + end; + if md = 1 then + Chunk.put1(m.disp); + elsif md = 2 then + Chunk.put4(m.disp); + end; +end; + +(* op reg, rm (both registers) *) +proc opR(pfx: INT; w: BOOL; op, reg, rm: INT; byteReg: BOOL); +begin + prefix(pfx, w, reg, NoIndex, rm, byteReg and (((reg >= 4) and (reg <= 7)) or ((rm >= 4) and (rm <= 7)))); + opcode(op); + Chunk.put1(0C0H | ((reg & 7) shl 3) | (rm & 7)); +end; + +(* The listing: the text of each instruction, as it is made *) + +(* How many instructions the listing has, and back to n of them, for + code made again *) +proc saidCount*: INT; +begin + return numSaid; +end; + +proc unsay*(n: INT); +begin + numSaid := n; +end; + +proc sayAt*(at: INT; s: []U8); +begin + if not listing then return; end; + if numSaid = saidCap then + said := ^Said(Scan.regrab(^U8(said), numSaid * SIZE(Said), (saidCap * 2 + 1024) * SIZE(Said))); + saidCap := saidCap * 2 + 1024; + end; + said[numSaid].at := at; + said[numSaid].text := s; + INC(numSaid); +end; + +(* The text of the instruction about to be written *) +proc say*(s: []U8); +begin + sayAt(Chunk.pc, s); +end; + +(* The text of the instruction at at, said again, as when its operand is + patched *) +proc restate*(at: INT; s: []U8); +var i: INT; +begin + i := numSaid - 1; + while (i >= 0) and (said[i].at # at) do DEC(i); end; + if i >= 0 then said[i].text := s; end; +end; + +const + RegNames: [4][16][]U8 = [ + ["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*: [16][]U8 = ["o", "no", "b", "ae", "e", "ne", "be", "a", "s", "ns", "p", "np", "l", "ge", "le", "g"]; + AluNames: [8][]U8 = ["add", "or", "adc", "sbb", "and", "sub", "xor", "cmp"]; + ShiftNames: [8][]U8 = ["rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar"]; + UnaryNames: [8][]U8 = ["", "", "not", "neg", "mul", "imul", "div", "idiv"]; (* from 2 *) + +(* The name of register r, of size bytes *) +proc rnSized(r, size: INT): []U8; +begin + if size = 1 then return RegNames[3][r]; end; + if size = 2 then return RegNames[2][r]; end; + if size = 4 then return RegNames[1][r]; end; + return RegNames[0][r]; +end; + +proc rn(r: INT): []U8; +begin + return RegNames[0][r]; +end; + +proc xn(x: INT): []U8; +begin + return Diag.say("xmm{}", [Fmt.int(x)]); +end; + +(* A memory operand, with the size of what it holds, as the assembler + reads it *) +proc mnSized(m: Mem; size: INT): []U8; +var b: ^Buf.Buf; +begin + b := ^Buf.Buf(Scan.grab(SIZE(Buf.Buf))); + Buf.init(b, Heap.heap); + if size = 1 then Buf.str(b, "byte "); + elsif size = 2 then Buf.str(b, "word "); + elsif size = 4 then Buf.str(b, "dword "); + elsif size = 8 then Buf.str(b, "qword "); + end; + Buf.str(b, "["); + if m.base = RIP then Buf.str(b, Chunk.chunkName(m.chunk)); else Buf.str(b, rn(m.base)); end; + if m.index # NoIndex then Fmt.write(b, " + {} * {}", [Fmt.str(rn(m.index)), Fmt.int(m.scale)]); end; + if m.disp > 0 then + Fmt.write(b, " + {}", [Fmt.int(m.disp)]); + elsif m.disp < 0 then + Fmt.write(b, " - {}", [Fmt.int(-m.disp)]); + end; + Buf.str(b, "]"); + return Buf.bytes(b); +end; + +proc mn(m: Mem): []U8; +begin + return mnSized(m, 0); +end; + +(* "op a, b" and "op a" *) +proc text2(op, a, b: []U8): []U8; +begin + return Diag.say("{} {}, {}", [Fmt.str(op), Fmt.str(a), Fmt.str(b)]); +end; + +proc text1(op, a: []U8): []U8; +begin + return Diag.say("{} {}", [Fmt.str(op), Fmt.str(a)]); +end; + +(* v in decimal *) +proc num(v: INT): []U8; +begin + return Diag.say("{}", [Fmt.int(v)]); +end; + +proc movRR*(dst, src: INT); +begin + if listing then say(text2("mov", rn(dst), rn(src))); end; + opR(0, true, 89H, src, dst, false); +end; + +(* The operand-size prefix a size of 2 bytes takes *) +proc pfx16(size: INT): INT; +begin + if size = 2 then return 66H; end; + return 0; +end; + +(* The immediate of n bytes that ends an instruction *) +proc putImm(v, n: INT); +begin + if n = 4 then + Chunk.put4(v); + else + Chunk.put1(v & 0FFH); + if n = 2 then Chunk.put1((v shr 8) & 0FFH); end; + end; +end; + +(* op [m], v, on size bytes; v fits in them, or in 32 bits for 8 *) +proc aluMI*(op: INT; m: Mem; v, size: INT); +var n: INT; +begin + if listing then say(text2(AluNames[op], mnSized(m, size), num(v))); end; + if (size = 1) or ((v >= -128) and (v <= 127)) then + n := 1; + elsif size = 2 then + n := 2; + else + n := 4; + end; + if m.base = RIP then m.disp := m.disp - n; end; + if size = 1 then + opM(0, false, 80H, op, m, false); + elsif n = 1 then + opM(pfx16(size), size = 8, 83H, op, m, false); + else + opM(pfx16(size), size = 8, 81H, op, m, false); + end; + putImm(v, n); +end; + +(* mov [m], v, of size bytes; v fits in them, or in 32 bits for 8 *) +proc storeI*(m: Mem; v, size: INT); +var n: INT; +begin + if listing then say(text2("mov", mnSized(m, size), num(v))); end; + n := size; + if n > 4 then n := 4; end; + if m.base = RIP then m.disp := m.disp - n; end; + if size = 1 then + opM(0, false, 0C6H, 0, m, false); + else + opM(pfx16(size), size = 8, 0C7H, 0, m, false); + end; + putImm(v, n); +end; + +proc movRI*(r: INT; v: I64); +begin + if listing then + if v = 0 then + say(text2("xor", rnSized(r, 4), rnSized(r, 4))); + else + say(text2("mov", rn(r), Diag.say("{}", [Fmt.int(v)]))); + end; + end; + if (v >= -2147483648) and (v <= 2147483647) then + if v = 0 then + opR(0, false, 31H, r, r, false); (* xor r32, r32 *) + elsif v > 0 then (* mov r32, imm32 *) + prefix(0, false, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put4(INT(v)); + else + opR(0, true, 0C7H, 0, r, false); Chunk.put4(INT(v)); (* sign-extended imm32 *) + end; + elsif (v > 0) and (v <= 0FFFFFFFFH) then + prefix(0, false, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put4(INT(v)); + else + prefix(0, true, 0, NoIndex, r, false); Chunk.put1(0B8H + (r & 7)); Chunk.put8(v); + end; +end; + +proc load*(r: INT; m: Mem; size: INT; signed: BOOL); +begin + if listing then + if size = 8 then + say(text2("mov", rn(r), mn(m))); + elsif (size = 4) and not signed then + say(text2("mov", rnSized(r, 4), mn(m))); + elsif size = 4 then + say(text2("movsxd", rn(r), mnSized(m, 4))); + elsif signed then + say(text2("movsx", rn(r), mnSized(m, size))); + else + say(text2("movzx", rnSized(r, 4), mnSized(m, size))); + end; + end; + if size = 1 then + if signed then opM(0, true, 0BE0FH, r, m, false); else opM(0, false, 0B60FH, r, m, false); end; + elsif size = 2 then + if signed then opM(0, true, 0BF0FH, r, m, false); else opM(0, false, 0B70FH, r, m, false); end; + elsif size = 4 then + if signed then opM(0, true, 63H, r, m, false); else opM(0, false, 8BH, r, m, false); end; + else + opM(0, true, 8BH, r, m, false); + end; +end; + +proc store*(m: Mem; r: INT; size: INT); +begin + if listing then say(text2("mov", mn(m), rnSized(r, size))); end; + if size = 1 then + opM(0, false, 88H, r, m, true); + elsif size = 2 then + opM(66H, false, 89H, r, m, false); + elsif size = 4 then + opM(0, false, 89H, r, m, false); + else + opM(0, true, 89H, r, m, false); + end; +end; + +proc lea*(r: INT; m: Mem); +begin + if listing then say(text2("lea", rn(r), mn(m))); end; + opM(0, true, 8DH, r, m, false); +end; + +proc alu*(op, dst, src: INT); +begin + if listing then say(text2(AluNames[op], rn(dst), rn(src))); end; + opR(0, true, (op shl 3) | 1, src, dst, false); +end; + +proc aluI*(op, r: INT; v: INT); +begin + if listing then say(text2(AluNames[op], rn(r), num(v))); end; + if (v >= -128) and (v <= 127) then + opR(0, true, 83H, op, r, false); Chunk.put1(v); + else + opR(0, true, 81H, op, r, false); Chunk.put4(v); + end; +end; + +(* op r, [m] *) +proc aluM*(op, r: INT; m: Mem); +begin + if listing then say(text2(AluNames[op], rn(r), mn(m))); end; + opM(0, true, (op shl 3) | 3, r, m, false); +end; + +proc imul*(dst, src: INT); +begin + if listing then say(text2("imul", rn(dst), rn(src))); end; + opR(0, true, 0AF0FH, dst, src, false); +end; + +proc imulI*(r: INT; v: INT); +begin + if listing then say(Diag.say("imul {}, {}, {}", [Fmt.str(rn(r)), Fmt.str(rn(r)), Fmt.int(v)])); end; + opR(0, true, 69H, r, r, false); + Chunk.put4(v); +end; + +proc shift*(op, r: INT); +begin + if listing then say(text2(ShiftNames[op], rn(r), "cl")); end; + opR(0, true, 0D3H, op, r, false); +end; + +proc shiftI*(op, r, n: INT); +begin + if listing then say(text2(ShiftNames[op], rn(r), num(n))); end; + opR(0, true, 0C1H, op, r, false); + Chunk.put1(n); +end; + +(* F7 /ext: 2 not, 3 neg, 6 div, 7 idiv *) +proc unary*(ext, r: INT); +begin + if listing then say(text1(UnaryNames[ext], rn(r))); end; + opR(0, true, 0F7H, ext, r, false); +end; + +proc cqo*; +begin + if listing then say("cqo"); end; + Chunk.put1(48H); Chunk.put1(99H); +end; + +(* Brings a value of size bytes in r to 64 bits, by its sign or zeros. *) +proc extend*(r, size: INT; signed: BOOL); +begin + if listing then + if size = 4 then + if signed then + say(text2("movsxd", rn(r), rnSized(r, 4))); + else + say(text2("mov", rnSized(r, 4), rnSized(r, 4))); + end; + elsif signed then + say(text2("movsx", rn(r), rnSized(r, size))); + else + say(text2("movzx", rnSized(r, 4), rnSized(r, size))); + end; + end; + if size = 1 then + if signed then opR(0, true, 0BE0FH, r, r, true); else opR(0, false, 0B60FH, r, r, true); end; + elsif size = 2 then + if signed then opR(0, true, 0BF0FH, r, r, false); else opR(0, false, 0B70FH, r, r, false); end; + elsif size = 4 then + if signed then opR(0, true, 63H, r, r, false); else opR(0, false, 89H, r, r, false); end; + end; +end; + +(* r := 1 if the condition holds, else 0 *) +proc setCC*(cc, r: INT); +begin + if listing then say(text1(Diag.say("set{}", [Fmt.str(CondNames[cc])]), rnSized(r, 1))); end; + opR(0, false, 900FH + (cc shl 8), 0, r, true); + if listing then say(text2("movzx", rnSized(r, 4), rnSized(r, 1))); end; + opR(0, false, 0B60FH, r, r, true); +end; + +proc testRR*(a, b: INT); +begin + if listing then say(text2("test", rn(a), rn(b))); end; + opR(0, true, 85H, b, a, false); +end; + +proc push*(r: INT); +begin + if listing then say(text1("push", rn(r))); end; + if r >= 8 then Chunk.put1(41H); end; + Chunk.put1(50H + (r & 7)); +end; + +proc pop*(r: INT); +begin + if listing then say(text1("pop", rn(r))); end; + if r >= 8 then Chunk.put1(41H); end; + Chunk.put1(58H + (r & 7)); +end; + +proc callChunk*(c: INT); +begin + if listing then say(text1("call", Chunk.chunkName(c))); end; + Chunk.put1(0E8H); + Chunk.addFixup(Chunk.pc, c, 0); + Chunk.put4(0); +end; + +proc callBack*(target: INT); +begin + if listing then say("call"); end; + Chunk.put1(0E8H); + Chunk.put4(target - (Chunk.pc + 4)); +end; + +proc callR*(r: INT); +begin + if listing then say(text1("call", rn(r))); end; + opR(0, false, 0FFH, 2, r, false); +end; + +proc jmpR*(r: INT); +begin + if listing then say(text1("jmp", rn(r))); end; + opR(0, false, 0FFH, 4, r, false); +end; + +proc callM*(m: Mem); +begin + if listing then say(text1("call", mn(m))); end; + opM(0, false, 0FFH, 2, m, false); +end; + +proc ret*; +begin + if listing then say("ret"); end; + Chunk.put1(0C3H); +end; + +proc leave*; +begin + say("leave"); Chunk.put1(0C9H); +end; + +proc syscall*; +begin + say("syscall"); Chunk.put1(0FH); Chunk.put1(05H); +end; + +proc mfence*; +begin + say("mfence"); Chunk.put1(0FH); Chunk.put1(0AEH); Chunk.put1(0F0H); +end; + +proc ud2*; +begin + say("ud2"); Chunk.put1(0FH); Chunk.put1(0BH); +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 *) +proc align*(n: INT); +const + Nops: [8][]U8 = ["\x90", "\x66\x90", "\x0F\x1F\x00", "\x0F\x1F\x40\x00", + "\x0F\x1F\x44\x00\x00", "\x66\x0F\x1F\x44\x00\x00", "\x0F\x1F\x80\x00\x00\x00\x00", + "\x0F\x1F\x84\x00\x00\x00\x00\x00"]; +var k, i: INT; +begin + while Chunk.pc mod n # 0 do + k := n - Chunk.pc mod n; + if k > 8 then k := 8; end; + say("nop"); + for i := 0 to k - 1 do Chunk.put1(INT(Nops[k - 1][i])); end; + end; +end; + +proc repMovsb*; +begin + say("rep movsb"); Chunk.put1(0F3H); Chunk.put1(0A4H); +end; + +(* the direction flag, which has rep movsb go down, and back up *) +proc std*; +begin + say("std"); Chunk.put1(0FDH); +end; + +proc cld*; +begin + say("cld"); Chunk.put1(0FCH); +end; + +proc repStosb*; +begin + say("rep stosb"); Chunk.put1(0F3H); Chunk.put1(0AAH); +end; + +proc repeCmpsb*; +begin + say("repe cmpsb"); Chunk.put1(0F3H); Chunk.put1(0A6H); +end; + +proc lockCmpxchg*(m: Mem; r: INT); +begin + if listing then say(text2("lock cmpxchg", mn(m), rn(r))); end; + Chunk.put1(0F0H); + opM(0, true, 0B10FH, r, m, false); +end; + +proc xchg*(m: Mem; r: INT); +begin + if listing then say(text2("xchg", mn(m), rn(r))); end; + opM(0, true, 87H, r, m, false); +end; + +proc lockXadd*(m: Mem; r: INT); +begin + if listing then say(text2("lock xadd", mn(m), rn(r))); end; + Chunk.put1(0F0H); + opM(0, true, 0C10FH, r, m, false); +end; + +proc movqXR*(x, r: INT); +begin + if listing then say(text2("movq", xn(x), rn(r))); end; + opR(66H, true, 6E0FH, x, r, false); +end; + +proc movqRX*(r, x: INT); +begin + if listing then say(text2("movq", rn(r), xn(x))); end; + opR(66H, true, 7E0FH, x, r, false); +end; + +(* movaps: all of xmm y to xmm x, the shortest move between two *) +proc movX*(x, y: INT); +begin + if listing then say(text2("movaps", xn(x), xn(y))); end; + opR(0, false, 280FH, x, y, false); +end; + +(* The prefix of a real instruction, and the end of its name: sd, or ss for single *) +proc realPfx(single: BOOL): INT; +begin + if single then return 0F3H; end; + return 0F2H; +end; + +proc realEnd(single: BOOL): []U8; +begin + if single then return "ss"; end; + return "sd"; +end; + +(* The real instructions take single: F32 (ss) rather than F64 (sd) *) +proc movsXM*(x: INT; m: Mem; single: BOOL); +begin + if listing then say(text2(Diag.say("movs{}", [Fmt.str(realEnd(single)[1..2])]), xn(x), mn(m))); end; + opM(realPfx(single), false, 100FH, x, m, false); +end; + +proc movsMX*(m: Mem; x: INT; single: BOOL); +begin + if listing then say(text2(Diag.say("movs{}", [Fmt.str(realEnd(single)[1..2])]), mn(m), xn(x))); end; + opM(realPfx(single), false, 110FH, x, m, false); +end; + +proc sseName(op: INT; single: BOOL): []U8; +begin + if op = 58H then return Diag.say("add{}", [Fmt.str(realEnd(single))]); end; + if op = 59H then return Diag.say("mul{}", [Fmt.str(realEnd(single))]); end; + if op = 5CH then return Diag.say("sub{}", [Fmt.str(realEnd(single))]); end; + if op = 5EH then return Diag.say("div{}", [Fmt.str(realEnd(single))]); end; + return Diag.say("cvt{}2{}", [Fmt.str(realEnd(single)), Fmt.str(realEnd(not single))]); +end; + +(* 58 add, 59 mul, 5C sub, 5E div, 5A convert *) +proc sse*(op, x, y: INT; single: BOOL); +begin + if listing then say(text2(sseName(op, single), xn(x), xn(y))); end; + opR(realPfx(single), false, 0FH | (op shl 8), x, y, false); +end; + +(* The same, its right operand in memory: addsd x, [m] *) +proc sseM*(op, x: INT; m: Mem; single: BOOL); +begin + if listing then say(text2(sseName(op, single), xn(x), mn(m))); end; + opM(realPfx(single), false, 0FH | (op shl 8), x, m, false); +end; + +proc ucomis*(x, y: INT; single: BOOL); +begin + if listing then say(text2(Diag.say("ucomi{}", [Fmt.str(realEnd(single))]), xn(x), xn(y))); end; + if single then opR(0, false, 2E0FH, x, y, false); else opR(66H, false, 2E0FH, x, y, false); end; +end; + +proc cvtsi2s*(x, r: INT; single: BOOL); +begin + if listing then say(text2(Diag.say("cvtsi2{}", [Fmt.str(realEnd(single))]), xn(x), rn(r))); end; + opR(realPfx(single), true, 2A0FH, x, r, false); +end; + +proc cvtts2si*(r, x: INT; single: BOOL); +begin + if listing then say(text2(Diag.say("cvtt{}2si", [Fmt.str(realEnd(single))]), rn(r), xn(x))); end; + opR(realPfx(single), true, 2C0FH, r, x, false); +end; + +proc btc*(r, bit: INT); +begin + if listing then say(text2("btc", rn(r), num(bit))); end; + opR(0, true, 0BA0FH, 7, r, false); + Chunk.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. *) + +proc jmp*(var L: INT); +begin + if listing then say("jmp"); end; + Chunk.put1(0E9H); + Chunk.put4(L); + L := Chunk.pc - 4; +end; + +proc jcc*(cc: INT; var L: INT); +begin + if listing then say(Diag.say("j{}", [Fmt.str(CondNames[cc])])); end; + Chunk.put1(0FH); Chunk.put1(80H + cc); + Chunk.put4(L); + L := Chunk.pc - 4; +end; + +proc jmpBack*(target: INT); +begin + if listing then say("jmp"); end; + Chunk.put1(0E9H); + Chunk.put4(target - (Chunk.pc + 4)); +end; + +proc jccBack*(cc, target: INT); +begin + if listing then say(Diag.say("j{}", [Fmt.str(CondNames[cc])])); end; + Chunk.put1(0FH); Chunk.put1(80H + cc); + Chunk.put4(target - (Chunk.pc + 4)); +end; + +proc fixLinkTo*(L, target: INT); +var next: INT; +begin + while L # NoLabel do + next := Chunk.get4At(L); + Chunk.put4At(L, target - (L + 4)); + L := next; + end; +end; + +proc fixLink*(L: INT); +begin + fixLinkTo(L, Chunk.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. *) +proc dropJumpTo*(var L: INT); +begin + if (L = NoLabel) or (L # Chunk.pc - 4) or (Chunk.text[L - 1] # 0E9H) then return; end; + L := Chunk.get4At(L); + Chunk.takeBack(5); + if listing and (numSaid > 0) and (said[numSaid - 1].at = Chunk.pc) then DEC(numSaid); end; +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 *) +proc joinLinks*(L1, L2: INT): INT; +var L: INT; +begin + if L2 = NoLabel then return L1; end; + if L1 # NoLabel then + L := L2; + while Chunk.get4At(L) # NoLabel do L := Chunk.get4At(L); end; + Chunk.put4At(L, L1); + end; + return 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 + OpKind = (oReg, oXmm, oMem, oImm); + Operand = record + kind: OpKind; + r, size: INT; (* oReg, oXmm: the register and its size; oMem: its size, or 0 *) + m: Mem; + v: I64; (* oImm *) + end; + +(* The current symbol as a word: an identifier, or a reserved word that + is also an instruction *) +proc asmWord: []U8; +begin + match Scan.tok of + | sIdent: return Scan.nameOf(Scan.id); + | sAnd: return "and"; + | sOr: return "or"; + | sXor: return "xor"; + | sNot: return "not"; + | sDiv: return "div"; + | sShl: return "shl"; + | sShr: return "shr"; + | else: return ""; + end; +end; + +(* Whether w names a register: rax, eax, ax, al and so on, or xmm0 to + xmm15 (size 16); r and size are set if so *) +proc isReg(w: []U8; r, size: ^INT): BOOL; +const Sizes: [4]INT = [8, 4, 2, 1]; +var i, j, n, d: INT; +begin + for i := 0 to 3 do + for j := 0 to 15 do + if RegNames[i][j] = w then r^ := j; size^ := Sizes[i]; return true; end; + end; + end; + size^ := 16; + if not Str.hasPrefix(w, "xmm") or (LEN(w) <= 3) then return false; end; + (* the seed read the two bytes after xmm as a number, whatever follows *) + n := LEN(w) - 3; + if n > 2 then n := 2; end; + r^ := 0; + for i := 0 to n - 1 do + d := INT(w[3 + i]) - 48; + if (d < 0) or (d > 9) then return false; end; + r^ := r^ * 10 + d; + end; + return r^ <= 15; +end; + +(* Which word of list, a list of words each with a space either side, + w is, from 0; -1 if none *) +proc wordIndex(w: []U8; list: []U8): INT; +var i, n, start: INT; +begin + n := 0; + start := 1; + for i := 1 to LEN(list) - 1 do + if list[i] = ' ' then + if (i - start = LEN(w)) and (list[start..i] = w) then return n; end; + INC(n); + start := i + 1; + end; + end; + return -1; +end; + +(* w from byte from on, at most n bytes of it, as copy does *) +proc part(w: []U8; from, n: INT): []U8; +var e: INT; +begin + e := from + n; + if e > LEN(w) then e := LEN(w); end; + if from >= e then return ""; end; + return w[from..e]; +end; + +(* The condition a name ends in: e of je, nz of jnz *) +proc cond(w: []U8): INT; +const + Alias: [12][]U8 = ["c", "nae", "nc", "nb", "z", "nz", "na", "nbe", "nge", "nl", "ng", "nle"]; + AliasCc: [12]INT = [2, 2, 3, 3, 4, 5, 6, 7, 12, 13, 14, 15]; +var i: INT; +begin + for i := 0 to 15 do + if CondNames[i] = w then return i; end; + end; + for i := 0 to 11 do + if Alias[i] = w then return AliasCc[i]; end; + end; + return -1; +end; + +proc operand(o: ^Operand; constExpr: ConstFn): ERROR; +var w: []U8; r, size, sz: INT; st: Scan.State; v: I64; isR, wasMinus: BOOL; +begin + o^ := {}; + w := asmWord(); + sz := 0; + if w = "byte" then sz := 1; + elsif w = "word" then sz := 2; + elsif w = "dword" then sz := 4; + elsif w = "qword" then sz := 8; + end; + if sz # 0 then Scan.next; w := asmWord(); end; + if Scan.tok = Scan.sLbrak then + (* [base + index * scale + disp], the displacement last *) + Scan.next; + o^.kind := oMem; o^.size := sz; + o^.m := mem(NoBase, 0); + repeat + if isReg(asmWord(), ADR(r), ADR(size)) and (size = 8) then + Scan.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 Scan.tok = Scan.sTimes then + Scan.next; + o^.m.index := r; + v := try constExpr(false); + o^.m.scale := INT(v); + elsif o^.m.base = NoBase then + o^.m.base := r; + else + o^.m.index := r; o^.m.scale := 1; + end; + else + v := try constExpr(true); + o^.m.disp := o^.m.disp + INT(v); + end; + if (Scan.tok # Scan.sPlus) and (Scan.tok # Scan.sMinus) then break; end; + wasMinus := Scan.tok = Scan.sMinus; + Scan.saveScan(st); + Scan.next; + isR := isReg(asmWord(), ADR(r), ADR(size)); + if not isR and wasMinus then Scan.restoreScan(st); end; + until false; + if (Scan.tok # Scan.sRbrak) or (o^.m.base = NoBase) + or not ((o^.m.scale = 1) or (o^.m.scale = 2) or (o^.m.scale = 4) or (o^.m.scale = 8)) then + return Scan.mark("expected a memory operand, [base + index * scale + disp]"); + end; + Scan.next; + elsif isReg(w, ADR(o^.r), ADR(o^.size)) then + if o^.size = 16 then o^.kind := oXmm; else o^.kind := oReg; end; + Scan.next; + else + o^.kind := oImm; + o^.v := try constExpr(true); + end; + return nil; +end; + +(* op with register reg and the register or memory operand o *) +proc rm(pfx: INT; w: BOOL; op, reg: INT; o: Operand; byteReg: BOOL); +begin + if o.kind = oMem then opM(pfx, w, op, reg, o.m, byteReg); else opR(pfx, w, op, reg, o.r, byteReg); end; +end; + +proc putImmV(v: I64; size: INT); +begin + if size = 1 then + Chunk.put1(INT(v & 0FFH)); + elsif size = 2 then + Chunk.put1(INT(v & 0FFH)); Chunk.put1(INT((v shr 8) & 0FFH)); + else + Chunk.put4(INT(v & 0FFFFFFFFH)); + end; +end; + +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: [7]INT = [51H, 58H, 59H, 5CH, 5DH, 5EH, 5FH]; + (* 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: [10]INT = [60H, 61H, 74H, 70H, 0DBH, 0DFH, 0EBH, 0EFH, 0FCH, 0F8H]; + (* bit scans and counts: reg, reg or memory, with the prefix and code that tell them *) + BitOps = " bsf bsr tzcnt lzcnt popcnt "; + BitPfx: [5]INT = [0, 0, 0F3H, 0F3H, 0F3H]; + BitCodes: [5]INT = [0BC0FH, 0BD0FH, 0BC0FH, 0BD0FH, 0B80FH]; + Plain: [15][]U8 = ["ret", "leave", "syscall", "cpuid", "rdtsc", + "pause", "nop", "ud2", "int3", "hlt", "cqo", "cdq", "mfence", "lfence", "sfence"]; + PlainOp: [15]INT = [0C3H, 0C9H, 050FH, 0A20FH, 310FH, + 90F3H, 90H, 0B0FH, 0CCH, 0F4H, 9948H, 99H, 0F0AE0FH, 0E8AE0FH, 0F8AE0FH]; + +var + (* the instruction being assembled *) + aw: []U8; (* its word *) + ao: [3]Operand; (* its operands *) + an: INT; (* how many *) + asize, apfx: INT; + awide, abyte: BOOL; + aat: Diag.Pos; (* where it starts *) + (* the labels of the procedure *) + lnames, lplaces, lchains: [64]INT; + lusedAt: [64]Diag.Pos; + numLabels: INT; + +(* The label called n, entered if new *) +proc lab(n: INT): (INT, ERROR); +var i: INT; +begin + for i := 0 to numLabels - 1 do + if lnames[i] = n then return i, nil; end; + end; + if numLabels > 63 then return 0, Scan.mark("more than 64 labels"); end; + lnames[numLabels] := n; lplaces[numLabels] := -1; lchains[numLabels] := NoLabel; + lusedAt[numLabels] := Scan.tokPos(); + numLabels := numLabels + 1; + return numLabels - 1, nil; +end; + +proc bad: ERROR; +begin + return Scan.markAt(aat, Diag.say("can't assemble {} with these operands", [Fmt.str(aw)])); +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) *) +proc two(toRM, fromRM, opImm, digit: INT): ERROR; +var b: INT; +begin + b := 0; + if abyte then b := 1; end; + if an # 2 then return bad(); end; + if ao[1].kind = oImm then + if (ao[0].kind = oImm) or (opImm < 0) then return bad(); end; + if (opImm = 81H) and not abyte and (ao[1].v >= -128) and (ao[1].v <= 127) then + rm(apfx, awide, 83H, digit, ao[0], false); (* a byte, sign-extended *) + Chunk.put1(INT(ao[1].v & 0FFH)); + else + rm(apfx, awide, opImm - b, digit, ao[0], false); + putImmV(ao[1].v, asize); + end; + elsif (ao[1].kind = oReg) and ((ao[0].kind = oReg) or (ao[0].kind = oMem)) then + rm(apfx, awide, toRM - b, ao[1].r, ao[0], abyte); + elsif (ao[0].kind = oReg) and (ao[1].kind = oMem) then + rm(apfx, awide, fromRM - b, ao[0].r, ao[1], abyte); + else + return bad(); + end; + return nil; +end; + +(* whether operand i is an xmm register or a memory operand *) +proc isXM(i: INT): BOOL; +begin + return (ao[i].kind = oXmm) or (ao[i].kind = oMem); +end; + +(* whether operand i is a general register or a memory operand, for an + xmm register's partner *) +proc isRMem(i: INT): BOOL; +begin + return (ao[i].kind = oReg) or (ao[i].kind = oMem); +end; + +(* b as 1 for true *) +proc bit(f: BOOL): INT; +begin + if f then return 1; end; + return 0; +end; + +(* The instruction w with its operands, in ao and an, apart from the + jumps to labels and db, which assemble does *) +proc instruction(): ERROR; +var k: INT; +begin + if wordIndex(aw, Alus) >= 0 then + k := wordIndex(aw, Alus); + return two(k * 8 + 1, k * 8 + 3, 81H, k); + elsif aw = "mov" then + if (an = 2) and (ao[0].kind = oReg) and (ao[1].kind = oImm) and (asize >= 4) then + if awide then + movRI(ao[0].r, ao[1].v); + else + prefix(0, false, 0, NoIndex, ao[0].r, false); Chunk.put1(0B8H + (ao[0].r & 7)); Chunk.put4(INT(ao[1].v & 0FFFFFFFFH)); + end; + return nil; + end; + return two(89H, 8BH, 0C7H, 0); + elsif aw = "test" then + return two(85H, 85H, 0F7H, 0); + elsif aw = "xchg" then + return two(87H, 87H, -1, 0); + elsif (aw = "cmpxchg") or (aw = "xadd") then + if (an # 2) or (ao[1].kind # oReg) then return bad(); end; + if aw = "xadd" then k := 0C10FH; else k := 0B10FH; end; + rm(apfx, awide, k - (bit(abyte) shl 8), ao[1].r, ao[0], abyte); + elsif aw = "lea" then + if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind # oMem) then return bad(); end; + rm(apfx, awide, 8DH, ao[0].r, ao[1], false); + elsif (aw = "movzx") or (aw = "movsx") or (aw = "movsxd") then + if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end; + if aw = "movsxd" then + k := 63H; + elsif ao[1].size = 1 then + k := 0B60FH; + elsif ao[1].size = 2 then + k := 0B70FH; + else + return bad(); + end; + if aw = "movsx" then k := k + 0800H; end; + rm(apfx, awide, k, ao[0].r, ao[1], ao[1].size = 1); + elsif ((wordIndex(aw, Unaries) >= 0) and (an = 1)) or (aw = "inc") or (aw = "dec") then + if ao[0].kind = oImm then return bad(); end; + if aw = "inc" then + rm(apfx, awide, 0FFH - bit(abyte), 0, ao[0], abyte); + elsif aw = "dec" then + rm(apfx, awide, 0FFH - bit(abyte), 1, ao[0], abyte); + else + rm(apfx, awide, 0F7H - bit(abyte), wordIndex(aw, Unaries) + 2, ao[0], abyte); + end; + elsif aw = "imul" then + if (an < 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end; + if an = 2 then + rm(apfx, awide, 0AF0FH, ao[0].r, ao[1], false); + else + rm(apfx, awide, 69H, ao[0].r, ao[1], false); + putImmV(ao[2].v, asize); + end; + elsif wordIndex(aw, Shifts) >= 0 then + k := wordIndex(aw, Shifts); + if k = 6 then k := 4; end; (* sal is shl *) + if (an # 2) or (ao[0].kind = oImm) then return bad(); end; + if ao[1].kind = oImm then + rm(apfx, awide, 0C1H - bit(abyte), k, ao[0], abyte); + Chunk.put1(INT(ao[1].v & 0FFH)); + elsif (ao[1].kind = oReg) and (ao[1].r = RCX) and (ao[1].size = 1) then + rm(apfx, awide, 0D3H - bit(abyte), k, ao[0], abyte); + else + return bad(); + end; + elsif (aw = "push") or (aw = "pop") then + if (an # 1) or (ao[0].kind # oReg) or not awide then return bad(); end; + if aw = "push" then push(ao[0].r); else pop(ao[0].r); end; + elsif (aw = "call") or (aw = "jmp") then + if (an # 1) or (ao[0].kind = oImm) then return bad(); end; + if aw = "call" then rm(0, false, 0FFH, 2, ao[0], false); else rm(0, false, 0FFH, 4, ao[0], false); end; + elsif Str.hasPrefix(aw, "set") and (cond(part(aw, 3, 3)) >= 0) then + if (an # 1) or (ao[0].kind = oImm) or (asize # 1) then return bad(); end; + rm(0, false, 900FH + (cond(part(aw, 3, 3)) shl 8), 0, ao[0], true); + elsif Str.hasPrefix(aw, "cmov") and (cond(part(aw, 4, 3)) >= 0) then + if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) then return bad(); end; + rm(apfx, awide, 400FH + (cond(part(aw, 4, 3)) shl 8), ao[0].r, ao[1], false); + elsif (LEN(aw) > 2) and (wordIndex(aw[0..LEN(aw) - 2], SseOps) >= 0) + and ((aw[LEN(aw) - 2..LEN(aw)] = "sd") or (aw[LEN(aw) - 2..LEN(aw)] = "ss")) then + (* sqrtsd, addss and the like: xmm, xmm or memory *) + if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end; + k := 0FH | (SseCodes[wordIndex(aw[0..LEN(aw) - 2], SseOps)] shl 8); + rm(realPfx(aw[LEN(aw) - 1] = 's'), false, k, ao[0].r, ao[1], false); + elsif wordIndex(aw, PackedOps) >= 0 then + if (an < 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end; + k := wordIndex(aw, PackedOps); + rm(66H, false, 0FH | (PackedCodes[k] shl 8), ao[0].r, ao[1], false); + if aw = "pshufd" then + if (an # 3) or (ao[2].kind # oImm) then return bad(); end; + Chunk.put1(INT(ao[2].v & 0FFH)); + elsif an # 2 then + return bad(); + end; + elsif (aw = "movdqu") or (aw = "movdqa") then + (* the load is 6F and the store 7F; movdqu is F3, movdqa 66 *) + if aw = "movdqu" then k := 0F3H; else k := 66H; end; + if (an = 2) and (ao[0].kind = oXmm) and isXM(1) then + rm(k, false, 6F0FH, ao[0].r, ao[1], false); + elsif (an = 2) and (ao[0].kind = oMem) and (ao[1].kind = oXmm) then + rm(k, false, 7F0FH, ao[1].r, ao[0], false); + else + return bad(); + end; + elsif aw = "pmovmskb" then + if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind # oXmm) then return bad(); end; + rm(66H, false, 0D70FH, ao[0].r, ao[1], false); + elsif wordIndex(aw, BitOps) >= 0 then + if (an # 2) or (ao[0].kind # oReg) or (ao[1].kind = oImm) or (asize < 4) then return bad(); end; + k := wordIndex(aw, BitOps); + rm(BitPfx[k], awide, BitCodes[k], ao[0].r, ao[1], false); + elsif (aw = "movsd") or (aw = "movss") then + if aw = "movsd" then k := 0F2H; else k := 0F3H; end; + if (an = 2) and (ao[0].kind = oXmm) and isXM(1) then + rm(k, false, 100FH, ao[0].r, ao[1], false); + elsif (an = 2) and (ao[0].kind = oMem) and (ao[1].kind = oXmm) then + rm(k, false, 110FH, ao[1].r, ao[0], false); + else + return bad(); + end; + elsif (aw = "movq") or (aw = "movd") then + if (an = 2) and (ao[0].kind = oXmm) and isRMem(1) then + rm(66H, aw = "movq", 6E0FH, ao[0].r, ao[1], false); + elsif (an = 2) and (ao[1].kind = oXmm) and isRMem(0) then + rm(66H, aw = "movq", 7E0FH, ao[1].r, ao[0], false); + else + return bad(); + end; + elsif (aw = "ucomisd") or (aw = "ucomiss") then + if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end; + if aw = "ucomisd" then + rm(66H, false, 2E0FH, ao[0].r, ao[1], false); + else + rm(0, false, 2E0FH, ao[0].r, ao[1], false); + end; + elsif (aw = "cvtsi2sd") or (aw = "cvtsi2ss") then + if (an # 2) or (ao[0].kind # oXmm) or not isRMem(1) then return bad(); end; + rm(realPfx(aw = "cvtsi2ss"), ao[1].size # 4, 2A0FH, ao[0].r, ao[1], false); + elsif (aw = "cvttsd2si") or (aw = "cvttss2si") then + if (an # 2) or (ao[0].kind # oReg) or not isXM(1) then return bad(); end; + rm(realPfx(aw = "cvttss2si"), awide, 2C0FH, ao[0].r, ao[1], false); + elsif (aw = "cvtsd2ss") or (aw = "cvtss2sd") then + if (an # 2) or (ao[0].kind # oXmm) or not isXM(1) then return bad(); end; + rm(realPfx(aw = "cvtss2sd"), false, 5A0FH, ao[0].r, ao[1], false); + else + k := 0; + while (k <= 14) and (Plain[k] # aw) do INC(k); end; + if (k > 14) or (an # 0) then + return Scan.markAt(aat, Diag.say("unknown instruction {}", [Fmt.str(aw)])); + end; + opcode(PlainOp[k]); + end; + return nil; +end; + +(* One instruction or label, as assemble reads it *) +proc statement(constExpr: ConstFn): ERROR; +var + i, k, cc, first: INT; wasListing: BOOL; start: Diag.Pos; v: I64; +begin + aat := Scan.tokPos(); + aw := asmWord(); + if LEN(aw) = 0 then return Scan.mark("expected an instruction"); end; + Scan.next; + if Scan.tok = Scan.sColon then + sayAt(Chunk.pc, Diag.say("{}:", [Fmt.str(aw)])); + k := try lab(Scan.intern(ADR(aw[0]), LEN(aw))); + if lplaces[k] >= 0 then + return Scan.markAt(aat, Diag.say("label {} is defined twice", [Fmt.str(aw)])); + end; + lplaces[k] := Chunk.pc; + fixLink(lchains[k]); + Scan.next; + return nil; + end; + first := Chunk.pc; + wasListing := listing; + listing := false; (* the instruction is said as it is written *) + if aw = "lock" then + Chunk.put1(0F0H); + aw := asmWord(); + Scan.next; + end; + cc := -1; + if aw = "db" then + repeat + start := Scan.tokPos(); + v := try constExpr(true); + if (v < -128) or (v > 255) then + return Scan.markAt(Scan.spanFrom(start), Diag.say("expected a byte from 0 to 255, found {}", [Fmt.int(v)])); + end; + Chunk.put1(INT(v & 0FFH)); + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + elsif (aw[0] = 'j') and ((aw = "jmp") or (cond(part(aw, 1, 3)) >= 0)) and (Scan.tok = Scan.sIdent) then + (* a jump to a label *) + k := try lab(Scan.id); + Scan.next; + if aw # "jmp" then cc := cond(part(aw, 1, 3)); end; + if lplaces[k] >= 0 then + if cc < 0 then jmpBack(lplaces[k]); else jccBack(cc, lplaces[k]); end; + elsif cc < 0 then + jmp(lchains[k]); + else + jcc(cc, lchains[k]); + end; + else + an := 0; + if Scan.tok # Scan.sSemicolon then + repeat + if an > 2 then return Scan.mark("too many operands"); end; + try operand(ADR(ao[an]), constExpr); + INC(an); + if Scan.tok # Scan.sComma then break; end; + Scan.next; + until false; + end; + (* the size: a register's, or what the memory operand says *) + asize := 8; + for i := an - 1 to 0 by -1 do + if (ao[i].kind = oReg) or ((ao[i].kind = oMem) and (ao[i].size # 0)) then asize := ao[i].size; end; + end; + if an > 0 then + if (ao[0].kind = oReg) or ((ao[0].kind = oMem) and (ao[0].size # 0)) then asize := ao[0].size; end; + end; + awide := asize = 8; + abyte := asize = 1; + if asize = 2 then apfx := 66H; else apfx := 0; end; + try instruction(); + end; + if Scan.tok # Scan.sSemicolon then return Scan.mark("expected \";\""); end; + listing := wasListing; + sayAt(first, Diag.source(Scan.spanFrom(aat))); + Scan.next; + return nil; +end; + +proc assemble*(constExpr: ConstFn): ERROR; +var k: INT; +begin + numLabels := 0; + while (Scan.tok # Scan.sEnd) and (Scan.tok # Scan.sEof) do + if Scan.tok = Scan.sSemicolon then + Scan.next; + else + try statement(constExpr); + end; + end; + for k := 0 to numLabels - 1 do + if lplaces[k] < 0 then + return Scan.markAt(lusedAt[k], Diag.say("label {} isn't defined", [Fmt.str(Scan.nameOf(lnames[k]))])); + end; + end; + return nil; +end; + +(* Whether s holds a space *) +proc hasSpace(s: []U8): BOOL; +var i: INT; +begin + for i := 0 to LEN(s) - 1 do + if s[i] = ' ' then return true; end; + end; + return false; +end; + +(* n, in decimal, at least w wide, as write(n: w) *) +proc padded(n, w: INT); +var s: []U8; i: INT; +begin + s := Diag.say("{}", [Fmt.int(n)]); + for i := LEN(s) to w - 1 do Out.str(" "); end; + Out.str(s); +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. *) +proc list*(home: INT); +var order: ^INT; n, i, j, k, c, t, line: INT; text: []U8; +begin + order := ^INT(Scan.grab(Chunk.numChunks * SIZE(INT))); + n := 0; + for c := 0 to Chunk.numChunks - 1 do + if Chunk.chunks[c].live and (Chunk.chunks[c].sec = Chunk.secText) and (Chunk.chunks[c].home = home) then + i := n; + while (i > 0) and (Chunk.chunks[order[i - 1]].start > Chunk.chunks[c].start) do + order[i] := order[i - 1]; + DEC(i); + end; + order[i] := c; + INC(n); + end; + end; + i := 0; j := 0; + for k := 0 to n - 1 do + c := order[k]; + Out.ln; + Out.str(Chunk.chunkName(c)); Out.str(":\n"); + line := -1; + while (i < numSaid) and (said[i].at < Chunk.chunks[c].start) do INC(i); end; + while (i < numSaid) and (said[i].at < Chunk.chunks[c].start + Chunk.chunks[c].size) do + while (j < Chunk.numLines) and (Chunk.lines[j].at <= said[i].at) do + if (Chunk.lines[j].chunk = c) and (Chunk.lines[j].line # line) then + line := Chunk.lines[j].line; + padded(line, 6); + Out.str(" "); + Out.str(Diag.lineText(Scan.nameOf(Chunk.lines[j].path), line)); + Out.ln; + end; + INC(j); + end; + text := said[i].text; + t := said[i].at; + if (text = "jmp") or (text = "call") then + text := Diag.say("{} {}", [Fmt.str(text), Fmt.int(t + 5 + Chunk.get4At(t + 1) - Chunk.chunks[c].start)]); + elsif (text[0] = 'j') and not hasSpace(text) then + text := Diag.say("{} {}", [Fmt.str(text), Fmt.int(t + 6 + Chunk.get4At(t + 2) - Chunk.chunks[c].start)]); + end; + padded(t - Chunk.chunks[c].start, 14); + Out.str(" "); + Out.str(text); + Out.ln; + INC(i); + end; + end; +end; + +begin + listing := false; + numSaid := 0; + saidCap := 0; + said := nil; +end X64. diff --git a/src/bench.sh b/src/bench.sh new file mode 100755 index 0000000..3a89687 --- /dev/null +++ b/src/bench.sh @@ -0,0 +1,34 @@ +#!/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 src/check.sh has built the tests. +set -e +b=build/self +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.self src/test/ScanBench.raz +echo "$(wc -l <$b/Bench.raz) lines" +for t in seed self; 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 self; do + if [ $t = seed ]; then cp raz build/cmp/raz; else cp $b/raz.self build/cmp/raz; fi + best=0 + for i in 1 2 3 4 5; do + s=$(date +%s%N); build/cmp/raz -o build/cmp/bench/Bench.$t build/cmp/bench/Bench.raz; e=$(date +%s%N) + d=$(( (e - s) / 1000000 )); if [ $best = 0 ] || [ $d -lt $best ]; then best=$d; fi + done + echo "compile, $t: $best ms" +done diff --git a/src/check.sh b/src/check.sh new file mode 100755 index 0000000..340a3af --- /dev/null +++ b/src/check.sh @@ -0,0 +1,180 @@ +#!/bin/sh +# Tests src/'s units against the seed's: each dumper reads the same +# files and must give the same standard output, standard error and +# status. Run from the repository root, after `make raz`; the seed's +# side is built by fpc from seed/. +set -e +b=build/self +mkdir -p $b +fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/scandump.seed src/test/ScanDump.pas >/dev/null +./raz -Werror -I src -o $b/scandump.self src/test/ScanDump.raz +python3 src/test/genreals.py > $b/reals.raz +# one small file for each message the scanner makes, and the places +# diag shows them in: a tab, a long line, characters before the place +mkdir -p $b/lex +python3 src/test/genlex.py $b/lex +n=0; bad=0 +for f in $b/lex/*.raz lib/*.raz examples/*.raz tools/*.raz src/*.raz src/test/*.raz test/run/*.raz test/err/*.raz \ + conform/*/*.raz $b/reals.raz; do + [ -f "$f" ] || continue + s1=0; s2=0 + $b/scandump.seed $f >$b/seed.out 2>$b/seed.err || s1=$? + $b/scandump.self $f >$b/self.out 2>$b/self.err || s2=$? + n=$((n + 1)) + if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.err; then + echo "differs: $f (status $s1 and $s2)"; bad=$((bad + 1)) + fi +done +echo "$n files, $bad differ" +test $bad = 0 + +# Jump: a parser's way of going on after an error +./raz -Werror -I src -o $b/recover src/test/Recover.raz +printf 'a bad b bad bad c\nd bad\n' >$b/rec.raz +r=$($b/recover $b/rec.raz 2>/dev/null) || test $? = 1 +test "$r" = "8 names, 4 failed, 4 errors" && echo "recover ok" + +# Chunk and Sym: a fixed pseudo-random script each, run by both sides, +# which print all they have made or answered; Sym also ends, as the +# argument says, in an error, whose message and status must agree +for u in Chunk Sym; do + l=$(echo $u | tr A-Z a-z) + fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/${l}dump.seed src/test/${u}Dump.pas >/dev/null + ./raz -Werror -I src -o $b/${l}dump.self src/test/${u}Dump.raz +done +for a in "" dup deep; do + for s in seed self; do + t=0; $b/chunkdump.$s >$b/chunk.$s 2>/dev/null || t=$? + t2=0; $b/symdump.$s $a >$b/sym.$s.out 2>$b/sym.$s.err || t2=$? + echo "$t $t2" >$b/status.$s + done + cmp $b/status.seed $b/status.self + cmp $b/chunk.seed $b/chunk.self + cmp $b/sym.seed.out $b/sym.self.out + cmp $b/sym.seed.err $b/sym.self.err +done +echo "chunk and sym ok" + +# Link and Elf: a program of chunks made by a script, linked and written +# as a static, a dynamic and a stripped executable, which must be the +# same file from both sides +fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/linkdump.seed src/test/LinkDump.pas >/dev/null +./raz -Werror -I src -o $b/linkdump.self src/test/LinkDump.raz +for m in 0 1 2; do + $b/linkdump.seed $m $b/link.seed + $b/linkdump.self $m $b/link.self + cmp $b/link.seed $b/link.self +done +echo "link and elf ok" + +# X64: every encoder, then the assembler on a long run of instructions +# of every kind and a file for each error it makes; the bytes and the +# listing, or the message and status, must be the same +fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/x64dump.seed src/test/X64Dump.pas >/dev/null +./raz -Werror -I src -o $b/x64dump.self src/test/X64Dump.raz +$b/x64dump.seed >$b/x64.seed +$b/x64dump.self >$b/x64.self +cmp $b/x64.seed $b/x64.self +fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/asmdump.seed src/test/AsmDump.pas >/dev/null +./raz -Werror -I src -o $b/asmdump.self src/test/AsmDump.raz +mkdir -p $b/asm +python3 src/test/genasm.py $b/asm +n=0; bad=0 +for f in $b/asm/*.raz; do + s1=0; s2=0 + $b/asmdump.seed $f >$b/seed.out 2>$b/seed.err || s1=$? + $b/asmdump.self $f >$b/self.out 2>$b/self.err || s2=$? + n=$((n + 1)) + if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.err; then + echo "differs: $f (status $s1 and $s2)"; bad=$((bad + 1)) + fi +done +echo "x64: $n assembler files, $bad differ" +test $bad = 0 + +# Gen: procedures made by a script of calls (expressions, statements, +# calls, frames, checks, defers, the entry point), whose bytes, fixups, +# line notes and listing must be the same; once with the static entry +# point and once with the dynamic one +fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/gendump.seed src/test/GenDump.pas >/dev/null +./raz -Werror -I src -o $b/gendump.self src/test/GenDump.raz +for a in "" dyn; do + $b/gendump.seed $a >$b/gen.seed + $b/gendump.self $a >$b/gen.self + cmp $b/gen.seed $b/gen.self +done +echo "gen ok" + +# Item: operands and operations driven by a script with mistakes in it, +# which show their messages and go on; what each step gave, the code +# made and the messages must be the same. A run ends at the 20th error, +# as a compile does, so the script changes with each argument. +fpc -O2 -Mobjfpc -Sh- -vew -FUbuild -Fuseed -o$b/itemdump.seed src/test/ItemDump.pas >/dev/null +./raz -Werror -I src -o $b/itemdump.self src/test/ItemDump.raz +n=0; bad=0 +for a in $(seq 0 59); do + s1=0; s2=0 + $b/itemdump.seed $a >$b/seed.out 2>$b/seed.err || s1=$? + $b/itemdump.self $a >$b/self.out 2>$b/self.err || s2=$? + n=$((n + 1)) + if [ $s1 != $s2 ] || ! cmp -s $b/seed.out $b/self.out || ! cmp -s $b/seed.err $b/self.err; then + echo "differs: item script $a (status $s1 and $s2)"; bad=$((bad + 1)) + fi +done +echo "item: $n scripts, $bad differ" +test $bad = 0 + +# Parse and Raz: the compiler this makes, built by the seed, compiles +# what the seed compiles, to the same file, with the same messages and +# status: every example, test and tool, and the library, with each +# one's own options. Both sides run as build/cmp/raz, since a program +# holds the paths it was made from and the library is found beside the +# compiler. +printf 'module Version;\nconst Text* = "%s";\nend Version.\n' "$(tr -d "'" < build/version.inc)" >$b/Version.raz +./raz -Werror -I src -I $b -o $b/raz.self src/Raz.raz +c=build/cmp +mkdir -p $c +ln -sfn ../../lib $c/lib +# and the big program that times the compiler, 348,025 lines +mkdir -p $c/bench +python3 test/genbench.py 12000 >$c/bench/Bench.raz +files= +for f in $c/bench/Bench.raz lib/*.raz examples/*.raz tools/*.raz src/*.raz test/run/*.raz test/libc/*.raz test/bench/*.raz \ + conform/run/*.raz test/err/*.raz conform/err/*.raz; do + files="$files $f" +done +for side in seed self; do + rm -rf $c/$side + mkdir -p $c/$side + if [ $side = seed ]; then cp raz $c/raz; else cp $b/raz.self $c/raz; fi + for f in $files; do + dir=$(dirname $f); name=$(basename $f .raz); x=$(echo $dir | tr / _).$name + flags= + case $dir in + examples|tools|lib|src) flags=-Werror ;; + esac + [ -f $dir/$name.args ] && [ $dir = test/err ] && flags="$flags $(cat $dir/$name.args)" + case $dir in + lib) opts= ;; + src|tools) opts="-I src -I build/self" ;; + test/err) opts="-I test/err/mods -I test/run/mods" ;; + *) opts="-I $dir/mods" ;; + esac + s=0 + $c/raz $flags $opts -o $c/$side/$x $f >$c/$side/$x.out 2>$c/$side/$x.err || s=$? + echo $s >$c/$side/$x.status + done +done +n=0; bad=0 +for f in $files; do + x=$(dirname $f | tr / _).$(basename $f .raz) + n=$((n + 1)) + for e in "" .out .err .status; do + [ -f $c/seed/$x$e ] || [ -f $c/self/$x$e ] || continue + if ! cmp -s $c/seed/$x$e $c/self/$x$e; then + echo "differs: $f ($x$e)"; bad=$((bad + 1)); break + fi + done +done +echo "raz: $n files, $bad differ" +test $bad = 0 diff --git a/src/chunk.pas b/src/chunk.pas deleted file mode 100644 index 91b6dff..0000000 --- a/src/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/src/diag.pas b/src/diag.pas deleted file mode 100644 index 9480509..0000000 --- a/src/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/src/elf.pas b/src/elf.pas deleted file mode 100644 index 79b576f..0000000 --- a/src/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/src/fixpoint.sh b/src/fixpoint.sh new file mode 100755 index 0000000..73c3a38 --- /dev/null +++ b/src/fixpoint.sh @@ -0,0 +1,27 @@ +#!/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 +# 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. +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 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 $d/stage3 raz +make check +make bench diff --git a/src/gen.pas b/src/gen.pas deleted file mode 100644 index aeed68b..0000000 --- a/src/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/src/item.pas b/src/item.pas deleted file mode 100644 index e2afc4f..0000000 --- a/src/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/src/link.pas b/src/link.pas deleted file mode 100644 index edf0611..0000000 --- a/src/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/src/parse.pas b/src/parse.pas deleted file mode 100644 index 58ca27a..0000000 --- a/src/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/src/raz.pas b/src/raz.pas deleted file mode 100644 index c0ef892..0000000 --- a/src/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/src/scan.pas b/src/scan.pas deleted file mode 100644 index ac8f725..0000000 --- a/src/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/src/sym.pas b/src/sym.pas deleted file mode 100644 index 29c01fd..0000000 --- a/src/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/src/test/AsmDump.pas b/src/test/AsmDump.pas new file mode 100644 index 0000000..5df5959 --- /dev/null +++ b/src/test/AsmDump.pas @@ -0,0 +1,46 @@ +{ Assembles the instructions in the file of the argument, as the body of + a code procedure that ends in end, and prints the bytes and the + listing: the seed's side of a test of the assembler in src/X64.raz, + whose AsmDump.raz does the same and prints the same. Constants are + numbers, with a minus sign, and sums of them. } +program asmdump; +{$mode objfpc}{$H-} +uses diag, scan, chunk, x64; +var i: longint; path: string; + +function ConstVal(whole: boolean): int64; +var neg: boolean; v: int64; +begin + neg := tok = sMinus; + if neg then Next; + if tok <> sInt then Mark('expected a number'); + v := ival; + Next; + if neg then v := -v; + while whole and (tok in [sPlus, sMinus]) do begin + neg := tok = sMinus; + Next; + if tok <> sInt then Mark('expected a number'); + if neg then v := v - ival else v := v + ival; + Next; + end; + ConstVal := v; +end; + +begin + if Open(ParamStr(1)) <> '' then Fatal('no file'); + path := 'lib/Rt.raz'; + curFile := Intern(@path[1], length(path)); + listing := true; + NewChunk(secText, 0, 0); + BeginChunk(0); + NoteLine(1, 1); + Next; + Assemble(@ConstVal); + EndChunk(0); + chunks^[0].live := true; + for i := 0 to pc - 1 do write(HexStr(code^[i], 2)); + writeln; + List(0); + Finish; +end. diff --git a/src/test/AsmDump.raz b/src/test/AsmDump.raz new file mode 100644 index 0000000..61cda72 --- /dev/null +++ b/src/test/AsmDump.raz @@ -0,0 +1,55 @@ +(* Assembles the instructions in the file of the argument, as the body of + a code procedure that ends in end, and prints the bytes and the + listing: src/X64.raz's assembler's side of a test against the seed's, + AsmDump.pas, which prints the same. Constants are numbers, with a + minus sign, and sums of them. *) +module AsmDump; +import Out, Files, Diag, Scan, Chunk, X64; + +proc number(neg: BOOL): (I64, ERROR); +var v: I64; +begin + if Scan.tok # Scan.sInt then return 0, Scan.mark("expected a number"); end; + v := Scan.ival; + Scan.next; + if neg then v := -v; end; + return v, nil; +end; + +proc constant(whole: BOOL): (I64, ERROR); +var neg: BOOL; v, w: I64; +begin + neg := Scan.tok = Scan.sMinus; + if neg then Scan.next; end; + v := try number(neg); + while whole and ((Scan.tok = Scan.sPlus) or (Scan.tok = Scan.sMinus)) do + neg := Scan.tok = Scan.sMinus; + Scan.next; + w := try number(neg); + v := v + w; + end; + return v, nil; +end; + +proc main*; +var i: INT; path: []U8; err: ERROR; +begin + if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end; + path := "lib/Rt.raz"; + Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path))); + X64.setListing(true); + _ := Chunk.newChunk(Chunk.secText, 0, 0); + Chunk.beginChunk(0); + Chunk.noteLine(1, 1); + Scan.next; + err := X64.assemble(constant); + if err # nil then Diag.finish; end; + Chunk.endChunk(0); + Chunk.setLive(0); + for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end; + Out.ln; + X64.list(0); + Diag.finish; +end; + +end AsmDump. diff --git a/src/test/ChunkDump.pas b/src/test/ChunkDump.pas new file mode 100644 index 0000000..3eb721f --- /dev/null +++ b/src/test/ChunkDump.pas @@ -0,0 +1,89 @@ +{ Makes a program of chunks by a fixed pseudo-random script and prints + all of it: the seed's side of a test of src/Chunk.raz, whose + ChunkDump.raz does the same and prints the same. } +program chunkdump; +{$mode objfpc}{$H-} +uses diag, scan, chunk; +var + seed: int64; + names: array[0..7] of longint; + i, k, n, op, c, sum, open, x, y, z: longint; + b: array[0..63] of byte; + +function Rnd(n: longint): longint; +begin + seed := (seed * 1103515245 + 12345) and $7FFFFFFF; + Rnd := (seed shr 8) mod n; +end; + +begin + seed := 7; + for i := 0 to 7 do begin b[0] := 97 + i; names[i] := Intern(@b[0], 1) end; + open := -1; + sum := 0; + for k := 1 to 30000 do begin + op := Rnd(16); + case op of + 0..3: Put1(Rnd(256)); + 4: begin x := Rnd(1 shl 30); y := Rnd(1 shl 30); Put4(x - y) end; + 5: begin x := Rnd(1 shl 30); y := Rnd(1 shl 30); Put8(int64(x) * 4096 - y) end; + 6: begin + if open >= 0 then EndChunk(open); + x := Rnd(5); y := Rnd(9); + open := NewChunk(secText, x - 1, y - 1); + BeginChunk(open); + end; + 7: begin x := Rnd(8); curFile := names[x]; x := Rnd(300); y := Rnd(80); NoteLine(x, y) end; + 8: if numChunks > 0 then begin x := Rnd(numChunks); y := Rnd(100); AddFixup(pc, x, y - 50) end; + 9: if (open >= 0) and (pc - chunks^[open].start > 8) then begin x := Rnd(6); TakeBack(x) end; + 10: begin + x := Rnd(5); y := Rnd(9); + c := NewChunk(secRodata, x - 1, y - 1); + n := Rnd(64); + for i := 0 to n - 1 do b[i] := Rnd(256); + x := Rnd(4); + SetData(c, @b[0], n, 1 shl x); + n := Rnd(4); + for i := 1 to n do begin x := Rnd(8); y := Rnd(numChunks); z := Rnd(10); AddDataFixup(c, x * 8, y, z) end; + end; + 11: begin + x := Rnd(5); y := Rnd(9); + c := NewChunk(secBss, x - 1, y - 1); + x := Rnd(100); y := Rnd(4); + SetBss(c, x, 1 shl y); + end; + 12: begin x := Rnd(8); c := ExternChunk(names[x]) end; + 13: if numChunks > 0 then begin + x := Rnd(numChunks); y := Rnd(8); z := Rnd(200); n := Rnd(5); + NoteVar(x, names[y], z - 100, n); + end; + 14: if pc >= 8 then begin + x := Rnd(1 shl 30); y := Rnd(1 shl 30); + Put4At(pc - 8, x - y); + sum := (sum + Get4At(pc - 8)) and $FFFFFF; + end; + 15: if numChunks > 0 then begin + x := Rnd(numChunks); chunks^[x].live := true; + x := Rnd(numChunks); y := Rnd(1 shl 30); chunks^[x].adr := y; + end; + end; + end; + if open >= 0 then EndChunk(open); + writeln('sum ', sum, ' pc ', pc, ' rolen ', rolen); + for i := 0 to numChunks - 1 do + with chunks^[i] do + writeln('C ', i, ' ', ord(sec), ' ', start, ' ', size, ' ', align, ' ', firstFix, ' ', numFix, ' ', + module, ' ', name, ' ', adr, ' ', ord(live), ' ', ord(ext), ' ', ChunkName(i)); + for i := 0 to numFixups - 1 do + writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend); + for i := 0 to numDataFixups - 1 do + writeln('D ', dataFixups^[i].at, ' ', dataFixups^[i].chunk, ' ', dataFixups^[i].addend); + for i := 0 to numLines - 1 do + writeln('L ', lines^[i].at, ' ', lines^[i].chunk, ' ', lines^[i].path, ' ', lines^[i].line, ' ', lines^[i].col); + for i := 0 to numVarNotes - 1 do + writeln('V ', varNotes[i].chunk, ' ', varNotes[i].name, ' ', varNotes[i].off, ' ', varNotes[i].kind); + for i := 0 to pc - 1 do write(HexStr(code^[i], 2)); + writeln; + for i := 0 to rolen - 1 do write(HexStr(rodata^[i], 2)); + writeln; +end. diff --git a/src/test/ChunkDump.raz b/src/test/ChunkDump.raz new file mode 100644 index 0000000..30a025c --- /dev/null +++ b/src/test/ChunkDump.raz @@ -0,0 +1,118 @@ +(* Makes a program of chunks by a fixed pseudo-random script and prints + all of it: src/Chunk.raz's side of a test against the seed's, + ChunkDump.pas, which prints the same. *) +module ChunkDump; +import Out, Fmt, Scan, Chunk; + +var seed: I64; + +proc rnd(n: INT): INT; +begin + seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; + return INT((seed shr 8) mod I64(n)); +end; + +(* a flag, as the number the seed's side prints for it *) +proc bit(f: BOOL): INT; +begin + if f then return 1; end; + return 0; +end; + +proc main*; +var + names: [8]INT; b: [64]U8; + i, k, n, op, c, sum, open, x, y, z: INT; +begin + seed := 7; + for i := 0 to 7 do b[0] := U8(97 + i); names[i] := Scan.intern(ADR(b[0]), 1); end; + open := -1; + sum := 0; + for k := 1 to 30000 do + op := rnd(16); + match op of + | 0..3: Chunk.put1(rnd(256)); + | 4: x := rnd(1 shl 30); y := rnd(1 shl 30); Chunk.put4(x - y); + | 5: x := rnd(1 shl 30); y := rnd(1 shl 30); Chunk.put8(I64(x) * 4096 - I64(y)); + | 6: + if open >= 0 then Chunk.endChunk(open); end; + x := rnd(5); y := rnd(9); + open := Chunk.newChunk(Chunk.secText, x - 1, y - 1); + Chunk.beginChunk(open); + | 7: + x := rnd(8); Chunk.setCurFile(names[x]); + x := rnd(300); y := rnd(80); Chunk.noteLine(x, y); + | 8: + if Chunk.numChunks > 0 then + x := rnd(Chunk.numChunks); y := rnd(100); Chunk.addFixup(Chunk.pc, x, y - 50); + end; + | 9: + if (open >= 0) and (Chunk.pc - Chunk.chunks[open].start > 8) then + x := rnd(6); Chunk.takeBack(x); + end; + | 10: + x := rnd(5); y := rnd(9); + c := Chunk.newChunk(Chunk.secRodata, x - 1, y - 1); + n := rnd(64); + for i := 0 to n - 1 do b[i] := U8(rnd(256)); end; + x := rnd(4); + Chunk.setData(c, ADR(b[0]), n, 1 shl x); + n := rnd(4); + for i := 1 to n do + x := rnd(8); y := rnd(Chunk.numChunks); z := rnd(10); + Chunk.addDataFixup(c, x * 8, y, z); + end; + | 11: + x := rnd(5); y := rnd(9); + c := Chunk.newChunk(Chunk.secBss, x - 1, y - 1); + x := rnd(100); y := rnd(4); + Chunk.setBss(c, x, 1 shl y); + | 12: x := rnd(8); c := Chunk.externChunk(names[x]); + | 13: + if Chunk.numChunks > 0 then + x := rnd(Chunk.numChunks); y := rnd(8); z := rnd(200); n := rnd(5); + Chunk.noteVar(x, names[y], z - 100, n); + end; + | 14: + if Chunk.pc >= 8 then + x := rnd(1 shl 30); y := rnd(1 shl 30); + Chunk.put4At(Chunk.pc - 8, x - y); + sum := (sum + Chunk.get4At(Chunk.pc - 8)) & 0FFFFFFH; + end; + | else: + if Chunk.numChunks > 0 then + x := rnd(Chunk.numChunks); Chunk.setLive(x); + x := rnd(Chunk.numChunks); y := rnd(1 shl 30); Chunk.setAdr(x, y); + end; + end; + end; + if open >= 0 then Chunk.endChunk(open); end; + Fmt.print("sum {} pc {} rolen {}\n", [Fmt.int(sum), Fmt.int(Chunk.pc), Fmt.int(Chunk.rolen)]); + for i := 0 to Chunk.numChunks - 1 do + Fmt.print("C {} {} {} {} {} {} {} {} {} {} {} {} {}\n", [Fmt.int(i), Fmt.int(INT(Chunk.chunks[i].sec)), + Fmt.int(Chunk.chunks[i].start), Fmt.int(Chunk.chunks[i].size), Fmt.int(Chunk.chunks[i].align), + Fmt.int(Chunk.chunks[i].firstFix), Fmt.int(Chunk.chunks[i].numFix), Fmt.int(Chunk.chunks[i].home), + Fmt.int(Chunk.chunks[i].name), Fmt.int(Chunk.chunks[i].adr), + Fmt.int(bit(Chunk.chunks[i].live)), Fmt.int(bit(Chunk.chunks[i].ext)), Fmt.str(Chunk.chunkName(i))]); + end; + for i := 0 to Chunk.numFixups - 1 do + Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]); + end; + for i := 0 to Chunk.numDataFixups - 1 do + Fmt.print("D {} {} {}\n", [Fmt.int(Chunk.dataFixups[i].at), Fmt.int(Chunk.dataFixups[i].chunk), Fmt.int(Chunk.dataFixups[i].addend)]); + end; + for i := 0 to Chunk.numLines - 1 do + Fmt.print("L {} {} {} {} {}\n", [Fmt.int(Chunk.lines[i].at), Fmt.int(Chunk.lines[i].chunk), + Fmt.int(Chunk.lines[i].path), Fmt.int(Chunk.lines[i].line), Fmt.int(Chunk.lines[i].col)]); + end; + for i := 0 to Chunk.numVarNotes - 1 do + Fmt.print("V {} {} {} {}\n", [Fmt.int(Chunk.varNotes[i].chunk), Fmt.int(Chunk.varNotes[i].name), + Fmt.int(Chunk.varNotes[i].off), Fmt.int(Chunk.varNotes[i].kind)]); + end; + for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end; + Out.ln; + for i := 0 to Chunk.rolen - 1 do Out.hex(U64(Chunk.rodata[i]), 2); end; + Out.ln; +end; + +end ChunkDump. diff --git a/src/test/GenDump.pas b/src/test/GenDump.pas new file mode 100644 index 0000000..0cbf6f5 --- /dev/null +++ b/src/test/GenDump.pas @@ -0,0 +1,708 @@ +{ Compiles procedures made by a fixed pseudo-random script of calls to + Gen, valid by construction, then prints the bytes, the fixups and the + listing (raz -S) of what it made: the seed's side of a test of + src/Gen.raz, whose GenDump.raz makes and prints the same. With an + argument, the entry point is the dynamic one. } +program gendump; +{$mode objfpc}{$H-} +uses diag, scan, sym, chunk, x64, gen; + +const + FirstProc = 3; + NumProcs = 80; + FirstGlob = FirstProc + NumProcs; + NumGlobs = 4; + Arith: array[0..9] of TSym = (sPlus, sMinus, sTimes, sDiv, sMod, sAmp, sBar, sXor, sShl, sShr); + Cmps: array[0..5] of TSym = (sEql, sNeq, sLss, sLeq, sGtr, sGeq); + RealOps: array[0..3] of TSym = (sPlus, sMinus, sTimes, sSlash); + +var + seed: int64; + slots: array[0..5] of int64; + regs: array[0..4] of longint; + numRegs: longint; + xregs: array[0..3] of longint; + numX: longint; + tuple2, tuple3, record3, sliceT: PType; + results: array[0..8] of PType; + curRes: longint; + +function Rnd(n: longint): longint; +begin + seed := (seed * 1103515245 + 12345) and $7FFFFFFF; + Rnd := (seed shr 8) mod n; +end; + +function Pos: TPos; +var p: TPos; +begin + p.f := 0; p.a := Rnd(400); p.b := p.a + 1; + Pos := p; +end; + +function Size: longint; +begin + Size := 1 shl Rnd(4); +end; + +function Slot: int64; +begin + Slot := slots[Rnd(6)]; +end; + +function Bit(f: boolean): longint; +begin + if f then Bit := 1 else Bit := 0; +end; + +function Flag: boolean; +begin + Flag := Rnd(2) = 0; +end; + +function ConstVal: int64; +var x: longint; r: int64; +begin + x := Rnd(1 shl 30); + case Rnd(7) of + 0: r := x mod 10; + 1: r := -(x mod 100); + 2: r := int64(1) shl (x mod 20); + 3: r := x; + 4: r := int64(x) * 4096 * 4096 * 9 - 7; + 5: r := -int64(x) * 8; + else r := x mod 1000 - 500; + end; + ConstVal := r; +end; + +function NewObjs(t: PType; n: longint): PObj; +var first, o, last: PObj; i: longint; +begin + first := nil; last := nil; + for i := 0 to n - 1 do begin + o := NewObj(oVar, 0, t); + o^.val := 8 * i; + if last = nil then first := o else last^.next := o; + last := o; + end; + NewObjs := first; +end; + +procedure MakeTypes; +begin + tuple2 := NewType(fRecord, 16, 8); + tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := NewObjs(tInt, 2); + tuple3 := NewType(fRecord, 24, 8); + tuple3^.tuple := true; tuple3^.len := 3; tuple3^.fields := NewObjs(tInt, 3); + record3 := NewType(fRecord, 24, 8); + record3^.fields := NewObjs(tReal, 3); + sliceT := NewType(fSlice, 16, 8); + sliceT^.base := tU8; + results[0] := nil; + results[1] := tInt; + results[2] := tReal; + results[3] := sliceT; + results[4] := tuple2; + results[5] := tuple3; + results[6] := tF32; + results[7] := tI16; + results[8] := record3; +end; + +function MemAdr: TAdr; +var a: TAdr; c: longint; +begin + c := Rnd(3); + if c = 0 then begin + a.base := bFrame; a.chunk := 0; a.hi := 0; a.off := Slot; if Flag then a.off := a.off + 8; + end else if c = 1 then begin + a.base := bGlobal; a.chunk := FirstGlob + Rnd(NumGlobs); a.hi := 0; a.off := 8 * Rnd(3); + end else begin + a.base := bSlot; a.chunk := Slot; a.hi := 0; a.off := 8 * Rnd(3); + end; + MemAdr := a; +end; + +function PushableAdr: TAdr; +var a: TAdr; +begin + a.chunk := 0; a.hi := 0; + if Flag then begin + a.base := bFrame; a.off := Slot; if Flag then a.off := a.off + 8; + end else begin + a.base := bGlobal; a.chunk := FirstGlob + Rnd(NumGlobs); a.off := 8 * Rnd(3); + end; + PushableAdr := a; +end; + +function RegAdr(r: longint): TAdr; +var a: TAdr; +begin + a.base := bReg; a.chunk := r; a.hi := 0; a.off := 0; + RegAdr := a; +end; + +function StackAdr: TAdr; +var a: TAdr; +begin + a.base := bStack; a.chunk := 0; a.hi := 0; a.off := 8 * Rnd(3); + StackAdr := a; +end; + +procedure PushIntVar; +var a: TAdr; sz, c: longint; +begin + sz := Size; + c := Rnd(5); + if (c = 0) and (numRegs > 0) then begin + if Flag then inPlace := regs[Rnd(numRegs)]; + PushVar(RegAdr(regs[Rnd(numRegs)]), 8, false, kWord); + end else if c = 1 then begin + PushAdr(PushableAdr); + a := StackAdr; + PushVar(a, sz, Flag, kWord); + end else begin + a := MemAdr; + PushVar(a, sz, Flag, kWord); + end; +end; + +procedure IntExpr(b: longint); forward; +procedure RealExpr(k: TKind; b: longint); forward; +procedure CallExpr(want, b: longint); forward; + +function RealKind: TKind; +begin + if Flag then RealKind := kF64 else RealKind := kF32; +end; + +procedure IntExpr(b: longint); +var c, sz, n: longint; sg, f: boolean; k: TKind; sy: TSym; a: TAdr; +begin + if b > 0 then c := Rnd(14) else c := Rnd(3); + case c of + 0: PushConst(kWord, ConstVal); + 1: PushIntVar; + 2: PushIntVar; + 3, 4, 5: begin + IntExpr(b - 1); IntExpr(b - 1); + sy := Arith[Rnd(10)]; sz := Size; sg := Flag; + Op(sy, kWord, sz, sg); + end; + 6: + if Flag then begin + IntExpr(b - 1); IntExpr(b - 1); + sy := Cmps[Rnd(6)]; sg := Flag; + Compare(sy, kWord, sg); + end else begin + k := RealKind; + RealExpr(k, b - 1); RealExpr(k, b - 1); + sy := Cmps[Rnd(6)]; + Compare(sy, k, false); + end; + 7: begin + IntExpr(b - 1); + n := Rnd(4); sz := Size; sg := Flag; + if n = 0 then Neg(kWord, sz, sg) + else if n = 1 then Complement(sz, sg) + else if n = 2 then NotBool + else Narrow(sz, sg); + end; + 8: begin + IntExpr(b - 1); + a := PushableAdr; + sz := Size; sg := Flag; + n := 10 + Rnd(100); + CheckIndex(n, Pos); + IndexArray(a, sz); + a := StackAdr; a.off := 0; + PushVar(a, sz, sg, kWord); + end; + 9: begin + n := Rnd(3); + sz := Size; sg := Flag; + if n = 0 then begin + a := MemAdr; + if a.base = bGlobal then a.base := bFrame; + IntExpr(b - 1); + f := Flag; + IndexSlice(a, sz, f, Pos); + end else if n = 1 then begin + PushAdr(PushableAdr); + IntExpr(b - 1); + a := StackAdr; a.off := 0; + f := Flag; + IndexSlice(a, sz, f, Pos); + end else begin + a.base := bReg; a.chunk := R13; a.hi := R14; a.off := 0; + IntExpr(b - 1); + f := Flag; + IndexSlice(a, sz, f, Pos); + end; + a := StackAdr; a.off := 0; + PushVar(a, sz, sg, kWord); + end; + 10: begin + k := RealKind; + RealExpr(k, b - 1); + RealToInt(k); + end; + 11: CallExpr(1, b - 1); + 12: begin + IntExpr(b - 1); + PushConst(kWord, Rnd(100) - 50); + Op(sPlus, kWord, 8, false); + end; + else begin + IntExpr(b - 1); + PushConst(kWord, ConstVal); + sy := Arith[Rnd(10)]; sz := Size; sg := Flag; + Op(sy, kWord, sz, sg); + end; + end; +end; + +procedure RealExpr(k: TKind; b: longint); +var c, n: longint; sy: TSym; a: TAdr; k2: TKind; v: int64; +begin + if b > 0 then c := Rnd(9) else c := Rnd(3); + case c of + 0: begin + n := Rnd(4); + if n = 0 then v := $3FF0000000000000 + else if n = 1 then v := $4000000000000000 + else if n = 2 then v := 0 + else v := $3FE0000000000000; + PushConst(k, v); + end; + 1: begin + a := MemAdr; + if k = kF32 then PushVar(a, 4, false, k) else PushVar(a, 8, false, k); + end; + 2: + if numX > 0 then begin + if Flag then inPlace := xregs[Rnd(numX)]; + PushVar(RegAdr(xregs[Rnd(numX)]), 8, false, k); + end else begin + PushAdr(PushableAdr); + a := StackAdr; + PushVar(a, 8, false, k); + end; + 3, 4: begin + RealExpr(k, b - 1); RealExpr(k, b - 1); + sy := RealOps[Rnd(4)]; + Op(sy, k, 8, false); + end; + 5: begin + IntExpr(b - 1); + IntToReal(k, Flag); + end; + 6: begin + RealExpr(k, b - 1); + Neg(k, 8, false); + end; + 7: begin + if k = kF32 then k2 := kF64 else k2 := kF32; + RealExpr(k2, b - 1); + RealToReal(k2); + end; + else CallExpr(2, b - 1); + end; +end; + +procedure CallExpr(want, b: longint); +var + c: TCall; sig: PType; i, n, kind, r, ni: longint; k: TKind; +begin + sig := NewType(fProc, 8, 8); + sig^.variadic := Rnd(5) = 0; + if want = 1 then begin + r := Rnd(5); + if r = 0 then sig^.base := tBool + else if r = 1 then sig^.base := tI8 + else if r = 2 then sig^.base := tU32 + else if r = 3 then sig^.base := tuple2 + else sig^.base := tInt; + end else if want = 2 then begin + if Flag then sig^.base := tReal else sig^.base := tF32; + end else + sig^.base := results[Rnd(9)]; + c.sig := sig; c.param := nil; c.obj := nil; c.ext := Rnd(4) = 0; + c.n := 0; c.target := 0; + c.chunk := FirstProc + Rnd(NumProcs); + if Rnd(5) = 0 then begin c.chunk := -1; c.ext := false; c.target := Slot end; + n := Rnd(8); + for i := 0 to n - 1 do begin + kind := Rnd(4); + if kind = 0 then begin + k := RealKind; + RealExpr(k, b); + c.isF[c.n] := true; c.pair[c.n] := false; + inc(c.n); + end else if kind = 1 then begin + IntExpr(b); IntExpr(b); + c.isF[c.n] := false; c.pair[c.n] := true; + c.isF[c.n + 1] := false; c.pair[c.n + 1] := false; + inc(c.n, 2); + end else begin + IntExpr(b); + c.isF[c.n] := false; c.pair[c.n] := false; + inc(c.n); + end; + end; + Call(c); + ni := 0; + if sig^.base <> nil then begin + if sig^.base^.form = fSlice then ni := 0 + else if sig^.base = tuple2 then ni := 2 + else if BehindPointer(sig^.base) then ni := 0 + else ni := 1; + end; + if want = 0 then begin + for i := 1 to ni do Drop; + end else if ni = 2 then + Drop; +end; + +procedure BoolExpr(b: longint); +var sy: TSym; sg: boolean; +begin + if Flag then begin + IntExpr(b); IntExpr(b); + sy := Cmps[Rnd(6)]; sg := Flag; + Compare(sy, kWord, sg); + end else + IntExpr(b); +end; + +procedure Stmt(b: longint); forward; + +procedure Assign(b: longint); +var a: TAdr; c, sz: longint; k: TKind; +begin + c := Rnd(6); + sz := Size; + if c = 0 then begin + a := MemAdr; + IntExpr(b); + PopVar(a, sz); + end else if c = 1 then begin + PushAdr(PushableAdr); + a := StackAdr; + IntExpr(b); + PopVar(a, sz); + end else if (c = 2) and (numRegs > 0) then begin + a := RegAdr(regs[Rnd(numRegs)]); + inPlace := a.chunk; + PushVar(a, 8, false, kWord); + IntExpr(b); + Op(Arith[Rnd(3)], kWord, 8, false); + PopVar(a, 8); + end else if (c = 3) and (numX > 0) then begin + k := RealKind; + a := RegAdr(xregs[Rnd(numX)]); + RealExpr(k, b); + PopVar(a, 8); + end else if c = 4 then begin + k := RealKind; + a := MemAdr; + RealExpr(k, b); + if k = kF32 then PopVar(a, 4) else PopVar(a, 8); + end else begin + a := MemAdr; + PushConst(kWord, ConstVal); + PopVar(a, sz); + end; +end; + +procedure RetStmt(b: longint); +var i: longint; +begin + if curRes = 1 then IntExpr(b) + else if curRes = 7 then IntExpr(b) + else if curRes = 2 then RealExpr(kF64, b) + else if curRes = 6 then RealExpr(kF32, b) + else if (curRes = 3) or (curRes = 4) then begin IntExpr(b); IntExpr(b) end + else if curRes = 5 then begin + for i := 0 to 2 do begin IntExpr(b); ResultTo(8 * i, 8) end; + end else if curRes = 8 then begin + PushAdr(PushableAdr); + CopyResult(0, 24); + end; + ReturnJump; +end; + +procedure Stmt(b: longint); +var + c, n, lo, i, start, saved, sz, tmp: longint; L, E, S, fj, tj: longint; a, a2: TAdr; sy: TSym; sg: boolean; + mk: int64; f: boolean; +begin + mk := TempMark; + if b <= 0 then c := Rnd(4) else c := Rnd(22); + case c of + 0, 1, 2, 3: Assign(b); + 4: begin + L := NoLabel; + BoolExpr(b); + JumpIf(L, false); + Stmt(b - 1); + Fix(L); + end; + 5: begin + L := NoLabel; + AlignLoop; + start := pc; + BoolExpr(b); + JumpIf(L, false); + Stmt(b - 1); + JumpBack(start); + Fix(L); + end; + 6: begin + L := NoLabel; + IntExpr(b); IntExpr(b); + sy := Cmps[Rnd(6)]; sg := Flag; + if Flag then JumpCmp(sy, sg, L) else JumpOut(sy, sg, L); + Stmt(b - 1); + Fix(L); + end; + 7: begin + fj := NoLabel; tj := NoLabel; + IntExpr(b); IntExpr(b); + sy := Cmps[Rnd(6)]; sg := Flag; + CondValue(sy, sg, fj, tj); + a := MemAdr; + PopVar(a, 1); + end; + 8: CallExpr(0, b); + 9: begin + a := MemAdr; + if a.base = bSlot then begin a.base := bFrame; a.off := slots[0] end; + IntExpr(b); + PopVar(a, 8); + E := NoLabel; + n := 2 + Rnd(4); lo := Rnd(5) - 2; + if Flag then S := NoLabel else S := pc; + start := JumpTable(a.off, lo, n, S, E); + for i := 0 to n - 1 do TableEntry(start, pc + 4 * (n - i)); + for i := 0 to n - 1 do + Stmt(b - 1); + Fix(E); + end; + 10: begin + PushAdr(PushableAdr); PushAdr(PushableAdr); + n := 1 + Rnd(150); lo := 8 * Rnd(3); + CopyBlock(n, lo); + end; + 11: begin + PushAdr(PushableAdr); + a := MemAdr; + if Flag and (numRegs > 1) then begin + a.base := bReg; a.chunk := regs[0]; a.hi := regs[1]; a.off := 0; + end; + n := 1 + Rnd(150); + CopyTo(a, n); + end; + 12: begin + a := MemAdr; + n := 1 + Rnd(100); + ZeroVar(a, n); + end; + 13: begin + tmp := AllocTemp(16, 8); + n := Rnd(3); + sz := Size; sg := Flag; + if n = 0 then begin + a := PushableAdr; + PushAdr(a); IntExpr(b); IntExpr(b); + a := StackAdr; a.off := 0; + f := Flag; n := 10 + Rnd(50); + Slice(a, f, n, sz, tmp, sg, Pos); + end else if n = 1 then begin + a := MemAdr; + if a.base = bGlobal then a.base := bFrame; + IntExpr(b); IntExpr(b); + Slice(a, false, 0, sz, tmp, sg, Pos); + end else begin + IntExpr(b); IntExpr(b); IntExpr(b); + SlicePtr(sz, tmp, sg, Pos); + end; + end; + 14: begin + a.off := Slot; a2.off := Slot; sz := Size; f := Flag; + CopySlice(a.off, a2.off, sz, f, Pos); + end; + 15: begin + n := Rnd(4); sz := Size; sg := Flag; + if n = 0 then begin + PushAdr(PushableAdr); IntExpr(b); + f := Flag; + IncDec(sz, sg, f); + end else if (n = 1) and (numRegs > 0) then begin + IntExpr(b); + IncDecReg(regs[0], sz, sg, Flag); + end else if n = 2 then begin + IntExpr(b); + n := 3 + Rnd(6); lo := FirstGlob + Rnd(NumGlobs); + CheckEnum(n, lo, Pos); + Drop; + end else begin + IntExpr(b); + n := Rnd(8000); + CheckNil(n, Pos); + Drop; + end; + end; + 16: begin + n := Rnd(3); + if n = 0 then begin + a.off := Slot; a2.off := Slot; n := Rnd(4); f := Flag; + CompareSeq(a.off, a2.off, n, f); + Drop; + end else if n = 1 then begin + IntExpr(b); + ErrorText(AllocTemp(16, 8)); + end else begin + IntExpr(b); + n := 1 + Rnd(200); + ZeroNew(n); + Drop; + end; + end; + 17: begin + n := Rnd(3); + if n = 0 then begin + IntExpr(b); IntExpr(b); IntExpr(b); + Atomic(bCas); + end else if n = 1 then begin + IntExpr(b); IntExpr(b); + Atomic(bXchg); + end else begin + IntExpr(b); IntExpr(b); + Atomic(bXadd); + end; + Drop; + end; + 18: begin + n := Rnd(7); + for i := 1 to n do IntExpr(b); + SysCall(n); + Drop; + if Flag then Fence; + end; + 19: begin + L := NoLabel; + start := DeferBegin(L, saved); + Stmt(b - 1); + DeferEnd(L, saved); + RunDefer(start); + end; + 20: if curRes <> 0 then RetStmt(b) else Assign(b); + else + if curRes <> 0 then begin + TryAlign; + TryReturn(Slot); + end else + Assign(b); + end; + ReleaseTemps(mk); +end; + +procedure GenProc(c: longint); +var + sig: PType; params, p, last: PObj; i, n, kind, mask, j, ns, line: longint; t: PType; + mk: TCodeMark; open: boolean; +begin + sig := NewType(fProc, 8, 8); + curRes := Rnd(9); + sig^.base := results[curRes]; + params := nil; last := nil; + n := Rnd(8); + for i := 0 to n - 1 do begin + kind := Rnd(5); + if kind = 0 then t := tReal + else if kind = 1 then t := sliceT + else if kind = 2 then t := tI32 + else t := tInt; + p := NewObj(oVar, 0, t); + p^.param := true; + p^.isVar := kind = 4; + if last = nil then params := p else last^.next := p; + last := p; + end; + BeginProc(sig, params); + for i := 0 to 5 do slots[i] := AllocPerm(8, 8); + mask := Rnd(32); + j := Rnd(16); + mask := mask or (j shl XBit); + if Rnd(3) = 0 then mask := 0; + numRegs := 0; numX := 0; + for j := 0 to 4 do + if mask and (1 shl j) <> 0 then begin regs[numRegs] := VarRegs[j]; inc(numRegs) end; + for j := 0 to 3 do + if mask and (1 shl (XBit + j)) <> 0 then begin + xregs[numX] := XVarRegs[j]; inc(numX); + XHome(XVarRegs[j], AllocPerm(8, 8)); + end; + j := 0; + p := params; + while p <> nil do begin + if (p^.typ = tInt) and (not p^.isVar) and (j < numRegs) and Flag then begin + p^.reg := regs[j]; inc(j); + end else if (p^.typ = tReal) and (numX > 0) and Flag then begin + p^.reg := xregs[0]; + end else if Flag then + KeepArrived(p); + p := p^.next; + end; + UseRegs(mask); + line := 1 + Rnd(40); + EnterBody(c, line); + MarkCode(mk); + if Flag then begin + Stmt(2); + Rewind(mk); + Redo(mk); + end; + ns := 2 + Rnd(8); + for i := 1 to ns do Stmt(3); + open := Flag and (sig^.base <> nil); + if (sig^.base <> nil) and (not open) then RetStmt(2); + EndProc(c, open); + writeln('proc ', c, ' lost ', Bit(lost), ' regs ', mask, ' saves ', chunks^[c].saveMask, ' at ', chunks^[c].saveAt); +end; + +function ChunkNameOf(i: longint): longint; +var s: string; +begin + s := 'p' + chr(48 + i div 10) + chr(48 + i mod 10); + ChunkNameOf := Intern(@s[1], 3); +end; + +var + i, c, entry: longint; path: string; links: array[0..1] of TLink; dyn: boolean; +begin + seed := 5; + path := 'lib/Rt.raz'; + if Open(path) <> '' then Fatal('no file'); + dyn := ParamCount >= 1; + listing := true; + curFile := Intern(@path[1], length(path)); + for i := 0 to NumProcs - 1 do begin c := NewChunk(secText, -1, ChunkNameOf(i)); chunks^[c].live := true end; + for i := 0 to NumGlobs - 1 do begin + c := NewChunk(secBss, -1, ChunkNameOf(NumProcs + i)); + SetBss(c, 64, 8); + end; + MakeTypes; + for i := 0 to NumProcs - 1 do GenProc(FirstProc + i); + links[0].chunk := FirstProc; links[0].into := FirstGlob; + links[1].chunk := FirstProc + 1; links[1].into := FirstGlob + 1; + entry := EntryPoint(dyn, nil, nil, FirstProc + 2, FirstProc + 3, links, 2); + writeln('entry ', entry, ' pc ', pc, ' fixups ', numFixups, ' lines ', numLines, ' said ', SaidCount); + for i := 0 to pc - 1 do write(HexStr(code^[i], 2)); + writeln; + for i := 0 to numFixups - 1 do writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend); + for i := 0 to numLines - 1 do writeln('L ', lines^[i].at, ' ', lines^[i].chunk, ' ', lines^[i].line, ' ', lines^[i].col); + List(-1); +end. diff --git a/src/test/GenDump.raz b/src/test/GenDump.raz new file mode 100644 index 0000000..0f4af1c --- /dev/null +++ b/src/test/GenDump.raz @@ -0,0 +1,732 @@ +(* Compiles procedures made by a fixed pseudo-random script of calls to + Gen, valid by construction (an expression pushes its operands, then + operates on them; a statement leaves the stack as it found it), then + prints the bytes, the fixups, the line notes and the listing (raz -S) + of what it made: src/Gen.raz's side of a test against the seed's, + GenDump.pas, which makes and prints the same. With the argument dyn, + the entry point is the dynamic one. *) +module GenDump; +import Out, Fmt, Diag, Scan, Sym, Chunk, X := X64, Gen; + +const + FirstProc = 3; (* chunks 0 to 2 are Gen's own *) + NumProcs = 80; + FirstGlob = FirstProc + NumProcs; + NumGlobs = 4; + Arith: [10]Scan.Sym = [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod, + Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr]; + Cmps: [6]Scan.Sym = [Scan.sEql, Scan.sNeq, Scan.sLss, Scan.sLeq, Scan.sGtr, Scan.sGeq]; + RealOps: [4]Scan.Sym = [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sSlash]; + +var + seed: I64; + slots: [6]I64; (* frame slots of the procedure *) + regs: [5]INT; (* the registers of variables it keeps *) + numRegs: INT; + xregs: [4]INT; (* ... of reals, as numbered from XmmVar *) + numX: INT; + tuple2, tuple3, record3, sliceT: ^Sym.Type; + results: [9]^Sym.Type; + curRes: INT; (* the procedure's result: an index of results *) + +proc rnd(n: INT): INT; +begin + seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; + return INT((seed shr 8) mod I64(n)); +end; + +proc pos: Diag.Pos; +var p: Diag.Pos; +begin + p.f := 0; p.a := rnd(400); p.b := p.a + 1; + return p; +end; + +(* a size of 1, 2, 4 or 8 bytes *) +proc size: INT; +begin + return 1 shl rnd(4); +end; + +(* a slot of the procedure's frame *) +proc slot: I64; +begin + return slots[rnd(6)]; +end; + +proc bit(f: BOOL): INT; +begin + if f then return 1; end; + return 0; +end; + +proc flag: BOOL; +begin + return rnd(2) = 0; +end; + +proc constVal: I64; +var x: INT; r: I64; +begin + x := rnd(1 shl 30); + match rnd(7) of + | 0: r := x mod 10; + | 1: r := -(x mod 100); + | 2: r := I64(1) shl (x mod 20); + | 3: r := x; + | 4: r := I64(x) * 4096 * 4096 * 9 - 7; + | 5: r := -I64(x) * 8; + | else: r := x mod 1000 - 500; + end; + return r; +end; + +proc newObjs(t: ^Sym.Type; n: INT): ^Sym.Obj; +var first, o, last: ^Sym.Obj; i: INT; +begin + first := nil; last := nil; + for i := 0 to n - 1 do + o := Sym.newObj(Sym.oVar, 0, t); + o^.val := 8 * i; + if last = nil then first := o; else last^.next := o; end; + last := o; + end; + return first; +end; + +proc makeTypes; +begin + tuple2 := Sym.newType(Sym.fRecord, 16, 8); + tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := newObjs(Sym.tInt, 2); + tuple3 := Sym.newType(Sym.fRecord, 24, 8); + tuple3^.tuple := true; tuple3^.len := 3; tuple3^.fields := newObjs(Sym.tInt, 3); + record3 := Sym.newType(Sym.fRecord, 24, 8); + record3^.fields := newObjs(Sym.tReal, 3); + sliceT := Sym.newType(Sym.fSlice, 16, 8); + sliceT^.base := Sym.tU8; + results[0] := nil; + results[1] := Sym.tInt; + results[2] := Sym.tReal; + results[3] := sliceT; + results[4] := tuple2; + results[5] := tuple3; + results[6] := Sym.tF32; + results[7] := Sym.tI16; + results[8] := record3; +end; + +(* Variables *) + +(* the address of a variable of the procedure that has one: in the frame, + a chunk, or a slot holding its address *) +proc memAdr: Gen.Adr; +var a: Gen.Adr; c: INT; +begin + c := rnd(3); + if c = 0 then + a.base := Gen.bFrame; a.chunk := 0; a.hi := 0; a.off := slot(); if flag() then a.off := a.off + 8; end; + elsif c = 1 then + a.base := Gen.bGlobal; a.chunk := FirstGlob + rnd(NumGlobs); a.hi := 0; a.off := 8 * rnd(3); + else + a.base := Gen.bSlot; a.chunk := INT(slot()); a.hi := 0; a.off := 8 * rnd(3); + end; + return a; +end; + +(* an address that can go on the stack: frame or chunk *) +proc pushableAdr: Gen.Adr; +var a: Gen.Adr; +begin + a.chunk := 0; a.hi := 0; + if flag() then + a.base := Gen.bFrame; a.off := slot(); if flag() then a.off := a.off + 8; end; + else + a.base := Gen.bGlobal; a.chunk := FirstGlob + rnd(NumGlobs); a.off := 8 * rnd(3); + end; + return a; +end; + +proc regAdr(r: INT): Gen.Adr; +var a: Gen.Adr; +begin + a.base := Gen.bReg; a.chunk := r; a.hi := 0; a.off := 0; + return a; +end; + +proc stackAdr: Gen.Adr; +var a: Gen.Adr; +begin + a.base := Gen.bStack; a.chunk := 0; a.hi := 0; a.off := 8 * rnd(3); + return a; +end; + +proc pushIntVar; +var a: Gen.Adr; sz: INT; c: INT; +begin + sz := size(); + c := rnd(5); + if (c = 0) and (numRegs > 0) then + if flag() then Gen.setInPlace(regs[rnd(numRegs)]); end; + Gen.pushVar(regAdr(regs[rnd(numRegs)]), 8, false, Gen.kWord); + elsif c = 1 then + Gen.pushAdr(pushableAdr()); + a := stackAdr(); + Gen.pushVar(a, sz, flag(), Gen.kWord); + else + a := memAdr(); + Gen.pushVar(a, sz, flag(), Gen.kWord); + end; +end; + +proc intExpr(b: INT); forward; +proc realExpr(k: Gen.Kind; b: INT); forward; +proc callExpr(want, b: INT); forward; + +proc realKind: Gen.Kind; +begin + if flag() then return Gen.kF64; end; + return Gen.kF32; +end; + +proc intExpr(b: INT); +var c, sz, n: INT; sg, f: BOOL; k: Gen.Kind; sy: Scan.Sym; a: Gen.Adr; +begin + if b > 0 then c := rnd(14); else c := rnd(3); end; + match c of + | 0: Gen.pushConst(Gen.kWord, constVal()); + | 1: pushIntVar(); + | 2: pushIntVar(); + | 3, 4, 5: + intExpr(b - 1); intExpr(b - 1); + sy := Arith[rnd(10)]; sz := size(); sg := flag(); + Gen.op(sy, Gen.kWord, sz, sg); + | 6: + if flag() then + intExpr(b - 1); intExpr(b - 1); + sy := Cmps[rnd(6)]; sg := flag(); + Gen.compare(sy, Gen.kWord, sg); + else + k := realKind(); + realExpr(k, b - 1); realExpr(k, b - 1); + sy := Cmps[rnd(6)]; + Gen.compare(sy, k, false); + end; + | 7: + intExpr(b - 1); + n := rnd(4); sz := size(); sg := flag(); + if n = 0 then Gen.neg(Gen.kWord, sz, sg); + elsif n = 1 then Gen.complement(sz, sg); + elsif n = 2 then Gen.notBool(); + else Gen.narrow(sz, sg); end; + | 8: + (* an element of an array in the frame or a chunk *) + intExpr(b - 1); + a := pushableAdr(); + sz := size(); sg := flag(); + n := 10 + rnd(100); + Gen.checkIndex(n, pos()); + Gen.indexArray(a, sz); + a := stackAdr(); a.off := 0; + Gen.pushVar(a, sz, sg, Gen.kWord); + | 9: + (* an element of a slice, in a frame slot or on the stack, or in registers *) + n := rnd(3); + sz := size(); sg := flag(); + if n = 0 then + a := memAdr(); + if a.base = Gen.bGlobal then a.base := Gen.bFrame; end; + intExpr(b - 1); + f := flag(); + Gen.indexSlice(a, sz, f, pos()); + elsif n = 1 then + Gen.pushAdr(pushableAdr()); + intExpr(b - 1); + a := stackAdr(); a.off := 0; + f := flag(); + Gen.indexSlice(a, sz, f, pos()); + else + a.base := Gen.bReg; a.chunk := X.R13; a.hi := X.R14; a.off := 0; + intExpr(b - 1); + f := flag(); + Gen.indexSlice(a, sz, f, pos()); + end; + a := stackAdr(); a.off := 0; + Gen.pushVar(a, sz, sg, Gen.kWord); + | 10: + k := realKind(); + realExpr(k, b - 1); + Gen.realToInt(k); + | 11: callExpr(1, b - 1); + | 12: + (* x + 1, and the offset noted on a word *) + intExpr(b - 1); + Gen.pushConst(Gen.kWord, rnd(100) - 50); + Gen.op(Scan.sPlus, Gen.kWord, 8, false); + | else: + intExpr(b - 1); + Gen.pushConst(Gen.kWord, constVal()); + sy := Arith[rnd(10)]; sz := size(); sg := flag(); + Gen.op(sy, Gen.kWord, sz, sg); + end; +end; + +proc realExpr(k: Gen.Kind; b: INT); +var c, n: INT; sy: Scan.Sym; a: Gen.Adr; k2: Gen.Kind; v: I64; +begin + if b > 0 then c := rnd(9); else c := rnd(3); end; + match c of + | 0: + n := rnd(4); + if n = 0 then v := 3FF0000000000000H; + elsif n = 1 then v := 4000000000000000H; + elsif n = 2 then v := 0; + else v := 3FE0000000000000H; end; + Gen.pushConst(k, v); + | 1: + a := memAdr(); + if k = Gen.kF32 then Gen.pushVar(a, 4, false, k); else Gen.pushVar(a, 8, false, k); end; + | 2: + if numX > 0 then + if flag() then Gen.setInPlace(xregs[rnd(numX)]); end; + Gen.pushVar(regAdr(xregs[rnd(numX)]), 8, false, k); + else + Gen.pushAdr(pushableAdr()); + a := stackAdr(); + Gen.pushVar(a, 8, false, k); + end; + | 3, 4: + realExpr(k, b - 1); realExpr(k, b - 1); + sy := RealOps[rnd(4)]; + Gen.op(sy, k, 8, false); + | 5: + intExpr(b - 1); + Gen.intToReal(k, flag()); + | 6: + realExpr(k, b - 1); + Gen.neg(k, 8, false); + | 7: + if k = Gen.kF32 then k2 := Gen.kF64; else k2 := Gen.kF32; end; + realExpr(k2, b - 1); + Gen.realToReal(k2); + | else: callExpr(2, b - 1); + end; +end; + +(* A call of one of the procedures, with arguments of all kinds. want: 0 + for a statement, any result; 1 an integer is left on the stack, 2 a + real. *) +proc callExpr(want, b: INT); +var + c: Gen.CallInfo; sig: ^Sym.Type; i, n, kind, r, ni: INT; k: Gen.Kind; +begin + sig := Sym.newType(Sym.fProc, 8, 8); + sig^.variadic := rnd(5) = 0; + if want = 1 then + r := rnd(5); + if r = 0 then sig^.base := Sym.tBool; + elsif r = 1 then sig^.base := Sym.tI8; + elsif r = 2 then sig^.base := Sym.tU32; + elsif r = 3 then sig^.base := tuple2; + else sig^.base := Sym.tInt; end; + elsif want = 2 then + if flag() then sig^.base := Sym.tReal; else sig^.base := Sym.tF32; end; + else + sig^.base := results[rnd(9)]; + end; + c.sig := sig; c.param := nil; c.obj := nil; c.ext := rnd(4) = 0; + c.n := 0; c.target := 0; + c.chunk := FirstProc + rnd(NumProcs); + if rnd(5) = 0 then c.chunk := -1; c.ext := false; c.target := slot(); end; + n := rnd(8); + for i := 0 to n - 1 do + kind := rnd(4); + if kind = 0 then + k := realKind(); + realExpr(k, b); + c.isF[c.n] := true; c.pair[c.n] := false; + INC(c.n); + elsif kind = 1 then + intExpr(b); intExpr(b); + c.isF[c.n] := false; c.pair[c.n] := true; + c.isF[c.n + 1] := false; c.pair[c.n + 1] := false; + INC(c.n, 2); + else + intExpr(b); + c.isF[c.n] := false; c.pair[c.n] := false; + INC(c.n); + end; + end; + Gen.call(c); + (* what comes back: a value or two, or nothing, or a temporary *) + ni := 0; + if sig^.base # nil then + if sig^.base^.form = Sym.fSlice then ni := 0; + elsif sig^.base = tuple2 then ni := 2; + elsif Sym.behindPointer(sig^.base) then ni := 0; + else ni := 1; end; + end; + if want = 0 then + for i := 1 to ni do Gen.drop(); end; + elsif ni = 2 then + Gen.drop(); (* the second; the first is the value *) + end; +end; + +(* A condition, left as a BOOL on the stack *) +proc boolExpr(b: INT); +var sy: Scan.Sym; sg: BOOL; +begin + if flag() then + intExpr(b); intExpr(b); + sy := Cmps[rnd(6)]; sg := flag(); + Gen.compare(sy, Gen.kWord, sg); + else + intExpr(b); + end; +end; + +proc stmt(b: INT); forward; + +(* a variable assigned the value on top: its address, if on the stack, + having been pushed first *) +proc assign(b: INT); +var a: Gen.Adr; c, sz: INT; k: Gen.Kind; +begin + c := rnd(6); + sz := size(); + if c = 0 then + a := memAdr(); + intExpr(b); + Gen.popVar(a, sz); + elsif c = 1 then + Gen.pushAdr(pushableAdr()); + a := stackAdr(); + intExpr(b); + Gen.popVar(a, sz); + elsif (c = 2) and (numRegs > 0) then + a := regAdr(regs[rnd(numRegs)]); + Gen.setInPlace(a.chunk); + Gen.pushVar(a, 8, false, Gen.kWord); + intExpr(b); + Gen.op(Arith[rnd(3)], Gen.kWord, 8, false); + Gen.popVar(a, 8); + elsif (c = 3) and (numX > 0) then + k := realKind(); + a := regAdr(xregs[rnd(numX)]); + realExpr(k, b); + Gen.popVar(a, 8); + elsif c = 4 then + k := realKind(); + a := memAdr(); + realExpr(k, b); + if k = Gen.kF32 then Gen.popVar(a, 4); else Gen.popVar(a, 8); end; + else + a := memAdr(); + Gen.pushConst(Gen.kWord, constVal()); + Gen.popVar(a, sz); + end; +end; + +proc retStmt(b: INT); +var i: INT; +begin + if curRes = 1 then intExpr(b); + elsif curRes = 7 then intExpr(b); + elsif curRes = 2 then realExpr(Gen.kF64, b); + elsif curRes = 6 then realExpr(Gen.kF32, b); + elsif (curRes = 3) or (curRes = 4) then intExpr(b); intExpr(b); + elsif curRes = 5 then + for i := 0 to 2 do intExpr(b); Gen.resultTo(8 * i, 8); end; + elsif curRes = 8 then + Gen.pushAdr(pushableAdr()); + Gen.copyResult(0, 24); + end; + Gen.returnJump(); +end; + +proc stmt(b: INT); +var + c, n, lo, i, start, saved, sz, tmp: INT; L, E, S, fj, tj: INT; a, a2: Gen.Adr; sy: Scan.Sym; sg: BOOL; + mk: I64; f: BOOL; +begin + mk := Gen.tempMark(); + if b <= 0 then c := rnd(4); else c := rnd(22); end; + match c of + | 0, 1, 2, 3: assign(b); + | 4: + (* if cond then s end *) + L := Gen.NoLabel; + boolExpr(b); + Gen.jumpIf(L, false); + stmt(b - 1); + Gen.fix(L); + | 5: + (* while cond do s end *) + L := Gen.NoLabel; + Gen.alignLoop(); + start := Chunk.pc; + boolExpr(b); + Gen.jumpIf(L, false); + stmt(b - 1); + Gen.jumpBack(start); + Gen.fix(L); + | 6: + (* if a < b then s end, with a jump on the comparison *) + L := Gen.NoLabel; + intExpr(b); intExpr(b); + sy := Cmps[rnd(6)]; sg := flag(); + if flag() then Gen.jumpCmp(sy, sg, L); else Gen.jumpOut(sy, sg, L); end; + stmt(b - 1); + Gen.fix(L); + | 7: + (* v := a < b and c, a condition worked out into a BOOL *) + fj := Gen.NoLabel; tj := Gen.NoLabel; + intExpr(b); intExpr(b); + sy := Cmps[rnd(6)]; sg := flag(); + Gen.condValue(sy, sg, fj, tj); + a := memAdr(); + Gen.popVar(a, 1); + | 8: callExpr(0, b); + | 9: + (* a match through a jump table *) + a := memAdr(); + if a.base = Gen.bSlot then a.base := Gen.bFrame; a.off := slots[0]; end; + intExpr(b); + Gen.popVar(a, 8); + E := Gen.NoLabel; + n := 2 + rnd(4); lo := rnd(5) - 2; + if flag() then S := Gen.NoLabel; else S := Chunk.pc; end; + start := Gen.jumpTable(a.off, lo, n, S, E); + for i := 0 to n - 1 do Gen.tableEntry(start, Chunk.pc + 4 * (n - i)); end; + for i := 0 to n - 1 do + stmt(b - 1); + end; + Gen.fix(E); + | 10: + Gen.pushAdr(pushableAdr()); Gen.pushAdr(pushableAdr()); + n := 1 + rnd(150); lo := 8 * rnd(3); + Gen.copyBlock(n, lo); + | 11: + Gen.pushAdr(pushableAdr()); + a := memAdr(); + if flag() and (numRegs > 1) then + a.base := Gen.bReg; a.chunk := regs[0]; a.hi := regs[1]; a.off := 0; + end; + n := 1 + rnd(150); + Gen.copyTo(a, n); + | 12: + a := memAdr(); + n := 1 + rnd(100); + Gen.zeroVar(a, n); + | 13: + (* a slice of an array, of a slice, of a pointer *) + tmp := INT(Gen.allocTemp(16, 8)); + n := rnd(3); + sz := size(); sg := flag(); + if n = 0 then + a := pushableAdr(); + Gen.pushAdr(a); intExpr(b); intExpr(b); + a := stackAdr(); a.off := 0; + f := flag(); n := 10 + rnd(50); + Gen.slice(a, f, n, sz, tmp, sg, pos()); + elsif n = 1 then + a := memAdr(); + if a.base = Gen.bGlobal then a.base := Gen.bFrame; end; + intExpr(b); intExpr(b); + Gen.slice(a, false, 0, sz, tmp, sg, pos()); + else + intExpr(b); intExpr(b); intExpr(b); + Gen.slicePtr(sz, tmp, sg, pos()); + end; + | 14: + a.off := slot(); a2.off := slot(); sz := size(); f := flag(); + Gen.copySlice(a.off, a2.off, sz, f, pos()); + | 15: + n := rnd(4); sz := size(); sg := flag(); + if n = 0 then + Gen.pushAdr(pushableAdr()); intExpr(b); + f := flag(); + Gen.incDec(sz, sg, f); + elsif (n = 1) and (numRegs > 0) then + intExpr(b); + Gen.incDecReg(regs[0], sz, sg, flag()); + elsif n = 2 then + intExpr(b); + n := 3 + rnd(6); lo := FirstGlob + rnd(NumGlobs); + Gen.checkEnum(n, lo, pos()); + Gen.drop(); + else + intExpr(b); + n := rnd(8000); + Gen.checkNil(n, pos()); + Gen.drop(); + end; + | 16: + n := rnd(3); + if n = 0 then + a.off := slot(); a2.off := slot(); n := rnd(4); f := flag(); + Gen.compareSeq(a.off, a2.off, n, f); + Gen.drop(); + elsif n = 1 then + intExpr(b); + Gen.errorText(Gen.allocTemp(16, 8)); + else + intExpr(b); + n := 1 + rnd(200); + Gen.zeroNew(n); + Gen.drop(); + end; + | 17: + n := rnd(3); + if n = 0 then + intExpr(b); intExpr(b); intExpr(b); + Gen.atomic(Sym.bCas); + elsif n = 1 then + intExpr(b); intExpr(b); + Gen.atomic(Sym.bXchg); + else + intExpr(b); intExpr(b); + Gen.atomic(Sym.bXadd); + end; + Gen.drop(); + | 18: + n := rnd(7); + for i := 1 to n do intExpr(b); end; + Gen.sysCall(n); + Gen.drop(); + if flag() then Gen.fence(); end; + | 19: + (* defer s *) + L := Gen.NoLabel; + start, saved := Gen.deferBegin(L); + stmt(b - 1); + Gen.deferEnd(L, saved); + Gen.runDefer(start); + | 20: + if curRes # 0 then retStmt(b); else assign(b); end; + | else: + if curRes # 0 then + Gen.tryAlign(); + Gen.tryReturn(slot()); + else + assign(b); + end; + end; + Gen.releaseTemps(mk); +end; + +(* Each statement may be preceded by a few that are made and taken back, + as the parser does when it compiles a body a second time *) +proc genProc(c: INT); +var + sig: ^Sym.Type; params, p, last: ^Sym.Obj; i, n, kind, mask, j, ns, line: INT; t: ^Sym.Type; + mk: Gen.CodeMark; open: BOOL; +begin + sig := Sym.newType(Sym.fProc, 8, 8); + curRes := rnd(9); + sig^.base := results[curRes]; + params := nil; last := nil; + n := rnd(8); + for i := 0 to n - 1 do + kind := rnd(5); + if kind = 0 then t := Sym.tReal; + elsif kind = 1 then t := sliceT; + elsif kind = 2 then t := Sym.tI32; + else t := Sym.tInt; end; + p := Sym.newObj(Sym.oVar, 0, t); + p^.param := true; + p^.isVar := kind = 4; + if last = nil then params := p; else last^.next := p; end; + last := p; + end; + Gen.beginProc(sig, params); + for i := 0 to 5 do slots[i] := Gen.allocPerm(8, 8); end; + mask := rnd(32); + j := rnd(16); + mask := mask | (j shl Gen.XBit); + if rnd(3) = 0 then mask := 0; end; + numRegs := 0; numX := 0; + for j := 0 to 4 do + if (mask & (1 shl j)) # 0 then regs[numRegs] := Gen.VarRegs[j]; INC(numRegs); end; + end; + for j := 0 to 3 do + if (mask & (1 shl (Gen.XBit + j))) # 0 then + xregs[numX] := Gen.XVarRegs[j]; INC(numX); + Gen.xHome(Gen.XVarRegs[j], Gen.allocPerm(8, 8)); + end; + end; + (* some parameters live in registers: a register variable's, or kept + where they arrived *) + j := 0; + p := params; + while p # nil do + if (p^.typ = Sym.tInt) and (not p^.isVar) and (j < numRegs) and flag() then + p^.reg := regs[j]; INC(j); + elsif (p^.typ = Sym.tReal) and (numX > 0) and flag() then + p^.reg := xregs[0]; + elsif flag() then + Gen.keepArrived(p); + end; + p := p^.next; + end; + Gen.useRegs(mask); + line := 1 + rnd(40); + Gen.enterBody(c, line); + Gen.markCode(mk); + (* a body made and taken back *) + if flag() then + stmt(2); + Gen.rewind(mk); + Gen.redo(mk); (* the jumps to the exit went with the code *) + end; + ns := 2 + rnd(8); + for i := 1 to ns do stmt(3); end; + open := flag() and (sig^.base # nil); + if (sig^.base # nil) and (not open) then retStmt(2); end; + _ := Gen.endProc(c, open); + Fmt.print("proc {} lost {} regs {} saves {} at {}\n", [Fmt.int(c), Fmt.int(bit(Gen.lost)), Fmt.int(mask), + Fmt.int(Chunk.chunks[c].saveMask), Fmt.int(Chunk.chunks[c].saveAt)]); +end; + +(* The name p0, p1, ... of chunk i, interned *) +proc chunkNameOf(i: INT): INT; +var s: [3]U8; +begin + s[0] := 'p'; s[1] := U8(48 + i div 10); s[2] := U8(48 + i mod 10); + return Scan.intern(ADR(s[0]), 3); +end; + +proc main*; +var i, c: INT; path: []U8; links: [2]Gen.Link; entry: INT; dyn: BOOL; +begin + seed := 5; + path := "lib/Rt.raz"; + if LEN(Scan.open(path)) # 0 then Diag.fatal("no file"); end; + dyn := ARGC > 1; + X.setListing(true); + Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path))); + for i := 0 to NumProcs - 1 do c := Chunk.newChunk(Chunk.secText, -1, chunkNameOf(i)); Chunk.setLive(c); end; + for i := 0 to NumGlobs - 1 do + c := Chunk.newChunk(Chunk.secBss, -1, chunkNameOf(NumProcs + i)); + Chunk.setBss(c, 64, 8); + end; + makeTypes(); + for i := 0 to NumProcs - 1 do genProc(FirstProc + i); end; + links[0].chunk := FirstProc; links[0].into := FirstGlob; + links[1].chunk := FirstProc + 1; links[1].into := FirstGlob + 1; + entry := Gen.entryPoint(dyn, nil, nil, FirstProc + 2, FirstProc + 3, links, 2); + Fmt.print("entry {} pc {} fixups {} lines {} said {}\n", [Fmt.int(entry), Fmt.int(Chunk.pc), + Fmt.int(Chunk.numFixups), Fmt.int(Chunk.numLines), Fmt.int(X.saidCount())]); + for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end; + Out.ln; + for i := 0 to Chunk.numFixups - 1 do + Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]); + end; + for i := 0 to Chunk.numLines - 1 do + Fmt.print("L {} {} {} {}\n", [Fmt.int(Chunk.lines[i].at), Fmt.int(Chunk.lines[i].chunk), + Fmt.int(Chunk.lines[i].line), Fmt.int(Chunk.lines[i].col)]); + end; + X.list(-1); +end; + +end GenDump. diff --git a/src/test/ItemDump.pas b/src/test/ItemDump.pas new file mode 100644 index 0000000..ecc10c3 --- /dev/null +++ b/src/test/ItemDump.pas @@ -0,0 +1,665 @@ +{ Drives item with a fixed pseudo-random script of operands and + operations, with mistakes among them, and prints what each step gave + (the item, or that it failed, whose message goes to standard error), + then the bytes, fixups, line notes and listing (raz -S) of the code + it made: the seed's side of a test of src/Item.raz, whose + ItemDump.raz does and prints the same. The argument, a number, + changes the script. A run ends at the 20th error, as a compile does, + so several scripts are run. } +program itemdump; +{$mode objfpc}{$H-} +uses diag, scan, sym, chunk, x64, gen, item; + +const + FirstProc = 3; + NumProcs = 30; + FirstGlob = FirstProc + NumProcs; + NumGlobs = 4; + Steps = 14; + YInt = 0; YI64 = 1; YI32 = 2; YU8 = 3; YU16 = 4; YU32 = 5; YU64 = 6; YBool = 7; + YReal = 8; YF32 = 9; YI8 = 10; YEnum = 11; YSet = 12; YPtr = 13; YVptr = 14; + YPtrArr = 15; YArr = 16; YArrU8 = 17; YSlice = 18; YBytes = 19; YRec = 20; + YPacked = 21; YVariant = 22; YProc0 = 23; YProc1 = 24; YProc2 = 25; + YPtrRec = 26; YErr = 27; YVrec = 28; YVarr = 29; + NumT = 30; + IntTypes: array[0..7] of longint = (YInt, YI64, YI32, YU8, YU16, YU32, YU64, YI8); + Ops: array[0..19] of TSym = (sPlus, sMinus, sTimes, sDiv, sMod, + sAmp, sBar, sXor, sShl, sShr, + sEql, sNeq, sLss, sLeq, sGtr, sGeq, + sSlash, sIn, sPlus, sMinus); + Cmps: array[0..5] of TSym = (sEql, sNeq, sLss, sLeq, sGtr, sGeq); + +var + Letters: string[9]; + seed: int64; + ty: array[0..NumT - 1] of PType; + vars: array[0..NumT - 1] of PObj; + procs: array[0..5] of PObj; + strs: array[0..2] of PObj; + arrConst, typeObj, builtinObj, caseObj: PObj; + mod0, mod1: PModule; + tuple2, record3, packedR, variantT: PType; + results: array[0..8] of PType; + curRes: longint; + call: TCall; + jb: jmp_buf; + gK: longint; + gX: TItem; + gOk: boolean; + +function Rnd(n: longint): longint; +begin + seed := (seed * 1103515245 + 12345) and $7FFFFFFF; + Rnd := (seed shr 8) mod n; +end; + +function Flag: boolean; +begin + Flag := Rnd(2) = 0; +end; + +function Bit(f: boolean): longint; +begin + if f then Bit := 1 else Bit := 0; +end; + +function Pos: TPos; +var p: TPos; +begin + p.f := 0; p.a := Rnd(400); p.b := p.a + 1 + Rnd(12); + Pos := p; +end; + +function ConstVal: int64; +var x: longint; r: int64; +begin + x := Rnd(1 shl 30); + case Rnd(7) of + 0: r := x mod 10; + 1: r := -(x mod 100); + 2: r := int64(1) shl (x mod 20); + 3: r := x; + 4: r := int64(x) * 4096 * 4096 * 9 - 7; + 5: r := -int64(x) * 8; + else r := x mod 1000 - 500; + end; + ConstVal := r; +end; + +function InternStr(const s: shortstring): longint; +begin + InternStr := Intern(@s[1], length(s)); +end; + +{ A name v00, v01, ... , interned } +function NameOf(i: longint): longint; +var s: string[3]; +begin + s := 'v' + chr(48 + i div 10) + chr(48 + i mod 10); + NameOf := Intern(@s[1], 3); +end; + +function NewObjs(cls: TClass; t: PType; n: longint; step: int64; at: longint): PObj; +var first, o, last: PObj; i: longint; +begin + first := nil; last := nil; + for i := 0 to n - 1 do begin + o := NewObj(cls, NameOf(at + i), t); + o^.val := step * i; + if last = nil then first := o else last^.next := o; + last := o; + end; + NewObjs := first; +end; + +function ProcType(res: PType; params: PObj; n: longint): PType; +var t: PType; +begin + t := NewType(fProc, 8, 8); + t^.base := res; + t^.fields := params; + t^.len := n; + ProcType := t; +end; + +function Param(t: PType; isVar: boolean; at: longint): PObj; +var o: PObj; +begin + o := NewObj(oVar, NameOf(at), t); + o^.param := true; + o^.isVar := isVar; + Param := o; +end; + +procedure MakeTypes; +var t: PType; p, q, r: PObj; i: longint; +begin + ty[YInt] := tInt; ty[YI64] := tI64; ty[YI32] := tI32; ty[YU8] := tU8; + ty[YU16] := tU16; ty[YU32] := tU32; ty[YU64] := tU64; ty[YBool] := tBool; + ty[YReal] := tReal; ty[YF32] := tF32; ty[YI8] := tI8; ty[YErr] := tError; + ty[YBytes] := tBytes; + t := NewType(fEnum, 1, 1); t^.len := 5; ty[YEnum] := t; + t := NewType(fSet, 8, 8); t^.len := 5; t^.base := ty[YEnum]; ty[YSet] := t; + t := NewType(fPtr, 8, 8); t^.base := tI64; ty[YPtr] := t; + t := NewType(fPtr, 8, 8); t^.base := tI64; t^.vol := true; ty[YVptr] := t; + t := NewType(fArray, 48, 8); t^.base := tI64; t^.len := 6; ty[YArr] := t; + t := NewType(fPtr, 8, 8); t^.base := ty[YArr]; ty[YPtrArr] := t; + t := NewType(fPtr, 8, 8); t^.base := ty[YArr]; t^.vol := true; ty[YVarr] := t; + t := NewType(fArray, 8, 1); t^.base := tU8; t^.len := 8; ty[YArrU8] := t; + t := NewType(fSlice, 16, 8); t^.base := tI64; ty[YSlice] := t; + record3 := NewType(fRecord, 24, 8); + p := NewObj(oField, NameOf(40), tI64); p^.val := 0; + q := NewObj(oField, NameOf(41), tReal); q^.val := 8; p^.next := q; + r := NewObj(oField, NameOf(42), tI32); r^.val := 16; q^.next := r; + record3^.fields := p; + ty[YRec] := record3; + t := NewType(fPtr, 8, 8); t^.base := record3; ty[YPtrRec] := t; + t := NewType(fPtr, 8, 8); t^.base := record3; t^.vol := true; ty[YVrec] := t; + packedR := NewType(fRecord, 53, 1); + packedR^.packd := true; + p := NewObj(oField, NameOf(43), tU8); p^.val := 0; + q := NewObj(oField, NameOf(44), tI32); q^.val := 1; p^.next := q; + r := NewObj(oField, NameOf(46), ty[YArr]); r^.val := 5; q^.next := r; + packedR^.fields := p; + ty[YPacked] := packedR; + variantT := NewType(fVariant, 16, 8); + ty[YVariant] := variantT; + tuple2 := NewType(fRecord, 16, 8); + tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := NewObjs(oVar, tInt, 2, 8, 45); + p := Param(tInt, false, 46); p^.next := Param(tReal, false, 47); + ty[YProc0] := ProcType(tInt, p, 2); + ty[YProc1] := ProcType(nil, nil, 0); + p := Param(tI64, true, 48); p^.next := Param(ty[YSlice], false, 49); + ty[YProc2] := ProcType(tuple2, p, 2); + results[0] := nil; results[1] := tInt; results[2] := tReal; results[3] := ty[YSlice]; + results[4] := tuple2; results[5] := record3; results[6] := tF32; results[7] := tI16; + results[8] := ty[YBytes]; + for i := 0 to NumT - 1 do + if ty[i] = nil then Fatal('a type is missing'); +end; + +procedure MakeObjs; +var i, c: longint; o: PObj; +begin + New(mod0); mod0^.name := InternStr('Zero'); + New(mod1); mod1^.name := InternStr('Other'); + curModule := mod0; + for i := 0 to 5 do begin + o := NewObj(oProc, NameOf(50 + i), ty[YProc0 + i mod 3]); + o^.chunk := FirstProc + Rnd(NumProcs); + o^.ext := i >= 4; + o^.isCode := i = 3; + procs[i] := o; + end; + for i := 0 to 2 do begin + o := NewObj(oConst, NameOf(60 + i), tStr); + o^.val := 2 + 3 * i; + c := NewChunk(secRodata, -1, -1); + SetData(c, @Letters[1], o^.val + 1, 1); + o^.chunk := c; + strs[i] := o; + end; + arrConst := NewObj(oConst, NameOf(63), ty[YArr]); + arrConst^.chunk := NewChunk(secRodata, -1, -1); + SetData(arrConst^.chunk, @Letters[1], 8, 8); + typeObj := NewObj(oType, NameOf(64), ty[YRec]); + builtinObj := NewObj(oBuiltin, NameOf(65), tNone); + caseObj := NewObj(oCase, NameOf(66), variantT); + caseObj^.val := 3; + caseObj^.fields := NewObjs(oField, tInt, 2, 8, 67); + caseObj^.fields^.val := 8; +end; + +procedure MakeVars; +var i, k: longint; o: PObj; t: PType; +begin + for i := 0 to NumT - 1 do begin + t := ty[i]; + o := NewObj(oVar, NameOf(i), t); + o^.lev := 1; + k := Rnd(9); + if k = 2 then begin + o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs); + end else if k = 3 then begin + o^.ind := true; o^.val := AllocPerm(8, 8); o^.off := 8 * Rnd(3); + end else if k = 4 then begin + if (t^.form in [fInt, fPtr]) and (t^.size = 8) then + o^.reg := VarRegs[Rnd(5)] + else if t^.form = fReal then + o^.reg := XVarRegs[Rnd(4)] + else if t^.form = fSlice then begin + o^.reg := VarRegs[Rnd(3)]; o^.reg2 := VarRegs[3 + Rnd(2)]; + end; + if o^.reg = 0 then o^.val := AllocPerm(t^.size, 8); + end else if k = 5 then begin + o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs); o^.module := mod1; + end else if k = 6 then begin + o^.lev := 0; o^.chunk := FirstGlob + Rnd(NumGlobs); o^.ext := true; + end else + o^.val := AllocPerm(t^.size + 8, 8); + vars[i] := o; + end; +end; + +{ Operands } + +function IntType: PType; +begin + IntType := ty[IntTypes[Rnd(8)]]; +end; + +procedure VarItem(var x: TItem; t: PType); +var i, k: longint; +begin + k := Rnd(NumT); + for i := 0 to NumT - 1 do + if ty[i] = t then k := i; + FillChar(x, SizeOf(x), 0); + x.pos := Pos; + MakeItem(x, vars[k]); +end; + +procedure Operand(var x: TItem; t: PType); +var k: longint; r: double; v: int64; +begin + FillChar(x, SizeOf(x), 0); + x.pos := Pos; + if t = nil then begin + case Rnd(14) of + 0: MakeConst(x, tConst, ConstVal); + 1: MakeConst(x, tConst, ConstVal mod 200); + 2: begin t := IntType; v := ConstVal mod 100; MakeConst(x, t, v) end; + 3: begin r := (ConstVal mod 1000) / 8.0; MakeReal(x, r) end; + 4: MakeConst(x, tBool, Rnd(2)); + 5: MakeItem(x, strs[Rnd(3)]); + 6: MakeConst(x, tNil, 0); + 7: MakeItem(x, procs[Rnd(6)]); + 8: begin + if Rnd(4) = 0 then begin + case Rnd(3) of + 0: MakeItem(x, typeObj); + 1: MakeItem(x, builtinObj); + else MakeItem(x, caseObj); + end; + end else + MakeItem(x, arrConst); + end; + 13: begin MakeItem(x, vars[Rnd(NumT)]); Value(x) end; + else VarItem(x, ty[Rnd(NumT)]); + end; + exit; + end; + k := Rnd(10); + if IsInt(t) then begin + if k < 3 then begin MakeConst(x, tConst, ConstVal mod 100); exit end; + if k = 3 then begin MakeConst(x, t, ConstVal mod 100); exit end; + end else if t^.form = fReal then begin + if k < 3 then begin r := (ConstVal mod 1000) / 8.0; MakeReal(x, r); exit end; + end else if t^.form = fBool then begin + if k < 3 then begin MakeConst(x, tBool, Rnd(2)); exit end; + end else if t^.form = fPtr then begin + if k < 2 then begin MakeConst(x, tNil, 0); exit end; + end else if (t^.form = fSlice) and (t^.base = tU8) then begin + if k < 3 then begin MakeItem(x, strs[Rnd(3)]); exit end; + end; + VarItem(x, t); +end; + +procedure CondItem(var x: TItem); +var y: TItem; L: longint; op: TSym; t: PType; +begin + t := IntType; + op := Cmps[Rnd(6)]; + Operand(x, t); + Op1(op, x, L); + Operand(y, t); + Op2(op, x, y, L); +end; + +procedure Place(var x: TItem); +var i, k: longint; f: PObj; y, lo, hi: TItem; +begin + VarItem(x, ty[Rnd(NumT)]); + for i := 1 to 3 do begin + if Rnd(3) <> 0 then begin + k := Rnd(6); + if (k = 0) or (x.typ^.form = fPtr) then + Deref(x) + else if x.typ^.form = fRecord then begin + f := x.typ^.fields; + k := Rnd(3); + while (k > 0) and (f^.next <> nil) do begin f := f^.next; dec(k) end; + Field(x, f); + end else if x.typ^.form in [fArray, fSlice, fStr] then begin + IndexPrep(x); + if k < 4 then begin + Operand(y, IntType); + Index(x, y); + end else begin + Operand(lo, IntType); + SliceLo(lo); + Operand(hi, IntType); + Slice(x, lo, hi); + end; + end; + end; + end; +end; + +procedure Dump(var x: TItem); +var name: shortstring; flags: longint; +begin + name := '-'; + if x.typ <> nil then name := TypeName(x.typ); + flags := Bit(x.vol) + 2 * Bit(x.isVar) + 4 * Bit(x.odd) + 8 * Bit(x.ro) + 16 * Bit(x.deref); + write('I ', ord(x.mode), ' ', name, ' ', ord(x.rel), ' ', Bit(x.relSigned), ' ', x.fj, ' ', x.tj, ' ', x.val); + writeln(' ', ord(x.base), ' ', x.chunk, ' ', x.off, ' ', flags, ' depth ', depth, ' pushed ', pushed); +end; + +procedure DoCall(var x: TItem); +var f, a: TItem; p: PObj; n: longint; +begin + FillChar(f, SizeOf(f), 0); + f.pos := Pos; + if Rnd(5) = 0 then MakeItem(f, vars[YProc0 + Rnd(3)]) + else MakeItem(f, procs[Rnd(6)]); + BeginCall(call, f); + p := call.param; + n := Rnd(4) - 1; + while (p <> nil) or (n > 0) do begin + if p <> nil then begin + if p^.isVar and (Rnd(2) = 0) then begin + VarItem(a, ty[YVptr]); + Deref(a); + end else if Rnd(6) = 0 then Operand(a, nil) + else Operand(a, p^.typ); + p := p^.next; + end else begin + Operand(a, nil); + n := n - 1; + end; + PassArg(call, a); + if (p = nil) and (n < 0) then n := 0; + if (p <> nil) and (n < 0) and (Rnd(4) = 0) then begin p := nil; n := 0 end; + end; + EndCall(call, x); +end; + +procedure Binary(var x: TItem); +var y: TItem; L, M: longint; op: TSym; t: PType; +begin + L := NoLabel; + M := NoLabel; + op := Ops[Rnd(20)]; + case Rnd(8) of + 0, 1: t := IntType; + 2: t := ty[YReal + Rnd(2)]; + 3: t := ty[YBool]; + 4: t := ty[YEnum + Rnd(2)]; + else t := ty[Rnd(NumT)]; + end; + if Rnd(6) = 0 then begin + if Flag then op := sAnd else op := sOr; + CondItem(x); + Op1(op, x, L); + CondItem(y); + end else if op = sIn then begin + Operand(x, ty[YEnum]); + Op1(op, x, L); + Operand(y, ty[YSet]); + end else begin + Operand(x, t); + Op1(op, x, L); + if Rnd(5) = 0 then Operand(y, nil) else Operand(y, t); + end; + Op2(op, x, y, L); + if (x.mode = mCond) and (Rnd(3) <> 0) then begin + if Flag then CondJump(x, M) else CondJumpTrue(x, M); + Fix(M); + x.mode := mNone; + end; +end; + +procedure Unary(var x: TItem); +begin + Operand(x, nil); + case Rnd(3) of + 0: Neg(x); + 1: NotOp(x); + else Complement(x); + end; +end; + +procedure DoMatch(var x: TItem); +var p, lo, hi: int64; L: longint; +begin + L := NoLabel; + case Rnd(3) of + 0: VarItem(x, ty[YVariant]); + 1: VarItem(x, ty[YEnum]); + else Operand(x, nil); + end; + p := MatchBegin(x); + MatchTag(p, ConstVal mod 10, L); + lo := ConstVal mod 10; + hi := ConstVal mod 10 + 10; + MatchRange(p, lo, hi, L); + MatchRange(p, 3, 3, L); + Fix(L); +end; + +procedure DoFor(var x: TItem); +var o: PObj; lim: TItem; step: int64; exitL: longint; +begin + o := vars[IntTypes[Rnd(8)]]; + step := ConstVal mod 5; + if step = 0 then step := 1; + if Rnd(2) = 0 then step := -step; + FillChar(lim, SizeOf(lim), 0); + lim.pos := Pos; + MakeConst(lim, o^.typ, ConstVal mod 50); + exitL := NoLabel; + ForStep(o, step); + ForNext(o, lim, step, exitL, pc, pc); + Fix(exitL); + x := lim; +end; + +procedure DoMisc(var x: TItem); +var y: TItem; +begin + case Rnd(5) of + 0: begin + Place(x); + Address(x); + Operand(y, x.typ); + IncDec(x, y, Flag); + end; + 1: begin + Place(x); + Pin(x); + end; + 2: begin + Place(x); + CopyDest(x); + Place(y); + CopyFrom(x, y); + end; + 3: begin + Operand(x, nil); + MakeStr(y); + Coerce(y, ty[YBytes]); + end; + else begin + Operand(x, nil); + NilTest(x); + UsesReals(x.pos); + Discard(x); + end; + end; +end; + +procedure DoTemp(var x: TItem); +var a: TItem; c, h, n: longint; f: PObj; +begin + FillChar(x, SizeOf(x), 0); + x.pos := Pos; + case Rnd(5) of + 0: ZeroTemp(x, ty[YVariant]); + 1: begin + Construct(x, caseObj); + f := caseObj^.fields; + Operand(a, f^.typ); + SetField(x, f, a); + end; + 2: begin + ZeroTemp(x, ty[YRec]); + f := ty[YRec]^.fields; + if Flag then f := f^.next; + Operand(a, f^.typ); + SetField(x, f, a); + end; + 3: begin + Operand(a, nil); + h := Rnd(3) - 1; + n := Rnd(3) - 1; + c := ErrorChunk(a, h, n); + MakeConst(x, tError, int64(c) + 1); + end; + else begin + Operand(x, ty[YErr]); + Msg(x); + end; + end; +end; + +procedure DoReturn(var x: TItem); +var f: PObj; +begin + if (curRes = 4) and Flag then begin + f := tuple2^.fields; + if Flag then f := f^.next; + if Flag then begin + Operand(x, f^.typ); + ReturnField(f, x); + exit; + end; + DoCall(x); + ReturnAll(x); + exit; + end; + if Rnd(4) = 0 then begin ReturnNone; exit end; + Operand(x, results[curRes]); + ReturnValue(x); +end; + +procedure Step(k: longint; var x: TItem); +var y: TItem; +begin + FillChar(x, SizeOf(x), 0); + case k of + 0: begin Operand(x, nil); Value(x) end; + 1: begin Operand(x, nil); Address(x) end; + 2: begin Operand(x, nil); Coerce(x, ty[Rnd(NumT)]) end; + 3: begin Operand(x, nil); CoerceExact(x, IntType, '') end; + 4: begin + Place(x); + Operand(y, x.typ); + Assign(x, y); + end; + 5: Unary(x); + 6: Binary(x); + 7: begin Operand(x, nil); Convert(x, ty[Rnd(NumT)]) end; + 8: Place(x); + 9: DoCall(x); + 10: DoMatch(x); + 11: DoFor(x); + 12: DoMisc(x); + 13: DoTemp(x); + 14: DoReturn(x); + else Binary(x); + end; +end; + +{ A step, and what it leaves, each a recovery point as the parser's + statements are } +procedure RunStep; +begin + gOk := false; + recovery := @jb; + if setjmp(jb) = 0 then begin + Step(gK, gX); + gOk := true; + end; + recovery := nil; +end; + +procedure RunDiscard; +begin + recovery := @jb; + if setjmp(jb) = 0 then Discard(gX); + recovery := nil; +end; + +procedure GenProc(c: longint); +var sig: PType; i, line: longint; +begin + curRes := Rnd(9); + sig := ProcType(results[curRes], nil, 0); + BeginProc(sig, nil); + for i := 0 to 5 do AllocPerm(8, 8); + MakeVars; + checks := Flag; + line := 1 + Rnd(40); + EnterBody(c, line); + for i := 1 to Steps do begin + if errors >= 19 then break; + gK := Rnd(17); + demoted := false; + RunStep; + if not gOk then + writeln('S ', c, ' ', gK, ' failed') + else begin + writeln('S ', c, ' ', gK, ' ok'); + Dump(gX); + if (gK < 4) or ((gK >= 5) and (gK <= 9)) then RunDiscard; + end; + writeln('demoted ', Bit(demoted)); + ResetStack(0, 0); + end; + EndProc(c, sig^.base <> nil); +end; + +function ChunkNameOf(i: longint): longint; +var s: string; +begin + s := 'p' + chr(48 + i div 10) + chr(48 + i mod 10); + ChunkNameOf := Intern(@s[1], 3); +end; + +var + i, c: longint; path: string; +begin + seed := 5; + for i := 1 to length(ParamStr(1)) do seed := seed * 10 + ord(ParamStr(1)[i]) - 48; + Letters := 'abcdefgh' + #0; + path := 'src/test/ItemDump.txt'; + if Open(path) <> '' then Fatal('no file'); + Next; + listing := true; + curFile := Intern(@path[1], length(path)); + for i := 0 to NumProcs - 1 do begin c := NewChunk(secText, -1, ChunkNameOf(i)); chunks^[c].live := true end; + for i := 0 to NumGlobs - 1 do begin + c := NewChunk(secBss, -1, ChunkNameOf(NumProcs + i)); + SetBss(c, 64, 8); + end; + MakeTypes; + MakeObjs; + for i := 0 to NumProcs - 1 do GenProc(FirstProc + i); + writeln('pc ', pc, ' fixups ', numFixups, ' lines ', numLines, ' said ', SaidCount); + for i := 0 to pc - 1 do write(HexStr(code^[i], 2)); + writeln; + for i := 0 to numFixups - 1 do writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend); + for i := 0 to numLines - 1 do writeln('L ', lines^[i].at, ' ', lines^[i].chunk, ' ', lines^[i].line, ' ', lines^[i].col); + List(-1); +end. diff --git a/src/test/ItemDump.raz b/src/test/ItemDump.raz new file mode 100644 index 0000000..8e4b126 --- /dev/null +++ b/src/test/ItemDump.raz @@ -0,0 +1,679 @@ +(* Drives Item with a fixed pseudo-random script of operands and + operations, with mistakes among them, and prints what each step gave + (the item, or that it failed, whose message goes to standard error), + then the bytes, fixups, line notes and listing (raz -S) of the code + it made: src/Item.raz's side of a test against the seed's, + ItemDump.pas, which does and prints the same. The argument, a digit, + changes the script. A run ends at the 20th error, as a compile does, + so several scripts are run. *) +module ItemDump; +import Out, Fmt, Files, Heap, Diag, Scan, Sym, Chunk, X := X64, Gen, Item; + +const + FirstProc = 3; (* chunks 0 to 2 are Gen's own *) + NumProcs = 30; + FirstGlob = FirstProc + NumProcs; + NumGlobs = 4; + Steps = 14; + (* the types of the script, by number *) + YInt = 0; YI64 = 1; YI32 = 2; YU8 = 3; YU16 = 4; YU32 = 5; YU64 = 6; YBool = 7; + YReal = 8; YF32 = 9; YI8 = 10; YEnum = 11; YSet = 12; YPtr = 13; YVptr = 14; + YPtrArr = 15; YArr = 16; YArrU8 = 17; YSlice = 18; YBytes = 19; YRec = 20; + YPacked = 21; YVariant = 22; YProc0 = 23; YProc1 = 24; YProc2 = 25; + YPtrRec = 26; YErr = 27; YVrec = 28; YVarr = 29; + NumT = 30; + IntTypes: [8]INT = [YInt, YI64, YI32, YU8, YU16, YU32, YU64, YI8]; + Ops: [20]Scan.Sym = [Scan.sPlus, Scan.sMinus, Scan.sTimes, Scan.sDiv, Scan.sMod, + Scan.sAmp, Scan.sBar, Scan.sXor, Scan.sShl, Scan.sShr, + Scan.sEql, Scan.sNeq, Scan.sLss, Scan.sLeq, Scan.sGtr, Scan.sGeq, + Scan.sSlash, Scan.sIn, Scan.sPlus, Scan.sMinus]; + Cmps: [6]Scan.Sym = [Scan.sEql, Scan.sNeq, Scan.sLss, Scan.sLeq, Scan.sGtr, Scan.sGeq]; + +var + Letters: []U8; + seed: I64; + ty: [NumT]^Sym.Type; + vars: [NumT]^Sym.Obj; (* a variable of each type, placed anew for each procedure *) + procs: [6]^Sym.Obj; + strs: [3]^Sym.Obj; + arrConst, typeObj, builtinObj, caseObj: ^Sym.Obj; + mod0, mod1: ^Sym.Module; + tuple2, record3, packedR, variantT: ^Sym.Type; + results: [9]^Sym.Type; + curRes: INT; (* the result of the procedure, an index of results *) + call: Gen.CallInfo; + +proc rnd(n: INT): INT; +begin + seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; + return INT((seed shr 8) mod I64(n)); +end; + +proc flag: BOOL; +begin + return rnd(2) = 0; +end; + +proc bit(f: BOOL): INT; +begin + if f then return 1; end; + return 0; +end; + +proc pos: Diag.Pos; +var p: Diag.Pos; +begin + p.f := 0; p.a := rnd(400); p.b := p.a + 1 + rnd(12); + return p; +end; + +proc constVal: I64; +var x: INT; r: I64; +begin + x := rnd(1 shl 30); + match rnd(7) of + | 0: r := x mod 10; + | 1: r := -(x mod 100); + | 2: r := I64(1) shl (x mod 20); + | 3: r := x; + | 4: r := I64(x) * 4096 * 4096 * 9 - 7; + | 5: r := -I64(x) * 8; + | else: r := x mod 1000 - 500; + end; + return r; +end; + +(* A name, interned *) +proc intern(s: []U8): INT; +begin + return Scan.intern(ADR(s[0]), LEN(s)); +end; + +(* A name v00, v01, ... , interned *) +proc nameOf(i: INT): INT; +var s: [3]U8; +begin + s[0] := 'v'; s[1] := U8(48 + i div 10); s[2] := U8(48 + i mod 10); + return Scan.intern(ADR(s[0]), 3); +end; + +proc newObjs(cls: Sym.Class; t: ^Sym.Type; n: INT; step: I64; at: INT): ^Sym.Obj; +var first, o, last: ^Sym.Obj; i: INT; +begin + first := nil; last := nil; + for i := 0 to n - 1 do + o := Sym.newObj(cls, nameOf(at + i), t); + o^.val := step * I64(i); + if last = nil then first := o; else last^.next := o; end; + last := o; + end; + return first; +end; + +proc newType(form: Sym.Form; size, align: I64): ^Sym.Type; +begin + return Sym.newType(form, size, align); +end; + +proc procType(res: ^Sym.Type; params: ^Sym.Obj; n: INT): ^Sym.Type; +var t: ^Sym.Type; +begin + t := newType(Sym.fProc, 8, 8); + t^.base := res; + t^.fields := params; + t^.len := n; + return t; +end; + +proc param(t: ^Sym.Type; isVar: BOOL; at: INT): ^Sym.Obj; +var o: ^Sym.Obj; +begin + o := Sym.newObj(Sym.oVar, nameOf(at), t); + o^.param := true; + o^.isVar := isVar; + return o; +end; + +proc makeTypes; +var t: ^Sym.Type; p, q, r: ^Sym.Obj; i: INT; +begin + ty[YInt] := Sym.tInt; ty[YI64] := Sym.tI64; ty[YI32] := Sym.tI32; ty[YU8] := Sym.tU8; + ty[YU16] := Sym.tU16; ty[YU32] := Sym.tU32; ty[YU64] := Sym.tU64; ty[YBool] := Sym.tBool; + ty[YReal] := Sym.tReal; ty[YF32] := Sym.tF32; ty[YI8] := Sym.tI8; ty[YErr] := Sym.tError; + ty[YBytes] := Sym.tBytes; + t := newType(Sym.fEnum, 1, 1); t^.len := 5; ty[YEnum] := t; + t := newType(Sym.fSet, 8, 8); t^.len := 5; t^.base := ty[YEnum]; ty[YSet] := t; + t := newType(Sym.fPtr, 8, 8); t^.base := Sym.tI64; ty[YPtr] := t; + t := newType(Sym.fPtr, 8, 8); t^.base := Sym.tI64; t^.vol := true; ty[YVptr] := t; + t := newType(Sym.fArray, 48, 8); t^.base := Sym.tI64; t^.len := 6; ty[YArr] := t; + t := newType(Sym.fPtr, 8, 8); t^.base := ty[YArr]; ty[YPtrArr] := t; + t := newType(Sym.fPtr, 8, 8); t^.base := ty[YArr]; t^.vol := true; ty[YVarr] := t; + t := newType(Sym.fArray, 8, 1); t^.base := Sym.tU8; t^.len := 8; ty[YArrU8] := t; + t := newType(Sym.fSlice, 16, 8); t^.base := Sym.tI64; ty[YSlice] := t; + (* a record of an I64, an F64 and an I32 *) + record3 := newType(Sym.fRecord, 24, 8); + p := Sym.newObj(Sym.oField, nameOf(40), Sym.tI64); p^.val := 0; + q := Sym.newObj(Sym.oField, nameOf(41), Sym.tReal); q^.val := 8; p^.next := q; + r := Sym.newObj(Sym.oField, nameOf(42), Sym.tI32); r^.val := 16; q^.next := r; + record3^.fields := p; + ty[YRec] := record3; + t := newType(Sym.fPtr, 8, 8); t^.base := record3; ty[YPtrRec] := t; + t := newType(Sym.fPtr, 8, 8); t^.base := record3; t^.vol := true; ty[YVrec] := t; + (* a packed record: a byte, then an I32 that may be misaligned *) + packedR := newType(Sym.fRecord, 53, 1); + packedR^.packd := true; + p := Sym.newObj(Sym.oField, nameOf(43), Sym.tU8); p^.val := 0; + q := Sym.newObj(Sym.oField, nameOf(44), Sym.tI32); q^.val := 1; p^.next := q; + r := Sym.newObj(Sym.oField, nameOf(46), ty[YArr]); r^.val := 5; q^.next := r; + packedR^.fields := p; + ty[YPacked] := packedR; + variantT := newType(Sym.fVariant, 16, 8); + ty[YVariant] := variantT; + tuple2 := newType(Sym.fRecord, 16, 8); + tuple2^.tuple := true; tuple2^.len := 2; tuple2^.fields := newObjs(Sym.oVar, Sym.tInt, 2, 8, 45); + (* procedures: (I64, F64) I64; (); (var I64, []I64) of two results *) + p := param(Sym.tInt, false, 46); p^.next := param(Sym.tReal, false, 47); + ty[YProc0] := procType(Sym.tInt, p, 2); + ty[YProc1] := procType(nil, nil, 0); + p := param(Sym.tI64, true, 48); p^.next := param(ty[YSlice], false, 49); + ty[YProc2] := procType(tuple2, p, 2); + results[0] := nil; results[1] := Sym.tInt; results[2] := Sym.tReal; results[3] := ty[YSlice]; + results[4] := tuple2; results[5] := record3; results[6] := Sym.tF32; results[7] := Sym.tI16; + results[8] := ty[YBytes]; + for i := 0 to NumT - 1 do + if ty[i] = nil then Diag.fatal("a type is missing"); end; + end; +end; + +(* The objects named by the script: procedures, strings, constants of + an array, a type, a built-in, a case of a variant *) +proc makeObjs; +var i, c: INT; o: ^Sym.Obj; +begin + NEW(mod0, Heap.heap); mod0^.name := intern("Zero"); + NEW(mod1, Heap.heap); mod1^.name := intern("Other"); + Sym.setCurModule(mod0); + for i := 0 to 5 do + o := Sym.newObj(Sym.oProc, nameOf(50 + i), ty[YProc0 + i mod 3]); + o^.chunk := FirstProc + rnd(NumProcs); + o^.ext := i >= 4; + o^.isCode := i = 3; + procs[i] := o; + end; + for i := 0 to 2 do + o := Sym.newObj(Sym.oConst, nameOf(60 + i), Sym.tStr); + o^.val := 2 + 3 * i; + c := Chunk.newChunk(Chunk.secRodata, -1, -1); + Chunk.setData(c, ADR(Letters[0]), INT(o^.val) + 1, 1); + o^.chunk := c; + strs[i] := o; + end; + arrConst := Sym.newObj(Sym.oConst, nameOf(63), ty[YArr]); + arrConst^.chunk := Chunk.newChunk(Chunk.secRodata, -1, -1); + Chunk.setData(arrConst^.chunk, ADR(Letters[0]), 8, 8); + typeObj := Sym.newObj(Sym.oType, nameOf(64), ty[YRec]); + builtinObj := Sym.newObj(Sym.oBuiltin, nameOf(65), Sym.tNone); + caseObj := Sym.newObj(Sym.oCase, nameOf(66), variantT); + caseObj^.val := 3; + caseObj^.fields := newObjs(Sym.oField, Sym.tInt, 2, 8, 67); + caseObj^.fields^.val := 8; +end; + +(* The variable of each type, in the frame, a chunk, a slot, a register, + another module or C's, as the procedure compiled has them *) +proc makeVars; +var i, k: INT; o: ^Sym.Obj; t: ^Sym.Type; +begin + for i := 0 to NumT - 1 do + t := ty[i]; + o := Sym.newObj(Sym.oVar, nameOf(i), t); + o^.lev := 1; + k := rnd(9); + if k = 2 then + o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs); + elsif k = 3 then + o^.ind := true; o^.val := Gen.allocPerm(8, 8); o^.off := 8 * rnd(3); + elsif k = 4 then + if (t^.form in {Sym.fInt, Sym.fPtr}) and (t^.size = 8) then + o^.reg := Gen.VarRegs[rnd(5)]; + elsif t^.form = Sym.fReal then + o^.reg := Gen.XVarRegs[rnd(4)]; + elsif t^.form = Sym.fSlice then + o^.reg := Gen.VarRegs[rnd(3)]; o^.reg2 := Gen.VarRegs[3 + rnd(2)]; + end; + if o^.reg = 0 then o^.val := Gen.allocPerm(t^.size, 8); end; + elsif k = 5 then + o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs); o^.home := mod1; + elsif k = 6 then + o^.lev := 0; o^.chunk := FirstGlob + rnd(NumGlobs); o^.ext := true; + else + o^.val := Gen.allocPerm(t^.size + 8, 8); + end; + vars[i] := o; + end; +end; + +(* Operands *) + +proc intType: ^Sym.Type; +begin + return ty[IntTypes[rnd(8)]]; +end; + +proc varItem(var x: Item.Item; t: ^Sym.Type): ERROR; +var i, k: INT; +begin + k := rnd(NumT); + for i := 0 to NumT - 1 do + if ty[i] = t then k := i; end; + end; + x := {}; + x.pos := pos(); + return Item.makeItem(x, vars[k]); +end; + +(* An operand of type t, or of any if t is nil *) +proc operand(var x: Item.Item; t: ^Sym.Type): ERROR; +var k: INT; r: F64; v: I64; +begin + x := {}; + x.pos := pos(); + if t = nil then + match rnd(14) of + | 0: Item.makeConst(x, Sym.tConst, constVal()); + | 1: Item.makeConst(x, Sym.tConst, constVal() mod 200); + | 2: t := intType(); v := constVal() mod 100; Item.makeConst(x, t, v); + | 3: r := F64(constVal() mod 1000) / 8.0; Item.makeReal(x, r); + | 4: Item.makeConst(x, Sym.tBool, I64(rnd(2))); + | 5: return Item.makeItem(x, strs[rnd(3)]); + | 6: Item.makeConst(x, Sym.tNil, 0); + | 7: return Item.makeItem(x, procs[rnd(6)]); + | 8: if rnd(4) = 0 then + match rnd(3) of + | 0: return Item.makeItem(x, typeObj); + | 1: return Item.makeItem(x, builtinObj); + | else: return Item.makeItem(x, caseObj); + end; + end; + return Item.makeItem(x, arrConst); + | 13: try Item.makeItem(x, vars[rnd(NumT)]); return Item.value(x); + | else: return varItem(x, ty[rnd(NumT)]); + end; + return nil; + end; + k := rnd(10); + if Sym.isInt(t) then + if k < 3 then Item.makeConst(x, Sym.tConst, constVal() mod 100); return nil; end; + if k = 3 then Item.makeConst(x, t, constVal() mod 100); return nil; end; + elsif t^.form = Sym.fReal then + if k < 3 then r := F64(constVal() mod 1000) / 8.0; Item.makeReal(x, r); return nil; end; + elsif t^.form = Sym.fBool then + if k < 3 then Item.makeConst(x, Sym.tBool, I64(rnd(2))); return nil; end; + elsif t^.form = Sym.fPtr then + if k < 2 then Item.makeConst(x, Sym.tNil, 0); return nil; end; + elsif (t^.form = Sym.fSlice) and (t^.base = Sym.tU8) then + if k < 3 then return Item.makeItem(x, strs[rnd(3)]); end; + end; + return varItem(x, t); +end; + +(* A condition, left as one: a comparison of two integers *) +proc condItem(var x: Item.Item): ERROR; +var y: Item.Item; L: INT; op: Scan.Sym; t: ^Sym.Type; +begin + t := intType(); + op := Cmps[rnd(6)]; + try operand(x, t); + try Item.op1(op, x, L); + try operand(y, t); + return Item.op2(op, x, y, L); +end; + +(* A variable, or part of one: through a pointer, a field, an element, a slice *) +proc place(var x: Item.Item): ERROR; +var i, k: INT; f: ^Sym.Obj; y, lo, hi: Item.Item; +begin + try varItem(x, ty[rnd(NumT)]); + for i := 1 to 3 do + if rnd(3) # 0 then + k := rnd(6); + if (k = 0) or (x.typ^.form = Sym.fPtr) then + try Item.deref(x); + elsif x.typ^.form = Sym.fRecord then + f := x.typ^.fields; + k := rnd(3); + while (k > 0) and (f^.next # nil) do f := f^.next; DEC(k); end; + try Item.field(x, f); + elsif (x.typ^.form in {Sym.fArray, Sym.fSlice, Sym.fStr}) then + try Item.indexPrep(x); + if k < 4 then + try operand(y, intType()); + try Item.index(x, y); + else + try operand(lo, intType()); + try Item.sliceLo(lo); + try operand(hi, intType()); + try Item.slice(x, lo, hi); + end; + end; + end; + end; + return nil; +end; + +(* The state of an item *) +proc dump(var x: Item.Item); +var name: []U8; flags: INT; +begin + name := "-"; + if x.typ # nil then name := Sym.typeName(x.typ); end; + flags := bit(x.vol) + 2 * bit(x.isVar) + 4 * bit(x.odd) + 8 * bit(x.ro) + 16 * bit(x.deref); + Fmt.print("I {} {} {} {} {} {} {}", [Fmt.int(INT(x.mode)), Fmt.str(name), Fmt.int(INT(x.rel)), + Fmt.int(bit(x.relSigned)), Fmt.int(x.fj), Fmt.int(x.tj), Fmt.int(x.val)]); + Fmt.print(" {} {} {} {} depth {} pushed {}\n", [Fmt.int(INT(x.base)), Fmt.int(x.chunk), Fmt.int(x.off), + Fmt.int(flags), Fmt.int(Gen.depth), Fmt.int(Gen.pushed)]); +end; + +(* A call: of a procedure of the script or a variable of a procedure + type, with arguments that mostly fit its parameters *) +proc doCall(var x: Item.Item): ERROR; +var f, a: Item.Item; p: ^Sym.Obj; n: INT; +begin + f := {}; + f.pos := pos(); + if rnd(5) = 0 then try Item.makeItem(f, vars[YProc0 + rnd(3)]); + else try Item.makeItem(f, procs[rnd(6)]); end; + try Item.beginCall(call, f); + p := call.param; + n := rnd(4) - 1; + while (p # nil) or (n > 0) do + if p # nil then + if p^.isVar and (rnd(2) = 0) then + try varItem(a, ty[YVptr]); + try Item.deref(a); + elsif rnd(6) = 0 then try operand(a, nil); + else try operand(a, p^.typ); end; + p := p^.next; + else + try operand(a, nil); + n := n - 1; + end; + try Item.passArg(call, a); + if (p = nil) and (n < 0) then n := 0; end; + if (p # nil) and (n < 0) and (rnd(4) = 0) then p := nil; n := 0; end; + end; + return Item.endCall(call, x); +end; + +(* A binary operation, with a condition's jumps made after it, sometimes *) +proc binary(var x: Item.Item): ERROR; +var y: Item.Item; L, M: INT; op: Scan.Sym; t: ^Sym.Type; +begin + L := Gen.NoLabel; + M := Gen.NoLabel; + op := Ops[rnd(20)]; + match rnd(8) of + | 0, 1: t := intType(); + | 2: t := ty[YReal + rnd(2)]; + | 3: t := ty[YBool]; + | 4: t := ty[YEnum + rnd(2)]; + | else: t := ty[rnd(NumT)]; + end; + if rnd(6) = 0 then + (* and, or *) + if flag() then op := Scan.sAnd; else op := Scan.sOr; end; + try condItem(x); + try Item.op1(op, x, L); + try condItem(y); + elsif op = Scan.sIn then + try operand(x, ty[YEnum]); + try Item.op1(op, x, L); + try operand(y, ty[YSet]); + else + try operand(x, t); + try Item.op1(op, x, L); + if rnd(5) = 0 then try operand(y, nil); else try operand(y, t); end; + end; + try Item.op2(op, x, y, L); + if (x.mode = Item.mCond) and (rnd(3) # 0) then + if flag() then try Item.condJump(x, M); else try Item.condJumpTrue(x, M); end; + Gen.fix(M); + x.mode := Item.mNone; (* its values are used *) + end; + return nil; +end; + +proc unary(var x: Item.Item): ERROR; +begin + try operand(x, nil); + match rnd(3) of + | 0: return Item.neg(x); + | 1: return Item.notOp(x); + | else: return Item.complement(x); + end; +end; + +(* match: the slot of a variant, an enumeration or an integer, and + tests of it *) +proc doMatch(var x: Item.Item): ERROR; +var p, lo, hi: I64; L: INT; +begin + L := Gen.NoLabel; + match rnd(3) of + | 0: try varItem(x, ty[YVariant]); + | 1: try varItem(x, ty[YEnum]); + | else: try operand(x, nil); + end; + p := try Item.matchBegin(x); + Item.matchTag(p, constVal() mod 10, L); + lo := constVal() mod 10; + hi := constVal() mod 10 + 10; + Item.matchRange(p, lo, hi, L); + Item.matchRange(p, 3, 3, L); + Gen.fix(L); + return nil; +end; + +(* A for loop's variable stepped and tested *) +proc doFor(var x: Item.Item): ERROR; +var o: ^Sym.Obj; lim: Item.Item; step: I64; exitL: INT; +begin + o := vars[IntTypes[rnd(8)]]; + step := constVal() mod 5; + if step = 0 then step := 1; end; + if rnd(2) = 0 then step := -step; end; + lim := {}; + lim.pos := pos(); + Item.makeConst(lim, o^.typ, constVal() mod 50); + exitL := Gen.NoLabel; + try Item.forStep(o, step); + try Item.forNext(o, lim, step, exitL, Chunk.pc, Chunk.pc); + Gen.fix(exitL); + x := lim; + return nil; +end; + +(* INC and DEC, pin, COPY *) +proc doMisc(var x: Item.Item): ERROR; +var y: Item.Item; +begin + match rnd(5) of + | 0: + try place(x); + try Item.address(x); + try operand(y, x.typ); + return Item.incDec(x, y, flag()); + | 1: + try place(x); + return Item.pin(x); + | 2: + try place(x); + try Item.copyDest(x); + try place(y); + return Item.copyFrom(x, y); + | 3: + try operand(x, nil); + Item.makeStr(y); + return Item.coerce(y, ty[YBytes]); + | else: + try operand(x, nil); + Item.nilTest(x); + Item.usesReals(x.pos); + return Item.discard(x); + end; +end; + +(* A variant, a record's fields, an error's chunk, the message of one *) +proc doTemp(var x: Item.Item): ERROR; +var a: Item.Item; c, h, n: INT; f: ^Sym.Obj; +begin + x := {}; + x.pos := pos(); + match rnd(5) of + | 0: Item.zeroTemp(x, ty[YVariant]); + | 1: + Item.construct(x, caseObj); + f := caseObj^.fields; + try operand(a, f^.typ); + return Item.setField(x, f, a); + | 2: + Item.zeroTemp(x, ty[YRec]); + f := ty[YRec]^.fields; + if flag() then f := f^.next; end; + try operand(a, f^.typ); + return Item.setField(x, f, a); + | 3: + try operand(a, nil); + h := rnd(3) - 1; + n := rnd(3) - 1; + c := try Item.errorChunk(a, h, n); + Item.makeConst(x, Sym.tError, I64(c) + 1); + return nil; + | else: + try operand(x, ty[YErr]); + return Item.msg(x); + end; + return nil; +end; + +proc doReturn(var x: Item.Item): ERROR; +var f: ^Sym.Obj; +begin + if (curRes = 4) and flag() then + (* several results *) + f := tuple2^.fields; + if flag() then f := f^.next; end; + if flag() then + try operand(x, f^.typ); + return Item.returnField(f, x); + end; + try doCall(x); + return Item.returnAll(x); + end; + if rnd(4) = 0 then return Item.returnNone(); end; + try operand(x, results[curRes]); + return Item.returnValue(x); +end; + +(* One step of the script, whose item is x *) +proc step(k: INT; var x: Item.Item): ERROR; +var y: Item.Item; +begin + x := {}; + match k of + | 0: try operand(x, nil); return Item.value(x); + | 1: try operand(x, nil); return Item.address(x); + | 2: try operand(x, nil); return Item.coerce(x, ty[rnd(NumT)]); + | 3: try operand(x, nil); return Item.coerceExact(x, intType(), ""); + | 4: + try place(x); + try operand(y, x.typ); + return Item.assign(x, y); + | 5: return unary(x); + | 6: return binary(x); + | 7: try operand(x, nil); return Item.convert(x, ty[rnd(NumT)]); + | 8: return place(x); + | 9: return doCall(x); + | 10: return doMatch(x); + | 11: return doFor(x); + | 12: return doMisc(x); + | 13: return doTemp(x); + | 14: return doReturn(x); + | else: return binary(x); + end; +end; + +(* One procedure of Steps steps *) +proc genProc(c: INT); +var + sig: ^Sym.Type; i, k, line: INT; x: Item.Item; err: ERROR; +begin + curRes := rnd(9); + sig := procType(results[curRes], nil, 0); + Item.beginProc(sig, nil); + for i := 0 to 5 do _ := Gen.allocPerm(8, 8); end; + makeVars(); + Item.setChecks(flag()); + line := 1 + rnd(40); + Gen.enterBody(c, line); + for i := 1 to Steps do + if Diag.errors >= 19 then break; end; (* the 20th would end the run *) + k := rnd(17); + Item.setDemoted(false); + err := step(k, x); + if err # nil then + Fmt.print("S {} {} failed\n", [Fmt.int(c), Fmt.int(k)]); + else + Fmt.print("S {} {} ok\n", [Fmt.int(c), Fmt.int(k)]); + dump(x); + (* the items of these steps are as an operand is, on the stack *) + if (k < 4) or ((k >= 5) and (k <= 9)) then _ := Item.discard(x); end; + end; + Fmt.print("demoted {}\n", [Fmt.int(bit(Item.demoted))]); + Gen.resetStack(0, 0); + end; + _ := Gen.endProc(c, sig^.base # nil); +end; + +proc chunkNameOf(i: INT): INT; +var s: [3]U8; +begin + s[0] := 'p'; s[1] := U8(48 + i div 10); s[2] := U8(48 + i mod 10); + return Scan.intern(ADR(s[0]), 3); +end; + +proc main*; +var i, c: INT; path: []U8; arg: []U8; +begin + arg := Files.arg(1); + seed := 5; + for i := 0 to LEN(arg) - 1 do seed := seed * 10 + I64(arg[i]) - 48; end; + Letters := "abcdefgh\0"; + path := "src/test/ItemDump.txt"; + if LEN(Scan.open(path)) # 0 then Diag.fatal("no file"); end; + Scan.next; (* the string the file starts with *) + X.setListing(true); + Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path))); + for i := 0 to NumProcs - 1 do c := Chunk.newChunk(Chunk.secText, -1, chunkNameOf(i)); Chunk.setLive(c); end; + for i := 0 to NumGlobs - 1 do + c := Chunk.newChunk(Chunk.secBss, -1, chunkNameOf(NumProcs + i)); + Chunk.setBss(c, 64, 8); + end; + makeTypes(); + makeObjs(); + for i := 0 to NumProcs - 1 do genProc(FirstProc + i); end; + Fmt.print("pc {} fixups {} lines {} said {}\n", [Fmt.int(Chunk.pc), + Fmt.int(Chunk.numFixups), Fmt.int(Chunk.numLines), Fmt.int(X.saidCount())]); + for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end; + Out.ln; + for i := 0 to Chunk.numFixups - 1 do + Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]); + end; + for i := 0 to Chunk.numLines - 1 do + Fmt.print("L {} {} {} {}\n", [Fmt.int(Chunk.lines[i].at), Fmt.int(Chunk.lines[i].chunk), + Fmt.int(Chunk.lines[i].line), Fmt.int(Chunk.lines[i].col)]); + end; + X.list(-1); +end; + +end ItemDump. diff --git a/src/test/ItemDump.txt b/src/test/ItemDump.txt new file mode 100644 index 0000000..5be0a4c --- /dev/null +++ b/src/test/ItemDump.txt @@ -0,0 +1,41 @@ +"item test" + x value sum alpha beta; + next beta items len alpha next count alpha beta; + value beta count beta next value; + len beta count; + sum len alpha len len value alpha count; + next x n; + x next beta len n next; + sum x beta len len sum count items beta; + tmp beta len alpha len count p; + next value items p len p items n; + x tmp count beta; + n next p items tmp p n; + beta beta next value x items x; + value alpha sum beta next len; + items items tmp items len p len p beta; + beta n p tmp sum beta alpha tmp tmp; + sum len sum p n; + value sum items alpha p items x len; + p alpha count; + n x tmp count value value p beta x; + value next n x value next; + tmp value items sum value; + x beta x x; + sum count alpha p; + len x n n alpha x value next items; + len items x tmp next len sum; + tmp alpha p sum next value value value; + beta p sum value alpha count; + count p x; + items len alpha; + alpha len x; + beta items len alpha beta count len; + x sum n items len items; + beta beta p p p p; + beta x beta tmp items; + n p tmp x next alpha count next; + x tmp next alpha next; + sum beta tmp n next; + x items count next next; + next items sum count len count count value tmp; diff --git a/src/test/LinkDump.pas b/src/test/LinkDump.pas new file mode 100644 index 0000000..f4cd152 --- /dev/null +++ b/src/test/LinkDump.pas @@ -0,0 +1,91 @@ +{ Makes a program of chunks by a fixed pseudo-random script, links it and + writes it as an executable to the file of the second argument, in the + way the first says (0 static, 1 dynamic, 2 stripped): the seed's side + of a test of src/Link.raz and src/Elf.raz, whose LinkDump.raz does + the same and writes the same file. } +program linkdump; +{$mode objfpc}{$H-} +uses diag, scan, chunk, link, elf; +const NumC = 200; +var + seed: int64; + names: array[0..7] of longint; + i, j, k, kind, n, x, y, z, mode: longint; + b: array[0..63] of byte; + +function Rnd(n: longint): longint; +begin + seed := (seed * 1103515245 + 12345) and $7FFFFFFF; + Rnd := (seed shr 8) mod n; +end; + +var c, e, line, col: longint; +begin + seed := 5; + mode := ord(ParamStr(1)[1]) - 48; + for i := 0 to 7 do begin b[0] := 97 + i; names[i] := Intern(@b[0], 1) end; + placesChunk := NewChunk(secRodata, -1, -1); + SetData(placesChunk, @b[0], 0, 8); + for i := 0 to NumC - 1 do begin + if i = 0 then kind := 0 else kind := Rnd(10); + x := Rnd(4); y := Rnd(8); + case kind of + 0..5: begin + c := NewChunk(secText, x - 1, y); + BeginChunk(c); + z := Rnd(3); curFile := names[z]; + line := Rnd(300); col := Rnd(60); + NoteLine(line, col); + if i = 0 then begin AddFixup(pc, placesChunk, 0); Put4(0) end; + n := 2 + Rnd(10); + for j := 1 to n do begin + z := Rnd(5); + if z <= 1 then begin + e := Rnd(NumC); y := Rnd(8); + AddFixup(pc, e, y); + Put4(0); + end else if z = 2 then begin + z := Rnd(3); curFile := names[z]; + line := Rnd(300); col := Rnd(60); + NoteLine(line, col); + end else begin x := Rnd(1 shl 30); Put4(x); x := Rnd(256); Put1(x) end; + end; + EndChunk(c); + n := Rnd(3); + for j := 1 to n do begin + x := Rnd(8); y := Rnd(200); z := Rnd(6); + NoteVar(c, names[x], y - 100, z); + end; + end; + 6, 7: begin + c := NewChunk(secRodata, x - 1, y); + n := 8 * (1 + Rnd(4)); + for j := 0 to n - 1 do b[j] := Rnd(256); + SetData(c, @b[0], n, 8); + for j := 0 to n div 8 - 1 do begin + z := Rnd(2); + if z = 0 then begin e := Rnd(NumC); y := Rnd(8); AddDataFixup(c, j * 8, e, y) end; + end; + end; + 8: begin + c := NewChunk(secBss, x - 1, y); + z := Rnd(200); e := Rnd(4); + SetBss(c, 1 + z, 1 shl e); + end; + 9: begin z := Rnd(8); c := ExternChunk(names[z]) end; + end; + end; + { every chunk a fixup names must exist, and be defined if it is reached } + while numChunks < NumC do begin c := NewChunk(secBss, -1, -1); SetBss(c, 8, 8) end; + for i := 0 to numChunks - 1 do + if chunks^[i].size < 0 then SetBss(i, 8, 8); + mainPath := 'some/main.raz'; + if mode = 1 then begin + numNeeded := 2; + needed[0] := names[0]; needed[1] := names[1]; + end; + stripped := mode = 2; + if mode = 2 then placesChunk := -1; + MarkLive(1); + WriteElf(ParamStr(2), 1); +end. diff --git a/src/test/LinkDump.raz b/src/test/LinkDump.raz new file mode 100644 index 0000000..92d97de --- /dev/null +++ b/src/test/LinkDump.raz @@ -0,0 +1,103 @@ +(* Makes a program of chunks by a fixed pseudo-random script, links it + and writes it as an executable to the file of the second argument, + in the way the first says (0 static, 1 dynamic, 2 stripped): + src/Link.raz's and src/Elf.raz's side of a test against the seed's, + LinkDump.pas, which writes the same file. *) +module LinkDump; +import Files, Diag, Scan, Chunk, Link, Elf; + +const NumC = 200; + +var seed: I64; + +proc rnd(n: INT): INT; +begin + seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; + return INT((seed shr 8) mod I64(n)); +end; + +(* a library that must be taken *) +proc ok(taken: BOOL); +begin + if not taken then Diag.fatal("too many libraries"); end; +end; + +proc main*; +var + names: [8]INT; b: [64]U8; arg: []U8; + i, j, kind, n, x, y, z, c, e, line, col, mode: INT; +begin + seed := 5; + arg := Files.arg(1); + mode := INT(arg[0]) - 48; + for i := 0 to 7 do b[0] := U8(97 + i); names[i] := Scan.intern(ADR(b[0]), 1); end; + Link.setPlaces(Chunk.newChunk(Chunk.secRodata, -1, -1)); + Chunk.setData(Link.placesChunk, ADR(b[0]), 0, 8); + for i := 0 to NumC - 1 do + if i = 0 then kind := 0; else kind := rnd(10); end; + x := rnd(4); y := rnd(8); + match kind of + | 0..5: + c := Chunk.newChunk(Chunk.secText, x - 1, y); + Chunk.beginChunk(c); + z := rnd(3); Chunk.setCurFile(names[z]); + line := rnd(300); col := rnd(60); + Chunk.noteLine(line, col); + if i = 0 then Chunk.addFixup(Chunk.pc, Link.placesChunk, 0); Chunk.put4(0); end; + n := 2 + rnd(10); + for j := 1 to n do + z := rnd(5); + if z <= 1 then + e := rnd(NumC); y := rnd(8); + Chunk.addFixup(Chunk.pc, e, y); + Chunk.put4(0); + elsif z = 2 then + z := rnd(3); Chunk.setCurFile(names[z]); + line := rnd(300); col := rnd(60); + Chunk.noteLine(line, col); + else + x := rnd(1 shl 30); Chunk.put4(x); x := rnd(256); Chunk.put1(x); + end; + end; + Chunk.endChunk(c); + n := rnd(3); + for j := 1 to n do + x := rnd(8); y := rnd(200); z := rnd(6); + Chunk.noteVar(c, names[x], y - 100, z); + end; + | 6, 7: + c := Chunk.newChunk(Chunk.secRodata, x - 1, y); + n := 8 * (1 + rnd(4)); + for j := 0 to n - 1 do b[j] := U8(rnd(256)); end; + Chunk.setData(c, ADR(b[0]), n, 8); + for j := 0 to n div 8 - 1 do + z := rnd(2); + if z = 0 then e := rnd(NumC); y := rnd(8); Chunk.addDataFixup(c, j * 8, e, y); end; + end; + | 8: + c := Chunk.newChunk(Chunk.secBss, x - 1, y); + z := rnd(200); e := rnd(4); + Chunk.setBss(c, 1 + z, 1 shl e); + | else: z := rnd(8); c := Chunk.externChunk(names[z]); + end; + end; + (* every chunk a fixup names must exist, and be defined if it is reached *) + while Chunk.numChunks < NumC do + c := Chunk.newChunk(Chunk.secBss, -1, -1); + Chunk.setBss(c, 8, 8); + end; + for i := 0 to Chunk.numChunks - 1 do + if Chunk.chunks[i].size < 0 then Chunk.setBss(i, 8, 8); end; + end; + Elf.setMainPath("some/main.raz"); + if mode = 1 then + ok(Elf.needLib(names[0])); + ok(Elf.needLib(names[1])); + end; + Elf.setStripped(mode = 2); + if mode = 2 then Link.setPlaces(-1); end; + Link.markLive(1); + Elf.writeElf(Files.arg(2), 1); +end; + +end LinkDump. diff --git a/src/test/Recover.raz b/src/test/Recover.raz new file mode 100644 index 0000000..cf0ae41 --- /dev/null +++ b/src/test/Recover.raz @@ -0,0 +1,38 @@ +(* Tests going on after an error, as the parser does with try: a driver + reads a file's symbols and reports each name `bad` as an error, + several calls deep; the error comes back up through them, and the + driver reads on from the next symbol. *) +module Recover; +import Out, Files, Diag, Scan; + +var failed, names: INT; + +proc deep(n: INT): ERROR; +begin + if n > 0 then + try deep(n - 1); + return nil; + end; + return Scan.mark("a bad name"); +end; + +proc main*; +var err: ERROR; +begin + if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end; + while Scan.tok # Scan.sEof do + Scan.next; + if Scan.tok = Scan.sIdent then + INC(names); + if Scan.nameOf(Scan.id) = "bad" then + err := deep(5); + if err # nil then INC(failed); end; + end; + end; + end; + Out.int(names); Out.str(" names, "); Out.int(failed); Out.str(" failed, "); + Out.int(Diag.errors); Out.str(" errors\n"); + Diag.finish; +end; + +end Recover. diff --git a/src/test/ScanBench.pas b/src/test/ScanBench.pas new file mode 100644 index 0000000..75b0336 --- /dev/null +++ b/src/test/ScanBench.pas @@ -0,0 +1,12 @@ +{ 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 new file mode 100644 index 0000000..a49e516 --- /dev/null +++ b/src/test/ScanBench.raz @@ -0,0 +1,15 @@ +(* 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/src/test/ScanDump.pas b/src/test/ScanDump.pas new file mode 100644 index 0000000..1b92f8e --- /dev/null +++ b/src/test/ScanDump.pas @@ -0,0 +1,21 @@ +{ Prints the symbols of a file, one per line: the seed's side of a test + of src/Scan.raz, which prints the same. A real is shown by its bits, + so that no formatting library decides what is the same. } +program scandump; +{$mode objfpc}{$H-} +uses diag, scan; +var i: longint; bits: int64; +begin + if Open(ParamStr(1)) <> '' then Fatal('no file'); + repeat + Next; + write(LineOf(TokPos), ':', TokPos.a, ':', TokPos.b, ' ', CurLine, ':', CurCol, ' ', ord(tok)); + case tok of + sIdent: write(' ', NameOf(id), ' ', id); + sInt, sChar: write(' ', ival); + sReal: begin Move(rval, bits, 8); write(' ', HexStr(bits, 16)) end; + sString: begin write(' "'); for i := 0 to slen - 1 do write(sbuf[i], ','); write('"') end; + end; + writeln; + until tok = sEof; +end. diff --git a/src/test/ScanDump.raz b/src/test/ScanDump.raz new file mode 100644 index 0000000..6d6643c --- /dev/null +++ b/src/test/ScanDump.raz @@ -0,0 +1,35 @@ +(* Prints the symbols of a file, one per line: src/Scan.raz's side of a + test against the seed's, ScanDump.pas, which prints the same. *) +module ScanDump; +import Out, Fmt, Files, Diag, Scan; + +proc main*; +var p: Diag.Pos; bits: ^U64; i: INT; str: []U8; r: F64; +begin + if LEN(Scan.open(Files.arg(1))) # 0 then Diag.fatal("no file"); end; + repeat + Scan.next; + p := Scan.tokPos(); + Fmt.print("{}:{}:{} {}:{} {}", [Fmt.int(Diag.lineOf(p)), Fmt.int(p.a), Fmt.int(p.b), + Fmt.int(Scan.curLine()), Fmt.int(Scan.curCol()), Fmt.int(INT(Scan.tok))]); + match Scan.tok of + | sIdent: Fmt.print(" {} {}", [Fmt.str(Scan.nameOf(Scan.id)), Fmt.int(Scan.id)]); + | sInt: Fmt.print(" {}", [Fmt.int(Scan.ival)]); + | sChar: Fmt.print(" {}", [Fmt.int(Scan.ival)]); + | sReal: + r := Scan.rval; + bits := ^U64(ADR(r)); + Out.str(" "); + Out.hex(bits^, 16); + | sString: + Out.str(" \""); + str := Scan.strBytes(); + for i := 0 to LEN(str) - 1 do Fmt.print("{},", [Fmt.int(INT(str[i]))]); end; + Out.str("\""); + | else: + end; + Out.ln; + until Scan.tok = Scan.sEof; +end; + +end ScanDump. diff --git a/src/test/SymDump.pas b/src/test/SymDump.pas new file mode 100644 index 0000000..d87e42d --- /dev/null +++ b/src/test/SymDump.pas @@ -0,0 +1,185 @@ +{ Builds types and objects by a fixed pseudo-random script, asks of them + what the parser asks of sym, and prints the answers: the seed's side + of a test of src/Sym.raz, whose SymDump.raz does the same and prints + the same. With the argument dup or deep it ends in the error of a name + declared twice, or of too many scopes. } +program symdump; +{$mode objfpc}{$H-} +uses diag, scan, sym; +const + Words: array[0..19] of string = ('alpha', 'alpho', 'beta', 'bet', 'gamma', 'gama', 'delta', 'Delta', + 'eps', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi', 'omicron', 'pi'); +var + seed: int64; + names: array[0..19] of longint; + mods: array[0..2] of PModule; + base: array[0..11] of PType; + pool: array[0..299] of PType; + objs: array[0..299] of PObj; + numPool, numObjs, i, k, n, op, x, y, z: longint; + t, o2: PType; + o: PObj; + saved: array[0..MaxDepth - 1] of longint; + d: longint; + v: int64; + +function Rnd(n: longint): longint; +begin + seed := (seed * 1103515245 + 12345) and $7FFFFFFF; + Rnd := (seed shr 8) mod n; +end; + +function Fields(m: longint; allowVar: boolean): PObj; +var f, first, last: PObj; j, x, y, z: longint; +begin + first := nil; last := nil; + for j := 1 to m do begin + x := Rnd(20); y := Rnd(numPool); + f := NewObj(oField, names[x], pool[y]); + z := Rnd(2); f^.exported := z = 0; + z := Rnd(3); f^.isVar := allowVar and (z = 0); + f^.val := j * 8; + if first = nil then first := f else last^.next := f; + last := f; + end; + Fields := first; +end; + +procedure Add(t: PType); +begin + if numPool <= High(pool) then begin pool[numPool] := t; inc(numPool) end; +end; + +procedure MakeType; +var t: PType; r, m, x: longint; f: PObj; +begin + r := Rnd(11); + case r of + 0: t := NewType(fPtr, 8, 8); + 1: t := NewType(fArray, 0, 1); + 2: t := NewType(fSlice, 16, 8); + 3: t := NewType(fRecord, 0, 8); + 4: t := NewType(fProc, 8, 8); + 5: t := NewType(fSet, 8, 8); + 6: t := NewType(fVariant, 16, 8); + 7: t := NewType(fEnum, 1, 1); + 8: t := NewType(fRecord, 16, 8); + 9: t := NewType(fProc, 8, 8); + else t := NewType(fPtr, 8, 8); + end; + x := Rnd(numPool); t^.base := pool[x]; + t^.len := Rnd(5); + x := Rnd(4); t^.vol := x = 0; + x := Rnd(4); t^.variadic := (t^.form = fProc) and (x = 0); + x := Rnd(2); t^.tuple := (t^.form = fRecord) and (x = 0); + if t^.form in [fRecord, fProc, fVariant] then begin + m := Rnd(4); + t^.fields := Fields(m, t^.form = fProc); + t^.len := m; + if t^.form = fRecord then t^.base := nil; + x := Rnd(2); + if (t^.form = fProc) and (x = 0) then t^.base := nil; + if t^.form = fVariant then begin + f := t^.fields; + while f <> nil do begin f^.cls := oCase; x := Rnd(3); f^.fields := Fields(x, false); f := f^.next end; + end; + end; + x := Rnd(3); + if x = 0 then begin + x := Rnd(20); t^.obj := NewObj(oType, names[x], t); + x := Rnd(3); t^.obj^.module := mods[x]; + end; + Add(t); +end; + +begin + seed := 11; + for i := 0 to 19 do names[i] := Intern(@Words[i][1], length(Words[i])); + for i := 0 to 2 do begin + New(mods[i]); FillChar(mods[i]^, SizeOf(TModule), 0); + mods[i]^.sname := names[i * 5]; + end; + curModule := mods[0]; + base[0] := tI8; base[1] := tI16; base[2] := tI32; base[3] := tI64; base[4] := tU8; + base[5] := tU16; base[6] := tU32; base[7] := tU64; base[8] := tBool; base[9] := tF32; + base[10] := tReal; base[11] := tInt; + for i := 0 to 11 do Add(base[i]); + if ParamCount >= 1 then begin if Open('lib/Rt.raz') <> '' then Fatal('no file'); Next; Next end; + numObjs := 0; + for k := 1 to 4000 do begin + op := Rnd(14); + case op of + 0, 1, 2: MakeType; + 3, 4: if numObjs <= High(objs) then begin + x := Rnd(8); y := Rnd(20); + if Find(x, names[y]) = nil then begin + z := Rnd(8); n := Rnd(numPool); + o := NewObj(TClass(z), names[y], pool[n]); + z := Rnd(2); o^.exported := z = 0; + z := Rnd(3); o^.module := mods[z]; + Insert(o, x); + objs[numObjs] := o; inc(numObjs); + writeln('I ', x, ' ', NameOf(names[y]), ' ', o^.scope); + end; + end; + 5: begin x := Rnd(8); y := Rnd(20); o := Find(x, names[y]); + write('F ', x, ' ', NameOf(names[y]), ' '); + if o = nil then writeln('-') else writeln(ord(o^.cls), ' ', o^.scope); + end; + 6: begin + x := Rnd(8); y := Rnd(20); + if ScopeDepth < 6 then OpenScope(x); + o := Lookup(names[y]); + write('L ', ScopeDepth, ' ', NameOf(names[y]), ' '); + if o = nil then writeln('-') else writeln(ord(o^.cls), ' ', o^.scope); + z := Rnd(2); + if (ScopeDepth > 1) and (z = 0) then CloseScope; + end; + 7: begin + y := Rnd(20); x := Rnd(9) - 1; z := Rnd(3); curModule := mods[z]; + o := Closest(names[y], x); + write('C ', NameOf(names[y]), ' ', x, ' '); + if o = nil then writeln('-') else writeln(NameOf(o^.name), ' ', o^.scope); + end; + 8: begin + x := Rnd(numPool); z := Rnd(3); curModule := mods[z]; + writeln('T ', TypeName(pool[x])); + end; + 9: begin + x := Rnd(numPool); y := Rnd(numPool); + writeln('S ', ord(Same(pool[x], pool[y])), ' ', ord(Same(pool[x], pool[x]))); + t := NewType(fPtr, 8, 8); t^.base := pool[x]; + o2 := t; t := NewType(fPtr, 8, 8); t^.base := pool[x]; + writeln('S ', ord(Same(o2, t))); + end; + 10: if numObjs > 0 then begin x := Rnd(numObjs); writeln('P ', HexStr(Fingerprint(objs[x]), 16)) end; + 11: begin + x := Rnd(numPool); y := Rnd(1 shl 20); z := Rnd(2); n := Rnd(2); + v := int64(y) * 4096 * z - y * n; + t := pool[x]; + writeln('B ', ord(Fits(v, t)), ' ', ord(IsInt(t)), ' ', ord(IsScalar(t)), ' ', ord(IsAggregate(t)), ' ', + ord(InTwoRegs(t)), ' ', ord(BehindPointer(t)), ' ', AlignUp(y, 1 shl z)); + end; + 12: if (ScopeDepth > 1) and (ScopeDepth < 6) then begin + d := ScopeDepth; SaveScopes(d, saved); + writeln('V ', ScopeDepth, ' ', TopScope); + RestoreScopes(d, saved); + writeln('V ', ScopeDepth, ' ', TopScope); + x := NewScope; writeln('N ', x); + end; + 13: begin x := ScopeDepth; if x > 3 then CutScopes(2); writeln('X ', x, ' ', ScopeDepth) end; + end; + end; + { the universe, and the sizes it made } + for i := 0 to 11 do writeln('U ', ord(base[i]^.form), ' ', base[i]^.size, ' ', ord(base[i]^.signed), ' ', NameOf(base[i]^.obj^.name)); + if ParamCount >= 1 then begin + if ParamStr(1) = 'dup' then begin + o := NewObj(oVar, names[3], tI8); + Insert(o, 100); Insert(o, 100); + end; + if ParamStr(1) = 'deep' then begin + CutScopes(1); + for i := 1 to MaxDepth + 1 do OpenScope(i); + end; + end; +end. diff --git a/src/test/SymDump.raz b/src/test/SymDump.raz new file mode 100644 index 0000000..8807ff7 --- /dev/null +++ b/src/test/SymDump.raz @@ -0,0 +1,225 @@ +(* Builds types and objects by a fixed pseudo-random script, asks of them + what the parser asks of Sym, and prints the answers: src/Sym.raz's + side of a test against the seed's, SymDump.pas, which prints the same. + With the argument dup or deep it ends in the error of a name declared + twice, or of too many scopes. *) +module SymDump; +import Out, Fmt, Files, Heap, Diag, Scan, Sym; + +const + Words: [20][]U8 = ["alpha", "alpho", "beta", "bet", "gamma", "gama", "delta", "Delta", + "eps", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu", "nu", "xi", "omicron", "pi"]; + +var + seed: I64; + names: [20]INT; + mods: [3]^Sym.Module; + base: [12]^Sym.Type; + pool: [300]^Sym.Type; + objs: [300]^Sym.Obj; + classes: [8]Sym.Class; + numPool, numObjs: INT; + +proc rnd(n: INT): INT; +begin + seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; + return INT((seed shr 8) mod I64(n)); +end; + +proc bit(f: BOOL): INT; +begin + if f then return 1; end; + return 0; +end; + +proc nm(i: INT): []U8; +begin + return Scan.nameOf(names[i]); +end; + +(* The result of a call that must succeed *) +proc ok(e: ERROR); +begin + if e # nil then Diag.finish; end; +end; + +proc fields(m: INT; allowVar: BOOL): ^Sym.Obj; +var f, first, last: ^Sym.Obj; j, x, y, z: INT; +begin + first := nil; last := nil; + for j := 1 to m do + x := rnd(20); y := rnd(numPool); + f := Sym.newObj(Sym.oField, names[x], pool[y]); + z := rnd(2); f^.exported := z = 0; + z := rnd(3); f^.isVar := allowVar and (z = 0); + f^.val := j * 8; + if first = nil then first := f; else last^.next := f; end; + last := f; + end; + return first; +end; + +proc add(t: ^Sym.Type); +begin + if numPool < 300 then pool[numPool] := t; INC(numPool); end; +end; + +proc makeType; +var t: ^Sym.Type; r, m, x: INT; f: ^Sym.Obj; +begin + r := rnd(11); + match r of + | 0: t := Sym.newType(Sym.fPtr, 8, 8); + | 1: t := Sym.newType(Sym.fArray, 0, 1); + | 2: t := Sym.newType(Sym.fSlice, 16, 8); + | 3: t := Sym.newType(Sym.fRecord, 0, 8); + | 4: t := Sym.newType(Sym.fProc, 8, 8); + | 5: t := Sym.newType(Sym.fSet, 8, 8); + | 6: t := Sym.newType(Sym.fVariant, 16, 8); + | 7: t := Sym.newType(Sym.fEnum, 1, 1); + | 8: t := Sym.newType(Sym.fRecord, 16, 8); + | 9: t := Sym.newType(Sym.fProc, 8, 8); + | else: t := Sym.newType(Sym.fPtr, 8, 8); + end; + x := rnd(numPool); t^.base := pool[x]; + t^.len := rnd(5); + x := rnd(4); t^.vol := x = 0; + x := rnd(4); t^.variadic := (t^.form = Sym.fProc) and (x = 0); + x := rnd(2); t^.tuple := (t^.form = Sym.fRecord) and (x = 0); + if (t^.form = Sym.fRecord) or (t^.form = Sym.fProc) or (t^.form = Sym.fVariant) then + m := rnd(4); + t^.fields := fields(m, t^.form = Sym.fProc); + t^.len := m; + if t^.form = Sym.fRecord then t^.base := nil; end; + x := rnd(2); + if (t^.form = Sym.fProc) and (x = 0) then t^.base := nil; end; + if t^.form = Sym.fVariant then + f := t^.fields; + while f # nil do + f^.cls := Sym.oCase; + x := rnd(3); f^.fields := fields(x, false); + f := f^.next; + end; + end; + end; + x := rnd(3); + if x = 0 then + x := rnd(20); t^.obj := Sym.newObj(Sym.oType, names[x], t); + x := rnd(3); t^.obj^.home := mods[x]; + end; + add(t); +end; + +proc main*; +var + i, k, op, x, y, z, n, d: INT; t, o2: ^Sym.Type; o: ^Sym.Obj; v: I64; + saved: [Sym.MaxDepth]INT; arg: []U8; +begin + seed := 11; + classes := [Sym.oConst, Sym.oType, Sym.oVar, Sym.oProc, Sym.oModule, Sym.oField, Sym.oCase, Sym.oBuiltin]; + for i := 0 to 19 do names[i] := Scan.intern(ADR(Words[i][0]), LEN(Words[i])); end; + for i := 0 to 2 do + NEW(mods[i], Heap.heap); + mods[i]^.sname := names[i * 5]; + end; + Sym.setCurModule(mods[0]); + base[0] := Sym.tI8; base[1] := Sym.tI16; base[2] := Sym.tI32; base[3] := Sym.tI64; base[4] := Sym.tU8; + base[5] := Sym.tU16; base[6] := Sym.tU32; base[7] := Sym.tU64; base[8] := Sym.tBool; base[9] := Sym.tF32; + base[10] := Sym.tReal; base[11] := Sym.tInt; + for i := 0 to 11 do add(base[i]); end; + arg := ""; + if ARGC > 1 then arg := Files.arg(1); end; + if LEN(arg) > 0 then + if LEN(Scan.open("lib/Rt.raz")) # 0 then Diag.fatal("no file"); end; + Scan.next; Scan.next; + end; + numObjs := 0; + for k := 1 to 4000 do + op := rnd(14); + match op of + | 0, 1, 2: makeType; + | 3, 4: + if numObjs < 300 then + x := rnd(8); y := rnd(20); + if Sym.find(x, names[y]) = nil then + z := rnd(8); n := rnd(numPool); + o := Sym.newObj(classes[z], names[y], pool[n]); + z := rnd(2); o^.exported := z = 0; + z := rnd(3); o^.home := mods[z]; + ok(Sym.insert(o, x)); + objs[numObjs] := o; INC(numObjs); + Fmt.print("I {} {} {}\n", [Fmt.int(x), Fmt.str(nm(y)), Fmt.int(o^.scope)]); + end; + end; + | 5: + x := rnd(8); y := rnd(20); o := Sym.find(x, names[y]); + Fmt.print("F {} {} ", [Fmt.int(x), Fmt.str(nm(y))]); + if o = nil then Out.str("-\n"); + else Fmt.print("{} {}\n", [Fmt.int(INT(o^.cls)), Fmt.int(o^.scope)]); end; + | 6: + x := rnd(8); y := rnd(20); + if Sym.scopeDepth() < 6 then ok(Sym.openScope(x)); end; + o := Sym.lookup(names[y]); + Fmt.print("L {} {} ", [Fmt.int(Sym.scopeDepth()), Fmt.str(nm(y))]); + if o = nil then Out.str("-\n"); + else Fmt.print("{} {}\n", [Fmt.int(INT(o^.cls)), Fmt.int(o^.scope)]); end; + z := rnd(2); + if (Sym.scopeDepth() > 1) and (z = 0) then Sym.closeScope; end; + | 7: + y := rnd(20); x := rnd(9) - 1; z := rnd(3); Sym.setCurModule(mods[z]); + o := Sym.closest(names[y], x); + Fmt.print("C {} {} ", [Fmt.str(nm(y)), Fmt.int(x)]); + if o = nil then Out.str("-\n"); + else Fmt.print("{} {}\n", [Fmt.str(Scan.nameOf(o^.name)), Fmt.int(o^.scope)]); end; + | 8: + x := rnd(numPool); z := rnd(3); Sym.setCurModule(mods[z]); + Fmt.print("T {}\n", [Fmt.str(Sym.typeName(pool[x]))]); + | 9: + x := rnd(numPool); y := rnd(numPool); + Fmt.print("S {} {}\n", [Fmt.int(bit(Sym.same(pool[x], pool[y]))), Fmt.int(bit(Sym.same(pool[x], pool[x])))]); + t := Sym.newType(Sym.fPtr, 8, 8); t^.base := pool[x]; + o2 := t; t := Sym.newType(Sym.fPtr, 8, 8); t^.base := pool[x]; + Fmt.print("S {}\n", [Fmt.int(bit(Sym.same(o2, t)))]); + | 10: + if numObjs > 0 then + x := rnd(numObjs); + Out.str("P "); Out.hex(Sym.fingerprint(objs[x]), 16); Out.ln; + end; + | 11: + x := rnd(numPool); y := rnd(1 shl 20); z := rnd(2); n := rnd(2); + v := I64(y) * 4096 * I64(z) - I64(y) * I64(n); + t := pool[x]; + Fmt.print("B {} {} {} {} {} {} {}\n", [Fmt.int(bit(Sym.fits(v, t))), Fmt.int(bit(Sym.isInt(t))), + Fmt.int(bit(Sym.isScalar(t))), Fmt.int(bit(Sym.isAggregate(t))), Fmt.int(bit(Sym.inTwoRegs(t))), + Fmt.int(bit(Sym.behindPointer(t))), Fmt.int(Sym.alignUp(y, 1 shl z))]); + | 12: + if (Sym.scopeDepth() > 1) and (Sym.scopeDepth() < 6) then + d := Sym.saveScopes(saved); + Fmt.print("V {} {}\n", [Fmt.int(Sym.scopeDepth()), Fmt.int(Sym.topScope())]); + Sym.restoreScopes(d, saved); + Fmt.print("V {} {}\n", [Fmt.int(Sym.scopeDepth()), Fmt.int(Sym.topScope())]); + x := Sym.newScope(); + Fmt.print("N {}\n", [Fmt.int(x)]); + end; + | else: + x := Sym.scopeDepth(); + if x > 3 then Sym.cutScopes(2); end; + Fmt.print("X {} {}\n", [Fmt.int(x), Fmt.int(Sym.scopeDepth())]); + end; + end; + for i := 0 to 11 do + Fmt.print("U {} {} {} {}\n", [Fmt.int(INT(base[i]^.form)), Fmt.int(base[i]^.size), + Fmt.int(bit(base[i]^.signed)), Fmt.str(Scan.nameOf(base[i]^.obj^.name))]); + end; + if arg = "dup" then + o := Sym.newObj(Sym.oVar, names[3], Sym.tI8); + ok(Sym.insert(o, 100)); + ok(Sym.insert(o, 100)); + end; + if arg = "deep" then + Sym.cutScopes(1); + for i := 1 to Sym.MaxDepth + 1 do ok(Sym.openScope(i)); end; + end; +end; + +end SymDump. diff --git a/src/test/X64Dump.pas b/src/test/X64Dump.pas new file mode 100644 index 0000000..3966839 --- /dev/null +++ b/src/test/X64Dump.pas @@ -0,0 +1,160 @@ +{ Writes every instruction the encoder makes, with operands drawn by a + fixed pseudo-random script, then prints the bytes, the fixups and the + listing (raz -S) of what it made: the seed's side of a test of + src/X64.raz, whose X64Dump.raz does the same and prints the same. } +program x64dump; +{$mode objfpc}{$H-} +uses diag, scan, chunk, x64; +var + seed: int64; + i, k, op, a, b, c, d, lab1, lab2: longint; + m: TMem; + path: string; + +function Rnd(n: longint): longint; +begin + seed := (seed * 1103515245 + 12345) and $7FFFFFFF; + Rnd := (seed shr 8) mod n; +end; + +{ a register, with the stack and base pointers and the high ones often enough } +function Reg: longint; +begin + Reg := Rnd(16); +end; + +{ a size of 1, 2, 4 or 8 bytes } +function Size: longint; +begin + Size := 1 shl Rnd(4); +end; + +{ a value that fits size bytes, of 8 as 32 bits } +function Imm(sz: longint): longint; +var x: longint; +begin + x := Rnd(1 shl 30); + case Rnd(3) of + 0: Imm := x mod 100 - 50; + 1: Imm := x - (1 shl 29); + else Imm := x mod 20000 - 10000; + end; + if sz = 1 then Imm := Imm mod 128 + else if sz = 2 then Imm := Imm mod 32768; +end; + +function RandMem: TMem; +var kind, base, idx, sc, disp, x: longint; +begin + kind := Rnd(6); + base := Reg; idx := Reg; sc := 1 shl Rnd(4); x := Rnd(5); + case x of + 0: disp := 0; + 1: disp := Rnd(250) - 125; + 2: disp := Rnd(1 shl 20) - (1 shl 19); + 3: disp := 127 + Rnd(3) - 1; + else disp := -128 + Rnd(3) - 1; + end; + case kind of + 0, 1: RandMem := Mem(base, disp); + 2: RandMem := MemRip(Rnd(5), disp); + 3, 4: RandMem := MemIdx(base, idx, sc, disp); + else RandMem := Mem(base, 0); + end; +end; + +begin + seed := 3; + path := 'lib/Rt.raz'; + if Open(path) <> '' then Fatal('no file'); + listing := true; + for i := 0 to 4 do NewChunk(secText, i - 1, i); + curFile := Intern(@path[1], length(path)); + BeginChunk(0); + lab1 := NoLabel; lab2 := NoLabel; + for k := 1 to 3000 do begin + if k mod 7 = 0 then begin a := Rnd(300); b := Rnd(60); NoteLine(1 + a, b) end; + op := Rnd(50); + case op of + 0: begin a := Reg; b := Reg; MovRR(a, b) end; + 1: begin + a := Reg; b := Rnd(6); c := Rnd(1 shl 30); + case b of + 0: MovRI(a, 0); + 1: MovRI(a, c); + 2: MovRI(a, -c); + 3: MovRI(a, int64(c) * 8 + 5); + 4: MovRI(a, int64(c) * 4096 * 4096 * 9 - 7); + else MovRI(a, 0); + end; + end; + 2: begin a := Rnd(8); m := RandMem; b := Size; c := Imm(b); AluMI(a, m, c, b) end; + 3: begin m := RandMem; b := Size; c := Imm(b); StoreI(m, c, b) end; + 4: begin a := Reg; m := RandMem; b := Size; c := Rnd(2); Load(a, m, b, c = 0) end; + 5: begin m := RandMem; a := Reg; b := Size; Store(m, a, b) end; + 6: begin a := Reg; m := RandMem; Lea(a, m) end; + 7: begin a := Rnd(8); b := Reg; c := Reg; Alu(a, b, c) end; + 8: begin a := Rnd(8); b := Reg; c := Imm(8); AluI(a, b, c) end; + 9: begin a := Rnd(8); b := Reg; m := RandMem; AluM(a, b, m) end; + 10: begin a := Reg; b := Reg; Imul(a, b) end; + 11: begin a := Reg; c := Imm(8); ImulI(a, c) end; + 12: begin a := Rnd(3); b := Reg; if a = 0 then a := shShl else if a = 1 then a := shShr else a := shSar; Shift(a, b) end; + 13: begin a := Rnd(3); b := Reg; c := Rnd(64); if a = 0 then a := shShl else if a = 1 then a := shShr else a := shSar; ShiftI(a, b, c) end; + 14: begin a := Rnd(4); b := Reg; if a < 2 then a := a + 2 else a := a + 4; Unary(a, b) end; + 15: Cqo; + 16: begin a := Reg; b := 1 shl Rnd(3); c := Rnd(2); Extend(a, b, c = 0) end; + 17: begin a := Rnd(16); b := Reg; SetCC(a, b) end; + 18: begin a := Reg; b := Reg; TestRR(a, b) end; + 19: begin a := Reg; Push(a) end; + 20: begin a := Reg; Pop(a) end; + 21: begin a := Rnd(5); CallChunk(a) end; + 22: begin a := Rnd(1000); CallBack(a) end; + 23: begin a := Reg; CallR(a) end; + 24: begin a := Reg; JmpR(a) end; + 25: begin m := RandMem; CallM(m) end; + 26: begin a := Rnd(5); case a of 0: Ret; 1: Leave; 2: Syscall; 3: Mfence; else Ud2 end end; + 27: begin a := 8 shl Rnd(3); Align(a) end; + 28: begin a := Rnd(5); case a of 0: RepMovsb; 1: Std; 2: Cld; 3: RepStosb; else RepeCmpsb end end; + 29: begin m := RandMem; a := Reg; LockCmpxchg(m, a) end; + 30: begin m := RandMem; a := Reg; Xchg(m, a) end; + 31: begin m := RandMem; a := Reg; LockXadd(m, a) end; + 32: begin a := Reg; b := Reg; MovqXR(a, b) end; + 33: begin a := Reg; b := Reg; MovqRX(a, b) end; + 34: begin a := Reg; b := Reg; MovX(a, b) end; + 35: begin a := Reg; m := RandMem; b := Rnd(2); MovsXM(a, m, b = 0) end; + 36: begin m := RandMem; a := Reg; b := Rnd(2); MovsMX(m, a, b = 0) end; + 37: begin + d := Rnd(5); a := Reg; b := Reg; c := Rnd(2); + case d of 0: d := $58; 1: d := $59; 2: d := $5C; 3: d := $5E; else d := $5A end; + Sse(d, a, b, c = 0); + end; + 38: begin + d := Rnd(5); a := Reg; m := RandMem; c := Rnd(2); + case d of 0: d := $58; 1: d := $59; 2: d := $5C; 3: d := $5E; else d := $5A end; + SseM(d, a, m, c = 0); + end; + 39: begin a := Reg; b := Reg; c := Rnd(2); Ucomis(a, b, c = 0) end; + 40: begin a := Reg; b := Reg; c := Rnd(2); Cvtsi2s(a, b, c = 0) end; + 41: begin a := Reg; b := Reg; c := Rnd(2); Cvtts2si(a, b, c = 0) end; + 42: begin a := Reg; b := Rnd(64); Btc(a, b) end; + 43: begin + a := Rnd(16); b := Rnd(2); + if b = 0 then Jmp(lab1) else Jcc(a, lab2); + end; + 44: begin a := Rnd(16); b := Rnd(2); c := pc - Rnd(200); if b = 0 then JmpBack(c) else JccBack(a, c) end; + 45: if Rnd(3) = 0 then begin FixLink(lab1); lab1 := NoLabel end + else begin FixLinkTo(lab2, pc - 20); lab2 := NoLabel end; + 46: begin Jmp(lab1); DropJumpTo(lab1) end; + 47: begin a := JoinLinks(lab1, lab2); lab1 := a; lab2 := NoLabel end; + else begin a := Rnd(256); Put1(a) end; + end; + end; + FixLink(lab1); FixLink(lab2); + EndChunk(0); + chunks^[0].live := true; + writeln('pc ', pc, ' fixups ', numFixups, ' lines ', numLines, ' said ', SaidCount); + for i := 0 to pc - 1 do write(HexStr(code^[i], 2)); + writeln; + for i := 0 to numFixups - 1 do writeln('F ', fixups^[i].at, ' ', fixups^[i].chunk, ' ', fixups^[i].addend); + List(-1); +end. diff --git a/src/test/X64Dump.raz b/src/test/X64Dump.raz new file mode 100644 index 0000000..7494488 --- /dev/null +++ b/src/test/X64Dump.raz @@ -0,0 +1,208 @@ +(* Writes every instruction the encoder makes, with operands drawn by a + fixed pseudo-random script, then prints the bytes, the fixups and the + listing (raz -S) of what it made: src/X64.raz's side of a test + against the seed's, X64Dump.pas, which prints the same. *) +module X64Dump; +import Out, Fmt, Diag, Scan, Chunk, X64; + +var seed: I64; + +proc rnd(n: INT): INT; +begin + seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; + return INT((seed shr 8) mod I64(n)); +end; + +(* a register *) +proc reg: INT; +begin + return rnd(16); +end; + +(* a size of 1, 2, 4 or 8 bytes *) +proc size: INT; +begin + return 1 shl rnd(4); +end; + +(* a value that fits sz bytes, of 8 as 32 bits *) +proc imm(sz: INT): INT; +var x, r: INT; +begin + x := rnd(1 shl 30); + match rnd(3) of + | 0: r := x mod 100 - 50; + | 1: r := x - (1 shl 29); + | else: r := x mod 20000 - 10000; + end; + if sz = 1 then + r := r mod 128; + elsif sz = 2 then + r := r mod 32768; + end; + return r; +end; + +proc randMem: X64.Mem; +var kind, base, idx, sc, disp, x: INT; +begin + kind := rnd(6); + base := reg(); idx := reg(); sc := 1 shl rnd(4); x := rnd(5); + match x of + | 0: disp := 0; + | 1: disp := rnd(250) - 125; + | 2: disp := rnd(1 shl 20) - (1 shl 19); + | 3: disp := 127 + rnd(3) - 1; + | else: disp := -128 + rnd(3) - 1; + end; + match kind of + | 0, 1: return X64.mem(base, disp); + | 2: return X64.memRip(rnd(5), disp); + | 3, 4: return X64.memIdx(base, idx, sc, disp); + | else: return X64.mem(base, 0); + end; +end; + +proc main*; +var + i, k, op, a, b, c, d, lab1, lab2: INT; m: X64.Mem; path: []U8; +begin + seed := 3; + path := "lib/Rt.raz"; + if LEN(Scan.open(path)) # 0 then Diag.fatal("no file"); end; + X64.setListing(true); + for i := 0 to 4 do c := Chunk.newChunk(Chunk.secText, i - 1, i); end; + Chunk.setCurFile(Scan.intern(ADR(path[0]), LEN(path))); + Chunk.beginChunk(0); + lab1 := X64.NoLabel; lab2 := X64.NoLabel; + for k := 1 to 3000 do + if k mod 7 = 0 then a := rnd(300); b := rnd(60); Chunk.noteLine(1 + a, b); end; + op := rnd(50); + match op of + | 0: a := reg(); b := reg(); X64.movRR(a, b); + | 1: + a := reg(); b := rnd(6); c := rnd(1 shl 30); + match b of + | 0: X64.movRI(a, 0); + | 1: X64.movRI(a, c); + | 2: X64.movRI(a, -c); + | 3: X64.movRI(a, I64(c) * 8 + 5); + | 4: X64.movRI(a, I64(c) * 4096 * 4096 * 9 - 7); + | else: X64.movRI(a, 0); + end; + | 2: a := rnd(8); m := randMem(); b := size(); c := imm(b); X64.aluMI(a, m, c, b); + | 3: m := randMem(); b := size(); c := imm(b); X64.storeI(m, c, b); + | 4: a := reg(); m := randMem(); b := size(); c := rnd(2); X64.load(a, m, b, c = 0); + | 5: m := randMem(); a := reg(); b := size(); X64.store(m, a, b); + | 6: a := reg(); m := randMem(); X64.lea(a, m); + | 7: a := rnd(8); b := reg(); c := reg(); X64.alu(a, b, c); + | 8: a := rnd(8); b := reg(); c := imm(8); X64.aluI(a, b, c); + | 9: a := rnd(8); b := reg(); m := randMem(); X64.aluM(a, b, m); + | 10: a := reg(); b := reg(); X64.imul(a, b); + | 11: a := reg(); c := imm(8); X64.imulI(a, c); + | 12: + a := rnd(3); b := reg(); + if a = 0 then a := X64.shShl; elsif a = 1 then a := X64.shShr; else a := X64.shSar; end; + X64.shift(a, b); + | 13: + a := rnd(3); b := reg(); c := rnd(64); + if a = 0 then a := X64.shShl; elsif a = 1 then a := X64.shShr; else a := X64.shSar; end; + X64.shiftI(a, b, c); + | 14: + a := rnd(4); b := reg(); + if a < 2 then a := a + 2; else a := a + 4; end; + X64.unary(a, b); + | 15: X64.cqo; + | 16: a := reg(); b := 1 shl rnd(3); c := rnd(2); X64.extend(a, b, c = 0); + | 17: a := rnd(16); b := reg(); X64.setCC(a, b); + | 18: a := reg(); b := reg(); X64.testRR(a, b); + | 19: a := reg(); X64.push(a); + | 20: a := reg(); X64.pop(a); + | 21: a := rnd(5); X64.callChunk(a); + | 22: a := rnd(1000); X64.callBack(a); + | 23: a := reg(); X64.callR(a); + | 24: a := reg(); X64.jmpR(a); + | 25: m := randMem(); X64.callM(m); + | 26: + a := rnd(5); + match a of + | 0: X64.ret; + | 1: X64.leave; + | 2: X64.syscall; + | 3: X64.mfence; + | else: X64.ud2; + end; + | 27: a := 8 shl rnd(3); X64.align(a); + | 28: + a := rnd(5); + match a of + | 0: X64.repMovsb; + | 1: X64.std; + | 2: X64.cld; + | 3: X64.repStosb; + | else: X64.repeCmpsb; + end; + | 29: m := randMem(); a := reg(); X64.lockCmpxchg(m, a); + | 30: m := randMem(); a := reg(); X64.xchg(m, a); + | 31: m := randMem(); a := reg(); X64.lockXadd(m, a); + | 32: a := reg(); b := reg(); X64.movqXR(a, b); + | 33: a := reg(); b := reg(); X64.movqRX(a, b); + | 34: a := reg(); b := reg(); X64.movX(a, b); + | 35: a := reg(); m := randMem(); b := rnd(2); X64.movsXM(a, m, b = 0); + | 36: m := randMem(); a := reg(); b := rnd(2); X64.movsMX(m, a, b = 0); + | 37: + d := rnd(5); a := reg(); b := reg(); c := rnd(2); + match d of + | 0: d := 58H; + | 1: d := 59H; + | 2: d := 5CH; + | 3: d := 5EH; + | else: d := 5AH; + end; + X64.sse(d, a, b, c = 0); + | 38: + d := rnd(5); a := reg(); m := randMem(); c := rnd(2); + match d of + | 0: d := 58H; + | 1: d := 59H; + | 2: d := 5CH; + | 3: d := 5EH; + | else: d := 5AH; + end; + X64.sseM(d, a, m, c = 0); + | 39: a := reg(); b := reg(); c := rnd(2); X64.ucomis(a, b, c = 0); + | 40: a := reg(); b := reg(); c := rnd(2); X64.cvtsi2s(a, b, c = 0); + | 41: a := reg(); b := reg(); c := rnd(2); X64.cvtts2si(a, b, c = 0); + | 42: a := reg(); b := rnd(64); X64.btc(a, b); + | 43: + a := rnd(16); b := rnd(2); + if b = 0 then X64.jmp(lab1); else X64.jcc(a, lab2); end; + | 44: + a := rnd(16); b := rnd(2); c := Chunk.pc - rnd(200); + if b = 0 then X64.jmpBack(c); else X64.jccBack(a, c); end; + | 45: + a := rnd(3); + if a = 0 then + X64.fixLink(lab1); lab1 := X64.NoLabel; + else + X64.fixLinkTo(lab2, Chunk.pc - 20); lab2 := X64.NoLabel; + end; + | 46: X64.jmp(lab1); X64.dropJumpTo(lab1); + | 47: a := X64.joinLinks(lab1, lab2); lab1 := a; lab2 := X64.NoLabel; + | else: a := rnd(256); Chunk.put1(a); + end; + end; + X64.fixLink(lab1); X64.fixLink(lab2); + Chunk.endChunk(0); + Chunk.setLive(0); + Fmt.print("pc {} fixups {} lines {} said {}\n", [Fmt.int(Chunk.pc), Fmt.int(Chunk.numFixups), + Fmt.int(Chunk.numLines), Fmt.int(X64.saidCount())]); + for i := 0 to Chunk.pc - 1 do Out.hex(U64(Chunk.text[i]), 2); end; + Out.ln; + for i := 0 to Chunk.numFixups - 1 do + Fmt.print("F {} {} {}\n", [Fmt.int(Chunk.fixups[i].at), Fmt.int(Chunk.fixups[i].chunk), Fmt.int(Chunk.fixups[i].addend)]); + end; + X64.list(-1); +end; + +end X64Dump. diff --git a/src/test/genasm.py b/src/test/genasm.py new file mode 100644 index 0000000..5749c55 --- /dev/null +++ b/src/test/genasm.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +"""Writes the files the assembler of X64 is tested on, into the directory +given: valid.raz, a long run of instructions of every kind the assembler +knows, and one small file for each error it reports. Each ends in `end`, +as a code procedure's body does. Fixed seed: the same files each run.""" +import random, sys, os + +random.seed(7) +out = sys.argv[1] +os.makedirs(out, exist_ok=True) + +R64 = "rax rcx rdx rbx rsp rbp rsi rdi r8 r9 r10 r11 r12 r13 r14 r15".split() +R32 = "eax ecx edx ebx esp ebp esi edi r8d r9d r10d r11d r12d r13d r14d r15d".split() +R16 = "ax cx dx bx sp bp si di r8w r9w r10w r11w r12w r13w r14w r15w".split() +R8 = "al cl dl bl spl bpl sil dil r8b r9b r10b r11b r12b r13b r14b r15b".split() +BY = {8: R64, 4: R32, 2: R16, 1: R8} +PRE = {8: "qword ", 4: "dword ", 2: "word ", 1: "byte "} +XM = ["xmm%d" % i for i in range(16)] +CC = "o no b ae e ne be a s ns p np l ge le g c nae nc nb z nz na nbe nge nl ng nle".split() + + +def reg(size=8): + return random.choice(BY[size]) + + +def mem(size=0): + k = random.randrange(8) + b = random.choice(R64) + i = random.choice([r for r in R64 if r != "rsp"]) + d = random.choice([0, 8, -8, 127, -128, 128, 4096, -4096, 100000]) + s = random.choice([1, 2, 4, 8]) + p = PRE[size] if size else "" + if k == 0: + t = "[%s]" % b + elif k == 1: + t = "[%s + %d]" % (b, abs(d)) if d >= 0 else "[%s - %d]" % (b, -d) + elif k == 2: + t = "[%s + %s * %d]" % (b, i, s) + elif k == 3: + t = "[%s + %s * %d + %d]" % (b, i, s, abs(d)) if d >= 0 else "[%s + %s * %d - %d]" % (b, i, s, -d) + elif k == 4: + t = "[%s + %s]" % (b, i) + elif k == 5: + t = "[%s + 0]" % b + elif k == 6: + t = "[rsp + %d]" % abs(d) + else: + t = "[%s - %d]" % (b, abs(d) + 1) + return p + t + + +def imm(size): + if size == 1: + return str(random.choice([0, 1, -1, 127, 255, -128, 77])) + if size == 2: + return str(random.choice([0, 1, -1, 300, 32767, -32768, 255, 65535])) + return str(random.choice([0, 1, -1, 127, 128, -128, -129, 100000, -100000, 2147483647, -2147483648, 4294967295])) + + +def size(): + return random.choice([1, 2, 4, 8]) + + +lines = [] + + +def emit(s): + lines.append(" " + s + ";") + + +for n in range(900): + k = random.randrange(40) + sz = size() + if k < 6: + op = random.choice("add or adc sbb and sub xor cmp".split()) + f = random.randrange(5) + if f == 0: + emit("%s %s, %s" % (op, reg(sz), reg(sz))) + elif f == 1: + emit("%s %s, %s" % (op, reg(sz), mem(sz if random.random() < .5 else 0))) + elif f == 2: + emit("%s %s, %s" % (op, mem(sz if random.random() < .5 else 0), reg(sz))) + elif f == 3: + emit("%s %s, %s" % (op, reg(sz), imm(sz))) + else: + emit("%s %s, %s" % (op, mem(sz), imm(sz))) + elif k < 10: + f = random.randrange(5) + if f == 0: + emit("mov %s, %s" % (reg(sz), reg(sz))) + elif f == 1: + emit("mov %s, %s" % (reg(sz), mem())) + elif f == 2: + emit("mov %s, %s" % (mem(), reg(sz))) + elif f == 3: + v = random.choice([0, 5, -5, 2147483647, 4294967295, 4294967296, -2147483649, 123456789012345]) + emit("mov %s, %d" % (reg(8 if sz >= 4 else sz) if sz >= 4 else reg(sz), v if sz == 8 else (v % 65536 if sz == 2 else v % 256 if sz == 1 else v % 4294967296))) + else: + emit("mov %s, %s" % (mem(sz), imm(sz))) + elif k == 10: + emit("test %s, %s" % (reg(sz), random.choice([reg(sz), imm(sz) if sz != 1 else "1"]))) + elif k == 11: + emit("xchg %s, %s" % (random.choice([reg(sz), mem()]), reg(sz))) + elif k == 12: + emit("%slock %s %s, %s" % ("", random.choice(["cmpxchg", "xadd"]), mem(), reg(sz))) + elif k == 13: + emit("lea %s, %s" % (reg(random.choice([2, 4, 8])), mem())) + elif k == 14: + op = random.choice(["movzx", "movsx"]) + emit("%s %s, %s" % (op, reg(random.choice([2, 4, 8])), random.choice([mem(random.choice([1, 2])), reg(random.choice([1, 2]))]))) + elif k == 15: + emit("movsxd %s, %s" % (reg(8), random.choice([mem(4), reg(4)]))) + elif k == 16: + emit("%s %s" % (random.choice("not neg mul imul div idiv inc dec".split()), random.choice([reg(sz), mem(sz)]))) + elif k == 17: + emit("imul %s" % ", ".join([reg(sz if sz > 1 else 4), random.choice([reg(sz if sz > 1 else 4)] * 1 + [mem()])] + ([imm(sz if sz > 1 else 4)] if random.random() < .4 else [])).replace("%", "%")) + elif k == 18: + op = random.choice("rol ror rcl rcr shl shr sal sar".split()) + emit("%s %s, %s" % (op, random.choice([reg(sz), mem(sz)]), random.choice([str(random.randrange(64)), "cl"]))) + elif k == 19: + emit("%s %s" % (random.choice(["push", "pop"]), reg(8))) + elif k == 20: + op = random.choice(["call", "jmp"]) + emit("%s %s" % (op, random.choice([reg(8), mem()]) if op == "call" else mem())) + elif k == 21: + emit("set%s %s" % (random.choice(CC), random.choice([reg(1), mem(1)]))) + elif k == 22: + emit("cmov%s %s, %s" % (random.choice(CC), reg(random.choice([2, 4, 8])), random.choice([reg(8), mem()]))) + elif k == 23: + op = random.choice("sqrt add mul sub min div max".split()) + random.choice(["sd", "ss"]) + emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()]))) + elif k == 24: + op = random.choice("punpcklbw punpcklwd pcmpeqb pand pandn por pxor paddb psubb".split()) + emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()]))) + elif k == 25: + emit("pshufd %s, %s, %d" % (random.choice(XM), random.choice([random.choice(XM), mem()]), random.randrange(256))) + elif k == 26: + op = random.choice(["movdqu", "movdqa"]) + if random.random() < .5: + emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()]))) + else: + emit("%s %s, %s" % (op, mem(), random.choice(XM))) + elif k == 27: + emit("pmovmskb %s, %s" % (reg(4), random.choice(XM))) + elif k == 28: + emit("%s %s, %s" % (random.choice("bsf bsr tzcnt lzcnt popcnt".split()), reg(random.choice([4, 8])), random.choice([reg(8), mem()]))) + elif k == 29: + op = random.choice(["movsd", "movss"]) + if random.random() < .5: + emit("%s %s, %s" % (op, random.choice(XM), random.choice([random.choice(XM), mem()]))) + else: + emit("%s %s, %s" % (op, mem(), random.choice(XM))) + elif k == 30: + op = random.choice(["movq", "movd"]) + if random.random() < .5: + emit("%s %s, %s" % (op, random.choice(XM), random.choice([reg(8), mem()]))) + else: + emit("%s %s, %s" % (op, random.choice([reg(8), mem()]), random.choice(XM))) + elif k == 31: + emit("%s %s, %s" % (random.choice(["ucomisd", "ucomiss"]), random.choice(XM), random.choice([random.choice(XM), mem()]))) + elif k == 32: + emit("%s %s, %s" % (random.choice(["cvtsi2sd", "cvtsi2ss"]), random.choice(XM), random.choice([reg(random.choice([4, 8])), mem(random.choice([4, 8]))]))) + elif k == 33: + emit("%s %s, %s" % (random.choice(["cvttsd2si", "cvttss2si"]), reg(random.choice([4, 8])), random.choice([random.choice(XM), mem()]))) + elif k == 34: + emit("%s %s, %s" % (random.choice(["cvtsd2ss", "cvtss2sd"]), random.choice(XM), random.choice([random.choice(XM), mem()]))) + elif k == 35: + emit(random.choice("ret leave syscall cpuid rdtsc pause nop ud2 int3 hlt cqo cdq mfence lfence sfence".split())) + elif k == 36: + emit("db " + ", ".join(str(random.choice([0, 1, 255, 128, 77, -1, -128])) for _ in range(random.randrange(1, 6)))) + elif k == 37: + lines.append(" L%d:" % n) + lines.append(" add rax, 1;") + lines.append(" j%s L%d;" % (random.choice(CC), n)) + lines.append(" jmp L%d;" % n) + elif k == 38: + lines.append(" jmp F%d;" % n) + lines.append(" nop;") + lines.append(" j%s F%d;" % (random.choice(CC), n)) + lines.append(" F%d:" % n) + else: + emit("lock add %s, %s" % (mem(sz), reg(sz))) + +open(os.path.join(out, "valid.raz"), "w").write("\n".join(lines) + "\n end\n") + +errors = { + "empty": "", + "badop": "foo rax;", + "noinsn": "42;", + "nosemi": "nop", + "undefined": "jmp nowhere;", + "twice": "a: nop; a: nop;", + "toomany": "add rax, rbx, rcx, rdx;", + "movimm": "mov 1, 2;", + "movmm": "mov [rax], [rbx];", + "addimm": "add 1, rax;", + "pushmem": "push [rax];", + "pushsmall": "push eax;", + "badmem": "mov rax, [rsi * 4];", + "badscale": "mov rax, [rsi + rdi * 3];", + "nomem": "mov rax, [];", + "unclosed": "mov rax, [rbx;", + "shiftcl": "shl rax, dl;", + "shiftimm": "shl 3, 1;", + "lea": "lea rax, rbx;", + "movzx": "movzx rax, rbx;", + "movzx4": "movzx rax, dword [rbx];", + "setsize": "sete rax;", + "cmovimm": "cmove rax, 5;", + "sse": "addsd rax, xmm1;", + "sse1": "addsd xmm1;", + "pshufd": "pshufd xmm1, xmm2;", + "pand3": "pand xmm1, xmm2, 3;", + "movdq": "movdqu rax, xmm1;", + "pmov": "pmovmskb xmm1, rax;", + "bits": "popcnt ax, bx;", + "movsd": "movsd rax, xmm1;", + "movq": "movq rax, rbx;", + "ucomi": "ucomisd rax, xmm1;", + "cvtsi": "cvtsi2sd rax, xmm1;", + "cvtt": "cvttsd2si xmm1, xmm2;", + "cvtss": "cvtss2sd rax, xmm1;", + "plainops": "ret rax;", + "dbrange": "db 256;", + "dbneg": "db -129;", + "imul1": "imul rax, 5;", + "imulmem": "imul [rax], rbx;", + "unary2": "not rax, rbx;", + "unaryimm": "neg 5;", + "inc": "inc 5;", + "xchgimm": "xchg rax, 5;", + "cmpxchg": "cmpxchg rax, 5;", + "calli": "call 5;", + "jmpimm": "jmp 5;", + "labels65": "".join("l%d: nop; " % i for i in range(65)), + "xmm16": "addsd xmm16, xmm1;", + "noend": None, +} +for name, body in errors.items(): + if body is None: + text = " nop;\n" + else: + text = " " + body + "\n end\n" + open(os.path.join(out, "err_%s.raz" % name), "w").write(text) diff --git a/src/test/genlex.py b/src/test/genlex.py new file mode 100644 index 0000000..f2607ea --- /dev/null +++ b/src/test/genlex.py @@ -0,0 +1,29 @@ +# Writes into the directory given a file for each message the scanner +# makes, with the places diag shows them in: after a tab, in a long +# line, after characters of several bytes, in a CRLF file. +import sys +d = sys.argv[1] +cases = { + "slip1": "x == y;\n", "slip2": "a && b;\n", "slip3": "a || b;\n", "slip4": "a != b;\n", "slip5": "!a;\n", + "str": "x := \"abc\n", "chr": "x := 'a\n", "chr2": "x := 'ab';\n", "chr3": "x := '';\n", + "esc": "x := \"\\q\";\n", "esc2": "x := 'a\\x41';\n", "esc3": "x := \"\\x4\";\n", + "esc4": "x := \"\\u41\";\n", "esc5": "x := \"\\u{110000}\";\n", "esc6": "x := \"\\u{D800}\";\n", + "esc7": "x := \"\\u{1234567}\";\n", "esc8": "x := \"\\u{}\";\n", "esc9": "x := \"\\u{41\";\n", + "esc10": "x := \"\\u{1F600}\\u{e9}\\x00\\xff\\n\\t\\r\\0\\\\\\'\\\"\";\n", + "cmt": "x := 1; (* open (* nested *)\n", "nul": "x := 1;\0 y;\n", "hexbad": "x := 12AB;\n", + "hexbig": "x := 1FFFFFFFFFFFFFFFFH;\n", "hexok": "x := 0FFFFFFFFFFFFFFFFH; y := 7FFFFFFFFFFFFFFFH;\n", + "decbig": "x := 9223372036854775808;\n", "decmax": "x := 9223372036854775807;\n", + "realhex": "x := 1A.5;\n", "realexp": "x := 1.5E;\n", "realexp2": "x := 1.5E+;\n", "realbig": "x := 1.0E309;\n", + "realmax": "x := 1.7976931348623159E308;\n", "reallong": "x := " + "1" * 254 + ".5;\n", + "digname": "x := 12abc;\n", "uni": "x := \u00e9;\n", "badutf": b"x := \"a\xc3(\";\n", "badutf2": b"x := \"\xed\xa0\x80\";\n", + "badutf3": b"x := \"\xc0\x80\";\n", "badutf4": b"x := \"\xf5\x80\x80\x80\";\n", "badutf5": b"x := \"\xe2\x82\";\n", + "okutf": "x := \"h\u00e9llo \u20ac \U0001F600\"; y := '\u00e9'; (* \u00e9 *)\n", + "unexp": "x := @;\n", "long": "x := " + "a + " * 60 + "@;\n", "longmid": "x := " + "a + " * 40 + "@ " + "+ b" * 40 + ";\n", + "tab": "\t\tx := @;\n", "multi": "x := \"\u00e9\u00e9\u00e9\" + @;\n", "ident64": "x" * 64 + ";\n", "ident63": "x" * 63 + ";\n", + "bigstr": "x := \"" + "a" * 70000 + "\";\n", "empty": "", "nonl": "x := y", + "ops": "+ - * / = # < <= > >= := : ; , . .. ... ( ) [ ] { } ^ & ~ | _ __ _a\n", + "words": "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 Volatile\n", +} +for k, v in cases.items(): + open(f"{d}/{k}.raz", "wb").write(v.encode("utf-8", "surrogateescape") if isinstance(v, str) else v) +open(f"{d}/crlf.raz", "wb").write(b"x := 1;\r\ny := @;\r\n") diff --git a/src/test/genreals.py b/src/test/genreals.py new file mode 100644 index 0000000..3074392 --- /dev/null +++ b/src/test/genreals.py @@ -0,0 +1,19 @@ +# Prints a raz module of reals that are hard to read exactly: the +# extremes, halves between neighbours, and many random ones. +import random +random.seed(7) +v = ["0.0", "1.0", "0.1", "4.9E-324", "2.4703282292062327E-324", "2.4703282292062328E-324", + "2.2250738585072014E-308", "2.2250738585072011E-308", "1.7976931348623157E308", + "9007199254740993.0", "9007199254740992.5", "9007199254740993.5", "0.000001E+3", + "123456789012345678901234567890.0E-10", "1.0E-400", "0.5E1", "5.0E-1"] +for _ in range(3000): + d = random.randint(1, 10 ** random.randint(1, 30)) + e = random.randint(-320, 300) + s = str(d) + v.append(s[0] + "." + (s[1:] or "0") + "E" + ("%+d" % e if random.random() < .5 else str(e))) +for _ in range(500): + v.append("%d.%d" % (random.randint(0, 10 ** 6), random.randint(0, 10 ** 12))) +print("module Reals;\nvar x: F64;\nbegin") +for s in v: + print(" x := " + s + ";") +print("end Reals.") diff --git a/src/x64.pas b/src/x64.pas deleted file mode 100644 index e7efa73..0000000 --- a/src/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.