Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-28 22:13:49 -05:00
commit 05756094ac
706 files changed
+135430

No files matched your search

+136
View File
@@ -0,0 +1,136 @@
# sakura::compiler
`sakura::compiler` is the middle of the Sakura compiler. It lowers a program
that `sakura::analyzer` has checked to intermediate code: values each assigned
once, in blocks that take parameters where control flow joins. It optimizes
that code, and assembles each function into the code `sakura::machine` runs.
The compiler's back end builds executables from the same intermediate code.
## Using it
Require this repository, which exports each of the compiler's libraries, and name this
one among a target's `deps` with the analyzer, which it reads itself:
```yaml
requires:
- https://git.malunal.studio/sakura/std@v1.0.0
- https://git.malunal.studio/sakura/sakurac@v1.0.0
targets:
- name: app
type: program
deps: [sakura.analyzer, sakura.compiler, std.io]
```
A program is lowered from the checker that checked it, as `sakura::analyzer`'s
README checks one:
```sakura
import std::io;
import sakura::analyzer;
import sakura::compiler;
# Checks a file importing nothing, with `core`, whose folder is given, then
# lowers it, optimizes it at a level, and prints the code of the function of a
# name. Gives whether it could.
def lower(path: strview, core: strview, level: u32, name: strview): bool {
var paths := vector::<string>::new();
paths.append(string::from(path, nothing {}));
paths.append(string::from(builtin_path, nothing {}));
every_file(core, &mut paths);
var names := names::new();
var notes := vector::<note>::new();
var sources := vector::<source>::new();
var syntaxes := vector::<syntax>::new();
var roots := vector::<u32>::new();
sources.reserve(paths.length);
syntaxes.reserve(paths.length);
for i in 0..paths.length {
val at := paths[i].view();
sources.append(at == builtin_path ? source::from(at, builtin_text) : source::open(at));
syntaxes.append(syntax::new());
var lexing := lexer::new(sources.at(i), &mut names, &mut notes, i as u32);
lexing.tokenize_all(syntaxes.at(i));
var parsing := parser::new(syntaxes.at(i), &names, &mut notes, i as u32);
roots.append(parsing.parse());
}
var checker := checker::new(&mut names, &mut notes);
for i in 0..paths.length {
checker.add(sources.at(i), syntaxes.at(i), roots.at(i));
}
checker.check();
return false if notes.length != 0;
var lowered := lowerer::new(&mut checker, lowering { verify = true, level = level });
lowered.compile();
for &each in lowered.problems {
println(each);
}
return false if lowered.problems.length != 0;
lowered.drop_unreached_functions();
for &function in lowered.program.functions {
if function.lowered && function.name.view() == name {
print(function.body.print());
}
}
return true;
}
```
For `def square(x: i32): i32 { return x * x; }` at level 0, it prints:
```
b0(v0: i64):
v1 = mul v0, v0
v2 = wrap v1, 32, signed
ret v2
```
The values of constants are computed by running code on `sakura::machine`.
Its `evaluate` gives the `outcomes`, which are set as the lowerer's `evaluated`
before `compile`.
## What it holds
- **Lowering**: `lowerer` lowers each function once something that runs names
it, by `lowering`'s options. `emitter/` has a file for each part of the
language.
- `layouts` lays out types as C lays out the same fields.
- `dispatch` holds the vtables of traits.
- `globals` gives the globals their values before `main` runs.
- `escapes` and `flows` find where each reference may go, so a local whose
address is kept lives in a cell of the frame.
- **Intermediate code** (`intermediate/`): `code`, a function's blocks,
instructions and cells. `builder` makes it in one pass. `verifier` checks it
is well formed. `printer` writes it as text.
- **Optimizing** (`optimizer/`):
- `-O1` simplifies, cleans up control flow, numbers values, and removes dead
code.
- `-O2` also inlines and promotes cells to values.
- Below `-O2`, calls of `@inline` functions are inlined all the same, and at
`-O0` that is all that changes.
- At `-O1` and above, a function asking which vector instructions the
processor has, or counting a word's bits, gets a version for x86-64-v3's,
and an executable's stores filling 16 bytes of a struct are merged into one
of a vector once the rest is done.
- Each pass leaves the code well formed.
- **The machine's code**: `bytecode` assembles each function into the words
`sakura::machine` runs.
- **Constants**: the program that computes the constants and the `if const`
conditions the checker left undecided.
- **Threads**: `workers` shares functions among threads, which optimize and
assemble them into the same bytes however many there are.
## Testing
From the repository's root, `blossom test` runs them as `sakura.compiler.tests`, or:
```sh
sakurac run --lib sakura::analyzer=analyzer --lib sakura::compiler=compiler \
tests/main.sakura tests/compiler/*.sakura
```
The tests are declared within the module. Most check and lower a small program
and compare its printed code with what is expected, after the verifier has
found nothing wrong with it.
+71
View File
@@ -0,0 +1,71 @@
#! @file atomics.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the operations of atomics, as `core::atomic` and both compilers number
#! them, and the orders they take, as `core::order` does.
module sakura::compiler;
# The operations an `atomic` instruction works, its `aux`. Each takes the address
# first, but a fence, which takes none, and its orders last.
pub const atomic_load: u32 = 0; #! (address, order): what the address holds.
pub const atomic_store: u32 = 1; #! (address, value, order): writes the value, giving nothing.
pub const atomic_exchange: u32 = 2; #! (address, value, order): writes the value, giving what was there.
pub const atomic_compare_exchange: u32 = 3; #! (address, expected, desired, success, failure): writes `desired` where it holds `expected`, giving what was there.
pub const atomic_add: u32 = 4; #! (address, operand, order): adds, wrapping, giving what was there.
pub const atomic_sub: u32 = 5; #! Subtracts, wrapping.
pub const atomic_and: u32 = 6; #! Keeps the bits both have.
pub const atomic_or: u32 = 7; #! Keeps the bits either has.
pub const atomic_xor: u32 = 8; #! Keeps the bits one has.
pub const atomic_min: u32 = 9; #! Keeps the less, compared as the access is, signed or unsigned.
pub const atomic_max: u32 = 10; #! Keeps the greater.
pub const atomic_fence: u32 = 11; #! (order): orders the reads and writes around it, giving nothing.
#! Set in an `atomic` instruction's `imm`, beside its access, where the integer
#! is unsigned, which the access alone does not say of 64 bits.
pub const atomic_unsigned: u64 = 0x100;
#! The access an `atomic` instruction reads and writes as.
#! @param imm Its `imm`.
#! @returns The access.
pub def atomic_access(imm: u64): access {
return (imm & 0xFF) as access;
}
#! Whether an `atomic` instruction compares as signed integers do.
#! @param imm Its `imm`.
#! @returns Whether it does.
pub def atomic_signed(imm: u64): bool {
val how := atomic_access(imm);
return (imm & atomic_unsigned) == 0 && (how == access::i8 || how == access::i16 || how == access::i32 || how == access::i64);
}
# The orders, as `core::order` numbers them.
pub const order_relaxed: u64 = 0;
pub const order_acquire: u64 = 1;
pub const order_release: u64 = 2;
pub const order_acq_rel: u64 = 3;
pub const order_seq_cst: u64 = 4;
#! The name of each atomic operation, as the printed code writes it.
pub const atomic_names: strview[12] = [
"load", "store", "exchange", "compare_exchange", "add", "sub", "and", "or", "xor", "min", "max", "fence"
];
#! Whether an atomic operation gives what the address held.
#! @param operation The operation.
#! @returns Whether it does.
pub def atomic_gives(operation: u32): bool {
return operation != atomic_store && operation != atomic_fence;
}
#! Whether an atomic operation is one of those `core::atomic`'s integers alone
#! have, which read, combine, and write.
#! @param operation The operation.
#! @returns Whether it is.
pub def atomic_combines(operation: u32): bool {
return operation >= atomic_add && operation <= atomic_max;
}
File diff suppressed because it is too large. Load diff
+475
View File
@@ -0,0 +1,475 @@
#! @file compiler.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the compiler, which lowers a checked program to a program of
#! intermediate code: `main`, the code initializing the globals, and every
#! function they reach, each lowered once something that runs names it. What
#! each node means comes from the checker's tables: a function's nodes from
#! its file's result table, and those of an instance of a generic from the
#! instance's. What lowering does with each part of the language is split
#! across the files of the `emitter` directory, as the checker's are.
import std::containers;
import sakura::analyzer;
module sakura::compiler;
#! How the code is lowered.
pub struct lowering {
pub var keep_locals: bool; #! Whether every named local is kept in a cell of its own, as debugging information wants.
pub var describe: bool; #! Whether the variables of optimized code are noted for debugging information, which changes nothing of the code.
pub var verify: bool; #! Whether each function is verified once lowered.
pub var everything: bool; #! Whether every function that is no generic's template is lowered, not only those `main` reaches.
pub var evaluating: bool; #! Whether the program evaluates constants while compiling, rather than running.
pub var checks: bool; #! Whether what each reference and pointer reaches is checked as the program runs, as `run --checks` asks.
pub var level: u32; #! How much the code is optimized: 0 not at all, 1 within each function, 2 inlining too.
pub var inline_limit: u32; #! The most instructions a function inlined may have, but for its constants, or 0 for `inline_limit`.
pub var threads: u32; #! How many threads optimize and assemble functions at once, the compiler's own among them; 0 or 1 for it alone.
}
#! The compiler.
pub struct lowerer {
pub var checker: &mut checker; #! The checker, whose tables say what the program means.
pub var program: program; #! What is made.
var options: lowering; #! How the code is lowered.
var layout_ids: dict<u32, u32>; #! The layout of each type.
var laying: u32; #! How many layouts are being made, one within another.
var referents: vector<u32>; #! References and pointers laid out, each with the type it reaches, which is laid out once the outermost is.
var signature_ids: dict<u32, u32>; #! The signature of each function type.
var function_ids: dict<u64, u32>; #! The function of each declaration and instance, by `pair_key(decl, instance)`, the instance one more than its index.
var builtin_ids: dict<u64, u32>; #! The function giving each built-in type each method, by `pair_key(type, name)`.
var lambda_ids: dict<u64, u32>; #! The function of each anonymous function, by `pair_key(table, node)`.
var adapter_ids: dict<u64, u32>; #! The adapter of each function named as a value of another function type, by `pair_key(table, node)`.
var global_ids: dict<u32, u64>; #! Where each global is among the globals, by its declaration.
var begun_globals: hashset<u32>; #! The globals whose initializers are lowered, or being lowered.
var vtable_ids: dict<u64, u32>; #! The vtable of each type for each trait's type, by `pair_key(type, trait)`.
var retrait_ids: dict<u64, u32>; #! The map of each conversion between traits' types, by `pair_key(from, to)`.
var linked_ids: dict<u32, u32>; #! The C function each foreign declaration calls.
var texts: interner<string>; #! Each text a datum holds.
var text_data: vector<u32>; #! The datum holding each text, by its ID in `texts`.
var dispatches: dict<u32, u32>; #! The run of the methods of each trait in the order its vtables hold them, in `lists`.
var lists: runs<u32>; #! The runs `dispatches` names.
var queue: vector<u32>; #! The functions waiting to be lowered.
pub var problems: vector<string>; #! What lowering could not lower, which a program the checker passes never has.
var summaries: dict<u64, keeping>; #! What each function does with what it is given, by `pair_key(decl, instance)`, once found for good.
var pending: vector<pending_scan>; #! The functions whose summaries are being found, in the order they were reached.
var pending_ids: dict<u64, u32>; #! The place of each in `pending`, by its key.
var reader_of: vector<u32>; #! Of each link of a pending function's readers, the reader, by its place.
var reader_next: vector<u32>; #! Of each link, one more than the next link of the same function, or 0.
var read_pairs: hashset<u64>; #! The pending functions each reader read, by `pair_key(read, reader)`.
var scanning: u32; #! The pending function whose scan is being made, or `no_scan`.
pub var dispatch: u32; #! The function safe points call, `system::dispatch`, or `no_function` where the program handles no signal.
pub var evaluations: vector<evaluation>; #! Of a program evaluating constants, what it evaluates.
pub var evaluation_ids: dict<u64, u32>; #! The evaluation of each constant, condition, or text, by its key.
pub var evaluated: outcomes; #! What evaluating worked out, which the program holds as data.
var constant_data: dict<u64, u32>; #! The datum holding each constant evaluated, by its key.
}
#! Provides read only access to how much the code is optimized: 0 not at all,
#! 1 within each function, 2 inlining too.
#! @param this The compiler.
#! @returns How much.
pub val lowerer::level: u32 {
get => this.options.level;
}
#! Makes a compiler of a program the checker has checked.
#! @param checker The checker.
#! @param options How the code is lowered.
#! @returns The compiler.
pub def lowerer::new(checker: &mut checker, options: lowering): lowerer {
return lowerer {
checker = checker,
program = program::new(),
options = options,
layout_ids = dict::<u32, u32>::new(),
referents = vector::<u32>::new(),
signature_ids = dict::<u32, u32>::new(),
function_ids = dict::<u64, u32>::new(),
builtin_ids = dict::<u64, u32>::new(),
lambda_ids = dict::<u64, u32>::new(),
adapter_ids = dict::<u64, u32>::new(),
global_ids = dict::<u32, u64>::new(),
begun_globals = hashset::<u32>::new(),
vtable_ids = dict::<u64, u32>::new(),
retrait_ids = dict::<u64, u32>::new(),
linked_ids = dict::<u32, u32>::new(),
texts = interner::<string>::new(),
text_data = vector::<u32>::new(),
dispatches = dict::<u32, u32>::new(),
lists = runs::<u32>::new(),
queue = vector::<u32>::new(),
problems = vector::<string>::new(),
summaries = dict::<u64, keeping>::new(),
pending = vector::<pending_scan>::new(),
pending_ids = dict::<u64, u32>::new(),
reader_of = vector::<u32>::new(),
reader_next = vector::<u32>::new(),
read_pairs = hashset::<u64>::new(),
scanning = no_scan,
dispatch = no_function,
evaluations = vector::<evaluation>::new(),
evaluation_ids = dict::<u64, u32>::new(),
evaluated = outcomes::new(),
constant_data = dict::<u64, u32>::new()
};
}
#! Lowers the program: the code initializing the globals, `main`, and every
#! function they reach, then fills the vtables' maps between traits.
#! @param this The compiler.
#! @returns Whether everything was lowered, with nothing it could not lower.
pub def lowerer::compile(&mut this): bool {
# A program evaluating constants computes them, and runs nothing else.
if this.options.evaluating {
this.lower_evaluations();
this.drain();
this.fill_retraits();
this.drain();
return this.problems.length == 0;
}
val main := this.checker.modules.decl(0, word::main);
if main != 0 && this.checker.decls.kinds.p[main] == dk::function {
this.program.main = this.function_of(main, 0);
}
this.find_dispatch();
val point := mark_scratch();
this.program.init = this.lower_globals();
release_scratch(point);
if this.options.everything {
this.want_everything();
}
this.drain();
this.fill_retraits();
this.drain();
this.optimize();
return this.problems.length == 0;
}
#! Lowers the functions waiting, and those they reach in turn, each freeing
#! the scratch memory it took as it ends.
#! @param this The compiler.
pub def lowerer::drain(&mut this): void {
var at: u64 = 0;
while at < this.queue.length {
val point := mark_scratch();
this.lower_function(this.queue[at]);
release_scratch(point);
at++;
}
this.queue.clear();
}
#! Notes what lowering could not lower.
#! @param this The compiler.
#! @param file The file it is in.
#! @param node Its node.
#! @param what What it is, said in words.
pub def lowerer::problem(&mut this, file: u32, node: u32, what: strview): void {
val held := &this.checker.units[file].source;
val at := held.lines.place_of(this.node_offset(file, node));
this.problems.append($"{held.path}:{at.line}:{at.column}: {what}");
}
#! The type of a function, or of an instance of it.
#! @param this The compiler.
#! @param decl The function's declaration.
#! @param instance One more than the instance, or 0.
#! @returns The type.
pub def lowerer::type_of_function(&this, decl: u32, instance: u32): u32 {
return instance != 0 ? this.checker.instances[instance - 1].kind : this.checker.decls.types.p[decl];
}
#! The table of nodes a function's body was checked in: its instance's, whose
#! instances are checked where they were not yet, or its file's, where it is no
#! instance or the instance's body was never checked.
#! @param this The compiler.
#! @param decl The function's declaration.
#! @param instance One more than the instance, or 0.
#! @returns The table.
pub def lowerer::body_table(&mut this, decl: u32, instance: u32): u32 {
if instance != 0 {
if this.checker.instances[instance - 1].table == 0 {
this.check_instances();
}
val held: u32 = this.checker.instances[instance - 1].table;
return held - 1 if held != 0;
}
return this.checker.units[this.checker.decls.files.p[decl]].table;
}
#! The function a declaration is lowered to, given the instance of a generic it
#! is, made and waiting to be lowered where it is new.
#! @param this The compiler.
#! @param decl The function's declaration.
#! @param instance One more than the instance of the checker it is, or 0.
#! @returns The function's index.
pub def lowerer::function_of(&mut this, decl: u32, instance: u32): u32 {
val key := pair_key(decl, instance);
if this.function_ids.get(&key) is some(got) {
return got;
}
this.checker.resolve(decl);
val kind := this.type_of_function(decl, instance);
val index := this.add_function(this.function_name(decl, instance), this.signature_of(this.call_type(this.function_type(decl, kind))));
this.function_ids.set(key, index);
val node: u32 = this.checker.decls.nodes.p[decl];
val file: u32 = this.checker.decls.files.p[decl];
this.program.functions[index].decl = decl;
this.program.functions[index].instance = instance;
this.program.functions[index].file = file;
this.program.functions[index].offset = this.node_offset(file, node);
this.program.functions[index].callback = this.checker.decls.has(decl, df::callback);
this.program.functions[index].inline = this.checker.decls.has(decl, df::inline);
val name: u32 = this.checker.decls.names.p[decl];
this.program.functions[index].stepping = this.checker.decls.has(decl, df::method)
&& (name == word::next || name == word::next_back || name == word::invoke);
this.want(index);
return index;
}
#! The function type a function is lowered with: its own, where a trait's
#! default method takes `this` as a reference to the trait rather than to
#! `self`, which only what implements it knows. A default compiled for each
#! type takes its own type, as its type says.
#! @param this The compiler.
#! @param decl The function's declaration.
#! @param kind Its function type, given its type arguments.
#! @returns The function type.
pub def lowerer::function_type(&mut this, decl: u32, kind: u32): u32 {
val holder: u32 = this.checker.decls.owners.p[decl];
val owner: u32 = holder != 0 && this.checker.decls.kinds.p[holder] == dk::property
? this.checker.decls.owners.p[holder]
: holder;
return kind if owner == 0 || this.checker.decls.kinds.p[owner] != dk::trait_type
|| !this.checker.decls.has(decl, df::method) || this.checker.typed_default(decl);
# An instance of a generic trait's default already takes the trait, given
# its arguments.
var params := this.checker.types.parts_of(kind);
return kind if params.length == 0;
val taken := this.checker.unalias(this.checker.types.first_of(params[0]));
return kind if this.checker.named_kind(taken) == dk::trait_type;
val writes := this.checker.decls.has(decl, df::mut_this);
params[0] = this.checker.types.reference(this.checker.decls.types.p[owner], writes);
return this.checker.types.function(params.view(), this.checker.types.first_of(kind), this.checker.types.second_of(kind) != 0);
}
#! Adds a function of the program, lowered later.
#! @param this The compiler.
#! @param name Its name, as a trace writes it.
#! @param signature How it is called.
#! @returns Its index.
pub def lowerer::add_function(&mut this, name: string, signature: u32): u32 {
this.program.functions.append(function {
name = move(&mut name),
signature = signature,
body = code::new(),
compiled = bytecode::new(),
order = vector::<u32>::new(),
named = vector::<u32>::new()
});
return (this.program.functions.length - 1) as u32;
}
#! Notes that a function's code names another as a value, each once.
#! @param this The compiler.
#! @param function The function naming it.
#! @param named The function named.
pub def lowerer::names(&mut this, function: u32, named: u32): void {
for &each in this.program.functions[function].named.view() {
return if each == named;
}
this.program.functions[function].named.append(named);
}
#! Marks a function as named by code that runs, so it is lowered.
#! @param this The compiler.
#! @param index The function.
pub def lowerer::want(&mut this, index: u32): void {
return if this.program.functions[index].queued;
this.program.functions[index].queued = true;
this.queue.append(index);
}
#! The name of a function as a trace writes it, as the C compiler names it: a
#! method's names its type, as `vec2::normalize`, and an instance of a generic
#! names its type arguments, as `max<i64>` and `list<i64>::push`.
#! @param this The compiler.
#! @param decl The function's declaration.
#! @param instance One more than the instance of a generic it is, or 0.
#! @returns The name.
pub def lowerer::function_name(&mut this, decl: u32, instance: u32): string {
var holder: u32 = this.checker.decls.owners.p[decl];
if holder != 0 && this.checker.decls.kinds.p[holder] == dk::property {
holder = this.checker.decls.owners.p[holder];
}
# The type arguments of an instance are its owner's, then its own.
val args := instance != 0 ? this.checker.types.parts_view(this.checker.instances[instance - 1].args) : span::<u32>::empty();
val own := this.checker.own_param_count(decl) as u64;
val outer := args.length > own ? args.length - own : 0;
var made := string::new(nothing {});
if holder != 0 {
made.append(this.checker.names.text(this.checker.decls.names.p[holder]));
if outer != 0 {
this.type_args(args, 0, outer, &mut made);
}
made.append("::");
}
made.append(this.checker.names.text(this.checker.decls.names.p[decl]));
if own != 0 && args.length > outer {
this.type_args(args, outer, args.length, &mut made);
}
return made;
}
#! Writes type arguments as a name shows them, `<i64, bool>`, a pack's types as
#! the arguments they are, and an empty pack as none, as the checker writes them.
#! @param this The compiler.
#! @param args The type arguments.
#! @param from The first written.
#! @param to The one past the last written.
#! @param out Where they are written.
def lowerer::type_args(&this, args: span<u32>, from: u64, to: u64, out: &mut string): void {
out.append("<");
this.checker.describe_args(span::<u32>::over(args.data + from, to - from), out);
out.append(">");
}
#! The byte of a file a node begins at.
#! @param this The compiler.
#! @param file The file.
#! @param node The node.
#! @returns The byte.
pub def lowerer::node_offset(&this, file: u32, node: u32): u32 {
val syntax := &this.checker.units[file].syntax;
return syntax.token_offsets[syntax.node_tokens[node]];
}
#! Lowers a function waiting to be lowered.
#! @param this The compiler.
#! @param index The function.
def lowerer::lower_function(&mut this, index: u32): void {
return if this.program.functions[index].lowered;
this.program.functions[index].lowered = true;
var made := emitter::new(this, index);
made.lower();
made.finish();
}
#! The datum holding text, made where it is new: its bytes, followed by a zero
#! the length does not count.
#! @param this The compiler.
#! @param text The text.
#! @returns The datum's index.
pub def lowerer::text_datum(&mut this, text: strview): u32 {
# A text new to `texts` is given the next ID, which has no datum yet.
val id := this.texts.intern_view(text);
if id < this.text_data.length {
return this.text_data[id];
}
var bytes := vector::<u8>::new();
bytes.extend(text);
bytes.append(0);
val index := this.program.data.length as u32;
this.program.data.append(datum {
bytes = move(&mut bytes),
align = 1,
relocations = vector::<relocation>::new()
});
this.text_data.append(index);
return index;
}
#! Places a global after those placed before it, where it is not yet placed.
#! @param this The compiler.
#! @param decl The global's declaration.
#! @returns Where it is among the globals.
pub def lowerer::global_of(&mut this, decl: u32): u64 {
if this.global_ids.get(&decl) is some(got) {
return got;
}
this.checker.resolve(decl);
val held := this.shape_of(this.checker.decls.types.p[decl]);
this.program.globals = round_up(this.program.globals, held.align);
val offset := this.program.globals;
this.global_ids.set(decl, offset);
this.program.globals += held.size;
# Evaluating, a byte between globals keeps an address just past one from being
# where the next begins, so an empty view at the end of a constant's array is
# still that constant's.
if this.options.evaluating {
this.program.globals += 1;
}
return offset;
}
#! Places a global no declaration names after those placed before it, as what
#! a global refers to that was made for it is.
#! @param this The compiler.
#! @param kind Its type.
#! @returns Where it is among the globals.
pub def lowerer::unnamed_global(&mut this, kind: u32): u64 {
val held := this.shape_of(kind);
this.program.globals = round_up(this.program.globals, held.align);
val offset := this.program.globals;
this.program.globals += held.size == 0 ? 1 : held.size;
return offset;
}
#! Asks for every function that is no generic's template, and has a body, as a
#! library's tests want, rather than only those `main` reaches.
#! @param this The lowerer.
def lowerer::want_everything(&mut this): void {
for id in 1..this.checker.decls.count {
val decl := id as u32;
continue if this.checker.decls.kinds.p[decl] != dk::function || this.checker.decls.has(decl, df::generic);
continue if this.checker.decls.has(decl, df::intrinsic) || this.checker.decls.has(decl, df::failed);
continue if !this.checker.has_body(decl) || this.trait_of_method(decl) != 0;
this.function_of(decl, 0);
}
}
#! Gives the program safe points where it handles a signal, which is where
#! anything calls `system::handle`: each calls `system::dispatch`, which runs
#! the handlers of the signals that have come.
#! @param this The lowerer.
def lowerer::find_dispatch(&mut this): void {
val sys := this.checker.modules.find(0, word::system);
return if sys == 0;
val handle := this.checker.modules.decl(sys, this.checker.names.intern(&"handle"));
val dispatch := this.checker.modules.decl(sys, this.checker.names.intern(&"dispatch"));
return if handle == 0 || dispatch == 0 || this.checker.decls.kinds.p[dispatch] != dk::function;
return if !this.checker.is_depended(handle);
this.dispatch = this.function_of(dispatch, 0);
}
#! Whether a declaration is `core`'s, std's, or `system`'s, whose code has no
#! safe points.
#! @param this The lowerer.
#! @param decl The declaration.
#! @returns Whether it is.
pub def lowerer::in_std(&this, decl: u32): bool {
var at: u32 = this.checker.decls.modules.p[decl];
var steps := 0;
while at != 0 && this.checker.modules.parents[at] != 0 && steps < 64 {
at = this.checker.modules.parents[at];
steps++;
}
return at != 0 && (this.checker.modules.names[at] == word::std
|| this.checker.modules.names[at] == word::core
|| this.checker.modules.names[at] == word::system);
}
+358
View File
@@ -0,0 +1,358 @@
#! @file constants.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the values computed while compiling: the constants, the
#! conditions of the `if const` statements the checker left undecided, and the
#! text of each `compile_error` it was given text it could not read.
#!
#! A program evaluating them is lowered first, with a function of its own for
#! each, which computes the value into a global. Reading a constant stops that
#! program unless the constant is evaluated, so the machine evaluates the one it
#! needs first; and it stops reading what only a running program has, such as
#! a variable given its value once it runs.
#!
#! The value each computes is kept as bytes laid out as its type, with the
#! memory it points into, each address within them noted rather than written,
#! since the memory it was computed in is the compiler's. The program then
#! holds each as data, whose addresses are written where it is placed: a
#! constant is read where its data is, and a condition decides its branch.
import sakura::analyzer;
import std::containers;
module sakura::compiler;
#! What stands for no block, where an address a value holds names a function.
pub const no_block: u32 = 0xFFFFFFFF;
#! What stands for a block, where an address a value holds points into another
#! constant's value, which `decl`, or `table` and `node`, name as for a function.
pub const in_constant: u32 = 0xFFFFFFFE;
#! Where a value computed while compiling holds an address: of memory it points
#! into, kept as a block, of another constant's value, or of a function, as a
#! function value holds it.
pub struct kept_address {
pub var at: u64; #! The byte of the value or block the address is written at.
pub var block: u32; #! The block it points into, `in_constant`, or `no_block` for a function.
pub var addend: u64; #! How far into the block or the constant's value it points.
pub var decl: u32; #! The function's or the global constant's declaration, or 0 for an anonymous function or a local constant.
pub var instance: u32; #! One more than the instance of a generic it is, or 0.
pub var table: u32; #! Of an anonymous function or a local constant, the result table of its nodes.
pub var node: u32; #! Of an anonymous function, its `lambda` node, and of a local constant, its `variable` node.
pub var file: u32; #! Of an anonymous function, its file.
}
#! Memory a value computed while compiling points into.
pub struct kept_block {
pub var bytes: vector<u8>; #! What it holds.
pub var addresses: vector<kept_address>; #! Where it holds addresses.
}
#! A value computed while compiling: its bytes, laid out as its type is, and
#! the memory it reaches.
pub struct evaluated {
pub var bytes: vector<u8>; #! The value.
pub var addresses: vector<kept_address>; #! Where it holds addresses.
pub var blocks: vector<kept_block>; #! The memory it points into, which addresses name by index.
}
#! What evaluating worked out, by the key of each constant, condition, or text.
pub struct outcomes {
pub var values: dict<u64, evaluated>; #! The value of each constant.
pub var decisions: dict<u64, bool>; #! Whether the condition of each `if const` holds.
pub var texts: dict<u64, string>; #! What each `compile_error` evaluating reports says.
}
#! Makes outcomes holding nothing.
#! @returns The outcomes.
pub def outcomes::new(): outcomes {
return outcomes {
values = dict::<u64, evaluated>::new(),
decisions = dict::<u64, bool>::new(),
texts = dict::<u64, string>::new()
};
}
#! The key of a global constant.
#! @param decl Its declaration.
#! @returns The key.
pub def decl_key(decl: u32): u64 {
return decl as u64;
}
#! The key of a local constant, the condition of an `if const`, or the text of
#! a `compile_error`: the result table it was checked in, and its node.
#! @param table The table.
#! @param node The `variable`, `if_const`, or `call` node.
#! @returns The key.
pub def node_key(table: u32, node: u32): u64 {
return (1u << 63) | pair_key(table, node);
}
#! A value computed while compiling, in the program evaluating them.
pub struct evaluation {
pub var key: u64; #! Its key.
pub var decl: u32; #! The global constant, or 0.
pub var table: u32; #! The result table a local constant, condition, or text was checked in.
pub var node: u32; #! Its `variable`, `if_const`, or `call` node.
pub var condition: bool; #! Whether it is the condition of an `if const`.
pub var text: bool; #! Whether it is the text of a `compile_error`, its first argument.
pub var kind: u32; #! The type of its value.
pub var offset: u64; #! The global holding its value.
pub var function: u32; #! The function computing it.
}
#! Lowers the program evaluating what the checker left to evaluating: every
#! global constant whose value is not a number it worked out, and the local
#! constants, conditions of `if const`, and text of `compile_error` it noted.
#! @param this The compiler.
pub def lowerer::lower_evaluations(&mut this): void {
for id in 1..this.checker.decls.count {
val decl := id as u32;
continue if !this.needs_evaluation(decl);
this.evaluation_of(decl_key(decl), decl, 0, 0, false);
}
for i in 0..this.checker.to_evaluate.length {
val each: u64 = this.checker.to_evaluate[i];
val table := pair_high(each);
val node := pair_low(each);
val syntax := &this.checker.units[this.checker.tables.p[table].file].syntax;
val condition := syntax.node_kinds[node] == nk::if_const;
this.evaluation_of(node_key(table, node), 0, table, node, condition);
}
}
#! Whether a declaration is a global constant whose value is evaluated: one the
#! checker did not work out as a number, or one of a struct, a union, or an
#! array.
#! @param this The compiler.
#! @param decl The declaration.
#! @returns Whether it is.
pub def lowerer::needs_evaluation(&mut this, decl: u32): bool {
return false if this.checker.decls.kinds.p[decl] != dk::variable || !this.checker.decls.has(decl, df::constant);
return false if this.checker.decls.has(decl, df::failed) || this.checker.decls.nodes.p[decl] == 0;
val owner: u32 = this.checker.decls.owners.p[decl];
return false if owner != 0 && this.checker.own_param_count(owner) != 0;
val saved := this.checker.at;
this.checker.use_table(this.checker.units[this.checker.decls.files.p[decl]].table);
val value := this.checker.record(this.checker.decls.nodes.p[decl], variable_slot::value);
val known := value != 0 && this.checker.is_known(value) && this.is_scalar_type(this.checker.decls.types.p[decl]);
this.checker.at = saved;
return value != 0 && !known;
}
#! Whether values of a type are one word, as a number, `bool`, enum, or pointer.
#! @param this The compiler.
#! @param kind The type.
#! @returns Whether they are.
pub def lowerer::is_scalar_type(&mut this, kind: u32): bool {
return false if kind == bt::error || kind == bt::void_type || kind == 0;
val plain := this.layout_type(kind);
return this.checker.types.is_numeric(plain) || this.checker.types.is_boolean(plain)
|| this.checker.named_kind(plain) == dk::enum_type || this.checker.types.kind_of(plain) == ty::pointer;
}
#! The evaluation computing a constant, condition, or text, made where it is
#! new: a global holding its value, and a function computing it there.
#! @param this The compiler.
#! @param key Its key.
#! @param decl The global constant, or 0.
#! @param table The result table of a local constant, condition, or text.
#! @param node Its node: of text, the `compile_error` call.
#! @param condition Whether it is the condition of an `if const`.
#! @returns Its index.
pub def lowerer::evaluation_of(&mut this, key: u64, decl: u32, table: u32, node: u32, condition: bool): u32 {
if this.evaluation_ids.get(&key) is some(got) {
return got;
}
val saved := this.checker.at;
var kind: u32 = bt::boolean;
var offset: u64 = 0;
var text := false;
var name := string::new(nothing {});
if decl != 0 {
this.checker.resolve(decl);
kind = this.checker.decls.types.p[decl];
offset = this.global_of(decl);
name.append(this.checker.names.text(this.checker.decls.names.p[decl]));
} else {
this.checker.use_table(table);
text = !condition && this.checker.kind_of(node) == nk::call;
if text {
# Text is evaluated as the type it is given as, as a `string` that owns
# its bytes, rather than the view `compile_error` takes of them.
kind = this.checker.type_at(this.checker.run_at(this.checker.right_of(node), 0));
name.append("<compile_error>");
} else if !condition {
kind = this.checker.type_at(node);
name.append(this.checker.names.text(this.checker.name_of(node)));
} else {
name.append("<if const>");
}
val held := this.shape_of(kind);
this.program.globals = round_up(this.program.globals, held.align);
offset = this.program.globals;
this.program.globals += (held.size == 0 ? word_size : held.size) + 1;
}
this.checker.at = saved;
val void_type := this.checker.types.function(span::<u32>::empty(), bt::void_type, false);
val function := this.add_function(move(&mut name), this.signature_of(void_type));
val index := this.evaluations.length as u32;
this.evaluations.append(evaluation {
key = key,
decl = decl,
table = table,
node = node,
condition = condition,
text = text,
kind = kind,
offset = offset,
function = function
});
this.evaluation_ids.set(key, index);
this.program.functions[function].evaluation = index + 1;
this.want(function);
return index;
}
#! Lowers the function computing an evaluation's value into its global.
#! @param this The emitter.
#! @param index The evaluation.
pub def emitter::lower_evaluation(&mut this, index: u32): void {
val held: evaluation = this.c.evaluations[index];
var value: u32 = 0;
if held.decl != 0 {
this.table = this.c.checker.units[this.c.checker.decls.files.p[held.decl]].table;
this.use_own_table();
value = this.c.checker.record(this.c.checker.decls.nodes.p[held.decl], variable_slot::value);
this.at_node(this.c.checker.decls.nodes.p[held.decl]);
} else {
this.table = held.table;
this.use_own_table();
if held.condition {
value = this.c.checker.left_of(held.node);
} else if held.text {
value = this.c.checker.run_at(this.c.checker.right_of(held.node), 0);
} else {
value = this.c.checker.record(held.node, variable_slot::value);
}
this.at_node(held.node);
}
this.result = bt::void_type;
this.plan_storage(value);
val mark := this.begin_statement();
val address := this.build.value(op::global, span::<u32>::empty(), vt::word, 0, held.offset);
val place := location { kind = held.kind, address = address };
val made := this.value_as(value, held.kind);
this.adopt(&made);
this.store(&place, &made);
this.end_statement(mark);
this.build.ret(span::<u32>::empty());
}
#! The data holding a value computed while compiling, made where it is new:
#! the memory it points into first, then the value, each address within them
#! written where the data is placed, and each function as it is numbered here.
#! @param this The compiler.
#! @param key The constant's key.
#! @param kind Its type.
#! @returns The datum, or `no_block` where nothing was evaluated for it.
pub def lowerer::evaluated_datum(&mut this, key: u64, kind: u32): u32 {
if this.constant_data.get(&key) is some(got) {
return got;
}
return no_block if !this.evaluated.values.contains(&key);
# Each block is placed before any is written, since one may point into another.
val count := this.evaluated.values[key].blocks.length;
val first := this.program.data.length as u32;
for _ in 0..count {
this.program.data.append(datum { bytes = vector::<u8>::new(), align = 16, relocations = vector::<relocation>::new() });
}
for b in 0..count {
var bytes := vector::<u8>::copy_of(&this.evaluated.values[key].blocks[b].bytes);
var moved := vector::<relocation>::new();
var addresses := vector::<kept_address>::copy_of(&this.evaluated.values[key].blocks[b].addresses);
this.place_addresses(&mut bytes, &mut moved, addresses.view(), first);
bytes.append(0);
this.program.data[first as u64 + b].bytes = move(&mut bytes);
this.program.data[first as u64 + b].relocations = move(&mut moved);
}
var bytes := vector::<u8>::copy_of(&this.evaluated.values[key].bytes);
var moved := vector::<relocation>::new();
var addresses := vector::<kept_address>::copy_of(&this.evaluated.values[key].addresses);
this.place_addresses(&mut bytes, &mut moved, addresses.view(), first);
bytes.append(0);
val shape := this.shape_of(kind);
val index := this.program.data.length as u32;
this.program.data.append(datum {
bytes = move(&mut bytes),
align = shape.align < word_size ? word_size : shape.align,
relocations = move(&mut moved)
});
this.constant_data.set(key, index);
return index;
}
#! Writes the addresses a value computed while compiling holds: each of a
#! block as a relocation into the data the block became, each into another
#! constant as one into the data that constant's value is, and each function
#! as its index here plus one.
#! @param this The compiler.
#! @param bytes The bytes holding them.
#! @param moved Where the relocations are written.
#! @param addresses The addresses.
#! @param first The datum the first block became.
def lowerer::place_addresses(&mut this, bytes: &mut vector<u8>, moved: &mut vector<relocation>, addresses: span<kept_address>, first: u32): void {
for &each in addresses {
if each.block == in_constant {
# The constant was evaluated before the one pointing into it, so its data
# never waits on this.
moved.append(relocation { at = each.at, target = this.constant_datum(each.decl, each.table, each.node), addend = each.addend });
continue;
}
if each.block != no_block {
moved.append(relocation { at = each.at, target = first + each.block, addend = each.addend });
continue;
}
var function: u32 = 0;
if each.decl != 0 {
function = this.function_of(each.decl, each.instance);
} else {
val saved := this.checker.at;
this.checker.use_table(each.table);
val kind := this.checker.type_at(each.node);
this.checker.at = saved;
function = this.lambda_of(each.table, each.node, each.file, kind, false);
}
this.program.functions[function].taken = true;
val word := function as u64 + 1;
write_number(bytes, each.at, word_size, word);
}
}
#! The data holding another constant's value, which an address a value holds
#! points into, made where it is new.
#! @param this The compiler.
#! @param decl The global constant, or 0 for a local one.
#! @param table Of a local constant, the result table it was checked in.
#! @param node Of a local constant, its `variable` node.
#! @returns The datum.
def lowerer::constant_datum(&mut this, decl: u32, table: u32, node: u32): u32 {
if decl != 0 {
return this.evaluated_datum(decl_key(decl), this.checker.decls.types.p[decl]);
}
val saved := this.checker.at;
this.checker.use_table(table);
val kind := this.checker.type_at(node);
this.checker.at = saved;
return this.evaluated_datum(node_key(table, node), kind);
}
+31
View File
@@ -0,0 +1,31 @@
#! @file conventions.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what the machine and the native backend both know of how calls
#! cross to C: how many words of a frame a value passed to a function of the
#! program takes, and which aggregates Microsoft's ABI passes by value. The
#! machine calls C through code of its own on Windows, and the native backend
#! writes the code of each call, so both cross by these rules.
module sakura::compiler;
#! How many words of a frame a value of a layout takes as an argument of a
#! function of the program: the address of one held in memory, or its words.
#! @param shape The layout.
#! @returns How many.
pub def argument_words(shape: &layout): u64 {
return in_memory(shape) ? 1 : word_count(shape) as u64;
}
#! Whether Microsoft's ABI passes an aggregate of a size by value, as an integer
#! of as many bytes, which it does for one of 1, 2, 4, or 8 bytes. It passes any
#! other by the address of a copy, and returns it through memory whose address
#! the caller passes.
#! @param size The aggregate's bytes.
#! @returns Whether it does.
pub def micro_by_value(size: u64): bool {
return size == 1 || size == 2 || size == 4 || size == 8;
}
+427
View File
@@ -0,0 +1,427 @@
#! @file dispatch.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains how calls reach the functions they call: the instance of a method
#! a value of a generic type is given, the order a trait's vtables hold its
#! methods in, each type's vtable for each trait it is referred to through, the
#! maps a reference to one trait becomes one to another by, and the C functions
#! the program calls by name.
import sakura::analyzer;
module sakura::compiler;
#! What a method called on a value of a type reaches: a function of the
#! program, or a trait's method, called through a vtable.
pub struct target {
var function: u32; #! The function called directly, or `no_function`.
var holder: u32; #! The trait whose vtable is called through, or 0.
var kind: u32; #! The method's function type, given the type's arguments.
}
#! What a method called on a value of a type reaches: the instance of a generic
#! type's method, given the type's arguments, a function of its own, or a
#! trait's method, which a value of a type parameter or a reference to a trait
#! calls through a vtable.
#! @param this The compiler.
#! @param decl The method's declaration.
#! @param owner The type it is called on, read through its references.
#! @returns What it reaches.
pub def lowerer::method_target(&mut this, decl: u32, owner: u32): target {
this.checker.resolve(decl);
var holder: u32 = this.checker.decls.owners.p[decl];
if holder != 0 && this.checker.decls.kinds.p[holder] == dk::property {
holder = this.checker.decls.owners.p[holder];
}
val plain := this.checker.unalias(owner);
if this.checker.trait_asks(decl) {
val kind := this.checker.trait_method_type(decl, plain);
val dynamic := this.checker.named_kind(plain) == dk::trait_type || this.checker.types.kind_of(plain) == ty::param;
if dynamic || !this.checker.has_body(decl) {
return target { function = no_function, holder = holder, kind = kind };
}
val own := span::<u32>::empty();
return target { function = this.default_of(decl, this.checker.implemented(plain, holder), plain, own), kind = kind };
}
if !this.checker.decls.has(decl, df::generic) {
return target { function = this.function_of(decl, 0), kind = this.checker.decls.types.p[decl] };
}
# A generic type's method is the instance its arguments give.
var args := vector::<u32>::new();
if this.checker.types.kind_of(plain) == ty::named {
for i in 0..this.checker.types.part_count(plain) {
args.append(this.checker.types.part_at(plain, i as u32));
}
}
val instance := this.checker.instance_of(decl, args.view(), 0);
if instance == 0 {
return target { function = this.function_of(decl, 0), kind = this.checker.method_type(decl, plain) };
}
return target {
function = this.function_of(decl, instance),
kind = this.checker.instances[instance - 1].kind
};
}
#! Checks the bodies of the instances asked for since the checker last did,
#! which lowering asks for where it calls a method the checker only looked up,
#! as a loop's `next` or a value's `close`.
#! @param this The compiler.
pub def lowerer::check_instances(&mut this): void {
val notes := this.checker.notes_made;
this.checker.check_wanted();
if this.checker.notes_made != notes {
this.problems.append("Checking an instance lowering asked for made notes.");
}
}
#! The methods of a trait in the order its vtables hold them: what it takes on
#! from the traits it composes, in order, and then what it declares itself, the
#! accessors of a property among them. A member taken on is numbered by each
#! trait taking it in its own order.
#! @param this The compiler.
#! @param holder The trait's declaration.
#! @returns The run of the methods in `lists`.
pub def lowerer::dispatch_of(&mut this, holder: u32): u32 {
if this.dispatches.get(&holder) is some(got) {
return got;
}
var methods := vector::<u32>::new();
this.collect_dispatch(holder, &mut methods, 0);
val run := this.lists.add(methods.view());
this.dispatches.set(holder, run);
return run;
}
#! Collects the methods a trait's vtables hold, those of the traits it composes
#! first, each once.
#! @param this The compiler.
#! @param holder The trait's declaration.
#! @param methods Where they are collected.
#! @param depth How deeply composition has been followed.
def lowerer::collect_dispatch(&mut this, holder: u32, methods: &mut vector<u32>, depth: u32): void {
return if depth > 16;
val composed := this.checker.composed_of(holder);
for i in 0..this.checker.decls.list_length(composed) {
val inner := this.checker.types.first_of(this.checker.decls.list_at(composed, i as u32));
this.collect_dispatch(inner, methods, depth + 1);
}
val run: u32 = this.checker.decls.children.p[holder];
for i in 0..this.checker.decls.list_length(run) {
val member := this.checker.decls.list_at(run, i as u32);
match this.checker.decls.kinds.p[member] {
dk::function => this.add_method(member, methods);
dk::property => {
val accessors: u32 = this.checker.decls.children.p[member];
for j in 0..this.checker.decls.list_length(accessors) {
this.add_method(this.checker.decls.list_at(accessors, j as u32), methods);
}
}
else => {}
}
}
}
#! Adds a method to those a vtable holds, where it is not there already.
#! @param this The compiler.
#! @param method The method's declaration.
#! @param methods The methods so far.
def lowerer::add_method(&mut this, method: u32, methods: &mut vector<u32>): void {
return if methods.view().contains(&method);
methods.append(method);
}
#! The slot of a method among those a trait's vtables hold.
#! @param this The compiler.
#! @param holder The trait's declaration.
#! @param method The method's declaration.
#! @returns The slot.
pub def lowerer::dispatch_index(&mut this, holder: u32, method: u32): u32 {
val run := this.dispatch_of(holder);
if this.lists.view(run).index_of(&method) is some(slot) {
return slot as u32;
}
return 0;
}
#! The signature a call through a trait's vtable passes arguments by: the
#! method's, taking `this` as a reference to the trait, and giving the type the
#! call gives, which a generic trait's method gives in terms of the trait's
#! arguments.
#! @param this The compiler.
#! @param method The method's declaration.
#! @param holder The trait referred to.
#! @param result The type the call gives.
#! @returns The signature's index.
pub def lowerer::trait_signature(&mut this, method: u32, holder: u32, result: u32, trait_kind: u32 = 0): u32 {
this.checker.resolve(method);
# A trait's method in terms of the arguments of the trait referred to, as a
# pack it takes is the parameters of its types.
val kind: u32 = trait_kind != 0
? this.checker.requirement_type(method, this.checker.bound_for(trait_kind, this.trait_of_method(method)), trait_kind)
: this.checker.decls.types.p[method];
var params := this.checker.types.parts_of(kind);
if params.length != 0 {
params[0] = this.checker.types.reference(this.checker.decls.types.p[holder], this.checker.decls.has(method, df::mut_this));
}
val made := this.checker.types.function(params.view(), result, this.checker.types.second_of(kind) != 0);
return this.signature_of(this.call_type(made));
}
#! The vtable of a type for a trait it implements, made where it is new, which
#! names the function giving each of the trait's methods, or the trait's default
#! where the type gives none.
#! @param this The compiler.
#! @param kind The type referred to.
#! @param trait_kind The trait's type, given its arguments.
#! @returns The vtable's index.
pub def lowerer::vtable_of(&mut this, kind: u32, trait_kind: u32): u32 {
# An alias's methods come before those of what it stands for, so its vtable
# is its own.
val plain := this.checker.unalias(kind);
val key := pair_key(kind, trait_kind);
if this.vtable_ids.get(&key) is some(got) {
return got;
}
# Placed before its slots are filled, which may make more vtables.
val holder := this.checker.types.first_of(trait_kind);
val index := this.program.vtables.length as u32;
this.program.vtables.append(vtable {
type_id = kind,
trait_id = trait_kind,
layout = this.layout_of(plain),
functions = vector::<u32>::new(),
owners = vector::<u32>::new()
});
this.vtable_ids.set(key, index);
# Read by place, since making the vtables its slots name may add runs.
val run := this.dispatch_of(holder);
for i in 0..this.lists.length(run) {
val method: u32 = this.lists.at(run, i);
var function := no_function;
var owner := index;
val found := this.implementation(kind, method, trait_kind);
if found != 0 && this.trait_of_method(found) == 0 {
function = this.method_target(found, kind).function;
} else if this.checker.has_body(method) {
# The default addresses the slots of the trait declaring it.
val declarer := this.trait_of_method(method);
val declaring := this.checker.bound_for(trait_kind, declarer);
function = this.default_of(method, declaring, plain, span::<u32>::empty());
if declarer != holder {
owner = this.vtable_of(kind, declaring);
}
} else if found != 0 && this.checker.has_body(found) {
function = this.default_of(found, this.checker.bound_for(trait_kind, this.trait_of_method(found)), plain, span::<u32>::empty());
} else if found == 0 {
# A built-in type's method is a function the compiler makes.
function = this.builtin_function(plain, this.checker.decls.names.p[method]);
}
this.program.vtables[index].functions.append(function);
this.program.vtables[index].owners.append(owner);
}
return index;
}
#! The function a trait's default method is, for the trait given its
#! arguments: an instance of it where the trait is generic, so its body is
#! lowered with the types the arguments give, or for the type taking it, where
#! the trait is only a bound.
#! @param this The compiler.
#! @param method The default's declaration.
#! @param trait_kind The trait declaring it, given its arguments.
#! @param self_kind The type taking it.
#! @param own The default's own type arguments.
#! @returns The function's index.
pub def lowerer::default_of(&mut this, method: u32, trait_kind: u32, self_kind: u32, own: span<u32>): u32 {
return this.function_of(method, this.checker.default_instance(method, trait_kind, self_kind, own));
}
#! The trait a method is a member of, directly or as a property's accessor, or
#! 0.
#! @param this The compiler.
#! @param method The method's declaration.
#! @returns The trait's declaration, or 0.
pub def lowerer::trait_of_method(&this, method: u32): u32 {
var owner: u32 = this.checker.decls.owners.p[method];
if owner != 0 && this.checker.decls.kinds.p[owner] == dk::property {
owner = this.checker.decls.owners.p[owner];
}
return this.checker.trait_asks(method) ? owner : 0;
}
#! The method of a type implementing a trait's: of its overloads, the one taking
#! what the trait's does, or the trait's default where the type has none.
#! @param this The compiler.
#! @param kind The type.
#! @param method The trait's method.
#! @returns The type's method, or 0.
def lowerer::implementation(&mut this, kind: u32, method: u32, trait_kind: u32): u32 {
# A property's accessor is found through the property of its name.
var name: u32 = this.checker.decls.names.p[method];
val setter := this.checker.decls.has(method, df::setter);
val accessor := this.checker.decls.has(method, df::accessor);
val found := this.checker.find_member(kind, name);
return 0 if found.decl == 0;
if accessor {
return 0 if this.checker.decls.kinds.p[found.decl] != dk::property;
val run: u32 = this.checker.decls.children.p[found.decl];
for i in 0..this.checker.decls.list_length(run) {
val each := this.checker.decls.list_at(run, i as u32);
return each if this.checker.decls.has(each, df::setter) == setter;
}
return 0;
}
# Of overloads, the one with the method's shape, in terms of the trait's
# arguments, as a pack it takes is the parameters of its types: as many
# parameters, and `&mut this` where it takes it, or else `&this`, which meets
# it too.
this.checker.resolve(method);
val asked := this.checker.requirement_type(method, this.checker.bound_for(trait_kind, this.trait_of_method(method)), kind);
val wanted := this.checker.types.part_count(asked);
var first: u32 = 0;
var counted: u32 = 0;
var walk := this.checker.decls.walk_overloads(found.decl);
while true {
val at := walk.next();
break if at == 0;
if this.checker.decls.kinds.p[at] == dk::function && this.checker.decls.has(at, df::method) {
this.checker.resolve(at);
val count := this.checker.types.part_count(this.checker.decls.types.p[at]);
if first == 0 {
first = at;
}
if count == wanted && counted == 0 {
counted = at;
}
if count == wanted && this.checker.decls.has(at, df::mut_this) == this.checker.decls.has(method, df::mut_this) {
return at;
}
}
}
return counted != 0 ? counted : first;
}
#! The map a reference to one trait becomes one to another by, made where it is
#! new, and filled once every vtable is made.
#! @param this The compiler.
#! @param from The trait's type converted from.
#! @param to The trait's type converted to.
#! @returns The map's index.
pub def lowerer::retrait_of(&mut this, from: u32, to: u32): u32 {
val key := pair_key(from, to);
if this.retrait_ids.get(&key) is some(got) {
return got;
}
val index := this.program.retraits.length as u32;
this.program.retraits.append(retrait { from = from, to = to, vtables = vector::<u32>::new() });
this.retrait_ids.set(key, index);
return index;
}
#! Fills each map between traits with the vtable each vtable of its trait
#! becomes, once the code is lowered. Making a vtable of a trait converted to
#! may make more, so every map is settled before any is filled.
#! @param this The compiler.
pub def lowerer::fill_retraits(&mut this): void {
return if this.program.retraits.length == 0;
var done: u64 = 0;
while done < this.program.vtables.length {
val count := this.program.vtables.length;
for v in done..count {
for i in 0..this.program.retraits.length {
val from: u32 = this.program.retraits[i].from;
val to: u32 = this.program.retraits[i].to;
if this.program.vtables[v].trait_id == from {
this.vtable_of(this.program.vtables[v].type_id, to);
}
}
}
done = count;
}
for i in 0..this.program.retraits.length {
var map := vector::<u32>::new();
for v in 0..this.program.vtables.length {
val held_trait: u32 = this.program.vtables[v].trait_id;
if held_trait == this.program.retraits[i].from {
map.append(this.vtable_of(this.program.vtables[v].type_id, this.program.retraits[i].to));
} else {
map.append(0);
}
}
this.program.retraits[i].vtables = move(&mut map);
}
}
#! The C function a declaration of an `extern module` without a body calls,
#! among those the program links, found by its name in its file's libraries.
#! @param this The compiler.
#! @param decl The declaration.
#! @returns The C function's index.
pub def lowerer::linked_of(&mut this, decl: u32): u32 {
if this.linked_ids.get(&decl) is some(got) {
return got;
}
val index := this.program.linked.length as u32;
var libraries := this.libraries_of(decl);
var first := libraries.length != 0 ? string::copy_of(&libraries[0]) : string::new(nothing {});
this.program.linked.append(linked {
name = this.checker.decls.names.p[decl],
library = move(&mut first),
libraries = move(&mut libraries),
decl = decl
});
this.linked_ids.set(decl, index);
return index;
}
#! The libraries a C function may be found in: those its file's `extern import`s
#! name for the target, or none for one the running program has.
#! @param this The lowerer.
#! @param decl The function's declaration.
#! @returns The libraries.
def lowerer::libraries_of(&mut this, decl: u32): vector<string> {
var libraries := vector::<string>::new();
val file: u32 = this.checker.decls.files.p[decl];
val saved := this.checker.at;
this.checker.use_table(this.checker.units[file].table);
for &each in this.checker.libraries {
continue if (each >> 32) as u32 != file;
val written := this.checker.text_of(this.checker.left_of(each as u32));
var text := string::new(nothing {});
this.checker.decode_text(written.substr(1, written.length < 2 ? 0 : written.length - 2), &mut text);
libraries.append(move(&mut text));
}
this.checker.at = saved;
return libraries;
}
#! The function type as the code of a function takes its parameters: a variadic
#! one's last as a view of what it is given.
#! @param this The compiler.
#! @param kind The function type.
#! @returns The type.
pub def lowerer::call_type(&mut this, kind: u32): u32 {
val plain := this.checker.unalias(kind);
val count := this.checker.types.part_count(plain);
return plain if this.checker.types.kind_of(plain) != ty::function || this.checker.types.second_of(plain) == 0 || count == 0;
var params := this.checker.types.parts_of(plain);
val last: u32 = params.last();
if this.checker.types.kind_of(last) != ty::pack {
params.last() = this.checker.span_of(last);
}
return this.checker.types.function(params.view(), this.checker.types.first_of(plain), false);
}
+699
View File
@@ -0,0 +1,699 @@
#! @file emitter.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the emitter, which lowers one function's body to intermediate code:
#! where each local is held, the scopes that close them, the values a
#! statement makes that close and no place owns yet, and the cells of the
#! frame what is held in memory lives in. What it does with each part of the
#! language is split across the files of the `emitter` directory.
import sakura::analyzer;
import std::containers;
module sakura::compiler;
#! A value as lowering holds it: the words it is, or the address of the memory
#! holding it, which a struct, union, or fixed array is held in.
pub struct operand {
var kind: u32; #! Its type.
var count: u32; #! How many words it is, where it is held as words.
var words: u32[2]; #! Its words.
var address: u32; #! The address of its memory, where it is held there, or 0.
}
#! Where a value is: in variables of the builder, or in memory.
pub struct location {
var kind: u32; #! The type of what is there.
var held: bool; #! Whether it is in variables rather than memory.
var vars: u32[2]; #! The variable of each word, where it is in variables.
var address: u32; #! The address its memory is reached from.
var offset: u64; #! How many bytes past the address it is.
var framed: bool; #! Whether the memory is in the frame, which a reference to it refers to while the frame lasts.
}
#! How a local is held.
pub enum held_as : u8 {
words, #! As the values of variables, where it is a word or a few.
cell, #! In a cell of the frame, where it is in memory or referred to.
}
#! A local the emitter knows: a variable, a parameter, or a name a test or a
#! loop gives.
pub struct local_info {
var node: u32; #! The node declaring it.
var place: location; #! Where it is.
var closes: bool; #! Whether it is closed where its scope ends.
var pack: u32; #! Of a pack, the first of its values in `packs`, and `count` how many.
var count: u32; #! Of a pack, how many values it holds.
var record: u32; #! One more than its variable among the code's, or 0.
var checks: bool; #! Whether it is an `ensures`, which is checked where its scope ends rather than closed.
}
#! A value a statement made that closes and no place owns, which the statement
#! closes where it ends, where the flag says it was made.
pub struct kept_value {
var address: u32; #! The address of its memory.
var cell: u32; #! One more than the cell holding it, whose address is taken again where it closes, or 0.
var kind: u32; #! Its type.
var flag: u32; #! The variable saying whether it was made, 1, or not, 0.
}
#! A loop being lowered, which `break` and `continue` leave.
pub struct loop_info {
var exit: u32; #! The block `break` goes to.
var next: u32; #! The block `continue` goes to.
var locals: u64; #! How many locals there were before its body, which a jump out of it closes past.
var kept: u64; #! How many kept values there were before its body, which a jump out of it closes past.
}
#! The call whose defaults are being made, which a default asks where it is,
#! or the text of what it was given.
pub struct default_site {
var node: u32; #! The call, or 0 where no default is being made.
var file: u32; #! The file the call is in.
var table: u32; #! The result table its nodes' results are in.
var args: u32; #! The run of the arguments it writes.
var params: u32; #! The run of the parameters of the function it calls.
var skip: u32; #! How many parameters come before the first argument, as `this`.
}
#! The emitter.
pub struct emitter {
var c: &mut lowerer; #! The compiler.
var build: builder; #! What builds the code.
var function: u32; #! The function being lowered.
var table: u32; #! The result table its nodes' results are in.
var result: u32; #! The type its `return` gives.
var locals: vector<local_info>;#! The locals in scope, the innermost last.
var local_ids: scoped_dict<u64, u32>; #! One more than the local each node declares, by its file and node, a change for each local in scope.
var packs: vector<location>; #! The values packs hold.
var kept: vector<kept_value>;#! The values made that close, which no place owns yet.
var loops: vector<loop_info>; #! The loops around what is lowered, the innermost last.
var storage: dict<u32, held_as>;#! How each local is held, by the node declaring it, where it is not in variables.
var free: vector<u32>; #! The temporary cells free to be taken again.
var lanes_cells: vector<bool>; #! Whether each cell is a temporary holding a vector, which only another vector takes again, so the cell is promoted to a vector, not words.
var taken: vector<u32>; #! The temporary cells taken by the statements being lowered.
var held: vector<u32>; #! The temporary cells holding kept values, freed once the values are closed or taken.
var named: dict<u32, u64>; #! Of each variable of the builder holding a word of a named local, the local's variable among the code's, then which word, as `variable << 8 | word`.
var defaulting: default_site; #! The call whose defaults are being made.
var returned: operand; #! What a `return` gives, while the `ensures` it leaves are checked.
var returning: bool; #! Whether a `return` giving a value is closing what it leaves.
}
#! Makes an emitter of a function.
#! @param c The compiler.
#! @param function The function.
#! @returns The emitter, whose builder takes the function's parameters.
pub def emitter::new(c: &mut lowerer, function: u32): emitter {
val signature: u32 = c.program.functions[function].signature;
var params := c.param_types(signature);
val result := c.layout_at(c.program.signatures[signature].result);
# A closure is given its environment, a reference to what it captures.
if c.program.functions[function].closure {
params.append(vt::word);
}
var made := emitter {
c = c,
build = builder::new(params.view()),
function = function,
locals = vector::<local_info>::new(scratch()),
local_ids = scoped_dict::<u64, u32>::new(scratch()),
packs = vector::<location>::new(scratch()),
kept = vector::<kept_value>::new(scratch()),
loops = vector::<loop_info>::new(scratch()),
storage = dict::<u32, held_as>::new(scratch()),
free = vector::<u32>::new(scratch()),
lanes_cells = vector::<bool>::new(scratch()),
taken = vector::<u32>::new(scratch()),
held = vector::<u32>::new(scratch()),
named = dict::<u32, u64>::new(scratch())
};
if !in_memory(&result) {
for _ in 0..word_count(&result) {
made.build.code.results.append(word_type(&result));
}
} else {
made.build.code.returned = result.size as u32;
}
return made;
}
#! Finishes the code lowered and gives it to the function, verifying it where
#! the options ask.
#! @param this The emitter.
pub def emitter::finish(&mut this): void {
var body := this.build.finish();
body.vectors = !this.c.options.evaluating && this.c.checker.names.text(this.c.checker.target.backend) == "native";
if this.c.options.verify {
val verdict := body.verify();
for &each in verdict.problems {
this.c.problems.append($"{this.c.program.functions[this.function].name}: {each}");
}
}
this.c.program.functions[this.function].body = move(&mut body);
}
#! Makes the function's result table the one the checker reads results from.
#! @param this The emitter.
pub def emitter::use_own_table(&mut this): void {
this.c.checker.use_table(this.table);
}
#! Notes what lowering could not lower, at a node.
#! @param this The emitter.
#! @param node The node.
#! @param what What it is, said in words.
pub def emitter::problem(&mut this, node: u32, what: strview): void {
if node == 0 {
this.c.problems.append($"{this.c.program.functions[this.function].name}: {what}");
return;
}
this.c.problem(this.c.checker.at.file, node, what);
}
#! Says where in the source the instructions added next are from.
#! @param this The emitter.
#! @param node The node they are lowered from.
pub def emitter::at_node(&mut this, node: u32): void {
return if node == 0;
this.build.pos = this.place_at(node);
}
#! Where in the source a node is, as instructions and variables say: one more
#! than its file above its byte.
#! @param this The emitter.
#! @param node The node.
#! @returns Where.
def emitter::place_at(&this, node: u32): u64 {
val file := this.c.checker.at.file;
return pair_key(file + 1, this.c.node_offset(file, node));
}
# Operands.
#! A value of no words, as `void` is.
#! @param kind The type.
#! @returns The operand.
pub def operand::none(kind: u32): operand {
return operand { kind = kind };
}
#! A value of one word.
#! @param kind The type.
#! @param word The word.
#! @returns The operand.
pub def operand::one(kind: u32, word: u32): operand {
var made := operand { kind = kind, count = 1 };
made.words[0] = word;
return made;
}
#! A value of two words, as a reference to a trait or a function is.
#! @param kind The type.
#! @param a The first word.
#! @param b The second.
#! @returns The operand.
pub def operand::two(kind: u32, a: u32, b: u32): operand {
var made := operand { kind = kind, count = 2 };
made.words[0] = a;
made.words[1] = b;
return made;
}
#! A value held in memory.
#! @param kind The type.
#! @param address The address of its memory.
#! @returns The operand.
pub def operand::at(kind: u32, address: u32): operand {
return operand { kind = kind, address = address };
}
#! The values of the code an operand gives where it is passed: its words, or
#! the address of its memory.
#! @param this The operand.
#! @param into Where they are appended.
pub def operand::args(&this, into: &mut vector<u32>): void {
if this.address != 0 {
into.append(this.address);
return;
}
for i in 0..this.count {
into.append(this.words[i]);
}
}
# Cells.
#! A temporary cell of a size, which the statement taking it holds until it
#! ends: one taken before and freed since where one fits.
#! @param this The emitter.
#! @param size How many bytes it holds.
#! @param align What its address is a multiple of.
#! @returns The cell.
pub def emitter::temporary(&mut this, size: u64, align: u64): u32 {
return this.temporary_for(size, align, false);
}
#! A temporary cell, as `temporary` gives, holding a vector or not: a cell is
#! taken again only for what it held before, a vector or not.
#! @param this The emitter.
#! @param size How many bytes it holds.
#! @param align What its address is a multiple of.
#! @param lanes Whether it holds a vector.
#! @returns The cell.
def emitter::temporary_for(&mut this, size: u64, align: u64, lanes: bool): u32 {
val wanted := round_up(size == 0 ? word_size : size, word_size) as u32;
val aligned := (align < word_size ? word_size : align) as u32;
for i in 0..this.free.length {
val cell: u32 = this.free[i];
val held: cell = this.build.code.cells[cell];
val vector := (cell as u64) < this.lanes_cells.length && this.lanes_cells[cell];
if held.size == wanted && held.align >= aligned && vector == lanes {
this.free.remove_at(i);
this.taken.append(cell);
return cell;
}
}
val made := this.build.code.add_cell(wanted, aligned, ck::temporary, 0);
if lanes {
this.lanes_cells.resize(made as u64 + 1);
this.lanes_cells[made] = true;
}
this.taken.append(made);
return made;
}
#! A temporary cell holding a value of a type, and its address.
#! @param this The emitter.
#! @param kind The type.
#! @returns The address of the cell.
pub def emitter::temporary_of(&mut this, kind: u32): u32 {
val held := this.c.shape_of(kind);
return this.build.cell_address(this.temporary_for(held.size, held.align, this.c.checker.is_lanes_type(kind)));
}
#! How many temporary cells the statements being lowered have taken, which
#! `release` frees those taken since.
#! @param this The emitter.
#! @returns The mark.
pub def emitter::cell_mark(&this): u64 {
return this.taken.length;
}
#! Frees the temporary cells taken since a mark, to be taken again.
#! @param this The emitter.
#! @param mark How many were taken before.
pub def emitter::release(&mut this, mark: u64): void {
while this.taken.length > mark {
val cell: u32 = this.taken.last();
this.taken.truncate();
# A cell holding a value the statement still closes is held until it does.
var kept := false;
for &each in this.kept {
kept = kept || each.cell == cell + 1;
}
if kept {
this.held.append(cell);
} else {
this.free.append(cell);
}
}
}
#! Frees the cell a kept value was held in, once it is closed or a place took
#! it, where the statement's cells were released before.
#! @param this The emitter.
#! @param cell One more than the cell, or 0.
def emitter::unhold(&mut this, cell: u32): void {
return if cell == 0;
for i in 0..this.held.length {
if this.held[i] == cell - 1 {
this.held.remove_at(i);
this.free.append(cell - 1);
return;
}
}
}
# Locals.
#! The local a node of the file being read declares, or none. A local is
#! known by its file as well as its node, since the defaults of a call name the
#! parameters of a function of another file, whose nodes are counted apart, as
#! the arguments written for them name the caller's locals.
#! @param this The emitter.
#! @param node The node.
#! @returns One more than the local's index, or 0.
pub def emitter::local_of(&this, node: u32): u32 {
return this.local_ids.get_or(&pair_key(this.c.checker.at.file, node), 0);
}
#! Declares a local where it is.
#! @param this The emitter.
#! @param node The node declaring it.
#! @param place Where it is.
#! @param closes Whether it is closed where its scope ends.
#! @returns The local's index.
pub def emitter::declare(&mut this, node: u32, place: location, closes: bool): u32 {
val index := this.locals.length as u32;
this.locals.append(local_info {
node = node,
place = place,
closes = closes,
record = this.describe(node, &place)
});
this.local_ids.set(pair_key(this.c.checker.at.file, node), index + 1);
return index;
}
#! Notes a local as a variable debugging information shows, where it is named
#! and held in memory: in a cell, or the copy of a parameter given as memory.
#! Where locals are kept for debugging information, one in an object of the
#! heap is too, whose address a cell is given to hold.
#! @param this The emitter.
#! @param node The node declaring it.
#! @param place Where it is.
#! @returns One more than the variable among the code's, or 0.
def emitter::describe(&mut this, node: u32, place: &location): u32 {
return 0 if node == 0 || place.held || place.address == 0 || place.offset != 0;
val name := this.c.checker.param_name(node);
return 0 if name == 0;
val at := this.place_at(node);
val param := this.c.checker.kind_of(node) == nk::param;
val held: origin = this.build.code.origins[place.address];
var cell: u32 = 0;
var given: u32 = 0;
if held.param {
return 0 if held.from != 0 || !place.framed;
given = held.index + 1;
} else if this.build.code.insts[held.from].kind == op::cell {
cell = this.build.code.insts[held.from].aux + 1;
} else {
return 0;
}
# Optimized code notes them only for debugging information.
return 0 if !this.c.options.keep_locals && !this.c.options.describe;
this.build.code.variables.append(variable_info {
name = name, at = at, kind = place.kind, cell = cell, given = given, param = param,
first = this.build.code.insts.length as u32
});
return this.build.code.variables.length as u32;
}
#! Notes a local held in values as a variable debugging information shows,
#! where it is named: one in variables of the builder, which each value they
#! are given binds.
#! @param this The emitter.
#! @param node The node declaring it.
#! @param place Where it is.
#! @param words How many words it is.
def emitter::describe_held(&mut this, node: u32, place: &location, words: u64): void {
return if !this.c.options.describe;
val name := this.c.checker.param_name(node);
return if name == 0;
val at := this.place_at(node);
val param := this.c.checker.kind_of(node) == nk::param;
val index := this.build.code.variables.length as u32;
this.build.code.variables.append(variable_info {
name = name, at = at, kind = place.kind, param = param, held = true
});
for i in 0..words {
this.named.set(place.vars[i], (index as u64 << 8) | i);
}
}
#! Binds a named local to a value given a variable of the builder holding one
#! of its words, where it is one.
#! @param this The emitter.
#! @param held The variable of the builder.
#! @param value The value.
pub def emitter::bind(&mut this, held: u32, value: u32): void {
if this.named.get(&held) is some(found) {
this.bind_word((found >> 8) as u32, (found & 0xFF) as u32, value);
}
}
#! Binds a word of a variable held in values to a value, where the code being
#! built is.
#! @param this The emitter.
#! @param variable The variable, among the code's.
#! @param word Which of its words.
#! @param value The value.
def emitter::bind_word(&mut this, variable: u32, word: u32, value: u32): void {
val block := this.build.at;
this.build.code.bindings.append(binding {
variable = variable, word = word, value = value, after = this.build.code.blocks[block].last, block = block
});
}
#! Makes a place for a local of a type declared by a node, held as the storage
#! worked out for it says: in variables, or a cell.
#! @param this The emitter.
#! @param node The node declaring it.
#! @param kind Its type.
#! @param cells The kind of cell it takes where it takes one: `undefined` for
#! one the frame leaves as it is.
#! @returns Where it is.
pub def emitter::new_place(&mut this, node: u32, kind: u32, cells: ck = ck::local): location {
val held := this.c.shape_of(kind);
var how := this.storage.get_or(&node, held_as::words);
if in_memory(&held) && how == held_as::words {
how = held_as::cell;
}
if this.c.options.keep_locals && how == held_as::words && word_count(&held) != 0 {
how = held_as::cell;
}
match how {
held_as::cell => {
val name := this.c.checker.name_of(node);
val made := this.build.code.add_cell(round_up(held.size == 0 ? word_size : held.size, word_size) as u32,
held.align < word_size ? word_size as u32 : held.align as u32, cells, name);
return location { kind = kind, address = this.build.cell_address(made), framed = true };
}
else => {
var place := location { kind = kind, held = true };
for i in 0..word_count(&held) {
place.vars[i] = this.build.variable(word_type(&held));
}
if !this.c.options.keep_locals {
this.describe_held(node, &place, word_count(&held));
}
return place;
}
}
return location { kind = kind };
}
#! How many locals are in scope, which `end_scope` closes those declared since.
#! @param this The emitter.
#! @returns The mark.
pub def emitter::scope_mark(&this): u64 {
return this.locals.length;
}
#! Closes the locals declared since a mark, in the reverse of the order they
#! were declared, but the one given back by name, and ends their scope.
#! @param this The emitter.
#! @param mark How many were in scope before.
#! @param given The node of a local given back by name, which is not closed, or
#! 0.
pub def emitter::end_scope(&mut this, mark: u64, given: u32): void {
this.close_locals(mark, given);
this.forget_locals(mark);
}
#! Ends the scope of the locals declared since a mark, without closing them.
#! @param this The emitter.
#! @param mark How many were in scope before.
pub def emitter::forget_locals(&mut this, mark: u64): void {
# Each local set the node declaring it once, so taking back the changes
# since the mark gives each node the local it named before.
while this.locals.length > mark {
val record: u32 = this.locals.last().record;
if record != 0 {
this.build.code.variables[record as u64 - 1].end = this.build.code.insts.length as u32;
}
this.locals.truncate();
}
this.local_ids.rewind(mark);
}
#! Closes the locals declared since a mark that close, in the reverse of the
#! order they were declared, so each is closed while everything it was built
#! from still stands, but the one given back by name.
#! @param this The emitter.
#! @param mark How many were in scope before.
#! @param given The node of a local given back by name, or 0.
pub def emitter::close_locals(&mut this, mark: u64, given: u32): void {
var at := this.locals.length;
while at > mark {
at--;
val held: local_info = this.locals[at];
continue if !held.closes || held.node == given;
if held.checks {
this.check_ensures(held.node);
continue;
}
# A pack closes each of its values, the last first.
if held.count != 0 {
var k := held.count;
while k > 0 {
k--;
val each: location = this.packs[held.pack as u64 + k as u64];
this.close(&each);
}
continue;
}
this.close(&held.place);
}
}
# Kept values.
#! Keeps a value a statement made that closes, which no place owns yet, so the
#! statement closes it where it ends unless a place takes it first.
#! @param this The emitter.
#! @param value The value, held in memory.
pub def emitter::keep(&mut this, value: &operand): void {
return if value.address == 0 || !this.c.checker.closes(value.kind);
for &each in this.kept {
return if each.address == value.address;
}
val flag := this.build.variable(vt::word);
this.build.assign(flag, this.build.word(1));
# It may be made down one branch of the statement, and closed where they join,
# so the address of the cell holding it is taken again there.
var cell: u32 = 0;
val held: origin = this.build.code.origins[value.address];
if !held.param && this.build.code.insts[held.from].kind == op::cell {
cell = this.build.code.insts[held.from].aux + 1;
}
this.kept.append(kept_value { address = value.address, cell = cell, kind = value.kind, flag = flag });
}
#! Says a place took a kept value, so the statement no longer closes it.
#! @param this The emitter.
#! @param value The value.
pub def emitter::adopt(&mut this, value: &operand): void {
return if value.address == 0;
var at := this.kept.length;
while at > 0 {
at--;
if this.kept[at].address == value.address {
val cell: u32 = this.kept[at].cell;
this.kept.remove_at(at);
this.unhold(cell);
return;
}
}
}
#! Closes the values kept since a mark, in the reverse of the order they were
#! made, each where it was made on the way here, and forgets them.
#! @param this The emitter.
#! @param mark How many were kept before.
pub def emitter::close_kept(&mut this, mark: u64): void {
this.leave_kept(mark);
while this.kept.length > mark {
val cell: u32 = this.kept.last().cell;
this.kept.truncate();
this.unhold(cell);
}
}
#! Forgets the values kept since a mark without closing them, where the program
#! stops before they would be.
#! @param this The emitter.
#! @param mark How many were kept before.
pub def emitter::drop_kept(&mut this, mark: u64): void {
while this.kept.length > mark {
val cell: u32 = this.kept.last().cell;
this.kept.truncate();
this.unhold(cell);
}
}
#! Closes the values kept since a mark, each where it was made on the way here,
#! without forgetting them, as a jump out of the statements keeping them does.
#! @param this The emitter.
#! @param mark How many were kept before.
pub def emitter::leave_kept(&mut this, mark: u64): void {
var at := this.kept.length;
while at > mark {
at--;
val held: kept_value = this.kept[at];
val made := this.build.read(held.flag);
# Each close forgets it was made, so a jump in a later pass of a loop, taken
# before it is made again, does not close it twice.
if this.is_one(made) {
val place := location { kind = held.kind, address = held.address, framed = true };
this.close(&place);
this.build.assign(held.flag, this.build.word(0));
continue;
}
val closing := this.build.new_block();
val after := this.build.new_block();
this.build.branch(made, closing, after);
this.build.seal(closing);
this.build.switch_to(closing);
val address := held.cell != 0 ? this.build.cell_address(held.cell - 1) : held.address;
val place := location { kind = held.kind, address = address, framed = true };
this.close(&place);
this.build.assign(held.flag, this.build.word(0));
this.build.jump(after);
this.build.seal(after);
this.build.switch_to(after);
}
}
#! Whether a value is the word 1, made where it is known to be.
#! @param this The emitter.
#! @param value The value.
#! @returns Whether it is.
pub def emitter::is_one(&this, value: u32): bool {
val held: origin = this.build.code.origins[value];
return false if held.param;
val made: inst = this.build.code.insts[held.from];
return made.kind == op::iconst && made.imm == 1;
}
# Statements.
#! What a statement holds while it is lowered, which it lets go of once it ends.
pub struct statement_mark {
var cells: u64; #! The temporary cells taken before it.
var kept: u64; #! The values kept before it.
}
#! Begins a statement.
#! @param this The emitter.
#! @returns What it holds, as `end_statement` takes it.
pub def emitter::begin_statement(&this): statement_mark {
return statement_mark { cells = this.taken.length, kept = this.kept.length };
}
#! Ends a statement: closes what it kept, and frees the cells it took.
#! @param this The emitter.
#! @param mark What it held, as `begin_statement` gave it.
pub def emitter::end_statement(&mut this, mark: statement_mark): void {
this.close_kept(mark.kept);
this.release(mark.cells);
}
#! A safe point, where the handlers of the signals that have come run. Only a
#! program handling a signal has them, and only in its own functions, at the
#! start of each and of each pass of each loop, so a handler never finds a
#! container of std in the middle of a change.
#! @param this The emitter.
pub def emitter::safepoint(&mut this): void {
return if this.c.dispatch == no_function;
val held := &this.c.program.functions[this.function];
val decl: u32 = held.decl != 0 ? held.decl : held.outer;
return if decl == 0 || held.builtin != 0 || this.c.in_std(decl);
this.build.effect(op::safepoint, span::<u32>::empty(), this.c.dispatch, 0);
}
+253
View File
@@ -0,0 +1,253 @@
#! @file bodies.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the lowering of a function's body: where its parameters are, its
#! statements, and how it returns, closing its parameters as it does.
import sakura::analyzer;
module sakura::compiler;
#! Lowers the function the emitter is of.
#! @param this The emitter.
pub def emitter::lower(&mut this): void {
val decl: u32 = this.c.program.functions[this.function].decl;
val instance: u32 = this.c.program.functions[this.function].instance;
val lambda: u32 = this.c.program.functions[this.function].node;
if this.c.program.functions[this.function].adapted != 0 {
this.lower_adapter();
return;
}
if lambda != 0 {
this.lower_lambda(lambda);
return;
}
if this.c.program.functions[this.function].builtin != 0 {
this.lower_builtin();
return;
}
val evaluation: u32 = this.c.program.functions[this.function].evaluation;
if evaluation != 0 {
this.lower_evaluation(evaluation - 1);
return;
}
if decl == 0 {
this.build.unreachable();
return;
}
val table := this.c.body_table(decl, instance);
if instance != 0 && this.c.checker.instances[instance - 1].table == 0 {
this.c.checker.use_table(table);
this.problem(this.c.checker.decls.nodes.p[decl], "The instance's body was never checked.");
this.build.unreachable();
return;
}
this.table = table;
this.use_own_table();
val node: u32 = this.c.checker.decls.nodes.p[decl];
val accessor := this.c.checker.decls.has(decl, df::accessor);
val body := accessor ? this.c.checker.record(node, accessor_slot::body) : this.c.checker.record(node, function_slot::body);
val params := accessor ? this.c.checker.left_of(node) : this.c.checker.record(node, function_slot::params);
val kind := this.c.type_of_function(decl, instance);
this.at_node(node);
this.result = this.c.checker.types.first_of(kind);
this.plan_function(decl, params, kind, body);
this.take_params(decl, params, kind);
this.safepoint();
this.lower_body(body);
}
#! Lowers a body: a block, which ends returning nothing where control falls off
#! its end, or an expression, whose value is returned.
#! @param this The emitter.
#! @param body The body's node.
pub def emitter::lower_body(&mut this, body: u32): void {
if this.c.checker.kind_of(body) != nk::block {
val mark := this.begin_statement();
this.at_node(body);
if this.c.checker.types.kind_of(this.c.layout_type(this.result)) == ty::void_type {
this.value(body);
this.end_statement(mark);
this.close_locals(0, 0);
this.build.ret(span::<u32>::empty());
return;
}
this.return_value(body, mark);
return;
}
this.lower_block(body);
return if this.build.ended();
# Running off the end returns, which a function giving a value never does.
if this.c.checker.types.kind_of(this.c.layout_type(this.result)) == ty::void_type {
this.close_locals(0, 0);
this.build.ret(span::<u32>::empty());
return;
}
this.build.trap(fault::unreachable as u32);
}
#! Takes the function's parameters where its code is given them: each as a
#! local, held as its storage says, and a pack's as one local holding each.
#! @param this The emitter.
#! @param decl The function's declaration.
#! @param params The run of its parameters' nodes.
#! @param kind Its function type, given its type arguments.
def emitter::take_params(&mut this, decl: u32, params: u32, kind: u32): void {
val signature: u32 = this.c.program.functions[this.function].signature;
val count := this.c.checker.run_length(params);
var next: u32 = 0;
# A pack parameter takes every parameter from its own on, one value of each.
val written: u32 = this.c.checker.decls.types.p[decl];
val wcount := this.c.checker.types.part_count(written);
val packed := this.c.checker.decls.has(decl, df::variadic) && wcount != 0
&& this.c.checker.types.is_open_pack(this.c.checker.types.part_at(written, wcount - 1));
val total := this.c.program.signatures[signature].params.length as u32;
for i in 0..count {
val node := this.c.checker.run_at(params, i as u32);
if packed && i as u32 + 1 == count {
val first := this.packs.length as u32;
for p in i as u32..total {
val held := this.take_param(signature, p, &mut next);
val place := this.param_place(0, held);
this.packs.append(place);
}
val index := this.declare(node, location { kind = this.c.checker.type_at(node) }, true);
this.locals[index].pack = first;
this.locals[index].count = this.packs.length as u32 - first;
continue;
}
break if i as u32 >= total;
val held := this.take_param(signature, i as u32, &mut next);
val place := this.param_place(node, held);
this.declare(node, place, this.c.checker.closes(held.kind));
}
}
#! A parameter as the code is given it: its words, or the address of the
#! function's own copy of it.
#! @param this The emitter.
#! @param signature The function's signature.
#! @param index The parameter's position.
#! @param next The first of the code's parameters not yet taken, moved
#! past those of this one.
#! @returns The parameter's value.
def emitter::take_param(&mut this, signature: u32, index: u32, next: &mut u32): operand {
val layout_index: u32 = this.c.program.signatures[signature].params[index];
val shape := this.c.layout_at(layout_index);
val kind := shape.type_id;
if in_memory(&shape) {
val address := this.build.param(next);
next++;
return operand::at(kind, address);
}
var made := operand { kind = kind, count = word_count(&shape) };
for i in 0..made.count {
made.words[i] = this.build.param(next);
next++;
}
return made;
}
#! Where a parameter is held: in memory it was given, or its own copy, as its
#! storage says where it is referred to.
#! @param this The emitter.
#! @param node The parameter's node, or 0 for a value of a pack.
#! @param held Its value.
#! @returns Where it is.
def emitter::param_place(&mut this, node: u32, held: operand): location {
if held.address != 0 {
return location { kind = held.kind, address = held.address, framed = true };
}
val place := node != 0 ? this.new_place(node, held.kind) : this.fresh_place(held.kind);
this.store(&place, &held);
return place;
}
#! A place for a value of a type that no node declares, as each value of a
#! pack: in variables, or a cell where it is in memory.
#! @param this The emitter.
#! @param kind The type.
#! @returns Where it is.
pub def emitter::fresh_place(&mut this, kind: u32): location {
val held := this.c.shape_of(kind);
if in_memory(&held) {
val made := this.build.code.add_cell(round_up(held.size == 0 ? word_size : held.size, word_size) as u32,
held.align < word_size ? word_size as u32 : held.align as u32, ck::local, 0);
return location { kind = kind, address = this.build.cell_address(made), framed = true };
}
var place := location { kind = kind, held = true };
for i in 0..word_count(&held) {
place.vars[i] = this.build.variable(word_type(&held));
}
return place;
}
#! Lowers `return value;`: the value is made, or the local it names handed
#! over, everything the statements and scopes around it hold is closed, and the
#! function returns.
#! @param this The emitter.
#! @param node The value's node.
#! @param mark What the statement held before the value.
pub def emitter::return_value(&mut this, node: u32, mark: statement_mark): void {
var made := this.value_as(node, this.result);
# Returning a local by name hands it over, so it is not closed.
var given: u32 = 0;
if this.c.checker.kind_of(node) == nk::name {
val ref := this.c.checker.ref_at(node);
if (ref & ref_local) != 0 {
given = ref & ref_mask;
}
}
this.return_made(&mut made, given, mark);
}
#! Ends the function returning a value made, closing what the statement made and
#! what the function's locals hold, all but the local handed over.
#! @param this The emitter.
#! @param made The value returned.
#! @param given The local the value is, handed over rather than closed, or 0.
#! @param mark Where the statement began.
pub def emitter::return_made(&mut this, made: &mut operand, given: u32, mark: statement_mark): void {
this.adopt(made);
# What the statement made closes, and what the statements around it made too,
# which they still close down the paths that do not return. The cells it took
# are freed only once the closing is lowered, which might take them otherwise.
var args := vector::<u32>::new();
made.args(&mut args);
this.close_kept(mark.kept);
this.leave_kept(0);
# An `ensures` naming what is returned reads it as the locals close.
this.returned = made;
this.returning = true;
this.close_locals(0, given);
this.returning = false;
this.release(mark.cells);
this.give_back(args.view());
}
#! Ends the block returning what the function gives: its words, or the address
#! of what it gives in memory, and nothing where that has no bytes, as a struct
#! of no fields.
#! @param this The emitter.
#! @param args The words, or the address.
pub def emitter::give_back(&mut this, args: span<u32>): void {
if this.build.code.results.length == 0 && this.build.code.returned == 0 {
this.build.ret(span::<u32>::empty());
return;
}
this.build.ret(args);
}
+310
View File
@@ -0,0 +1,310 @@
#! @file builtins.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the methods the compiler gives the built-in types, which make
#! numbers, `bool`, enums, and pointers `equatable`, `hashable`, `ordered`, and
#! `numeric` as far as each allows: written where they are called, and made
#! functions of their own where a vtable names them.
import sakura::analyzer;
module sakura::compiler;
#! A call of a method the compiler gives a built-in type, on the value it is
#! called on and the other operand.
#! @param this The emitter.
#! @param node The `call` node.
#! @returns What it gives.
pub def emitter::builtin_call(&mut this, node: u32): operand {
val callee := this.c.checker.left_of(node);
val object := this.c.checker.left_of(callee);
val name := this.c.checker.name_of(callee);
# `f.invoke(args)` calls the function, or the C function, the value is.
if name == word::invoke {
val made := this.value_of_type(object);
val function := this.through_references(&made);
var given := gathered { values = vector::<operand>::new() };
this.gather(node, 0, 0, this.called_type(function.kind), 0, &mut given);
return this.call_function_value(&function, &given);
}
# A fixed array is compared and hashed element by element, where it is.
val reached := this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(object)));
if this.c.checker.types.kind_of(reached) == ty::fixed {
val whole := this.object(object);
val first := this.address_of(&whole);
val result := this.c.checker.type_at(node);
if name == word::hash {
return operand::one(result, this.hash_elements(first, reached));
}
val run := this.c.checker.right_of(node);
val other := this.object(this.c.checker.run_at(run, 0));
return operand::one(result, this.equal_elements(first, this.address_of(&other), reached));
}
val made := this.value_of_type(object);
val subject := this.through_references(&made);
var other := operand {};
val run := this.c.checker.right_of(node);
if this.c.checker.run_length(run) != 0 {
val given := this.value_of_type(this.c.checker.run_at(run, 0));
other = this.through_references(&given);
other = this.convert(&other, subject.kind);
}
return this.builtin_method(name, &subject, &other, this.c.checker.type_at(node));
}
#! What a method the compiler gives a built-in type gives: `equals` compares,
#! `hash` gives the bits, as 0 for both zeros of a float, `compare` gives -1, 0,
#! or 1, and the methods of `numeric` operate.
#! @param this The emitter.
#! @param name The ID of the method's name.
#! @param a The value it is called on.
#! @param b The other operand, where it takes one.
#! @param result The type it gives.
#! @returns What it gives.
pub def emitter::builtin_method(&mut this, name: u32, a: &operand, b: &operand, result: u32): operand {
val kind := a.kind;
val floating := this.is_float(kind);
val signed := this.is_signed(kind);
if name == word::equals {
return operand::one(result, this.build.binary(floating ? op::feq : op::eq, a.words[0], b.words[0]));
}
if name == word::compare {
val less := floating ? op::flt : (signed ? op::lts : op::ltu);
val below := this.build.binary(less, a.words[0], b.words[0]);
val above := this.build.binary(less, b.words[0], a.words[0]);
return operand::one(result, this.build.binary(op::sub, above, below));
}
if name == word::hash {
if !floating {
return operand::one(result, a.words[0]);
}
# Both zeros hash as 0, and anything else as its bits, an `f32`'s as one.
val shape := this.c.shape_of(kind);
val cell := this.temporary(word_size, word_size);
val address := this.build.cell_address(cell);
this.build.store(shape.bits <= 32 ? access::f32 : access::f64, address, 0, a.words[0]);
val bits := this.build.load(shape.bits <= 32 ? access::u32 : access::i64, address, 0);
val zero := this.build.binary(op::feq, a.words[0], this.build.real(0));
val nonzero := this.build.binary(op::eq, zero, this.build.word(0));
val mask := this.build.unary(op::neg, nonzero);
return operand::one(result, this.build.binary(op::band, bits, mask));
}
if name == word::negate {
val made := this.build.unary(floating ? op::fneg : op::neg, a.words[0]);
return operand::one(result, this.normalize(made, kind));
}
if name == word::bit_not {
return operand::one(result, this.normalize(this.build.unary(op::bnot, a.words[0]), kind));
}
var chosen := op::add;
if name == word::add {
chosen = floating ? op::fadd : op::add;
} else if name == word::sub {
chosen = floating ? op::fsub : op::sub;
} else if name == word::mul {
chosen = floating ? op::fmul : op::mul;
} else if name == word::div {
chosen = floating ? op::fdiv : (signed ? op::divs : op::divu);
} else if name == word::rem {
chosen = floating ? op::frem : (signed ? op::rems : op::remu);
} else if name == word::bit_and {
chosen = op::band;
} else if name == word::bit_or {
chosen = op::bor;
} else if name == word::bit_xor {
chosen = op::bxor;
} else if name == word::shift_left {
chosen = op::shl;
} else if name == word::shift_right {
chosen = signed ? op::shrs : op::shru;
}
return operand::one(result, this.normalize(this.build.binary(chosen, a.words[0], b.words[0]), kind));
}
#! The function giving a built-in type a method, as a vtable names it, made
#! where it is new: it takes `this` and the other operand by reference, as the
#! method's type says.
#! @param this The compiler.
#! @param kind The built-in type.
#! @param name The ID of the method's name.
#! @returns The function's index, or `no_function` where the type has no such
#! method.
pub def lowerer::builtin_function(&mut this, kind: u32, name: u32): u32 {
val type_of := this.checker.builtin_method(kind, name);
return no_function if type_of == 0;
val key := pair_key(kind, name);
if this.builtin_ids.get(&key) is some(got) {
return got;
}
var text := string::from(this.checker.names.text(name), nothing {});
val index := this.add_function(move(&mut text), this.signature_of(this.call_type(type_of)));
this.builtin_ids.set(key, index);
this.program.functions[index].builtin = name;
this.program.functions[index].owner_type = kind;
this.want(index);
return index;
}
#! Lowers a function giving a built-in type a method.
#! @param this The emitter.
pub def emitter::lower_builtin(&mut this): void {
val name: u32 = this.c.program.functions[this.function].builtin;
val kind: u32 = this.c.program.functions[this.function].owner_type;
# `invoke` calls the function, or the C function, its `this` refers to, with
# the arguments it is given, as they are.
if name == word::invoke {
val signature: u32 = this.c.program.functions[this.function].signature;
val total := this.c.program.signatures[signature].params.length as u32;
var next: u32 = 0;
val taken := this.take_param(signature, 0, &mut next);
val place := location { kind = kind, address = taken.words[0] };
val function := this.load(&place);
var given := gathered { values = vector::<operand>::new() };
for p in 1..total {
given.values.append(this.take_param(signature, p as u32, &mut next));
}
val made := this.call_function_value(&function, &given);
var args := vector::<u32>::new();
made.args(&mut args);
this.give_back(args.view());
return;
}
if this.c.checker.types.kind_of(this.c.checker.unalias(kind)) == ty::fixed {
val plain := this.c.checker.unalias(kind);
var words: u32[1] = [0];
if name == word::hash {
words[0] = this.hash_elements(this.build.param(0), plain);
} else {
words[0] = this.equal_elements(this.build.param(0), this.build.param(2), plain);
}
this.build.ret(words[0:1]);
return;
}
val first := location { kind = kind, address = this.build.param(0) };
val a := this.load(&first);
var b := operand {};
if this.c.program.signatures[this.c.program.functions[this.function].signature].params.length > 1 {
val second := location { kind = kind, address = this.build.param(2) };
b = this.load(&second);
}
val result := this.c.checker.types.first_of(this.c.checker.builtin_method(kind, name));
val made := this.builtin_method(name, &a, &b, result);
var args := vector::<u32>::new();
made.args(&mut args);
this.give_back(args.view());
}
#! Whether the elements of two fixed arrays are equal, one by one, as each
#! says it is equal: a number by its value, and a struct by its `equals`.
#! @param this The emitter.
#! @param a The address of one array.
#! @param b The address of the other.
#! @param kind The arrays' type.
#! @returns A word of 1 where they are, and 0 where not.
pub def emitter::equal_elements(&mut this, a: u32, b: u32, kind: u32): u32 {
val element := this.c.checker.types.first_of(kind);
val count := this.c.checker.types.second_of(kind) as u64;
val size := this.c.shape_of(element).size;
val same := this.build.variable(vt::word);
val index := this.build.variable(vt::word);
this.build.assign(same, this.build.word(1));
this.build.assign(index, this.build.word(0));
val head := this.build.new_block();
val body := this.build.new_block();
val differs := this.build.new_block();
val next := this.build.new_block();
val done := this.build.new_block();
val at := this.count_up(index, count, head, body, done);
val offset := this.scaled(at, size);
val equal := this.element_equals(this.build.binary(op::add, a, offset), this.build.binary(op::add, b, offset), element);
this.build.branch(equal, next, differs);
this.build.seal(differs);
this.build.switch_to(differs);
this.build.assign(same, this.build.word(0));
this.build.jump(done);
this.build.seal(next);
this.build.switch_to(next);
this.count_on(index, head, done);
return this.build.read(same);
}
#! Whether two values of a type, at their addresses, are equal, as the type
#! says it is.
#! @param this The emitter.
#! @param a The address of one.
#! @param b The address of the other.
#! @param kind The type.
#! @returns A word of 1 where they are, and 0 where not.
def emitter::element_equals(&mut this, a: u32, b: u32, kind: u32): u32 {
val plain := this.c.checker.unalias(kind);
if this.c.checker.types.kind_of(plain) == ty::fixed {
return this.equal_elements(a, b, plain);
}
val first := location { kind = kind, address = a };
val second := location { kind = kind, address = b };
if this.c.checker.find_member(kind, word::equals).decl == 0 {
val x := this.load(&first);
val y := this.load(&second);
return this.builtin_method(word::equals, &x, &y, bt::boolean).words[0];
}
val method := this.c.checker.find_member(kind, word::equals).decl;
val reference := this.c.checker.types.reference(kind, false);
val subject := this.reference_to(&first, reference);
var others := vector::<operand>::new();
others.append(this.reference_to(&second, reference));
return this.method_call(method, kind, &subject, others.view()).words[0];
}
#! The hash of a fixed array: of its length, then each element's in turn,
#! mixed as the C compiler mixes them.
#! @param this The emitter.
#! @param a The array's address.
#! @param kind Its type.
#! @returns The hash.
pub def emitter::hash_elements(&mut this, a: u32, kind: u32): u32 {
val element := this.c.checker.types.first_of(kind);
val count := this.c.checker.types.second_of(kind) as u64;
val size := this.c.shape_of(element).size;
val code := this.build.variable(vt::word);
val index := this.build.variable(vt::word);
this.build.assign(code, this.build.word(count));
this.build.assign(index, this.build.word(0));
val head := this.build.new_block();
val body := this.build.new_block();
val done := this.build.new_block();
val at := this.count_up(index, count, head, body, done);
val each := this.element_hash(this.build.binary(op::add, a, this.scaled(at, size)), element);
val mixed := this.build.binary(op::mul, this.build.binary(op::bxor, this.build.read(code), each), this.build.word(0x9E3779B97F4A7C15));
this.build.assign(code, this.build.binary(op::bxor, mixed, this.build.binary(op::shru, mixed, this.build.word(29))));
this.count_on(index, head, done);
return this.build.read(code);
}
#! The hash of a value of a type, at its address, as the type gives it.
#! @param this The emitter.
#! @param a The value's address.
#! @param kind The type.
#! @returns The hash.
def emitter::element_hash(&mut this, a: u32, kind: u32): u32 {
val plain := this.c.checker.unalias(kind);
if this.c.checker.types.kind_of(plain) == ty::fixed {
return this.hash_elements(a, plain);
}
val place := location { kind = kind, address = a };
val method := this.c.checker.find_member(kind, word::hash).decl;
if method == 0 {
val x := this.load(&place);
return this.builtin_method(word::hash, &x, &operand {}, bt::uint64).words[0];
}
val subject := this.reference_to(&place, this.c.checker.types.reference(kind, false));
return this.method_call(method, kind, &subject, span::<operand>::empty()).words[0];
}
+702
View File
@@ -0,0 +1,702 @@
#! @file calls.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the lowering of calls: of functions and the instances of generics,
#! of methods given the value they are called on, of traits' methods through a
#! vtable, of function values, and of C functions, with the arguments a call
#! leaves to defaults, those a variadic parameter gathers, and those a pack
#! spreads. Also contains the calls the compiler makes itself, for reading and
#! writing a property and indexing what implements `indexable`, and the
#! intrinsics, which are code of their own rather than calls.
import sakura::analyzer;
module sakura::compiler;
#! The arguments of a call as lowering gathers them, each the value of a
#! parameter, in order.
pub struct gathered {
var values: vector<operand>; #! The value given each parameter.
}
#! The instance of a generic a node calls, as the checker recorded it.
#! @param this The emitter.
#! @param node The node.
#! @returns One more than the instance, or 0.
pub def emitter::called(&mut this, node: u32): u32 {
return this.c.called(node);
}
#! Lowers a call.
#! @param this The emitter.
#! @param node The `call` node.
#! @returns What it gives.
pub def emitter::call(&mut this, node: u32): operand {
val callee := this.c.checker.left_of(node);
var decl := this.c.checker.ref_at(node);
# A value of no function type is called through its `invoke`, given the value
# as `this`, which the callee is however it is reached, as `obj.f` of `obj.f(x)`.
if this.c.checker.has_flag(node, rf::invokes) && decl != 0 {
return this.call_decl(node, decl, callee);
}
# `x.(d)()` calls the method a description names, which the callee names.
if decl == 0 && this.c.checker.kind_of(callee) == nk::member_of {
decl = this.c.checker.ref_at(callee);
}
# An intrinsic of reflection records what it reaches as the call's own, as
# `value_of(d)` does the function `d` describes, so its callee says what it is.
val named := this.c.checker.kind_of(callee) == nk::name || this.c.checker.kind_of(callee) == nk::path
? this.c.checker.ref_at(callee) : 0;
if named != 0 && (named & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[named] == dk::function
&& this.c.checker.decls.has(named, df::intrinsic) {
return this.intrinsic(node, named);
}
if decl != 0 && (decl & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[decl] == dk::function {
if this.c.checker.decls.has(decl, df::intrinsic) {
return this.intrinsic(node, decl);
}
var object: u32 = 0;
val callee_kind := this.c.checker.kind_of(callee);
if (callee_kind == nk::member || callee_kind == nk::member_of) && this.c.checker.decls.has(decl, df::method) {
object = this.c.checker.left_of(callee);
}
return this.call_decl(node, decl, object);
}
# A method the compiler gives a built-in type, as `equals` of a number, but
# not a field holding a function.
if this.c.checker.kind_of(callee) == nk::member && decl == 0 {
val field := this.c.checker.ref_at(callee);
val is_field := field != 0 && (field & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[field] == dk::field;
if !is_field {
return this.builtin_call(node);
}
}
return this.call_value(node);
}
#! Lowers a call of a declared function, given the value a method is called on.
#! @param this The emitter.
#! @param node The `call` node.
#! @param decl The function's declaration.
#! @param object The node of the value a method is called on, or 0.
#! @returns What it gives.
def emitter::call_decl(&mut this, node: u32, decl: u32, object: u32): operand {
val instance := this.called(node);
val holder := this.c.trait_of_method(decl);
var kind := this.c.type_of_function(decl, instance);
if holder != 0 && object != 0 && instance == 0 {
kind = this.c.checker.trait_method_type(decl, this.c.checker.reached(this.c.checker.type_at(object)));
}
var given := gathered { values = vector::<operand>::new() };
if object != 0 {
given.values.append(this.receiver(object, this.c.checker.types.part_at(kind, 0), decl));
}
this.gather(node, decl, instance, kind, object != 0 ? 1 : 0, &mut given);
return this.call_gathered(decl, instance, holder, kind, object, &given);
}
#! Calls a declared function with its arguments gathered: through a vtable, as
#! a trait's default, through its address where it is C's, or as it is.
#! @param this The emitter.
#! @param decl The function's declaration.
#! @param instance One more than the instance called, or 0.
#! @param holder The trait it is a member of, or 0.
#! @param kind The function type called.
#! @param object The node of the value a method is called on, or 0.
#! @param given The arguments.
#! @returns What it gives.
pub def emitter::call_gathered(
&mut this,
decl: u32,
instance: u32,
holder: u32,
kind: u32,
object: u32,
given: &gathered
): operand {
# A trait's method is called through the vtable of the value's trait
# reference, but a default it writes a body for, called on a value of a type
# that takes it, is that body: the type's own instance of it, which the
# checker made where the call gives the default's type arguments, or one
# given the value as a reference to the trait.
if holder != 0 {
val receiver_type := object != 0 ? this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(object))) : 0;
val dynamic := object != 0 && (this.c.checker.named_kind(receiver_type) == dk::trait_type
|| this.c.checker.types.kind_of(receiver_type) == ty::param);
if dynamic || !this.c.checker.has_body(decl) {
return this.call_trait(decl, holder, given, this.c.checker.types.first_of(kind));
}
if instance != 0 {
return this.call_function(this.c.function_of(decl, instance), given, this.c.checker.types.first_of(kind));
}
val implemented := this.c.checker.implemented(receiver_type, this.c.checker.enclosing_trait(decl));
val own := span::<u32>::empty();
return this.call_function(this.c.default_of(decl, implemented, receiver_type, own), given, this.c.checker.types.first_of(kind));
}
# A C function without a body is called through its address.
if this.c.checker.decls.has(decl, df::foreign) && !this.c.checker.has_body(decl) {
val address := this.build.value(op::c_address, span::<u32>::empty(), vt::word, this.c.linked_of(decl), 0);
return this.call_address(address, this.c.call_type(kind), given, this.c.checker.types.first_of(kind));
}
return this.call_function(this.c.function_of(decl, instance), given, this.c.checker.types.first_of(kind));
}
#! The reference a method's `this` takes to the value it is called on: the
#! reference the value already is, read through to the one `this` takes, or one
#! to the place it is, or to a copy of it where it is no place. A trait's
#! default method takes it as a reference to the trait.
#! @param this The emitter.
#! @param object The node of the value.
#! @param param The type of `this`.
#! @param decl The method's declaration.
#! @returns The reference.
pub def emitter::receiver(&mut this, object: u32, param: u32, decl: u32): operand {
var made := this.receiver_of(object, this.c.checker.decls.has(decl, df::mut_this));
# A default takes the value as a reference to its trait, unless it is compiled
# for each type.
val holder := this.c.trait_of_method(decl);
if holder != 0 && made.count == 1 && !this.c.checker.typed_default(decl) {
val given := this.c.checker.types.first_of(this.c.checker.unalias(made.kind));
val referent := this.c.checker.unalias(given);
if this.c.checker.named_kind(referent) != dk::trait_type {
val implemented := this.c.checker.implemented(referent, this.c.checker.enclosing_trait(decl));
val vtable := this.c.vtable_of(given, implemented);
return operand::two(this.c.checker.types.reference(implemented, false),
made.words[0], this.build.word(vtable as u64));
}
}
return this.convert(&made, param);
}
#! A reference to what a node gives, which a parameter taking a reference is
#! given where the value given is no reference: one to its place, or to a copy
#! of it the statement holds until it ends.
#! @param this The emitter.
#! @param node The node.
#! @param kind The reference's type.
#! @returns The reference.
pub def emitter::reference_arg(&mut this, node: u32, kind: u32): operand {
if this.c.checker.is_place(node) {
val place := this.place_of(node);
return this.reference_to(&place, kind) if this.lends_as_is(place.kind, kind);
}
# A value is referred to where the statement holds it, which closes it where
# the statement ends. A value referred to as a trait it implements is held as
# its own type.
val referent := this.c.checker.types.first_of(this.c.checker.unalias(kind));
var value := this.value_of_type(node);
if this.c.checker.named_kind(this.c.checker.unalias(referent)) != dk::trait_type {
value = this.convert(&value, referent);
}
val place := this.hold(&value);
return this.reference_to(&place, kind);
}
#! A reference to an operand an operator's method is given, which never keeps
#! it: to the place it names, or to where the statement holds its value, which
#! the statement closes where it ends.
#! @param this The emitter.
#! @param node The operand's node.
#! @param kind The reference's type.
#! @returns The reference.
pub def emitter::lent_arg(&mut this, node: u32, kind: u32): operand {
if this.c.checker.is_place(node) {
val place := this.place_of(node);
return this.reference_to(&place, kind) if this.lends_as_is(place.kind, kind);
}
val referent := this.c.checker.types.first_of(this.c.checker.unalias(kind));
var value := this.value(node);
value = this.convert(&value, referent);
val place := this.hold(&value);
if value.address == 0 {
var held := operand::at(value.kind, place.address);
this.keep(&held);
}
return this.reference_to(&place, kind);
}
#! Whether a place is referred to as it is where a reference is wanted: one of
#! its own type, of a trait it implements, of a reference it holds, or one
#! written through. A place of another type is converted first, as a view where
#! a `string` is wanted is copied into one, and the copy referred to.
#! @param this The emitter.
#! @param held The place's type.
#! @param kind The reference's type.
#! @returns Whether it is.
def emitter::lends_as_is(&mut this, held: u32, kind: u32): bool {
val wanted := this.c.checker.unalias(kind);
return true if this.c.checker.types.kind_of(wanted) != ty::reference || this.c.checker.types.second_of(wanted) != 0;
val referent := this.c.checker.unalias(this.c.checker.types.first_of(wanted));
val own := this.c.checker.unalias(held);
return referent == own || this.c.checker.named_kind(referent) == dk::trait_type
|| this.c.checker.types.kind_of(own) == ty::reference;
}
#! Gathers the arguments of a call: those written, each converted to its
#! parameter or referred to where the parameter takes a reference, those a
#! variadic parameter takes as a view of them, those a pack spreads, and the
#! defaults of the parameters the call leaves out.
#! @param this The emitter.
#! @param node The `call` node.
#! @param decl The function's declaration.
#! @param instance One more than the instance called, or 0.
#! @param kind The function type called.
#! @param skip How many parameters come before the first argument, as
#! `this`.
#! @param into Where the arguments are gathered, after any already there.
pub def emitter::gather(
&mut this,
node: u32,
decl: u32,
instance: u32,
kind: u32,
skip: u32,
into: &mut gathered
): void {
val run := this.c.checker.right_of(node);
val count := this.c.checker.types.part_count(kind);
val variadic := this.c.checker.types.second_of(kind) != 0;
val stop: u32 = variadic ? count - 1 : count;
var p := skip;
var rest_given := false;
for i in 0..this.c.checker.run_length(run) {
val arg := this.c.checker.run_at(run, i as u32);
val packs := this.is_spread(arg)
&& this.c.checker.types.kind_of(this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(this.c.checker.left_of(arg))))) == ty::pack;
# A variadic function's pack ends in a view of the rest, which is the view a
# variadic parameter takes as it is.
val ends_in_rest := packs && this.c.checker.types.second_of(this.c.checker.reached(this.c.checker.type_at(this.c.checker.left_of(arg)))) != 0;
break if p >= stop && variadic && !ends_in_rest;
break if p >= count;
# `...args` spreads the values of a pack, one to a parameter.
if packs {
val pack := this.c.checker.left_of(arg);
val ref := this.c.checker.ref_at(pack);
val local := (ref & ref_local) != 0 ? this.local_of(ref & ref_mask) : 0;
if local != 0 {
val held: local_info = this.locals[local - 1];
for j in 0..held.count {
val place: location = this.packs[held.pack as u64 + j as u64];
val value := this.load(&place);
if ends_in_rest && variadic && j + 1 == held.count && p + 1 == count {
into.values.append(value);
p = count;
rest_given = true;
break;
}
# A value that closes is moved to the parameter taking it, as the
# function then owns it: the pack is left empty, so it isn't closed
# twice. The value was copied out of the pack's place as it was read.
val param := this.c.checker.types.part_at(kind, p);
if this.c.checker.closes(place.kind)
&& this.c.checker.types.kind_of(this.c.checker.unalias(param)) != ty::reference {
this.zero(&place);
}
into.values.append(this.convert(&value, param));
p++;
}
}
continue;
}
into.values.append(this.argument(arg, this.c.checker.types.part_at(kind, p)));
p++;
}
# A variadic parameter takes a view of the rest, which `...xs` gives as it is,
# after the defaults of those before it the call leaves out.
if variadic && !rest_given {
if p < stop {
this.defaults_of(decl, instance, kind, p, stop, into, node, skip);
p = stop;
}
val element := this.c.checker.types.part_at(kind, count - 1);
val view := this.c.checker.span_of(element);
var rest := vector::<u32>::new();
for i in (p - skip) as u64..this.c.checker.run_length(run) as u64 {
rest.append(this.c.checker.run_at(run, i as u32));
}
if rest.length == 1 && this.is_spread(rest[0]) {
into.values.append(this.spread_view(this.c.checker.left_of(rest[0]), view));
} else {
into.values.append(this.gathered_view(rest.view(), element, view));
}
p = count;
}
# The parameters left out take their defaults, made where the function is.
if p < count {
this.defaults_of(decl, instance, kind, p, count, into, node, skip);
}
}
#! Whether a node is `...xs`.
#! @param this The emitter.
#! @param node The node.
#! @returns Whether it is.
pub def emitter::is_spread(&mut this, node: u32): bool {
return this.c.checker.kind_of(node) == nk::unary && this.c.checker.token_kind(node) == tk::spread;
}
#! An argument as its parameter takes it: converted to its type, or referred to
#! where it takes a reference and the argument is none.
#! @param this The emitter.
#! @param node The argument's node.
#! @param param The parameter's type.
#! @returns The value.
pub def emitter::argument(&mut this, node: u32, param: u32) : operand {
if this.c.checker.has_flag(node, rf::borrowed) {
val made := this.reference_arg(node, param);
return this.convert(&made, param);
}
return this.value_as(node, param);
}
#! A view of the arguments a variadic parameter gathers, held in an array the
#! statement holds.
#! @param this The emitter.
#! @param args The arguments' nodes.
#! @param element The type of each.
#! @param view The view's type.
#! @returns The view.
def emitter::gathered_view(&mut this, args: span<u32>, element: u32, view: u32): operand {
val address := this.temporary_of(view);
if args.length == 0 {
this.build.clear(address, 2 * word_size);
return operand::at(view, address);
}
val array := this.c.checker.types.fixed(element, args.length as u32);
val held := this.c.shape_of(element);
val first := this.temporary_of(array);
for i in 0..args.length {
val value := this.value_as(args[i], element);
this.adopt(&value);
val place := location { kind = element, address = first, offset = i as u64 * held.size, framed = true };
this.store(&place, &value);
}
this.build.store(access::i64, address, 0, first);
this.build.store(access::i64, address, word_size, this.build.word(args.length));
# What the array holds closes where the statement ends, as an array literal's does.
var whole := operand::at(array, first);
this.keep(&whole);
return operand::at(view, address);
}
#! The view `...xs` gives a variadic parameter: a view as it is, or one of every
#! element of a fixed array.
#! @param this The emitter.
#! @param node The node of what is spread.
#! @param view The view's type.
#! @returns The view.
def emitter::spread_view(&mut this, node: u32, view: u32): operand {
val through := this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(node)));
if this.c.checker.types.kind_of(through) == ty::fixed {
val whole := this.object(node);
val shape := this.c.shape_of(through);
val address := this.temporary_of(view);
this.build.store(access::i64, address, 0, this.address_of(&whole));
this.build.store(access::i64, address, word_size, this.build.word(shape.count as u64));
return operand::at(view, address);
}
val made := this.value(node);
val read := this.through_references(&made);
return this.convert(&read, view);
}
#! The defaults of the parameters a call leaves out, each made where the
#! function is declared, with the parameters before it named as the arguments
#! the call gave them.
#! @param this The emitter.
#! @param decl The function's declaration.
#! @param instance One more than the instance called, or 0.
#! @param kind The function type called.
#! @param from The first parameter left out.
#! @param to One past the last.
#! @param into The arguments gathered so far, which the defaults follow.
def emitter::defaults_of(
&mut this,
decl: u32,
instance: u32,
kind: u32,
from: u32,
to: u32,
into: &mut gathered,
call: u32,
skip: u32
): void {
# What a default asks of its call, as where it is or the text of an argument,
# is of the call written, not of a call a default makes.
val outer := this.defaulting;
if outer.node == 0 {
this.defaulting = default_site {
node = call,
file = this.c.checker.at.file,
table = this.c.checker.at.table,
args = this.c.checker.right_of(call),
skip = skip
};
}
val table := this.c.body_table(decl, instance);
val saved := this.c.checker.at;
this.c.checker.use_table(table);
val node: u32 = this.c.checker.decls.nodes.p[decl];
val params := this.c.checker.record(node, function_slot::params);
val mark := this.scope_mark();
if outer.node == 0 {
this.defaulting.params = params;
}
# The parameters given are named as what they were given.
for i in 0..from {
break if i as u64 >= into.values.length || i >= this.c.checker.run_length(params);
val param := this.c.checker.run_at(params, i as u32);
val place := this.hold(&into.values[i]);
this.declare(param, place, false);
}
for i in from..to {
break if i >= this.c.checker.run_length(params);
val param := this.c.checker.run_at(params, i as u32);
val value := this.c.checker.record(param, parameter_slot::value);
val wanted := this.c.checker.types.part_at(kind, i as u32);
if value == 0 {
this.problem(param, "The parameter is left out and has no default.");
into.values.append(this.zero_value(wanted));
continue;
}
val made := this.value_as(value, wanted);
into.values.append(made);
val place := this.hold(&made);
this.declare(param, place, false);
}
this.forget_locals(mark);
this.c.checker.at = saved;
this.defaulting = outer;
}
#! The argument a call wrote for a parameter a default names, where the default
#! being made names one: the node, in the call's own table.
#! @param this The emitter.
#! @param node The node naming the parameter, in the default.
#! @returns The argument's node, or 0.
pub def emitter::written_argument(&mut this, node: u32): u32 {
return 0 if this.defaulting.node == 0 || this.c.checker.kind_of(node) != nk::name;
val ref := this.c.checker.ref_at(node);
return 0 if (ref & ref_local) == 0;
val param := ref & ref_mask;
val params := this.defaulting.params;
for i in 0..this.c.checker.run_length(params) {
continue if this.c.checker.run_at(params, i as u32) != param;
return 0 if (i as u32) < this.defaulting.skip;
val at := i as u32 - this.defaulting.skip;
val saved := this.c.checker.at;
this.c.checker.use_table(this.defaulting.table);
val arg := at < this.c.checker.run_length(this.defaulting.args) ? this.c.checker.run_at(this.defaulting.args, at) : 0;
this.c.checker.at = saved;
return arg;
}
return 0;
}
#! Calls a function of the program with the arguments gathered.
#! @param this The emitter.
#! @param index The function.
#! @param given The arguments.
#! @param result The type it gives.
#! @returns What it gives.
pub def emitter::call_function(&mut this, index: u32, given: &gathered, result: u32): operand {
var args := vector::<u32>::new();
this.pass_args(given, &mut args);
return this.call_with(op::call, index, 0, &mut args, result);
}
#! Adds the words of the arguments gathered to a call's operands, which the call
#! takes as its own.
#! @param this The emitter.
#! @param given The arguments.
#! @param args The operands.
def emitter::pass_args(&mut this, given: &gathered, args: &mut vector<u32>): void {
for &each in given.values {
this.adopt(&each);
each.args(args);
}
}
#! Adds a call, writing what it gives to a cell the statement holds where it is
#! held in memory, whose address the call is given last.
#! @param this The emitter.
#! @param kind The kind of call.
#! @param aux The function or signature called.
#! @param imm The slot of a vtable called through, or 0.
#! @param args The operands.
#! @param result The type it gives.
#! @returns What it gives.
pub def emitter::call_with(&mut this, kind: op, aux: u32, imm: u64, args: &mut vector<u32>, result: u32): operand {
val held := this.c.shape_of(result);
if in_memory(&held) {
# A value of no bytes, as a struct of no fields, is returned as nothing, so
# the call is given nowhere to write it.
val address := this.temporary_of(result);
if returned_in_memory(&held) {
args.append(address);
}
this.build.effect(kind, args.view(), aux, imm);
return operand::at(result, address);
}
var gives := vector::<vt>::new();
for _ in 0..word_count(&held) {
gives.append(word_type(&held));
}
val index := this.build.emit(kind, args.view(), gives.view(), aux, imm);
var made := operand { kind = result, count = word_count(&held) };
val first: u32 = this.build.code.insts[index].result;
for i in 0..made.count {
made.words[i] = first + i as u32;
}
return made;
}
#! Calls a trait's method through the vtable of the reference it is given.
#! @param this The emitter.
#! @param decl The method's declaration.
#! @param holder The trait's declaration.
#! @param given The arguments, the trait reference first.
#! @param result The type it gives.
#! @returns What it gives.
pub def emitter::call_trait(&mut this, decl: u32, holder: u32, given: &gathered, result: u32): operand {
var args := vector::<u32>::new();
this.pass_args(given, &mut args);
# The reference's own trait numbers the slots its vtables hold; within a
# default, `this` holds the vtable of the trait declaring it.
val reached := given.values.length != 0 ? this.c.checker.types.first_of(this.c.checker.unalias(given.values[0].kind)) : 0;
val plain := this.c.checker.unalias(reached);
var owner := this.c.checker.named_kind(plain) == dk::trait_type ? this.c.checker.types.first_of(plain) : holder;
if this.c.checker.types.kind_of(plain) == ty::param {
val param := this.c.checker.types.first_of(plain);
val declarer: u32 = this.c.checker.decls.owners.p[param];
if this.c.checker.decls.names.p[param] == names::self_id && declarer != 0
&& this.c.checker.decls.kinds.p[declarer] == dk::trait_type {
owner = declarer;
}
}
val slot := this.c.dispatch_index(owner, decl);
val signature := this.c.trait_signature(decl, owner, result,
this.c.checker.named_kind(plain) == dk::trait_type ? plain : 0);
return this.call_with(op::call_trait, signature, slot as u64, &mut args, result);
}
#! Calls a C function through its address.
#! @param this The emitter.
#! @param address The function's address.
#! @param kind Its function type.
#! @param given The arguments.
#! @param result The type it gives.
#! @returns What it gives.
pub def emitter::call_address(&mut this, address: u32, kind: u32, given: &gathered, result: u32): operand {
var args := vector::<u32>::new();
args.append(address);
this.pass_args(given, &mut args);
return this.call_with(op::call_c, this.c.signature_of(kind), 0, &mut args, result);
}
#! Lowers a call of a function value: a local, a field, or anything giving a
#! function, or the address of a C function.
#! @param this The emitter.
#! @param node The `call` node.
#! @returns What it gives.
def emitter::call_value(&mut this, node: u32): operand {
val callee := this.c.checker.left_of(node);
val made := this.value_of_type(callee);
val function := this.through_references(&made);
# A function value has no defaults, but takes a view of the rest where its last
# parameter is variadic, and a value of each type of a pack spread into it.
var given := gathered { values = vector::<operand>::new() };
this.gather(node, 0, 0, this.called_type(function.kind), 0, &mut given);
return this.call_function_value(&function, &given);
}
#! The function type a function value, or the address of a C function, is called
#! as.
#! @param this The emitter.
#! @param kind The value's type.
#! @returns The function type.
pub def emitter::called_type(&mut this, kind: u32): u32 {
val plain := this.c.checker.unalias(kind);
return this.c.checker.is_std(plain, word::cfn)
? this.c.checker.unalias(this.c.checker.types.part_at(plain, 0))
: plain;
}
#! Calls a function value, or the address of a C function, given its arguments.
#! @param this The emitter.
#! @param function The value.
#! @param given The arguments, as its parameters take them.
#! @returns What it gives.
pub def emitter::call_function_value(&mut this, function: &operand, given: &gathered): operand {
val plain := this.called_type(function.kind);
val result := this.c.checker.types.first_of(plain);
if this.c.checker.is_std(this.c.checker.unalias(function.kind), word::cfn) {
return this.call_address(function.words[0], plain, given, result);
}
var args := vector::<u32>::new();
function.args(&mut args);
this.pass_args(given, &mut args);
return this.call_with(op::call_value, this.c.signature_of(this.c.call_type(plain)), 0, &mut args, result);
}
#! Calls an accessor the compiler calls itself, as `at` indexing what implements
#! `indexable`, given the value it is called on and its other argument.
#! @param this The emitter.
#! @param node The node the call stands for.
#! @param decl The accessor's declaration.
#! @param object The node of the value it is called on.
#! @param arg The node of its other argument, or 0.
#! @returns What it gives.
pub def emitter::accessor_call(&mut this, node: u32, decl: u32, object: u32, arg: u32): operand {
val owner := this.c.checker.reached(this.object_type(object));
val target := this.c.method_target(decl, owner);
var given := gathered { values = vector::<operand>::new() };
given.values.append(this.receiver(object, this.c.checker.types.part_at(target.kind, 0), decl));
if arg != 0 && this.c.checker.types.part_count(target.kind) > 1 {
given.values.append(this.value_as(arg, this.c.checker.types.part_at(target.kind, 1)));
}
val result := this.c.checker.types.first_of(target.kind);
if target.holder != 0 {
return this.call_trait(decl, target.holder, &given, result);
}
return this.call_function(target.function, &given, result);
}
#! Calls a method on a value already lowered, as the compiler does where a loop
#! asks an iterator for its next element, or a value is closed: given a
#! reference to it, and the other arguments.
#! @param this The emitter.
#! @param decl The method's declaration.
#! @param owner The type it is called on.
#! @param receiver The reference `this` takes.
#! @param others The other arguments.
#! @returns What it gives.
pub def emitter::method_call(&mut this, decl: u32, owner: u32, receiver: &operand, others: span<operand>): operand {
val target := this.c.method_target(decl, owner);
var given := gathered { values = vector::<operand>::new() };
given.values.append(this.convert(receiver, this.c.checker.types.part_at(target.kind, 0)));
given.values.extend(others);
val result := this.c.checker.types.first_of(target.kind);
if target.holder != 0 {
return this.call_trait(decl, target.holder, &given, result);
}
return this.call_function(target.function, &given, result);
}
+303
View File
@@ -0,0 +1,303 @@
#! @file closures.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains functions as values: a function named, the instance of a generic
#! one, the address of a C function, and anonymous functions, which refer to
#! the locals of the function around them they name. An anonymous function
#! naming any is a closure, given an environment of references to them after
#! its parameters, which is a cell of the frame making it, as the locals are.
#! So a closure is good while the locals it refers to are, and one outliving
#! them is the program's mistake, as a reference outliving what it refers to
#! is.
import sakura::analyzer;
module sakura::compiler;
#! A function named as a value: its index plus one, with no environment, a C
#! function's address, or the address of the entry C calls one of the program
#! back through, where it is given as a `cfn`.
#! @param this The emitter.
#! @param node The node naming it.
#! @param decl The function's declaration.
#! @returns The value.
pub def emitter::function_value(&mut this, node: u32, decl: u32): operand {
val kind := this.c.checker.type_at(node);
if this.c.checker.decls.has(decl, df::foreign) {
return operand::one(kind, this.build.value(op::c_address, span::<u32>::empty(), vt::word, this.c.linked_of(decl), 0));
}
if this.c.checker.decls.has(decl, df::callback) && this.c.checker.is_std(this.c.checker.unalias(kind), word::cfn) {
val function := this.c.function_of(decl, 0);
return operand::one(kind, this.build.value(op::callback, span::<u32>::empty(), vt::word, function, 0));
}
var instance := this.called(node);
# A generic type's function named through it is the instance its arguments give.
if instance == 0 && this.c.checker.decls.has(decl, df::generic) && this.c.checker.kind_of(node) == nk::path {
val target := this.c.checker.path_target(node);
if target.owner != bt::error && this.c.checker.types.kind_of(target.owner) == ty::named {
var args := this.c.checker.types.parts_of(target.owner);
instance = this.c.checker.instance_of(decl, args.view(), node);
}
}
val index := this.c.function_of(decl, instance);
# Named where another function type is expected, it is called through a
# function of that type made for it.
if this.c.checker.has_flag(node, rf::adapted) {
val wanted := this.c.checker.converted(node);
val adapter := this.c.adapter_of(this.c.checker.at.table, node, this.c.checker.at.file, wanted, index);
this.c.names(this.function, adapter);
return operand::two(wanted, this.build.word(adapter as u64 + 1), this.build.word(0));
}
this.c.program.functions[index].taken = true;
this.c.names(this.function, index);
return operand::two(kind, this.build.word(index as u64 + 1), this.build.word(0));
}
#! An anonymous function as a value: its index plus one, and where it names
#! locals of the functions around it, the environment holding a reference to
#! each, in a cell of the frame.
#! @param this The emitter.
#! @param node The `lambda` node.
#! @returns The value.
pub def emitter::lambda_value(&mut this, node: u32): operand {
val kind := this.c.checker.type_at(node);
var captures := this.captures_of(node);
val index := this.c.lambda_of(this.c.checker.at.table, node, this.c.checker.at.file, kind, captures.length != 0);
val outer: u32 = this.c.program.functions[this.function].decl != 0
? this.c.program.functions[this.function].decl
: this.c.program.functions[this.function].outer;
this.c.program.functions[index].outer = outer;
this.c.program.functions[index].taken = true;
this.c.names(this.function, index);
val function := this.build.word(index as u64 + 1);
if captures.length == 0 {
return operand::two(kind, function, this.build.word(0));
}
# The environment is a fixed array of references, one to each local captured.
val reference := this.c.checker.types.reference(bt::int64, false);
val holder := this.c.checker.types.fixed(reference, captures.length as u32);
val shape := this.c.shape_of(holder);
val cell := this.build.code.add_cell(round_up(shape.size, word_size) as u32, word_size as u32, ck::local, 0);
val environment := this.build.cell_address(cell);
for i in 0..captures.length {
val local := this.local_of(captures[i]);
if local == 0 {
this.problem(node, "A local the function captures is not where it is named.");
continue;
}
val held: local_info = this.locals[local - 1];
val made := this.reference_to(&held.place, reference);
val at := location { kind = reference, address = environment, offset = i as u64 * word_size };
this.store(&at, &made);
}
return operand::two(kind, function, environment);
}
#! The locals of the functions around an anonymous function that it names, or
#! that one within it names, in the order it first names them.
#! @param this The emitter.
#! @param node The `lambda` node.
#! @returns The nodes declaring them.
pub def emitter::captures_of(&mut this, node: u32): vector<u32> {
var made := vector::<u32>::new();
val first := this.lowest_node(node);
var walk := node_walk::new(node);
while walk.more() {
val at := walk.next();
# A contract left out captures nothing.
continue if this.c.checker.contracts_off && this.c.checker.kind_of(at) == nk::contract;
if this.c.checker.kind_of(at) == nk::name {
val ref := this.c.checker.ref_at(at);
if (ref & ref_local) != 0 {
val local := ref & ref_mask;
if (local < first || local > node) && !made.view().contains(&local) {
made.append(local);
}
}
}
walk.enter(this.c.checker.syn(), at);
}
return made;
}
#! The first node of what a node was parsed from, which the parser made before
#! the node itself, one after another.
#! @param this The emitter.
#! @param node The node.
#! @returns The lowest node under it.
pub def emitter::lowest_node(&mut this, node: u32): u32 {
var lowest := node;
var walk := node_walk::new(node);
while walk.more() {
val at := walk.next();
lowest = at < lowest ? at : lowest;
walk.enter(this.c.checker.syn(), at);
}
return lowest;
}
#! The function an anonymous function is lowered to, made where it is new.
#! @param this The compiler.
#! @param table The result table its nodes' results are in.
#! @param node Its `lambda` node.
#! @param file The file it is in.
#! @param kind Its function type.
#! @param closure Whether it captures locals.
#! @returns The function's index.
pub def lowerer::lambda_of(&mut this, table: u32, node: u32, file: u32, kind: u32, closure: bool): u32 {
val key := pair_key(table, node);
if this.lambda_ids.get(&key) is some(got) {
return got;
}
val index := this.add_function(string::from("<lambda>", nothing {}), this.signature_of(kind));
this.lambda_ids.set(key, index);
this.program.functions[index].node = node;
this.program.functions[index].table = table;
this.program.functions[index].file = file;
this.program.functions[index].offset = this.node_offset(file, node);
this.program.functions[index].closure = closure;
this.want(index);
return index;
}
#! The adapter of a function named as a value of another function type: a
#! function of that type, made where it is first named, which calls it as a call
#! would, with the defaults of the parameters the type leaves out.
#! @param this The compiler.
#! @param table The result table holding the node.
#! @param node The node naming the function.
#! @param file The file the node is in.
#! @param kind The function type the adapter is of.
#! @param callee The function it calls.
#! @returns The adapter.
pub def lowerer::adapter_of(&mut this, table: u32, node: u32, file: u32, kind: u32, callee: u32): u32 {
val key := pair_key(table, node);
if this.adapter_ids.get(&key) is some(got) {
return got;
}
var name := string::from(this.program.functions[callee].name.view(), nothing {});
name.append(" (adapted)");
val index := this.add_function(move(&mut name), this.signature_of(kind));
this.adapter_ids.set(key, index);
this.program.functions[index].adapted = callee + 1;
this.program.functions[index].node = node;
this.program.functions[index].table = table;
this.program.functions[index].file = file;
this.program.functions[index].offset = this.node_offset(file, node);
this.program.functions[index].taken = true;
this.want(index);
return index;
}
#! Lowers an adapter: each parameter of the type it is of is given to the
#! function it calls as a call gives an argument: a value lent where it takes a
#! reference, closed once the call returns, a reference read through where it
#! takes what it reaches, and a value converted or moved where it takes a value.
#! The parameters the type leaves out take their defaults, and what the function
#! gives is converted to what the type gives.
#! @param this The emitter.
pub def emitter::lower_adapter(&mut this): void {
val entry := this.function;
val callee: u32 = this.c.program.functions[entry].adapted - 1;
val node: u32 = this.c.program.functions[entry].node;
this.table = this.c.program.functions[entry].table;
this.use_own_table();
this.at_node(node);
val wanted := this.c.checker.unalias(this.c.checker.converted(node));
val kind := this.c.checker.unalias(this.c.checker.type_at(node));
this.result = this.c.checker.types.first_of(wanted);
val signature: u32 = this.c.program.functions[entry].signature;
val count := this.c.checker.types.part_count(wanted);
var next: u32 = 0;
var given := gathered { values = vector::<operand>::new() };
var lent := vector::<location>::new();
for i in 0..count {
val held := this.take_param(signature, i as u32, &mut next);
val param := this.c.checker.types.part_at(kind, i as u32);
val place := this.param_place(0, held);
val takes_reference := this.c.is_reference_type(this.c.checker.unalias(param));
if takes_reference && !this.c.is_reference_type(this.c.checker.unalias(held.kind)) {
given.values.append(this.reference_to(&place, param));
if this.c.checker.closes(held.kind) {
lent.append(place);
}
continue;
}
val value := this.load(&place);
given.values.append(this.convert(&value, param));
# What converts lends from what the adapter holds, as a string a view of its
# text, and what doesn't is moved into the call.
if !takes_reference && this.c.checker.closes(held.kind)
&& this.c.checker.unalias(held.kind) != this.c.checker.unalias(param) {
lent.append(place);
}
}
val decl: u32 = this.c.program.functions[callee].decl;
val instance: u32 = this.c.program.functions[callee].instance;
val total := this.c.checker.types.part_count(kind);
if count < total {
this.defaults_of(decl, instance, kind, count as u32, total, &mut given, node, 0);
}
val made := this.call_function(callee, &given, this.c.checker.types.first_of(kind));
val result := this.convert(&made, this.result);
for &each in lent.view() {
this.close(&each);
}
var args := vector::<u32>::new();
result.args(&mut args);
this.give_back(args.view());
}
#! Lowers an anonymous function: the locals it captures are reached through the
#! references its environment holds, which it never closes, since the function
#! declaring them owns them.
#! @param this The emitter.
#! @param node The `lambda` node.
pub def emitter::lower_lambda(&mut this, node: u32): void {
this.table = this.c.program.functions[this.function].table;
this.use_own_table();
this.at_node(node);
val kind := this.c.checker.type_at(node);
this.result = this.c.checker.types.first_of(kind);
val params := this.c.checker.left_of(node);
val body := this.c.checker.record(node, lambda_slot::body);
val signature: u32 = this.c.program.functions[this.function].signature;
val total := this.c.program.signatures[signature].params.length as u32;
var next: u32 = 0;
var taken := vector::<operand>::new();
for i in 0..total {
taken.append(this.take_param(signature, i as u32, &mut next));
}
# The environment follows the parameters.
if this.c.program.functions[this.function].closure {
val environment := this.build.param(next);
var captures := this.captures_of(node);
val reference := this.c.checker.types.reference(bt::int64, false);
for i in 0..captures.length {
val at := location { kind = reference, address = environment, offset = i as u64 * word_size };
val made := this.load(&at);
val captured := captures[i];
val place := location { kind = this.c.checker.type_at(captured), address = made.words[0] };
this.declare(captured, place, false);
}
}
this.plan_lambda(node);
for i in 0..this.c.checker.run_length(params) {
break if i as u64 >= taken.length;
val param := this.c.checker.run_at(params, i as u32);
val place := this.param_place(param, taken[i]);
this.declare(param, place, this.c.checker.closes(taken[i].kind));
}
this.safepoint();
this.lower_body(body);
}
+553
View File
@@ -0,0 +1,553 @@
#! @file composite.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the lowering of values built from others, and of what reads into
#! them: struct and union literals, with the defaults of the fields they leave
#! out, array literals, the members of a value, its properties through their
#! accessors, and slices.
import sakura::analyzer;
module sakura::compiler;
#! A struct or union literal, built in a cell the statement holds.
#! @param this The emitter.
#! @param node The `construct` node.
#! @returns The value.
pub def emitter::construct(&mut this, node: u32): operand {
return this.construct_of(this.c.checker.type_at(node), this.c.checker.right_of(node));
}
#! A struct or union literal of a type, given its field inits, built in a cell
#! the statement holds, as an attribute's value is too.
#! @param this The emitter.
#! @param kind The type.
#! @param inits The run of `field_init` nodes.
#! @returns The value.
pub def emitter::construct_of(&mut this, kind: u32, inits: u32): operand {
val plain := this.c.checker.unalias(kind);
return operand::none(kind) if plain == bt::void_type;
val index := this.c.layout_of(plain);
val shape := this.c.layout_at(index);
val address := this.temporary_of(kind);
val decl := this.c.checker.types.first_of(plain);
# A struct's fields given write themselves, so what is cleared is the rest:
# the padding, and the fields left out, which take their defaults over zero.
if shape.kind != lk::variant && this.c.checker.decls.kinds.p[decl] != dk::union_type {
this.clear_unwritten(address, index, inits);
} else {
this.build.clear(address, shape.size);
}
val whole := location { kind = kind, address = address, framed = true };
# A union holds the one field it is given, whose index is its tag. A C union
# holds it over the others, without a tag.
if shape.kind == lk::variant {
if this.c.checker.run_length(inits) == 0 {
this.defaults(&whole);
return operand::at(kind, address);
}
val init := this.c.checker.run_at(inits, 0);
val field := this.c.checker.ref_at(init);
for i in 0..shape.count {
val each := this.c.field_at(index, i as u32);
continue if each.decl != field;
if shape.niche == 0 {
this.build.store(access::i64, address, 0, this.build.word(i));
}
val value := this.value_as(this.c.checker.left_of(init), each.type_id);
this.adopt(&value);
val at := this.within(&whole, each.offset, each.type_id);
this.store(&at, &value);
}
return operand::at(kind, address);
}
var given := vector::<u32>::new();
for i in 0..this.c.checker.run_length(inits) {
val init := this.c.checker.run_at(inits, i as u32);
val field := this.c.checker.ref_at(init);
given.append(field);
val at := this.field_in(&whole, plain, field, 0);
val value := this.value_as(this.c.checker.left_of(init), at.kind);
this.adopt(&value);
this.store(&at, &value);
}
if this.c.checker.decls.kinds.p[decl] == dk::union_type {
if given.length == 0 {
this.defaults(&whole);
}
return operand::at(kind, address);
}
# The fields left out take their defaults, or the defaults of what they hold.
for i in 0..shape.count {
val each := this.c.field_at(index, i as u32);
var was_given := false;
for &field in given {
was_given = was_given || field == each.decl;
}
continue if was_given;
val at := this.within(&whole, each.offset, each.type_id);
this.default_of(&at, each.decl, each.spread);
}
return operand::at(kind, address);
}
#! Clears the bytes of a struct literal's memory that none of the fields it
#! gives writes, where each is written whole: those of its own fields, and not
#! those a spread brings in, whose spread field is cleared whole.
#! @param this The emitter.
#! @param address Where the struct is built.
#! @param index Its layout.
#! @param inits The run of `field_init` nodes.
def emitter::clear_unwritten(&mut this, address: u32, index: u32, inits: u32): void {
val shape := this.c.layout_at(index);
var written := vector::<bool>::new();
written.resize(shape.size);
for i in 0..this.c.checker.run_length(inits) {
val field := this.c.checker.ref_at(this.c.checker.run_at(inits, i as u32));
for k in 0..shape.count {
val each := this.c.field_at(index, k as u32);
continue if each.decl != field || each.spread;
val end := each.offset + this.c.shape_of(each.type_id).size;
for at in each.offset..end {
written[at] = true;
}
}
}
var at: u64 = 0;
while at < shape.size {
if written[at] {
at++;
continue;
}
var end := at;
while end < shape.size && !written[end] {
end++;
}
this.clear_bytes(address, at, end);
at = end;
}
}
#! Clears a run of bytes at an address: as stores of zero where it is a few
#! words, as padding is, and otherwise at once.
#! @param this The emitter.
#! @param address The address.
#! @param from The first byte.
#! @param to Past the last.
def emitter::clear_bytes(&mut this, address: u32, from: u64, to: u64): void {
if to - from > 4 * word_size {
val first := from == 0 ? address : this.build.binary(op::add, address, this.build.word(from));
this.build.clear(first, to - from);
return;
}
val zero := this.build.word(0);
var at := from;
while at < to {
val left := to - at;
val how := left >= 8 && at % 8 == 0 ? access::i64
: left >= 4 && at % 4 == 0 ? access::u32
: left >= 2 && at % 2 == 0 ? access::u16 : access::u8;
this.build.store(how, address, at, zero);
at += how.width();
}
}
#! `a..b`, or `a..=b`, as a value: std's `range<T>`, built in a cell the
#! statement holds from its fields in the order std declares them, its start,
#! its end, and whether it is still to give its end.
#! @param this The emitter.
#! @param node The `range` node.
#! @returns The value.
pub def emitter::range_value(&mut this, node: u32): operand {
val kind := this.c.checker.type_at(node);
val plain := this.c.checker.unalias(kind);
val index := this.c.layout_of(plain);
val shape := this.c.layout_at(index);
val address := this.temporary_of(kind);
this.build.clear(address, shape.size);
val whole := location { kind = kind, address = address, framed = true };
val start := this.c.field_at(index, 0);
val first := this.value_as(this.c.checker.left_of(node), start.type_id);
val at_start := this.within(&whole, start.offset, start.type_id);
this.store(&at_start, &first);
val end := this.c.field_at(index, 1);
val last := this.value_as(this.c.checker.right_of(node), end.type_id);
val at_end := this.within(&whole, end.offset, end.type_id);
this.store(&at_end, &last);
if this.c.checker.token_kind(node) == tk::cascadeeq {
val held := this.c.field_at(index, 2);
this.build.store(access::u8, address, held.offset, this.build.word(1));
}
return operand::at(kind, address);
}
#! Sets the defaults of the fields of a zeroed struct, and of the first field a
#! zeroed union holds, as a variable without a value is given them.
#! @param this The emitter.
#! @param place The place, zeroed.
pub def emitter::defaults(&mut this, place: &location): void {
val plain := this.c.checker.unalias(place.kind);
return if this.c.checker.types.kind_of(plain) != ty::named;
val index := this.c.layout_of(plain);
val shape := this.c.layout_at(index);
val decl := this.c.checker.types.first_of(plain);
val named := this.c.checker.decls.kinds.p[decl];
return if named != dk::struct_type && named != dk::union_type;
# A union is zeroed as its first field, and so is a C union.
if named == dk::union_type {
if shape.count != 0 {
val first := this.c.field_at(index, 0);
val inner := this.c.layout_at(first.layout);
if inner.kind == lk::record {
val at := this.within(place, first.offset, first.type_id);
this.defaults(&at);
}
}
return;
}
for i in 0..shape.count {
val each := this.c.field_at(index, i as u32);
val at := this.within(place, each.offset, each.type_id);
this.default_of(&at, each.decl, each.spread);
}
}
#! Gives a field of a zeroed struct its default: the value it is declared with,
#! made where the struct is declared, or the defaults of a struct it holds.
#! @param this The emitter.
#! @param place The field's place, zeroed.
#! @param field The field's declaration.
#! @param spread Whether it spreads another struct's fields.
def emitter::default_of(&mut this, place: &location, field: u32, spread: bool): void {
val value := spread ? 0 : this.c.checker.field_default(field);
if value == 0 {
val inner := this.c.shape_of(place.kind);
if inner.kind == lk::record {
this.defaults(place);
}
return;
}
val file: u32 = this.c.checker.decls.files.p[field];
val saved := this.c.checker.at;
this.c.checker.use_table(this.c.checker.units[file].table);
val made := this.value_as(value, place.kind);
this.c.checker.at = saved;
this.adopt(&made);
this.store(place, &made);
}
#! An array literal: a fixed array holding its elements, or, where a view is
#! wanted, a view of such an array, which lives as long as the function does,
#! since the view may outlive the statement.
#! @param this The emitter.
#! @param node The `array` node.
#! @param kind The type it is used as.
#! @returns The value.
pub def emitter::array_literal(&mut this, node: u32, kind: u32): operand {
val run := this.c.checker.left_of(node);
val count := this.c.checker.run_length(run);
val plain := this.c.checker.unalias(kind);
val viewed := this.c.viewed(plain);
val element := viewed != 0 ? viewed : this.c.checker.types.first_of(plain);
val inner := this.c.shape_of(element);
if viewed != 0 {
val view := this.temporary_of(kind);
if count == 0 {
this.build.clear(view, 2 * word_size);
return operand::at(kind, view);
}
# A read-only view of what is known while compiling views data the program
# holds, made once.
if this.c.checker.is_std(plain, word::span) {
val held := this.static_datum(node, element);
if held != no_block {
val data := this.build.value(op::datum, span::<u32>::empty(), vt::word, held, 0);
this.build.store(access::i64, view, 0, data);
this.build.store(access::i64, view, word_size, this.build.word(count as u64));
return operand::at(kind, view);
}
}
val array := this.c.checker.types.fixed(element, count);
val held := this.c.shape_of(array);
val cell := this.build.code.add_cell(round_up(held.size, word_size) as u32,
held.align < word_size ? word_size as u32 : held.align as u32, ck::local, 0);
val first := this.build.cell_address(cell);
this.fill_array(run, element, inner.size, first);
this.build.store(access::i64, view, 0, first);
this.build.store(access::i64, view, word_size, this.build.word(count as u64));
# What the array holds closes where the statement ends, since a view owns
# nothing.
var whole := operand::at(array, first);
this.keep(&whole);
return operand::at(kind, view);
}
val address := this.temporary_of(kind);
this.fill_array(run, element, inner.size, address);
return operand::at(kind, address);
}
#! The datum holding the elements of an array literal, where each is known
#! while compiling: a number, text, or an array literal viewed of the same.
#! @param this The emitter.
#! @param node The `array` node.
#! @param element The elements' type.
#! @returns The datum, or `no_block` where an element is not known.
def emitter::static_datum(&mut this, node: u32, element: u32): u32 {
val run := this.c.checker.left_of(node);
val count := this.c.checker.run_length(run);
val inner := this.c.shape_of(element);
var bytes := vector::<u8>::new();
bytes.resize(count as u64 * inner.size + 1);
var moved := vector::<relocation>::new();
for i in 0..count {
val each := this.c.checker.run_at(run, i as u32);
return no_block if !this.write_static(each, element, &mut bytes, i as u64 * inner.size, &mut moved);
}
val index := this.c.program.data.length as u32;
this.c.program.data.append(datum {
bytes = move(&mut bytes),
align = inner.align < word_size ? word_size : inner.align,
relocations = move(&mut moved)
});
return index;
}
#! Writes a value known while compiling into the bytes of a datum, laid out as
#! its type is.
#! @param this The emitter.
#! @param node The value's node.
#! @param kind Its type.
#! @param bytes The datum's bytes.
#! @param at Where it is written.
#! @param moved Where the addresses it holds are noted.
#! @returns Whether it is known.
def emitter::write_static(&mut this, node: u32, kind: u32, bytes: &mut vector<u8>, at: u64, moved: &mut vector<relocation>): bool {
val shape := this.c.shape_of(kind);
if this.c.is_scalar_type(kind) && this.c.checker.is_known(node) {
val value := this.c.checker.value_at(node);
var word: u64 = 0;
if shape.kind == lk::floating {
val real := value.as_real();
word = shape.bits <= 32 ? bits_of_single(real as f32) as u64 : bits_of_real(real);
} else {
word = value.floating ? (value.real as i64) as u64 : value.bits();
}
write_number(bytes, at, shape.size, word);
return true;
}
val viewed := this.c.viewed(kind);
return false if viewed == 0 || !this.c.checker.is_std(this.c.checker.unalias(kind), word::span);
var target: u32 = no_block;
var length: u64 = 0;
if this.c.checker.kind_of(node) == nk::string {
var text := string::new(nothing {});
this.decode_literal(this.c.checker.text_of(node), &mut text);
target = this.c.text_datum(text.view());
length = text.length;
} else if this.c.checker.kind_of(node) == nk::array {
length = this.c.checker.run_length(this.c.checker.left_of(node)) as u64;
target = length == 0 ? no_block : this.static_datum(node, viewed);
return false if length != 0 && target == no_block;
} else {
return false;
}
if length != 0 {
moved.append(relocation { at = at, target = target, addend = 0 });
}
write_number(bytes, at + word_size, word_size, length);
return true;
}
#! The bits of an `f32`.
#! @param value The value.
#! @returns Its bits.
def bits_of_single(value: f32): u32 {
var held := value;
return ((&mut held) as *mut u32)[0];
}
#! Writes the elements of an array literal one after another from an address.
#! @param this The emitter.
#! @param run The run of the elements' nodes.
#! @param element Their type.
#! @param size The size of each.
#! @param first Where the first goes.
def emitter::fill_array(&mut this, run: u32, element: u32, size: u64, first: u32): void {
for i in 0..this.c.checker.run_length(run) {
val value := this.value_as(this.c.checker.run_at(run, i as u32), element);
this.adopt(&value);
val at := location { kind = element, address = first, offset = i as u64 * size, framed = true };
this.store(&at, &value);
}
}
#! `x.name`: a field, read where it is, or a property, read through its `get`.
#! The length of a fixed array is known while compiling, which its value gives.
#! @param this The emitter.
#! @param node The `member` node.
#! @returns The value.
pub def emitter::member_value(&mut this, node: u32): operand {
val property := this.property_of(node);
if property != 0 {
val object := this.c.checker.left_of(node);
val receiver := this.receiver_of(object, false);
return this.property_get(property, &receiver, node);
}
val place := this.place_of(node);
return this.load(&place);
}
#! The property a member names, or 0.
#! @param this The emitter.
#! @param node The node.
#! @returns The property's declaration, or 0.
pub def emitter::property_of(&mut this, node: u32): u32 {
val kind := this.c.checker.kind_of(node);
return 0 if kind != nk::member && kind != nk::member_of;
val ref := this.c.checker.ref_at(node);
return 0 if ref == 0 || (ref & (ref_local | ref_type)) != 0;
# `x.(d)` may name the accessor of the property.
if this.c.checker.decls.kinds.p[ref] == dk::function && this.c.checker.decls.has(ref, df::accessor) {
return this.c.checker.decls.owners.p[ref];
}
return this.c.checker.decls.kinds.p[ref] == dk::property ? ref : 0;
}
#! The reference a method or a property's accessors take to the value they are
#! of: the reference the value already is, read through to the last, or one to
#! the place it is, or to a copy of it where it is no place.
#! @param this The emitter.
#! @param object The node of the value.
#! @param writes Whether it is written.
#! @returns The reference.
pub def emitter::receiver_of(&mut this, object: u32, writes: bool): operand {
val kind := this.c.checker.type_at(object);
return this.through_one(object) if this.c.is_reference_type(kind);
return this.reference_arg(object, this.c.checker.types.reference(kind, writes));
}
#! The accessor of a property: its `set`, or its `get`.
#! @param this The emitter.
#! @param property The property's declaration.
#! @param setter Whether the `set` is wanted.
#! @returns The accessor's declaration, or 0.
pub def emitter::accessor_of(&mut this, property: u32, setter: bool): u32 {
val run: u32 = this.c.checker.decls.children.p[property];
for i in 0..this.c.checker.decls.list_length(run) {
val each := this.c.checker.decls.list_at(run, i as u32);
return each if this.c.checker.decls.has(each, df::setter) == setter;
}
return 0;
}
#! Reads a property through its `get`.
#! @param this The emitter.
#! @param property The property's declaration.
#! @param receiver The reference to the value it is of.
#! @param node The node reading it.
#! @returns What its `get` gives.
pub def emitter::property_get(&mut this, property: u32, receiver: &operand, node: u32): operand {
val getter := this.accessor_of(property, false);
if getter == 0 {
this.problem(node, "The property has no `get`.");
return this.zero_value(this.c.checker.type_at(node));
}
val owner := this.c.checker.types.first_of(this.c.checker.unalias(receiver.kind));
val made := this.method_call(getter, owner, receiver, span::<operand>::empty());
this.keep(&made);
return made;
}
#! Writes a property through its `set`.
#! @param this The emitter.
#! @param property The property's declaration.
#! @param receiver The reference to the value it is of.
#! @param value The value written.
#! @param node The node writing it.
pub def emitter::property_set(&mut this, property: u32, receiver: &operand, value: &operand, node: u32): void {
val setter := this.accessor_of(property, true);
if setter == 0 {
this.problem(node, "The property has no `set`.");
return;
}
val owner := this.c.checker.types.first_of(this.c.checker.unalias(receiver.kind));
var others: operand[1] = [value];
this.method_call(setter, owner, receiver, others[0:1]);
}
#! `x[start:count]`: a view of the elements of a fixed array, of what a pointer
#! points at, or of another view, checked against how many there are where that
#! is known. Either bound may be left out but a pointer's count.
#! @param this The emitter.
#! @param node The `slice` node.
#! @returns The view.
pub def emitter::slice(&mut this, node: u32): operand {
val object := this.c.checker.left_of(node);
val start := this.c.checker.record(node, slice_slot::start);
val count := this.c.checker.record(node, slice_slot::count);
val kind := this.c.checker.type_at(node);
val through := this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(object)));
var data: u32 = 0;
var held: u32 = 0;
var element: u32 = 0;
match this.c.checker.types.kind_of(through) {
ty::fixed => {
val whole := this.object(object);
val shape := this.c.shape_of(through);
data = this.address_of(&whole);
held = this.build.word(shape.count as u64);
element = this.c.checker.types.first_of(through);
}
ty::pointer => {
val pointer := this.value_of_type(object);
data = this.through_references(&pointer).words[0];
element = this.c.checker.types.first_of(through);
}
else => {
val whole := this.object(object);
data = this.build.load(access::i64, whole.address, whole.offset);
held = this.build.load(access::i64, whole.address, whole.offset + word_size);
element = this.c.viewed(through);
}
}
val size := this.c.shape_of(element).size;
var from := this.build.word(0);
if start != 0 {
from = this.value_as(start, bt::uint64).words[0];
if held != 0 && this.checking() {
this.build.check(this.build.binary(op::leu, from, held), fault::out_of_bounds as u32);
}
}
var many: u32 = 0;
if count != 0 {
many = this.value_as(count, bt::uint64).words[0];
if held != 0 && this.checking() {
val rest := this.build.binary(op::sub, held, from);
this.build.check(this.build.binary(op::leu, many, rest), fault::out_of_bounds as u32);
}
} else {
many = held != 0 ? this.build.binary(op::sub, held, from) : this.build.word(0);
}
val first := this.build.binary(op::add, data, this.scaled(from, size));
val view := this.temporary_of(kind);
this.build.store(access::i64, view, 0, first);
this.build.store(access::i64, view, word_size, many);
return operand::at(kind, view);
}
+238
View File
@@ -0,0 +1,238 @@
#! @file formatting.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the lowering of text a program writes while it runs: interpolated
#! strings, whose holes are written as the values they hold, and the text of
#! literals, decoded from how they are written.
import sakura::analyzer;
module sakura::compiler;
#! An interpolated string: its text and the values of its holes, written in
#! order into text a `string` then owns. A view of bytes, and a string, are
#! written as the text they hold.
#! @param this The emitter.
#! @param node The `istring` node.
#! @returns The string.
pub def emitter::interpolated(&mut this, node: u32): operand {
this.build.effect(op::format, span::<u32>::empty(), 0, 0);
val run := this.c.checker.left_of(node);
val count := this.c.checker.run_length(run);
# The lines of a block are written without the indentation its closing
# delimiter stands at, as a block of plain text is.
var indent: u64 = 0;
var block := false;
if count != 0 && this.c.checker.kind_of(this.c.checker.run_at(run, 0)) == nk::string {
val opened := this.c.checker.text_of(this.c.checker.run_at(run, 0));
block = opened.length >= 4 && opened.substr(0, 4) == "$\"\"\"";
}
if block && this.c.checker.kind_of(this.c.checker.run_at(run, count - 1)) == nk::string {
val closed := this.c.checker.text_of(this.c.checker.run_at(run, count - 1));
var line := closed.length;
while line > 0 && closed[line - 1] != '\n' {
line--;
}
if line != 0 && closed.length >= 3 {
indent = closed.length - 3 - line;
}
}
for i in 0..count {
val piece := this.c.checker.run_at(run, i as u32);
if this.c.checker.kind_of(piece) == nk::string {
var text := string::new(nothing {});
if block {
this.block_piece(piece, i == 0, indent, &mut text);
} else {
this.piece_text(piece, &mut text);
}
if text.length != 0 {
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(text.view()), 0);
}
continue;
}
val mark := this.cell_mark();
val value := this.value(piece);
this.format_value(&value);
this.release(mark);
}
# Text written where a view is wanted is made as a string all the same, which
# the statement closes, so the view is only good while it runs.
val made := this.c.checker.type_at(node);
val text := this.owned_text(made);
val wanted := this.c.checker.converted(node);
return text if wanted == made;
return this.convert(&text, wanted);
}
#! Writes a value into the text being made: the bytes a view of them or a
#! string holds, or the value as its layout says it is written.
#! @param this The emitter.
#! @param value The value.
pub def emitter::format_value(&mut this, value: &operand): void {
val kind := this.c.checker.unalias(value.kind);
val viewed := this.c.is_reference_type(kind) ? 0 : this.c.viewed(kind);
if viewed != 0 {
val element := this.c.shape_of(viewed);
if element.size == 1 && element.kind != lk::record {
var args: u32[2] = [this.build.load(access::i64, value.address, 0), this.build.load(access::i64, value.address, word_size)];
this.build.effect(op::format_bytes, args[0:2], 0, 0);
return;
}
}
if !this.c.is_reference_type(kind) && this.c.is_string(kind) {
val index := this.c.layout_of(kind);
val data := this.c.field_at(index, 1);
val count := this.c.field_at(index, 2);
var args: u32[2] = [this.build.load(access::i64, value.address, data.offset), this.build.load(access::i64, value.address, count.offset)];
this.build.effect(op::format_bytes, args[0:2], 0, 0);
return;
}
var args := vector::<u32>::new();
value.args(&mut args);
this.build.effect(op::format_value, args.view(), this.c.layout_of(kind), 0);
}
#! The text of a piece of an interpolated block, decoded: each of its lines
#! without the spaces trailing it and followed by a line break, and each line
#! after one without the indentation the block's closing delimiter stands at.
#! The first piece begins below the line the block opens.
#! @param this The emitter.
#! @param piece The `string` node of the piece.
#! @param first Whether it is the first piece.
#! @param indent How far the block's lines are indented.
#! @param out Where the bytes are written.
def emitter::block_piece(&mut this, piece: u32, first: bool, indent: u64, out: &mut string): void {
val written := this.c.checker.text_of(piece);
var from := 0u;
var to := written.length;
if written.length >= 4 && written.substr(0, 4) == "$\"\"\"" {
from = 4;
} else if written.length >= 1 && written[0] == '}' {
from = 1;
}
if to >= from + 3 && written.substr(to - 3, 3) == "\"\"\"" {
to -= 3;
} else if to > from && written[to - 1] == '{' {
to -= 1;
}
var at := from;
if first {
while at < to && written[at] != '\n' {
at++;
}
return if at >= to;
at = past_indent(written, at + 1, to, indent);
}
var start := at;
while at < to {
if written[at] != '\n' {
at++;
continue;
}
var stop := at;
while stop > start && (written[stop - 1] == ' ' || written[stop - 1] == '\t') {
stop--;
}
this.c.checker.decode_text(written.substr(start, stop - start), out);
out.push('\n');
at = past_indent(written, at + 1, to, indent);
start = at;
}
this.c.checker.decode_text(written.substr(start, to - start), out);
}
#! Where a line begins past the indentation of a block.
#! @param text The text.
#! @param at Where the line begins.
#! @param end Where the text ends.
#! @param indent How far the block's lines are indented.
#! @returns Where the line begins past it.
def past_indent(text: strview, at: u64, end: u64, indent: u64): u64 {
var made := at;
var skipped: u64 = 0;
while skipped < indent && made < end && (text[made] == ' ' || text[made] == '\t') {
made++;
skipped++;
}
return made;
}
#! The text of a piece of an interpolated string, without what opens and
#! closes it, decoded.
#! @param this The emitter.
#! @param piece The `string` node of the piece.
#! @param out Where the bytes are written.
def emitter::piece_text(&mut this, piece: u32, out: &mut string): void {
val written := this.c.checker.text_of(piece);
var from := 0u;
var to := written.length;
if written.length >= 4 && written.substr(0, 4) == "$\"\"\"" {
from = 4;
} else if written.length >= 2 && written.substr(0, 2) == "$\"" {
from = 2;
} else if written.length >= 1 && written[0] == '}' {
from = 1;
}
if to >= from + 3 && written.substr(to - 3, 3) == "\"\"\"" {
to -= 3;
} else if to > from && (written[to - 1] == '"' || written[to - 1] == '{') {
to -= 1;
}
this.c.checker.decode_text(written.substr(from, to - from), out);
}
#! Decodes the text a literal is written as: between its quotes, with its
#! escapes, or of text spanning lines, each of its lines without the
#! indentation the closing quotes stand at, and each followed by a line break.
#! @param this The emitter.
#! @param written The literal, with its quotes.
#! @param out Where the bytes are written.
pub def emitter::decode_literal(&mut this, written: strview, out: &mut string): void {
if written.length < 6 || written.substr(0, 3) != "\"\"\"" {
this.c.checker.decode_text(written.substr(1, written.length < 2 ? 0 : written.length - 2), out);
return;
}
# The text begins below the line the block opens, and the closing quotes' own
# line says how far every line of it is indented.
val inner := written.substr(3, written.length - 6);
var first := 0u;
while first < inner.length && inner[first] != '\n' {
first++;
}
var last := inner.length;
while last > 0 && inner[last - 1] != '\n' {
last--;
}
return if first >= inner.length || last <= first;
val indent := inner.length - last;
var line := first + 1;
while line < last {
var stop := line;
while stop < last && inner[stop] != '\n' {
stop++;
}
var at := line;
var skipped := 0u;
while skipped < indent && at < stop && (inner[at] == ' ' || inner[at] == '\t') {
at++;
skipped++;
}
var text := stop;
while text > at && (inner[text - 1] == ' ' || inner[text - 1] == '\t') {
text--;
}
this.c.checker.decode_text(inner.substr(at, text - at), out);
out.push('\n');
line = stop + 1;
}
}
+546
View File
@@ -0,0 +1,546 @@
#! @file intrinsics.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the intrinsics, the functions std declares `@intrinsic` that the
#! compiler gives: an operation of their own, or a value worked out while
#! compiling, rather than a call.
import sakura::analyzer;
module sakura::compiler;
#! Lowers a call of an intrinsic.
#! @param this The emitter.
#! @param node The `call` node.
#! @param decl The intrinsic's declaration.
#! @returns What it gives.
pub def emitter::intrinsic(&mut this, node: u32, decl: u32): operand {
val name := this.c.checker.names.text(this.c.checker.decls.names.p[decl]);
val kind := this.c.checker.type_at(node);
val run := this.c.checker.right_of(node);
# A type's layout is known while compiling.
if name == "size_of" || name == "align_of" {
val instance := this.called(node);
var size: u64 = 0;
if instance != 0 {
val args: u32 = this.c.checker.instances[instance - 1].args;
val held := this.c.shape_of(this.c.checker.types.part_at(args, 0));
size = name == "size_of" ? held.size : held.align;
}
return operand::one(kind, this.build.word(size));
}
if name == "os" || name == "arch" || name == "backend" {
val value := name == "os" ? this.c.checker.target.os : name == "arch" ? this.c.checker.target.arch : this.c.checker.target.backend;
return this.text_value(this.c.checker.names.text(value), kind);
}
if name == "call_site" {
return this.call_site(node, kind);
}
if name == "contracts" || name == "checking" {
val off := name == "contracts" ? this.c.checker.contracts_off : this.c.checker.checks_off;
return operand::one(kind, this.build.word(off ? 0 : 1));
}
# These read the argument as it is written: in a default, the argument the
# call wrote for the parameter it names.
if name == "source_of" || name == "values_of" {
val arg := this.c.checker.run_length(run) != 0 ? this.c.checker.run_at(run, 0) : 0;
val written := arg != 0 ? this.written_argument(arg) : 0;
val saved := this.c.checker.at;
if written != 0 {
this.c.checker.use_table(this.defaulting.table);
}
val chosen := written != 0 ? written : arg;
var made := operand {};
if name == "source_of" {
var text := string::new(nothing {});
if chosen != 0 {
this.source_text(chosen, &mut text);
}
this.c.checker.at = saved;
made = this.text_value(text.view(), kind);
} else {
val outer := this.defaulting;
this.defaulting = default_site {};
made = this.values_of(chosen, kind);
this.defaulting = outer;
this.c.checker.at = saved;
}
return made;
}
if name == "name_of" || name == "path_of" {
# The checker keeps the type named as the callee's.
val named := this.c.checker.type_at(this.c.checker.left_of(node));
var text := string::new(nothing {});
if named != 0 && named != bt::error {
text = name == "path_of" ? this.c.checker.describe_path(named) : this.c.checker.describe(named);
}
return this.text_value(text.view(), kind);
}
if name == "value_of" {
if this.c.checker.is_known(node) && this.c.is_scalar_type(kind) {
return this.known(&this.c.checker.value_at(node), kind);
}
val ref := this.c.checker.ref_at(node);
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::enum_member {
var value := constant {};
this.c.checker.decl_value(ref, &mut value);
return this.known(&value, kind);
}
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::variable {
val place := this.global_place(ref);
return this.load(&place);
}
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::function {
return this.function_value(node, ref);
}
# An attribute is the value it writes, made where it is read.
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::attribute {
val saved := this.c.checker.at;
this.c.checker.use_table(this.c.checker.units[this.c.checker.decls.files.p[ref]].table);
val made := this.construct_of(this.c.checker.decls.types.p[ref], this.c.checker.right_of(this.c.checker.decls.nodes.p[ref]));
this.c.checker.at = saved;
return made;
}
this.problem(node, "`value_of` reaches nothing lowering knows.");
return this.zero_value(kind);
}
if name == "attached" {
return this.attached(node, kind);
}
if name == "compile_error" {
this.build.unreachable();
return operand::none(kind);
}
if name == "lanes_have" || name == "lanes_apply" {
return this.lanes(node, name == "lanes_have", kind);
}
# Vectors are values held in registers between operations in an executable
# optimized with inlining and promotion, and nowhere else.
if name == "lanes_held" {
val native := !this.c.options.evaluating && this.c.checker.names.text(this.c.checker.target.backend) == "native";
return operand::one(kind, this.build.word(native && this.c.options.level >= 2 ? 1 : 0));
}
if name.starts_with("atomic_") {
return this.atomic(node, name, kind);
}
# `fault` takes its text's two words, wherever the view is.
if name == "fault" {
val text := this.value(this.c.checker.run_at(run, 0));
var words: u32[2] = [0, 0];
if text.address != 0 {
words[0] = this.build.load(access::i64, text.address, 0);
words[1] = this.build.load(access::i64, text.address, word_size);
} else {
words[0] = text.words[0];
words[1] = text.words[1];
}
this.build.effect(op::fault, words[0:2], 0, 0);
return operand::none(kind);
}
# The rest are operations, given their arguments' values.
var args := vector::<u32>::new();
for i in 0..this.c.checker.run_length(run) {
val made := this.value(this.c.checker.run_at(run, i as u32));
made.args(&mut args);
}
# A member of an enum's place among the values of its members, and the member
# at a place, by which a range of its members counts.
if name == "rank_of" || name == "member_at" {
val instance := this.called(node);
val members := instance != 0 ? this.c.checker.types.part_at(this.c.checker.instances[instance - 1].args, 0) : bt::error;
if members == bt::error || this.c.checker.named_kind(this.c.checker.unalias(members)) != dk::enum_type {
this.problem(node, "`rank_of` and `member_at` count the members of an enum.");
return this.zero_value(kind);
}
val made := name == "rank_of" ? this.member_rank(args[0], members) : this.member_of_rank(args[0], members);
return operand::one(kind, made);
}
if name == "raw_allocate" || name == "raw_allocate_zeroed" {
val uncleared: u32 = name == "raw_allocate" ? 1 : 0;
return operand::one(kind, this.build.value(op::allocate, args.view(), vt::word, uncleared, 0));
}
if name == "raw_release" {
this.build.effect(op::release, args.view(), 0, 0);
return operand::none(kind);
}
# `core::close` closes a value where it is, as its scope ending would: its own
# `close`, then what it holds that closes.
if name == "close_where_it_is" {
val instance := this.called(node);
if instance != 0 && args.length > 0 {
val closed := this.c.checker.types.part_at(this.c.checker.instances[instance - 1].args, 0);
val place := location { kind = closed, address = args[0] };
this.close(&place);
}
return operand::none(kind);
}
if name == "raw_resize" {
return operand::one(kind, this.build.value(op::resize, args.view(), vt::word, 0, 0));
}
if name == "syscall" {
return operand::one(kind, this.build.value(op::syscall, args.view(), vt::word, 0, 0));
}
if name == "frame" || name == "executable" || name == "environ" || name == "take_signals" || name == "current" {
val chosen := name == "frame" ? op::frame : name == "executable" ? op::image : name == "environ" ? op::environ
: name == "current" ? op::current : op::signals;
return operand::one(kind, this.build.value(chosen, span::<u32>::empty(), vt::word, 0, 0));
}
# A thread runs the function value, of two words, given the context, a word;
# the runtime starts one of the system on a record's stacks.
if name == "start" || name == "clone_thread" {
return operand::one(kind, this.build.value(name == "start" ? op::start : op::clone, args.view(), vt::word, 0, 0));
}
if name == "catch_signal" {
return operand::one(kind, this.build.value(op::catch, args.view(), vt::word, 0, 0));
}
if name == "exit" {
this.build.effect(op::exit, args.view(), 0, 0);
return operand::none(kind);
}
if name == "abort" {
this.build.effect(op::abort, span::<u32>::empty(), 0, 0);
return operand::none(kind);
}
if name == "trap" {
this.build.effect(op::trap, args.view(), 0, 0);
return operand::none(kind);
}
# Operations of the machine on a whole real or word, which `std::math` narrows
# for the other types.
if name == "square_root" {
return operand::one(kind, this.build.unary(op::fsqrt, args[0]));
}
if name == "ones_in" || name == "zeros_leading" || name == "zeros_trailing" || name == "bytes_reversed" {
val chosen := name == "ones_in" ? op::ones : name == "zeros_leading" ? op::clz : name == "zeros_trailing" ? op::ctz : op::bswap;
return operand::one(kind, this.build.unary(chosen, args[0]));
}
this.problem(node, "The intrinsic is not lowered.");
return this.zero_value(kind);
}
#! `lanes_have` and `lanes_apply`, of an operation on lanes: in an executable,
#! whether the processor it runs on has the vector instructions working it, as
#! it found when it started, and the lanes worked with them. The virtual machine
#! and constants have none, so never reach the second.
#! @param this The emitter.
#! @param node The `call` node.
#! @param have Whether it is `lanes_have`.
#! @param kind What it gives.
#! @returns What it gives.
def emitter::lanes(&mut this, node: u32, have: bool, kind: u32): operand {
# Its type arguments are the type of lane, the operation, and how many lanes.
var lane := lane_none;
var operation: u32 = 0;
var count: u64 = 0;
val instance := this.called(node);
if instance != 0 {
val args: u32 = this.c.checker.instances[instance - 1].args;
lane = this.lane_of(this.c.checker.types.part_at(args, 0));
operation = this.constant_argument(this.c.checker.types.part_at(args, 1)) as u32;
count = this.constant_argument(this.c.checker.types.part_at(args, 2));
}
val native := !this.c.options.evaluating && this.c.checker.names.text(this.c.checker.target.backend) == "native";
val need := native && lane != lane_none ? lanes_needs(operation, lane, count * lane_bits(lane) / 8) : cpu_never;
if have {
return operand::one(kind, this.build.word(0)) if need == cpu_never;
return operand::one(kind, this.build.word(1)) if need == cpu_sse2;
val found := this.build.value(op::cpu, span::<u32>::empty(), vt::word, 0, 0);
val held := this.build.binary(op::band, found, this.build.word(need));
return operand::one(kind, this.build.binary(op::eq, held, this.build.word(need)));
}
if need == cpu_never {
this.build.unreachable();
return operand::none(kind);
}
# The pointers: where the result goes, then the operands.
var pointers := vector::<u32>::new();
val run := this.c.checker.right_of(node);
for i in 0..this.c.checker.run_length(run) {
val made := this.value(this.c.checker.run_at(run, i as u32));
made.args(&mut pointers);
}
# The operands are read, worked as values, and the result written, so a
# vector a cell holds is a value wherever the cell is promoted.
val bytes := count * lane_bits(lane) / 8;
var args := vector::<u32>::new();
for k in 0..lanes_operands(operation) {
val how := lanes_operand_access(operation, lane, bytes, k);
args.append(this.build.load(how, pointers[1 + k as u64], 0));
}
val result := lanes_result_access(operation, lane, bytes);
val made := operation == lanes_copy ? args[0]
: this.build.value(op::lanes, args.view(), result.value_type(), operation, lane as u64 | bytes << 8);
this.build.store(result, pointers[0], 0, made);
return operand::none(kind);
}
#! The atomics of `core::atomic`: an operation on the `T` at an address, in one
#! step, which is the first type argument, and of `atomic_fetch` the operation
#! the second. A compare-exchange gives whether it wrote, and writes what it
#! found where a pointer it is given points.
#! @param this The emitter.
#! @param node The `call` node.
#! @param name The intrinsic's name.
#! @param kind What it gives.
#! @returns What it gives.
def emitter::atomic(&mut this, node: u32, name: strview, kind: u32): operand {
var operation := name == "atomic_load" ? atomic_load : name == "atomic_store" ? atomic_store
: name == "atomic_exchange" ? atomic_exchange : name == "atomic_compare_exchange" ? atomic_compare_exchange
: name == "atomic_fence" ? atomic_fence : atomic_add;
var how := access::i64;
var unsigned: u64 = 0;
val instance := this.called(node);
if instance != 0 && operation != atomic_fence {
val args: u32 = this.c.checker.instances[instance - 1].args;
val held := this.c.checker.types.part_at(args, 0);
how = this.c.shape_of(held).how;
if this.c.checker.types.kind_of(this.c.checker.unalias(held)) == ty::unsigned {
unsigned = atomic_unsigned;
}
if name == "atomic_fetch" {
operation = this.constant_argument(this.c.checker.types.part_at(args, 1)) as u32;
}
}
var values := vector::<u32>::new();
val run := this.c.checker.right_of(node);
for i in 0..this.c.checker.run_length(run) {
val made := this.value(this.c.checker.run_at(run, i as u32));
made.args(&mut values);
}
if operation == atomic_fence {
this.build.effect(op::atomic, values.view(), operation, 0);
return operand::none(kind);
}
# While compiling, what it reaches is checked as a read through a pointer is.
this.reaches(values[0], this.build.word(1), how.width());
if operation == atomic_compare_exchange {
this.reaches(values[3], this.build.word(1), how.width());
var args: u32[5] = [values[0], values[1], values[2], values[4], values[5]];
val found := this.build.value(op::atomic, args[0:5], vt::word, operation, how as u64 | unsigned);
this.build.store(how, values[3], 0, found);
return operand::one(kind, this.build.binary(op::eq, found, values[1]));
}
if atomic_gives(operation) {
return operand::one(kind, this.build.value(op::atomic, values.view(), vt::word, operation, how as u64 | unsigned));
}
this.build.effect(op::atomic, values.view(), operation, how as u64 | unsigned);
return operand::none(kind);
}
#! The type of lane a number is, as vector instructions take it.
#! @param this The emitter.
#! @param kind The type.
#! @returns The type of lane, or `lane_none` where it is no number.
def emitter::lane_of(&mut this, kind: u32): u32 {
val plain := this.c.checker.unalias(kind);
val of := this.c.checker.types.kind_of(plain);
val bits := this.c.checker.types.first_of(plain);
if of == ty::floating {
return bits == 32 ? lane_f32 : lane_f64;
}
return lane_none if of != ty::signed && of != ty::unsigned;
val width: u32 = bits == 8 ? 0 : bits == 16 ? 2 : bits == 32 ? 4 : 6;
return width + (of == ty::unsigned ? 1 : 0);
}
#! The number a constant type argument is.
#! @param this The emitter.
#! @param arg The type argument.
#! @returns The number, or 0 where it is none.
def emitter::constant_argument(&mut this, arg: u32): u64 {
return 0 if this.c.checker.types.kind_of(arg) != ty::value;
return this.c.checker.known_at(this.c.checker.types.second_of(arg)).value.magnitude;
}
#! Where a call is written, as `core::site`: its file, line, and column, and the
#! signature of the function holding it.
#! @param this The emitter.
#! @param node The `call` node.
#! @param kind The `site` type.
#! @returns The value.
def emitter::call_site(&mut this, node: u32, kind: u32): operand {
# In a default, it is where the call leaving the parameter out is.
val file := this.defaulting.node != 0 ? this.defaulting.file : this.c.checker.at.file;
val site := this.defaulting.node != 0 ? this.defaulting.node : node;
val held := &this.c.checker.units[file].source;
val offset := this.c.node_offset(file, site);
val at := held.lines.place_of(offset);
val plain := this.c.checker.unalias(kind);
val index := this.c.layout_of(plain);
val shape := this.c.layout_at(index);
val address := this.temporary_of(kind);
this.build.clear(address, shape.size);
val whole := location { kind = kind, address = address, framed = true };
var signature := string::new(nothing {});
val decl: u32 = this.c.program.functions[this.function].decl;
if decl != 0 {
this.c.signature_text(decl, &mut signature);
}
for i in 0..shape.count {
val field := this.c.field_at(index, i as u32);
val name := this.c.checker.names.text(field.name);
val place := this.within(&whole, field.offset, field.type_id);
var value := operand {};
if name == "path" {
value = this.text_value(held.path, field.type_id);
} else if name == "line" {
value = operand::one(field.type_id, this.build.word(at.line as u64));
} else if name == "column" {
value = operand::one(field.type_id, this.build.word(at.column as u64));
} else if name == "signature" {
value = this.text_value(signature.view(), field.type_id);
} else {
continue;
}
this.store(&place, &value);
}
return operand::at(kind, address);
}
#! The text an expression is written as, without the spaces around it.
#! @param this The emitter.
#! @param node The expression.
#! @param out Where the text is written.
pub def emitter::source_text(&mut this, node: u32, out: &mut string): void {
val file := this.c.checker.at.file;
val syntax := &this.c.checker.units[file].syntax;
val held := &this.c.checker.units[file].source;
# A node's own token may come after those of what it was parsed from, as an
# operator's comes after its left operand, so the first is the least of all.
var first: u32 = syntax.node_tokens[node];
var walk := node_walk::new(node);
while walk.more() {
val at := walk.next();
val token := syntax.node_tokens[at];
first = token < first ? token : first;
walk.enter(&syntax, at);
}
val last := syntax.node_end(node);
val begin := syntax.token_offsets[first];
val end := syntax.token_offsets[last] + syntax.token_length(last, this.c.checker.names);
return if end <= begin;
out.append(held.make_lexeme(begin, end - begin));
}
#! What the operands of an expression held, as `values_of` gives it: both
#! operands of a comparison, or the expression itself, each as `text = value`,
#! but for literals, which say what they hold already.
#! @param this The emitter.
#! @param node The expression, or 0.
#! @param kind The `string` type.
#! @returns The text.
def emitter::values_of(&mut this, node: u32, kind: u32): operand {
this.build.effect(op::format, span::<u32>::empty(), 0, 0);
if node != 0 {
this.write_values(node, "");
}
return this.owned_text(kind);
}
#! Writes what the operands of an expression held into the text being made, as
#! `values_of` gives it, after a lead where there are any.
#! @param this The emitter.
#! @param node The expression.
#! @param lead What comes before the first, as `, with `, or nothing.
pub def emitter::write_values(&mut this, node: u32, lead: strview): void {
var named := vector::<u32>::new();
val shape := this.c.checker.kind_of(node);
if shape == nk::binary {
val operator := this.c.checker.token_kind(node);
if operator.compares() {
named.append(this.c.checker.left_of(node));
named.append(this.c.checker.right_of(node));
}
} else if shape != nk::unary {
named.append(node);
}
var first := true;
for &each in named {
val literal := this.c.checker.kind_of(each);
continue if literal == nk::number || literal == nk::string || literal == nk::character || literal == nk::boolean
|| literal == nk::null_lit;
if !first {
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(", "), 0);
} else if lead.length != 0 {
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(lead), 0);
}
first = false;
var text := string::new(nothing {});
this.source_text(each, &mut text);
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(text.view()), 0);
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(" = "), 0);
val mark := this.cell_mark();
val value := this.value(each);
this.format_value(&value);
this.release(mark);
}
}
#! `attached::<A>(d)`: a view of the values of the attributes of the type `A`
#! written on the declaration `d` describes, in the order they are written, each
#! made as the struct literal it is, where the declaration is. They are held as
#! long as the function runs, since the view may outlive the statement.
#! @param this The emitter.
#! @param node The `call` node.
#! @param kind The view's type.
#! @returns The view.
def emitter::attached(&mut this, node: u32, kind: u32): operand {
val view := this.temporary_of(kind);
this.build.clear(view, 2 * word_size);
val run := this.c.checker.right_of(node);
val wanted := this.c.viewed(kind);
return operand::at(kind, view) if wanted == 0 || this.c.checker.run_length(run) == 0;
val one := this.c.checker.reflected_one(this.c.checker.run_at(run, 0));
return operand::at(kind, view) if one == checker::no_reflection;
val held: desc = this.c.checker.descs[one];
return operand::at(kind, view) if held.param != 0;
# The attributes of the type, in the order they are written.
val decl := held.decl;
var types := this.c.checker.attribute_types(decl);
val saved := this.c.checker.at;
this.c.checker.use_table(this.c.checker.units[this.c.checker.decls.files.p[decl]].table);
val attrs := this.c.checker.attributes_of(this.c.checker.decls.nodes.p[decl]);
var chosen := vector::<u32>::new();
var at: u64 = 0;
for i in 0..this.c.checker.run_length(attrs) {
val attr := this.c.checker.run_at(attrs, i as u32);
continue if this.c.checker.kind_of(attr) != nk::attribute;
if at < types.length && this.c.checker.strip(types[at], 0) == this.c.checker.strip(wanted, 0) {
chosen.append(attr);
}
at++;
}
if chosen.length == 0 {
this.c.checker.at = saved;
return operand::at(kind, view);
}
val shape := this.c.shape_of(wanted);
val array := this.c.checker.types.fixed(wanted, chosen.length as u32);
val whole := this.c.shape_of(array);
val cell := this.build.code.add_cell(round_up(whole.size, word_size) as u32,
whole.align < word_size ? word_size as u32 : whole.align as u32, ck::local, 0);
val first := this.build.cell_address(cell);
for i in 0..chosen.length {
val made := this.construct_of(wanted, this.c.checker.right_of(chosen[i]));
val place := location { kind = wanted, address = first, offset = i * shape.size, framed = true };
this.store(&place, &made);
}
this.c.checker.at = saved;
this.build.store(access::i64, view, 0, first);
this.build.store(access::i64, view, word_size, this.build.word(chosen.length));
return operand::at(kind, view);
}
+410
View File
@@ -0,0 +1,410 @@
#! @file loops.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the lowering of `for`: counting through a range, walking the
#! elements of a fixed array or a view, each bound by reference, asking an
#! iterator for each element until it gives none, and `for const`, whose body
#! the checker checked once for each value of a pack.
import sakura::analyzer;
module sakura::compiler;
#! Lowers `for`.
#! @param this The emitter.
#! @param node The `for_stmt` node.
pub def emitter::for_statement(&mut this, node: u32): void {
val iterated := this.c.checker.record(node, for_slot::iterated);
val end := this.c.checker.record(node, for_slot::end);
if this.c.checker.node_has(node, nf::constant) {
this.unrolled(node);
return;
}
if end != 0 {
this.for_range(node);
return;
}
# What's walked is of the type it's converted to, as a literal of text is a
# `strview`.
val through := this.c.checker.unalias(this.c.checker.reached(this.c.checker.converted(iterated)));
if this.c.checker.types.kind_of(through) == ty::fixed || this.c.viewed(through) != 0 {
this.for_elements(node, through);
return;
}
this.for_iterator(node, through);
}
#! A loop's blocks: where each pass begins, its body, where `continue` goes, and
#! where it ends.
struct loop_blocks {
var head: u32; #! Where each pass asks whether there is another.
var body: u32; #! The body.
var next: u32; #! Where `continue` goes, which steps to the next pass.
var exit: u32; #! Where it ends.
}
#! Makes the blocks of a loop, and goes to its head.
#! @param this The emitter.
#! @returns The blocks.
def emitter::begin_loop(&mut this): loop_blocks {
val made := loop_blocks {
head = this.build.new_block(),
body = this.build.new_block(),
next = this.build.new_block(),
exit = this.build.new_block()
};
this.build.jump(made.head);
this.build.switch_to(made.head);
return made;
}
#! Lowers a loop's body, with `break` and `continue` going where the loop says,
#! then goes to the step to the next pass.
#! @param this The emitter.
#! @param blocks The loop's blocks.
#! @param body The body's node.
#! @param locals How many locals there were before the loop's variables,
#! which each pass closes past.
def emitter::loop_body(&mut this, blocks: &loop_blocks, body: u32, locals: u64): void {
this.safepoint();
this.loops.append(loop_info { exit = blocks.exit, next = blocks.next, locals = locals, kept = this.kept.length });
this.lower_block(body);
this.loops.truncate();
this.close_locals(locals, 0);
this.build.jump(blocks.next);
this.build.seal(blocks.next);
this.build.switch_to(blocks.next);
}
#! Goes into a loop's body where there is another pass, and leaves it where not.
#! @param this The emitter.
#! @param blocks The loop's blocks.
#! @param more Whether there is another pass.
#! @returns How many locals there were before the pass's own.
def emitter::enter_pass(&mut this, blocks: &loop_blocks, more: u32): u64 {
this.build.branch(more, blocks.body, blocks.exit);
this.build.seal(blocks.body);
this.build.switch_to(blocks.body);
return this.scope_mark();
}
#! Lowers the body of a counted pass, then counts it and ends the loop.
#! @param this The emitter.
#! @param blocks The loop's blocks.
#! @param node The `for_stmt` node.
#! @param locals How many locals there were before the pass's own.
#! @param counter The variable counting the passes.
def emitter::end_pass(&mut this, blocks: &loop_blocks, node: u32, locals: u64, counter: u32): void {
this.loop_body(blocks, this.c.checker.right_of(node), locals);
this.forget_locals(locals);
this.count_on(counter, blocks.head, blocks.exit);
}
#! Ends a loop: the step jumps back to its head, and what follows goes on from
#! its exit.
#! @param this The emitter.
#! @param blocks The loop's blocks.
def emitter::end_loop(&mut this, blocks: &loop_blocks): void {
this.close_loop(blocks.head, blocks.exit);
}
#! Ends a loop of the blocks given: where the code is jumps back to its head,
#! every way into which is known then, and what follows goes on from its exit.
#! @param this The emitter.
#! @param head The loop's head.
#! @param exit The block after it.
def emitter::close_loop(&mut this, head: u32, exit: u32): void {
this.build.jump(head);
this.build.seal(head);
this.build.seal(exit);
this.build.switch_to(exit);
}
#! Goes into a loop counting a variable up to a count, as one over the elements
#! of a fixed array does: its head goes into its body while the variable is
#! below the count, and out of the loop otherwise, and what follows is the body.
#! @param this The emitter.
#! @param index The variable, which holds where the count begins.
#! @param count The count, which the variable stays below.
#! @param head The loop's head.
#! @param body Its body.
#! @param exit The block after it.
#! @returns What the variable holds in the body.
def emitter::count_up(&mut this, index: u32, count: u64, head: u32, body: u32, exit: u32): u32 {
this.build.jump(head);
this.build.switch_to(head);
val at := this.build.read(index);
this.build.branch(this.build.binary(op::ltu, at, this.build.word(count)), body, exit);
this.build.seal(body);
this.build.switch_to(body);
return at;
}
#! Ends the pass of a loop counting a variable up: counts it, and ends the loop.
#! @param this The emitter.
#! @param index The variable.
#! @param head The loop's head.
#! @param exit The block after it.
def emitter::count_on(&mut this, index: u32, head: u32, exit: u32): void {
this.build.assign(index, this.build.binary(op::add, this.build.read(index), this.build.word(1)));
this.close_loop(head, exit);
}
#! Declares the variable of a loop's pass, and its index, where it has one.
#! @param this The emitter.
#! @param node The `for_stmt` node.
#! @param value The value the variable is given.
#! @param counter The index of the pass, a word.
#! @param closes Whether the variable is the loop's own, closed where each
#! pass ends.
def emitter::bind_pass(&mut this, node: u32, value: &operand, counter: u32, closes: bool): void {
val variable := this.c.checker.record(node, for_slot::variable);
val index := this.c.checker.record(node, for_slot::index);
if variable != 0 {
val kind := this.c.checker.type_at(variable);
val place := this.new_place(variable, kind);
val made := this.convert(value, kind);
this.store(&place, &made);
this.declare(variable, place, closes);
}
if index != 0 {
val place := this.new_place(index, bt::uint64);
val made := operand::one(bt::uint64, counter);
this.store(&place, &made);
this.declare(index, place, false);
}
}
#! `for i in a..b`: counts from the start to just before the end, or through it
#! where the loop is `a..=b`, each count a variable of the body's own. A range
#! of an enum's members counts their places among the values of its members,
#! each pass's variable the member at its place.
#! @param this The emitter.
#! @param node The `for_stmt` node.
def emitter::for_range(&mut this, node: u32): void {
val mark := this.begin_statement();
val variable := this.c.checker.record(node, for_slot::variable);
val kind := variable != 0 ? this.c.checker.type_at(variable) : this.c.checker.converted(this.c.checker.record(node, for_slot::iterated));
val start := this.value_as(this.c.checker.record(node, for_slot::iterated), kind);
val limit := this.value_as(this.c.checker.record(node, for_slot::end), kind);
val members := this.c.checker.named_kind(this.c.checker.unalias(kind)) == dk::enum_type;
val first := members ? this.member_rank(start.words[0], kind) : start.words[0];
val last := members ? this.member_rank(limit.words[0], kind) : limit.words[0];
val count := this.build.variable(vt::word);
this.build.assign(count, first);
# `a..=b` gives `b` too, so whether another pass follows is kept apart from the
# count, which may pass the end of its type after `b`.
val inclusive := this.c.checker.node_has(node, nf::inclusive);
val signed := !members && this.is_signed(kind);
var keep: u32 = 0;
if inclusive {
keep = this.build.variable(vt::word);
this.build.assign(keep, this.build.binary(signed ? op::les : op::leu, first, last));
}
val blocks := this.begin_loop();
val more := inclusive
? this.build.read(keep)
: this.build.binary(signed ? op::lts : op::ltu, this.build.read(count), last);
val locals := this.enter_pass(&blocks, more);
if variable != 0 {
val place := this.new_place(variable, kind);
val counted := this.build.read(count);
val made := operand::one(kind, members ? this.member_of_rank(counted, kind) : counted);
this.store(&place, &made);
this.declare(variable, place, false);
}
if inclusive {
this.loop_body(&blocks, this.c.checker.right_of(node), locals);
this.forget_locals(locals);
this.build.assign(keep, this.build.binary(op::ne, this.build.read(count), last));
this.count_on(count, blocks.head, blocks.exit);
} else {
this.end_pass(&blocks, node, locals, count);
}
this.end_statement(mark);
}
#! Walks the elements of a fixed array or a view, which lie one after another,
#! binding a reference to each.
#! @param this The emitter.
#! @param node The `for_stmt` node.
#! @param through The type walked, read through its references.
def emitter::for_elements(&mut this, node: u32, through: u32): void {
val mark := this.begin_statement();
val whole := this.object(this.c.checker.record(node, for_slot::iterated));
var first: u32 = 0;
var limit: u32 = 0;
var element: u32 = 0;
if this.c.checker.types.kind_of(through) == ty::fixed {
val shape := this.c.shape_of(through);
first = this.address_of(&whole);
limit = this.build.word(shape.count as u64);
element = this.c.checker.types.first_of(through);
} else {
first = this.build.load(access::i64, whole.address, whole.offset);
limit = this.build.load(access::i64, whole.address, whole.offset + word_size);
element = this.c.viewed(through);
}
val size := this.c.shape_of(element).size;
val counter := this.build.variable(vt::word);
this.build.assign(counter, this.build.word(0));
val blocks := this.begin_loop();
val locals := this.enter_pass(&blocks, this.build.binary(op::ltu, this.build.read(counter), limit));
val address := this.build.binary(op::add, first, this.scaled(this.build.read(counter), size));
val reference := operand::one(this.c.checker.types.reference(element, true), address);
this.bind_pass(node, &reference, this.build.read(counter), false);
this.end_pass(&blocks, node, locals, counter);
this.end_statement(mark);
}
#! Asks an iterator for each element until it gives `none`. The iterator is the
#! one the loop is given, advanced where it is, or the one what it walks lends
#! through `iter`, which the loop holds and closes where it ends. An element
#! given by value is the loop's own, closed where each pass ends.
#! @param this The emitter.
#! @param node The `for_stmt` node.
#! @param through The type walked, read through its references.
def emitter::for_iterator(&mut this, node: u32, through: u32): void {
val mark := this.begin_statement();
val iterated := this.c.checker.record(node, for_slot::iterated);
val mutable := this.c.checker.node_has(node, nf::mutable);
val locals := this.scope_mark();
# The iterator, where it is: what the loop is given, or what `iter` lends.
var cursor_place := location {};
var cursor_type := through;
if !this.c.checker.has_method(through, word::next) {
val lends := this.c.checker.pick_iter(through, mutable);
val receiver := this.c.is_reference_type(this.c.checker.type_at(iterated))
? this.through_one(iterated)
: this.reference_arg(iterated, this.c.checker.types.reference(through, mutable));
val made := this.method_call(lends, through, &receiver, span::<operand>::empty());
this.adopt(&made);
cursor_type = this.c.checker.unalias(made.kind);
cursor_place = this.fresh_place(made.kind);
this.store(&cursor_place, &made);
this.declare(this.c.checker.right_of(node), cursor_place, this.c.checker.closes(made.kind));
} else if this.c.is_reference_type(this.c.checker.type_at(iterated)) {
val made := this.through_one(iterated);
cursor_place = this.referent(&made);
} else if this.c.checker.is_place(iterated) {
cursor_place = this.place_of(iterated);
} else {
val made := this.value_of_type(iterated);
this.adopt(&made);
cursor_place = this.fresh_place(made.kind);
this.store(&cursor_place, &made);
this.declare(this.c.checker.right_of(node), cursor_place, this.c.checker.closes(made.kind));
}
val next := this.c.checker.find_member(cursor_type, word::next);
val counter := this.build.variable(vt::word);
this.build.assign(counter, this.build.word(0));
val blocks := this.begin_loop();
# `next` gives `some` of the element while there are more, and `none` after.
val receiver := this.reference_to(&cursor_place, this.c.checker.types.reference(cursor_type, true));
val given := this.method_call(next.decl, cursor_type, &receiver, span::<operand>::empty());
val maybe := this.hold(&given);
val plain := this.c.checker.unalias(given.kind);
val index := this.c.layout_of(plain);
var some: u32 = 0;
for i in 0..this.c.layout_at(index).count {
if this.c.field_at(index, i as u32).name == word::some {
some = i as u32;
}
}
val passes := this.enter_pass(&blocks, this.tag_is(&maybe, some));
val field := this.c.field_at(index, some);
val payload := this.within(&maybe, field.offset, field.type_id);
val element := this.load(&payload);
this.bind_pass(node, &element, this.build.read(counter), !this.c.is_reference_type(field.type_id) && this.c.checker.closes(field.type_id));
this.end_pass(&blocks, node, passes, counter);
# Leaving the loop, by its end or a `break`, closes the iterator it holds.
this.end_scope(locals, 0);
this.end_statement(mark);
}
#! The reference a node is, read through the references it refers to until one
#! refers to what is no reference.
#! @param this The emitter.
#! @param node The node, of a reference type.
#! @returns The reference.
def emitter::through_one(&mut this, node: u32): operand {
var made := this.value_of_type(node);
while this.c.is_reference_type(this.c.checker.types.first_of(this.c.checker.unalias(made.kind))) {
val place := this.referent(&made);
made = this.load(&place);
}
return made;
}
#! `for const`: the body the checker checked once for each value of a pack, or
#! each declaration reflection gives, each with a result table of its own, run
#! one after another. `continue` goes on to the next, and `break` past the last.
#! @param this The emitter.
#! @param node The `for_stmt` node.
def emitter::unrolled(&mut this, node: u32): void {
val variable := this.c.checker.record(node, for_slot::variable);
val iterated := this.c.checker.record(node, for_slot::iterated);
val body := this.c.checker.right_of(node);
val outer := this.c.checker.at.table;
val pack := this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(iterated)));
val is_pack := this.c.checker.types.kind_of(pack) == ty::pack;
# The tables the checker made for each pass, in order.
var tables := vector::<u32>::new();
for t in 0..this.c.checker.tables.length {
val held: rtable = this.c.checker.tables.p[t];
if held.parent == outer + 1 && held.base == variable && held.count == body - variable + 1 {
tables.append(t as u32);
}
}
# The pack is named in the table around the passes, which theirs do not hold.
var values := vector::<location>::new();
if is_pack {
for i in 0..this.c.checker.types.part_count(pack) {
values.append(this.pack_place(iterated, i as u32));
}
}
val exit := this.build.new_block();
for i in 0..tables.length {
val next := this.build.new_block();
this.c.checker.use_table(tables[i]);
val locals := this.scope_mark();
if is_pack {
# The variable is the pack's value itself, so writing it writes the pack.
val place: location = i < values.length ? values[i] : location { kind = bt::error };
this.declare(variable, place, false);
} else if this.c.checker.record(node, for_slot::end) != 0 {
# The variable is the number this pass counts.
val kind := this.c.checker.type_at(variable);
val made := this.known(&this.c.checker.value_at(variable), kind);
val place := this.new_place(variable, kind);
this.store(&place, &made);
this.declare(variable, place, false);
} else {
this.reflected_pass(variable);
}
this.loops.append(loop_info { exit = exit, next = next, locals = locals, kept = this.kept.length });
this.lower_block(body);
this.loops.truncate();
this.end_scope(locals, 0);
this.build.jump(next);
this.build.seal(next);
this.build.switch_to(next);
this.c.checker.use_table(outer);
}
this.build.jump(exit);
this.build.seal(exit);
this.build.switch_to(exit);
}
+238
View File
@@ -0,0 +1,238 @@
#! @file match.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the lowering of `match`: the first arm naming the field a union
#! holds, or the member an enum is, or a value equal to the subject, runs, or
#! else the `else` arm. A union's arm may name the value its field holds, a
#! copy of it, taken out where it closes, or with `&` or `&mut` a reference to
#! it. A match used as a value gives what its arm gives.
import sakura::analyzer;
module sakura::compiler;
#! A `match` used as a value.
#! @param this The emitter.
#! @param node The `match_value` node.
#! @returns What the arm taken gives.
pub def emitter::match_value(&mut this, node: u32): operand {
return this.lower_match(node, true);
}
#! Lowers a match, as a statement or as a value.
#! @param this The emitter.
#! @param node The `match_stmt` or `match_value` node.
#! @param value Whether it is used as a value.
#! @returns What the arm taken gives, where it is used as a value.
pub def emitter::lower_match(&mut this, node: u32, value: bool): operand {
val subject := this.c.checker.left_of(node);
val arms := this.c.checker.right_of(node);
val kind := value ? this.c.checker.type_at(node) : bt::void_type;
val whole := this.object(subject);
val plain := this.c.checker.unalias(whole.kind);
val union_like := this.c.checker.named_kind(plain) == dk::union_type;
# Values are compared with the subject as read once, before any arm runs.
var held := operand {};
if !union_like {
held = this.load(&whole);
}
val result := value ? this.result_place(kind) : location {};
val join := this.build.new_block();
var otherwise := false;
for i in 0..this.c.checker.run_length(arms) {
val arm := this.c.checker.run_at(arms, i as u32);
val patterns := this.c.checker.left_of(arm);
val body := this.c.checker.right_of(arm);
if patterns == 0 {
this.lower_arm(arm, body, value, kind, &result, &whole, 0, 0);
this.build.jump(join);
otherwise = true;
break;
}
# The arm runs where any of its patterns does.
val taken := this.build.new_block();
val next := this.build.new_block();
var field: u32 = 0;
var binding: u32 = 0;
for j in 0..this.c.checker.run_length(patterns) {
val pattern := this.c.checker.run_at(patterns, j as u32);
val failed := j + 1 == this.c.checker.run_length(patterns) as u64 ? next : this.build.new_block();
var test: u32 = 0;
if union_like {
field = this.c.checker.ref_at(pattern);
if this.c.checker.kind_of(pattern) == nk::call {
val given := this.c.checker.right_of(pattern);
if this.c.checker.run_length(given) == 1 {
binding = this.c.checker.named_binding(this.c.checker.run_at(given, 0));
}
}
test = this.tag_is(&whole, this.field_index(plain, field));
} else {
test = this.equals_value(&held, pattern, plain);
}
this.build.branch(test, taken, failed);
if failed != next {
this.build.seal(failed);
this.build.switch_to(failed);
}
}
this.build.seal(taken);
this.build.seal(next);
this.build.switch_to(taken);
this.lower_arm(arm, body, value, kind, &result, &whole, field, binding);
this.build.jump(join);
this.build.switch_to(next);
}
# A match used as a value with no `else` finds no arm only for a value no enum
# member has, which only memory written through pointers can hold, and which
# only code that checks looks for.
if !otherwise {
if value && this.checking() {
this.build.trap(fault::not_member as u32);
} else if value {
this.build.unreachable();
} else {
this.build.jump(join);
}
}
this.build.seal(join);
this.build.switch_to(join);
return operand::none(bt::void_type) if !value;
val made := this.load_result(&result);
this.keep(&made);
return made;
}
#! The index of a union's field among its fields.
#! @param this The emitter.
#! @param kind The union's type, without aliases.
#! @param field The field's declaration.
#! @returns Its index.
pub def emitter::field_index(&mut this, kind: u32, field: u32): u32 {
val index := this.c.layout_of(kind);
for i in 0..this.c.layout_at(index).count {
return i as u32 if this.c.field_at(index, i as u32).decl == field;
}
return 0;
}
#! Whether a value equals a pattern's: as words, or through `equals`, or part by
#! part for what the language compares that way.
#! @param this The emitter.
#! @param held The value.
#! @param pattern The pattern's node.
#! @param kind The type compared, without aliases.
#! @returns A word of 1 where they are equal.
def emitter::equals_value(&mut this, held: &operand, pattern: u32, kind: u32): u32 {
val given := this.value_as(pattern, kind);
val shape := this.c.shape_of(kind);
if !in_memory(&shape) {
if this.c.checker.has_method(kind, word::equals) && this.c.checker.named_kind(kind) != dk::enum_type
&& !this.c.checker.types.is_numeric(kind) && this.c.checker.types.kind_of(kind) != ty::pointer
&& !this.c.checker.types.is_boolean(kind) {
return this.equals_call(held, &given, kind);
}
val floating := shape.kind == lk::floating;
return this.build.binary(floating ? op::feq : op::eq, held.words[0], given.words[0]);
}
if this.c.checker.has_method(kind, word::equals) {
return this.equals_call(held, &given, kind);
}
var args: u32[2] = [held.address, given.address];
return this.build.value(op::equal, args[0:2], vt::word, this.c.layout_of(kind), 0);
}
#! Calls a type's `equals` on two values, given references to each.
#! @param this The emitter.
#! @param a One value.
#! @param b The other.
#! @param kind Their type, without aliases.
#! @returns A word of 1 where they are equal.
def emitter::equals_call(&mut this, a: &operand, b: &operand, kind: u32): u32 {
val method := this.pick_method(kind, word::equals, true);
val reference := this.c.checker.types.reference(kind, false);
val left := this.hold(a);
val right := this.hold(b);
val subject := this.reference_to(&left, reference);
var others: operand[1] = [this.reference_to(&right, reference)];
val made := this.method_call(method, kind, &subject, others[0:1]);
return made.words[0];
}
#! Lowers an arm: the value its pattern names, where it names one, and its body,
#! whose value the match gives where it is used as one.
#! @param this The emitter.
#! @param arm The arm's node.
#! @param body Its body's node.
#! @param value Whether the match is used as a value.
#! @param kind The match's type.
#! @param result Where its value goes.
#! @param whole The place of the subject.
#! @param field The field the arm names of a union, or 0.
#! @param binding The node naming the field's value, or 0.
def emitter::lower_arm(
&mut this,
arm: u32,
body: u32,
value: bool,
kind: u32,
result: &location,
whole: &location,
field: u32,
binding: u32
): void {
val locals := this.scope_mark();
var named: u32 = 0;
if binding != 0 && field != 0 {
val refers := this.c.checker.kind_of(binding) == nk::reference;
named = refers ? this.c.checker.left_of(binding) : binding;
val plain := this.c.checker.unalias(whole.kind);
val held := this.c.field_at(this.c.layout_of(plain), this.field_index(plain, field));
val payload := this.within(whole, held.offset, held.type_id);
val bound := this.c.checker.type_at(named);
val place := this.new_place(named, bound);
if refers {
# A field holding a reference gives that reference, since references
# never stack.
var made := operand {};
if this.c.checker.has_flag(binding, rf::relent) {
val inner := this.load(&payload);
made = this.convert(&inner, bound);
} else {
made = this.reference_to(&payload, bound);
}
this.store(&place, &made);
this.declare(named, place, false);
} else {
val made := this.load(&payload);
val converted := this.convert(&made, bound);
this.store(&place, &converted);
val closes := this.c.checker.closes(held.type_id);
if closes {
this.zero(&payload);
}
this.declare(named, place, closes);
}
}
# An arm giving the value its name took hands it over to the match.
var given: u32 = 0;
if value {
if this.c.checker.kind_of(body) == nk::name && named != 0 && (this.c.checker.ref_at(body) & ref_mask) == named {
given = named;
}
val made := this.value_as(body, kind);
this.adopt(&made);
this.store(result, &made);
} else {
this.lower_block(body);
}
this.end_scope(locals, given);
}
File diff suppressed because it is too large. Load diff
+146
View File
@@ -0,0 +1,146 @@
#! @file ownership.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains closing values: a value of a type naming `owning` is closed by its
#! own `close`, and then what it holds is closed, in the reverse of the order
#! it was written, as a scope closes its locals. Also contains the text a
#! format made, which a `string` holding no allocator owns.
import sakura::analyzer;
module sakura::compiler;
#! Closes a value where it is: its own `close` first, then the fields it holds
#! that close, the last first, or of a union the one it holds, or of a fixed
#! array each element, the last first. Closing a zeroed value closes nothing.
#! @param this The emitter.
#! @param place The value's place.
pub def emitter::close(&mut this, place: &location): void {
return if place.held || !this.c.checker.closes(place.kind);
val plain := this.c.checker.unalias(place.kind);
val index := this.c.layout_of(plain);
val shape := this.c.layout_at(index);
if shape.kind == lk::fixed {
this.close_elements(place, plain, &shape);
return;
}
# Its own `close`, where it names `owning`.
val owning := this.c.checker.std_decl(word::owning);
if owning != 0 && this.c.checker.satisfies(plain, this.c.checker.decls.types.p[owning]) {
val closer := this.closer_of(plain);
if closer != 0 {
val receiver := this.reference_to(place, this.c.checker.types.reference(plain, true));
this.method_call(closer, plain, &receiver, span::<operand>::empty());
}
}
# A union holds one of its fields, so only that one is closed.
if shape.kind == lk::variant {
var at := shape.count;
while at > 0 {
at--;
val each := this.c.field_at(index, at as u32);
continue if !this.c.checker.closes(each.type_id);
val holding := this.build.new_block();
val after := this.build.new_block();
this.build.branch(this.tag_is(place, at as u32), holding, after);
this.build.seal(holding);
this.build.switch_to(holding);
val inner := this.within(place, each.offset, each.type_id);
this.close(&inner);
this.build.jump(after);
this.build.seal(after);
this.build.switch_to(after);
}
return;
}
var at := shape.count;
while at > 0 {
at--;
val each := this.c.field_at(index, at as u32);
continue if !this.c.checker.closes(each.type_id);
val inner := this.within(place, each.offset, each.type_id);
this.close(&inner);
}
}
#! The `close(&mut this): void` of `owning` a type gives, or 0.
#! @param this The emitter.
#! @param kind The type.
#! @returns The method's declaration, or 0.
pub def emitter::closer_of(&mut this, kind: u32): u32 {
val found := this.c.checker.find_member(kind, word::close);
return 0 if found.decl == 0;
var walk := this.c.checker.decls.walk_overloads(found.decl);
while true {
val at := walk.next();
break if at == 0;
this.c.checker.resolve(at);
if this.c.checker.decls.kinds.p[at] == dk::function && this.c.checker.decls.has(at, df::mut_this)
&& this.c.checker.types.part_count(this.c.checker.decls.types.p[at]) == 1 {
return at;
}
}
return 0;
}
#! Closes the elements of a fixed array, the last first, by a loop.
#! @param this The emitter.
#! @param place The array's place.
#! @param kind Its type, without aliases.
#! @param shape Its layout.
def emitter::close_elements(&mut this, place: &location, kind: u32, shape: &layout): void {
return if shape.count == 0;
val element := this.c.checker.types.first_of(kind);
val size := this.c.layout_at(shape.element - 1).size;
val first := this.address_of(place);
val left := this.build.variable(vt::word);
this.build.assign(left, this.build.word(shape.count as u64));
val head := this.build.new_block();
val body := this.build.new_block();
val exit := this.build.new_block();
this.build.jump(head);
this.build.switch_to(head);
val count := this.build.read(left);
this.build.branch(this.build.binary(op::ne, count, this.build.word(0)), body, exit);
this.build.seal(body);
this.build.switch_to(body);
val index := this.build.binary(op::sub, this.build.read(left), this.build.word(1));
this.build.assign(left, index);
val address := this.build.binary(op::add, first, this.scaled(index, size));
val inner := location { kind = element, address = address, framed = place.framed };
this.close(&inner);
this.close_loop(head, exit);
}
#! The text a format made, taken from what the program manages itself and
#! handed to a `string` holding no allocator, which gives it back with
#! `raw_release` where it closes. The statement keeps it until a place takes it.
#! @param this The emitter.
#! @param kind The `string` type.
#! @returns The string.
pub def emitter::owned_text(&mut this, kind: u32): operand {
var gives: vt[2] = [vt::word, vt::word];
val made := this.build.emit(op::format_owned, span::<u32>::empty(), gives[0:2], 0, 0);
val pointer: u32 = this.build.code.insts[made].result;
val length := pointer + 1;
val index := this.c.layout_of(this.c.checker.unalias(kind));
val shape := this.c.layout_at(index);
val address := this.temporary_of(kind);
this.build.clear(address, shape.size);
for i in 1..shape.count {
break if i >= 4;
val field := this.c.field_at(index, i as u32);
this.build.store(access::i64, address, field.offset, i == 1 ? pointer : length);
}
var text := operand::at(kind, address);
this.keep(&text);
return text;
}
+617
View File
@@ -0,0 +1,617 @@
#! @file places.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains places: where what a name, a field, an element, or what a pointer
#! or reference reaches is, how what is there is read and written, and the
#! references made to it. A reference is read through to what it refers to,
#! as many as it takes, wherever a place is reached through it.
import sakura::analyzer;
module sakura::compiler;
#! The address a place's memory begins at.
#! @param this The emitter.
#! @param place The place, in memory.
#! @returns The address.
pub def emitter::address_of(&mut this, place: &location): u32 {
return place.address if place.offset == 0;
return this.build.binary(op::add, place.address, this.build.word(place.offset));
}
#! Reads what a place holds. What is held in memory is copied to a cell of the
#! statement's own, so writing the place afterwards leaves the value as it was.
#! @param this The emitter.
#! @param place The place.
#! @returns The value.
pub def emitter::load(&mut this, place: &location): operand {
val held := this.c.shape_of(place.kind);
var made := operand { kind = place.kind, count = word_count(&held) };
if place.held {
for i in 0..made.count {
made.words[i] = this.build.read(place.vars[i]);
}
return made;
}
if in_memory(&held) {
val copy := this.temporary_of(place.kind);
this.build.copy(copy, this.address_of(place), held.size);
return operand::at(place.kind, copy);
}
if made.count == 1 {
made.words[0] = this.build.load(held.how, place.address, place.offset);
return made;
}
for i in 0..made.count {
made.words[i] = this.build.load(access::i64, place.address, place.offset + i as u64 * word_size);
}
return made;
}
#! Writes a value to a place, which is of the value's type.
#! @param this The emitter.
#! @param place The place.
#! @param value The value.
pub def emitter::store(&mut this, place: &location, value: &operand): void {
val held := this.c.shape_of(place.kind);
if place.held {
for i in 0..word_count(&held) {
this.build.assign(place.vars[i], value.words[i]);
this.bind(place.vars[i], value.words[i]);
}
return;
}
if in_memory(&held) {
return if value.address == 0;
this.build.copy(this.address_of(place), value.address, held.size);
return;
}
if word_count(&held) == 1 {
this.build.store(held.how, place.address, place.offset, value.words[0]);
return;
}
for i in 0..word_count(&held) {
this.build.store(access::i64, place.address, place.offset + i as u64 * word_size, value.words[i]);
}
}
#! Zeroes what a place holds.
#! @param this The emitter.
#! @param place The place.
pub def emitter::zero(&mut this, place: &location): void {
val held := this.c.shape_of(place.kind);
if place.held {
for i in 0..word_count(&held) {
val zero := word_type(&held) == vt::real ? this.build.real(0) : this.build.word(0);
this.build.assign(place.vars[i], zero);
this.bind(place.vars[i], zero);
}
return;
}
this.build.clear(this.address_of(place), held.size);
}
#! A reference to a place, as the word a reference is: where the value is. A
#! place held in variables has no address, so a copy of its value is referred
#! to instead, which the storage worked out before lowering avoids for what a
#! reference must reach.
#! @param this The emitter.
#! @param place The place.
#! @param kind The reference's type.
#! @returns The reference.
pub def emitter::reference_to(&mut this, place: &location, kind: u32): operand {
if place.held {
val value := this.load(place);
val copy := location { kind = place.kind, address = this.temporary_of(place.kind), framed = true };
this.store(&copy, &value);
return this.reference_to(&copy, kind);
}
# A reference to a trait the value implements is given its type's vtable.
val wanted := this.c.checker.unalias(kind);
if this.c.checker.types.kind_of(wanted) == ty::reference {
val referent := this.c.checker.unalias(this.c.checker.types.first_of(wanted));
if this.c.checker.named_kind(referent) == dk::trait_type && this.c.checker.named_kind(this.c.checker.unalias(place.kind)) != dk::trait_type {
val own := this.c.checker.types.reference(place.kind, this.c.checker.types.second_of(wanted) != 0);
val made := operand::one(own, this.address_of(place));
return this.convert(&made, kind);
}
}
return operand::one(kind, this.address_of(place));
}
#! The place a reference refers to.
#! @param this The emitter.
#! @param value The reference.
#! @returns The place.
pub def emitter::referent(&mut this, value: &operand): location {
val kind := this.c.checker.types.first_of(this.c.checker.unalias(value.kind));
# Running with its memory checked, what a reference refers to is where the
# program holds memory, as what a pointer points at is.
if this.c.options.checks && this.c.checker.named_kind(this.c.checker.unalias(kind)) != dk::trait_type {
this.reaches(value.words[0], this.build.word(1), this.c.shape_of(kind).size);
}
return location { kind = kind, address = value.words[0] };
}
#! A place within another, at an offset, as a field is.
#! @param this The emitter.
#! @param place The place holding it.
#! @param offset How many bytes in it is.
#! @param kind Its type.
#! @returns The place.
pub def emitter::within(&mut this, place: &location, offset: u64, kind: u32): location {
var made: location = place;
if place.held {
# A value held in variables is no struct, so this is never reached; it is
# copied to memory where it is.
val value := this.load(place);
made = location { kind = place.kind, address = this.temporary_of(place.kind), framed = true };
this.store(&made, &value);
}
made.kind = kind;
made.offset = made.offset + offset;
return made;
}
#! The place a node's value is at, read through as many references as it holds
#! until what they refer to is no reference, or as many as `levels` says.
#! @param this The emitter.
#! @param node The node.
#! @param levels How many references to read through at most.
#! @returns The place.
pub def emitter::object_by(&mut this, node: u32, levels: u32): location {
var kind := this.c.checker.type_at(node);
if !this.c.is_reference_type(kind) || levels == 0 {
return this.place_of(node);
}
var value := this.value_of_type(node);
var place := this.referent(&value);
var steps: u32 = 1;
while steps < levels && this.c.is_reference_type(place.kind) && steps < 16 {
value = this.load(&place);
place = this.referent(&value);
steps++;
}
return place;
}
#! The place a node's value is at, read through every reference it holds.
#! @param this The emitter.
#! @param node The node.
#! @returns The place.
pub def emitter::object(&mut this, node: u32): location {
return this.object_by(node, 16);
}
#! The place a node names: a local, a global, a field, an element, or what a
#! pointer points at; or else a cell of the statement's own holding its value.
#! @param this The emitter.
#! @param node The node.
#! @returns The place.
pub def emitter::place_of(&mut this, node: u32): location {
val saved := this.build.pos;
this.at_node(node);
val made := this.place_node(node);
this.build.pos = saved;
return made;
}
#! The place a node names, by the kind of the node.
#! @param this The emitter.
#! @param node The node.
#! @returns The place.
def emitter::place_node(&mut this, node: u32): location {
match this.c.checker.kind_of(node) {
nk::name, nk::path => {
val ref := this.c.checker.ref_at(node);
if (ref & ref_local) != 0 {
val index := this.local_of(ref & ref_mask);
if index != 0 {
val held: local_info = this.locals[index - 1];
return held.place;
}
if this.pass_variable(ref & ref_mask) {
val held: local_info = this.locals[this.local_of(ref & ref_mask) - 1];
return held.place;
}
this.problem(node, "The local is not where it is named.");
} else if ref != 0 && (ref & ref_type) == 0 && this.c.checker.decls.kinds.p[ref] == dk::variable
&& !this.c.checker.is_known(node) {
return this.global_place(ref);
}
}
nk::member => {
val ref := this.c.checker.ref_at(node);
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::field {
return this.field_place(node, ref);
}
}
nk::member_of => {
val ref := this.c.checker.ref_at(node);
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::field {
return this.field_place(node, ref);
}
# What else a description names is no place.
if this.property_of(node) == 0 {
this.problem(node, "The member a description names is not lowered.");
return location { kind = this.c.checker.type_at(node), address = this.build.word(0) };
}
}
nk::index => {
# Through `at`, it is the reference `at` gives, held as any value is.
if !this.indexes_through_at(node) {
return this.element_place(node);
}
}
nk::call => {
# `value_of(d)` of a variable is the variable.
val ref := this.c.checker.ref_at(node);
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::variable
&& !this.c.checker.is_known(node) {
return this.global_place(ref);
}
}
nk::unary => {
if this.c.checker.token_kind(node) == tk::star {
# A reference to a pointer is read through to the pointer.
val given := this.value_of_type(this.c.checker.left_of(node));
val pointer := this.through_references(&given);
val kind := this.c.checker.type_at(node);
this.reaches(pointer.words[0], this.build.word(1), this.c.shape_of(kind).size);
return location { kind = kind, address = pointer.words[0] };
}
}
else => {}
}
# Anything else is a value, held where the statement holds what it makes.
val value := this.value_of_type(node);
return this.hold(&value);
}
#! A place holding a value: its own memory, where it is in memory, or a cell of
#! the statement's own the value is written to.
#! @param this The emitter.
#! @param value The value.
#! @returns The place.
pub def emitter::hold(&mut this, value: &operand): location {
if value.address != 0 {
return location { kind = value.kind, address = value.address, framed = true };
}
val place := location { kind = value.kind, address = this.temporary_of(value.kind), framed = true };
this.store(&place, value);
return place;
}
#! The place of a global, where it is placed among the globals.
#! @param this The emitter.
#! @param decl The global's declaration.
#! @returns The place.
pub def emitter::global_place(&mut this, decl: u32): location {
val kind: u32 = this.c.checker.decls.types.p[decl];
val constant := this.c.checker.decls.has(decl, df::constant);
# While compiling, a constant is read once it is evaluated, and a variable
# given its value once the program runs is not read at all.
if this.c.options.evaluating {
if !constant {
this.build.trap(fault::not_constant as u32);
val nowhere := this.build.word(0);
return location { kind = kind, address = nowhere };
}
val index := this.c.evaluation_of(decl_key(decl), decl, 0, 0, false);
this.build.effect(op::ready, span::<u32>::empty(), index, 0);
val offset: u64 = this.c.evaluations[index].offset;
val address := this.build.value(op::global, span::<u32>::empty(), vt::word, 0, offset);
return location { kind = kind, address = address };
}
# A constant evaluated is read where the program holds its value as data.
if constant {
val datum := this.c.evaluated_datum(decl_key(decl), kind);
if datum != no_block {
val address := this.build.value(op::datum, span::<u32>::empty(), vt::word, datum, 0);
return location { kind = kind, address = address };
}
}
val offset := this.c.global_of(decl);
val address := this.build.value(op::global, span::<u32>::empty(), vt::word, 0, offset);
return location { kind = kind, address = address };
}
#! Whether the code checks what only a checked build does: indexes and slices,
#! the field a union holds, an integer converted to an enum, and a `match`
#! finding no arm. A constant is evaluated checked in every build.
#! @param this The emitter.
#! @returns Whether it does.
pub def emitter::checking(&this): bool {
return !this.c.checker.checks_off || this.c.options.evaluating;
}
#! Stops the program where a pointer is null, which only the code of a checked
#! program reaching an element past the first page asks. Elsewhere reading or
#! writing through null stops the program where it does, in every build: the
#! machine compares each address it reads or writes through with the first
#! page, and an executable faults there, which its runtime reports as the same.
#! @param this The emitter.
#! @param pointer The pointer.
def emitter::compare_null(&mut this, pointer: u32): void {
val zero := this.build.word(0);
this.build.check(this.build.binary(op::ne, pointer, zero), fault::null_reference as u32);
}
#! The place of a field of a struct or union, read through the references the
#! object is reached by. A field a struct's spread brings in is reached through
#! the spread field holding it, and a field of a union only where the union
#! holds it.
#! @param this The emitter.
#! @param node The `member` node.
#! @param field The field's declaration.
#! @returns The place.
pub def emitter::field_place(&mut this, node: u32, field: u32): location {
val object := this.c.checker.left_of(node);
val whole := this.object(object);
val kind := this.c.checker.type_at(node);
val owner := this.c.checker.unalias(whole.kind);
return this.field_in(&whole, owner, field, kind);
}
#! The place of a field within a place holding a struct or union of a type.
#! @param this The emitter.
#! @param whole The place of the struct or union.
#! @param owner Its type, without aliases.
#! @param field The field's declaration.
#! @param kind The field's type, as checked.
#! @returns The place.
pub def emitter::field_in(&mut this, whole: &location, owner: u32, field: u32, kind: u32): location {
val index := this.c.layout_of(owner);
val shape := this.c.layout_at(index);
for i in 0..shape.count {
val each := this.c.field_at(index, i as u32);
if each.decl == field {
if shape.kind == lk::variant {
this.check_held(whole, i as u32);
}
return this.within(whole, each.offset, each.type_id);
}
}
# Reached through a spread field, which holds the struct declaring it.
for i in 0..shape.count {
val each := this.c.field_at(index, i as u32);
continue if !each.spread;
val inner := this.within(whole, each.offset, each.type_id);
val plain := this.c.checker.unalias(each.type_id);
if this.holds_field(plain, field, 0) {
return this.field_in(&inner, plain, field, kind);
}
}
this.problem(0, "A field is not in the layout of what holds it.");
return this.within(whole, 0, kind);
}
#! Whether a struct holds a field, its own or one a spread brings in.
#! @param this The emitter.
#! @param kind The struct's type.
#! @param field The field's declaration.
#! @param depth How deeply spreads have been followed.
#! @returns Whether it holds it.
def emitter::holds_field(&mut this, kind: u32, field: u32, depth: u32): bool {
return false if depth > 16;
val index := this.c.layout_of(kind);
val shape := this.c.layout_at(index);
for i in 0..shape.count {
val each := this.c.field_at(index, i as u32);
return true if each.decl == field;
if each.spread && this.holds_field(this.c.checker.unalias(each.type_id), field, depth + 1) {
return true;
}
}
return false;
}
#! Stops the program unless a union holds its field of an index, where the code
#! checks.
#! @param this The emitter.
#! @param whole The place of the union.
#! @param index The field's index.
pub def emitter::check_held(&mut this, whole: &location, index: u32): void {
return if !this.checking();
val holds := this.tag_is(whole, index);
this.build.check(holds, fault::not_held as u32);
}
#! Whether a union holds its field of an index, as a word of 0 or 1.
#! @param this The emitter.
#! @param whole The place of the union.
#! @param index The field's index.
#! @returns The word.
pub def emitter::tag_is(&mut this, whole: &location, index: u32): u32 {
var tag: u32 = 0;
if whole.held {
tag = this.build.read(whole.vars[0]);
} else {
tag = this.build.load(access::i64, whole.address, whole.offset);
}
# A union without a tag holds the field it is laid out for where its first word
# is not null, and the empty one where it is.
val shape := this.c.shape_of(whole.kind);
if shape.niche != 0 {
return this.build.binary(index + 1 == shape.niche ? op::ne : op::eq, tag, this.build.word(0));
}
return this.build.binary(op::eq, tag, this.build.word(index as u64));
}
#! The place of an element: of a fixed array, at an index checked against its
#! length; of what a pointer points at, which is not checked; of a view, checked
#! against how many it views; of a pack, at an index known while compiling; or
#! of what implements `indexable`, the place its `at` refers to.
#! @param this The emitter.
#! @param node The `index` node.
#! @returns The place.
pub def emitter::element_place(&mut this, node: u32): location {
val object := this.c.checker.left_of(node);
val at := this.c.checker.right_of(node);
val kind := this.c.checker.type_at(node);
val whole_type := this.object_type(object);
val through := this.c.checker.unalias(this.c.checker.reached(whole_type));
match this.c.checker.types.kind_of(through) {
ty::fixed => {
val whole := this.object(object);
val shape := this.c.shape_of(through);
val element := this.c.layout_at(shape.element - 1);
if this.c.checker.is_known(at) {
val index := this.c.checker.value_at(at).magnitude;
if index < shape.count as u64 {
return this.within(&whole, index * element.size, this.c.checker.types.first_of(through));
}
}
val index := this.value_as(at, bt::uint64);
if this.checking() {
val within := this.build.binary(op::ltu, index.words[0], this.build.word(shape.count as u64));
this.build.check(within, fault::out_of_bounds as u32);
}
val first := this.address_of(&whole);
val address := this.build.binary(op::add, first, this.scaled(index.words[0], element.size));
return location { kind = this.c.checker.types.first_of(through), address = address, framed = whole.framed };
}
ty::pointer => {
val pointer := this.value_of_type(object);
val reached := this.through_references(&pointer);
val element := this.c.shape_of(this.c.checker.types.first_of(through));
# An element past the first page is no fault there, so a checked program
# compares the pointer with null first, unless the index is known to
# stay within it.
val near := this.c.checker.is_known(at) && (element.size == 0 || this.c.checker.value_at(at).magnitude < null_page / element.size);
if this.checking() && !near {
this.compare_null(reached.words[0]);
}
val index := this.value_as(at, bt::uint64);
val address := this.build.binary(op::add, reached.words[0], this.scaled(index.words[0], element.size));
this.reaches(address, this.build.word(1), element.size);
return location { kind = this.c.checker.types.first_of(through), address = address };
}
ty::pack => {
val index := this.c.checker.value_at(at).magnitude;
return this.pack_place(object, index as u32);
}
else => {}
}
# A view holds where its elements are and how many, so an element of one is the
# place that many along, once the index is checked against the count. A view
# holding any element is never over null, as std makes every view, so the
# index's check is all it needs.
val viewed := this.c.viewed(through);
if viewed != 0 {
val whole := this.object(object);
val data := this.build.load(access::i64, whole.address, whole.offset);
val count := this.build.load(access::i64, whole.address, whole.offset + word_size);
val index := this.value_as(at, bt::uint64);
if this.checking() {
this.build.check(this.build.binary(op::ltu, index.words[0], count), fault::out_of_bounds as u32);
}
val element := this.c.shape_of(viewed);
val address := this.build.binary(op::add, data, this.scaled(index.words[0], element.size));
return location { kind = viewed, address = address };
}
# What implements `indexable` gives a reference to the element through `at`.
val method := this.c.checker.ref_at(node);
if method != 0 && (method & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[method] == dk::function {
val made := this.accessor_call(node, method, object, at);
if this.c.is_reference_type(made.kind) {
return this.referent(&made);
}
return this.hold(&made);
}
this.problem(node, "Nothing is indexed here.");
return location { kind = kind, address = this.temporary_of(kind) };
}
#! The type of what an element or a member is reached through: its own, or,
#! for a constant, the one it settles as, so `"text"[0]` is a `strview`'s.
#! @param this The emitter.
#! @param object The node of the value reached through.
#! @returns The type.
pub def emitter::object_type(&mut this, object: u32): u32 {
val own := this.c.checker.type_at(object);
return this.c.checker.types.is_untyped(own) ? this.c.checker.converted(object) : own;
}
#! Whether `x[k]` is indexed through `at`, and so is the reference it gives
#! rather than a place of its own.
#! @param this The emitter.
#! @param node The `index` node.
#! @returns Whether it is.
pub def emitter::indexes_through_at(&mut this, node: u32): bool {
val method := this.c.checker.ref_at(node);
return method != 0 && (method & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[method] == dk::function
&& this.c.is_reference_type(this.c.checker.type_at(node));
}
#! The reference `x[k]` gives through `at`: the one `at` gives, or, for a view,
#! which is indexed without calling it, one to the element it covers.
#! @param this The emitter.
#! @param node The `index` node.
#! @returns The reference.
pub def emitter::indexed_reference(&mut this, node: u32): operand {
val object := this.c.checker.left_of(node);
val through := this.c.checker.unalias(this.c.checker.reached(this.object_type(object)));
if this.c.viewed(through) != 0 {
val place := this.element_place(node);
return this.reference_to(&place, this.c.checker.type_at(node));
}
return this.accessor_call(node, this.c.checker.ref_at(node), object, this.c.checker.right_of(node));
}
#! A count of elements of a size, in bytes.
#! @param this The emitter.
#! @param count The count, a word.
#! @param size The size of each.
#! @returns The bytes.
pub def emitter::scaled(&mut this, count: u32, size: u64): u32 {
return count if size == 1;
return this.build.binary(op::mul, count, this.build.word(size));
}
#! A value read through every reference it is, until it is no reference.
#! @param this The emitter.
#! @param value The value.
#! @returns What it reaches.
pub def emitter::through_references(&mut this, value: &operand): operand {
var at: operand = value;
var steps := 0;
while this.c.is_reference_type(at.kind) && steps < 16 {
val place := this.referent(&at);
at = this.load(&place);
steps++;
}
return at;
}
#! The place of a value of a pack, by its index.
#! @param this The emitter.
#! @param object The node naming the pack.
#! @param index The value's index.
#! @returns The place.
pub def emitter::pack_place(&mut this, object: u32, index: u32): location {
val ref := this.c.checker.ref_at(object);
val local := (ref & ref_local) != 0 ? this.local_of(ref & ref_mask) : 0;
if local != 0 {
val held: local_info = this.locals[local - 1];
if index < held.count {
return this.packs[held.pack as u64 + index as u64];
}
}
this.problem(object, "The pack holds no value at the index.");
return location { kind = bt::error };
}
+253
View File
@@ -0,0 +1,253 @@
#! @file reflection.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what reflection gives a program: descriptions of its declarations,
#! as `core::decl`s, which the checker found while compiling. They are written
#! as data the program holds as long as it runs, the text they name among it,
#! and read where the program stands.
import sakura::analyzer;
module sakura::compiler;
#! What reflection gives an expression: one description, read from the data
#! holding it, or a view of a list of them.
#! @param this The emitter.
#! @param node The expression.
#! @returns The value.
pub def emitter::reflected_value(&mut this, node: u32): operand {
val kind := this.c.checker.type_at(node);
val at := this.c.checker.reflected_at(node);
if at == checker::no_reflection {
this.problem(node, "Reflection gives nothing here.");
return this.zero_value(kind);
}
var items := vector::<u32>::new();
for i in 0..this.c.checker.reflected_count(at) {
items.append(this.c.checker.reflected_item(at, i as u32));
}
if this.c.checker.reflected_kind(at) == rk::one as u32 {
val datum := this.c.descriptions(items.view(), kind);
val address := this.build.value(op::datum, span::<u32>::empty(), vt::word, datum, 0);
val place := location { kind = kind, address = address };
return this.load(&place);
}
val view := this.temporary_of(kind);
if items.length == 0 {
this.build.clear(view, 2 * word_size);
return operand::at(kind, view);
}
val element := this.c.viewed(kind);
val datum := this.c.descriptions(items.view(), element);
val first := this.build.value(op::datum, span::<u32>::empty(), vt::word, datum, 0);
this.build.store(access::i64, view, 0, first);
this.build.store(access::i64, view, word_size, this.build.word(items.length));
return operand::at(kind, view);
}
#! Declares the variable of a pass of `for const` over a list reflection gives:
#! the description the pass is of.
#! @param this The emitter.
#! @param variable The node of the loop's variable.
pub def emitter::reflected_pass(&mut this, variable: u32): void {
val kind := this.c.checker.type_at(variable);
val made := this.reflected_value(variable);
val place := this.new_place(variable, kind);
this.store(&place, &made);
this.declare(variable, place, false);
}
#! Declares the variable of a pass of `for const` over a list reflection gives
#! where a function the pass doesn't run in names it, as the one evaluating the
#! condition of an `if const` within the pass does: the description the pass is
#! of, as it is in the pass.
#! @param this The emitter.
#! @param variable The node of the loop's variable.
#! @returns Whether it is such a variable, and was declared.
pub def emitter::pass_variable(&mut this, variable: u32): bool {
val at := this.c.checker.reflected_at(variable);
return false if at == checker::no_reflection || this.c.checker.reflected_kind(at) != rk::one as u32;
this.reflected_pass(variable);
return true;
}
#! The datum holding descriptions as `core::decl`s one after another, made where
#! it is new, with the text each names among the program's data.
#! @param this The compiler.
#! @param items The descriptions' indices among the checker's.
#! @param kind The type of each, `core::decl`.
#! @returns The datum's index.
pub def lowerer::descriptions(&mut this, items: span<u32>, kind: u32): u32 {
val plain := this.checker.unalias(kind);
val index := this.layout_of(plain);
val shape := this.layout_at(index);
var bytes := vector::<u8>::new();
bytes.resize(shape.size * items.length);
var relocations := vector::<relocation>::new();
for i in 0..items.length {
val held: desc = this.checker.descs[items[i]];
val base := i * shape.size;
var name := string::new(nothing {});
var path := string::new(nothing {});
var signature := string::new(nothing {});
val decl := held.decl;
if held.param != 0 {
this.param_name(decl, held.param - 1, &mut name);
} else {
name.append(this.checker.names.text(this.checker.decls.names.p[decl]));
}
this.qualified_name(decl, &mut path);
this.signature_text(decl, &mut signature);
val file: u32 = this.checker.decls.files.p[decl];
val source := &this.checker.units[file].source;
val place := source.lines.place_of(this.node_offset(file, this.checker.decls.nodes.p[decl]));
for f in 0..shape.count {
val field := this.field_at(index, f as u32);
val field_name := this.checker.names.text(field.name);
val at := base + field.offset;
if field_name == "id" {
write_number(&mut bytes, at, this.layout_at(field.layout).size, decl as u64);
} else if field_name == "kind" {
val bit := held.param != 0 ? 0x2000u : this.checker.target_bit(decl);
write_number(&mut bytes, at, this.layout_at(field.layout).size, bit);
} else if field_name == "exported" {
write_number(&mut bytes, at, 1, held.param == 0 && this.checker.decls.has(decl, df::exported) ? 1 : 0);
} else if field_name == "generic" {
write_number(&mut bytes, at, 1, held.param == 0 && this.checker.own_param_count(decl) != 0 ? 1 : 0);
} else if field_name == "name" {
this.write_text(&mut bytes, &mut relocations, at, name.view());
} else if field_name == "path" {
this.write_text(&mut bytes, &mut relocations, at, path.view());
} else if field_name == "at" {
val inner := this.layout_at(field.layout);
for s in 0..inner.count {
val part := this.field_at(field.layout, s as u32);
val part_name := this.checker.names.text(part.name);
val within := at + part.offset;
if part_name == "path" {
this.write_text(&mut bytes, &mut relocations, within, source.path);
} else if part_name == "line" {
write_number(&mut bytes, within, this.layout_at(part.layout).size, place.line as u64);
} else if part_name == "column" {
write_number(&mut bytes, within, this.layout_at(part.layout).size, place.column as u64);
} else if part_name == "signature" {
this.write_text(&mut bytes, &mut relocations, within, signature.view());
}
}
}
}
}
val datum := this.program.data.length as u32;
bytes.append(0);
this.program.data.append(datum {
bytes = move(&mut bytes),
align = shape.align < word_size ? word_size : shape.align,
relocations = move(&mut relocations)
});
return datum;
}
#! Writes a number into bytes, as wide as it says, least significant first.
#! @param bytes Where it is written.
#! @param at The first byte.
#! @param size How many bytes it takes.
#! @param value The number.
pub def write_number(bytes: &mut vector<u8>, at: u64, size: u64, value: u64): void {
for i in 0..size {
bytes[at + i] = ((value >> (i * 8)) & 0xFF) as u8;
}
}
#! Writes a view of text into bytes: where the text is, as the address of a
#! datum holding it, and how many bytes it holds. Empty text points nowhere.
#! @param this The compiler.
#! @param bytes Where the view is written.
#! @param relocations Where the address is noted.
#! @param at The first byte of the view.
#! @param text The text.
def lowerer::write_text(&mut this, bytes: &mut vector<u8>, relocations: &mut vector<relocation>, at: u64, text: strview): void {
if text.length != 0 {
relocations.append(relocation { at = at, target = this.text_datum(text), addend = 0 });
}
write_number(bytes, at + word_size, word_size, text.length);
}
#! The name a function's parameter is declared with.
#! @param this The compiler.
#! @param decl The function's declaration.
#! @param index The parameter's position.
#! @param out Where the name is written.
def lowerer::param_name(&mut this, decl: u32, index: u32, out: &mut string): void {
val saved := this.checker.at;
this.checker.use_table(this.checker.units[this.checker.decls.files.p[decl]].table);
val node: u32 = this.checker.decls.nodes.p[decl];
val params := this.checker.decls.has(decl, df::accessor) ? this.checker.left_of(node) : this.checker.record(node, function_slot::params);
if index < this.checker.run_length(params) {
out.append(this.checker.names.text(this.checker.param_name(this.checker.run_at(params, index))));
}
this.checker.at = saved;
}
#! The name a declaration is reached by from outside its module, as
#! `sakura::analyzer::interns_keywords`.
#! @param this The compiler.
#! @param decl The declaration.
#! @param out Where the name is written.
pub def lowerer::qualified_name(&mut this, decl: u32, out: &mut string): void {
var modules := vector::<u32>::new();
var at: u32 = this.checker.decls.modules.p[decl];
var steps := 0;
while at != 0 && steps < 64 {
modules.append(at);
at = this.checker.modules.parents[at];
steps++;
}
var i := modules.length;
while i > 0 {
i--;
out.append(this.checker.names.text(this.checker.modules.names[modules[i]]));
out.append("::");
}
var holder: u32 = this.checker.decls.owners.p[decl];
if holder != 0 && this.checker.decls.kinds.p[holder] == dk::property {
holder = this.checker.decls.owners.p[holder];
}
if holder != 0 && this.checker.decls.kinds.p[holder] != dk::type_param {
out.append(this.checker.names.text(this.checker.decls.names.p[holder]));
out.append("::");
}
out.append(this.checker.names.text(this.checker.decls.names.p[decl]));
}
#! The signature a declaration is written with: its text from where it begins
#! to its body, or its first line.
#! @param this The compiler.
#! @param decl The declaration.
#! @param out Where the text is written.
pub def lowerer::signature_text(&mut this, decl: u32, out: &mut string): void {
val file: u32 = this.checker.decls.files.p[decl];
val node: u32 = this.checker.decls.nodes.p[decl];
return if node == 0;
val syntax := &this.checker.units[file].syntax;
val source := &this.checker.units[file].source;
val begin := syntax.token_offsets[syntax.start_of(node)];
val end_token := syntax.node_end(node);
val end := syntax.token_offsets[end_token] + syntax.token_length(end_token, this.checker.names);
return if end <= begin;
val whole := source.make_lexeme(begin, end - begin);
var stop := 0u;
while stop < whole.length && whole[stop] != '{' && whole[stop] != '\n' {
stop++;
}
while stop > 0 && (whole[stop - 1] == ' ' || whole[stop - 1] == '\t') {
stop--;
}
out.append(whole.substr(0, stop));
}
+653
View File
@@ -0,0 +1,653 @@
#! @file statements.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the lowering of statements: blocks and the locals declared in
#! them, branches, `if const` and `when`, loops, contracts, and leaving by
#! `return`, `break`, and `continue`, each closing what it leaves behind.
import sakura::analyzer;
module sakura::compiler;
#! Lowers a block, whose locals close where it ends. Statements after one the
#! checker found always leaves, as decided while checking, were never checked,
#! so they are not lowered either.
#! @param this The emitter.
#! @param node The block, or a statement standing for one.
pub def emitter::lower_block(&mut this, node: u32): void {
return if node == 0;
if this.c.checker.kind_of(node) != nk::block {
this.lower_statement(node);
return;
}
val mark := this.scope_mark();
val run := this.c.checker.left_of(node);
for i in 0..this.c.checker.run_length(run) {
val each := this.c.checker.run_at(run, i as u32);
this.lower_statement(each);
break if this.skips(each);
}
this.end_scope(mark, 0);
}
#! Whether a statement leaves where it was decided while checking, so the
#! checker checked nothing after it: an `if const` whose branch taken leaves,
#! with no `else`, or a block or `when` holding one.
#! @param this The emitter.
#! @param node The statement.
#! @returns Whether it does.
pub def emitter::skips(&mut this, node: u32): bool {
match this.c.checker.kind_of(node) {
nk::block => {
val run := this.c.checker.left_of(node);
for i in 0..this.c.checker.run_length(run) {
return true if this.skips(this.c.checker.run_at(run, i as u32));
}
}
nk::when_block => return this.skips(this.c.checker.when_branch(node));
nk::if_const => {
val condition := this.c.checker.left_of(node);
return false if !this.c.checker.is_known(condition);
val then := this.c.checker.record(node, if_slot::then);
val other := this.c.checker.record(node, if_slot::other);
if this.c.checker.value_at(condition).magnitude != 0 {
return this.skips(then) || (other == 0 && this.c.checker.has_flag(then, rf::leaves));
}
return other != 0 && this.skips(other);
}
else => {}
}
return false;
}
#! Lowers a statement.
#! @param this The emitter.
#! @param node The statement.
pub def emitter::lower_statement(&mut this, node: u32): void {
# A contract left out is no statement at all, so what follows takes no
# place of it.
return if this.c.checker.contracts_off && this.c.checker.kind_of(node) == nk::contract;
this.at_node(node);
match this.c.checker.kind_of(node) {
nk::block => this.lower_block(node);
nk::variable => this.local_statement(node);
nk::if_stmt => this.if_statement(node);
nk::if_const => this.if_const(node);
nk::when_block => this.lower_block(this.c.checker.when_branch(node));
nk::while_stmt => this.while_statement(node);
nk::for_stmt => this.for_statement(node);
nk::match_stmt => {
val mark := this.begin_statement();
this.lower_match(node, false);
this.end_statement(mark);
}
nk::return_stmt => {
val mark := this.begin_statement();
val value := this.c.checker.left_of(node);
if value != 0 && this.result != bt::void_type {
this.return_value(value, mark);
return;
}
# `return;` from a function giving more than nothing gives `void`, as a
# `result<void, E>` holds it.
if value == 0 && this.c.checker.unalias(this.result) != bt::void_type {
val none := operand::none(bt::void_type);
var made := this.convert(&none, this.result);
this.return_made(&mut made, 0, mark);
return;
}
# What gives nothing, returned from a function giving nothing, is done first.
if value != 0 {
this.value(value);
}
this.close_kept(mark.kept);
this.leave_kept(0);
this.close_locals(0, 0);
this.build.ret(span::<u32>::empty());
}
nk::break_stmt, nk::continue_stmt => this.leave_loop(this.c.checker.kind_of(node) == nk::break_stmt);
nk::contract => this.contract_statement(node);
nk::expr_stmt => {
val mark := this.begin_statement();
val inner := this.c.checker.left_of(node);
this.value(inner);
this.end_statement(mark);
# A call that ends the program, as `exit`, is never returned from.
if this.ends_program(inner) {
this.build.unreachable();
}
}
else => {}
}
}
#! Lowers a contract, as only a program checking contracts does: `expects` and
#! `asserts` are checked where they are, and an `ensures` is an entry among the
#! locals, which closing checks on each way out of its block, once what each
#! `old` within it reads is kept.
#! @param this The emitter.
#! @param node The `contract` node.
def emitter::contract_statement(&mut this, node: u32): void {
if this.c.checker.clause_of(node) != clause::ensures {
val mark := this.begin_statement();
this.check_contract(node);
this.end_statement(mark);
return;
}
this.keep_earlier(this.c.checker.left_of(node));
val index := this.declare(node, location {}, true);
this.locals[index].checks = true;
}
#! Keeps what each `old(e)` in an `ensures`'s condition reads, where the
#! `ensures` is reached, as a local the `old_value` node declares.
#! @param this The emitter.
#! @param condition The condition.
def emitter::keep_earlier(&mut this, condition: u32): void {
var walk := node_walk::new(condition);
while walk.more() {
val at := walk.next();
if this.c.checker.kind_of(at) == nk::old_value {
val held := this.c.checker.type_at(at);
val mark := this.begin_statement();
val made := this.value_as(this.c.checker.left_of(at), held);
val place := this.fresh_place(held);
this.store(&place, &made);
this.end_statement(mark);
this.declare(at, place, false);
continue;
}
this.c.scan_children(at, &mut walk);
}
}
#! Checks an `ensures` where its block is left, the name it gives what the
#! function returns standing for that. Where the way out returns nothing, as
#! where every way through the block returned before its end, it is never
#! reached.
#! @param this The emitter.
#! @param node The `contract` node.
pub def emitter::check_ensures(&mut this, node: u32): void {
return if this.build.ended();
val bound := this.c.checker.record(node, contract_slot::bound);
return if bound != 0 && !this.returning;
val locals := this.scope_mark();
if bound != 0 {
val place := this.new_place(bound, this.returned.kind);
this.store(&place, &this.returned);
this.declare(bound, place, false);
}
val mark := this.begin_statement();
this.check_contract(node);
this.end_statement(mark);
this.forget_locals(locals);
}
#! Lowers a contract's check: where its condition holds, the program goes on,
#! and where it does not, a block of its own, which nothing comes back from,
#! makes the report and stops the program with it, so a contract that holds
#! costs its condition and a branch.
#! @param this The emitter.
#! @param node The `contract` node.
def emitter::check_contract(&mut this, node: u32): void {
val saved := this.build.pos;
this.at_node(node);
val fine := this.build.new_block();
val failing := this.build.new_block();
this.branch_on(this.c.checker.left_of(node), fine, failing);
this.build.seal(failing);
this.build.switch_to(failing);
this.report_contract(node);
this.build.seal(fine);
this.build.switch_to(fine);
this.build.pos = saved;
}
#! Stops the program where a contract failed, saying which kind failed, what it
#! checked, as written or as its text says, and what the condition's operands
#! held, as `A pre-condition failed: b != 0, with b = 0.`
#! @param this The emitter.
#! @param node The `contract` node.
def emitter::report_contract(&mut this, node: u32): void {
val mark := this.begin_statement();
val condition := this.c.checker.left_of(node);
val text := this.c.checker.record(node, contract_slot::text);
val lead := match this.c.checker.clause_of(node) {
expects => "A pre-condition failed: ",
asserts => "An assertion failed: ",
ensures => "A post-condition failed: "
};
this.build.effect(op::format, span::<u32>::empty(), 0, 0);
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(lead), 0);
# Text written as a literal ends where the report's own full stop does.
if text != 0 && this.c.checker.kind_of(text) == nk::string {
var said := string::new(nothing {});
this.decode_literal(this.c.checker.text_of(text), &mut said);
if said.length != 0 && said[said.length - 1] == '.' {
said.resize(said.length - 1);
}
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(said.view()), 0);
} else if text != 0 {
val said := this.value(text);
this.format_sentence(&said);
} else {
var written := string::new(nothing {});
this.source_text(condition, &mut written);
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(written.view()), 0);
}
this.write_values(condition, ", with ");
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum("."), 0);
# The program stops with the report, so nothing made here is closed.
var report := this.owned_text(this.c.checker.type_at(node));
this.adopt(&report);
val index := this.c.layout_of(this.c.checker.unalias(report.kind));
val data := this.c.field_at(index, 1);
val count := this.c.field_at(index, 2);
var words: u32[2] = [this.build.load(access::i64, report.address, data.offset), this.build.load(access::i64, report.address, count.offset)];
this.build.effect(op::fault, words[0:2], 0, 0);
this.build.unreachable();
this.drop_kept(mark.kept);
this.release(mark.cells);
}
#! Writes a view of text into the text being made without a full stop it ends
#! with, where the report's own ends it.
#! @param this The emitter.
#! @param text The view.
def emitter::format_sentence(&mut this, text: &operand): void {
var data := text.words[0];
var length := text.words[1];
if text.address != 0 {
data = this.build.load(access::i64, text.address, 0);
length = this.build.load(access::i64, text.address, word_size);
}
val held := this.build.variable(vt::word);
this.build.assign(held, length);
val looking := this.build.new_block();
val dropping := this.build.new_block();
val after := this.build.new_block();
this.build.branch(this.build.binary(op::ne, length, this.build.word(0)), looking, after);
this.build.seal(looking);
this.build.switch_to(looking);
val last := this.build.load(access::u8, this.build.binary(op::add, data, this.build.binary(op::sub, length, this.build.word(1))), 0);
this.build.branch(this.build.binary(op::eq, last, this.build.word('.' as u64)), dropping, after);
this.build.seal(dropping);
this.build.switch_to(dropping);
this.build.assign(held, this.build.binary(op::sub, length, this.build.word(1)));
this.build.jump(after);
this.build.seal(after);
this.build.switch_to(after);
var args: u32[2] = [data, this.build.read(held)];
this.build.effect(op::format_bytes, args[0:2], 0, 0);
}
#! Whether an expression ends the program: a call of `exit` or `abort`, which
#! the checker treats as leaving.
#! @param this The emitter.
#! @param node The expression.
#! @returns Whether it does.
def emitter::ends_program(&mut this, node: u32): bool {
return false if this.c.checker.kind_of(node) != nk::call;
val decl := this.c.checker.ref_at(node);
return false if decl == 0 || (decl & (ref_local | ref_type)) != 0;
return false if !this.c.checker.decls.has(decl, df::intrinsic);
val name := this.c.checker.names.text(this.c.checker.decls.names.p[decl]);
return name == "exit" || name == "abort" || name == "fault";
}
#! Lowers a local variable or constant. A constant known while compiling is no
#! local at all, being written wherever it is named.
#! @param this The emitter.
#! @param node The `variable` node.
def emitter::local_statement(&mut this, node: u32): void {
val value := this.c.checker.record(node, variable_slot::value);
val kind := this.c.checker.type_at(node);
if this.c.checker.node_has(node, nf::constant) && this.c.checker.is_known(node) {
return;
}
# A constant the checker did not work out is evaluated: read where it is
# once it is, while compiling, and where the program holds it as data after.
if this.c.checker.node_has(node, nf::constant) {
val key := node_key(this.table, node);
if this.c.options.evaluating {
val index := this.c.evaluation_of(key, 0, this.table, node, false);
this.build.effect(op::ready, span::<u32>::empty(), index, 0);
val offset: u64 = this.c.evaluations[index].offset;
val address := this.build.value(op::global, span::<u32>::empty(), vt::word, 0, offset);
this.declare(node, location { kind = kind, address = address }, false);
return;
}
val datum := this.c.evaluated_datum(key, kind);
if datum != no_block {
val address := this.build.value(op::datum, span::<u32>::empty(), vt::word, datum, 0);
this.declare(node, location { kind = kind, address = address }, false);
return;
}
}
# A function declared within a block is named in its own body, so its local
# is declared before its value is made.
if this.c.checker.node_has(node, nf::function) {
val place := this.new_place(node, kind);
this.declare(node, place, false);
val mark := this.begin_statement();
val made := this.value(value);
this.store(&place, &made);
this.end_statement(mark);
return;
}
val mark := this.begin_statement();
if value != 0 && this.refers_to_temporary(value) {
this.bound_temporary(node, value, kind, mark);
return;
}
# `undefined` leaves a cell as it is, and words, which cost nothing to give
# a value, are zero. Running with its memory checked, the cell is marked as
# never written, so reading it first stops the program.
if value != 0 && this.c.checker.kind_of(value) == nk::undefined {
val left := this.new_place(node, kind, ck::undefined);
if left.held {
this.zero(&left);
} else if this.c.options.checks {
this.build.forget(left.address, this.c.shape_of(kind).size);
}
this.end_statement(mark);
this.declare(node, left, false);
return;
}
val place := this.new_place(node, kind);
if value == 0 {
this.zero(&place);
this.defaults(&place);
} else {
val made := this.value_as(value, kind);
this.adopt(&made);
this.store(&place, &made);
}
this.end_statement(mark);
this.declare(node, place, this.c.checker.closes(kind));
}
#! Whether a value is a reference to a value that is no place, as
#! `&point { x = 1 }` or `&make()`, which the statement would hold.
#! @param this The emitter.
#! @param node The value's node.
#! @returns Whether it is.
def emitter::refers_to_temporary(&mut this, node: u32): bool {
return false if this.c.checker.kind_of(node) != nk::reference;
val inner := this.c.checker.left_of(node);
return false if this.c.checker.has_flag(node, rf::relent);
return !(this.c.checker.is_place(inner) && (!this.c.checker.is_known(inner) || this.stored(inner)));
}
#! Lowers a local whose value is a reference to a value that is no place, which
#! lives as long as the name does, as C++ has a temporary bound to a reference:
#! held in a cell of its own, as a local declared just before the name is, and
#! closed just after the name is.
#! @param this The emitter.
#! @param node The `variable` node.
#! @param value The `reference` node.
#! @param kind The local's type.
#! @param mark What the statement held before.
def emitter::bound_temporary(&mut this, node: u32, value: u32, kind: u32, mark: statement_mark): void {
val taken := this.c.checker.type_at(value);
val referent := this.c.checker.types.first_of(this.c.checker.unalias(taken));
val made := this.value_as(this.c.checker.left_of(value), referent);
this.adopt(&made);
val shape := this.c.shape_of(referent);
val cell := this.build.code.add_cell(round_up(shape.size == 0 ? word_size : shape.size, word_size) as u32,
shape.align < word_size ? word_size as u32 : shape.align as u32, ck::local, 0);
val held := location { kind = referent, address = this.build.cell_address(cell), framed = true };
this.store(&held, &made);
val referred := this.reference_to(&held, taken);
val converted := this.convert(&referred, kind);
val place := this.new_place(node, kind);
this.store(&place, &converted);
this.end_statement(mark);
this.declare(value, held, this.c.checker.closes(referent));
this.declare(node, place, this.c.checker.closes(kind));
}
#! Lowers `if`: the names its condition's tests give are declared before it runs,
#! and close where it ends, but those an `is not` test gives the rest of the
#! block where its branch always leaves.
#! @param this The emitter.
#! @param node The `if_stmt` node.
def emitter::if_statement(&mut this, node: u32): void {
val condition := this.c.checker.left_of(node);
val then := this.c.checker.record(node, if_slot::then);
val other := this.c.checker.record(node, if_slot::other);
val mark := this.begin_statement();
val locals := this.scope_mark();
this.declare_tests(condition);
val then_block := this.build.new_block();
val join := this.build.new_block();
val else_block := other != 0 ? this.build.new_block() : join;
this.branch_on(condition, then_block, else_block);
this.lower_branches(then, other, then_block, else_block, join);
# The names an `is not` test gives stay for the rest of the block, where the
# branch it guards always leaves.
val gives_rest := other == 0 && this.c.checker.has_flag(then, rf::leaves) && this.binds_where(condition, false);
if !gives_rest {
this.end_scope(locals, 0);
}
this.end_statement(mark);
}
#! Lowers `if const`: the branch the checker decided it takes, or where only the
#! program running decides it, as in a generic's instance whose condition the
#! checker left unknown, both, by the condition's value.
#! @param this The emitter.
#! @param node The `if_const` node.
def emitter::if_const(&mut this, node: u32): void {
val condition := this.c.checker.left_of(node);
val then := this.c.checker.record(node, if_slot::then);
val other := this.c.checker.record(node, if_slot::other);
if this.c.checker.is_known(condition) {
val taken := this.c.checker.value_at(condition).magnitude != 0 ? then : other;
this.lower_block(taken);
return;
}
# A condition evaluated decides the branch as one the checker decided does.
if this.c.evaluated.decisions.get(&node_key(this.table, node)) is some(holds) {
val taken := holds ? then : other;
this.lower_block(taken);
return;
}
val mark := this.begin_statement();
val then_block := this.build.new_block();
val join := this.build.new_block();
val else_block := other != 0 ? this.build.new_block() : join;
val cond := this.value_as(condition, bt::boolean);
this.build.branch(cond.words[0], then_block, else_block);
this.lower_branches(then, other, then_block, else_block, join);
this.end_statement(mark);
}
#! Lowers the branches of an `if` its condition branched to, each going on
#! where they join, and goes on there.
#! @param this The emitter.
#! @param then The block taken where the condition holds.
#! @param other The one taken where it does not, or 0.
#! @param then_block Where the first begins.
#! @param else_block Where the second begins, or `join`.
#! @param join Where they join.
def emitter::lower_branches(&mut this, then: u32, other: u32, then_block: u32, else_block: u32, join: u32): void {
this.build.seal(then_block);
if other != 0 {
this.build.seal(else_block);
}
this.build.switch_to(then_block);
this.lower_block(then);
this.build.jump(join);
if other != 0 {
this.build.switch_to(else_block);
this.lower_block(other);
this.build.jump(join);
}
this.build.seal(join);
this.build.switch_to(join);
}
#! Lowers `while`. Each pass, and each `continue`, closes what the condition
#! made, and the names its tests gave, before making them again.
#! @param this The emitter.
#! @param node The `while_stmt` node.
def emitter::while_statement(&mut this, node: u32): void {
val condition := this.c.checker.left_of(node);
val body := this.c.checker.right_of(node);
val head := this.build.new_block();
val exit := this.build.new_block();
val next := this.build.new_block();
this.build.jump(head);
this.build.switch_to(head);
val mark := this.begin_statement();
val locals := this.scope_mark();
this.declare_tests(condition);
val inside := this.build.new_block();
this.branch_on(condition, inside, exit);
this.build.seal(inside);
this.build.switch_to(inside);
this.safepoint();
this.loops.append(loop_info { exit = exit, next = next, locals = this.locals.length, kept = this.kept.length });
this.lower_block(body);
this.loops.truncate();
this.build.jump(next);
this.build.seal(next);
this.build.switch_to(next);
this.close_locals(locals, 0);
this.leave_kept(mark.kept);
# A `break` leaves with the names the test gave, which close here, and what the
# condition made closes where the statement ends.
this.close_loop(head, exit);
this.end_scope(locals, 0);
this.end_statement(mark);
}
#! Lowers `break` or `continue`: what the statements and scopes of the loop's
#! body hold is closed, and control goes to the loop's exit or its next pass.
#! @param this The emitter.
#! @param leaves Whether it is `break`.
def emitter::leave_loop(&mut this, leaves: bool): void {
return if this.loops.length == 0;
val held: loop_info = this.loops.last();
this.leave_kept(held.kept);
this.close_locals(held.locals, 0);
this.build.jump(leaves ? held.exit : held.next);
}
#! Lowers a condition as a branch: where it holds, to one block, and to another
#! where it does not. `&&` and `||` go to the second only where the first does
#! not decide.
#! @param this The emitter.
#! @param node The condition.
#! @param then Where it goes where the condition holds.
#! @param other Where it goes where it does not.
pub def emitter::branch_on(&mut this, node: u32, then: u32, other: u32): void {
if this.c.checker.is_known(node) {
this.build.jump(this.c.checker.value_at(node).magnitude != 0 ? then : other);
return;
}
if this.c.checker.kind_of(node) == nk::binary {
val operator := this.c.checker.token_kind(node);
if operator == tk::logand || operator == tk::logor {
val middle := this.build.new_block();
if operator == tk::logand {
this.branch_on(this.c.checker.left_of(node), middle, other);
} else {
this.branch_on(this.c.checker.left_of(node), then, middle);
}
this.build.seal(middle);
this.build.switch_to(middle);
this.branch_on(this.c.checker.right_of(node), then, other);
return;
}
}
if this.c.checker.kind_of(node) == nk::unary && this.c.checker.token_kind(node) == tk::negate {
this.branch_on(this.c.checker.left_of(node), other, then);
return;
}
val made := this.value_as(node, bt::boolean);
this.build.branch(made.words[0], then, other);
}
#! Declares the locals the tests of a condition name their values in, before
#! any of it runs, since `&&` and `||` may leave a test that would set one
#! unrun. One that closes starts zeroed, so closing it where it was never given
#! closes nothing.
#! @param this The emitter.
#! @param node The condition.
pub def emitter::declare_tests(&mut this, node: u32): void {
return if node == 0;
match this.c.checker.kind_of(node) {
nk::is_test => {
val binding := this.c.checker.named_binding(this.c.checker.record(node, is_slot::binding));
return if binding == 0;
val named := this.c.checker.kind_of(binding) == nk::reference ? this.c.checker.left_of(binding) : binding;
return if !this.c.checker.has_flag(named, rf::narrowed) || this.local_of(named) != 0;
val kind := this.c.checker.type_at(named);
val place := this.new_place(named, kind);
val closes := this.c.checker.closes(kind);
if closes {
this.zero(&place);
}
this.declare(named, place, closes);
}
nk::binary => {
val operator := this.c.checker.token_kind(node);
if operator == tk::logand || operator == tk::logor {
this.declare_tests(this.c.checker.left_of(node));
this.declare_tests(this.c.checker.right_of(node));
}
}
nk::unary => {
if this.c.checker.token_kind(node) == tk::negate {
this.declare_tests(this.c.checker.left_of(node));
}
}
else => {}
}
}
#! Whether a condition's tests name a value where it holds as `positive` says,
#! through `&&`, `||`, and `!`.
#! @param this The emitter.
#! @param node The condition.
#! @param positive Whether the condition holds where the value is named.
#! @returns Whether they do.
pub def emitter::binds_where(&mut this, node: u32, positive: bool): bool {
return false if node == 0;
match this.c.checker.kind_of(node) {
nk::is_test => {
return this.c.checker.named_binding(this.c.checker.record(node, is_slot::binding)) != 0
&& this.c.checker.node_has(node, nf::negated) != positive;
}
nk::binary => {
val operator := this.c.checker.token_kind(node);
return false if !((operator == tk::logand && positive) || (operator == tk::logor && !positive));
return this.binds_where(this.c.checker.left_of(node), positive)
|| this.binds_where(this.c.checker.right_of(node), positive);
}
nk::unary => {
return this.c.checker.token_kind(node) == tk::negate && this.binds_where(this.c.checker.left_of(node), !positive);
}
else => {}
}
return false;
}
+246
View File
@@ -0,0 +1,246 @@
#! @file storage.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains where a function's locals are held, worked out before its body is
#! lowered from where its references are made, as `escapes.sakura` finds it. A
#! local is held in variables of the builder unless a reference to it is made,
#! and then in a cell of the frame, which the reference refers to while the
#! local lives. Nothing is moved to the heap: a reference that outlives what it
#! refers to is the program's mistake, which the checker warns of where it is
#! sure of it.
import sakura::analyzer;
module sakura::compiler;
#! Works out where the locals of a function's body are held, given what its
#! parameters are.
#! @param this The emitter.
#! @param decl The function's declaration.
#! @param params The run of its parameters' nodes.
#! @param kind Its function type, given its type arguments.
#! @param body The body's node.
pub def emitter::plan_function(&mut this, decl: u32, params: u32, kind: u32, body: u32): void {
var s := escape_scan::new(scratch());
s.result = this.c.checker.types.first_of(kind);
this.c.scan_params(&mut s, params, kind, this.c.packs_last(decl));
this.c.scan_body(&mut s, body);
this.apply_plan(&mut s, body);
}
#! Works out where the locals of an anonymous function's body are held. What it
#! captures is the function's around it, reached through its environment, as
#! what a parameter refers to is the caller's.
#! @param this The emitter.
#! @param node The `lambda` node.
pub def emitter::plan_lambda(&mut this, node: u32): void {
var s := escape_scan::new(scratch());
val kind := this.c.checker.type_at(node);
s.result = this.c.checker.types.first_of(kind);
var captures := this.captures_of(node);
for &each in captures {
val outer := s.graph.new_spot(spot_kind::outer, each, 0);
val inner := s.graph.new_spot(spot_kind::inner, each, 0);
s.graph.add(s.graph.held_by(outer), inner);
s.graph.add(s.graph.held_by(inner), inner);
s.slots.set(each, outer);
}
this.c.scan_params(&mut s, this.c.checker.left_of(node), kind, false);
val body := this.c.checker.record(node, lambda_slot::body);
this.c.scan_body(&mut s, body);
this.apply_plan(&mut s, body);
}
#! Works out where the locals of a value evaluated into a global are held,
#! which keeps what it holds.
#! @param this The emitter.
#! @param value The value's node.
pub def emitter::plan_storage(&mut this, value: u32): void {
var s := escape_scan::new(scratch());
s.graph.keep(this.c.value_flow(&mut s, value));
this.apply_plan(&mut s, value);
}
#! Holds in a cell each local a reference is made to. What is within an
#! anonymous function is left to its own plan.
#! @param this The emitter.
#! @param s The scan.
#! @param body The body scanned.
def emitter::apply_plan(&mut this, s: &mut escape_scan, body: u32): void {
for at in 0..s.graph.spots.length {
val held: spot = s.graph.spots[at];
continue if held.depth != 0;
if held.kind == spot_kind::local && held.taken {
this.raise(held.node, held_as::cell);
}
}
this.check_plan(s, body);
}
#! Holds in a cell any local a reference is made to that the scan did not see
#! made, which it always sees, so no reference refers to a local held in
#! variables: the operand of `&`, what a parameter taking a reference is given,
#! a method's receiver, the operands of an operator's method, what a loop
#! walks, a union a match names a field of by `&`, and what an anonymous
#! function captures.
#! @param this The emitter.
#! @param s The scan.
#! @param body The body scanned.
def emitter::check_plan(&mut this, s: &mut escape_scan, body: u32): void {
var walk := node_walk::new(body);
while walk.more() {
val at := walk.next();
# A contract left out refers to nothing.
continue if this.c.checker.contracts_off && this.c.checker.kind_of(at) == nk::contract;
match this.c.checker.kind_of(at) {
nk::reference => {
val inner := this.c.checker.left_of(at);
if this.c.checker.is_place(inner) && (!this.c.checker.is_known(inner) || this.stored(inner)) {
this.check_taken(s, inner);
}
}
nk::lambda => {
var captures := this.captures_of(at);
for &each in captures {
this.check_local(s, each);
}
}
nk::member => {
# A property's accessors are given a reference to the value.
if this.property_of(at) != 0 {
this.check_taken(s, this.c.checker.left_of(at));
}
}
nk::index => {
# So is `at`, but for what the language indexes itself.
val ref := this.c.checker.ref_at(at);
val through := this.c.checker.unalias(this.c.checker.reached(this.object_type(this.c.checker.left_of(at))));
val kind := this.c.checker.types.kind_of(through);
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::function
&& kind != ty::fixed && kind != ty::pointer && kind != ty::pack && this.c.viewed(through) == 0 {
this.check_taken(s, this.c.checker.left_of(at));
}
}
nk::binary, nk::assign => {
if this.operator_method(at) != 0 {
this.check_taken(s, this.c.checker.left_of(at));
this.check_taken(s, this.c.checker.right_of(at));
}
}
nk::unary => {
val token := this.c.checker.token_kind(at);
if (token == tk::minus || token == tk::bitnot) && this.operator_decl(at) != 0 {
this.check_taken(s, this.c.checker.left_of(at));
}
}
nk::for_stmt => {
val iterated := this.c.checker.record(at, for_slot::iterated);
val through := this.c.checker.unalias(this.c.checker.type_at(iterated));
if this.c.checker.record(at, for_slot::end) == 0 && !this.c.checker.node_has(at, nf::constant)
&& this.c.viewed(through) == 0 && this.c.checker.types.kind_of(through) != ty::pointer {
this.check_taken(s, iterated);
}
}
nk::is_test => {
val binding := this.c.checker.record(at, is_slot::binding);
if binding != 0 && this.c.checker.kind_of(binding) == nk::reference {
this.check_taken(s, this.c.checker.left_of(at));
}
}
nk::match_stmt, nk::match_value => {
if this.c.refers_in_arm(at) {
this.check_taken(s, this.c.checker.left_of(at));
}
}
else => {}
}
if this.c.checker.has_flag(at, rf::borrowed) {
this.check_taken(s, at);
}
if this.c.checker.kind_of(at) != nk::lambda {
this.c.scan_children(at, &mut walk);
}
}
}
#! Holds in a cell the local whose own storage a place is within, past fields
#! and the elements of fixed arrays, where a reference to it is made that the
#! scan did not see.
#! @param this The emitter.
#! @param s The scan.
#! @param node The place's node.
def emitter::check_taken(&mut this, s: &mut escape_scan, node: u32): void {
var at := node;
var steps := 0;
while at != 0 && steps < 64 {
steps++;
val kind := this.c.checker.kind_of(at);
if kind == nk::member {
val ref := this.c.checker.ref_at(at);
return if ref == 0 || (ref & (ref_local | ref_type)) != 0 || this.c.checker.decls.kinds.p[ref] != dk::field;
val inner := this.c.checker.left_of(at);
return if this.c.is_reference_type(this.c.checker.type_at(inner));
at = inner;
continue;
}
if kind == nk::index {
val inner := this.c.checker.left_of(at);
return if this.c.checker.types.kind_of(this.c.checker.unalias(this.c.checker.type_at(inner))) != ty::fixed;
at = inner;
continue;
}
break;
}
return if at == 0 || this.c.checker.kind_of(at) != nk::name;
val ref := this.c.checker.ref_at(at);
return if (ref & ref_local) == 0 || this.c.is_reference_type(this.c.checker.type_at(at));
this.check_local(s, ref & ref_mask);
}
#! Holds a local in a cell where the scan did not see a reference to it made.
#! @param this The emitter.
#! @param s The scan.
#! @param local The node declaring the local.
def emitter::check_local(&mut this, s: &mut escape_scan, local: u32): void {
if s.slots.get(&local) is some(at) {
return if s.graph.spots[at as u64].taken || s.graph.spots[at as u64].kind != spot_kind::local;
}
this.raise(local, held_as::cell);
}
#! Holds a local at least as the way given: a cell over variables.
#! @param this The emitter.
#! @param local The node declaring the local.
#! @param how How it must be held.
def emitter::raise(&mut this, local: u32, how: held_as): void {
val held := this.storage.get_or(&local, held_as::words);
if (how as u8) > (held as u8) {
this.storage.set(local, how);
}
}
#! The method an operator calls, where the language does not operate on its
#! operands itself: the one the checker chose for arithmetic, or the `equals`
#! or `compare` of what implements `equatable` or `ordered`, or 0.
#! @param this The emitter.
#! @param node The `binary` or `assign` node.
#! @returns The method's declaration, or 0.
pub def emitter::operator_method(&mut this, node: u32): u32 {
return 0 if this.c.checker.kind_of(node) == nk::unary;
val operator := this.c.checker.token_kind(node);
return 0 if operator == tk::logand || operator == tk::logor || operator == tk::assign;
val chosen := this.operator_decl(node);
return chosen if chosen != 0;
val kind := this.c.checker.type_at(this.c.checker.left_of(node));
val plain := this.c.checker.unalias(this.c.layout_type(this.c.checker.read_type(kind)));
val named := this.c.checker.named_kind(plain);
return 0 if named != dk::struct_type && named != dk::union_type;
if operator.compares() {
val equal := operator == tk::equals || operator == tk::noteq;
return this.pick_method(plain, equal ? word::equals : word::compare, true);
}
return 0;
}
+487
View File
@@ -0,0 +1,487 @@
#! @file values.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the lowering of expressions to their values: what each kind of
#! node gives, the constants the checker worked out, and the conversions the
#! checker recorded, by which a value of one type is taken where another is
#! expected.
import sakura::analyzer;
module sakura::compiler;
#! The value of an expression as the type it is used as: the type the checker
#! converts it to, or its own.
#! @param this The emitter.
#! @param node The expression.
#! @returns The value.
pub def emitter::value(&mut this, node: u32): operand {
var to := this.c.checker.converted(node);
if this.c.checker.is_known(node) && this.c.is_scalar_type(to) {
# An integer constant past what an `i64` holds is unsigned, as `1 << 63` is.
val held := this.c.checker.value_at(node);
if this.c.checker.types.kind_of(to) == ty::untyped_int && !held.floating && !held.negative
&& held.magnitude > 0x7FFFFFFFFFFFFFFF {
to = bt::uint64;
}
return this.known(&held, to);
}
val own := this.raw(node);
return this.convert(&own, to);
}
#! The value of an expression as its own type, before any conversion.
#! @param this The emitter.
#! @param node The expression.
#! @returns The value.
pub def emitter::value_of_type(&mut this, node: u32): operand {
val own := this.c.checker.type_at(node);
if this.c.checker.is_known(node) && this.c.is_scalar_type(own) {
return this.known(&this.c.checker.value_at(node), own);
}
return this.raw(node);
}
#! The value of an expression converted to a type.
#! @param this The emitter.
#! @param node The expression.
#! @param to The type.
#! @returns The value.
pub def emitter::value_as(&mut this, node: u32, to: u32): operand {
if this.c.checker.is_known(node) && this.c.is_scalar_type(to) {
return this.known(&this.c.checker.value_at(node), to);
}
val made := this.value(node);
return this.convert(&made, to);
}
#! A constant the checker worked out, as a value of a type.
#! @param this The emitter.
#! @param value The constant.
#! @param kind The type, a number, `bool`, enum, or pointer.
#! @returns The value.
pub def emitter::known(&mut this, value: &constant, kind: u32): operand {
val held := this.c.shape_of(kind);
if held.kind == lk::floating {
var real := value.as_real();
if held.bits <= 32 {
real = (real as f32) as f64;
}
return operand::one(kind, this.build.real(bits_of_real(real)));
}
var bits := value.floating ? (value.real < 0.0 ? 0 - ((0.0 - value.real) as u64) : value.real as u64) : value.bits();
return operand::one(kind, this.build.word(bits));
}
#! The value of an expression as its own type, of each kind of node. What it
#! lowers is from the node, as what its operands lower is from theirs, and
#! what is lowered after it is from where it was before.
#! @param this The emitter.
#! @param node The expression.
#! @returns The value.
pub def emitter::raw(&mut this, node: u32): operand {
val saved := this.build.pos;
this.at_node(node);
val made := this.raw_node(node);
this.build.pos = saved;
return made;
}
#! The value of an expression as its own type, by the kind of its node.
#! @param this The emitter.
#! @param node The expression.
#! @returns The value.
def emitter::raw_node(&mut this, node: u32): operand {
val kind := this.c.checker.type_at(node);
if this.c.checker.has_flag(node, rf::reflected) {
return this.reflected_value(node);
}
match this.c.checker.kind_of(node) {
nk::number, nk::character, nk::boolean => return this.known(&this.c.checker.value_at(node), kind);
nk::string => {
# Text given to what is not text, as a union holding a view, is made as the
# view it settles as, which is then converted.
val to := this.c.checker.converted(node);
val own := this.c.is_string(to) || this.c.viewed(to) != 0 ? to : this.c.checker.settle(kind);
return this.text_literal(node, own);
}
nk::istring => return this.interpolated(node);
nk::null_lit => return this.zero_value(this.c.checker.converted(node));
nk::name, nk::path => return this.name_value(node);
nk::unary => return this.unary(node);
nk::postfix => return this.step(node, this.c.checker.left_of(node), false);
nk::reference => return this.reference(node);
nk::binary => return this.binary(node);
nk::assign => return this.assign(node);
nk::ternary => return this.ternary(node);
nk::fallback => return this.fallback(node);
nk::call => {
val made := this.call(node);
this.keep(&made);
return made;
}
nk::index => {
if this.indexes_through_at(node) {
return this.indexed_reference(node);
}
val place := this.place_of(node);
return this.load(&place);
}
# `x.(d)` reads the field or property a description names.
nk::member_of => return this.member_value(node);
# `value_of(d)::<i64>` is the instance its type arguments make.
nk::type_args => return this.function_value(node, this.c.checker.ref_at(node));
nk::slice => return this.slice(node);
nk::member => return this.member_value(node);
nk::cast => return this.cast(node);
nk::is_test => return this.is_test(node);
nk::construct => {
val made := this.construct(node);
this.keep(&made);
return made;
}
nk::array => {
val made := this.array_literal(node, this.c.checker.converted(node));
this.keep(&made);
return made;
}
nk::lambda => return this.lambda_value(node);
nk::match_value => return this.match_value(node);
nk::range => return this.range_value(node);
# What `e` was is kept where its `ensures` was reached.
nk::old_value => {
val local := this.local_of(node);
if local != 0 {
val held: location = this.locals[local as u64 - 1].place;
return this.load(&held);
}
}
else => {}
}
this.problem(node, "The expression is not lowered.");
return this.zero_value(kind);
}
#! The zero value of a type: zero words, or a zeroed cell.
#! @param this The emitter.
#! @param kind The type.
#! @returns The value.
pub def emitter::zero_value(&mut this, kind: u32): operand {
val held := this.c.shape_of(kind);
if in_memory(&held) {
val address := this.temporary_of(kind);
this.build.clear(address, held.size);
return operand::at(kind, address);
}
var made := operand { kind = kind, count = word_count(&held) };
for i in 0..made.count {
made.words[i] = word_type(&held) == vt::real ? this.build.real(0) : this.build.word(0);
}
return made;
}
#! The value a name or path gives: a local, a global, a constant, an enum
#! member, a constant parameter, or a function.
#! @param this The emitter.
#! @param node The `name` or `path` node.
#! @returns The value.
pub def emitter::name_value(&mut this, node: u32): operand {
val ref := this.c.checker.ref_at(node);
val kind := this.c.checker.type_at(node);
if (ref & ref_local) != 0 {
val place := this.place_of(node);
return this.load(&place);
}
if (ref & ref_type) != 0 {
return this.known_argument(ref & ref_mask, kind);
}
if ref == 0 {
this.problem(node, "The name refers to nothing.");
return this.zero_value(kind);
}
match this.c.checker.decls.kinds.p[ref] {
dk::function => return this.function_value(node, ref);
dk::variable => {
val place := this.global_place(ref);
return this.load(&place);
}
dk::enum_member => {
var value := constant {};
this.c.checker.decl_value(ref, &mut value);
return this.known(&value, kind);
}
else => {}
}
this.problem(node, "The name is no value.");
return this.zero_value(kind);
}
#! The value of a constant type argument a constant parameter names.
#! @param this The emitter.
#! @param arg The type argument, a constant.
#! @param kind The type of its value.
#! @returns The value.
pub def emitter::known_argument(&mut this, arg: u32, kind: u32): operand {
if this.c.checker.types.kind_of(arg) != ty::value {
this.problem(0, "A constant parameter is given no value.");
return this.zero_value(kind);
}
return this.known_object(this.c.checker.types.second_of(arg), kind);
}
#! A value the checker worked out, as a value of a type: a number, text, a
#! struct, union, or array of them, `null`, a function, or the address of a
#! constant.
#! @param this The emitter.
#! @param id The value's ID among the checker's known values.
#! @param kind The type.
#! @returns The value.
pub def emitter::known_object(&mut this, id: u32, kind: u32): operand {
val held: known = this.c.checker.known_at(id);
val shape := this.c.shape_of(kind);
match held.kind {
kk::number, kk::real => return this.known(&held.value, kind);
kk::null_lit => return this.zero_value(kind);
kk::text => return this.text_value(this.c.checker.known_text(id), kind);
kk::function => {
val index := this.c.function_of(held.decl, 0);
this.c.program.functions[index].taken = true;
this.c.names(this.function, index);
return operand::two(kind, this.build.word(index as u64 + 1), this.build.word(0));
}
kk::address => {
val place := this.global_place(held.decl);
return this.reference_to(&place, kind);
}
kk::fields => {
val address := this.temporary_of(kind);
this.build.clear(address, shape.size);
val whole := location { kind = kind, address = address, framed = true };
val plain := this.c.checker.unalias(kind);
if shape.kind == lk::fixed {
val element := this.c.checker.types.first_of(plain);
val inner := this.c.shape_of(element);
for i in 0..this.c.checker.known_count(id) {
val part := this.known_object(this.c.checker.known_part(id, i as u32), element);
val at := this.within(&whole, i as u64 * inner.size, element);
this.store(&at, &part);
}
return operand::at(kind, address);
}
val index := this.c.layout_of(plain);
for i in 0..this.c.checker.known_count(id) {
break if i >= shape.count as u64;
val field := this.c.field_at(index, i as u32);
val part := this.known_object(this.c.checker.known_part(id, i as u32), field.type_id);
val at := this.within(&whole, field.offset, field.type_id);
this.store(&at, &part);
}
return operand::at(kind, address);
}
kk::held => {
val address := this.temporary_of(kind);
this.build.clear(address, shape.size);
val tag := held.value.magnitude as u32;
if shape.niche == 0 {
this.build.store(access::i64, address, 0, this.build.word(tag as u64));
}
val index := this.c.layout_of(this.c.checker.unalias(kind));
if tag < shape.count && this.c.checker.known_count(id) != 0 {
val field := this.c.field_at(index, tag);
val part := this.known_object(this.c.checker.known_part(id, 0), field.type_id);
val at := location { kind = field.type_id, address = address, offset = field.offset, framed = true };
this.store(&at, &part);
}
return operand::at(kind, address);
}
else => {}
}
this.problem(0, "A constant argument is not worked out.");
return this.zero_value(kind);
}
#! The value text written as a literal is, as the type it is used as: a view of
#! the bytes it was written with, which stand as long as the program runs, or a
#! `string` holding a copy of them it owns.
#! @param this The emitter.
#! @param node The `string` node.
#! @param kind The type it is used as.
#! @returns The value.
pub def emitter::text_literal(&mut this, node: u32, kind: u32): operand {
var text := string::new(nothing {});
this.decode_literal(this.c.checker.text_of(node), &mut text);
return this.text_value(text.view(), kind);
}
#! Text as a value of a type: a view of a datum holding its bytes, or a
#! `string` holding a copy of them.
#! @param this The emitter.
#! @param text The bytes.
#! @param kind The type: a view of bytes, or `string`.
#! @returns The value.
pub def emitter::text_value(&mut this, text: strview, kind: u32): operand {
val datum := this.c.text_datum(text);
if this.c.is_string(kind) {
this.build.effect(op::format, span::<u32>::empty(), 0, 0);
this.build.effect(op::format_text, span::<u32>::empty(), datum, 0);
return this.owned_text(kind);
}
val address := this.temporary_of(kind);
val data := text.length == 0 ? this.build.word(0) : this.build.value(op::datum, span::<u32>::empty(), vt::word, datum, 0);
this.build.store(access::i64, address, 0, data);
this.build.store(access::i64, address, word_size, this.build.word(text.length));
return operand::at(kind, address);
}
#! A value of a type taken as another, as the checker converts it: widened,
#! read through references, given to a union, referred to as a trait, or lent
#! as a view.
#! @param this The emitter.
#! @param value The value.
#! @param to The type it is taken as.
#! @returns The value converted.
pub def emitter::convert(&mut this, value: &operand, to: u32): operand {
var made: operand = value;
return made if value.kind == to || to == bt::error || to == 0 || value.kind == bt::error;
val from := this.c.layout_type(value.kind);
val target := this.c.layout_type(to);
made.kind = to;
return made if from == target || this.c.checker.strip(from, 0) == this.c.checker.strip(target, 0);
val fk := this.c.checker.types.kind_of(from);
val tok := this.c.checker.types.kind_of(target);
# Numbers widen within their kind, which their words already hold, and an
# integer operating with a float operates as the float.
if this.c.checker.types.is_numeric(from) && this.c.checker.types.is_numeric(target) {
if this.c.checker.types.is_float(target) && !this.c.checker.types.is_float(from) {
val signed := this.c.checker.types.is_signed(from);
var real := this.build.unary(signed ? op::itof : op::utof, value.words[0]);
if this.c.checker.types.first_of(target) <= 32 {
real = this.build.unary(op::fsingle, real);
}
return operand::one(to, real);
}
return made;
}
# An enum is its integer.
if this.c.checker.named_kind(from) == dk::enum_type && this.c.checker.types.is_integer(target) {
return made;
}
if fk == ty::reference && tok == ty::reference {
val inner_from := this.c.checker.unalias(this.c.checker.types.first_of(from));
val inner_to := this.c.checker.unalias(this.c.checker.types.first_of(target));
val from_trait := this.c.checker.named_kind(inner_from) == dk::trait_type;
val to_trait := this.c.checker.named_kind(inner_to) == dk::trait_type;
# A reference to a value becomes one to a trait it implements, given the
# vtable of its type for the trait.
if to_trait && !from_trait && this.c.checker.types.kind_of(inner_from) != ty::reference {
val vtable := this.c.vtable_of(this.c.checker.types.first_of(from), inner_to);
return operand::two(to, value.words[0], this.build.word(vtable as u64));
}
# A reference to a trait becomes one to another the value also implements.
if to_trait && from_trait {
return made if inner_from == inner_to;
var args: u32[1] = [value.words[1]];
val map := this.c.retrait_of(inner_from, inner_to);
val vtable := this.build.value(op::retrait, args[0:1], vt::word, map, 0);
return operand::two(to, value.words[0], vtable);
}
# A reference to a reference is read through to the one it holds.
if this.c.checker.types.kind_of(inner_from) == ty::reference && this.c.checker.types.kind_of(inner_to) != ty::reference {
val place := this.referent(value);
val inner := this.load(&place);
return this.convert(&inner, to);
}
return made;
}
# A union holds a value as the field of its type, another union's too, and
# a reference where one of its fields is one; and otherwise a reference is
# read through first.
if this.c.checker.named_kind(target) == dk::union_type && this.c.checker.united_field(value.kind, target) != 0 {
return this.unite(value, target, to);
}
# A reference written as one becomes a pointer at what it refers to, which
# holds the same word.
if fk == ty::reference && tok == ty::pointer
&& this.c.checker.unalias(this.c.checker.types.first_of(from)) == this.c.checker.unalias(this.c.checker.types.first_of(target)) {
return made;
}
# A plain reference is read through where its value is expected.
if fk == ty::reference {
val place := this.referent(value);
val inner := this.load(&place);
return this.convert(&inner, to);
}
# Bytes become a string by being copied, which the statement keeps, from the
# view's two words wherever they are.
if this.c.is_string(target) && this.c.checker.is_byte_view(from) && (value.address != 0 || value.count == 2) {
var args: u32[2] = [0, 0];
if value.address != 0 {
args[0] = this.build.load(access::i64, value.address, 0);
args[1] = this.build.load(access::i64, value.address, word_size);
} else {
args[0] = value.words[0];
args[1] = value.words[1];
}
this.build.effect(op::format, span::<u32>::empty(), 0, 0);
this.build.effect(op::format_bytes, args[0:2], 0, 0);
return this.owned_text(to);
}
# A string lends a view of its text: where its bytes begin, and how many.
if this.c.is_string(from) && this.c.viewed(target) != 0 {
val index := this.c.layout_of(from);
val data := this.c.field_at(index, 1);
val count := this.c.field_at(index, 2);
val address := this.temporary_of(to);
this.build.store(access::i64, address, 0, this.build.load(access::i64, value.address, data.offset));
this.build.store(access::i64, address, word_size, this.build.load(access::i64, value.address, count.offset));
return operand::at(to, address);
}
# What else converts holds the same words: a writable view lending a
# read-only one, a function by another name, `null` becoming a pointer.
return made;
}
#! A union holding a value, as the field the checker finds of its type.
#! @param this The emitter.
#! @param value The value.
#! @param target The union's type, without aliases.
#! @param to The type it is taken as.
#! @returns The union.
pub def emitter::unite(&mut this, value: &operand, target: u32, to: u32): operand {
val field := this.c.checker.united_field(value.kind, target);
val index := this.c.layout_of(target);
val shape := this.c.layout_at(index);
val address := this.temporary_of(to);
this.build.clear(address, shape.size);
for i in 0..shape.count {
val each := this.c.field_at(index, i as u32);
continue if each.decl != field;
if shape.niche == 0 {
this.build.store(access::i64, address, 0, this.build.word(i));
}
val held := this.convert(value, each.type_id);
val at := location { kind = each.type_id, address = address, offset = each.offset, framed = true };
this.store(&at, &held);
this.adopt(value);
return operand::at(to, address);
}
this.problem(0, "A union holds no field of the value's type.");
return operand::at(to, address);
}
File diff suppressed because it is too large. Load diff
+357
View File
@@ -0,0 +1,357 @@
#! @file flows.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains where the references of a body may go, as `escapes.sakura` finds
#! it: the spots a reference may refer to, and the sets of spots the values of
#! the body may hold references to. Each spot holds a set of its own, of what
#! is stored in it. A set flows into another as a value is copied; reading
#! through a set, what each of its spots holds flows into another; and writing
#! through one, a set flows into what each of its spots holds. Two sets stand
#! for where values leave the body: what may be kept past it, and what it gives
#! back.
#!
#! Solving carries each spot along the flows until no set grows, as Andersen's
#! analysis does, without telling the fields of a value apart. A spot then in
#! the set of what is kept is kept, one in the set given back is given back,
#! and so is every spot held by one that is, since whoever holds it may reach
#! them. A spot of the frame held by one that may outlive it is kept too: a
#! value a statement holds held by anything but another such value, or a local
#! held by a local declared before it, which may be given another value later,
#! as each pass of a loop gives one declared within it.
import std::containers;
module sakura::compiler;
#! What a spot stands for.
pub enum spot_kind : u8 {
local, #! The storage of a local, a parameter, or a name a test or a loop gives.
temp, #! A value a statement holds where a reference to it is taken.
env, #! The environment of an anonymous function, which holds references to what it captures.
outer, #! What a parameter taking a reference refers to, the caller's.
inner, #! What the caller's references reach through a parameter, the caller's.
shared, #! What any code may reach: the globals, the heap, and what pointers point at.
}
#! How far a spot may outlive the body, as solving finds.
pub enum reach : u8 {
stays, #! Not past the body.
given, #! Given back, in what the body returns.
kept, #! Kept past the body, as where it is stored.
}
#! A spot a reference may refer to.
pub struct spot {
var kind: spot_kind; #! What it stands for.
var node: u32; #! The node declaring it, or making it.
var held: u32; #! The set of what is stored in it.
var alone: u32; #! A set of it alone, or 0 until one is asked for.
var depth: u32; #! How many anonymous functions it is declared within.
var reach: reach; #! How far it may outlive the body.
var taken: bool; #! Whether a reference to it is made.
}
#! The spots and sets of a body, and the flows between them.
pub struct flow {
var spots: vector<spot>; #! The spots.
var heads: vector<u32>; #! Of each set, one more than its first member's link, or 0.
var member: vector<u32>; #! Of each link of a set's members, the spot.
var next: vector<u32>; #! Of each link, one more than the next link of the same list, or 0.
var copies: vector<u32>; #! Of each set, one more than the first link of the sets it flows into.
var reads: vector<u32>; #! Of each set, one more than the first link of the sets what its spots hold flows into.
var writes: vector<u32>; #! Of each set, one more than the first link of the sets that flow into what its spots hold.
var known: hashset<u64>; #! The spots each set holds, by `pair_key(set, spot)`.
var edges: hashset<u64>; #! The flows from set to set, by `pair_key(from, to)`.
var work: vector<u64>; #! The spots added to sets not yet carried on, by `pair_key(set, spot)`.
var kept: u32; #! The set of what may be kept past the body.
var given: u32; #! The set of what the body may give back.
var shared: u32; #! The spot of what any code may reach.
}
#! Makes the flows of a body, with nothing in them but the sets of what is kept
#! and given back, and the spot any code may reach, which holds itself.
#! @param alloc The optional allocator its memory is taken from.
#! @returns The flows.
pub def flow::new(alloc: maybe<&mut allocator>): flow {
var made := flow {
spots = vector::<spot>::new(alloc),
heads = vector::<u32>::new(alloc),
member = vector::<u32>::new(alloc),
next = vector::<u32>::new(alloc),
copies = vector::<u32>::new(alloc),
reads = vector::<u32>::new(alloc),
writes = vector::<u32>::new(alloc),
known = hashset::<u64>::new(alloc),
edges = hashset::<u64>::new(alloc),
work = vector::<u64>::new(alloc)
};
# Set 0 stands for none.
made.heads.append(0);
made.copies.append(0);
made.reads.append(0);
made.writes.append(0);
made.kept = made.new_set();
made.given = made.new_set();
made.shared = made.new_spot(spot_kind::shared, 0, 0);
made.add(made.spots[made.shared as u64].held, made.shared);
return made;
}
#! Makes an empty set.
#! @param this The flows.
#! @returns The set.
pub def flow::new_set(&mut this): u32 {
val made := this.heads.length as u32;
this.heads.append(0);
this.copies.append(0);
this.reads.append(0);
this.writes.append(0);
return made;
}
#! Makes a spot, holding nothing yet.
#! @param this The flows.
#! @param kind What it stands for.
#! @param node The node declaring or making it.
#! @param depth How many anonymous functions it is declared within.
#! @returns The spot.
pub def flow::new_spot(&mut this, kind: spot_kind, node: u32, depth: u32): u32 {
val held := this.new_set();
val made := this.spots.length as u32;
this.spots.append(spot { kind = kind, node = node, held = held, depth = depth });
return made;
}
#! The set of a spot alone, as a reference to it is.
#! @param this The flows.
#! @param at The spot.
#! @returns The set.
pub def flow::alone(&mut this, at: u32): u32 {
val had: u32 = this.spots[at as u64].alone;
return had if had != 0;
val made := this.new_set();
this.spots[at as u64].alone = made;
this.add(made, at);
return made;
}
#! The set of what a spot holds.
#! @param this The flows.
#! @param at The spot.
#! @returns The set.
pub def flow::held_by(&this, at: u32): u32 {
return this.spots[at as u64].held;
}
#! Whether what is written to a spot leaves the body: the caller's, or what any
#! code may reach.
#! @param this The flows.
#! @param at The spot.
#! @returns Whether it does.
pub def flow::outside(&this, at: u32): bool {
val kind: spot_kind = this.spots[at as u64].kind;
return kind == spot_kind::outer || kind == spot_kind::inner || kind == spot_kind::shared;
}
#! Adds a spot to a set, to be carried along its flows.
#! @param this The flows.
#! @param set The set, or 0 for none.
#! @param at The spot.
pub def flow::add(&mut this, set: u32, at: u32): void {
return if set == 0;
val key := pair_key(set, at);
return if !this.known.insert(key);
this.member.append(at);
this.next.append(this.heads[set as u64]);
this.heads[set as u64] = this.member.length as u32;
this.work.append(key);
}
#! Links a set into one of the lists a set has of where it flows.
#! @param this The flows.
#! @param head The first link of the list, which becomes the new one.
#! @param set The set linked.
def flow::link(&mut this, head: &mut u32, set: u32): void {
this.member.append(set);
this.next.append(head);
head = this.member.length as u32;
}
#! Has a set flow into another: every spot one holds, the other does.
#! @param this The flows.
#! @param from The set flowing, or 0 for none.
#! @param to The set it flows into, or 0 for none.
pub def flow::into(&mut this, from: u32, to: u32): void {
return if from == 0 || to == 0 || from == to;
return if !this.edges.insert(pair_key(from, to));
var head: u32 = this.copies[from as u64];
this.link(&mut head, to);
this.copies[from as u64] = head;
var at: u32 = this.heads[from as u64];
while at != 0 {
this.add(to, this.member[at as u64 - 1]);
at = this.next[at as u64 - 1];
}
}
#! Has what each spot of a set holds flow into another set, as reading through
#! the references the set stands for does.
#! @param this The flows.
#! @param from The set read through, or 0 for none.
#! @param to The set what is read flows into, or 0 for none.
pub def flow::read(&mut this, from: u32, to: u32): void {
return if from == 0 || to == 0;
var head: u32 = this.reads[from as u64];
this.link(&mut head, to);
this.reads[from as u64] = head;
var at: u32 = this.heads[from as u64];
while at != 0 {
this.into(this.held_by(this.member[at as u64 - 1]), to);
at = this.next[at as u64 - 1];
}
}
#! Has a set flow into what each spot of another holds, as writing through the
#! references that set stands for does. What is written to a spot outside the
#! body is kept.
#! @param this The flows.
#! @param at The set written through, or 0 for none.
#! @param from The set written, or 0 for none.
pub def flow::write(&mut this, at: u32, from: u32): void {
return if at == 0 || from == 0;
var head: u32 = this.writes[at as u64];
this.link(&mut head, from);
this.writes[at as u64] = head;
var each: u32 = this.heads[at as u64];
while each != 0 {
val target: u32 = this.member[each as u64 - 1];
this.into(from, this.outside(target) ? this.kept : this.held_by(target));
each = this.next[each as u64 - 1];
}
}
#! A set of what reading through a set gives.
#! @param this The flows.
#! @param from The set, or 0 for none.
#! @returns The set read, or 0 for none.
pub def flow::read_of(&mut this, from: u32): u32 {
return 0 if from == 0;
val made := this.new_set();
this.read(from, made);
return made;
}
#! A set of what either of two sets holds.
#! @param this The flows.
#! @param a One set, or 0 for none.
#! @param b The other, or 0 for none.
#! @returns The set, or 0 for none.
pub def flow::either(&mut this, a: u32, b: u32): u32 {
return b if a == 0;
return a if b == 0;
val made := this.new_set();
this.into(a, made);
this.into(b, made);
return made;
}
#! Has a set's spots be kept past the body.
#! @param this The flows.
#! @param set The set, or 0 for none.
pub def flow::keep(&mut this, set: u32): void {
this.into(set, this.kept);
}
#! Carries every spot added along the flows of the sets it was added to, until
#! no set grows.
#! @param this The flows.
pub def flow::solve(&mut this): void {
while this.work.length != 0 {
val key: u64 = this.work.last();
this.work.truncate();
val set := pair_high(key);
val at := pair_low(key);
var link: u32 = this.copies[set as u64];
while link != 0 {
this.add(this.member[link as u64 - 1], at);
link = this.next[link as u64 - 1];
}
link = this.reads[set as u64];
while link != 0 {
this.into(this.held_by(at), this.member[link as u64 - 1]);
link = this.next[link as u64 - 1];
}
link = this.writes[set as u64];
while link != 0 {
this.into(this.member[link as u64 - 1], this.outside(at) ? this.kept : this.held_by(at));
link = this.next[link as u64 - 1];
}
}
}
#! Works out how far each spot may outlive the body, once solved: those kept or
#! given back, those held by one that is, and those of the frame held by one
#! that may outlive them.
#! @param this The flows.
pub def flow::settle(&mut this): void {
var todo := vector::<u32>::new();
this.mark_all(this.given, reach::given, &mut todo);
this.mark_all(this.kept, reach::kept, &mut todo);
# A value a statement holds lives only while it runs, and a local only from
# where it is declared on, so one held by what may outlive it is kept.
for h in 0..this.spots.length {
val holder: spot = this.spots[h];
continue if holder.kind != spot_kind::local && holder.kind != spot_kind::env && holder.kind != spot_kind::temp;
var at: u32 = this.heads[holder.held as u64];
while at != 0 {
val held: u32 = this.member[at as u64 - 1];
at = this.next[at as u64 - 1];
val kind: spot_kind = this.spots[held as u64].kind;
val later := (kind == spot_kind::local || kind == spot_kind::env) && holder.kind != spot_kind::temp
&& this.spots[held as u64].node > holder.node;
if (kind == spot_kind::temp && holder.kind != spot_kind::temp) || later {
this.mark(held, reach::kept, &mut todo);
}
}
}
# Whoever holds a spot reaches what it holds.
while todo.length != 0 {
val at: u32 = todo.last();
todo.truncate();
val how: reach = this.spots[at as u64].reach;
var link: u32 = this.heads[this.spots[at as u64].held as u64];
while link != 0 {
this.mark(this.member[link as u64 - 1], how, &mut todo);
link = this.next[link as u64 - 1];
}
}
}
#! Marks each spot of a set as outliving the body at least as far as given.
#! @param this The flows.
#! @param set The set.
#! @param how How far.
#! @param todo The spots whose reach grew, whose held spots are marked next.
def flow::mark_all(&mut this, set: u32, how: reach, todo: &mut vector<u32>): void {
var at: u32 = this.heads[set as u64];
while at != 0 {
this.mark(this.member[at as u64 - 1], how, todo);
at = this.next[at as u64 - 1];
}
}
#! Marks a spot as outliving the body at least as far as given.
#! @param this The flows.
#! @param at The spot.
#! @param how How far.
#! @param todo The spots whose reach grew, whose held spots are marked next.
def flow::mark(&mut this, at: u32, how: reach, todo: &mut vector<u32>): void {
val had: reach = this.spots[at as u64].reach;
return if (had as u8) >= (how as u8);
this.spots[at as u64].reach = how;
todo.append(at);
}
+158
View File
@@ -0,0 +1,158 @@
#! @file globals.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the globals: where each is among them, and `<globals>`, the
#! function the program runs before `main`, which gives each its value in the
#! order they are declared, after those its value reads. A constant is given
#! the value its declaration computes, as the program starts, until constants
#! are evaluated while compiling.
import sakura::analyzer;
module sakura::compiler;
#! Lowers `<globals>`, which gives every global of the program its value.
#! @param this The compiler.
#! @returns The function's index.
pub def lowerer::lower_globals(&mut this): u32 {
val void_type := this.checker.types.function(span::<u32>::empty(), bt::void_type, false);
val index := this.add_function(string::from("<globals>", nothing {}), this.signature_of(void_type));
this.program.functions[index].lowered = true;
this.program.functions[index].queued = true;
var made := emitter::new(this, index);
for id in 1..this.checker.decls.count {
made.lower_global(id as u32);
}
made.build.ret(span::<u32>::empty());
made.finish();
return index;
}
#! Whether a declaration is a global the program holds: a variable or constant
#! outside any function, or declared through a type, that checked.
#! @param this The compiler.
#! @param decl The declaration.
#! @returns Whether it is.
pub def lowerer::is_global(&this, decl: u32): bool {
return this.checker.decls.kinds.p[decl] == dk::variable && !this.checker.decls.has(decl, df::failed)
&& this.checker.decls.nodes.p[decl] != 0;
}
#! Gives a global its value in `<globals>`, after those its value reads.
#! @param this The emitter of `<globals>`.
#! @param decl The global's declaration.
pub def emitter::lower_global(&mut this, decl: u32): void {
return if !this.c.is_global(decl);
# A constant evaluated is held as data instead.
return if this.c.checker.decls.has(decl, df::constant) && this.c.evaluated.values.contains(&decl_key(decl));
return if !this.c.begun_globals.insert(decl);
val file: u32 = this.c.checker.decls.files.p[decl];
val saved := this.c.checker.at;
this.c.checker.use_table(this.c.checker.units[file].table);
this.table = this.c.checker.units[file].table;
val node: u32 = this.c.checker.decls.nodes.p[decl];
val value := this.c.checker.record(node, variable_slot::value);
# The globals its value reads are given theirs first.
if value != 0 {
var reads := vector::<u32>::new();
this.globals_read(value, &mut reads);
for &each in reads {
this.lower_global(each);
this.c.checker.use_table(this.table);
}
this.c.checker.use_table(this.c.checker.units[file].table);
this.table = this.c.checker.units[file].table;
}
this.at_node(node);
val kind: u32 = this.c.checker.decls.types.p[decl];
val mark := this.begin_statement();
val place := this.global_place(decl);
# The globals begin as zeros, so one without a value is only given the
# defaults of its fields, and a `val` of a value known while compiling
# begins with it, so code that runs before `<globals>` gives it, as the
# runtime's does where values are allocated, reads it.
if value == 0 {
this.defaults(&place);
} else if this.refers_to_temporary(value) {
# A value referred to where it is made lives as long as the global bound
# to it, as a global of its own.
val taken := this.c.checker.type_at(value);
val referent := this.c.checker.types.first_of(this.c.checker.unalias(taken));
val made := this.value_as(this.c.checker.left_of(value), referent);
this.adopt(&made);
val offset := this.c.unnamed_global(referent);
val address := this.build.value(op::global, span::<u32>::empty(), vt::word, 0, offset);
val held := location { kind = referent, address = address };
this.store(&held, &made);
val referred := this.reference_to(&held, taken);
val converted := this.convert(&referred, kind);
this.store(&place, &converted);
} else {
val made := this.value_as(value, kind);
this.adopt(&made);
val fixed := !this.c.checker.decls.has(decl, df::mutable);
if !fixed || !this.preset(&place, &made) {
this.store(&place, &made);
}
}
this.end_statement(mark);
this.c.checker.at = saved;
}
#! Gives a global the value it begins with, where that is a number known while
#! compiling, which it then has before any code runs.
#! @param this The emitter of `<globals>`.
#! @param place The global.
#! @param made Its value.
#! @returns Whether it was given, which it is not where the value is not known,
#! or not a number.
def emitter::preset(&mut this, place: &location, made: &operand): bool {
return false if made.count != 1 || made.address != 0 || place.address == 0 || place.offset != 0;
val at: origin = this.build.code.origins[place.address];
val value: origin = this.build.code.origins[made.words[0]];
return false if at.param || value.param || this.build.code.insts[at.from].kind != op::global;
val kind := this.build.code.insts[value.from].kind;
return false if kind != op::iconst && kind != op::fconst;
val bits: u64 = this.build.code.insts[value.from].imm;
val offset: u64 = this.build.code.insts[at.from].imm;
# Only an integer or an `f64` is written as its bytes: an `f32` would be
# narrowed first, so it is left to the store.
val how := this.c.shape_of(place.kind).how;
return false if how == access::bytes || how == access::f32 || how.value_type().lanes();
return false if kind == op::fconst && how != access::f64;
val width := how.width();
if this.c.program.preset.length < offset + width {
this.c.program.preset.resize(offset + width);
}
for i in 0..width {
this.c.program.preset[offset + i] = ((bits >> (8 * i)) & 0xFF) as u8;
}
return true;
}
#! Collects the globals an expression reads, by name.
#! @param this The emitter.
#! @param node The expression.
#! @param reads Where they are collected.
def emitter::globals_read(&mut this, node: u32, reads: &mut vector<u32>): void {
var walk := node_walk::new(node);
while walk.more() {
val at := walk.next();
val kind := this.c.checker.kind_of(at);
if kind == nk::name || kind == nk::path {
val ref := this.c.checker.ref_at(at);
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.is_global(ref) {
reads.append(ref);
}
}
continue if kind == nk::lambda;
walk.enter(this.c.checker.syn(), at);
}
}
+581
View File
@@ -0,0 +1,581 @@
#! @file builder.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the builder, which makes the intermediate code of a function in one
#! pass, as Braun et al.'s "Simple and Efficient Construction of Static Single
#! Assignment Form" does. What lowering calls a variable is written and read
#! by the builder, which finds the value it holds in the block where it is
#! read, or else along the edges into that block, making it a parameter of a
#! block where they join. A block is sealed once every edge into it is known,
#! and a parameter made before then is given its arguments as it is sealed.
#! Parameters that turn out to stand for one value, and blocks nothing reaches,
#! are taken out once the code is finished.
import std::containers;
module sakura::compiler;
#! Builds the code of one function.
pub struct builder {
var code: code; #! What is built.
var at: u32; #! The block instructions are added to.
var pos: u64; #! Where in the source what is added is from: one more than the file, then the byte.
var kinds: vector<vt>; #! The type of each variable.
var defs: dict<u64, u32>; #! The value of each variable in each block, by `pair_key(variable, block)`.
var sealed: vector<bool>; #! Whether each block is sealed.
var waiting: vector<u32>; #! Parameters of blocks not sealed yet, which wait for their arguments.
var held_for: vector<u32>; #! The variable each waiting parameter holds.
var zeros: u32[vt::count as u64]; #! The value of each type a variable has where nothing gave it one, made once.
}
#! Makes a builder of code whose entry takes parameters of the types.
#! @param params The types of the parameters.
#! @returns The builder, adding to the entry, which is sealed, since nothing
#! goes back into it.
pub def builder::new(params: span<vt>): builder {
var made := builder {
code = code::new(),
kinds = vector::<vt>::new(scratch()),
defs = dict::<u64, u32>::new(scratch()),
sealed = vector::<bool>::new(scratch()),
waiting = vector::<u32>::new(scratch()),
held_for = vector::<u32>::new(scratch())
};
made.sealed.append(true);
for &each in params {
made.code.add_param(0, each);
}
return made;
}
#! The value of a parameter of the entry: one the function takes.
#! @param this The builder.
#! @param index Its position.
#! @returns The value.
pub def builder::param(&this, index: u32): u32 {
return this.code.blocks[0].params[index];
}
#! Adds a block, which takes nothing yet and is not sealed.
#! @param this The builder.
#! @returns The block.
pub def builder::new_block(&mut this): u32 {
this.sealed.append(false);
return this.code.add_block();
}
#! Makes instructions be added to the end of a block.
#! @param this The builder.
#! @param block The block.
pub def builder::switch_to(&mut this, block: u32): void {
this.at = block;
}
#! Whether the block instructions are added to has ended, as after a `return`,
#! so what is added now is never reached.
#! @param this The builder.
#! @returns Whether it has.
pub def builder::ended(&this): bool {
val last: u32 = this.code.blocks[this.at].last;
return last != 0 && this.code.insts[last].kind.ends();
}
#! Says every edge into a block is known, giving the parameters it waits with
#! their arguments.
#! @param this The builder.
#! @param block The block.
pub def builder::seal(&mut this, block: u32): void {
return if this.sealed[block];
# Giving one its arguments may make more, which are given theirs in turn, in
# the order the block takes them.
var at: u64 = 0;
while at < this.waiting.length {
val param: u32 = this.waiting[at];
if this.code.origins[param].from == block {
this.fill(this.held_for[at], param, block);
this.waiting.remove_at(at);
this.held_for.remove_at(at);
continue;
}
at++;
}
this.sealed[block] = true;
}
#! Makes a variable of the type, which holds nothing yet.
#! @param this The builder.
#! @param kind Its type.
#! @returns The variable.
pub def builder::variable(&mut this, kind: vt): u32 {
this.kinds.append(kind);
return (this.kinds.length - 1) as u32;
}
#! Gives a variable a value, from where instructions are added on.
#! @param this The builder.
#! @param variable The variable.
#! @param value The value.
pub def builder::assign(&mut this, variable: u32, value: u32): void {
this.defs.set(pair_key(variable, this.at), value);
}
#! The value a variable holds where instructions are added.
#! @param this The builder.
#! @param variable The variable.
#! @returns The value.
pub def builder::read(&mut this, variable: u32): u32 {
return this.read_in(variable, this.at);
}
#! The value a variable holds at the end of a block.
#! @param this The builder.
#! @param variable The variable.
#! @param block The block.
#! @returns The value.
def builder::read_in(&mut this, variable: u32, block: u32): u32 {
val key := pair_key(variable, block);
if this.defs.get(&key) is some(got) {
return got;
}
val kind: vt = this.kinds[variable];
var value: u32 = 0;
val count := this.code.blocks[block].preds.length;
if !this.sealed[block] {
# Edges into it may yet be added, so it takes the value, given later.
value = this.code.add_param(block, kind);
this.waiting.append(value);
this.held_for.append(variable);
} else if count == 0 {
value = this.zero(kind);
} else if count == 1 {
val edge: u32 = this.code.blocks[block].preds[0];
value = this.read_in(variable, this.code.edge_source(edge));
} else {
# Recorded before its arguments are found, which may come back to it.
value = this.code.add_param(block, kind);
this.defs.set(key, value);
this.fill(variable, value, block);
}
this.defs.set(key, value);
return value;
}
#! Gives a parameter of a block the value the variable holds along each edge
#! into the block.
#! @param this The builder.
#! @param variable The variable it holds.
#! @param param The parameter.
#! @param block The block.
def builder::fill(&mut this, variable: u32, param: u32, block: u32): void {
var preds := this.code.blocks[block].preds.copied(scratch());
for &edge in preds {
val given := this.read_in(variable, this.code.edge_source(edge));
this.code.edges[edge].args.append(given);
}
}
#! The value of the type a variable holds where nothing gave it one: zero, made
#! first in the entry, which every block follows.
#! @param this The builder.
#! @param kind The type.
#! @returns The value.
def builder::zero(&mut this, kind: vt): u32 {
val held: u32 = this.zeros[kind as u64];
return held if held != 0;
# Made in the entry, then moved first, so it stands before everything there.
val saved := this.at;
this.at = 0;
val made := kind == vt::real ? op::fconst : kind.lanes() ? op::vzero : op::iconst;
val value := this.value(made, span::<u32>::empty(), kind, 0, 0);
this.at = saved;
val index: u32 = this.code.origins[value].from;
this.unlink(index);
this.code.put_first(0, index);
this.zeros[kind as u64] = value;
return value;
}
#! Takes an instruction out of its block's order, where it is last.
#! @param this The builder.
#! @param index The instruction.
def builder::unlink(&mut this, index: u32): void {
val block: u32 = this.code.insts[index].block;
val before := this.code.before(index);
val after: u32 = this.code.insts[index].next;
if before == 0 {
this.code.blocks[block].first = after;
} else {
this.code.insts[before].next = after;
}
if this.code.blocks[block].last == index {
this.code.blocks[block].last = before;
}
this.code.insts[index].next = 0;
}
#! Adds an instruction, in a block of its own where the block it would be added
#! to has ended, since nothing reaches it there.
#! @param this The builder.
#! @param kind What it does.
#! @param args Its operands.
#! @param gives The types of its results.
#! @param aux What its kind says `aux` holds.
#! @param imm What its kind says `imm` holds.
#! @returns The instruction.
pub def builder::emit(&mut this, kind: op, args: span<u32>, gives: span<vt>, aux: u32, imm: u64): u32 {
if this.ended() {
val unreached := this.new_block();
this.seal(unreached);
this.at = unreached;
}
return this.code.append(this.at, kind, args, gives, aux, imm, this.pos);
}
#! Adds an instruction giving one value.
#! @param this The builder.
#! @param kind What it does.
#! @param args Its operands.
#! @param give The type of what it gives.
#! @param aux What its kind says `aux` holds.
#! @param imm What its kind says `imm` holds.
#! @returns The value it gives.
pub def builder::value(&mut this, kind: op, args: span<u32>, give: vt, aux: u32, imm: u64): u32 {
var gives: vt[1] = [give];
val index := this.emit(kind, args, gives[0:1], aux, imm);
return this.code.insts[index].result;
}
#! Adds an instruction giving nothing.
#! @param this The builder.
#! @param kind What it does.
#! @param args Its operands.
#! @param aux What its kind says `aux` holds.
#! @param imm What its kind says `imm` holds.
#! @returns The instruction.
pub def builder::effect(&mut this, kind: op, args: span<u32>, aux: u32, imm: u64): u32 {
return this.emit(kind, args, span::<vt>::empty(), aux, imm);
}
#! A word.
#! @param this The builder.
#! @param bits Its bits.
#! @returns The value.
pub def builder::word(&mut this, bits: u64): u32 {
return this.value(op::iconst, span::<u32>::empty(), vt::word, 0, bits);
}
#! A real.
#! @param this The builder.
#! @param bits The bits of the `f64` it is.
#! @returns The value.
pub def builder::real(&mut this, bits: u64): u32 {
return this.value(op::fconst, span::<u32>::empty(), vt::real, 0, bits);
}
#! An operator of two values.
#! @param this The builder.
#! @param kind The operator.
#! @param a The first operand.
#! @param b The second operand.
#! @returns What it gives: a real for arithmetic of reals, and otherwise a word.
pub def builder::binary(&mut this, kind: op, a: u32, b: u32): u32 {
var args: u32[2] = [a, b];
val gives := kind == op::fadd || kind == op::fsub || kind == op::fmul || kind == op::fdiv || kind == op::frem
? vt::real : vt::word;
return this.value(kind, args[0:2], gives, 0, 0);
}
#! An operator of one value.
#! @param this The builder.
#! @param kind The operator.
#! @param a The operand.
#! @returns What it gives: a real where it gives one, and otherwise a word.
pub def builder::unary(&mut this, kind: op, a: u32): u32 {
var args: u32[1] = [a];
val gives := kind == op::fneg || kind == op::itof || kind == op::utof || kind == op::fsingle || kind == op::fsqrt
? vt::real : vt::word;
return this.value(kind, args[0:1], gives, 0, 0);
}
#! A word narrowed to a number of bits.
#! @param this The builder.
#! @param a The word.
#! @param bits How many bits it keeps.
#! @param signed Whether it is sign-extended rather than zero-extended.
#! @returns The word narrowed.
pub def builder::wrap(&mut this, a: u32, bits: u32, signed: bool): u32 {
var args: u32[1] = [a];
return this.value(op::wrap, args[0:1], vt::word, bits, signed ? 1 : 0);
}
#! The address of a cell.
#! @param this The builder.
#! @param index The cell.
#! @returns The address.
pub def builder::cell_address(&mut this, index: u32): u32 {
return this.value(op::cell, span::<u32>::empty(), vt::word, index, 0);
}
#! Reads a value from memory.
#! @param this The builder.
#! @param how How it is read.
#! @param address The address.
#! @param offset How many bytes past the address it is.
#! @returns The value, a real for a float, a vector for lanes, and a word
#! otherwise.
pub def builder::load(&mut this, how: access, address: u32, offset: u64): u32 {
var args: u32[1] = [address];
return this.value(op::load, args[0:1], how.value_type(), how as u32, offset);
}
#! Writes a value to memory.
#! @param this The builder.
#! @param how How it is written.
#! @param address The address.
#! @param offset How many bytes past the address it goes.
#! @param value The value.
pub def builder::store(&mut this, how: access, address: u32, offset: u64, value: u32): void {
var args: u32[2] = [address, value];
this.effect(op::store, args[0:2], how as u32, offset);
}
#! Copies bytes from one address to another.
#! @param this The builder.
#! @param to Where they go.
#! @param from Where they come from.
#! @param size How many there are.
pub def builder::copy(&mut this, to: u32, from: u32, size: u64): void {
return if size == 0;
var args: u32[2] = [to, from];
this.effect(op::copy, args[0:2], 0, size);
}
#! Zeroes bytes from an address.
#! @param this The builder.
#! @param address The address.
#! @param size How many there are.
pub def builder::clear(&mut this, address: u32, size: u64): void {
return if size == 0;
var args: u32[1] = [address];
this.effect(op::clear, args[0:1], 0, size);
}
#! Marks bytes at an address as never written, running with memory checked.
#! @param this The builder.
#! @param address The address.
#! @param size How many bytes.
pub def builder::forget(&mut this, address: u32, size: u64): void {
return if size == 0;
var args: u32[1] = [address];
this.effect(op::forget, args[0:1], 0, size);
}
#! Stops the program with an error where a word is zero.
#! @param this The builder.
#! @param cond The word.
#! @param error The error, as the machine numbers them.
pub def builder::check(&mut this, cond: u32, error: u32): void {
var args: u32[1] = [cond];
this.effect(op::check, args[0:1], error, 0);
}
#! Ends the block going to another.
#! @param this The builder.
#! @param target The block.
pub def builder::jump(&mut this, target: u32): void {
return if this.ended();
val index := this.effect(op::jump, span::<u32>::empty(), 0, 0);
this.code.insts[index].aux = this.code.add_edge(index, target, 0);
}
#! Ends the block going to one block where a word is not zero, and another
#! where it is.
#! @param this The builder.
#! @param cond The word.
#! @param then Where it goes where the word is not zero.
#! @param other Where it goes where it is.
pub def builder::branch(&mut this, cond: u32, then: u32, other: u32): void {
return if this.ended();
var args: u32[1] = [cond];
val index := this.effect(op::branch, args[0:1], 0, 0);
this.code.insts[index].aux = this.code.add_edge(index, then, 0);
this.code.add_edge(index, other, 0);
}
#! Ends the block returning words, or the memory at an address.
#! @param this The builder.
#! @param args The words, or the address.
pub def builder::ret(&mut this, args: span<u32>): void {
return if this.ended();
this.effect(op::ret, args, 0, 0);
}
#! Ends the block stopping the program with an error.
#! @param this The builder.
#! @param error The error, as the machine numbers them.
pub def builder::trap(&mut this, error: u32): void {
return if this.ended();
this.effect(op::trap, span::<u32>::empty(), error, 0);
}
#! Ends the block as one nothing goes on from, as after a call that never
#! returns.
#! @param this The builder.
pub def builder::unreachable(&mut this): void {
return if this.ended();
this.effect(op::unreachable, span::<u32>::empty(), 0, 0);
}
#! Finishes the code: seals what is not sealed, takes out the blocks nothing
#! reaches and the parameters standing for one value, and gives the code.
#! @param this The builder.
#! @returns The code.
pub def builder::finish(&mut this): code {
# A block left open, as one control falls off the end of, ends unreached.
for i in 0..this.code.blocks.length {
this.at = i as u32;
if !this.ended() {
this.unreachable();
}
this.seal(i as u32);
}
this.code.prune();
return move(&mut this.code);
}
#! Takes out the blocks the entry does not reach, and the parameters that stand
#! for one value, being given it, or themselves, along every edge, so each use
#! of one uses that value instead.
#! @param this The code.
pub def code::prune(&mut this): void {
this.forget_order();
this.drop_unreached();
this.drop_lone_params();
}
#! Takes out the parameters that stand for one value, being given it, or
#! themselves, along every edge, so each use of one uses that value instead.
#! @param this The code.
pub def code::drop_lone_params(&mut this): void {
return if !this.has_lone_param();
# What each parameter taken out stands for, followed until one that is not.
var aliases := vector::<u32>::new(scratch());
aliases.resize(this.origins.length);
val links := aliases.view().data;
val count := aliases.length;
var changed := true;
while changed {
changed = false;
for b in 1..this.blocks.length {
continue if this.blocks[b].gone;
for p in 0..this.blocks[b].params.length {
val param: u32 = this.blocks[b].params[p];
continue if aliases[param] != 0;
var only: u32 = 0;
var many := false;
for &edge in this.blocks[b].preds {
val given := follow_replaced(links, count, this.edges[edge].args[p]);
continue if given == param || given == only;
if only != 0 {
many = true;
break;
}
only = given;
}
continue if many || only == 0;
aliases[param] = only;
changed = true;
}
}
}
# Each use reads what it stands for, and each edge gives only the parameters
# left.
for i in 0..this.operands.length {
this.operands[i] = follow_replaced(links, count, this.operands[i]);
}
var keeps := vector::<bool>::new(scratch());
for b in 0..this.blocks.length {
continue if this.blocks[b].gone;
for &edge in this.blocks[b].preds.view() {
var args := this.edges[edge].args.slice();
for p in 0..args.length {
args[p] = follow_replaced(links, count, args[p]);
}
}
keeps.clear();
for &param in this.blocks[b].params.view() {
keeps.append(aliases[param] == 0);
}
if keeps.view().contains(&false) {
this.drop_params(b as u32, keeps.view());
}
}
}
#! Whether a block takes a parameter every edge into it gives one value, or
#! itself, which pruning takes out.
#! @param this The code.
#! @returns Whether one does.
def code::has_lone_param(&this): bool {
for b in 1..this.blocks.length {
continue if this.blocks[b].gone;
for p in 0..this.blocks[b].params.length {
val param: u32 = this.blocks[b].params[p];
var only: u32 = 0;
var many := false;
for &edge in this.blocks[b].preds {
val given: u32 = this.edges[edge].args[p];
continue if given == param || given == only;
if only != 0 {
many = true;
break;
}
only = given;
}
return true if !many;
}
}
return false;
}
#! Marks the blocks the entry does not reach as gone, and takes their edges out
#! of the blocks they went to. Those it reaches are the blocks of their order,
#! worked out where the code does not keep it, and kept, as what comes after
#! asks it.
#! @param this The code.
pub def code::drop_unreached(&mut this): void {
this.keep_order();
# Only the blocks a block newly gone went to lose edges.
var touched := vector::<u32>::new(scratch());
for b in 0..this.blocks.length {
continue if this.kept_number[b] != 0xFFFFFFFF || this.blocks[b].gone;
this.blocks[b].gone = true;
val last: u32 = this.blocks[b].last;
continue if last == 0;
val first: u32 = this.insts[last].aux;
for e in 0..this.edge_count(last) {
touched.append(this.edges[first + e as u32].target);
}
}
for &b in touched {
continue if this.kept_number[b] == 0xFFFFFFFF;
var kept := ids {};
for &edge in this.blocks[b].preds {
if this.kept_number[this.edge_source(edge)] != 0xFFFFFFFF {
kept.append(edge);
}
}
this.blocks[b].preds = move(&mut kept);
}
}
+205
View File
@@ -0,0 +1,205 @@
#! @file cells.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains which cells of a function's frame are zeroed as it begins, by an
#! executable's prologue and by the machine alike. The code reads a cell as
#! zeroed where nothing wrote it yet, so a cell is zeroed as the function
#! begins unless every word of it some path reads is written first on every
#! path to the read. A cell whose address is given anywhere but to reading,
#! writing, copying, and clearing it at offsets the code knows may be read
#! anywhere from there on, so where it is given is a read of every word of it:
#! a cell written whole before its address goes anywhere is not zeroed, as
#! one a statement makes before handing it to a call. A call writing what it
#! returns to a cell, at the address its last operand gives, writes it whole.
module sakura::compiler;
#! The most words of a cell the analysis follows; a larger one is zeroed.
const followed_words: u64 = 64;
#! Finds which cells a function's prologue zeroes.
#! @param body The code.
#! @param order Its blocks, in reverse postorder.
#! @param number Each block's place in that order.
#! @param writes Of each instruction, the bytes a call writes what it
#! returns to at its last operand, or 0, as `result_writes`
#! gives them.
#! @returns Whether each cell is zeroed.
pub def zeroed_cells(body: &code, order: span<u32>, number: span<u32>, writes: span<u64>): vector<bool> {
val cells := body.cells.length;
var zeroed := vector::<bool>::new(scratch());
zeroed.resize(cells);
return zeroed if cells == 0;
# A cell too large to follow is zeroed.
for c in 0..cells {
if (body.cells[c].size as u64 + 7) / 8 > followed_words {
zeroed[c] = true;
}
}
val addresses := body.cell_table();
var reads := body.reader();
# The words written for sure where each block ends, by cell, a word a bit,
# until they no longer change; each starts as every word, but at the entry.
var outs := vector::<u64>::new(scratch());
outs.resize(body.blocks.length * cells, 0xFFFFFFFFFFFFFFFF);
var state := vector::<u64>::new(scratch());
state.resize(cells);
var changed := true;
var rounds := 0;
while changed && rounds < 64 {
changed = false;
rounds++;
for k in 0..order.length {
val block: u32 = order[k];
for c in 0..cells {
state[c] = block == 0 ? 0 : 0xFFFFFFFFFFFFFFFF;
}
for p in 0..body.blocks[block].preds.length {
val from := body.edge_source(body.blocks[block].preds[p]);
continue if number[from] == 0xFFFFFFFF;
for c in 0..cells {
state[c] = state[c] & outs[from as u64 * cells + c];
}
}
walk_block(body, block, &addresses, &mut reads, writes, &mut state, &mut zeroed);
for c in 0..cells {
val at := block as u64 * cells + c;
if outs[at] != state[c] {
outs[at] = state[c];
changed = true;
}
}
}
}
if changed {
for c in 0..cells {
zeroed[c] = true;
}
}
return zeroed;
}
#! The bits of the words a run of bytes covers wholly, from the first word.
#! @param offset Where the run begins.
#! @param size How many bytes it takes.
#! @returns The bits.
def cell_words_whole(offset: u64, size: u64): u64 {
val first := (offset + 7) / 8;
val end := (offset + size) / 8;
return 0 if end <= first || first >= 64;
return bits_between(first, end > 64 ? 64 : end);
}
#! The bits of the words a run of bytes touches, from the first word.
#! @param offset Where the run begins.
#! @param size How many bytes it takes.
#! @returns The bits.
def cell_words_touched(offset: u64, size: u64): u64 {
return 0 if size == 0;
val first := offset / 8;
val end := (offset + size + 7) / 8;
return 0 if first >= 64;
return bits_between(first, end > 64 ? 64 : end);
}
#! The bits from one up to another.
#! @param from The first bit.
#! @param to Past the last, at most 64.
#! @returns The bits.
def bits_between(from: u64, to: u64): u64 {
val high := to >= 64 ? 0xFFFFFFFFFFFFFFFF : (1u << to) - 1;
val low := (1u << from) - 1;
return high & ~low;
}
#! Walks a block's instructions, from what is written for sure where it begins
#! to where it ends, noting each cell a read finds a word of not yet written.
#! @param body The code.
#! @param block The block.
#! @param addresses Which cell each value is the address of.
#! @param reads A walk of what the code's instructions read.
#! @param writes Of each instruction, the bytes a call writes what it
#! returns to at its last operand, or 0.
#! @param state What is written of each cell, a word a bit.
#! @param zeroed Whether each cell is zeroed.
def walk_block(
body: &code,
block: u32,
addresses: &cell_table,
reads: &mut read_walk,
writes: span<u64>,
state: &mut vector<u64>,
zeroed: &mut vector<bool>
): void {
var walk := body.walk(block);
while walk.more() {
val at := walk.next();
val held: inst = body.insts[at];
# A cell's address given anywhere but to the reads and writes below, and
# to where a call writes what it returns, may be read anywhere from here,
# as an edge's argument always may be, so every word of the cell is read
# here.
val returned: u64 = (at as u64) < writes.length ? writes[at] : 0;
var written: u32 = 0;
reads.start(at);
while reads.more() {
val cell := addresses.cell(reads.next());
continue if cell == 0;
val a := reads.operand();
val known := a != no_operand && match held.kind {
op::load, op::clear, op::store => a == 0,
op::copy => a < 2,
else => false
};
continue if known;
if a != no_operand && returned != 0 && a + 1 == held.argc {
written = cell;
continue;
}
if (cell_words_touched(0, body.cells[cell - 1].size as u64) & ~state[cell - 1]) != 0 {
zeroed[cell - 1] = true;
}
}
if written != 0 {
state[written - 1] = state[written - 1] | cell_words_whole(0, returned);
}
match held.kind {
op::load => {
val cell := addresses.cell(body.operands[held.args as u64]);
continue if cell == 0;
val read := cell_words_touched(held.imm, (held.aux as access).width());
if (read & ~state[cell - 1]) != 0 {
zeroed[cell - 1] = true;
}
}
op::store => {
val cell := addresses.cell(body.operands[held.args as u64]);
continue if cell == 0;
state[cell - 1] = state[cell - 1] | cell_words_whole(held.imm, (held.aux as access).width());
}
op::clear => {
val cell := addresses.cell(body.operands[held.args as u64]);
continue if cell == 0;
state[cell - 1] = state[cell - 1] | cell_words_whole(0, held.imm);
}
op::copy => {
val from := addresses.cell(body.operands[held.args as u64 + 1]);
if from != 0 && (cell_words_touched(0, held.imm) & ~state[from - 1]) != 0 {
zeroed[from - 1] = true;
}
val to := addresses.cell(body.operands[held.args as u64]);
if to != 0 {
state[to - 1] = state[to - 1] | cell_words_whole(0, held.imm);
}
}
else => {}
}
}
}
+677
View File
@@ -0,0 +1,677 @@
#! @file code.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the intermediate code of a function: values each assigned once,
#! the instructions giving them, the blocks holding the instructions, and the
#! cells of the frame that what is too large to be a value, or whose address is
#! taken, lives in. Where control flow joins, values arrive as the parameters
#! of a block, which each jump into it gives arguments for.
#!
#! A value is a word: an integer, which every integer type, `bool`, enum, and
#! pointer is held as, widened as a frame holds it, or a float, which an `f32`
#! is held as rounded to its precision. A reference is one value, its address,
#! and a reference to a trait or a function two. Structs,
#! unions, and fixed arrays live in cells or on the heap, and are read and
#! written through their addresses. An executable also has vectors, 16 or 32
#! bytes of lanes, which a cell holding a `simd` becomes where promoted.
module sakura::compiler;
#! The type of a value.
pub enum vt : u8 {
none, #! No value.
word, #! A 64-bit integer, which every integer type, `bool`, enum, and pointer is held as.
real, #! A 64-bit float, which an `f32` is held as.
v128, #! 16 bytes of lanes, which only an executable holds.
v256, #! 32 bytes of lanes, which only code for processors with AVX holds.
v512, #! 64 bytes of lanes, which only an executable holds, in memory, working them with AVX-512 where the processor has it.
count, #! How many types there are, which sizes the tables of them; not a type itself.
}
#! What an instruction does. Each says what its operands are, what its `aux`
#! and `imm` hold, and what it gives. Operators of integers take and give words,
#! and those of floats reals, but for comparisons, which give a word of 0 or 1.
pub enum op : u8 {
# Constants.
iconst, #! A word: `imm` is its bits.
fconst, #! A real: `imm` is its bits.
# Operators of two words, giving a word.
add, #! `a + b`, wrapping at 64 bits.
sub, #! `a - b`.
mul, #! `a * b`.
divs, #! `a / b` of signed words, stopping where `b` is zero.
divu, #! `a / b` of unsigned words, stopping where `b` is zero.
rems, #! What is left dividing signed words, stopping where `b` is zero.
remu, #! What is left dividing unsigned words, stopping where `b` is zero.
band, #! `a & b`.
bor, #! `a | b`.
bxor, #! `a ^ b`.
shl, #! `a << b`.
shrs, #! `a >> b`, keeping the sign.
shru, #! `a >> b`, filling with zeros.
eq, #! `a == b`.
ne, #! `a != b`.
lts, #! `a < b`, signed.
ltu, #! `a < b`, unsigned.
les, #! `a <= b`, signed.
leu, #! `a <= b`, unsigned.
eqsu, #! `a == b`, where `a` is signed and `b` unsigned, compared as the numbers they are.
ltsu, #! `a < b`, where `a` is signed and `b` unsigned.
lesu, #! `a <= b`, where `a` is signed and `b` unsigned.
ltus, #! `a < b`, where `a` is unsigned and `b` signed.
leus, #! `a <= b`, where `a` is unsigned and `b` signed.
# Operators of two reals.
fadd, #! `a + b`, giving a real.
fsub, #! `a - b`, giving a real.
fmul, #! `a * b`, giving a real.
fdiv, #! `a / b`, giving a real.
frem, #! What is left dividing, whose sign is the dividend's, giving a real.
feq, #! `a == b`, giving a word.
fne, #! `a != b`, giving a word.
flt, #! `a < b`, giving a word.
fle, #! `a <= b`, giving a word.
# Operators of one value.
neg, #! `-a` of a word.
bnot, #! `~a` of a word.
lnot, #! 1 where the word is zero, and 0 otherwise.
fneg, #! `-a` of a real.
itof, #! The real a signed word is.
utof, #! The real an unsigned word is.
ftoi, #! The signed word a real is, toward zero, saturating.
ftou, #! The unsigned word a real is, toward zero, saturating.
fsingle, #! The real rounded to the precision of an `f32`.
fsqrt, #! The square root of a real, rounded once.
ones, #! How many bits of the word are 1.
clz, #! How many 0 bits lead the word from its top, 64 where it is zero.
ctz, #! How many 0 bits trail the word from its bottom, 64 where it is zero.
bswap, #! The word with its bytes in the reverse order.
wrap, #! The word narrowed to `aux` bits, sign-extended where `imm` is 1 and zero-extended otherwise.
# Choosing.
select, #! (condition, a, b): `a` where the word is not zero, and `b` where it is, both words or both reals.
# Addresses.
cell, #! The address of the cell `aux`.
global, #! The address `imm` bytes into the globals.
datum, #! The address `imm` bytes into the bytes of datum `aux`, which are never written.
# Memory, `imm` bytes from an address.
load, #! (address): the value there, read as access `aux` says.
store, #! (address, value): writes the value there, as access `aux` says.
copy, #! (to, from): copies `imm` bytes.
clear, #! (address): zeroes `imm` bytes.
forget, #! (address): running with its memory checked, marks `imm` bytes as never written, so reading one before writing it stops the program; elsewhere nothing.
# Memory the program holds.
allocate, #! (size): zeroed memory the program gives back itself, or with aux 1 memory not cleared.
release, #! (address): gives memory back.
resize, #! (address, size): memory holding what the address's did.
# Calls, whose results are the words the callee returns, followed, where it
# returns memory, by an operand giving the address it is written to.
call, #! (arguments...): calls function `aux`.
call_trait, #! (pointer, vtable, arguments...): calls slot `imm` of the vtable, by signature `aux`.
call_value, #! (function, environment, arguments...): calls a function value, by signature `aux`.
call_c, #! (address, arguments...): calls a C function, by signature `aux`.
c_address, #! The address of the C function `aux` names.
callback, #! The address C calls function `aux` through.
# Values the runtime works with.
equal, #! (a, b): 1 where the values at the addresses of layout `aux` are equal.
retrait, #! (vtable): the vtable map `aux` gives, as a trait reference becomes another.
check, #! (condition): stops the program with error `aux` where the word is zero.
# The system.
syscall, #! (number, a, b, c, d, e, f): what the kernel gives.
frame, #! The frame pointer, in an executable.
image, #! The image an executable was built with.
environ, #! Where the system put the variables the program started with.
signals, #! The signals that came since last asked, one bit each.
catch, #! (number): has the backend note the signal, giving 0 or the negated error.
safepoint, #! Calls function `aux` where a signal the program handles has come.
exit, #! (code): ends the program with the status, having run everything asked of it.
abort, #! Ends the program at once, reporting where it was.
fault, #! (pointer, length): ends the program at once, reporting the text and where it was.
# Formatting text, which `format` begins and `format_owned` takes.
format, #! Begins text.
format_text, #! Adds the bytes of datum `aux`.
format_value, #! (value...): adds a value of layout `aux`, its words, or the address of its memory.
format_bytes, #! (pointer, length): adds the bytes.
format_owned, #! The text made, as two words: its pointer and length, in memory the program gives back.
# Checks only a program evaluating constants makes.
ready, #! Stops unless the constant evaluation `aux` computes is evaluated.
reach, #! (pointer, count): stops unless that many elements of `imm` bytes from the pointer are memory the program holds.
same, #! (a, b): stops unless the pointers are within the same memory.
# Vector instructions, which only an executable works.
cpu, #! The instruction sets of the processor running the executable, one bit each, as it found them when it started; `imm` those known to be among them.
lanes, #! (a, b, c...): operation `aux` on lanes, of type `imm & 0xFF` and `imm >> 8` bytes in all, giving a vector, or the word of a mask's bits.
vzero, #! A vector of zero bytes.
# Atomics, which several threads, or a thread and a signal handler, read and
# write without a lock. Each touches all memory, as a call does, so no load or
# store moves across one.
atomic, #! (address, operands..., orders...): operation `aux`, as `atomic_` numbers them, of access `imm`, giving what the address held.
# Threads.
start, #! (function, environment): starts a thread running the function value, giving its number or the negated error.
current, #! The running thread's record, in an executable.
clone, #! (record): starts a thread of the system on the record's stacks, running `runtime::thread_main`, in an executable.
# Ends of blocks.
jump, #! Goes to edge `aux`.
branch, #! (condition): goes to edge `aux` where the word is not zero, and edge `aux + 1` where it is.
switch, #! (word): goes to the edge from `aux` whose case is the word, of `imm` edges, the last being the default.
ret, #! (words..., address): returns the words, or the memory at the address.
trap, #! Stops the program with error `aux`, or with the error a word it takes says.
unreachable, #! Is never reached.
count, #! How many operations there are, which sizes the tables of them; not an operation itself.
}
#! How a value is read from memory or written to it, as the program's layouts
#! give it, in the order of the C machine's `access`.
pub enum access : u8 {
i8, #! A signed byte.
u8, #! An unsigned byte.
i16, #! A signed 16-bit integer.
u16, #! An unsigned 16-bit integer.
i32, #! A signed 32-bit integer.
u32, #! An unsigned 32-bit integer.
i64, #! A 64-bit integer.
f32, #! An `f32`, read as a real.
f64, #! An `f64`.
bytes, #! No word: what is copied as bytes.
v128, #! 16 bytes of lanes, read as a vector.
v256, #! 32 bytes of lanes, read as a vector.
v512, #! 64 bytes of lanes, read as a vector.
}
#! The errors code stops a program with, numbered as the machine numbers them.
pub enum fault : u32 {
out_of_bounds = 4, #! An index past the end, or a slice outside what it slices.
null_reference = 5, #! Reaching through a null pointer.
division = 6, #! Dividing by zero.
not_held = 7, #! Reading a field of a union holding another.
unreachable = 9, #! Reaching the end of a function that returns a value.
not_member = 13, #! Converting an integer to an enum none of whose members has its value.
not_constant = 15, #! Running, while compiling, what only the program running can.
}
#! The addresses below which a program holds no memory: the first page, which no
#! system maps. The machine stops at a read or a write there as at null, and an
#! executable faults there, whether the address is null or some way past it, as
#! an element of a null pointer is, so neither compares a pointer with null
#! before reaching through it where what it reaches stays within the page.
pub const null_page: u64 = 4096;
#! An instruction.
pub struct inst {
pub var kind: op; #! What it does.
pub var count: u8; #! How many results it gives.
pub var aux: u32; #! What its kind says: a cell, a function, a layout, an edge.
pub var imm: u64; #! What its kind says: bits, an offset, a size.
pub var args: u32; #! Where its operands begin in `operands`.
pub var argc: u32; #! How many operands it takes.
pub var result: u32; #! Its first result, the others following it.
pub var block: u32; #! The block holding it.
pub var next: u32; #! The next instruction of its block, or 0.
pub var at: u64; #! Where in the source it is from: one more than the file, then the byte.
pub var site: u32; #! One more than the site of the function it was inlined from, or 0 for the function's own.
}
#! Where a function's code was put within another's, which called it there.
#! A trace names it as a frame of its own, as though it were called.
pub struct inline_site {
pub var function: u32; #! The function inlined.
pub var at: u64; #! Where it was called: one more than the file, then the byte.
pub var parent: u32; #! One more than the site the call was within, or 0 for the function's own code.
}
#! Where a value comes from: the instruction giving it, as one of its results,
#! or the block taking it, as one of its parameters.
pub struct origin {
pub var kind: vt; #! Its type.
pub var param: bool; #! Whether a block takes it.
pub var from: u32; #! The instruction or block.
pub var index: u32; #! Which of its results or parameters it is.
}
#! A block: instructions in order, the last of which ends it.
pub struct block {
pub var first: u32; #! Its first instruction, or 0.
pub var last: u32; #! Its last instruction, or 0.
pub var params: ids; #! The values it takes.
pub var preds: ids; #! The edges into it.
pub var gone: bool; #! Whether it was removed, as unreachable.
}
#! A way out of a block into another, with the arguments it gives the other's
#! parameters.
pub struct edge {
var from: u32; #! The instruction it leaves by.
pub var target: u32; #! The block it goes to.
pub var args: ids; #! The values it gives the block's parameters.
pub var case: u64; #! Of a `switch`, the word it goes on.
}
#! The kinds of cell.
pub enum ck : u8 {
temporary, #! What a statement holds while it runs.
local, #! A variable, for the scope it is declared in.
param, #! A parameter taken as memory, whose address the entry block takes.
inlined, #! A cell of a function inlined, which its code clears or copies into where it begins, so the frame does not zero it.
undefined, #! A variable declared `= undefined`, which nothing zeroes, where it is declared or where its function is inlined.
}
#! A cell of the frame.
pub struct cell {
pub var size: u32; #! How many bytes it holds.
pub var align: u32; #! What its address is a multiple of.
pub var kind: ck; #! What it holds.
var name: u32; #! The ID of the name of the variable it holds, or 0.
}
#! A variable debugging information shows: a named local or parameter, and
#! where it is. Code lowered with its locals kept in cells holds each in
#! memory, with the instructions its scope covers. Optimized code holds a local
#! of words in values instead, which the code's bindings name.
pub struct variable_info {
pub var name: u32; #! The ID of its name.
pub var at: u64; #! Where it is declared: one more than the file, then the byte.
pub var kind: u32; #! Its type.
pub var layout: u32; #! Its layout, worked out once the program's are written, so noting it makes none.
pub var cell: u32; #! One more than the cell holding it, or 0 where it is a parameter given as memory.
pub var given: u32; #! Of a parameter given as memory, one more than which of the code's parameters is its address, or 0.
pub var param: bool; #! Whether it is a parameter.
pub var boxed: bool; #! Whether it is in an object of the heap: whose address its cell holds, or its binding names.
pub var held: bool; #! Whether it is held in values, which the code's bindings name.
pub var site: u32; #! One more than the inline site it was declared in, or 0 for the function's own.
pub var first: u32; #! How many instructions the code had where its scope begins.
pub var end: u32; #! How many it had where its scope ends, or 0 where it lasts to the end.
}
#! A value a variable held in values takes: from where it was given the value
#! on, it is that word of the variable, until another value is. Where the value
#! was a constant whose instruction went, the binding keeps the constant in its
#! place, as a constant is known anywhere.
pub struct binding {
pub var variable: u32; #! The variable, among the code's.
pub var word: u32; #! Which of its words.
pub var value: u32; #! The value, or 0 where it keeps a constant.
pub var after: u32; #! The instruction it was given the value after, or 0 where it was where its block begins.
pub var block: u32; #! The block it was given the value in, or `no_block` where that went.
pub var known: vt; #! The type of the constant it keeps, or `none` where it names a value.
pub var bits: u64; #! The constant's bits.
}
#! The intermediate code of one function. Instruction 0 and value 0 stand for
#! none, and block 0 is the entry, whose parameters are the function's.
pub struct code {
pub var insts: vector<inst>; #! The instructions, by index.
pub var operands: vector<u32>; #! The values the instructions take, as runs `args` and `argc` give.
pub var origins: vector<origin>; #! Where each value comes from, by index.
pub var blocks: vector<block>; #! The blocks, by index.
pub var edges: vector<edge>; #! The ways between them, by index.
pub var cells: vector<cell>; #! The cells of the frame, by index.
var results: vector<vt>; #! The words it returns.
pub var returned: u32; #! The bytes of the memory it returns, or 0 where it returns words.
pub var sites: vector<inline_site>; #! Where the functions inlined into it were called, which instructions name.
pub var variables: vector<variable_info>; #! Its variables, which debugging information shows.
pub var bindings: vector<binding>; #! The values its variables held in values take.
pub var vectors: bool; #! Whether it is an executable's, which may hold 16 bytes of lanes as values.
pub var wide: bool; #! Whether it runs only where the processor has AVX, so 32 bytes of lanes may be held as values.
var kept_order: vector<u32>; #! The blocks in reverse postorder, as last worked out, where `order_kept` says it holds.
var kept_number: vector<u32>; #! Each block's place in `kept_order`, or `0xFFFFFFFF` for one the entry does not reach.
var kept_idom: vector<u32>; #! Each block's immediate dominator, as last worked out, where `idom_kept` says it holds.
var order_kept: bool; #! Whether `kept_order` and `kept_number` hold for the blocks as they are.
var idom_kept: bool; #! Whether `kept_idom` holds for the blocks as they are.
}
#! Makes code of one empty block, the entry.
#! @returns The code.
pub def code::new(): code {
var made := code {
insts = vector::<inst>::new(),
operands = vector::<u32>::new(),
origins = vector::<origin>::new(),
blocks = vector::<block>::new(),
edges = vector::<edge>::new(),
cells = vector::<cell>::new(),
results = vector::<vt>::new(),
sites = vector::<inline_site>::new(),
variables = vector::<variable_info>::new(),
bindings = vector::<binding>::new(),
kept_order = vector::<u32>::new(),
kept_number = vector::<u32>::new(),
kept_idom = vector::<u32>::new()
};
made.insts.append(inst {});
made.origins.append(origin {});
made.add_block();
return made;
}
#! Adds a block, taking nothing yet.
#! @param this The code.
#! @returns Its index.
pub def code::add_block(&mut this): u32 {
this.blocks.append(block {});
return (this.blocks.length - 1) as u32;
}
#! Adds a parameter to a block.
#! @param this The code.
#! @param at The block.
#! @param kind The parameter's type.
#! @returns The value it is.
pub def code::add_param(&mut this, at: u32, kind: vt): u32 {
val value := this.origins.length as u32;
val index := this.blocks[at].params.length as u32;
this.origins.append(origin { kind = kind, param = true, from = at, index = index });
this.blocks[at].params.append(value);
return value;
}
#! Adds a cell to the frame.
#! @param this The code.
#! @param size How many bytes it holds.
#! @param align What its address is a multiple of.
#! @param kind What it holds.
#! @param name The ID of its variable's name, or 0.
#! @returns Its index.
pub def code::add_cell(&mut this, size: u32, align: u32, kind: ck, name: u32): u32 {
this.cells.append(cell { size = size, align = align == 0 ? 1 : align, kind = kind, name = name });
return (this.cells.length - 1) as u32;
}
#! Appends an instruction to the end of a block, with its operands and the
#! values it gives.
#! @param this The code.
#! @param at The block.
#! @param kind What it does.
#! @param args Its operands.
#! @param gives The types of its results, in order.
#! @param aux What its kind says `aux` holds.
#! @param imm What its kind says `imm` holds.
#! @param pos Where in the source it is from: one more than the file, then
#! the byte.
#! @returns Its index.
pub def code::append(
&mut this,
at: u32,
kind: op,
args: span<u32>,
gives: span<vt>,
aux: u32,
imm: u64,
pos: u64
): u32 {
val index := this.insts.length as u32;
val first := this.operands.length as u32;
# Appended one by one, which is inlined, where `extend` is a call for each
# instruction.
for &each in args {
this.operands.append(each);
}
val result := this.origins.length as u32;
for i in 0..gives.length {
this.origins.append(origin { kind = gives[i], from = index, index = i as u32 });
}
this.insts.append(inst {
kind = kind,
count = gives.length as u8,
aux = aux,
imm = imm,
args = first,
argc = args.length as u32,
result = gives.length == 0 ? 0 : result,
block = at,
at = pos
});
val last: u32 = this.blocks[at].last;
if last == 0 {
this.blocks[at].first = index;
} else {
this.insts[last].next = index;
}
this.blocks[at].last = index;
return index;
}
#! Puts an instruction first in a block, as a value a variable has nowhere is
#! put first in the entry.
#! @param this The code.
#! @param at The block.
#! @param index The instruction, appended to no block yet.
pub def code::put_first(&mut this, at: u32, index: u32): void {
this.insts[index].block = at;
this.insts[index].next = this.blocks[at].first;
this.blocks[at].first = index;
if this.blocks[at].last == 0 {
this.blocks[at].last = index;
}
}
#! Adds an edge from an instruction ending a block into another block, without
#! arguments yet.
#! @param this The code.
#! @param from The instruction.
#! @param target The block it goes to.
#! @param case Of a `switch`, the word it goes on.
#! @returns Its index.
pub def code::add_edge(&mut this, from: u32, target: u32, case: u64): u32 {
val index := this.edges.length as u32;
this.edges.append(edge { from = from, target = target, case = case });
this.blocks[target].preds.append(index);
return index;
}
#! The operand of an instruction, by its position.
#! @param this The code.
#! @param index The instruction.
#! @param at The operand's position, below its `argc`.
#! @returns The value.
pub def code::arg(&this, index: u32, at: u32): u32 {
return this.operands[this.insts[index].args as u64 + at as u64];
}
#! The type of a value.
#! @param this The code.
#! @param value The value.
#! @returns Its type.
pub def code::type_of(&this, value: u32): vt {
return this.origins[value].kind;
}
#! The block an instruction ending a block leaves from: the block holding it.
#! @param this The code.
#! @param index The edge.
#! @returns The block.
pub def code::edge_source(&this, index: u32): u32 {
return this.insts[this.edges[index].from].block;
}
#! How many edges an instruction ending a block leaves by.
#! @param this The code.
#! @param index The instruction.
#! @returns How many: none for one that returns or stops.
pub def code::edge_count(&this, index: u32): u32 {
return this.insts[index].edge_count();
}
#! How many edges an instruction leaves by, which follow one another from its
#! `aux`.
#! @param this The instruction.
#! @returns How many: none for one that does not end its block, or returns or
#! stops.
pub def inst::edge_count(&this): u32 {
return match this.kind {
op::jump => 1,
op::branch => 2,
op::switch => this.imm as u32,
else => 0
};
}
#! Whether an operation ends its block.
#! @param this The operation.
#! @returns Whether it does.
pub def op::ends(&this): bool {
return (op_traits[this as u64] & op_ends) != 0;
}
#! What an operation is like, as the bits `op_pure` and the others give.
#! @param this The operation.
#! @returns Its bits.
pub def op::traits(&this): u8 {
return op_traits[this as u64];
}
#! The name of an operation, as the printed code writes it.
#! @param this The operation.
#! @returns The name.
pub def op::name(&this): strview {
return op_names[this as u64];
}
# What an operation is like, which the passes over the code respect.
pub const op_pure: u8 = 0x01; #! It only computes its result from its operands, so it may move or go.
pub const op_traps: u8 = 0x02; #! It may stop the program.
pub const op_reads: u8 = 0x04; #! It reads memory.
pub const op_write: u8 = 0x08; #! It writes memory.
pub const op_calls: u8 = 0x1E; #! It calls code, which may read, write, and stop the program.
pub const op_ends: u8 = 0x20; #! It ends its block.
#! What each operation is like, in the order `op` declares them.
const op_traits: u8[op::count as u64] = [
op_pure, op_pure, # iconst, fconst
op_pure, op_pure, op_pure, op_traps, op_traps, op_traps, op_traps, # add .. remu
op_pure, op_pure, op_pure, op_pure, op_pure, op_pure, # band .. shru
op_pure, op_pure, op_pure, op_pure, op_pure, op_pure, # eq .. leu
op_pure, op_pure, op_pure, op_pure, op_pure, # eqsu .. leus
op_pure, op_pure, op_pure, op_pure, op_pure, # fadd .. frem
op_pure, op_pure, op_pure, op_pure, # feq .. fle
op_pure, op_pure, op_pure, op_pure, # neg, bnot, lnot, fneg
op_pure, op_pure, op_pure, op_pure, op_pure, # itof .. fsingle
op_pure, op_pure, op_pure, op_pure, op_pure, op_pure, # fsqrt .. wrap
op_pure, # select
op_pure, op_pure, op_pure, # cell, global, datum
op_reads | op_traps, op_write | op_traps, # load, store
op_reads | op_write | op_traps, op_write | op_traps, # copy, clear
op_calls, # forget
op_calls, op_calls, op_calls, # allocate .. resize
op_calls, op_calls, op_calls, op_calls, # call .. call_c
op_pure, op_pure, # c_address, callback
op_reads | op_calls, op_pure, op_traps, # equal, retrait, check
op_calls, op_reads, op_pure, op_pure, op_calls, op_calls, # syscall .. catch
op_calls, op_calls, op_calls, op_calls, # safepoint, exit, abort, fault
op_calls, op_calls, op_calls | op_reads, op_calls | op_reads, op_calls, # format ..
op_traps, op_traps, op_traps, # ready, reach, same
op_pure, op_pure, op_pure, # cpu, lanes, vzero
op_calls, # atomic
op_calls, op_pure, op_calls, # start, current, clone
op_ends, op_ends, op_ends, op_ends | op_reads, op_ends | op_traps, op_ends, # jump .. unreachable
];
#! The name of each operation, in the order `op` declares them.
const op_names: strview[op::count as u64] = [
"iconst", "fconst",
"add", "sub", "mul", "divs", "divu", "rems", "remu",
"band", "bor", "bxor", "shl", "shrs", "shru",
"eq", "ne", "lts", "ltu", "les", "leu",
"eqsu", "ltsu", "lesu", "ltus", "leus",
"fadd", "fsub", "fmul", "fdiv", "frem",
"feq", "fne", "flt", "fle",
"neg", "bnot", "lnot", "fneg",
"itof", "utof", "ftoi", "ftou", "fsingle",
"fsqrt", "ones", "clz", "ctz", "bswap", "wrap",
"select",
"cell", "global", "datum",
"load", "store", "copy", "clear", "forget",
"allocate", "release", "resize",
"call", "call_trait", "call_value", "call_c",
"c_address", "callback",
"equal", "retrait", "check",
"syscall", "frame", "image", "environ", "signals", "catch",
"safepoint", "exit", "abort", "fault",
"format", "format_text", "format_value", "format_bytes", "format_owned",
"ready", "reach", "same",
"cpu", "lanes", "vzero",
"atomic",
"start", "current", "clone",
"jump", "branch", "switch", "ret", "trap", "unreachable",
];
#! The name of each access, as the printed code writes it.
const access_names: strview[13] = ["i8", "u8", "i16", "u16", "i32", "u32", "i64", "f32", "f64", "bytes", "v128", "v256", "v512"];
#! The name of an access.
#! @param this The access.
#! @returns Its name.
pub def access::name(&this): strview {
return access_names[this as u64];
}
#! The type of value an access reads and writes.
#! @param how The access.
#! @returns The type: a real for a float, a vector for lanes, and otherwise a
#! word.
pub def access::value_type(&this): vt {
return match this {
access::f32, access::f64 => vt::real,
access::v128 => vt::v128,
access::v256 => vt::v256,
access::v512 => vt::v512,
else => vt::word
};
}
#! The bytes an access reads or writes.
#! @param this The access.
#! @returns How many: 8 for `bytes`, whose size the instruction gives.
pub def access::width(&this): u64 {
return match this {
access::i8, access::u8 => 1,
access::i16, access::u16 => 2,
access::i32, access::u32, access::f32 => 4,
access::v128 => 16,
access::v256 => 32,
access::v512 => 64,
else => 8
};
}
#! Whether a type of value is a vector's.
#! @param this The type.
#! @returns Whether it is.
pub def vt::lanes(&this): bool {
return this == vt::v128 || this == vt::v256 || this == vt::v512;
}
#! The real whose bits a word holds.
#! @param bits The bits of an `f64`.
#! @returns The real.
pub def real_of(bits: u64): f64 {
var held := bits;
return ((&mut held) as *mut f64)[0];
}
#! The bits of a real, as a word holds them.
#! @param value The real.
#! @returns Its bits.
pub def bits_of_real(value: f64): u64 {
var held := value;
return ((&mut held) as *mut u64)[0];
}
+250
View File
@@ -0,0 +1,250 @@
#! @file compact.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the compacting of code. A pass taking out an instruction, a block,
#! or an edge leaves its slot behind, and inlining leaves about half of a
#! function's slots so, yet every pass after and both backends size their
#! tables by the slots and walk past the empty ones. Compacting numbers again
#! what is left so they cost only what the code holds. The instructions keep
#! the order they were in, which keeps what goes by it: the instructions a
#! variable's scope covers, as how many the code had where it begins and ends.
#! The blocks are numbered in reverse postorder, so the order the code keeps
#! of them is known without working it out again.
module sakura::compiler;
#! What compacting gives a slot that goes.
const compacted_out: u32 = 0xFFFFFFFF;
#! Compacts the code, as the file says. The blocks not removed are kept, with
#! the instructions in them, the edges those instructions leave by, and the
#! values they give and the blocks take, and so are the values the bindings
#! name; the rest goes. The blocks the entry reaches are numbered in reverse
#! postorder, then those it does not, and everything else in the order it was.
#! A value a binding names whose instruction went stays, given by nothing, so
#! the variable is shown as nowhere from there, as it was; but where that
#! instruction made a constant, the binding keeps the constant in its place.
#! @param this The code.
pub def code::compact(&mut this): void {
# The blocks the entry reaches, in reverse postorder, then the others not
# removed.
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.block_order(&mut order, &mut number);
var block_to := vector::<u32>::new(scratch());
block_to.resize(this.blocks.length, compacted_out);
var block_from := vector::<u32>::new(scratch());
block_from.reserve(this.blocks.length);
for &b in order {
block_to[b] = block_from.length as u32;
block_from.append(b);
}
val reached := block_from.length as u32;
for b in 0..this.blocks.length {
continue if this.blocks[b].gone || block_to[b] != compacted_out;
block_to[b] = block_from.length as u32;
block_from.append(b as u32);
}
# The instructions in those blocks, marked, then numbered in the order they
# were, with how many are kept below each slot, as a variable's scope is
# numbered.
var inst_to := vector::<u32>::new(scratch());
inst_to.resize(this.insts.length, compacted_out);
inst_to[0] = 0;
var live: u64 = 1;
for &b in block_from {
var walk := this.walk(b);
while walk.more() {
inst_to[walk.next()] = 0;
live++;
}
}
var kept := vector::<u32>::new(scratch());
kept.reserve(live);
var below := vector::<u32>::new(scratch());
below.resize(this.insts.length + 1);
for i in 0..this.insts.length {
below[i] = kept.length as u32;
continue if inst_to[i] == compacted_out;
inst_to[i] = kept.length as u32;
kept.append(i as u32);
}
below[this.insts.length] = kept.length as u32;
# The values the instructions kept give, the blocks kept take, and the
# bindings name, marked, then numbered in the order they were, each moving
# down to its number where it is. The operands and edges kept are counted.
val values := this.origins.length;
var value_to := vector::<u32>::new(scratch());
value_to.resize(values, compacted_out);
value_to[0] = 0;
var operand_count: u64 = 0;
var edge_count: u64 = 0;
for &i in kept {
val held := &this.insts[i];
for r in 0..held.count {
value_to[held.result as u64 + r as u64] = 0;
}
operand_count += held.argc as u64;
edge_count += held.edge_count() as u64;
}
for &b in block_from {
for &param in this.blocks[b].params {
value_to[param] = 0;
}
}
# A binding naming a constant whose instruction went keeps the constant in
# the value's place.
for i in 0..this.bindings.length {
val bound := &mut this.bindings[i];
continue if bound.value == 0 || bound.value as u64 >= values;
val held: origin = this.origins[bound.value];
if !held.param && inst_to[held.from] == compacted_out {
bound.known = this.constant_kind(bound.value, &mut bound.bits);
if bound.known != vt::none {
bound.value = 0;
continue;
}
}
value_to[bound.value] = 0;
}
var origins_kept: u64 = 0;
val origins := this.origins.slice().data;
for v in 0..values {
continue if value_to[v] == compacted_out;
value_to[v] = origins_kept as u32;
var held: origin = origins[v];
if v != 0 {
val home := held.param ? block_to[held.from] : inst_to[held.from];
if home == compacted_out {
held.param = false;
held.from = 0;
held.index = 0;
} else {
held.from = home;
}
}
origins[origins_kept] = held;
origins_kept++;
}
# Copied into memory of their size, so the code holds no more than it needs.
var made_origins := vector::<origin>::new();
made_origins.extend(span::<origin>::over(this.origins.view().data, origins_kept));
this.origins = move(&mut made_origins);
# What the bindings and variables name. A binding whose instruction went
# takes effect where its block begins, or where the block of that
# instruction does where its own went, as the backends read it. This reads
# the instructions where they are, before they move.
for i in 0..this.bindings.length {
val bound := &mut this.bindings[i];
val after := bound.after;
var block := bound.block;
if block == no_block || block_to[block] == compacted_out {
block = after != 0 ? this.insts[after].block : no_block;
}
bound.block = block == no_block || block_to[block] == compacted_out ? no_block : block_to[block];
bound.after = inst_to[after] == compacted_out ? 0 : inst_to[after];
bound.value = bound.value as u64 >= values ? 0 : value_to[bound.value];
}
for i in 0..this.variables.length {
val held := &mut this.variables[i];
if held.first != 0 {
held.first = below[held.first];
}
if held.end != 0 {
held.end = below[held.end];
}
}
# The instructions, each moving down to its number, their operands each in
# a run of its own, and the edges they leave by, each instruction's in a run
# as before. Read and written where the elements are, as this runs over
# every operand.
var made_operands := vector::<u32>::new();
made_operands.resize(operand_count);
val operands_to := made_operands.slice().data;
val operands_from := this.operands.view().data;
val values_to := value_to.view().data;
var made_edges := vector::<edge>::new();
made_edges.reserve(edge_count);
var edge_to := vector::<u32>::new(scratch());
edge_to.resize(this.edges.length, compacted_out);
val insts := this.insts.slice().data;
var placed: u64 = 0;
for n in 0..kept.length {
val i: u32 = kept[n];
var held: inst = insts[i];
val args := held.args as u64;
held.args = placed as u32;
for k in 0..held.argc as u64 {
operands_to[placed] = values_to[operands_from[args + k]];
placed++;
}
held.result = held.count == 0 ? 0 : values_to[held.result];
if i != 0 {
held.block = block_to[held.block];
held.next = inst_to[held.next];
}
val count := held.edge_count();
if count != 0 {
val first: u64 = held.aux;
held.aux = made_edges.length as u32;
for e in 0..count {
val old := first + e as u64;
edge_to[old] = made_edges.length as u32;
var args := move(&mut this.edges[old].args);
for k in 0..args.length {
args[k as u64] = values_to[args[k as u64]];
}
made_edges.append(edge {
from = n as u32, target = block_to[this.edges[old].target], args = move(&mut args), case = this.edges[old].case
});
}
}
insts[n] = held;
}
var made_insts := vector::<inst>::new();
made_insts.extend(span::<inst>::over(this.insts.view().data, kept.length));
this.insts = move(&mut made_insts);
# The blocks, their parameters and the edges into them numbered as they are
# now.
var made_blocks := vector::<block>::new();
made_blocks.reserve(block_from.length);
for &b in block_from {
var params := move(&mut this.blocks[b].params);
for k in 0..params.length {
params[k as u64] = values_to[params[k as u64]];
}
var preds := ids {};
for &pred in this.blocks[b].preds {
if edge_to[pred] != compacted_out {
preds.append(edge_to[pred]);
}
}
made_blocks.append(block {
first = inst_to[this.blocks[b].first], last = inst_to[this.blocks[b].last],
params = move(&mut params), preds = move(&mut preds)
});
}
# The dominators the code kept, where it kept them, numbered as the blocks.
var idom := vector::<u32>::new(scratch());
if this.idom_kept {
idom.resize(block_from.length, no_block);
for i in 0..block_from.length {
val dominator: u32 = this.kept_idom[block_from[i]];
idom[i] = dominator == no_block ? no_block : block_to[dominator];
}
}
this.operands = move(&mut made_operands);
this.blocks = move(&mut made_blocks);
this.edges = move(&mut made_edges);
this.keep_numbered_order(reached, block_from.length as u32, idom.view());
}
+160
View File
@@ -0,0 +1,160 @@
#! @file ids.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `ids`, a short list of indices, as a block's parameters, the edges
#! into it, and the arguments an edge gives. Up to four are held in the list
#! itself, so most lists take no memory of their own, and more are moved to
#! memory of the list's own.
module sakura::compiler;
#! A list of indices, holding up to four itself and more in memory of its own.
pub struct ids : owning, iterable<u32> {
var _len: u32; #! How many it holds.
var _cap: u32; #! How many its memory holds, or 0 while it holds them itself.
var _own: u32[4]; #! Those it holds itself.
var _dat: *mut u32; #! Its memory, once it has any.
}
#! How many indices the list holds.
#! @param this The list.
#! @returns How many.
pub val ids::length: u64 {
get => this._len as u64;
}
#! Where the indices begin, in the list or in its memory.
#! @param this The list.
#! @returns The first index.
pub def ids::data(&this): *u32 {
return this._cap == 0 ? (&this._own) as *u32 : this._dat;
}
#! Makes a list holding the same indices as another, sharing no memory with it.
#! @param other The list.
#! @returns The copy.
pub def ids::copy_of(other: &ids): ids {
var made := ids {};
for &each in other.view() {
made.append(each);
}
return made;
}
#! Lends a view of the indices.
#! @param this The list.
#! @returns The view, which refers into the list.
pub def ids::view(&this): span<u32> {
return span::<u32>::over(this.data(), this._len as u64);
}
#! Lends a view of the indices that writes them where they are.
#! @param this The list.
#! @returns The view, which refers into the list.
pub def ids::slice(&mut this): slice<u32> {
val data := this._cap == 0 ? (&mut this._own) as *mut u32 : this._dat;
return slice::<u32>::over(data, this._len as u64);
}
#! Reads the index at a place in the list.
#! @param this The list.
#! @param index The place, below `length`, which stops the program otherwise.
#! @returns The index.
pub def ids::at(&this, index: u64): &u32 {
return &span::<u32>::over(this.data(), this._len as u64)[index];
}
#! Writes the index at a place in the list.
#! @param this The list.
#! @param index The place, below `length`, which stops the program otherwise.
#! @returns A reference that writes it.
pub def ids::at(&mut this, index: u64): &mut u32 {
var whole := this.slice();
return &mut whole[index];
}
#! What `iter(&this)` lends, which reads the indices.
pub type ids::cursor = span<u32>::cursor;
#! Lends a cursor that reads the indices.
#! @param this The list.
#! @returns The cursor, which refers into the list.
pub def ids::iter(&this): span<u32>::cursor {
return this.view().iter();
}
#! Adds an index after the last.
#! @param this The list.
#! @param value The index.
pub def ids::append(&mut this, value: u32): void {
if this._cap == 0 && this._len < 4 {
this._own[this._len as u64] = value;
this._len++;
return;
}
if this._len == this._cap || this._cap == 0 {
this.spill(this._cap == 0 ? 8 : this._cap * 2);
}
this._dat[this._len as u64] = value;
this._len++;
}
#! Removes every index, keeping the memory the list holds them in.
#! @param this The list.
pub def ids::clear(&mut this): void {
this._len = 0;
}
#! A vector holding the same indices, which changing the list leaves as it is.
#! @param this The list.
#! @param alloc The optional allocator the vector takes its memory from.
#! @returns The vector.
pub def ids::copied(&this, alloc: maybe<&mut allocator>): vector<u32> {
var made := vector::<u32>::new(this.length, alloc);
made.extend(this.view());
return made;
}
#! Whether two lists hold the same indices in the same order.
#! @param this The list.
#! @param other The list to compare it with.
#! @returns Whether they do.
pub def ids::same(&this, other: &ids): bool {
return false if this._len != other._len;
val mine := this.data();
val theirs := other.data();
for i in 0..this._len as u64 {
return false if mine[i] != theirs[i];
}
return true;
}
#! Gives back the memory the list holds, leaving it empty.
#! @param this The list.
pub def ids::close(&mut this): void {
if this._cap != 0 {
raw_release(this._dat as *mut u8);
}
this._dat = null;
this._cap = 0;
this._len = 0;
}
# Moves the indices to memory of the list's own, with room for a number of them.
def ids::spill(&mut this, size: u32): void {
if this._cap != 0 {
this._dat = raw_resize(this._dat as *mut u8, size as u64 * 4) as *mut u32;
this._cap = size;
return;
}
val made := raw_allocate(size as u64 * 4) as *mut u32;
for i in 0..this._len as u64 {
made[i] = this._own[i];
}
this._dat = made;
this._cap = size;
}
+133
View File
@@ -0,0 +1,133 @@
#! @file liveness.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what the machine's assembler and the native backend's register
#! allocator share of finding where each value of a function's code is live:
#! the block a value is made in, and the walk from each block a value is read
#! in back over the edges into it, to the block making it. A value read in a
#! block other than its own is live into that block, and out of every block an
#! edge into it leaves, and so on back to its own, as a value read in a loop is
#! live around it.
module sakura::compiler;
#! Where the value being found is live in a block.
pub struct block_reach {
pub var stamp: u32; #! The value it is for, or another, where it is stale.
pub var ends: u32; #! Past the last read in the block.
pub var out: bool; #! Whether it is live where the block ends.
pub var into: bool; #! Whether it is live where the block begins.
}
#! The walk finding the blocks a value is live in, from the reads of it back to
#! the block making it. The reach of each block is kept for the value being
#! found, and is stale for any other, so the values of a function are found one
#! after another in the same memory.
pub struct live_walk {
pub var reaches: vector<block_reach>; #! The reach of each block.
pub var touched: vector<u32>; #! The blocks the value reaches, each once.
var todo: vector<u32>; #! The blocks it is live into whose edges in are not walked yet.
var reach: slice<block_reach>; #! A view of `reaches`, which never grows, indexed without a call.
var value: u32; #! The value being found.
var home: u32; #! The block making it.
}
#! Makes a walk of the blocks of a function's code, finding no value yet.
#! @param blocks How many blocks the code has.
#! @param alloc The optional allocator for the memory backing of the walk.
#! @returns The walk.
pub def live_walk::new(blocks: u64, alloc: maybe<&mut allocator>): live_walk {
var made := live_walk {
reaches = vector::<block_reach>::new(alloc),
touched = vector::<u32>::new(alloc),
todo = vector::<u32>::new(alloc),
value = 0xFFFFFFFF
};
made.reaches.resize(blocks, block_reach { stamp = 0xFFFFFFFF });
made.reach = made.reaches.slice();
return made;
}
#! Begins finding where a value is live.
#! @param this The walk.
#! @param value The value, which no reach is stamped with yet.
#! @param home The block making it.
pub def live_walk::begin(&mut this, value: u32, home: u32): void {
this.touched.clear();
this.todo.clear();
this.value = value;
this.home = home;
}
#! Readies a block's reach for the value being found, where it is stale.
#! @param this The walk.
#! @param block The block.
pub def live_walk::touch(&mut this, block: u32): void {
return if this.reach[block].stamp == this.value;
this.reach[block] = block_reach { stamp = this.value };
this.touched.append(block);
}
# Each way the value is found live in a block notes it live into the block too,
# which is then walked back from, unless the block makes the value, or it was
# noted already.
#! Notes a read of the value in a block, at a position: the block holds it up
#! to there, and it is live into the block, unless the block makes it.
#! @param this The walk.
#! @param block The block.
#! @param position Where the read is.
pub def live_walk::read(&mut this, block: u32, position: u32): void {
this.touch(block);
if position + 1 > this.reach[block].ends {
this.reach[block].ends = position + 1;
}
if block != this.home && !this.reach[block].into {
this.reach[block].into = true;
this.todo.append(block);
}
}
#! Notes a read of the value where a block ends, as the argument of an edge
#! leaving it: it is live out of the block, and into it, unless the block makes
#! it.
#! @param this The walk.
#! @param block The block.
pub def live_walk::read_out(&mut this, block: u32): void {
this.touch(block);
this.reach[block].out = true;
if block != this.home && !this.reach[block].into {
this.reach[block].into = true;
this.todo.append(block);
}
}
#! Walks back from each block the value is live into, over each edge into it:
#! the value is live out of the block the edge leaves, and into that block too,
#! unless it makes the value. The block making it is reached last of all.
#! @param this The walk.
#! @param body The code.
#! @param number Each block's place in the order laid out, or `0xFFFFFFFF`
#! for one not laid out.
#! @param laid Whether the edges leaving blocks not laid out are passed
#! over, rather than walked as any other.
pub def live_walk::walk(&mut this, body: &code, number: &vector<u32>, laid: bool): void {
while this.todo.length != 0 {
val block: u32 = this.todo.last();
this.todo.truncate();
for &edge in body.blocks[block].preds {
val from := body.edge_source(edge);
continue if laid && number[from] == 0xFFFFFFFF;
this.touch(from);
this.reach[from].out = true;
if from != this.home && !this.reach[from].into {
this.reach[from].into = true;
this.todo.append(from);
}
}
}
this.touch(this.home);
}
+82
View File
@@ -0,0 +1,82 @@
#! @file moves.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the making of moves all at once, as the moves along an edge into the
#! places of what its block takes are made: a move whose place another still
#! reads waits for that one, and moves going round in a cycle save one place
#! first, which those reading it read from where it was saved. The machine's
#! assembler moves words of the frame, and the native backend's selector
#! registers, slots, and the stack, each making the moves itself.
module sakura::compiler;
#! What making moves all at once needs of the moves and of what makes them.
#! @tparam M The type of a move.
pub trait move_maker<M> {
#! Whether a move reads the place another writes.
def move_reads(&this, reader: &M, writer: &M): bool;
#! Makes a move.
def move_one(&mut this, made: &M): void;
#! The move saving what a move would write over, to a place no move reads or
#! writes.
def move_saving(&mut this, written: &M, pending: span<M>): M;
#! Has a move read what another saved from where it was saved.
def move_reread(&this, reader: &mut M, saved: &M): void;
}
#! Makes moves all at once: the first whose place no other reads, again and
#! again, and where every place written is still read, the first move's place
#! saved first, to be read from where it was saved.
#! @param pending The moves, no two writing one place, and none reading the
#! place it writes, which are taken as they are made.
#! @param maker What makes them.
#! @param swap Whether a move made gives its place among those left to the
#! last, rather than those after it each moving up one, which
#! is the order the rest are tried in.
pub def make_moves<M, K>(pending: &mut vector<M>, maker: &mut K, swap: bool): void where K: move_maker<M> {
# The moves are read through a view, without a call, taken again as one goes.
var moves := pending.slice();
while moves.length != 0 {
var ready := moves.length;
for i in 0..moves.length {
var read := false;
for j in 0..moves.length {
if j != i && maker.move_reads(&moves[j], &moves[i]) {
read = true;
break;
}
}
if !read {
ready = i;
break;
}
}
if ready != moves.length {
maker.move_one(&moves[ready]);
if swap {
moves[ready] = pending.last();
pending.truncate();
} else {
pending.remove_at(ready);
}
moves = pending.slice();
continue;
}
# Every place written is still read: the first is saved, and read from
# where it was saved.
val saved := maker.move_saving(&moves[0], moves.view());
maker.move_one(&saved);
for j in 0..moves.length {
if maker.move_reads(&moves[j], &moves[0]) {
maker.move_reread(&mut moves[j], &saved);
}
}
}
}
+152
View File
@@ -0,0 +1,152 @@
#! @file numbers.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the operations of one value the machine gives that no operator of the
#! language writes: a square root, and counting and reversing a word's bits and
#! bytes. The machine runs them, and the optimizer folds them, through these, so
#! the two agree with each other and with an executable, whose instructions give
#! the same. `std::math` reaches them through its intrinsics, which a compiler
#! building this one need not know.
#!
#! `root_of` is musl's `sqrt`, from src/math/sqrt.c of musl 1.2.5, which is
#! Copyright © 2005-2020 Rich Felker, et al., under the MIT license.
module sakura::compiler;
# The reciprocal square roots `root_of` begins from, by the lowest bit of the
# exponent and the top six of the significand: musl's `__rsqrt_tab`.
const reciprocal_roots: u16[128] = [
0xb451, 0xb2f0, 0xb196, 0xb044, 0xaef9, 0xadb6, 0xac79, 0xab43,
0xaa14, 0xa8eb, 0xa7c8, 0xa6aa, 0xa592, 0xa480, 0xa373, 0xa26b,
0xa168, 0xa06a, 0x9f70, 0x9e7b, 0x9d8a, 0x9c9d, 0x9bb5, 0x9ad1,
0x99f0, 0x9913, 0x983a, 0x9765, 0x9693, 0x95c4, 0x94f8, 0x9430,
0x936b, 0x92a9, 0x91ea, 0x912e, 0x9075, 0x8fbe, 0x8f0a, 0x8e59,
0x8daa, 0x8cfe, 0x8c54, 0x8bac, 0x8b07, 0x8a64, 0x89c4, 0x8925,
0x8889, 0x87ee, 0x8756, 0x86c0, 0x862b, 0x8599, 0x8508, 0x8479,
0x83ec, 0x8361, 0x82d8, 0x8250, 0x81c9, 0x8145, 0x80c2, 0x8040,
0xff02, 0xfd0e, 0xfb25, 0xf947, 0xf773, 0xf5aa, 0xf3ea, 0xf234,
0xf087, 0xeee3, 0xed47, 0xebb3, 0xea27, 0xe8a3, 0xe727, 0xe5b2,
0xe443, 0xe2dc, 0xe17a, 0xe020, 0xdecb, 0xdd7d, 0xdc34, 0xdaf1,
0xd9b3, 0xd87b, 0xd748, 0xd61a, 0xd4f1, 0xd3cd, 0xd2ad, 0xd192,
0xd07b, 0xcf69, 0xce5b, 0xcd51, 0xcc4a, 0xcb48, 0xca4a, 0xc94f,
0xc858, 0xc764, 0xc674, 0xc587, 0xc49d, 0xc3b7, 0xc2d4, 0xc1f4,
0xc116, 0xc03c, 0xbf65, 0xbe90, 0xbdbe, 0xbcef, 0xbc23, 0xbb59,
0xba91, 0xb9cc, 0xb90a, 0xb84a, 0xb78c, 0xb6d0, 0xb617, 0xb560,
];
# `a * b / 2^32` of the low 32 bits of each, rounded down.
def high_of_32(a: u64, b: u64): u64 {
return ((a & 0xFFFFFFFF) * (b & 0xFFFFFFFF)) >> 32;
}
# `a * b / 2^64`, short of it by less than 3.
def high_of_64(a: u64, b: u64): u64 {
val ahi := a >> 32;
val alo := a & 0xFFFFFFFF;
val bhi := b >> 32;
val blo := b & 0xFFFFFFFF;
return ahi * bhi + ((ahi * blo) >> 32) + ((alo * bhi) >> 32);
}
#! The square root of a real, correctly rounded, as IEEE 754 defines it and
#! `sqrtsd` gives it: the root of `-0` is `-0`, of infinity infinity, and of
#! what is below zero, or not a number, not a number.
#! @param x The real.
#! @returns Its square root.
pub def root_of(x: f64): f64 {
var ix := bits_of_real(x);
var top := ix >> 52;
# Below the least normal, infinite, not a number, or below zero.
if top - 1 >= 0x7FE {
return x if ix * 2 == 0 || ix == 0x7FF0000000000000;
if ix > 0x7FF0000000000000 {
return (x - x) / (x - x);
}
# A subnormal, made normal.
ix = bits_of_real(x * 4503599627370496.0);
top = (ix >> 52) - 52;
}
# x is 4^e times m, with m from 1 to 4 held as 2.62 bits, and 2^e is the
# exponent of the root.
val even := top & 1;
var m := (ix << 11) | 0x8000000000000000;
if even != 0 {
m >>= 1;
}
top = (top + 0x3FF) >> 1;
# r is near 1 / sqrt(m) and s near sqrt(m): from the table, then two steps of
# Goldschmidt's iteration in 32 bits, and one in 64.
val three: u64 = 0xC0000000;
var r := (reciprocal_roots[(ix >> 46) % 128] as u64) << 16;
var s := high_of_32(m >> 32, r);
var d := high_of_32(s, r);
var u := three - d;
r = (high_of_32(r, u) << 1) & 0xFFFFFFFF;
s = (high_of_32(s, u) << 1) & 0xFFFFFFFF;
d = high_of_32(s, r);
u = three - d;
r = (high_of_32(r, u) << 1) & 0xFFFFFFFF;
r = r << 32;
s = high_of_64(m, r);
d = high_of_64(s, r);
u = (three << 32) - d;
s = high_of_64(s, u);
s = (s - 2) >> 9;
# s is below sqrt(m) by less than 2^-52 and a little more, so the root is s or
# the next, as (2^52 s + 1/2)^2 compares with 2^104 m.
val d0 := (m << 42) - s * s;
val d1 := s - d0;
s += d1 >> 63;
s &= 0x000FFFFFFFFFFFFF;
s |= top << 52;
return real_of(s);
}
#! How many bits of a word are 1.
#! @param word The word.
#! @returns How many.
pub def ones_of(word: u64): u64 {
var x := word - ((word >> 1) & 0x5555555555555555);
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333);
x = (x + (x >> 4)) & 0x0F0F0F0F0F0F0F0F;
return (x * 0x0101010101010101) >> 56;
}
#! How many 0 bits lead a word, from its top.
#! @param word The word.
#! @returns How many: 64 where it is zero.
pub def leading_zeros_of(word: u64): u64 {
return 64 if word == 0;
var x := word;
var count: u64 = 0;
if (x & 0xFFFFFFFF00000000) == 0 { count += 32; x <<= 32; }
if (x & 0xFFFF000000000000) == 0 { count += 16; x <<= 16; }
if (x & 0xFF00000000000000) == 0 { count += 8; x <<= 8; }
if (x & 0xF000000000000000) == 0 { count += 4; x <<= 4; }
if (x & 0xC000000000000000) == 0 { count += 2; x <<= 2; }
if (x & 0x8000000000000000) == 0 { count += 1; }
return count;
}
#! How many 0 bits trail a word, from its bottom.
#! @param word The word.
#! @returns How many: 64 where it is zero.
pub def trailing_zeros_of(word: u64): u64 {
return 64 if word == 0;
return ones_of((word & (0 - word)) - 1);
}
#! A word with its bytes in the reverse order.
#! @param word The word.
#! @returns The word reversed.
pub def bytes_swapped(word: u64): u64 {
var x := ((word >> 8) & 0x00FF00FF00FF00FF) | ((word & 0x00FF00FF00FF00FF) << 8);
x = ((x >> 16) & 0x0000FFFF0000FFFF) | ((x & 0x0000FFFF0000FFFF) << 16);
return (x >> 32) | (x << 32);
}
+123
View File
@@ -0,0 +1,123 @@
#! @file orders.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the order of the blocks and their dominators, kept with the code.
#! Working them out reads the last instruction of every block, which is where
#! most of the time goes, and many passes ask for them in turn, most of which
#! leave the blocks as they were. So code keeps what was last worked out, and
#! forgets it where what leads where changes: in each edit that changes an
#! edge, and where a pass changes edges itself, as merging blocks does, or
#! where pruning works the order out anew after inlining. Finding the blocks
#! the entry reaches works it out and keeps it, as what follows asks for it.
#! The verifier checks that what is kept is what would be worked out, after
#! each pass.
module sakura::compiler;
#! Writes the blocks the entry reaches in reverse postorder, and each block's
#! place in it, as `reverse_postorder` works them out, keeping them for the next
#! pass to ask.
#! @param this The code.
#! @param order Where the blocks are written, in that order.
#! @param number Where each block's place is written, by its index, or
#! `0xFFFFFFFF` for one the entry does not reach.
pub def code::block_order(&mut this, order: &mut vector<u32>, number: &mut vector<u32>): void {
this.keep_order();
order.clear();
order.extend(this.kept_order.view());
number.clear();
number.extend(this.kept_number.view());
}
#! Writes the blocks' order as `block_order` does, from what the code keeps
#! where it keeps it, for those that cannot keep it, as the backends.
#! @param this The code.
#! @param order Where the blocks are written.
#! @param number Where each block's place is written.
pub def code::copy_order(&this, order: &mut vector<u32>, number: &mut vector<u32>): void {
if !this.order_kept {
this.reverse_postorder(order, number);
return;
}
order.clear();
order.extend(this.kept_order.view());
number.clear();
number.extend(this.kept_number.view());
}
#! The immediate dominator of each block, as `dominators` works them out,
#! keeping them for the next pass to ask.
#! @param this The code.
#! @returns The dominators, by block, in scratch memory.
pub def code::block_dominators(&mut this): vector<u32> {
if !this.idom_kept {
this.keep_order();
val found := this.dominators(this.kept_order.view(), this.kept_number.view());
this.kept_idom.clear();
this.kept_idom.extend(found.view());
this.idom_kept = true;
}
var made := vector::<u32>::new(scratch());
made.extend(this.kept_idom.view());
return made;
}
#! Works out the blocks' order, where the code does not keep it, or keeps it
#! for fewer blocks than it has, as where blocks were added since.
#! @param this The code.
def code::keep_order(&mut this): void {
return if this.order_kept && this.kept_number.length == this.blocks.length;
this.reverse_postorder(&mut this.kept_order, &mut this.kept_number);
this.order_kept = true;
}
#! Forgets the order and dominators the code keeps, as what changes where its
#! blocks lead does.
#! @param this The code.
pub def code::forget_order(&mut this): void {
this.order_kept = false;
this.idom_kept = false;
}
#! Keeps an order worked out elsewhere: the blocks numbered in reverse
#! postorder, as compacting numbers them, the first `reached` of `count` being
#! those the entry reaches, with their dominators where given.
#! @param this The code.
#! @param reached How many blocks the entry reaches.
#! @param count How many blocks there are.
#! @param idom The immediate dominator of each, by its new number, or an
#! empty view where they are not known.
pub def code::keep_numbered_order(&mut this, reached: u32, count: u32, idom: span<u32>): void {
this.kept_order.clear();
this.kept_number.clear();
this.kept_number.resize(count as u64, 0xFFFFFFFF);
for i in 0..reached {
this.kept_order.append(i as u32);
this.kept_number[i as u64] = i as u32;
}
this.order_kept = true;
this.idom_kept = idom.length == count as u64;
if this.idom_kept {
this.kept_idom.clear();
this.kept_idom.extend(idom);
}
}
#! Notes where what the code keeps of its blocks' order or dominators is not
#! what would be worked out now, as where an edit changed where blocks lead
#! without forgetting them.
#! @param this The code.
#! @param order The blocks' order, worked out now.
#! @param idom Their dominators, worked out now.
#! @param found Where what is wrong is noted.
pub def code::check_kept_order(&this, order: span<u32>, idom: span<u32>, found: &mut vector<string>): void {
if this.order_kept && this.kept_order.view() != order {
found.append("The order of the blocks kept is not theirs now.");
}
if this.idom_kept && this.kept_idom.view() != idom {
found.append("The dominators of the blocks kept are not theirs now.");
}
}
+322
View File
@@ -0,0 +1,322 @@
#! @file printer.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the printing of code as text, which is how the tests say what code
#! they expect, and how code is read while debugging.
module sakura::compiler;
#! Prints the code. Each block is written as its name and parameters, then its
#! instructions, one to a line:
#!
#! ```
#! b0(v0: i64):
#! v1 = iconst 1
#! v2 = add v0, v1
#! branch v2, b1(v2), b2
#! ```
#!
#! Blocks are written in reverse postorder, and values and blocks are numbered
#! in the order they are written, so code that is the same is printed the same
#! however it was made. The cells of the frame are listed first, as `c0: 16, 8`
#! for one of 16 bytes aligned to 8.
#! @param this The code.
#! @returns The text.
pub def code::print(&this): string {
var out := string::new(nothing {});
var names := code_names {
values = vector::<u32>::new(),
blocks = vector::<u32>::new(),
next = 0
};
names.values.resize(this.origins.length);
names.blocks.resize(this.blocks.length);
# Blocks are written in reverse postorder, each before those it goes to but
# along the edges going back, as control mostly flows.
var order := vector::<u32>::new();
var number := vector::<u32>::new();
this.reverse_postorder(&mut order, &mut number);
for i in 0..order.length {
names.blocks[order[i]] = i as u32;
}
for i in 0..this.cells.length {
val held: cell = this.cells[i];
out.append($"c{i}: {held.size}, {held.align}\n");
}
for &b in order {
continue if this.blocks[b].gone;
out.append($"b{names.blocks[b]}");
val params := this.blocks[b].params.length;
if params != 0 {
out.append("(");
for i in 0..params {
if i != 0 {
out.append(", ");
}
val value: u32 = this.blocks[b].params[i];
this.print_value(value, &mut names, &mut out);
out.append(": ");
out.append(type_name(this.type_of(value)));
}
out.append(")");
}
out.append(":\n");
var walk := this.walk(b);
while walk.more() {
out.append(" ");
this.print_inst(walk.next(), &mut names, &mut out);
out.append("\n");
}
}
return out;
}
#! How the printer numbers what it writes.
struct code_names {
var values: vector<u32>; #! One more than the number of each value, or 0 before it is written.
var blocks: vector<u32>; #! The number of each block.
var next: u32; #! The number the next value written takes.
}
#! The name of a type, as the printed code writes it.
#! @param kind The type.
#! @returns Its name.
def type_name(kind: vt): strview {
return match kind {
vt::word => "i64",
vt::real => "f64",
vt::v128 => "v128",
vt::v256 => "v256",
vt::v512 => "v512",
else => "none"
};
}
#! Writes a value's name, numbering it where it is new.
#! @param this The code.
#! @param value The value.
#! @param names How the printer numbers what it writes.
#! @param out Where it is written.
def code::print_value(&this, value: u32, names: &mut code_names, out: &mut string): void {
if value == 0 || value as u64 >= names.values.length {
out.append("v?");
return;
}
if names.values[value] == 0 {
names.next++;
names.values[value] = names.next;
}
out.append($"v{names.values[value] - 1}");
}
#! Writes the values of a run of operands, separated by commas.
#! @param this The code.
#! @param index The instruction.
#! @param from The first operand to write.
#! @param names How the printer numbers what it writes.
#! @param out Where it is written.
def code::print_args(&this, index: u32, from: u32, names: &mut code_names, out: &mut string): void {
val held: inst = this.insts[index];
for i in from..held.argc {
if i != from {
out.append(", ");
}
this.print_value(this.arg(index, i as u32), names, out);
}
}
#! Writes an edge: the block it goes to, and its arguments where it gives any.
#! @param this The code.
#! @param edge The edge.
#! @param names How the printer numbers what it writes.
#! @param out Where it is written.
def code::print_edge(&this, edge: u32, names: &mut code_names, out: &mut string): void {
val target: u32 = this.edges[edge].target;
out.append($"b{names.blocks[target]}");
val count := this.edges[edge].args.length;
return if count == 0;
out.append("(");
for i in 0..count {
if i != 0 {
out.append(", ");
}
this.print_value(this.edges[edge].args[i], names, out);
}
out.append(")");
}
#! Writes an instruction.
#! @param this The code.
#! @param index The instruction.
#! @param names How the printer numbers what it writes.
#! @param out Where it is written.
def code::print_inst(&this, index: u32, names: &mut code_names, out: &mut string): void {
val held: inst = this.insts[index];
for i in 0..held.count {
if i != 0 {
out.append(", ");
}
this.print_value(held.result + i as u32, names, out);
}
if held.count != 0 {
out.append(" = ");
}
out.append(held.kind.name());
match held.kind {
op::iconst => out.append($" {held.imm as i64}");
op::fconst => out.append($" {real_of(held.imm)}");
op::wrap => {
out.append(" ");
this.print_args(index, 0, names, out);
out.append(held.imm != 0 ? $", {held.aux}, signed" : $", {held.aux}, unsigned");
}
op::cell => out.append($" c{held.aux}");
op::global => out.append($" {held.imm}");
op::datum => out.append($" d{held.aux}+{held.imm}");
op::load => {
out.append($".{(held.aux as access).name()} ");
this.print_args(index, 0, names, out);
if held.imm != 0 {
out.append($"+{held.imm}");
}
}
op::store => {
out.append($".{(held.aux as access).name()} ");
this.print_value(this.arg(index, 0), names, out);
if held.imm != 0 {
out.append($"+{held.imm}");
}
out.append(", ");
this.print_value(this.arg(index, 1), names, out);
}
op::copy, op::clear, op::forget => {
out.append(" ");
this.print_args(index, 0, names, out);
out.append($", {held.imm}");
}
op::call => {
out.append($" f{held.aux}(");
this.print_args(index, 0, names, out);
out.append(")");
}
op::call_trait => {
out.append($" s{held.aux}[{held.imm}](");
this.print_args(index, 0, names, out);
out.append(")");
}
op::call_value, op::call_c => {
out.append($" s{held.aux}(");
this.print_args(index, 0, names, out);
out.append(")");
}
op::c_address => out.append($" x{held.aux}");
op::callback, op::safepoint => out.append($" f{held.aux}");
op::equal => {
out.append(" ");
this.print_args(index, 0, names, out);
out.append($", l{held.aux}");
}
op::retrait => {
out.append(" ");
this.print_args(index, 0, names, out);
out.append($", r{held.aux}");
}
op::check => {
out.append(" ");
this.print_args(index, 0, names, out);
out.append($", {error_name(held.aux)}");
}
op::format_text => out.append($" d{held.aux}");
op::ready => out.append($" e{held.aux}");
op::reach => {
out.append(" ");
this.print_args(index, 0, names, out);
out.append($", {held.imm}");
}
op::lanes => {
out.append($".{held.aux}.{held.imm & 0xFF}.{held.imm >> 8} ");
this.print_args(index, 0, names, out);
}
op::atomic => {
out.append($".{atomic_names[held.aux as u64]}.{atomic_access(held.imm).name()}");
if (held.imm & atomic_unsigned) != 0 {
out.append(".unsigned");
}
out.append(" ");
this.print_args(index, 0, names, out);
}
op::format_value => {
out.append($" l{held.aux}");
if held.argc != 0 {
out.append(", ");
this.print_args(index, 0, names, out);
}
}
op::jump => {
out.append(" ");
this.print_edge(held.aux, names, out);
}
op::branch => {
out.append(" ");
this.print_args(index, 0, names, out);
out.append(", ");
this.print_edge(held.aux, names, out);
out.append(", ");
this.print_edge(held.aux + 1, names, out);
}
op::switch => {
out.append(" ");
this.print_args(index, 0, names, out);
out.append(", [");
val cases := held.imm as u32 - 1;
for i in 0..cases {
if i != 0 {
out.append(", ");
}
val edge := held.aux + i as u32;
out.append($"{this.edges[edge].case}: ");
this.print_edge(edge, names, out);
}
out.append("], ");
this.print_edge(held.aux + cases, names, out);
}
op::trap => {
out.append(" ");
if held.argc != 0 {
this.print_args(index, 0, names, out);
} else {
out.append(error_name(held.aux));
}
}
else => {
if held.argc != 0 {
out.append(" ");
this.print_args(index, 0, names, out);
}
}
}
}
#! The name of an error the machine stops a program with, as printed.
#! @param code The error, as the machine numbers them.
#! @returns Its name.
pub def error_name(code: u32): strview {
return match code {
fault::out_of_bounds as u32 => "out_of_bounds",
fault::null_reference as u32 => "null_reference",
fault::division as u32 => "division",
fault::not_held as u32 => "not_held",
fault::unreachable as u32 => "unreachable",
fault::not_member as u32 => "not_member",
fault::not_constant as u32 => "not_constant",
else => "error"
};
}
+383
View File
@@ -0,0 +1,383 @@
#! @file verifier.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the verifier, which checks that code is well formed: each block
#! ends in exactly one instruction ending it, each value is defined before
#! every use, in a block dominating the use, each edge gives the block it goes
#! to an argument of the right type for each parameter, and each instruction
#! takes operands of the types its operation does. The tests run it on what
#! lowering makes and after every pass.
module sakura::compiler;
#! What verifying code found wrong.
pub struct verdict {
var problems: vector<string>; #! Each problem, said in words.
}
#! Whether verifying found nothing wrong.
#! @param this The verdict.
#! @returns Whether it did.
pub def verdict::ok(&this): bool {
return this.problems.length == 0;
}
#! Verifies the code.
#! @param this The code.
#! @returns What is wrong with it, which is nothing where it is well formed.
pub def code::verify(&this): verdict {
var made := verdict { problems = vector::<string>::new() };
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.reverse_postorder(&mut order, &mut number);
var idom := this.dominators(order.view(), number.view());
this.check_kept_order(order.view(), idom.view(), &mut made.problems);
# Where each instruction is in its block, so a use within one is after the
# value it uses.
var place := vector::<u32>::new(scratch());
place.resize(this.insts.length);
for b in 0..this.blocks.length {
continue if this.blocks[b].gone;
var walk := this.walk(b as u32);
var index: u32 = 1;
while walk.more() {
place[walk.next()] = index;
index++;
}
}
for b in 0..this.blocks.length {
continue if this.blocks[b].gone;
if b != 0 && number[b] == 0xFFFFFFFF {
made.problems.append($"b{b} is not reached from the entry, but is not removed.");
}
if b == 0 && this.blocks[b].preds.length != 0 {
made.problems.append("The entry has edges into it.");
}
if this.blocks[b].first == 0 {
made.problems.append($"b{b} is empty.");
continue;
}
var walk := this.walk(b as u32);
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
if held.block != b as u32 {
made.problems.append($"Instruction {at} is in b{b} but says it is in b{held.block}.");
}
if held.kind.ends() && held.next != 0 {
made.problems.append($"b{b} goes on past `{held.kind.name()}`, which ends it.");
}
if !held.kind.ends() && held.next == 0 {
made.problems.append($"b{b} does not end with what ends a block.");
}
for i in 0..held.argc {
val value := this.arg(at, i as u32);
this.verify_use(value, b as u32, place[at], &idom, &place, &mut made, held.kind.name());
}
this.verify_types(at, &mut made);
if held.kind.ends() {
this.verify_edges(at, &idom, &place, &mut made);
}
}
}
return made;
}
#! Checks that a value is defined where it is used: before the use in the same
#! block, or in a block dominating the block of the use.
#! @param this The code.
#! @param value The value used.
#! @param block The block of the use.
#! @param index Where in the block the use is, past every instruction for an
#! edge's argument.
#! @param idom The immediate dominator of each block.
#! @param place Where each instruction is in its block.
#! @param made Where problems are noted.
#! @param what What uses it, for the note.
def code::verify_use(
&this,
value: u32,
block: u32,
index: u32,
idom: &vector<u32>,
place: &vector<u32>,
made: &mut verdict,
what: strview
): void {
if value == 0 || value as u64 >= this.origins.length {
made.problems.append($"b{block}: `{what}` uses value {value}, which is none.");
return;
}
val held: origin = this.origins[value];
val home := this.home_of(value);
if this.blocks[home].gone {
made.problems.append($"b{block}: `{what}` uses v{value}, of b{home}, which is removed.");
return;
}
if held.param && this.blocks[home].params.length <= held.index as u64 {
made.problems.append($"b{block}: `{what}` uses v{value}, a parameter b{home} no longer takes.");
return;
}
if home == block {
if !held.param && place[held.from] >= index {
made.problems.append($"b{block}: `{what}` uses v{value} before it is defined.");
}
return;
}
if !dominates(idom, home, block) {
made.problems.append($"b{block}: `{what}` uses v{value}, defined in b{home}, which does not dominate it.");
}
}
#! Checks that an instruction ending a block gives each block it goes to an
#! argument of the right type for each of its parameters.
#! @param this The code.
#! @param index The instruction.
#! @param idom The immediate dominator of each block.
#! @param place Where each instruction is in its block.
#! @param made Where problems are noted.
def code::verify_edges(&this, index: u32, idom: &vector<u32>, place: &vector<u32>, made: &mut verdict): void {
val held: inst = this.insts[index];
var outs := this.edges_of(index);
while outs.more() {
val edge := outs.next();
val target: u32 = this.edges[edge].target;
val args := this.edges[edge].args.length;
val params := this.blocks[target].params.length;
if args != params {
made.problems.append($"b{held.block}: an edge into b{target} gives {args} arguments for {params} parameters.");
continue;
}
for i in 0..args {
val given: u32 = this.edges[edge].args[i];
this.verify_use(given, held.block, 0xFFFFFFFF, idom, place, made, "an edge");
val want := this.type_of(this.blocks[target].params[i]);
if given != 0 && (given as u64) < this.origins.length && this.type_of(given) != want {
made.problems.append($"b{held.block}: an edge gives parameter {i} of b{target} a value of another type.");
}
}
}
}
#! Checks that an instruction takes operands of the types its operation does.
#! @param this The code.
#! @param index The instruction.
#! @param made Where problems are noted.
def code::verify_types(&this, index: u32, made: &mut verdict): void {
val held: inst = this.insts[index];
val name := held.kind.name();
var wants := vector::<vt>::new(scratch());
var exact := true;
match held.kind {
op::add, op::sub, op::mul, op::divs, op::divu, op::rems, op::remu, op::band, op::bor, op::bxor,
op::shl, op::shrs, op::shru, op::eq, op::ne, op::lts, op::ltu, op::les, op::leu, op::eqsu,
op::ltsu, op::lesu, op::ltus, op::leus, op::copy, op::equal, op::resize, op::format_bytes, op::fault,
op::reach, op::same => {
wants.append(vt::word);
wants.append(vt::word);
}
op::fadd, op::fsub, op::fmul, op::fdiv, op::frem, op::feq, op::fne, op::flt, op::fle => {
wants.append(vt::real);
wants.append(vt::real);
}
op::neg, op::bnot, op::lnot, op::itof, op::utof, op::ones, op::clz, op::ctz, op::bswap, op::wrap, op::load,
op::clear, op::forget, op::allocate, op::release, op::retrait, op::check, op::catch, op::exit, op::branch,
op::switch => wants.append(vt::word);
op::fneg, op::ftoi, op::ftou, op::fsingle, op::fsqrt => wants.append(vt::real);
op::select => {
# A word chosen by a word, between two words or two reals, of the type it
# gives.
val chosen := held.count == 1 ? this.type_of(held.result) : vt::none;
if chosen != vt::word && chosen != vt::real {
made.problems.append($"b{held.block}: `{name}` gives no word or real.");
}
wants.append(vt::word);
wants.append(chosen);
wants.append(chosen);
}
op::store => {
wants.append(vt::word);
val how: access = held.aux as access;
wants.append(how.value_type());
}
op::syscall => {
for _ in 0..7 { wants.append(vt::word); }
}
op::call_trait, op::call_value => {
for _ in 0..2 { wants.append(vt::word); }
exact = false;
}
op::call_c => {
wants.append(vt::word);
exact = false;
}
op::call, op::format_value, op::lanes => exact = false;
op::start => {
for _ in 0..3 { wants.append(vt::word); }
}
op::clone => wants.append(vt::word);
op::atomic => {
# Words: the address but of a fence, its operands, and its orders.
val count: u32 = held.aux == atomic_fence ? 1 : held.aux == atomic_load ? 2 : held.aux == atomic_compare_exchange ? 5 : 3;
for _ in 0..count { wants.append(vt::word); }
}
op::trap => {
# The runtime stops with an error it is given, as a word.
if held.argc != 0 {
wants.append(vt::word);
}
}
op::ret => {
wants.extend(this.results.view());
if this.returned != 0 {
wants.append(vt::word);
}
}
else => {}
}
if exact && held.argc as u64 != wants.length {
made.problems.append($"b{held.block}: `{name}` takes {wants.length} operands, but is given {held.argc}.");
return;
}
if !exact && (held.argc as u64) < wants.length {
made.problems.append($"b{held.block}: `{name}` takes at least {wants.length} operands, but is given {held.argc}.");
return;
}
for i in 0..wants.length {
val given := this.arg(index, i as u32);
continue if given == 0 || given as u64 >= this.origins.length;
if this.type_of(given) != wants[i] {
made.problems.append($"b{held.block}: operand {i} of `{name}` is v{given}, of another type than it takes.");
}
}
}
#! Orders the blocks the entry reaches so each comes before those it goes to,
#! but along edges going back, and numbers each by its place in that order.
#! @param this The code.
#! @param order Where the blocks are written, in that order.
#! @param number Where each block's place is written, by its index, or
#! `0xFFFFFFFF` for one the entry does not reach.
pub def code::reverse_postorder(&this, order: &mut vector<u32>, number: &mut vector<u32>): void {
# Each block's number marks it seen, from where it is put on the walk, and is
# its place once the walk is done.
number.clear();
number.resize(this.blocks.length, 0xFFFFFFFF);
order.clear();
# Each block on the walk with the next of its edges to follow, as
# `pair_key(block, next)`; the blocks are written as each is left, which is
# postorder, then turned round.
var stack := vector::<u64>::new(scratch());
stack.append(pair_key(0, 0));
number[0] = 0;
while stack.length != 0 {
# The top is written before a block is pushed, which may move it.
val top := &mut stack.last();
val block := pair_high(top);
val next := pair_low(top);
val last: u32 = this.blocks[block].last;
val count := last == 0 ? 0 : this.edge_count(last);
if next >= count {
order.append(block);
stack.truncate();
continue;
}
top = pair_key(block, next + 1);
val target: u32 = this.edges[this.insts[last].aux + next].target;
if number[target] == 0xFFFFFFFF {
number[target] = 0;
stack.append(pair_key(target, 0));
}
}
val length := order.length;
for i in 0..length / 2 {
val other := length - 1 - i;
val held: u32 = order[i];
order[i] = order[other];
order[other] = held;
}
for i in 0..length {
number[order[i]] = i as u32;
}
}
#! The immediate dominator of each block the entry reaches, as Cooper, Harvey,
#! and Kennedy's "A Simple, Fast Dominance Algorithm" finds them.
#! @param this The code.
#! @param order The blocks in reverse postorder.
#! @param number Each block's place in that order.
#! @returns The immediate dominator of each block, by its index: the entry's is
#! itself, and that of a block not reached `no_block`.
pub def code::dominators(&this, order: span<u32>, number: span<u32>): vector<u32> {
var idom := vector::<u32>::new(scratch());
idom.resize(this.blocks.length, no_block);
return idom if order.length == 0;
idom[0] = 0;
var changed := true;
while changed {
changed = false;
for i in 1..order.length {
val block := order[i];
var chosen := no_block;
for &edge in this.blocks[block].preds {
val pred := this.edge_source(edge);
continue if idom[pred] == no_block;
chosen = chosen == no_block ? pred : intersect(&idom, number, pred, chosen);
}
if chosen != no_block && idom[block] != chosen {
idom[block] = chosen;
changed = true;
}
}
}
return idom;
}
#! The nearest block dominating both blocks.
#! @param idom The immediate dominator of each block so far.
#! @param number Each block's place in reverse postorder.
#! @param a One block.
#! @param b The other.
#! @returns The block.
def intersect(idom: &vector<u32>, number: span<u32>, a: u32, b: u32): u32 {
var x := a;
var y := b;
while x != y {
while number[x] > number[y] {
x = idom[x];
}
while number[y] > number[x] {
y = idom[y];
}
}
return x;
}
#! Whether a block dominates another: every path from the entry to the other
#! goes through it.
#! @param idom The immediate dominator of each block.
#! @param a The block that may dominate.
#! @param b The block it may dominate.
#! @returns Whether it does.
pub def dominates(idom: &vector<u32>, a: u32, b: u32): bool {
var at := b;
var steps := 0;
while at != a && steps < 1000000 {
return false if at == 0 || at == no_block;
at = idom[at];
steps++;
}
return at == a;
}
+246
View File
@@ -0,0 +1,246 @@
#! @file walks.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the walks over code that the passes and the backends share: of the
#! instructions of a block, or of every block not removed, of the edges an
#! instruction leaves by, and of the values an instruction reads. Each is asked
#! `more` and then gives the next with `next`, so a `continue` goes on to the
#! next rather than round again, and a walk gives nothing once it is done. What
#! each is asked is small enough for the optimizer to inline, so a pass walking
#! with one costs what a loop written out by hand does.
module sakura::compiler;
#! What `read_walk::operand` gives for a value an edge gives, which is no
#! operand.
pub const no_operand: u32 = 0xFFFFFFFF;
#! A walk of the instructions of one block, in order. It reads where each
#! instruction goes on to as it gives it, so the instruction given may be
#! rewritten, moved, or taken out, and what is put after it is not given.
#! Asking it for each is small enough to be inlined, and nothing takes its
#! address, so what it holds stays in registers as it goes.
pub struct inst_walk {
var body: &code; #! The code.
var at: u32; #! The next instruction it gives, or 0 where none is left.
}
#! Walks the instructions of a block, in order.
#! @param this The code.
#! @param block The block.
#! @returns The walk.
pub def code::walk(&this, block: u32): inst_walk {
return inst_walk { body = this, at = this.blocks[block].first };
}
#! Whether the walk has another instruction to give.
#! @param this The walk.
#! @returns Whether it has.
pub def inst_walk::more(&this): bool {
return this.at != 0;
}
#! Gives the next instruction, once `more` says there is one.
#! @param this The walk.
#! @returns The instruction.
pub def inst_walk::next(&mut this): u32 {
val at := this.at;
this.at = this.body.insts[at].next;
return at;
}
#! A walk of the instructions of every block not removed: the blocks in order,
#! and each one's instructions in order, as `inst_walk` gives them. It goes
#! into each block by a call that takes the walk's values, not its address, so
#! what it holds stays in registers too.
pub struct code_walk {
var body: &code; #! The code.
var at: u32; #! The next instruction it gives, or 0 where the block it is in has no more.
var block: u32; #! The next block it goes into once that one has no more.
var end: u32; #! The block after the last it goes into.
}
#! Walks the instructions of every block not removed. A block is asked whether
#! it is removed as the walk goes into it, and the blocks are those the code
#! has now.
#! @param this The code.
#! @returns The walk.
pub def code::walk_all(&this): code_walk {
return code_walk { body = this, end = this.blocks.length as u32 };
}
#! Whether the walk has another instruction to give.
#! @param this The walk.
#! @returns Whether it has.
pub def code_walk::more(&mut this): bool {
return true if this.at != 0;
val found := this.body.next_filled(this.block, this.end);
this.block = pair_high(found);
this.at = pair_low(found);
return this.at != 0;
}
#! Gives the next instruction, once `more` says there is one.
#! @param this The walk.
#! @returns The instruction.
pub def code_walk::next(&mut this): u32 {
val at := this.at;
this.at = this.body.insts[at].next;
return at;
}
#! Finds the first block from one on, and before another, that is not removed
#! and holds an instruction.
#! @param this The code.
#! @param block The block to look from.
#! @param end The block to look before.
#! @returns The block after the one found, and its first instruction, as
#! `pair_key` packs them, or `end` and 0 where none is.
pub def code::next_filled(&this, block: u32, end: u32): u64 {
var at := block;
while at < end {
val held := &this.blocks[at];
at++;
return pair_key(at, held.first) if !held.gone && held.first != 0;
}
return pair_key(end, 0);
}
#! A walk of the edges an instruction ending a block leaves by, which follow one
#! another from its `aux`.
pub struct edge_walk {
var at: u32; #! The next edge it gives.
var end: u32; #! The edge after the last.
}
#! Walks the edges an instruction leaves by, in order: none for one that does
#! not end its block, or returns or stops.
#! @param this The code.
#! @param index The instruction.
#! @returns The walk.
pub def code::edges_of(&this, index: u32): edge_walk {
val first: u32 = this.insts[index].aux;
return edge_walk { at = first, end = first + this.edge_count(index) };
}
#! Whether the walk has another edge to give.
#! @param this The walk.
#! @returns Whether it has.
pub def edge_walk::more(&this): bool {
return this.at < this.end;
}
#! Gives the next edge, once `more` says there is one.
#! @param this The walk.
#! @returns The edge.
pub def edge_walk::next(&mut this): u32 {
val at := this.at;
this.at = at + 1;
return at;
}
#! A walk of every value instructions read: an instruction's operands, in
#! order, then the arguments of each edge it leaves by, edge after edge. A
#! walk is made once for the code with `reader`, then started at each
#! instruction in turn, or made for one with `reads_of`. It reads the values
#! where they are held, so nothing may add instructions, operands, or edges to
#! the code while it walks. Starting it is small enough to be inlined, so a
#! pass walking what every instruction reads makes no call for each.
pub struct read_walk {
var insts: *inst; #! The code's instructions.
var values: *u32; #! The code's operands.
var edges: *edge; #! The code's edges.
var held: *inst; #! The instruction while its operands are given, or null once its edges' arguments are.
var data: *u32; #! Where the values it is giving are held: its operands, or an edge's arguments.
var at: u64; #! The place there of the next it gives.
var end: u64; #! How many are held there.
var ends: bool; #! Whether the instruction ends its block, so the arguments of its edges follow its operands.
var edge: u32; #! The next edge whose arguments it gives.
var last: u32; #! The edge after the instruction's last.
}
#! Makes a walk of what the code's instructions read, to be started at each.
#! @param this The code.
#! @returns The walk, which gives nothing until it is started.
pub def code::reader(&this): read_walk {
return read_walk {
insts = this.insts.view().data,
values = this.operands.view().data,
edges = this.edges.view().data
};
}
#! Walks every value an instruction reads.
#! @param this The code.
#! @param index The instruction.
#! @returns The walk.
pub def code::reads_of(&this, index: u32): read_walk {
var made := this.reader();
made.start(index);
return made;
}
#! Starts the walk at an instruction, from its first operand.
#! @param this The walk.
#! @param index The instruction.
pub def read_walk::start(&mut this, index: u32): void {
val held := this.insts + index as u64;
this.held = held;
this.data = this.values + held[0].args as u64;
this.at = 0;
this.end = held[0].argc as u64;
# The operations from `jump` on are those ending a block, as `op` orders
# them, which a comparison asks more cheaply than `op::ends`.
this.ends = held[0].kind as u32 >= op::jump as u32;
}
#! Whether the walk has another value to give.
#! @param this The walk.
#! @returns Whether it has.
pub def read_walk::more(&mut this): bool {
return true if this.at < this.end;
return this.ends && this.next_edge();
}
#! Gives the next value, once `more` says there is one.
#! @param this The walk.
#! @returns The value.
pub def read_walk::next(&mut this): u32 {
val value := this.data[this.at];
this.at++;
return value;
}
#! Which operand the value the walk gave last is.
#! @param this The walk.
#! @returns Its position among the operands, or `no_operand` where an edge
#! gives it.
pub def read_walk::operand(&this): u32 {
return this.held != null ? (this.at - 1) as u32 : no_operand;
}
#! Goes on to the arguments of the next edge of the instruction that gives
#! any, its operands given.
#! @param this The walk.
#! @returns Whether one does.
def read_walk::next_edge(&mut this): bool {
if this.held != null {
this.edge = this.held[0].aux;
this.last = this.edge + this.held[0].edge_count();
this.held = null;
}
while this.edge < this.last {
val args := &this.edges[this.edge as u64].args;
this.edge++;
if args.length != 0 {
this.data = args.data();
this.at = 0;
this.end = args.length;
return true;
}
}
return false;
}
+410
View File
@@ -0,0 +1,410 @@
#! @file keeps.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what a function may do with what it is given past a call, its
#! summary: of each parameter, whether the reference it is given may be kept,
#! as where the function stores it, or given back in what the function returns;
#! and whether what that reference reaches, or what a value given holds, may
#! be. A local a reference is taken of lives in a cell of the frame, which
#! keeps its address for as long as the function runs, where the reference may
#! be kept past the statement taking it, and in its slots otherwise, so the
#! summaries decide where the locals of every caller are held.
#!
#! A function's summary comes from scanning its body, as `escapes.sakura` does,
#! with what each parameter is given standing as spots of the caller's. A
#! reference held in a value is followed where the value goes, so a function
#! giving back a value holding a reference to what it was given only gives the
#! reference back, which its caller follows in turn. Anything the scan does not
#! recognize keeps what it is given.
#!
#! Functions calling one another are summarized together, as Tarjan's algorithm
#! finds them: a function whose scan is not done is taken to do what was found
#! of it so far, nothing at first, and each function reading that is noted as
#! its reader. Once the first function of such a group is scanned, each of the
#! group whose summary grew after a reader read it has that reader scanned
#! again, until none grows, and each is then summarized for good. A function is
#! so scanned again only for what it read, never for what it calls being
#! scanned again.
import sakura::analyzer;
module sakura::compiler;
#! What a function may do with what each parameter gives it, one bit for each
#! parameter, `this` first. A parameter at 62 or past is taken to keep all.
pub struct keeping {
var kept: u64; #! Whose reference may be kept past the call.
var given: u64; #! Whose reference may be given back, in what the call gives.
var reached: u64; #! Of whose reference what it reaches, or of whose value what it holds, may be kept.
var passed: u64; #! Of whose reference what it reaches, or of whose value what it holds, may be given back.
}
#! The summary of a function that may do anything with what it is given.
#! @returns The summary.
pub def keeping::all(): keeping {
return keeping { kept = 0xFFFFFFFFFFFFFFFF, given = 0xFFFFFFFFFFFFFFFF, reached = 0xFFFFFFFFFFFFFFFF, passed = 0xFFFFFFFFFFFFFFFF };
}
#! Whether a summary does all another does.
#! @param this The summary.
#! @param other The other.
#! @returns Whether it does.
pub def keeping::covers(&this, other: &keeping): bool {
return (this.kept | other.kept) == this.kept && (this.given | other.given) == this.given
&& (this.reached | other.reached) == this.reached && (this.passed | other.passed) == this.passed;
}
#! A function whose summary is being found.
pub struct pending_scan {
var key: u64; #! The function, as `pair_key(decl, instance)`.
var decl: u32; #! Its declaration.
var instance: u32; #! One more than the instance scanned, or 0.
var found: keeping; #! What was found of it so far.
var low: u32; #! The earliest pending function it reaches, by its place.
var stale: bool; #! Whether a summary it read grew since it read it.
var readers: u32; #! One more than the first link of the functions that read its summary, or 0.
}
#! What `scanning` holds where no summary is being scanned.
const no_scan: u32 = 0xFFFFFFFF;
#! The summary of a function, or of an instance of a generic one, found where
#! it is new. A C function is given only an address, good until it returns,
#! and nothing is taken as kept.
#! What has no body to scan, as an intrinsic or a trait's method, may do
#! anything, but for an instance of a default compiled for each type, which is
#! scanned as the type's own method is.
#! @param this The compiler.
#! @param decl The function's declaration.
#! @param instance One more than the instance called, or 0.
#! @returns The summary.
pub def lowerer::keeps_of(&mut this, decl: u32, instance: u32): keeping {
return keeping::all() if decl == 0 || (decl & (ref_local | ref_type)) != 0 || this.checker.decls.kinds.p[decl] != dk::function;
this.checker.resolve(decl);
return keeping {} if this.checker.decls.has(decl, df::foreign) && !this.checker.has_body(decl);
return keeping::all() if this.checker.decls.has(decl, df::intrinsic) || !this.checker.has_body(decl)
|| (this.trait_of_method(decl) != 0 && (instance == 0 || !this.checker.typed_default(decl)));
val key := pair_key(decl, instance);
if this.summaries.get(&key) is some(got) {
return got;
}
if this.pending_ids.get(&key) is some(at) {
this.lean_on(at);
return this.pending[at as u64].found;
}
return this.summarize(decl, instance, key);
}
#! The summary of the function a call calls: a trait's method without a body,
#! called on a value whose type is known, is the method of that type the
#! vtable holds.
#! @param this The compiler.
#! @param decl The function's declaration.
#! @param instance One more than the instance called, or 0.
#! @param object The node of the value a method is called on, or 0.
#! @returns The summary.
pub def lowerer::keeps_of_call(&mut this, decl: u32, instance: u32, object: u32): keeping {
if object != 0 && instance == 0 && decl != 0 && (decl & (ref_local | ref_type)) == 0 && this.checker.typed_default(decl) {
return this.keeps_of_method(decl, this.checker.reached(this.checker.type_at(object)));
}
if object != 0 && decl != 0 && (decl & (ref_local | ref_type)) == 0 && this.trait_of_method(decl) != 0
&& !this.checker.has_body(decl) {
val callee := this.trait_callee(decl, this.checker.reached(this.checker.type_at(object)));
return keeping::all() if callee == 0;
return this.keeps_of(pair_high(callee), pair_low(callee));
}
return this.keeps_of(decl, instance);
}
#! The summary of a method the compiler calls itself on a value of a type, as a
#! loop's `next`, the instance the type's arguments give.
#! @param this The compiler.
#! @param decl The method's declaration, or 0.
#! @param owner The type it is called on.
#! @returns The summary.
pub def lowerer::keeps_of_method(&mut this, decl: u32, owner: u32): keeping {
return keeping::all() if decl == 0;
this.checker.resolve(decl);
if this.checker.typed_default(decl) {
val plain := this.checker.unalias(owner);
val holder := this.checker.enclosing_trait(decl);
val made := this.checker.default_instance(decl, this.checker.implemented(plain, holder), plain, span::<u32>::empty());
return made == 0 ? keeping::all() : this.keeps_of(decl, made);
}
if this.trait_of_method(decl) != 0 {
return keeping::all() if this.checker.has_body(decl);
val callee := this.trait_callee(decl, owner);
return keeping::all() if callee == 0;
return this.keeps_of(pair_high(callee), pair_low(callee));
}
return this.keeps_of(decl, this.method_instance(decl, owner));
}
#! The method a trait's method without a body calls on a value of a known type,
#! as its vtable holds it.
#! @param this The compiler.
#! @param decl The trait's method.
#! @param receiver The type of the value, read through its references.
#! @returns The method and its instance, as `pair_key(decl, instance)`, or 0
#! where the type is not known, or the method is a default.
def lowerer::trait_callee(&mut this, decl: u32, receiver: u32): u64 {
val plain := this.checker.unalias(receiver);
return 0 if this.checker.types.kind_of(plain) != ty::named || this.checker.named_kind(plain) == dk::trait_type;
val implemented := this.checker.implemented(plain, this.checker.enclosing_trait(decl));
val found := this.implementation(plain, decl, implemented);
return 0 if found == 0 || this.trait_of_method(found) != 0;
return pair_key(found, this.method_instance(found, plain));
}
#! The instance of a method a type's arguments give, as `method_target` finds
#! it.
#! @param this The compiler.
#! @param decl The method's declaration.
#! @param owner The type it is called on.
#! @returns One more than the instance, or 0.
pub def lowerer::method_instance(&mut this, decl: u32, owner: u32): u32 {
return 0 if decl == 0;
this.checker.resolve(decl);
return 0 if this.trait_of_method(decl) != 0 || !this.checker.decls.has(decl, df::generic);
val plain := this.checker.unalias(owner);
var args := vector::<u32>::new();
if this.checker.types.kind_of(plain) == ty::named {
for i in 0..this.checker.types.part_count(plain) {
args.append(this.checker.types.part_at(plain, i as u32));
}
}
return this.checker.instance_of(decl, args.view(), 0);
}
#! The type of a method called on a value of a type, as `method_target` gives
#! it.
#! @param this The compiler.
#! @param decl The method's declaration.
#! @param instance One more than its instance, as `method_instance` gives it.
#! @param owner The type it is called on.
#! @returns The function type.
pub def lowerer::method_kind(&mut this, decl: u32, instance: u32, owner: u32): u32 {
return bt::error if decl == 0;
val plain := this.checker.unalias(owner);
return this.checker.trait_method_type(decl, plain) if this.trait_of_method(decl) != 0;
return this.checker.instances[instance - 1].kind if instance != 0;
return this.checker.method_type(decl, plain) if this.checker.decls.has(decl, df::generic);
return this.checker.decls.types.p[decl];
}
#! Notes that the scan being made read the summary of a pending function, which
#! it then reaches, and must be scanned again where that summary grows.
#! @param this The compiler.
#! @param at The pending function, by its place.
def lowerer::lean_on(&mut this, at: u32): void {
# A function calling itself reads its own summary too.
val reader := this.scanning;
return if reader == no_scan;
if at < this.pending[reader as u64].low {
this.pending[reader as u64].low = at;
}
return if !this.read_pairs.insert(pair_key(at, reader));
this.reader_of.append(reader);
this.reader_next.append(this.pending[at as u64].readers);
this.pending[at as u64].readers = this.reader_of.length as u32;
}
#! Finds the summary of a function not yet scanned: scans it, and where it is
#! the first of a group calling back into one another, settles the group.
#! @param this The compiler.
#! @param decl The function's declaration.
#! @param instance One more than the instance, or 0.
#! @param key The function, as `pair_key(decl, instance)`.
#! @returns What was found of it, for good where its group is settled.
def lowerer::summarize(&mut this, decl: u32, instance: u32, key: u64): keeping {
val at := this.pending.length as u32;
this.pending.append(pending_scan { key = key, decl = decl, instance = instance, low = at });
this.pending_ids.set(key, at);
val outer := this.scanning;
this.scanning = at;
val found := this.summary_scan(decl, instance);
this.scanning = outer;
this.grow(at, &found);
if this.pending[at as u64].low == at {
this.settle_group(at);
return this.summaries.get_or(&key, keeping::all());
}
# Still pending, as the group it is in is: the scan around it reaches what it
# reaches, and read what it found.
if outer != no_scan && this.pending[at as u64].low < this.pending[outer as u64].low {
this.pending[outer as u64].low = this.pending[at as u64].low;
}
this.lean_on(at);
return this.pending[at as u64].found;
}
#! Adds to what was found of a pending function, and has each function that read
#! it scanned again where that grew.
#! @param this The compiler.
#! @param at The pending function, by its place.
#! @param found What a scan found of it.
def lowerer::grow(&mut this, at: u32, found: &keeping): void {
val had: keeping = this.pending[at as u64].found;
return if had.covers(found);
this.pending[at as u64].found = keeping {
kept = had.kept | found.kept, given = had.given | found.given,
reached = had.reached | found.reached, passed = had.passed | found.passed
};
var link: u32 = this.pending[at as u64].readers;
while link != 0 {
this.pending[this.reader_of[link as u64 - 1] as u64].stale = true;
link = this.reader_next[link as u64 - 1];
}
}
#! Settles a group of functions calling back into one another, from its first,
#! once that is scanned: each that read a summary which grew since is scanned
#! again, until none grows, and each is then summarized for good. A group that
#! will not settle, which never happens, is taken to do anything.
#! @param this The compiler.
#! @param root The group's first function, by its place.
def lowerer::settle_group(&mut this, root: u32): void {
var rounds: u64 = 0;
var more := true;
while more {
more = false;
var m := root as u64;
while m < this.pending.length {
if this.pending[m].stale {
this.pending[m].stale = false;
more = true;
val outer := this.scanning;
this.scanning = m as u32;
val found := this.summary_scan(this.pending[m].decl, this.pending[m].instance);
this.scanning = outer;
this.grow(m as u32, &found);
rounds++;
}
m++;
}
if rounds > 64 * (this.pending.length - root as u64) + 1024 {
for k in root as u64..this.pending.length {
this.pending[k].found = keeping::all();
}
break;
}
}
for k in root as u64..this.pending.length {
val held: pending_scan = this.pending[k];
this.summaries.set(held.key, held.found);
this.pending_ids.remove(&held.key);
}
this.pending.resize(root as u64);
if this.pending.length == 0 {
this.reader_of.clear();
this.reader_next.clear();
this.read_pairs.clear();
}
}
#! Scans a function's body for what it does with what it is given, each
#! parameter given spots of the caller's, and the scan's memory freed once the
#! summary is read from it.
#! @param this The compiler.
#! @param decl The function's declaration.
#! @param instance One more than the instance scanned, or 0.
#! @returns What it was found to do.
def lowerer::summary_scan(&mut this, decl: u32, instance: u32): keeping {
val saved := this.checker.at;
this.checker.use_table(this.body_table(decl, instance));
val node: u32 = this.checker.decls.nodes.p[decl];
val accessor := this.checker.decls.has(decl, df::accessor);
val body := accessor ? this.checker.record(node, accessor_slot::body) : this.checker.record(node, function_slot::body);
val params := accessor ? this.checker.left_of(node) : this.checker.record(node, function_slot::params);
val kind := this.type_of_function(decl, instance);
val point := mark_scratch();
var made := keeping {};
{
var s := escape_scan::new(scratch());
s.result = this.checker.types.first_of(kind);
this.scan_params(&mut s, params, kind, this.packs_last(decl));
this.scan_body(&mut s, body);
s.graph.solve();
s.graph.settle();
val count := this.checker.types.part_count(kind) as u64;
for i in 0..(count < 62 ? count : 62) {
val bit := 1u << i;
val outer: u32 = i < s.outers.length ? s.outers[i] : 0;
val inner: u32 = i < s.inners.length ? s.inners[i] : 0;
# What a pack takes, or what no parameter names, may be anything.
if inner == 0 {
made.kept |= bit;
made.given |= bit;
made.reached |= bit;
made.passed |= bit;
continue;
}
if outer != 0 {
val went: reach = s.graph.spots[outer as u64].reach;
if went == reach::kept {
made.kept |= bit;
} else if went == reach::given {
made.given |= bit;
}
}
val within: reach = s.graph.spots[inner as u64].reach;
if within == reach::kept {
made.reached |= bit;
} else if within == reach::given {
made.passed |= bit;
}
}
}
release_scratch(point);
this.checker.at = saved;
return made;
}
#! Whether a function's last parameter is a pack, which takes every parameter
#! from its own on.
#! @param this The compiler.
#! @param decl The function's declaration.
#! @returns Whether it is.
pub def lowerer::packs_last(&mut this, decl: u32): bool {
val written: u32 = this.checker.decls.types.p[decl];
val count := this.checker.types.part_count(written);
return this.checker.decls.has(decl, df::variadic) && count != 0
&& this.checker.types.is_open_pack(this.checker.types.part_at(written, count - 1));
}
#! The method an arithmetic operator calls, as the checker chose it, or 0 where
#! the language operates on its operands itself.
#! @param this The compiler.
#! @param node The operator's node.
#! @returns The method's declaration, or 0.
def lowerer::operator_called(&mut this, node: u32): u32 {
val kind := this.checker.kind_of(node);
return 0 if kind == nk::unary && this.checker.token_kind(node) != tk::minus && this.checker.token_kind(node) != tk::bitnot;
val ref := this.checker.ref_at(node);
return 0 if ref == 0 || (ref & (ref_local | ref_type)) != 0 || this.checker.decls.kinds.p[ref] != dk::function;
return ref;
}
#! The instance of a generic a call or an operator's method uses, as the
#! checker chose it.
#! @param this The compiler.
#! @param node The call's node.
#! @returns One more than the instance, or 0.
pub def lowerer::called(&mut this, node: u32): u32 {
val key := this.checker.result_key(node);
return this.checker.called.get_or(&key, 0);
}
#! Whether a type is a reference.
#! @param this The compiler.
#! @param kind The type.
#! @returns Whether it is.
pub def lowerer::is_reference_type(&mut this, kind: u32): bool {
return kind != 0 && this.checker.types.kind_of(this.checker.unalias(kind)) == ty::reference;
}
+381
View File
@@ -0,0 +1,381 @@
#! @file lanes.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains which vector instructions each operation on the lanes of a `simd`
#! needs: what `core::lanes_have` asks the processor running an executable for,
#! as it found it when it started, and what `core::lanes_apply` then works the
#! lanes with. SSE2 is every x86-64 processor's, and the rest only some have, so
#! an operation needing them is worked as std writes it, a lane at a time, where
#! the processor lacks them.
module sakura::compiler;
#! The instruction sets an executable asks its processor for as it starts, one
#! bit each of the word it keeps them in.
pub const cpu_sse2: u64 = 0x01;
pub const cpu_ssse3: u64 = 0x02;
pub const cpu_sse41: u64 = 0x04;
pub const cpu_sse42: u64 = 0x08;
#! AVX, where the system also keeps the registers' upper halves.
pub const cpu_avx: u64 = 0x10;
pub const cpu_avx2: u64 = 0x20;
pub const cpu_fma: u64 = 0x40;
#! Counting a word's ones, `popcnt`, and its leading zeros, `lzcnt`.
pub const cpu_popcnt: u64 = 0x80;
pub const cpu_lzcnt: u64 = 0x100;
#! BMI1, which has `tzcnt`, counting trailing zeros.
pub const cpu_bmi1: u64 = 0x200;
#! AVX-512's foundation with its instructions of 16-bit lanes (BW), of 64-bit
#! integers (DQ), and of 16 and 32 bytes (VL), where the system also keeps the
#! mask registers and the registers' upper 384 bits, as x86-64-v4 has them.
pub const cpu_avx512: u64 = 0x400;
#! What no processor has, for an operation no instructions work.
pub const cpu_never: u64 = 0x8000000000000000;
#! The operations on lanes, as std numbers them.
pub const lanes_add: u32 = 1;
pub const lanes_sub: u32 = 2;
pub const lanes_mul: u32 = 3;
pub const lanes_div: u32 = 4;
pub const lanes_and: u32 = 5;
pub const lanes_or: u32 = 6;
pub const lanes_xor: u32 = 7;
pub const lanes_negate: u32 = 8;
pub const lanes_not: u32 = 9;
pub const lanes_min: u32 = 10;
pub const lanes_max: u32 = 11;
pub const lanes_abs: u32 = 12;
pub const lanes_sqrt: u32 = 13;
pub const lanes_floor: u32 = 14;
pub const lanes_ceil: u32 = 15;
pub const lanes_trunc: u32 = 16;
pub const lanes_round_even: u32 = 17;
pub const lanes_equal: u32 = 18;
pub const lanes_not_equal: u32 = 19;
pub const lanes_less: u32 = 20;
pub const lanes_less_equal: u32 = 21;
pub const lanes_greater: u32 = 22;
pub const lanes_greater_equal: u32 = 23;
pub const lanes_select: u32 = 24; #! `a` the mask, `b` taken where it is set, `c` where not.
pub const lanes_fma: u32 = 25; #! `a * b + c`.
pub const lanes_shift_left: u32 = 26; #! `b` the `u32` count.
pub const lanes_shift_right: u32 = 27;
pub const lanes_bits: u32 = 28; #! The `u32` of the lanes the mask `a` has set.
pub const lanes_splat: u32 = 29; #! The lane `a` points at, in every lane.
pub const lanes_copy: u32 = 30; #! The lanes `a` points at, as they are, which moves them whole.
pub const lanes_pack: u32 = 31; #! (a, b, ...): the vector of these lanes, lane 0 first, as merging stores makes it.
pub const lanes_sum: u32 = 32; #! The lanes added together, lane 0 first, as one of the lane's type.
pub const lanes_product: u32 = 33; #! The lanes multiplied together, lane 0 first.
pub const lanes_smallest: u32 = 34; #! The least lane.
pub const lanes_largest: u32 = 35; #! The greatest lane.
pub const lanes_round: u32 = 36; #! Each real lane rounded to the nearest integer, halves away from zero.
pub const lanes_shuffle: u32 = 37; #! (a, b): `a`'s lanes in the order the bytes of `b` name, read as 16 bytes, one past the last stopping the program.
pub const lanes_convert: u32 = 38; #! `a`'s lanes, each as the type of lane above the operation's number converts it, as many.
pub const lanes_low: u32 = 39; #! The first half of `a`'s 32 bytes.
pub const lanes_high: u32 = 40; #! The second half.
pub const lanes_join: u32 = 41; #! (a, b): `a`'s 16 bytes, then `b`'s.
pub const lanes_widen: u32 = 42; #! The first half of `a`'s lanes, each as the type above the number, twice as wide.
pub const lanes_widen_high: u32 = 43; #! The second half so.
pub const lanes_narrow: u32 = 44; #! (a, b): `a`'s lanes, then `b`'s, each as the type above the number, half as wide, saturated.
pub const lanes_gather: u32 = 45; #! (a, b): the lanes the address `a` is, at the 32-bit places `b`'s lanes name.
#! The bytes the type of lane above an operation's number takes, which the
#! operations giving lanes of another type are numbered with.
#! @param operation The operation, as `lanes_apply` is given it.
#! @returns The type of lane.
pub def lanes_target(operation: u32): u32 {
return (operation >> 8) & 0xFF;
}
#! The types of lane, as the instructions take them: signed and unsigned
#! integers of each width, then the reals.
pub const lane_i8: u32 = 0;
pub const lane_u8: u32 = 1;
pub const lane_i16: u32 = 2;
pub const lane_u16: u32 = 3;
pub const lane_i32: u32 = 4;
pub const lane_u32: u32 = 5;
pub const lane_i64: u32 = 6;
pub const lane_u64: u32 = 7;
pub const lane_f32: u32 = 8;
pub const lane_f64: u32 = 9;
#! What no instruction takes.
pub const lane_none: u32 = 10;
#! The bits of a lane of a type.
#! @param lane The type of lane.
#! @returns Its bits.
pub def lane_bits(lane: u32): u64 {
return lane == lane_f32 ? 32 : lane == lane_f64 ? 64 : 8u << (lane / 2) as u64;
}
#! Whether a type of lane is a signed integer.
#! @param lane The type of lane.
#! @returns Whether it is.
pub def lane_signed(lane: u32): bool {
return lane < lane_f32 && lane % 2 == 0;
}
#! The instruction sets an operation on lanes needs, of 16, 32, or 64 bytes, or
#! of one real alone, one bit each as the executable keeps them, or `cpu_never`
#! where none work it.
#!
#! Of 16 bytes, SSE2 has most: arithmetic but integer division, bitwise
#! operations of any lanes, comparisons, square roots, splatting a lane, and the
#! least and greatest of reals, made IEEE 754's with more instructions; products
#! of 32 and 64 bits, from `pmuludq`'s of 32 bits into 64; shifts of bytes,
#! through those of 16 bits and a mask; and the absolute values and `>>` of
#! 64-bit integers, through their signs. SSSE3 adds integers' absolute values,
#! SSE4.1 rounding reals and the least and greatest of more integers, and SSE4.2
#! comparing 64-bit integers, so their least and greatest. FMA fuses multiplying
#! and adding. 32 bytes take AVX's forms: of reals, and what only moves bits, AVX's,
#! and of integers AVX2's. One real alone, as `std::math` works its rounding and
#! `fma` of one number, takes the instruction of one number, which needs the same,
#! and splats nothing. 64 bytes take AVX-512's, as `avx512_needs` says.
#! @param operation The operation, as std numbers them.
#! @param lane The type of lane.
#! @param bytes The bytes of the vector.
#! @returns The sets.
pub def lanes_needs(operation: u32, lane: u32, bytes: u64): u64 {
return cpu_never if lane >= lane_none;
if (operation & 0xFF) >= lanes_convert {
return reshape_needs(operation & 0xFF, lane, lanes_target(operation), bytes);
}
val real := lane >= lane_f32;
val bits := lane_bits(lane);
val signed := lane_signed(lane);
if bytes == bits / 8 {
return cpu_never if !real;
return cpu_fma if operation == lanes_fma;
return cpu_sse41 if operation >= lanes_floor && operation <= lanes_round_even;
return cpu_sse2 if operation == lanes_sqrt;
return cpu_never;
}
return avx512_needs(operation, lane) if bytes == 64;
return cpu_never if bytes != 16 && bytes != 32;
var need := cpu_never;
if operation == lanes_add || operation == lanes_sub || operation == lanes_negate || operation == lanes_select {
need = cpu_sse2;
} else if operation == lanes_mul {
need = cpu_sse2;
} else if operation == lanes_div || operation == lanes_sqrt {
need = real ? cpu_sse2 : cpu_never;
} else if operation == lanes_and || operation == lanes_or || operation == lanes_xor || operation == lanes_not {
# Of any lanes, as a mask's are combined.
need = cpu_sse2;
} else if operation == lanes_min || operation == lanes_max {
need = real || lane == lane_i16 || lane == lane_u8 ? cpu_sse2 : bits == 64 ? cpu_sse42 : cpu_sse41;
} else if operation == lanes_abs {
need = real || !signed || bits == 64 ? cpu_sse2 : cpu_ssse3;
} else if operation == lanes_floor || operation == lanes_ceil || operation == lanes_trunc || operation == lanes_round_even {
need = real ? cpu_sse41 : cpu_never;
} else if operation == lanes_equal || operation == lanes_not_equal {
need = real || bits < 64 ? cpu_sse2 : cpu_sse41;
} else if operation == lanes_less || operation == lanes_less_equal || operation == lanes_greater
|| operation == lanes_greater_equal {
need = real || bits < 64 ? cpu_sse2 : cpu_sse42;
} else if operation == lanes_fma {
need = real ? cpu_fma : cpu_never;
} else if operation == lanes_shift_left || operation == lanes_shift_right {
need = real ? cpu_never : cpu_sse2;
} else if operation == lanes_bits {
# A mask of 16-bit lanes is packed into bytes first, which 32 bytes would do
# within each half of the register, so those are taken a half at a time.
need = bits == 16 && bytes == 32 ? cpu_never : cpu_sse2;
} else if operation == lanes_splat || operation == lanes_copy {
need = cpu_sse2;
} else if operation == lanes_sum {
# Integers added in any order, and reals a lane at a time, lane 0 first.
need = cpu_sse2;
} else if operation == lanes_product {
need = real ? cpu_sse2 : cpu_never;
} else if operation == lanes_smallest || operation == lanes_largest {
# Of integers, as their least and greatest; reals' order is kept, which the
# registers left do not hold.
need = real ? cpu_never : lane == lane_i16 || lane == lane_u8 ? cpu_sse2 : bits == 64 ? cpu_sse42 : cpu_sse41;
} else if operation == lanes_round {
need = real ? cpu_sse41 : cpu_never;
} else if operation == lanes_shuffle {
# Bytes chosen by SSSE3's `pshufb`, and 32 bytes of 32- and 64-bit lanes by
# AVX2's `vpermd`, which crosses the halves `vpshufb` keeps apart.
need = bytes == 16 ? cpu_ssse3 : bits >= 32 ? cpu_sse41 : cpu_never;
}
return need if need == cpu_never || bytes == 16;
val moves_bits := operation == lanes_select || (operation == lanes_abs && !signed)
|| (operation == lanes_bits && bits != 8) || operation == lanes_splat || operation == lanes_copy;
return need | (real || moves_bits ? cpu_avx : cpu_avx2);
}
#! The instruction sets an operation on 64 bytes of lanes needs: AVX-512's,
#! for arithmetic but integer division, bitwise operations, comparisons, choosing
#! lanes, splatting one, a mask's bits, and of reals square roots, rounding, and
#! `fma`; of integers their least, greatest, and absolute values, and shifts.
#! Moving them is SSE2's. The rest, and every operation of bytes, whose mask's
#! bits would not fit a `u32`, `simd` works a half or a quarter at a time.
#! @param operation The operation, as std numbers them.
#! @param lane The type of lane.
#! @returns The sets.
def avx512_needs(operation: u32, lane: u32): u64 {
return cpu_sse2 if operation == lanes_copy;
return cpu_never if lane_bits(lane) == 8;
val real := lane >= lane_f32;
if operation <= lanes_not || (operation >= lanes_equal && operation <= lanes_select) || operation == lanes_bits
|| operation == lanes_splat {
return operation == lanes_div && !real ? cpu_never : cpu_avx512;
}
if operation == lanes_min || operation == lanes_max || operation == lanes_shift_left || operation == lanes_shift_right {
return real ? cpu_never : cpu_avx512;
}
if operation == lanes_sqrt || (operation >= lanes_floor && operation <= lanes_round_even) || operation == lanes_fma {
return real ? cpu_avx512 : cpu_never;
}
return operation == lanes_abs ? cpu_avx512 : cpu_never;
}
#! The instruction sets the operations giving lanes of another type or size
#! need: `lanes_needs` of those, of `lane` lanes in `bytes` making `target` lanes.
#! Halves of 32 bytes are AVX's to take apart and join, as are reals' widening
#! and narrowing between `f32` and `f64`, of 32 bytes. Integers widen by
#! SSE4.1's `pmovsx` and `pmovzx`, narrow by its `pack`s, and of 32 bytes by
#! AVX2's; `i32` becomes `f32` by SSE2's `cvtdq2ps`, and `u32` by two halves of
#! 16 bits; and a real becomes a 32-bit integer by `cvttps2dq` or `cvttpd2dq`,
#! which `simd`'s `convert` asks only of lanes within `i32`'s range, where it is
#! exact. Gathering 32 and 64-bit lanes at 32-bit places is AVX2's.
def reshape_needs(operation: u32, lane: u32, target: u32, bytes: u64): u64 {
val real := lane >= lane_f32;
val bits := lane_bits(lane);
if operation == lanes_low || operation == lanes_high {
return bytes == 32 ? cpu_sse2 | cpu_avx : cpu_never;
}
if operation == lanes_join {
return bytes == 16 ? cpu_sse2 | cpu_avx : cpu_never;
}
if operation == lanes_gather {
return lane_bits(lane) >= 32 && (bytes / (bits / 8) == 4 || (bits == 32 && bytes == 32)) ? cpu_sse2 | cpu_avx | cpu_avx2 : cpu_never;
}
return cpu_never if target >= lane_none || (bytes != 16 && bytes != 32);
val into_real := target >= lane_f32;
val into_bits := lane_bits(target);
val wide: u64 = bytes == 32 ? cpu_avx | cpu_avx2 : 0;
if operation == lanes_widen || operation == lanes_widen_high {
return cpu_never if into_bits != 2 * bits;
return cpu_sse2 | (bytes == 32 ? cpu_avx : 0) if real && into_real;
return cpu_sse41 | wide if !real && !into_real;
return cpu_never;
}
if operation == lanes_narrow {
return cpu_never if 2 * into_bits != bits || real != into_real || bits == 64 && !real;
return cpu_sse2 | (bytes == 32 ? cpu_avx : 0) if real;
# Signed lanes pack by SSE2's but into `u16`, and unsigned ones are held at
# the type's greatest by SSE4.1's least of unsigned lanes first.
val plain := lane_signed(lane) && (bits == 16 || lane_signed(target));
return (plain ? cpu_sse2 : cpu_sse41) | wide;
}
# Converting each lane, as many.
val into_bytes := bytes / (bits / 8) * (into_bits / 8);
return cpu_never if into_bytes != 16 && into_bytes != 32;
if !real && !into_real {
return cpu_sse2 | (bytes == 32 ? cpu_avx : 0) if into_bits == bits;
return cpu_sse41 | (into_bytes == 32 ? cpu_avx | cpu_avx2 : 0) if into_bits > bits;
return cpu_ssse3 | cpu_avx | cpu_avx2 if bytes == 32 && 2 * into_bits == bits;
return cpu_never;
}
if !real && into_real {
return cpu_never if bits == 64 || (target == lane_f64 && bits != 32);
return cpu_sse2 | cpu_avx if target == lane_f64;
return cpu_never if bits != 32 && into_bytes == 16;
return cpu_sse41 | cpu_avx | cpu_avx2 if bits < 32;
return cpu_sse2 | (bytes == 32 ? cpu_avx | (lane == lane_u32 ? cpu_avx2 : 0) : 0);
}
if real && !into_real {
# Toward zero, of lanes `simd`'s `convert` finds within `i32`'s range.
return cpu_never if into_bits != 32;
return cpu_sse2 | (bytes == 32 ? cpu_avx : 0) if lane == lane_f32;
return cpu_sse2 | cpu_avx;
}
return cpu_sse2 | (bytes == 32 || into_bytes == 32 ? cpu_avx : 0);
}
#! How many operands an operation on lanes takes: the vectors, and for a shift
#! the count, and for `lanes_splat` the lane.
#! @param operation The operation.
#! @returns How many.
pub def lanes_operands(operation: u32): u32 {
return 3 if operation == lanes_select || operation == lanes_fma;
val base := operation & 0xFF;
return 2 if base == lanes_join || base == lanes_narrow || base == lanes_gather;
return 1 if operation == lanes_negate || operation == lanes_not || operation == lanes_bits || operation == lanes_splat
|| operation == lanes_copy || (operation >= lanes_abs && operation <= lanes_round_even)
|| (operation >= lanes_sum && operation <= lanes_round) || base >= lanes_convert;
return 2;
}
#! How the result of an operation on lanes is written where `lanes_apply` is
#! given it: as the vector, as a `u32` of a mask's bits, or as the lane's type,
#! of one lane alone or of the lanes worked together.
#! @param operation The operation.
#! @param lane The type of lane.
#! @param bytes The bytes of the vector.
#! @returns The access.
pub def lanes_result_access(operation: u32, lane: u32, bytes: u64): access {
return access::u32 if operation == lanes_bits;
val base := operation & 0xFF;
if base == lanes_low || base == lanes_high {
return access::v128;
}
if base == lanes_join {
return access::v256;
}
if base == lanes_convert {
val made := bytes / (lane_bits(lane) / 8) * (lane_bits(lanes_target(operation)) / 8);
return made == 32 ? access::v256 : access::v128;
}
if bytes < 16 || (operation >= lanes_sum && operation <= lanes_largest) {
return lanes_operand_access(lanes_splat, lane, bytes, 0);
}
return vector_access(bytes);
}
#! How a vector of so many bytes is read and written whole.
#! @param bytes 16, 32, or 64.
#! @returns The access.
pub def vector_access(bytes: u64): access {
return bytes == 64 ? access::v512 : bytes == 32 ? access::v256 : access::v128;
}
#! How an operand of an operation on lanes is read from where `lanes_apply` is
#! given it: as the vector, or for a shift's count a `u32`, or for
#! `lanes_splat`'s lane, and every operand of one lane alone, as the lane's type.
#! @param operation The operation.
#! @param lane The type of lane.
#! @param bytes The bytes of the vector.
#! @param k Which operand.
#! @returns The access.
pub def lanes_operand_access(operation: u32, lane: u32, bytes: u64, k: u32): access {
if operation == lanes_splat {
return match lane {
lane_i8 => access::i8,
lane_u8 => access::u8,
lane_i16 => access::i16,
lane_u16 => access::u16,
lane_i32 => access::i32,
lane_u32 => access::u32,
lane_f32 => access::f32,
lane_f64 => access::f64,
else => access::i64
};
}
return access::u32 if k == 1 && (operation == lanes_shift_left || operation == lanes_shift_right);
return access::v128 if k == 1 && operation == lanes_shuffle;
if (operation & 0xFF) == lanes_gather {
return access::i64 if k == 0;
return bytes / (lane_bits(lane) / 8) == 8 ? access::v256 : access::v128;
}
return (lane == lane_f32 ? access::f32 : access::f64) if bytes == lane_bits(lane) / 8;
return vector_access(bytes);
}
+503
View File
@@ -0,0 +1,503 @@
#! @file layouts.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the layouts of types, as the C compiler's `compiler__make_layout`
#! makes them: scalars aligned to their size, as C aligns them, so a struct is
#! laid out as C lays out one of the same fields, a union as its tag and then
#! its largest field, and each with a map of the words that may hold a heap
#! object. Also contains the signatures calls pass arguments by, and how many
#! words a value of each layout is as a value of the intermediate code.
import sakura::analyzer;
module sakura::compiler;
#! The type a value is laid out as: what its aliases stand for, and what a
#! constant settles as where nothing converts it.
#! @param this The compiler.
#! @param kind The type.
#! @returns The type laid out.
pub def lowerer::layout_type(&mut this, kind: u32): u32 {
var at := this.checker.unalias(kind);
if this.checker.types.is_untyped(at) {
at = this.checker.unalias(this.checker.settle(at));
}
return at;
}
#! The layout of a type, made where it is new.
#! @param this The compiler.
#! @param kind The type.
#! @returns The layout's index.
pub def lowerer::layout_of(&mut this, kind: u32): u32 {
val plain := this.layout_type(kind);
if this.layout_ids.get(&plain) is some(got) {
return got;
}
return this.make_layout(plain);
}
#! A copy of a layout, which stays as it is however the layouts grow.
#! @param this The compiler.
#! @param index The layout's index.
#! @returns The layout.
pub def lowerer::layout_at(&this, index: u32): layout {
return this.program.layouts[index];
}
#! The layout of a type's values: what kind it is, its size, and the rest.
#! @param this The compiler.
#! @param kind The type.
#! @returns A copy of the layout.
pub def lowerer::shape_of(&mut this, kind: u32): layout {
val index := this.layout_of(kind);
return this.program.layouts[index];
}
#! A field of a layout, by its position.
#! @param this The compiler.
#! @param index The layout's index.
#! @param at The field's position.
#! @returns A copy of the field.
pub def lowerer::field_at(&this, index: u32, at: u32): slot_field {
val first: u32 = this.program.layouts[index].fields;
return this.program.fields[first as u64 + at as u64];
}
#! Makes the layout of a type not yet laid out. It is registered before its
#! parts are laid out, so a type referring to itself through a reference or a
#! pointer finds it.
#! @param this The compiler.
#! @param kind The type, as `layout_type` gives it.
#! @returns The layout's index.
def lowerer::make_layout(&mut this, kind: u32): u32 {
this.laying++;
val index := this.program.layouts.length as u32;
this.program.layouts.append(layout { type_id = kind, align = 1, how = access::bytes });
this.layout_ids.set(kind, index);
var made := layout { type_id = kind, align = 1, how = access::bytes };
var parts := vector::<slot_field>::new();
match this.checker.types.kind_of(kind) {
ty::boolean, ty::untyped_bool => {
made.kind = lk::boolean;
made.bits = 8;
made.size = 1;
made.how = access::u8;
}
ty::signed, ty::unsigned => this.integer_layout(&mut made, this.checker.types.kind_of(kind) == ty::signed,
this.checker.types.first_of(kind));
ty::floating => {
val bits := this.checker.types.first_of(kind);
made.kind = lk::floating;
made.bits = bits;
made.size = bits <= 32 ? 4 : 8;
made.align = made.size;
made.how = bits <= 32 ? access::f32 : access::f64;
}
ty::reference, ty::null_type => {
val referent := this.checker.types.kind_of(kind) == ty::reference ? this.checker.types.first_of(kind) : 0;
val traited := referent != 0 && this.checker.named_kind(this.checker.unalias(referent)) == dk::trait_type;
made.kind = traited ? lk::trait_reference : lk::reference;
made.size = traited ? 2 * word_size : word_size;
made.align = word_size;
made.how = traited ? access::bytes : access::i64;
}
ty::pointer => this.pointer_layout(&mut made);
ty::fixed => {
val element := this.layout_of(this.checker.types.first_of(kind));
val inner := this.layout_at(element);
made.kind = lk::fixed;
made.element = element + 1;
made.count = this.checker.types.part_count(kind) == 0 ? this.checker.types.second_of(kind) : 0;
made.align = inner.align;
made.size = inner.size * made.count as u64;
}
ty::function => {
made.kind = lk::function;
made.size = 2 * word_size;
made.align = word_size;
}
ty::named => this.named_layout(kind, &mut made, &mut parts);
else => {}
}
# A view is written as the elements it views, and a view of bytes, like the
# string that owns them, as the text itself. Both keep where the elements
# begin in a pointer field, with how many there are in the field after it.
if made.kind == lk::record && parts.length >= 2 {
val viewed := this.viewed(kind);
val element: u32 = viewed != 0 ? this.layout_of(viewed) + 1 : 0;
var bytes := this.is_string(kind);
if element != 0 {
val inner := this.layout_at(element - 1);
bytes = bytes || (inner.size == 1 && inner.kind != lk::record);
}
for i in 0..parts.length - 1 {
break if !bytes && element == 0;
continue if this.layout_at(parts[i].layout).kind != lk::pointer;
made.texts = bytes;
made.views = !bytes;
made.viewed = bytes ? 0 : element;
made.text = i as u32;
break;
}
}
made.size = round_up(made.size, made.align);
val scalar := made.kind == lk::signed || made.kind == lk::unsigned || made.kind == lk::floating
|| made.kind == lk::boolean || made.kind == lk::pointer;
made.frame = scalar ? word_size : round_up(made.size, word_size);
# Each part is kept in a run of its own, after whatever laying out the parts
# made.
made.fields = this.program.fields.length as u32;
made.count = made.kind == lk::fixed ? made.count : parts.length as u32;
for &each in parts {
this.program.fields.append(each);
}
this.note_references(&mut made, parts.view());
# A reference or pointer is laid out without what it refers to, which may be a
# type still being laid out, or one holding a type that is, as `node` holds
# the `maybe<&node>` whose `&node` reaches it. So that comes once the outermost
# layout is made, where every size is known.
this.program.layouts[index] = made;
val held := this.checker.types.kind_of(kind);
if (held == ty::reference && made.kind == lk::reference) || held == ty::pointer {
this.referents.append(index);
this.referents.append(this.checker.types.first_of(kind));
}
this.laying--;
if this.laying == 0 {
this.laying = 1;
var at: u64 = 0;
while at < this.referents.length {
val reaching: u32 = this.referents[at];
val element := this.layout_of(this.referents[at + 1]);
this.program.layouts[reaching].element = element + 1;
at += 2;
}
this.referents.clear();
this.laying = 0;
}
return index;
}
#! Lays out an integer of the bits, aligned to its size as C aligns it.
#! @param this The compiler.
#! @param made The layout being made.
#! @param signed Whether it is signed.
#! @param bits Its bits.
def lowerer::integer_layout(&mut this, made: &mut layout, signed: bool, bits: u32): void {
made.kind = signed ? lk::signed : lk::unsigned;
made.bits = bits;
made.size = bits <= 8 ? 1 : bits <= 16 ? 2 : bits <= 32 ? 4 : 8;
made.align = made.size;
made.how = match made.size {
1 => signed ? access::i8 : access::u8,
2 => signed ? access::i16 : access::u16,
4 => signed ? access::i32 : access::u32,
else => access::i64
};
}
#! Lays out a pointer, an address the program follows itself, as the address
#! of a C function is too.
#! @param this The compiler.
#! @param made The layout being made.
def lowerer::pointer_layout(&mut this, made: &mut layout): void {
made.kind = lk::pointer;
made.size = word_size;
made.align = word_size;
made.how = access::i64;
}
#! Lays out a named type: a struct, a union, an enum, or the address of a C
#! function.
#! @param this The compiler.
#! @param kind The type.
#! @param made The layout being made.
#! @param parts Where its fields are written.
def lowerer::named_layout(&mut this, kind: u32, made: &mut layout, parts: &mut vector<slot_field>): void {
val decl: u32 = this.checker.types.first_of(kind);
if this.checker.is_std(kind, word::cfn) {
this.pointer_layout(made);
return;
}
match this.checker.decls.kinds.p[decl] {
dk::enum_type => {
# An enum is laid out as its integer, naming each member as a field whose
# offset is its value.
val integer := this.layout_at(this.layout_of(this.checker.enum_integer(kind)));
made.kind = integer.kind;
made.bits = integer.bits;
made.size = integer.size;
made.align = integer.align;
made.how = integer.how;
made.name = this.checker.decls.names.p[decl];
val run: u32 = this.checker.decls.children.p[decl];
for i in 0..this.checker.decls.list_length(run) {
val member := this.checker.decls.list_at(run, i as u32);
var value := constant {};
this.checker.decl_value(member, &mut value);
parts.append(slot_field {
name = this.checker.decls.names.p[member],
offset = value.bits(),
decl = member
});
}
}
dk::struct_type, dk::union_type => {
# An instance of a generic is named with its arguments, as `pair<i64>`.
made.name = this.checker.decls.names.p[decl];
if this.checker.types.part_count(kind) != 0 {
val named := this.checker.describe(kind);
made.name = this.checker.names.intern(&named.view());
}
val run: u32 = this.checker.decls.children.p[decl];
for i in 0..this.checker.decls.list_length(run) {
val field := this.checker.decls.list_at(run, i as u32);
continue if this.checker.decls.kinds.p[field] != dk::field;
this.checker.resolve(field);
val held := this.checker.instantiated(this.checker.decls.types.p[field], decl, kind);
parts.append(slot_field {
name = this.checker.decls.names.p[field],
layout = this.layout_of(held),
type_id = held,
decl = field,
spread = this.checker.is_spread(field)
});
}
val is_union := this.checker.decls.kinds.p[decl] == dk::union_type;
if is_union && this.checker.decls.has(decl, df::foreign) {
# Every field of a C union begins where it does, as an `extern module` lays it out.
made.kind = lk::record;
for &each in parts {
val inner := this.layout_at(each.layout);
made.size = inner.size > made.size ? inner.size : made.size;
made.align = inner.align > made.align ? inner.align : made.align;
}
return;
}
if !is_union {
made.kind = lk::record;
var offset: u64 = 0;
for i in 0..parts.length {
val inner := this.layout_at(parts[i].layout);
offset = round_up(offset, inner.align);
parts[i].offset = offset;
offset += inner.size;
made.align = inner.align > made.align ? inner.align : made.align;
}
made.size = offset;
return;
}
# A union of an empty field and a reference, a trait reference, a
# function value, or a struct of one of them alone, none of which is ever
# null, holds no tag: it holds the empty field where its first word is
# null, as `none` of `maybe<&T>` and `maybe<box<T>>`.
made.kind = lk::variant;
if parts.length == 2 {
val first := this.layout_at(parts[0].layout);
val second := this.layout_at(parts[1].layout);
var held: u32 = 0;
if first.size == 0 && this.never_null(&second) {
held = 2;
} else if second.size == 0 && this.never_null(&first) {
held = 1;
}
if held != 0 {
val payload := this.layout_at(parts[held - 1].layout);
made.niche = held;
made.size = payload.size;
made.align = payload.align;
parts[0].offset = 0;
parts[1].offset = 0;
return;
}
}
# Every field of a union is the payload after the tag, which is its index.
made.align = word_size;
var payload: u64 = 0;
for i in 0..parts.length {
val inner := this.layout_at(parts[i].layout);
parts[i].offset = word_size;
payload = inner.size > payload ? inner.size : payload;
made.align = inner.align > made.align ? inner.align : made.align;
}
made.size = word_size + payload;
}
else => {}
}
}
#! Notes whether a layout may hold a reference: as a reference, a trait
#! reference, or a function value, which holds its environment, or as what
#! holds one by value.
#! @param this The compiler.
#! @param made The layout being made.
#! @param parts Its fields.
def lowerer::note_references(&mut this, made: &mut layout, parts: span<slot_field>): void {
match made.kind {
lk::reference, lk::trait_reference, lk::function => made.pointers = true;
lk::fixed => {
if made.element != 0 {
made.pointers = this.layout_at(made.element - 1).pointers;
}
}
lk::record, lk::variant => {
for &each in parts {
if each.layout != 0 && this.layout_at(each.layout).pointers {
made.pointers = true;
}
}
}
else => {}
}
}
#! The elements a view of std views, or 0 for anything else: both the read-only
#! `span<T>` and the writable `slice<T>` are views, and hold the same two words.
#! @param this The compiler.
#! @param kind The type.
#! @returns The type of the elements, or 0.
pub def lowerer::viewed(&mut this, kind: u32): u32 {
val plain := this.checker.unalias(kind);
if this.checker.is_std(plain, word::span) || this.checker.is_std(plain, word::slice) {
return this.checker.types.part_count(plain) != 0 ? this.checker.types.part_at(plain, 0) : 0;
}
return 0;
}
#! Whether a type is std's `string`, which owns the text it holds.
#! @param this The compiler.
#! @param kind The type.
#! @returns Whether it is.
pub def lowerer::is_string(&mut this, kind: u32): bool {
return this.checker.is_std(this.checker.unalias(kind), word::string);
}
#! The field a union holds, by its index, given the first word of its value:
#! its tag, or of a union laid out without one, the field laid out where the
#! word is not null, and the empty one where it is.
#! @param held The union's layout.
#! @param first The first word of its value.
#! @returns The field's index.
pub def held_field(held: &layout, first: u64): u64 {
return first if held.niche == 0;
val laid: u64 = held.niche as u64 - 1;
return first != 0 ? laid : 1 - laid;
}
#! Whether a value of the layout is never null in its first word: a reference, a
#! trait reference, a function value, or a struct whose one field is one, as
#! `box<T>`, which a union holding it beside an empty field takes as its tag.
#! @param this The compiler.
#! @param held The layout.
#! @returns Whether it is.
pub def lowerer::never_null(&mut this, held: &layout): bool {
if held.kind == lk::record && held.count == 1 {
val field: slot_field = this.program.fields[held.fields as u64];
val inner := this.layout_at(field.layout);
return field.offset == 0 && inner.size == held.size && this.never_null(&inner);
}
return held.kind == lk::reference || held.kind == lk::trait_reference || held.kind == lk::function;
}
#! Whether a value of the layout is held in memory, at an address, rather than
#! as words: a fixed array, a struct, or a union.
#! @param held The layout.
#! @returns Whether it is.
pub def in_memory(held: &layout): bool {
return held.kind == lk::fixed || held.kind == lk::record || held.kind == lk::variant;
}
#! Whether a function giving a value of the layout returns it in memory, at an
#! address its call gives: one held in memory that has bytes. A struct of no
#! fields is returned as nothing.
#! @param held The layout.
#! @returns Whether it is.
pub def returned_in_memory(held: &layout): bool {
return in_memory(held) && held.size != 0;
}
#! How many words a value of the layout is, as a value of the code: none for
#! `void` and what is held in memory.
#! @param held The layout.
#! @returns How many.
pub def word_count(held: &layout): u32 {
return match held.kind {
lk::empty, lk::fixed, lk::record, lk::variant => 0,
lk::reference => 1,
lk::trait_reference, lk::function => 2,
else => 1
};
}
#! The type of a word of a value of the layout, as a value of the code.
#! @param held The layout.
#! @returns A real for a float, and a word for anything else.
pub def word_type(held: &layout): vt {
return held.kind == lk::floating ? vt::real : vt::word;
}
#! The signature of calls through a function type: the layout of each of its
#! parameters, where each begins, and its result's layout.
#! @param this The compiler.
#! @param kind The function type.
#! @returns The signature's index.
pub def lowerer::signature_of(&mut this, kind: u32): u32 {
val plain := this.checker.unalias(kind);
if this.signature_ids.get(&plain) is some(got) {
return got;
}
var params := vector::<u32>::new();
var offsets := vector::<u64>::new();
var size: u64 = 0;
for i in 0..this.checker.types.part_count(plain) {
val each := this.layout_of(this.checker.types.part_at(plain, i as u32));
params.append(each);
offsets.append(size);
size += this.layout_at(each).frame;
}
val result := this.layout_of(this.checker.types.first_of(plain));
val index := this.program.signatures.length as u32;
this.program.signatures.append(signature {
params = move(&mut params),
offsets = move(&mut offsets),
size = size,
result = result
});
this.signature_ids.set(plain, index);
return index;
}
#! The types of the values the code of a function of the signature takes: the
#! words of each parameter, or the address of one held in memory.
#! @param this The compiler.
#! @param index The signature.
#! @returns The types.
pub def lowerer::param_types(&this, index: u32): vector<vt> {
var made := vector::<vt>::new();
val held := &this.program.signatures[index];
for &each in held.params {
val shape := this.layout_at(each);
if in_memory(&shape) {
made.append(vt::word);
continue;
}
for _ in 0..word_count(&shape) {
made.append(word_type(&shape));
}
}
return made;
}
+64
View File
@@ -0,0 +1,64 @@
#! @file nodes.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the walk of a node of the syntax tree and the nodes under it, which
#! the scans lowering makes of what a body names share.
import sakura::analyzer;
module sakura::compiler;
#! A walk of a node of the syntax tree and the nodes under it, each before the
#! nodes it holds. The walk goes under a node only where it is asked to, so a
#! scan may pass over what a node holds, or go under only some of it.
pub struct node_walk {
var todo: vector<u32>; #! The nodes yet to be given, the next last, 0 standing for one absent.
}
#! Walks a node and the nodes under it.
#! @param node The node, or 0 for none.
#! @returns The walk.
pub def node_walk::new(node: u32): node_walk {
var made := node_walk { todo = vector::<u32>::new() };
made.todo.append(node);
return made;
}
#! Whether the walk has another node to give, passing over those absent.
#! @param this The walk.
#! @returns Whether it has.
pub def node_walk::more(&mut this): bool {
# It answers from within the loop, which keeps it small enough to be inlined.
while this.todo.length != 0 {
return true if this.todo.last() != 0;
this.todo.truncate();
}
return false;
}
#! Gives the next node, once `more` says there is one.
#! @param this The walk.
#! @returns The node.
pub def node_walk::next(&mut this): u32 {
val at: u32 = this.todo.last();
this.todo.truncate();
return at;
}
#! Goes under a node: the nodes it holds are given next, the last its shape
#! lists first.
#! @param this The walk.
#! @param tree The syntax tree.
#! @param node The node.
pub def node_walk::enter(&mut this, tree: &syntax, node: u32): void {
tree.children(node, &mut this.todo);
}
#! Goes under a node to one node it holds only, which is given next.
#! @param this The walk.
#! @param node The node held, or 0 for none.
pub def node_walk::add(&mut this, node: u32): void {
this.todo.append(node);
}
+393
View File
@@ -0,0 +1,393 @@
#! @file alias.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains alias analysis, which the passes of the optimizer ask whether an
#! instruction writing memory may write what a read reads, or what they know
#! memory holds. An access touches a region: bytes from a base, which its
#! address steps from by constants, as `add`s of constants and the steps loads
#! and stores take give them. An address stepping by what is not known from one
#! within a cell, the globals, a datum, or memory made, as indexing an array
#! does, is anywhere within the same.
#!
#! Two regions may hold a byte in common but where it is known they do not.
#! Regions of one base, of one cell, or both of the globals, do not where their
#! bytes do not overlap, and two cells do not. A cell that is not escaped, its
#! address going nowhere but to the instructions reading, writing, copying, and
#! clearing it, and to calls as where to write what they return, as the memory
#! pass finds, is touched by nothing reaching through another address, nor by
#! a call, or anything else writing memory the code does not name, but where it
#! writes what it returns. No cell is what an address the function was given,
#! the globals, or the heap holds, none of which is the frame. Memory a `box` or
#! `allocate` made is not what an address the function was given, the globals,
#! other memory made so, or an address read before it was made holds, as none
#! could point at what was not yet there. And nothing writes a datum.
#!
#! Sakura has no rule that memory of one type is not read or written as
#! another: std and the runtime reach through pointers cast to other types, as
#! `float_bits` is written as an `f64` and read as a `u64`, and loads and stores say only how they read and
#! write, not what they reach. So no region is told apart from another by the
#! type of what it holds.
module sakura::compiler;
#! What the base of a region is.
pub enum base_kind : u8 {
other, #! A value nothing more is known of.
cell, #! The address of a cell of the frame.
global, #! The start of the globals, a global's address stepping from it.
datum, #! The address of a datum, which nothing writes.
fresh, #! The address of memory a `box` or `allocate` made.
given, #! A parameter of the entry: an address the function was given.
loaded, #! An address read from memory.
}
#! What a region's size is where it is not known.
pub const unknown_size: u64 = 0xFFFFFFFFFFFFFFFF;
#! The bytes an access touches: a base, how far past it they begin, and how
#! many there are.
pub struct region {
pub var base: u32; #! The value the address steps from by constants.
pub var offset: u64; #! How far past the base the bytes begin, wrapping as addresses do; for a global, past the start of the globals.
pub var size: u64; #! How many bytes, or `unknown_size`.
pub var kind: base_kind; #! What the base is.
pub var cell: u32; #! The cell, where the base is a cell's address.
}
#! What alias analysis knows of code: which cell each value is the address
#! of, which cells are escaped, the bytes each call writes what it returns to,
#! and which block dominates which, where that is known.
pub struct aliases {
var addresses: cell_table; #! Which cell each value is the address of.
var escaped: vector<bool>; #! Whether each cell is escaped.
var writes: vector<u64>; #! Of each instruction, the bytes a call writes what it returns to at its last operand, or 0.
var idom: vector<u32>; #! The immediate dominator of each block, or nothing where it is not known.
var found: bool; #! Whether which cells are escaped is found.
}
#! Finds what alias analysis knows of the code.
#! @param this The code.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @param idom The immediate dominator of each block, or nothing, where
#! memory made after an address was read is not told apart
#! from what it points at, but within a block.
#! @returns What it knows, in scratch memory.
pub def code::aliases(&this, writes: span<u64>, idom: span<u32>): aliases {
var made := this.aliases_unfound(writes, idom);
made.find_escaped(this);
return made;
}
#! Begins what alias analysis knows of the code, but for which cells are
#! escaped, which `aliases::find_escaped` finds before anything asks whether
#! one region may hold a byte of another, and before anything changes which
#! cells are escaped.
#! @param this The code.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @param idom The immediate dominator of each block, or nothing.
#! @returns What it knows, in scratch memory.
pub def code::aliases_unfound(&this, writes: span<u64>, idom: span<u32>): aliases {
var made := aliases {
escaped = vector::<bool>::new(scratch()),
writes = vector::<u64>::new(scratch()),
idom = vector::<u32>::new(scratch())
};
made.writes.extend(writes);
made.idom.extend(idom);
return made;
}
#! Finds which cells are escaped, where that is not found yet.
#! @param this What alias analysis knows.
#! @param body The code.
pub def aliases::find_escaped(&mut this, body: &code): void {
return if this.found;
this.found = true;
this.addresses = body.cell_table();
this.escaped = body.escaped_cells(&this.addresses, this.writes.view());
}
#! Which cells are escaped: their address goes anywhere but to the instructions
#! reading, writing, copying, and clearing them, to `ret`, or to a call as
#! where to write what it returns.
#! @param this The code.
#! @param addresses Which cell each value is the address of.
#! @param writes Of each instruction, the bytes a call writes what it
#! returns to at its last operand, or 0.
#! @returns Whether each cell is, in scratch memory.
pub def code::escaped_cells(&this, addresses: &cell_table, writes: span<u64>): vector<bool> {
var escaped := vector::<bool>::new(scratch());
escaped.resize(this.cells.length);
return escaped if !addresses.any;
var walk := this.walk_all();
var reads := this.reader();
while walk.more() {
val at := walk.next();
val held := &this.insts[at];
reads.start(at);
while reads.more() {
val cell := addresses.cell(reads.next());
continue if cell == 0;
# A cell's address an edge gives escapes.
val i := reads.operand();
val direct := i != no_operand && match held.kind {
op::load, op::store, op::clear => i == 0,
op::copy => i < 2,
op::ret => true,
else => i + 1 == held.argc && (at as u64) < writes.length && writes[at] != 0
};
if !direct {
escaped[cell - 1] = true;
}
}
}
return escaped;
}
#! The region an access touches.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param index The `load`, `store`, `copy`, or `clear`.
#! @param operand Which address: of a `copy`, 0 for where it writes, 1 for
#! where it reads.
#! @returns The region.
pub def aliases::region_of(&this, body: &code, index: u32, operand: u32): region {
val held: inst = body.insts[index];
if held.kind == op::load || held.kind == op::store {
val how: access = held.aux as access;
return this.region_at(body, body.arg(index, 0), held.imm, how == access::bytes ? unknown_size : how.width());
}
return this.region_at(body, body.arg(index, operand), 0, held.imm);
}
#! The region of bytes past an address.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param address The address.
#! @param offset How far past it the bytes begin.
#! @param size How many there are, or `unknown_size`.
#! @returns The region.
pub def aliases::region_at(&this, body: &code, address: u32, offset: u64, size: u64): region {
var made := region { offset = offset, size = size };
this.find_base(body, address, &mut made, 0);
return made;
}
#! Finds the base of a region at an address, and how far past it the address
#! is, adding that to the region's offset. An address stepping by what is not
#! known from one within a cell, the globals, a datum, or memory made, and from
#! nothing else such, is somewhere within the same, as indexing an array is,
#! so the region is any of it.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param address The address.
#! @param made The region.
#! @param depth How many such steps were followed to the address.
def aliases::find_base(&this, body: &code, address: u32, made: &mut region, depth: u32): void {
var at := address;
var steps := 0;
while steps < 8 {
val index := body.defining(at);
break if index == 0 || body.insts[index].kind != op::add;
var step: u64 = 0;
if body.word_constant(body.arg(index, 1), &mut step) {
at = body.arg(index, 0);
} else if body.word_constant(body.arg(index, 0), &mut step) {
at = body.arg(index, 1);
} else {
break if depth >= 2;
var one := region {};
var two := region {};
this.find_base(body, body.arg(index, 0), &mut one, depth + 1);
this.find_base(body, body.arg(index, 1), &mut two, depth + 1);
break if one.within_object() == two.within_object();
val inside: region = one.within_object() ? one : two;
made.base = inside.base;
made.kind = inside.kind;
made.cell = inside.cell;
made.offset = 0;
made.size = unknown_size;
return;
}
made.offset = made.offset + step;
steps++;
}
made.base = at;
val held: origin = body.origins[at];
if held.param {
made.kind = held.from == 0 ? base_kind::given : base_kind::other;
return;
}
val from: inst = body.insts[held.from];
match from.kind {
op::cell => {
made.kind = base_kind::cell;
made.cell = from.aux;
}
op::global => {
made.kind = base_kind::global;
made.offset = made.offset + from.imm;
}
op::datum => made.kind = base_kind::datum;
op::allocate => made.kind = base_kind::fresh;
op::load => made.kind = base_kind::loaded;
else => made.kind = base_kind::other;
}
}
#! Whether a region's base is within a cell, the globals, a datum, or memory
#! made, which a number never is.
#! @param this The region.
#! @returns Whether it is.
def region::within_object(&this): bool {
return match this.kind {
base_kind::cell, base_kind::global, base_kind::datum, base_kind::fresh => true,
else => false
};
}
#! Whether two regions may hold a byte in common, as the file says.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param a One region.
#! @param b The other.
#! @returns Whether they may.
pub def aliases::may_alias(&this, body: &code, a: &region, b: &region): bool {
return false if a.size == 0 || b.size == 0;
return false if a.kind == base_kind::datum || b.kind == base_kind::datum;
if a.kind == base_kind::cell && b.kind == base_kind::cell {
return a.cell == b.cell && overlaps(a, b);
}
if a.kind == base_kind::cell {
return this.escaped[a.cell] && !b.outside_frame();
}
if b.kind == base_kind::cell {
return this.escaped[b.cell] && !a.outside_frame();
}
if a.kind == base_kind::global && b.kind == base_kind::global {
return overlaps(a, b);
}
return overlaps(a, b) if a.base == b.base;
if a.kind == base_kind::fresh {
return this.may_point_at(body, b, a.base);
}
if b.kind == base_kind::fresh {
return this.may_point_at(body, a, b.base);
}
return true;
}
#! Whether a region may hold bytes of memory a `box` or `allocate` made, its
#! base being other than that memory's address.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param other The region.
#! @param fresh The address of the memory made.
#! @returns Whether it may.
def aliases::may_point_at(&this, body: &code, other: &region, fresh: u32): bool {
return match other.kind {
base_kind::fresh, base_kind::given, base_kind::global => false,
base_kind::loaded => !this.read_before(body, other.base, fresh),
else => true
};
}
#! Whether an address was read before memory was made, wherever both are
#! known: the read is before the `box` or `allocate` in its block, or in a
#! block dominating its block.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param loaded The address read.
#! @param fresh The address of the memory made.
#! @returns Whether it was.
def aliases::read_before(&this, body: &code, loaded: u32, fresh: u32): bool {
val read := body.defining(loaded);
val made := body.defining(fresh);
val at: u32 = body.insts[read].block;
val home: u32 = body.insts[made].block;
if at == home {
var walk := body.walk(at);
while walk.more() {
val each := walk.next();
return true if each == read;
return false if each == made;
}
return false;
}
return (home as u64) < this.idom.length && dominates(&this.idom, at, home);
}
#! Whether the bytes of two regions of one base overlap.
#! @param a One region.
#! @param b The other.
#! @returns Whether they do.
def overlaps(a: &region, b: &region): bool {
return b.offset - a.offset < a.size || a.offset - b.offset < b.size;
}
#! Whether a region is outside the frame, so within no cell: the globals, the
#! heap, or what an address the function was given points at.
#! @param this The region.
#! @returns Whether it is.
def region::outside_frame(&this): bool {
return this.kind == base_kind::global || this.kind == base_kind::fresh || this.kind == base_kind::given;
}
#! What an instruction writes, as alias analysis tells it.
pub struct writing {
pub var place: region; #! The region a store, copy, or clear writes, or that a call writes what it returns to, or none of no bytes.
pub var wide: bool; #! Whether it may write any memory but an unescaped cell's, as a call does.
}
#! What an instruction writes: a store, copy, or clear its region; a call or
#! anything else writing memory the code does not name any but an unescaped
#! cell's, and where it writes what it returns; and anything else nothing.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param index The instruction.
#! @returns What it writes.
pub def aliases::writes_of(&this, body: &code, index: u32): writing {
val held: inst = body.insts[index];
var made := writing {};
if held.kind == op::store || held.kind == op::clear || held.kind == op::copy {
made.place = this.region_of(body, index, 0);
return made;
}
return made if held.kind == op::load || (held.kind.traits() & op_write) == 0;
made.wide = true;
val result: u64 = (index as u64) < this.writes.length ? this.writes[index] : 0;
if result != 0 {
made.place = this.region_at(body, body.arg(index, held.argc - 1), 0, result);
}
return made;
}
#! Whether what an instruction writes may hold a byte of a region.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param written What the instruction writes.
#! @param place The region.
#! @returns Whether it may.
pub def aliases::touches(&this, body: &code, written: &writing, place: &region): bool {
if written.wide {
return false if place.kind == base_kind::datum;
return true if place.kind != base_kind::cell || this.escaped[place.cell];
}
return this.may_alias(body, &written.place, place);
}
#! Whether an instruction may write a byte of a region.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param index The instruction.
#! @param place The region.
#! @returns Whether it may.
pub def aliases::clobbers(&this, body: &code, index: u32, place: &region): bool {
val written := this.writes_of(body, index);
return this.touches(body, &written, place);
}
File diff suppressed because it is too large. Load diff
+224
View File
@@ -0,0 +1,224 @@
#! @file dead.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the second pass of the optimizer, which takes out what nothing
#! needs: an instruction whose results nothing reads, where taking it out
#! changes nothing else, a parameter of a block that nothing reads, and a
#! cell whose address nothing takes, which leaves the frame smaller. What
#! is needed is found from what must stay, as a store or a call: what it
#! reads is needed, then what that reads in turn, and a parameter needed
#! needs the argument each edge into its block gives it. So a value carried
#! around a loop only to be carried around again goes too.
module sakura::compiler;
#! Takes out what nothing needs, as the file says.
#! @param this The code.
#! @returns Whether anything changed.
pub def code::remove_dead(&mut this): bool {
var live := worklist::new(this.origins.length, scratch());
var reached := vector::<bool>::new(scratch());
reached.resize(this.insts.length);
# What must stay needs what it reads, but for writes to cells nothing reads.
val read := this.read_cells();
var walk := this.walk_all();
while walk.more() {
val at := walk.next();
if !this.removable(at) && !this.unread_write(at, &read) {
reached[at] = true;
this.need_operands(at, &mut live);
}
}
# The entry's parameters are what the function takes, which stay.
for &each in this.blocks[0].params {
live.push_new(each);
}
while !live.is_empty {
val value := live.pop();
val held: origin = this.origins[value];
if held.param {
for &edge in this.blocks[held.from].preds {
val given: u32 = this.edges[edge].args[held.index];
live.push_new(given);
}
continue;
}
if !reached[held.from] {
reached[held.from] = true;
this.need_operands(held.from, &mut live);
}
}
var done := rewrite::new();
var sweep := this.walk_all();
while sweep.more() {
val at := sweep.next();
if !reached[at] {
done.remove(at);
}
}
this.apply(&done);
# Each parameter nothing needs goes, with what each edge gives it.
var changed := done.changed;
var keeps := vector::<bool>::new(scratch());
for b in 1..this.blocks.length {
continue if this.blocks[b].gone;
keeps.clear();
for &param in this.blocks[b].params.view() {
keeps.append(live.has(param));
}
continue if !keeps.view().contains(&false);
changed = true;
this.drop_params(b as u32, keeps.view());
}
return this.drop_cells() || changed;
}
#! Takes out the cells whose address nothing takes, numbering those left in
#! the order they were.
#! @param this The code.
#! @returns Whether any was taken out.
def code::drop_cells(&mut this): bool {
return false if this.cells.length == 0;
var used := vector::<bool>::new(scratch());
used.resize(this.cells.length);
var walk := this.walk_all();
while walk.more() {
val at := walk.next();
if this.insts[at].kind == op::cell {
used[this.insts[at].aux] = true;
}
}
var renumbered := vector::<u32>::new(scratch());
var kept := vector::<cell>::new();
for c in 0..this.cells.length {
renumbered.append(kept.length as u32);
if used[c] {
kept.append(this.cells[c]);
}
}
return false if kept.length == this.cells.length;
var again := this.walk_all();
while again.more() {
val at := again.next();
if this.insts[at].kind == op::cell {
this.insts[at].aux = renumbered[this.insts[at].aux];
}
}
this.cells = move(&mut kept);
for i in 0..this.variables.length {
val held: u32 = this.variables[i].cell;
continue if held == 0;
this.variables[i].cell = used[held - 1] ? renumbered[held - 1] + 1 : 0;
}
return true;
}
#! Which cells something reads: by loading from them, copying out of them,
#! or anything else their address is given to, which may read them.
#! @param this The code.
#! @returns Whether each cell is read.
def code::read_cells(&this): vector<bool> {
var read := vector::<bool>::new(scratch());
return read if this.cells.length == 0;
read.resize(this.cells.length);
var walk := this.walk_all();
var reads := this.reader();
while walk.more() {
val at := walk.next();
# Writing a cell at its address does not read it.
val kind := this.insts[at].kind;
val writes := kind == op::store || kind == op::clear || kind == op::copy;
reads.start(at);
while reads.more() {
val cell := this.cell_of(reads.next());
if cell != no_cell && !(writes && reads.operand() == 0) {
read[cell] = true;
}
}
}
return read;
}
#! Whether an instruction only writes a cell nothing reads, which goes: a store
#! or a clear of it, or a copy into it from an address that cannot be null.
#! @param this The code.
#! @param index The instruction.
#! @param read Which cells something reads.
#! @returns Whether it does.
def code::unread_write(&this, index: u32, read: &vector<bool>): bool {
val held: inst = this.insts[index];
return false if held.kind != op::store && held.kind != op::clear && held.kind != op::copy;
val cell := this.cell_of(this.arg(index, 0));
return false if cell == no_cell || read[cell];
return held.kind != op::copy || this.checked_address(index, this.arg(index, 1));
}
#! Whether an address an instruction reads cannot be null there: one never
#! zero, or a step from a pointer a check before it in its block found not
#! null.
#! @param this The code.
#! @param index The instruction.
#! @param address The address.
#! @returns Whether it cannot.
pub def code::checked_address(&this, index: u32, address: u32): bool {
return true if this.never_zero(address);
var base := address;
var steps := 0;
while steps < 8 {
val made := this.defining(base);
break if made == 0 || this.insts[made].kind != op::add;
base = this.arg(made, 0);
steps++;
}
var walk := this.walk(this.insts[index].block);
while walk.more() {
val at := walk.next();
break if at == index;
val held := &this.insts[at];
if held.kind == op::check && held.aux == fault::null_reference as u32 && this.arg(at, 0) == base {
return true;
}
}
return false;
}
#! Marks what an instruction reads as needed.
#! @param this The code.
#! @param index The instruction.
#! @param live The values needed, those newly needed waiting for their own
#! needs to be marked.
def code::need_operands(&this, index: u32, live: &mut worklist): void {
val held := &this.insts[index];
for i in 0..held.argc {
live.push_new(this.operands[held.args as u64 + i as u64]);
}
}
#! Whether an instruction may be taken out where nothing reads what it gives:
#! one that only works out its results, a division by a constant other than
#! zero, which never stops the program, and a read of an address never zero.
#! @param this The code.
#! @param index The instruction.
#! @returns Whether it may.
pub def code::removable(&this, index: u32): bool {
val held: inst = this.insts[index];
return false if held.count == 0 || held.kind.ends();
return true if (held.kind.traits() & op_pure) != 0;
match held.kind {
op::divs, op::divu, op::rems, op::remu => {
var bits: u64 = 0;
return this.word_constant(this.arg(index, 1), &mut bits) && bits != 0;
}
op::load => return this.never_zero(this.arg(index, 0));
else => return false;
}
return false;
}
+592
View File
@@ -0,0 +1,592 @@
#! @file edit.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what the passes of the optimizer share to change code: a rewrite,
#! which gathers the values a pass replaces and the instructions it takes out
#! and applies them in one sweep once the pass is done, and the changes made
#! in place, as an instruction becoming another that gives the same values, an
#! instruction put first in a block or before another, and a branch whose ways
#! out are swapped. Also what the passes ask of code: the constant a value is,
#! whether a value is never zero, and how often each value is used.
module sakura::compiler;
#! What a pass changes as it goes: the value each use of another reads instead,
#! and the instructions taken out, which `code::apply` applies in one sweep.
pub struct rewrite {
var forward: vector<u32>; #! The value read instead of each value, or 0.
var removed: vector<bool>; #! Whether each instruction is taken out.
var changed: bool; #! Whether the pass changed anything.
}
#! Makes a rewrite that changes nothing yet.
#! @returns The rewrite.
pub def rewrite::new(): rewrite {
return rewrite { forward = vector::<u32>::new(scratch()), removed = vector::<bool>::new(scratch()) };
}
#! The value read where a value is, following each value replaced to what
#! replaces it.
#! @param this The rewrite.
#! @param value The value.
#! @returns The value read.
pub def rewrite::resolve(&this, value: u32): u32 {
return follow_replaced(this.forward.view().data, this.forward.length, value);
}
#! The value read where a value is, following each value replaced to what
#! replaces it, until one not replaced, or a million steps, past which the
#! replacements are taken to go round.
#! @param forward The value replacing each value, by index, or 0 where it is
#! not replaced.
#! @param count How many values `forward` holds, past which none is
#! replaced.
#! @param value The value.
#! @returns The value read.
pub def follow_replaced(forward: *u32, count: u64, value: u32): u32 {
var at := value;
var steps := 0;
while (at as u64) < count && forward[at] != 0 && steps < 1000000 {
at = forward[at];
steps++;
}
return at;
}
#! Makes each use of a value read another.
#! @param this The rewrite.
#! @param from The value replaced.
#! @param to The value read instead.
pub def rewrite::replace(&mut this, from: u32, to: u32): void {
return if from == to || this.resolve(to) == from;
if this.forward.length <= from as u64 {
this.forward.resize(from as u64 + 1);
}
this.forward[from] = to;
this.changed = true;
}
#! Takes an instruction out of its block.
#! @param this The rewrite.
#! @param index The instruction.
pub def rewrite::remove(&mut this, index: u32): void {
if this.removed.length <= index as u64 {
this.removed.resize(index as u64 + 1);
}
this.removed[index] = true;
this.changed = true;
}
#! Whether an instruction is taken out.
#! @param this The rewrite.
#! @param index The instruction.
#! @returns Whether it is.
pub def rewrite::is_removed(&this, index: u32): bool {
return (index as u64) < this.removed.length && this.removed[index];
}
#! Applies a rewrite: each operand and argument reads what replaces the value
#! it named, and the instructions taken out leave their blocks.
#! @param this The code.
#! @param done The rewrite.
pub def code::apply(&mut this, done: &rewrite): void {
val count := done.forward.length;
if count != 0 {
# Read and written where the elements are, as this runs over every operand.
val forward := done.forward.view().data;
val operands := this.operands.slice().data;
for i in 0..this.operands.length {
operands[i] = follow_replaced(forward, count, operands[i]);
}
for e in 0..this.edges.length {
val args := this.edges[e].args.slice().data;
for a in 0..this.edges[e].args.length {
args[a] = follow_replaced(forward, count, args[a]);
}
}
# A variable takes what replaces a value it took.
for i in 0..this.bindings.length {
this.bindings[i].value = follow_replaced(forward, count, this.bindings[i].value);
}
}
this.take_out(done);
}
#! Takes the instructions a rewrite takes out out of their blocks.
#! @param this The code.
#! @param done The rewrite.
pub def code::take_out(&mut this, done: &rewrite): void {
return if done.removed.length == 0;
# Only the blocks holding what is taken out are linked anew.
var touched := vector::<bool>::new(scratch());
touched.resize(this.blocks.length);
for i in 0..done.removed.length {
if done.removed[i] && (this.insts[i].block as u64) < touched.length {
touched[this.insts[i].block] = true;
}
}
for b in 0..this.blocks.length {
continue if this.blocks[b].gone || !touched[b];
var walk := this.walk(b as u32);
var kept: u32 = 0;
this.blocks[b].first = 0;
this.blocks[b].last = 0;
while walk.more() {
val at := walk.next();
continue if done.is_removed(at);
if kept == 0 {
this.blocks[b].first = at;
} else {
this.insts[kept].next = at;
}
kept = at;
}
if kept != 0 {
this.insts[kept].next = 0;
}
this.blocks[b].last = kept;
}
}
#! The instruction giving a value, or 0 for one a block takes.
#! @param this The code.
#! @param value The value.
#! @returns The instruction.
pub def code::defining(&this, value: u32): u32 {
return 0 if value == 0 || (value as u64) >= this.origins.length;
val held: origin = this.origins[value];
return held.param ? 0 : held.from;
}
#! The block a value is made in: the block taking it, or holding the
#! instruction giving it.
#! @param this The code.
#! @param value The value.
#! @returns The block.
pub def code::home_of(&this, value: u32): u32 {
val held: origin = this.origins[value];
return held.param ? held.from : this.insts[held.from].block;
}
#! What `code::cell_of` gives for a value that is the address of no cell.
pub const no_cell: u32 = 0xFFFFFFFF;
#! The cell a value is the address of, as the instruction giving it says.
#! @param this The code.
#! @param value The value.
#! @returns The cell, or `no_cell`.
pub def code::cell_of(&this, value: u32): u32 {
val index := this.defining(value);
return no_cell if index == 0 || this.insts[index].kind != op::cell;
return this.insts[index].aux;
}
#! Which cell each value of code is the address of, found once from the `cell`
#! instructions of the blocks not removed, for a pass that asks it of many
#! values.
pub struct cell_table {
var of: vector<u32>; #! One more than the cell each value is the address of, or 0.
var any: bool; #! Whether any value is.
}
#! Finds which cell each value is the address of.
#! @param this The code.
#! @returns The table, in scratch memory.
pub def code::cell_table(&this): cell_table {
var made := cell_table { of = vector::<u32>::new(scratch()) };
# Code with no cells has no value that is the address of one.
return made if this.cells.length == 0;
made.of.resize(this.origins.length);
var walk := this.walk_all();
while walk.more() {
val held := &this.insts[walk.next()];
if held.kind == op::cell {
made.of[held.result] = held.aux + 1;
made.any = true;
}
}
return made;
}
#! The cell a value is the address of, as the table found it.
#! @param this The table.
#! @param value The value.
#! @returns One more than the cell, or 0, as for a value made after the table.
pub def cell_table::cell(&this, value: u32): u32 {
return (value as u64) < this.of.length ? this.of[value] : 0;
}
#! Whether a value is a constant word, and its bits.
#! @param this The code.
#! @param value The value.
#! @param bits Where its bits are written, where it is one.
#! @returns Whether it is.
pub def code::word_constant(&this, value: u32, bits: &mut u64): bool {
val index := this.defining(value);
return false if index == 0 || this.insts[index].kind != op::iconst;
bits = this.insts[index].imm;
return true;
}
#! Whether a value is a constant real, and its bits.
#! @param this The code.
#! @param value The value.
#! @param bits Where the bits of the `f64` are written, where it is one.
#! @returns Whether it is.
pub def code::real_constant(&this, value: u32, bits: &mut u64): bool {
val index := this.defining(value);
return false if index == 0 || this.insts[index].kind != op::fconst;
bits = this.insts[index].imm;
return true;
}
#! The type of the constant a value is, and its bits, read where the
#! instruction making it lies, taken out of its block or not, as a binding
#! naming the value keeps the constant once that instruction goes.
#! @param this The code.
#! @param value The value.
#! @param bits Where its bits are written, where it is one.
#! @returns Its type, or `none` where it is no constant.
pub def code::constant_kind(&this, value: u32, bits: &mut u64): vt {
return vt::word if this.word_constant(value, bits);
return vt::real if this.real_constant(value, bits);
return vt::none;
}
#! Whether a word is never zero: the address of a cell, a global, or a datum,
#! or a small step past one.
#! @param this The code.
#! @param value The word.
#! @returns Whether it is never zero.
pub def code::never_zero(&this, value: u32): bool {
var at := value;
var steps := 0;
while steps < 8 {
val index := this.defining(at);
return false if index == 0;
val held: inst = this.insts[index];
match held.kind {
op::cell, op::global, op::datum => return true;
op::iconst => return held.imm != 0;
op::add => {
var step: u64 = 0;
return false if !this.word_constant(this.arg(index, 1), &mut step) || step >= 0x100000000u;
at = this.arg(index, 0);
}
else => return false;
}
steps++;
}
return false;
}
#! How many times each value is read, by operands and by the arguments of
#! edges, in the blocks not removed.
#! @param this The code.
#! @returns The count of each value.
pub def code::use_counts(&this): vector<u32> {
var counts := vector::<u32>::new(scratch());
counts.resize(this.origins.length);
var walk := this.walk_all();
var reads := this.reader();
while walk.more() {
reads.start(walk.next());
while reads.more() {
val value := reads.next();
counts[value] = counts[value] + 1;
}
}
return counts;
}
#! Makes an instruction another that gives the same values, in place, so what
#! reads them reads what it gives now.
#! @param this The code.
#! @param index The instruction.
#! @param kind What it does now.
#! @param args Its operands now.
#! @param aux What its kind says `aux` holds.
#! @param imm What its kind says `imm` holds.
pub def code::become(&mut this, index: u32, kind: op, args: span<u32>, aux: u32, imm: u64): void {
# Operands fit where its old ones were, or else go after every other.
var first: u32 = this.insts[index].args;
if args.length > this.insts[index].argc as u64 {
first = this.operands.length as u32;
this.operands.resize(this.operands.length + args.length);
}
for i in 0..args.length {
this.operands[first as u64 + i] = args[i];
}
this.insts[index].kind = kind;
this.insts[index].args = first;
this.insts[index].argc = args.length as u32;
this.insts[index].aux = aux;
this.insts[index].imm = imm;
}
#! Makes an instruction the constant word it gives.
#! @param this The code.
#! @param index The instruction.
#! @param bits The word's bits.
pub def code::become_word(&mut this, index: u32, bits: u64): void {
this.become(index, op::iconst, span::<u32>::empty(), 0, bits);
this.origins[this.insts[index].result].kind = vt::word;
}
#! Makes an instruction the constant real it gives.
#! @param this The code.
#! @param index The instruction.
#! @param bits The bits of the `f64` it is.
pub def code::become_real(&mut this, index: u32, bits: u64): void {
this.become(index, op::fconst, span::<u32>::empty(), 0, bits);
}
#! Adds an instruction, in no block yet.
#! @param this The code.
#! @param kind What it does.
#! @param args Its operands.
#! @param gives The types of its results, in order.
#! @param aux What its kind says `aux` holds.
#! @param imm What its kind says `imm` holds.
#! @param pos Where in the source it is from.
#! @param site One more than the site of the function it was inlined from,
#! or 0.
#! @returns Its index.
pub def code::detached(
&mut this,
kind: op,
args: span<u32>,
gives: span<vt>,
aux: u32,
imm: u64,
pos: u64,
site: u32
): u32 {
val index := this.insts.length as u32;
val first := this.operands.length as u32;
# Appended one by one, which is inlined, where `extend` is a call for each
# instruction.
for &each in args {
this.operands.append(each);
}
val result := this.origins.length as u32;
for i in 0..gives.length {
this.origins.append(origin { kind = gives[i], from = index, index = i as u32 });
}
this.insts.append(inst {
kind = kind,
count = gives.length as u8,
aux = aux,
imm = imm,
args = first,
argc = args.length as u32,
result = gives.length == 0 ? 0 : result,
at = pos,
site = site
});
return index;
}
#! Puts an instruction made in no block before another in its block.
#! @param this The code.
#! @param index The instruction.
#! @param before The instruction it goes before.
pub def code::link_before(&mut this, index: u32, before: u32): void {
val block: u32 = this.insts[before].block;
val prior := this.before(before);
this.insts[index].block = block;
this.insts[index].next = before;
if prior == 0 {
this.blocks[block].first = index;
} else {
this.insts[prior].next = index;
}
}
#! The instruction before another in its block.
#! @param this The code.
#! @param index The instruction, which its block holds.
#! @returns The instruction before it, or 0 where it is the first.
pub def code::before(&this, index: u32): u32 {
var prior: u32 = 0;
var walk := this.walk(this.insts[index].block);
while walk.more() {
val at := walk.next();
break if at == index;
prior = at;
}
return prior;
}
#! Puts an instruction made in no block after another in its block.
#! @param this The code.
#! @param index The instruction.
#! @param after The instruction it goes after.
pub def code::link_after(&mut this, index: u32, after: u32): void {
val block: u32 = this.insts[after].block;
this.insts[index].block = block;
this.insts[index].next = this.insts[after].next;
this.insts[after].next = index;
if this.blocks[block].last == after {
this.blocks[block].last = index;
}
}
#! A constant word, made first in the entry, where it stands before everything
#! that may read it.
#! @param this The code.
#! @param bits Its bits.
#! @returns The value.
pub def code::word_value(&mut this, bits: u64): u32 {
var gives: vt[1] = [vt::word];
val index := this.detached(op::iconst, span::<u32>::empty(), gives[0:1], 0, bits, 0, 0);
this.put_first(0, index);
return this.insts[index].result;
}
#! A constant real, made first in the entry.
#! @param this The code.
#! @param bits The bits of the `f64` it is.
#! @returns The value.
pub def code::real_value(&mut this, bits: u64): u32 {
var gives: vt[1] = [vt::real];
val index := this.detached(op::fconst, span::<u32>::empty(), gives[0:1], 0, bits, 0, 0);
this.put_first(0, index);
return this.insts[index].result;
}
#! The zero of a type of value, made first in the entry: the word 0, the real
#! 0, or a vector of zero bytes.
#! @param this The code.
#! @param kind The type.
#! @returns The value.
pub def code::zero_value(&mut this, kind: vt): u32 {
return this.real_value(0) if kind == vt::real;
return this.word_value(0) if !kind.lanes();
var gives: vt[1] = [kind];
val index := this.detached(op::vzero, span::<u32>::empty(), gives[0:1], 0, 0, 0, 0);
this.put_first(0, index);
return this.insts[index].result;
}
#! The zero of each type of value a pass asks for, each made once, as
#! `code::zero_value` makes it.
pub struct zero_values {
var held: u32[vt::count as u64]; #! The zero of each type made, or 0.
}
#! The zero of a type of value, made first in the entry the first time it is
#! asked for.
#! @param this The zeros.
#! @param body The code.
#! @param kind The type.
#! @returns The value.
pub def zero_values::of(&mut this, body: &mut code, kind: vt): u32 {
val at := kind as u64;
if this.held[at] == 0 {
this.held[at] = body.zero_value(kind);
}
return this.held[at];
}
#! Takes an edge out of the edges into its block.
#! @param this The code.
#! @param edge The edge.
pub def code::drop_pred(&mut this, edge: u32): void {
this.forget_order();
val target: u32 = this.edges[edge].target;
var kept := ids {};
for &each in this.blocks[target].preds {
if each != edge {
kept.append(each);
}
}
this.blocks[target].preds = move(&mut kept);
}
#! Takes out the parameters of a block that do not stay, with the argument each
#! edge into the block gives them, numbering those left in the order they were.
#! @param this The code.
#! @param block The block.
#! @param keeps Whether each of its parameters stays, by its position.
pub def code::drop_params(&mut this, block: u32, keeps: span<bool>): void {
var kept := ids {};
for p in 0..keeps.length {
continue if !keeps[p];
val param: u32 = this.blocks[block].params[p];
this.origins[param].index = kept.length as u32;
kept.append(param);
}
for &edge in this.blocks[block].preds.view() {
var args := ids {};
for p in 0..keeps.length {
if keeps[p] {
args.append(this.edges[edge].args[p]);
}
}
this.edges[edge].args = move(&mut args);
}
this.blocks[block].params = move(&mut kept);
}
#! Makes an instruction ending a block go along one of its edges only, as a
#! `jump`, taking the others out of the blocks they went to.
#! @param this The code.
#! @param index The instruction.
#! @param kept The edge it goes along.
pub def code::jump_only(&mut this, index: u32, kept: u32): void {
this.forget_order();
var outs := this.edges_of(index);
while outs.more() {
val edge := outs.next();
if edge != kept {
this.drop_pred(edge);
}
}
this.become(index, op::jump, span::<u32>::empty(), kept, 0);
}
#! Swaps where a `branch` goes, so it goes where it went where its condition
#! was zero where it is not, as a branch on a condition's opposite does.
#! @param this The code.
#! @param index The `branch`.
pub def code::swap_branch(&mut this, index: u32): void {
this.forget_order();
val one: u32 = this.insts[index].aux;
val two := one + 1;
val first: u32 = this.edges[one].target;
val second: u32 = this.edges[two].target;
var args := move(&mut this.edges[one].args);
this.edges[one].args = move(&mut this.edges[two].args);
this.edges[two].args = move(&mut args);
this.edges[one].target = second;
this.edges[two].target = first;
return if first == second;
for i in 0..this.blocks[first].preds.length {
if this.blocks[first].preds[i] == one {
this.blocks[first].preds[i] = two;
}
}
for i in 0..this.blocks[second].preds.length {
if this.blocks[second].preds[i] == two {
this.blocks[second].preds[i] = one;
}
}
}
#! How many instructions the code holds, in the blocks not removed.
#! @param this The code.
#! @returns How many.
pub def code::size(&this): u32 {
var count: u32 = 0;
var walk := this.walk_all();
while walk.more() {
walk.next();
count++;
}
return count;
}
File diff suppressed because it is too large. Load diff
+985
View File
@@ -0,0 +1,985 @@
#! @file loops.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the ninth pass of the optimizer, which works on loops. A loop is
#! natural: its header dominates each block whose edge goes back to it, and it
#! holds the blocks from which those are reached without passing the header.
#!
#! A loop whose header asks whether to go round again, where no block going
#! back to it asks so too, is rotated: the header's code is copied into a guard
#! before the loop, which goes into it or past it as the header would have the
#! first time, and the header itself moves to the bottom, asking each time
#! round whether to go round again. Its edge back to the block after it is then
#! the loop's only jump. What the header made and the loop read is what the
#! block after it takes, from the guard's copy or from the header, as is what
#! it made and code past the loop read, where that is past the way out.
#!
#! Then what each loop works out the same each time round moves into the block
#! before it, its preheader, which is made where the loop has none: what only
#! works out its value from what is made outside the loop, and cannot stop the
#! program; a read of memory nothing in the loop may write, as alias analysis
#! tells, through an address read or written through, or checked, before the
#! loop; and a check of what is made outside the loop, or such a read through
#! an address that may be null, where it runs each time the loop is gone into
#! before anything the program would be seen to do in it, so that it stops the
#! program where it would have, and only where the loop is gone into. Inner
#! loops go first, so what moves out of one may move out of the loop holding it
#! in turn.
import std::containers;
module sakura::compiler;
#! What stands for no loop.
const no_loop: u32 = 0xFFFFFFFF;
#! The most instructions a header copied into a guard may hold, but for its
#! constants and the branch ending it.
const rotate_limit: u32 = 12;
#! The most loops of one function rotated, past which the rest stay as they
#! are.
const rotate_most: u32 = 256;
#! The natural loops of code. Two loops hold no block in common, or one holds
#! the other.
struct loop_nest {
var headers: vector<u32>; #! The block heading each loop, those holding fewer blocks first, so each comes before the loops holding it.
var parents: vector<u32>; #! The loop most nearly holding each loop, or `no_loop`.
var members: runs<u32>; #! The blocks of the loops, a run each, its header first.
var runs_of: vector<u32>; #! The run of `members` holding each loop's blocks.
var inner: vector<u32>; #! The loop most nearly holding each block, by block, or `no_loop`.
}
#! Whether a loop holds a block.
#! @param this The loops.
#! @param loop The loop.
#! @param block The block, which may be newer than the loops, and so in none.
#! @returns Whether it does.
def loop_nest::holds(&this, loop: u32, block: u32): bool {
var at: u32 = (block as u64) < this.inner.length ? this.inner[block] : no_loop;
# A loop holding another comes after it.
while at != no_loop && at <= loop {
return true if at == loop;
at = this.parents[at];
}
return false;
}
#! Which block dominates which, and the natural loops, as a pass over loops
#! asks of them.
struct loop_view {
var order: vector<u32>; #! The blocks in reverse postorder.
var number: vector<u32>; #! Each block's place in that order.
var idom: vector<u32>; #! The immediate dominator of each block.
var first: vector<u32>; #! The first block each block immediately dominates, or `no_block`.
var after: vector<u32>; #! The next block the immediate dominator of each immediately dominates, or `no_block`.
var nest: loop_nest; #! The natural loops.
}
#! A value a header makes that is read outside it, which rotating has read
#! what stands for it there.
struct header_read {
var place: u64; #! Where it is read: an operand's place among the code's operands, or an argument's among its edge's.
var edge: u32; #! The edge whose argument it is, or `no_block` for an operand.
var slot: u32; #! Which of the values the header makes it is.
var past: bool; #! Whether it is read past the way out of the loop, rather than past the way in.
}
#! Optimizes the loops of a function's code, knowing what each call writes
#! what it returns to.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether anything changed.
def lowerer::optimize_loops(&mut this, index: u32): bool {
val writes := this.result_writes(index);
return this.program.functions[index].body.optimize_loops(writes.view());
}
#! Optimizes the loops of the code, as the file says: rotating each that may
#! be, then moving out of each what it works out the same each time round.
#! @param this The code.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @returns Whether anything changed.
pub def code::optimize_loops(&mut this, writes: span<u64>): bool {
# Rotating a loop changes which block dominates which, so the loops are
# found again after each, but after the last that may rotate. A loop found
# not to rotate is not asked again. Code found to have no loops has nothing
# to move out of them either.
var refused := vector::<bool>::new(scratch());
var rotated: u32 = 0;
var looped := true;
var last := false;
while rotated < rotate_most && !last {
refused.resize(this.blocks.length);
val point := mark_scratch();
val more := this.rotate_one(&mut refused, &mut looped, &mut last);
release_scratch(point);
break if !more;
rotated++;
}
return rotated != 0 if !looped;
return this.hoist_invariants(writes) || rotated != 0;
}
#! Finds which block dominates which, and the natural loops, from the order
#! and dominators the code keeps where it keeps them.
#! @param this The code.
#! @returns What was found, in scratch memory.
def code::view_loops(&mut this): loop_view {
var made := loop_view {
order = vector::<u32>::new(scratch()),
number = vector::<u32>::new(scratch()),
idom = vector::<u32>::new(scratch()),
first = vector::<u32>::new(scratch()),
after = vector::<u32>::new(scratch())
};
this.block_order(&mut made.order, &mut made.number);
made.idom = this.block_dominators();
made.first.resize(this.blocks.length, no_block);
made.after.resize(this.blocks.length, no_block);
var k := made.order.length;
while k > 1 {
k--;
val block: u32 = made.order[k];
val parent: u32 = made.idom[block];
made.after[block] = made.first[parent];
made.first[parent] = block;
}
made.nest = this.find_loops(made.order.view(), made.number.view(), &made.idom);
return made;
}
#! Finds the natural loops of the code: each block an edge goes back to from a
#! block it dominates heads one, holding the blocks from which those edges are
#! reached without passing it.
#! @param this The code.
#! @param order The blocks in reverse postorder.
#! @param number Each block's place in that order.
#! @param idom The immediate dominator of each block.
#! @returns The loops, in scratch memory.
pub def code::find_loops(&this, order: span<u32>, number: span<u32>, idom: &vector<u32>): loop_nest {
var nest := loop_nest {
headers = vector::<u32>::new(scratch()),
parents = vector::<u32>::new(scratch()),
members = runs::<u32>::new(scratch()),
runs_of = vector::<u32>::new(scratch()),
inner = vector::<u32>::new(scratch())
};
nest.inner.resize(this.blocks.length, no_loop);
# Where no edge goes to a block at or before the block it leaves in the
# order, none goes back, and there is no loop.
var back := false;
for &block in order {
for &edge in this.blocks[block].preds {
val from := this.edge_source(edge);
back = back || (number[from] != 0xFFFFFFFF && number[from] >= number[block]);
}
}
return nest if !back;
# Each loop as it is found, its header first among its blocks, in the order
# the headers are in.
var heads := vector::<u32>::new(scratch());
var found := vector::<u32>::new(scratch());
var marks := stamped_set::new(this.blocks.length, scratch());
var todo := vector::<u32>::new(scratch());
for &block in order {
var any := false;
marks.next_round();
for &edge in this.blocks[block].preds {
val from := this.edge_source(edge);
continue if number[from] == 0xFFFFFFFF || number[from] < number[block] || !dominates(idom, block, from);
if !any {
any = true;
marks.put(block);
nest.members.push(block);
}
if marks.insert(from) {
nest.members.push(from);
todo.append(from);
}
}
continue if !any;
while todo.length != 0 {
val at: u32 = todo.last();
todo.truncate();
for &edge in this.blocks[at].preds {
val back := this.edge_source(edge);
if number[back] != 0xFFFFFFFF && marks.insert(back) {
nest.members.push(back);
todo.append(back);
}
}
}
heads.append(block);
found.append(nest.members.end());
}
# The loops holding fewer blocks first, then in the order found, so each
# comes before those holding it. The largest first, each says which it is
# most nearly held by, as the loop holding its header is then.
var keys := vector::<u64>::new(scratch());
for i in 0..heads.length {
keys.append(pair_key(nest.members.length(found[i]) as u32, i as u32));
}
keys.sort();
for &key in keys {
nest.headers.append(heads[pair_low(key)]);
nest.runs_of.append(found[pair_low(key)]);
}
val count := nest.headers.length;
nest.parents.resize(count, no_loop);
var k := count;
while k > 0 {
k--;
nest.parents[k] = nest.inner[nest.headers[k]];
for &block in nest.members.view(nest.runs_of[k]) {
nest.inner[block] = k as u32;
}
}
return nest;
}
# Rotation.
#! Rotates the first loop that may be rotated, innermost loops first.
#! @param this The code.
#! @param refused Whether each block heads a loop found not to rotate.
#! @param looped Where whether the code has any loop is written.
#! @param last Where whether no other loop may rotate is written.
#! @returns Whether one was.
def code::rotate_one(&mut this, refused: &mut vector<bool>, looped: &mut bool, last: &mut bool): bool {
val view := this.view_loops();
looped = view.nest.headers.length != 0;
for k in 0..view.nest.headers.length {
val header: u32 = view.nest.headers[k];
continue if refused[header];
if this.rotate(&view, k as u32) {
this.forget_order();
# The loop rotated is headed by the block after its header now, which
# does not rotate: it only jumps on, or the header, going back to it,
# leaves the loop too. So where every other loop was found not to
# rotate, none may.
var others := false;
for j in 0..view.nest.headers.length {
others = others || (j != k && !refused[view.nest.headers[j]]);
}
last = !others;
return true;
}
refused[header] = true;
}
return false;
}
#! Rotates a loop, as the file says, where its header asks whether to go round
#! again, no edge back into it is from a block asking so too, as each is once
#! the loop is rotated, and it holds few instructions. Each value the header
#! makes that is read outside it must be read where the block after it in the
#! loop dominates, or where the block it leaves to does, every edge into which
#! is then from the header or from where the block after it dominates.
#! @param this The code.
#! @param view Which block dominates which, and the loops.
#! @param loop The loop.
#! @returns Whether it was rotated.
def code::rotate(&mut this, view: &loop_view, loop: u32): bool {
val nest := &view.nest;
val header: u32 = nest.headers[loop];
val last: u32 = this.blocks[header].last;
return false if last == 0 || this.insts[last].kind != op::branch;
val one: u32 = this.insts[last].aux;
val first_in := nest.holds(loop, this.edges[one].target);
return false if first_in == nest.holds(loop, this.edges[one + 1].target);
val stay := first_in ? one : one + 1;
val leave := first_in ? one + 1 : one;
val into: u32 = this.edges[stay].target;
val out: u32 = this.edges[leave].target;
return false if into == header;
for &edge in this.blocks[header].preds {
val from := this.edges[edge].from;
continue if !nest.holds(loop, this.insts[from].block);
var outs := this.edges_of(from);
while outs.more() {
return false if !nest.holds(loop, this.edges[outs.next()].target);
}
}
var size: u32 = 0;
var sized := this.walk(header);
while sized.more() {
val at := sized.next();
val kind := this.insts[at].kind;
continue if at == last || kind == op::iconst || kind == op::fconst;
size++;
return false if size > rotate_limit;
}
# The values the header makes, its parameters first, each one more than its
# slot among them by value. Its constants go into the entry, where both it
# and the guard read them.
var slots := vector::<u32>::new(scratch());
slots.resize(this.origins.length);
var made := vector::<u32>::new(scratch());
for &param in this.blocks[header].params {
made.append(param);
slots[param] = made.length as u32;
}
var walk := this.walk(header);
while walk.more() {
val held: inst = this.insts[walk.next()];
continue if held.kind.made_anywhere();
for r in 0..held.count {
made.append(held.result + r as u32);
slots[held.result + r as u32] = made.length as u32;
}
}
# Where each is read outside the header, and whether past the way in or out:
# within what the header dominates, as what reads a value is.
var reads := vector::<header_read>::new(scratch());
var inside := vector::<bool>::new(scratch());
var past := vector::<bool>::new(scratch());
inside.resize(made.length);
past.resize(made.length);
var below := vector::<u32>::new(scratch());
var child: u32 = view.first[header];
while child != no_block {
below.append(child);
child = view.after[child];
}
var next_below: u64 = 0;
while next_below < below.length {
val b: u32 = below[next_below];
next_below++;
child = view.first[b];
while child != no_block {
below.append(child);
child = view.after[child];
}
var side: u8 = 0;
var each := this.walk(b);
while each.more() {
val at := each.next();
val held: inst = this.insts[at];
for i in 0..held.argc {
val place := held.args as u64 + i as u64;
val slot: u32 = slots[this.operands[place]];
continue if slot == 0;
side = side == 0 ? this.side_of(view, into, out, b) : side;
return false if side == 3;
reads.append(header_read { place = place, edge = no_block, slot = slot - 1, past = side == 2 });
}
}
# Only the last instruction of a block leaves it by edges.
var outs := this.edges_of(this.blocks[b].last);
while outs.more() {
val edge := outs.next();
for a in 0..this.edges[edge].args.length {
val slot: u32 = slots[this.edges[edge].args[a]];
continue if slot == 0;
side = side == 0 ? this.side_of(view, into, out, b) : side;
return false if side == 3;
reads.append(header_read { place = a, edge = edge, slot = slot - 1, past = side == 2 });
}
}
}
var any_past := false;
for &read in reads {
if read.past {
past[read.slot] = true;
any_past = true;
} else {
inside[read.slot] = true;
}
}
# The block left to takes what the header made where it is read past it,
# which each edge into it gives: the header, and the guard's copy, and from
# within the loop, what the block after the header took.
var exits := this.blocks[out].preds.copied(scratch());
val leaving := this.edges[leave].args.copied(scratch());
val staying := this.edges[stay].args.copied(scratch());
if any_past {
for &edge in exits {
continue if edge == leave;
return false if !dominates(&view.idom, into, this.edge_source(edge));
for s in 0..made.length {
inside[s] = inside[s] || past[s];
}
}
}
# The block after the header in the loop takes what the loop reads of what
# the header made; where other edges go into it too, a block of its own,
# going on to it, does.
var after := into;
var given := vector::<u32>::new(scratch());
if this.blocks[into].preds.length != 1 {
after = this.add_block();
for p in 0..this.blocks[into].params.length {
given.append(this.add_param(after, this.type_of(this.blocks[into].params[p])));
}
}
var taken := vector::<u32>::new(scratch());
taken.resize(made.length);
var left := vector::<u32>::new(scratch());
left.resize(made.length);
for s in 0..made.length {
if inside[s] {
taken[s] = this.add_param(after, this.type_of(made[s]));
}
if past[s] {
left[s] = this.add_param(out, this.type_of(made[s]));
}
}
for &edge in exits {
for s in 0..made.length {
continue if !past[s];
val given_out: u32 = edge == leave ? made[s] : taken[s];
this.edges[edge].args.append(given_out);
}
}
# The header's constants go first in the entry.
var prior: u32 = 0;
var moving := this.walk(header);
while moving.more() {
val at := moving.next();
if !this.insts[at].kind.made_anywhere() {
prior = at;
continue;
}
if prior == 0 {
this.blocks[header].first = this.insts[at].next;
} else {
this.insts[prior].next = this.insts[at].next;
}
this.put_first(0, at);
}
# The guard takes what the header took from outside the loop, and copies its
# code, each copy reading the copies of what the header made. Where one edge
# goes into the loop, the guard reads what it gives instead.
val guard := this.add_block();
var copies := vector::<u32>::new(scratch());
copies.resize(made.length);
var entries := vector::<u32>::new(scratch());
for &edge in this.blocks[header].preds {
if !nest.holds(loop, this.edge_source(edge)) {
entries.append(edge);
}
}
for p in 0..this.blocks[header].params.length {
if entries.length == 1 {
copies[p] = this.edges[entries[0]].args[p];
} else {
copies[p] = this.add_param(guard, this.type_of(this.blocks[header].params[p]));
}
}
for &edge in entries {
this.drop_pred(edge);
this.edges[edge].target = guard;
this.blocks[guard].preds.append(edge);
if entries.length == 1 {
this.edges[edge].args.clear();
}
}
var pairs := vector::<u64>::new(scratch());
var args := vector::<u32>::new(scratch());
var types := vector::<vt>::new(scratch());
var copying := this.walk(header);
while copying.more() {
val at := copying.next();
break if at == last;
val from: inst = this.insts[at];
args.clear();
for i in 0..from.argc {
args.append(copy_of_read(&slots, &copies, this.arg(at, i as u32)));
}
types.clear();
for r in 0..from.count {
types.append(this.type_of(from.result + r as u32));
}
val copy := this.append(guard, from.kind, args.view(), types.view(), from.aux, from.imm, from.at);
this.insts[copy].site = from.site;
for r in 0..from.count {
copies[slots[from.result + r as u32] - 1] = this.insts[copy].result + r as u32;
}
pairs.append(pair_key(at, copy));
}
# The guard goes into the loop through a preheader, or out as the header
# would have the first time.
val pre := this.add_block();
var cond: u32[1] = [copy_of_read(&slots, &copies, this.arg(last, 0))];
val test := this.append(guard, op::branch, cond[0:1], span::<vt>::empty(), 0, 0, this.insts[last].at);
this.insts[test].site = this.insts[last].site;
val first := this.add_edge(test, first_in ? pre : out, 0);
this.add_edge(test, first_in ? out : pre, 0);
this.insts[test].aux = first;
val past_guard := first_in ? first + 1 : first;
for &each in leaving {
this.edges[past_guard].args.append(copy_of_read(&slots, &copies, each));
}
for s in 0..made.length {
if past[s] {
this.edges[past_guard].args.append(copies[s]);
}
}
val jump := this.append(pre, op::jump, span::<u32>::empty(), span::<vt>::empty(), 0, 0, this.insts[last].at);
this.insts[jump].site = this.insts[last].site;
val going := this.add_edge(jump, after, 0);
this.insts[jump].aux = going;
for &each in staying {
this.edges[going].args.append(copy_of_read(&slots, &copies, each));
}
# The header, now the bottom of the loop, gives the block after it what it
# made.
if after != into {
this.drop_pred(stay);
this.edges[stay].target = after;
this.blocks[after].preds.append(stay);
val on := this.append(after, op::jump, span::<u32>::empty(), span::<vt>::empty(), 0, 0, this.insts[last].at);
this.insts[on].site = this.insts[last].site;
val edge := this.add_edge(on, into, 0);
this.insts[on].aux = edge;
for &each in given {
this.edges[edge].args.append(each);
}
}
for s in 0..made.length {
if inside[s] {
this.edges[stay].args.append(made[s]);
this.edges[going].args.append(copies[s]);
}
}
# What read what the header made reads what stands for it.
for &read in reads {
val value: u32 = read.past ? left[read.slot] : taken[read.slot];
if read.edge == no_block {
this.operands[read.place] = value;
} else {
var held := this.edges[read.edge].args.slice();
held[read.place] = value;
}
}
this.rebind_rotated(view, header, guard, into, out, &slots, &copies, &taken, &left, pairs.view());
return true;
}
#! Whether an operation makes a constant, or the address of a cell, a global,
#! or a datum, which may be made anywhere, and which constant hoisting moves
#! out of loops into the entry.
#! @param this The operation.
#! @returns Whether it does.
def op::made_anywhere(&this): bool {
return match this {
op::iconst, op::fconst, op::cell, op::global, op::datum => true,
else => false
};
}
#! Which side of a loop being rotated a block reading what its header made is.
#! @param this The code.
#! @param view Which block dominates which, and the loops.
#! @param into The block after the header in the loop.
#! @param out The block the header leaves the loop to.
#! @param block The block.
#! @returns 1 where the block after the header dominates it, 2 where the block
#! left to does, and 3 where neither does.
def code::side_of(&this, view: &loop_view, into: u32, out: u32, block: u32): u8 {
return 1 if dominates(&view.idom, into, block);
return 2 if dominates(&view.idom, out, block);
return 3;
}
#! What the guard's copy of a header reads where the header read a value: the
#! copy of what the header made, or the value itself.
#! @param slots One more than each value's slot among those the header
#! made, or 0.
#! @param copies The guard's copy of each value the header made.
#! @param value The value.
#! @returns The value read.
def copy_of_read(slots: &vector<u32>, copies: &vector<u32>, value: u32): u32 {
return value if value as u64 >= slots.length || slots[value] == 0;
return copies[slots[value] - 1];
}
#! Binds the variables a rotated loop's header bound in the guard too, to the
#! copies, and those bound where the parameters standing for what the header
#! made are read, to those parameters.
#! @param this The code.
#! @param view Which block dominated which before the loop was rotated.
#! @param header The header.
#! @param guard The guard.
#! @param into The block after the header in the loop.
#! @param out The block the header leaves the loop to.
#! @param slots One more than each value's slot among those the header
#! made, or 0.
#! @param copies The guard's copy of each value the header made.
#! @param taken What the block after the header takes for each, or 0.
#! @param left What the block left to takes for each, or 0.
#! @param pairs Each instruction of the header with its copy, as
#! `pair_key(instruction, copy)`.
def code::rebind_rotated(
&mut this,
view: &loop_view,
header: u32,
guard: u32,
into: u32,
out: u32,
slots: &vector<u32>,
copies: &vector<u32>,
taken: &vector<u32>,
left: &vector<u32>,
pairs: span<u64>
): void {
val count := this.bindings.length;
for i in 0..count {
val each: binding = this.bindings[i];
continue if each.block == no_block || each.block as u64 >= view.idom.length || this.blocks[each.block].gone;
if each.block == header {
var copy: binding = each;
copy.block = guard;
copy.value = copy_of_read(slots, copies, each.value);
copy.after = 0;
for &pair in pairs {
if pair_high(pair) == each.after {
copy.after = pair_low(pair);
}
}
this.bindings.append(copy);
continue;
}
continue if each.value as u64 >= slots.length || slots[each.value] == 0;
val slot := slots[each.value] - 1;
if taken[slot] != 0 && dominates(&view.idom, into, each.block) {
this.bindings[i].value = taken[slot];
} else if left[slot] != 0 && dominates(&view.idom, out, each.block) {
this.bindings[i].value = left[slot];
}
}
}
# Hoisting.
#! What moving out of loops knows of the code as it goes.
struct hoisting {
var reached: hashset<u64>; #! Each address read or written through, or checked not null, with the block it is so in, as `pair_key(address, block)`.
var moved: stamped_set; #! The instructions moved out of the loop worked on, a round each loop.
var aliases: aliases; #! What may write what.
var writers: vector<writing>; #! What each instruction writing memory in the loop worked on writes.
var before: u32; #! The block most nearly dominating the loop's header.
}
#! Moves what each loop works out the same each time round into its
#! preheader, inner loops first, as the file says. A loop with something to
#! move but no block before it that only jumps into it is given one first.
#! @param this The code.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @returns Whether anything moved.
def code::hoist_invariants(&mut this, writes: span<u64>): bool {
var view := this.view_loops();
return false if view.nest.headers.length == 0;
var state := hoisting {
reached = this.reached_addresses(&view),
moved = stamped_set::new(this.insts.length + view.nest.headers.length, scratch()),
aliases = this.aliases(writes, view.idom.view()),
writers = vector::<writing>::new(scratch())
};
var made := false;
for k in 0..view.nest.headers.length {
continue if this.preheader_of(&view, k as u32) != no_block;
continue if !this.hoist_loop(&view, k as u32, no_block, &mut state);
this.make_preheader(&view, k as u32);
made = true;
}
if made {
this.forget_order();
view = this.view_loops();
state.aliases = this.aliases(writes, view.idom.view());
}
var changed := false;
for k in 0..view.nest.headers.length {
val pre := this.preheader_of(&view, k as u32);
continue if pre == no_block;
changed = this.hoist_loop(&view, k as u32, pre, &mut state) || changed;
}
return changed;
}
#! Every address read or written through, or checked not null, with the block
#! it is so in, of those a read within a loop reads through, which are all that
#! is asked of. Reaching through null stops the program, so an address so in a
#! block dominating another is not null there. An instruction moving moves to
#! a block dominating the one it was in, where it is so still.
#! @param this The code.
#! @param view Which block dominates which, and the loops.
#! @returns Each, as `pair_key(address, block)`, in scratch memory.
def code::reached_addresses(&this, view: &loop_view): hashset<u64> {
var made := hashset::<u64>::new(scratch());
var asked := vector::<bool>::new(scratch());
asked.resize(this.origins.length);
var any := false;
for &block in view.order {
continue if view.nest.inner[block] == no_loop;
var inside := this.walk(block);
while inside.more() {
val at := inside.next();
if this.insts[at].kind == op::load {
asked[this.arg(at, 0)] = true;
any = true;
}
}
}
return made if !any;
var walk := this.walk_all();
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
val sized := (held.kind == op::copy || held.kind == op::clear) && held.imm != 0;
if (held.kind == op::load || held.kind == op::store || sized
|| (held.kind == op::check && held.aux == fault::null_reference as u32)) && asked[this.arg(at, 0)] {
made.insert(pair_key(this.arg(at, 0), held.block));
}
if held.kind == op::copy && sized && asked[this.arg(at, 1)] {
made.insert(pair_key(this.arg(at, 1), held.block));
}
}
return made;
}
#! Whether an address is not null where a block ends: it is never zero, or is
#! read or written through, or checked, in that block or one dominating it.
#! @param this The code.
#! @param view Which block dominates which, and the loops.
#! @param reached Each address read or written through, or checked, with
#! the block it is so in.
#! @param address The address.
#! @param block The block.
#! @returns Whether it is.
def code::reached_before(&this, view: &loop_view, reached: &hashset<u64>, address: u32, block: u32): bool {
return true if this.never_zero(address);
val home := this.home_of(address);
var at := block;
var steps := 0;
while steps < 64 && at != no_block && (at as u64) < view.idom.length {
val key := pair_key(address, at);
return true if reached.contains(&key);
return false if at == home || at == 0;
at = view.idom[at];
steps++;
}
return false;
}
#! The preheader of a loop: the one block outside it going into its header,
#! where that block only jumps there.
#! @param this The code.
#! @param view Which block dominates which, and the loops.
#! @param loop The loop.
#! @returns The block, or `no_block` where the loop has none.
def code::preheader_of(&this, view: &loop_view, loop: u32): u32 {
val header: u32 = view.nest.headers[loop];
var found := no_block;
for &edge in this.blocks[header].preds {
val from := this.edge_source(edge);
continue if view.nest.holds(loop, from);
return no_block if found != no_block;
found = from;
}
return no_block if found == no_block || this.insts[this.blocks[found].last].kind != op::jump;
return found;
}
#! Makes a preheader for a loop: a block taking what its header took from
#! outside it, every edge from outside going there, which jumps into the
#! header giving it that.
#! @param this The code.
#! @param view Which block dominates which, and the loops.
#! @param loop The loop.
def code::make_preheader(&mut this, view: &loop_view, loop: u32): void {
val header: u32 = view.nest.headers[loop];
val pre := this.add_block();
var given := vector::<u32>::new(scratch());
for p in 0..this.blocks[header].params.length {
given.append(this.add_param(pre, this.type_of(this.blocks[header].params[p])));
}
var entries := vector::<u32>::new(scratch());
for &edge in this.blocks[header].preds {
if !view.nest.holds(loop, this.edge_source(edge)) {
entries.append(edge);
}
}
for &edge in entries {
this.drop_pred(edge);
this.edges[edge].target = pre;
this.blocks[pre].preds.append(edge);
}
val first: u32 = this.blocks[header].first;
val jump := this.append(pre, op::jump, span::<u32>::empty(), span::<vt>::empty(), 0, 0, this.insts[first].at);
this.insts[jump].site = this.insts[first].site;
val edge := this.add_edge(jump, header, 0);
this.insts[jump].aux = edge;
for &each in given {
this.edges[edge].args.append(each);
}
}
#! Moves what a loop works out the same each time round into its preheader, in
#! the order the loop worked it out, or only finds whether anything would move.
#! The blocks running first each time the loop is gone into, its header and
#! each a jump goes on to in turn, run what may stop the program before
#! anything the program would be seen to do, until one of those that does not
#! move.
#! @param this The code.
#! @param view Which block dominates which, and the loops.
#! @param loop The loop.
#! @param pre The preheader, or `no_block` to only find whether anything
#! would move.
#! @param state What moving out of loops knows.
#! @returns Whether anything moved, or would.
def code::hoist_loop(&mut this, view: &loop_view, loop: u32, pre: u32, state: &mut hoisting): bool {
val nest := &view.nest;
val header: u32 = nest.headers[loop];
var keys := vector::<u64>::new(scratch());
for &block in nest.members.view(nest.runs_of[loop]) {
keys.append(pair_key(view.number[block], block));
}
keys.sort();
state.moved.next_round();
state.before = view.idom[header];
state.writers.clear();
for &key in keys {
var walk := this.walk(pair_low(key));
while walk.more() {
val at := walk.next();
val kind := this.insts[at].kind;
if kind != op::load && (kind.traits() & op_write) != 0 {
state.writers.append(state.aliases.writes_of(this, at));
}
}
}
# The blocks running first, each jumping to the next.
var firsts := vector::<u32>::new(scratch());
var at := header;
while true {
firsts.append(at);
val last: u32 = this.blocks[at].last;
break if this.insts[last].kind != op::jump;
at = this.edges[this.insts[last].aux].target;
break if !nest.holds(loop, at) || firsts.view().contains(&at);
}
var any := false;
var seen := false;
var tail: u32 = 0;
for &key in keys {
val block := pair_low(key);
val first := firsts.view().contains(&block);
var prior: u32 = 0;
var walk := this.walk(block);
while walk.more() {
val index := walk.next();
if this.invariant(index, view, loop, state, first && !seen) {
any = true;
state.moved.put(index);
continue if pre == no_block;
# It leaves its block, and follows what moved before it, but for a
# constant or the address of a cell, a global, or a datum, which goes
# first in the entry, as constant hoisting would put it.
val next: u32 = this.insts[index].next;
if prior == 0 {
this.blocks[block].first = next;
} else {
this.insts[prior].next = next;
}
if this.insts[index].kind.made_anywhere() {
this.put_first(0, index);
continue;
}
if tail == 0 {
this.link_before(index, this.blocks[pre].last);
} else {
this.link_after(index, tail);
}
tail = index;
continue;
}
if first && this.seen_to_run(index, view, state) {
seen = true;
}
prior = index;
}
}
return any;
}
#! Whether an instruction of a loop works out the same each time round and may
#! move into the preheader: everything it reads is made outside the loop, or
#! moves; and it works out only its values, but for a division by zero; it
#! reads memory nothing in the loop writes, through an address not null before
#! the loop, or where it runs first; or it is a check, where it runs first.
#! @param this The code.
#! @param index The instruction.
#! @param view Which block dominates which, and the loops.
#! @param loop The loop.
#! @param state What moving out of loops knows.
#! @param first Whether it runs each time the loop is gone into before
#! anything the program would be seen to do in it.
#! @returns Whether it may.
def code::invariant(&this, index: u32, view: &loop_view, loop: u32, state: &hoisting, first: bool): bool {
val held: inst = this.insts[index];
return false if held.kind.ends() || (held.count == 0 && held.kind != op::check);
for i in 0..held.argc {
val value := this.arg(index, i as u32);
val from := this.defining(value);
continue if from != 0 && state.moved.contains(from);
return false if view.nest.holds(loop, this.home_of(value));
}
return match held.kind {
op::check => first,
op::load => !this.written_in_loop(index, state) && (first || this.reached_before(view, &state.reached, this.arg(index, 0), state.before)),
else => this.removable(index)
};
}
#! Whether anything in the loop worked on may write what a read reads.
#! @param this The code.
#! @param index The `load`.
#! @param state What moving out of loops knows.
#! @returns Whether it may.
def code::written_in_loop(&this, index: u32, state: &hoisting): bool {
return false if state.writers.length == 0;
val place := state.aliases.region_of(this, index, 0);
for &each in state.writers {
return true if state.aliases.touches(this, &each, &place);
}
return false;
}
#! Whether an instruction that does not move does what the program would be
#! seen to do: writing memory, calling, or what may stop the program, as a read
#! through an address that may be null before the loop.
#! @param this The code.
#! @param index The instruction.
#! @param view Which block dominates which, and the loops.
#! @param state What moving out of loops knows.
#! @returns Whether it does.
def code::seen_to_run(&this, index: u32, view: &loop_view, state: &hoisting): bool {
val held := &this.insts[index];
return !this.reached_before(view, &state.reached, this.arg(index, 0), state.before) if held.kind == op::load;
return (held.kind.traits() & (op_traps | op_write)) != 0 && !this.removable(index);
}
+500
View File
@@ -0,0 +1,500 @@
#! @file memory.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the eighth pass of the optimizer, which cleans up what the code does
#! with the memory of its cells, of which building values and inlining leave
#! much. Where each cell is known to hold zero is followed through the blocks,
#! from what the frame zeroes and what the blocks before each leave: clearing
#! what is zero already, or storing zero to it, goes; copying from what is zero
#! clears instead; and reading it reads the zero. A clear whose bytes are all
#! written before anything reads them goes. Then a copy into the memory a
#! function returns, right before it returns, is returned from where it was
#! copied from.
#!
#! A cell whose address goes anywhere but to the instructions reading, writing,
#! copying, and clearing it, or to a call as where to write what it returns, is
#! escaped, as alias analysis finds: anything that may read or write memory the
#! code does not name may read or write it, but for what reaches through an
#! address outside the frame.
module sakura::compiler;
#! The most words of a cell the pass follows, a bit each.
const memory_words: u64 = 64;
#! What stands for a cell the pass does not follow.
const unfollowed: u32 = 0xFFFFFFFF;
#! The most words the ends of the blocks may take, past which no block begins
#! knowing what the blocks before it left.
const memory_ends_limit: u64 = 1048576;
#! What the pass knows of the cells of the code.
struct memory_known {
var addresses: cell_table; #! Which cell each value is the address of.
var escaped: vector<bool>; #! Whether each cell's address goes where it may be read or written without the code saying.
var place: vector<u32>; #! The place of each cell among those followed, or `unfollowed`.
var cells: vector<u32>; #! The cell followed at each place.
var exposed: vector<u32>; #! The places of the escaped cells followed.
var zero: vector<u64>; #! The words known zero of each cell followed, where the walk is, a bit each.
var clears: vector<u32>; #! Of each cell followed, the clear of it nothing has read since, or 0.
var cleared: vector<u64>; #! The words that clear zeroes.
var covered: vector<u64>; #! The words of it written whole since.
var ends: vector<u64>; #! The words known zero where each block ends, a word for each place, block after block.
var walked: vector<bool>; #! Whether each block was walked.
var zeros: zero_values; #! The zero of each type, made once.
}
#! The place among those followed of the cell an address is.
#! @param this What the pass knows.
#! @param value The address.
#! @returns The place, or `unfollowed`.
def memory_known::followed(&this, value: u32): u32 {
val cell := this.addresses.cell(value);
return cell == 0 ? unfollowed : this.place[cell - 1];
}
#! Says a cell was read, so the clear of it nothing had read stays.
#! @param this What the pass knows.
#! @param place The cell's place.
def memory_known::read(&mut this, place: u32): void {
this.clears[place] = 0;
}
#! Says memory the code does not name was read, which may be any escaped cell.
#! @param this What the pass knows.
def memory_known::read_escaped(&mut this): void {
for &k in this.exposed {
this.clears[k] = 0;
}
}
#! Says memory the code does not name was written, which may be any escaped
#! cell, so none is known zero.
#! @param this What the pass knows.
def memory_known::forget_escaped(&mut this): void {
for &k in this.exposed {
this.zero[k] = 0;
}
}
#! Says words of a cell were written whole, taking out the clear of it they
#! write over all of.
#! @param this What the pass knows.
#! @param place The cell's place.
#! @param words The words, a bit each.
#! @param done What the pass changes.
def memory_known::cover(&mut this, place: u32, words: u64, done: &mut rewrite): void {
return if this.clears[place] == 0;
this.covered[place] = this.covered[place] | words;
if (this.covered[place] & this.cleared[place]) == this.cleared[place] {
done.remove(this.clears[place]);
this.clears[place] = 0;
}
}
#! Says a cell was cleared by an instruction that stays.
#! @param this What the pass knows.
#! @param place The cell's place.
#! @param index The clear.
#! @param size How many bytes it clears.
#! @param done What the pass changes.
def memory_known::clear(&mut this, place: u32, index: u32, size: u64, done: &mut rewrite): void {
val whole := whole_words(0, size);
this.cover(place, whole, done);
this.clears[place] = index;
this.cleared[place] = touched_words(0, size);
this.covered[place] = 0;
this.zero[place] = this.zero[place] | whole;
}
#! The words bytes touch, a bit each.
#! @param offset Where they begin.
#! @param size How many there are.
#! @returns The words.
def touched_words(offset: u64, size: u64): u64 {
return 0 if size == 0;
return 0xFFFFFFFFFFFFFFFFu if offset + size > memory_words * word_size;
val first := offset / word_size;
val last := (offset + size - 1) / word_size;
return words_between(first, last + 1);
}
#! The words bytes cover whole, a bit each.
#! @param offset Where they begin.
#! @param size How many there are.
#! @returns The words.
def whole_words(offset: u64, size: u64): u64 {
return 0 if offset + size > memory_words * word_size;
val first := (offset + word_size - 1) / word_size;
val end := (offset + size) / word_size;
return first >= end ? 0 : words_between(first, end);
}
#! The words from one to before another, a bit each.
#! @param first The first.
#! @param end The one after the last.
#! @returns The words.
def words_between(first: u64, end: u64): u64 {
val high := end >= 64 ? 0xFFFFFFFFFFFFFFFFu : (1u << end) - 1;
return high & ~((1u << first) - 1);
}
#! Whether an address is within no cell: a step from a global, a datum, what
#! the program holds on the heap, or an address the function was given, which
#! points outside its frame.
#! @param this The code.
#! @param address The address.
#! @returns Whether it is.
def code::outside_cells(&this, address: u32): bool {
var at := address;
for _ in 0..8 {
val index := this.defining(at);
if index == 0 {
val held: origin = this.origins[at];
return held.param && held.from == 0;
}
match this.insts[index].kind {
op::global, op::datum, op::allocate => return true;
op::add => at = this.arg(index, 0);
else => return false;
}
}
return false;
}
#! Whether a value is a word or real all of whose bits are zero.
#! @param this The code.
#! @param value The value.
#! @returns Whether it is.
def code::zero_bits(&this, value: u32): bool {
var bits: u64 = 1;
val origin: origin = this.origins[value];
return true if !origin.param && this.insts[origin.from].kind == op::vzero;
return (this.word_constant(value, &mut bits) || this.real_constant(value, &mut bits)) && bits == 0;
}
#! Cleans up the memory of the cells, as the file says.
#! @param this The code.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @returns Whether anything changed.
pub def code::clean_memory(&mut this, writes: span<u64>): bool {
return false if this.cells.length == 0;
var state := memory_known {
addresses = this.cell_table(),
escaped = vector::<bool>::new(scratch()),
place = vector::<u32>::new(scratch()),
cells = vector::<u32>::new(scratch()),
exposed = vector::<u32>::new(scratch()),
zero = vector::<u64>::new(scratch()),
clears = vector::<u32>::new(scratch()),
cleared = vector::<u64>::new(scratch()),
covered = vector::<u64>::new(scratch()),
ends = vector::<u64>::new(scratch()),
walked = vector::<bool>::new(scratch())
};
return false if !state.addresses.any;
state.escaped = this.escaped_cells(&state.addresses, writes);
state.place.resize(this.cells.length, unfollowed);
for c in 0..this.cells.length {
continue if this.cells[c].size as u64 > memory_words * word_size;
state.place[c] = state.cells.length as u32;
if state.escaped[c] {
state.exposed.append(state.cells.length as u32);
}
state.cells.append(c as u32);
}
val count := state.cells.length;
state.zero.resize(count);
state.clears.resize(count);
state.cleared.resize(count);
state.covered.resize(count);
var done := rewrite::new();
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.block_order(&mut order, &mut number);
val inherits := count != 0 && this.blocks.length * count <= memory_ends_limit;
if inherits {
state.ends.resize(this.blocks.length * count);
state.walked.resize(this.blocks.length);
}
for &block in order {
continue if count == 0;
this.begin_memory(block, &mut state, inherits);
this.walk_memory(block, &mut state, writes, &mut done);
if inherits {
for k in 0..count {
state.ends[block as u64 * count + k] = state.zero[k];
}
state.walked[block] = true;
}
}
this.apply(&done);
var returns := rewrite::new();
this.forward_returns(&mut returns);
this.apply(&returns);
return done.changed || returns.changed;
}
#! Begins what is known zero where a block begins: every word of each cell the
#! frame zeroes at the entry, and elsewhere what every block going there left,
#! where each was walked.
#! @param this The code.
#! @param block The block.
#! @param state What the pass knows.
#! @param inherits Whether what the blocks before it left is known.
def code::begin_memory(&this, block: u32, state: &mut memory_known, inherits: bool): void {
val count := state.cells.length;
for k in 0..count {
state.zero[k] = 0;
state.clears[k] = 0;
}
val preds := &this.blocks[block].preds;
if block == 0 && preds.length == 0 {
for k in 0..count {
val held: cell = this.cells[state.cells[k]];
if held.kind == ck::temporary || held.kind == ck::local {
state.zero[k] = touched_words(0, held.size as u64);
}
}
return;
}
return if !inherits || preds.length == 0;
for &edge in preds.view() {
return if !state.walked[this.edge_source(edge)];
}
for k in 0..count {
state.zero[k] = 0xFFFFFFFFFFFFFFFFu;
}
for &edge in preds.view() {
val from := this.edge_source(edge) as u64;
for k in 0..count {
state.zero[k] = state.zero[k] & state.ends[from * count + k];
}
}
}
#! Walks the instructions of a block, as the file says.
#! @param this The code.
#! @param block The block.
#! @param state What the pass knows.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @param done What the pass changes.
def code::walk_memory(&mut this, block: u32, state: &mut memory_known, writes: span<u64>, done: &mut rewrite): void {
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
match held.kind {
op::load => this.memory_load(at, &held, state, done);
op::store => this.memory_store(at, &held, state, done);
op::clear => this.memory_clear(at, &held, state, done);
op::copy => this.memory_copy(at, &held, state, done);
else => this.memory_other(at, &held, state, writes, done);
}
}
}
#! Follows a read: of a cell's words known zero, it is that zero.
#! @param this The code.
#! @param index The `load`.
#! @param held The instruction.
#! @param state What the pass knows.
#! @param done What the pass changes.
def code::memory_load(&mut this, index: u32, held: &inst, state: &mut memory_known, done: &mut rewrite): void {
val address := this.arg(index, 0);
if state.addresses.cell(address) == 0 {
if !this.outside_cells(address) {
state.read_escaped();
}
return;
}
val k := state.followed(address);
return if k == unfollowed;
state.read(k);
val words := touched_words(held.imm, (held.aux as access).width());
return if (state.zero[k] & words) != words;
done.replace(held.result, state.zeros.of(this, this.type_of(held.result)));
done.remove(index);
}
#! Follows a write of a word: zero to words known zero goes.
#! @param this The code.
#! @param index The `store`.
#! @param held The instruction.
#! @param state What the pass knows.
#! @param done What the pass changes.
def code::memory_store(&mut this, index: u32, held: &inst, state: &mut memory_known, done: &mut rewrite): void {
val address := this.arg(index, 0);
if state.addresses.cell(address) == 0 {
if !this.outside_cells(address) {
state.forget_escaped();
}
return;
}
val k := state.followed(address);
return if k == unfollowed;
val width := (held.aux as access).width();
val words := touched_words(held.imm, width);
val whole := whole_words(held.imm, width);
if this.zero_bits(this.arg(index, 1)) {
if (state.zero[k] & words) == words {
done.remove(index);
return;
}
state.zero[k] = state.zero[k] | whole;
} else {
state.zero[k] = state.zero[k] & ~words;
}
state.cover(k, whole, done);
}
#! Follows a clear: of words known zero already, it goes.
#! @param this The code.
#! @param index The `clear`.
#! @param held The instruction.
#! @param state What the pass knows.
#! @param done What the pass changes.
def code::memory_clear(&mut this, index: u32, held: &inst, state: &mut memory_known, done: &mut rewrite): void {
val address := this.arg(index, 0);
if state.addresses.cell(address) == 0 {
if !this.outside_cells(address) {
state.forget_escaped();
}
return;
}
val k := state.followed(address);
return if k == unfollowed;
val words := touched_words(0, held.imm);
if (state.zero[k] & words) == words {
done.remove(index);
return;
}
state.clear(k, index, held.imm, done);
}
#! Follows a copy: from words known zero, it clears instead, or goes where what
#! it writes is known zero already.
#! @param this The code.
#! @param index The `copy`.
#! @param held The instruction.
#! @param state What the pass knows.
#! @param done What the pass changes.
def code::memory_copy(&mut this, index: u32, held: &inst, state: &mut memory_known, done: &mut rewrite): void {
val to := this.arg(index, 0);
val from := this.arg(index, 1);
val words := touched_words(0, held.imm);
var zero := false;
if state.addresses.cell(from) == 0 {
if !this.outside_cells(from) {
state.read_escaped();
}
} else {
val s := state.followed(from);
if s != unfollowed {
zero = (state.zero[s] & words) == words;
if !zero {
state.read(s);
}
}
}
if zero {
val d := state.followed(to);
if d != unfollowed && (state.zero[d] & words) == words {
done.remove(index);
return;
}
var args: u32[1] = [to];
this.become(index, op::clear, args[0:1], 0, held.imm);
done.changed = true;
if d != unfollowed {
state.clear(d, index, held.imm, done);
return;
}
}
if state.addresses.cell(to) == 0 {
if !this.outside_cells(to) {
state.forget_escaped();
}
return;
}
val d := state.followed(to);
return if d == unfollowed || zero;
state.zero[d] = state.zero[d] & ~words;
state.cover(d, whole_words(0, held.imm), done);
}
#! Follows any other instruction: one reading or writing memory the code does
#! not name may read or write any escaped cell, and a call writes what it
#! returns to the cell its last operand is.
#! @param this The code.
#! @param index The instruction.
#! @param held The instruction.
#! @param state What the pass knows.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @param done What the pass changes.
def code::memory_other(&mut this, index: u32, held: &inst, state: &mut memory_known, writes: span<u64>, done: &mut rewrite): void {
# What a cell's address is given to may read it, and as an operand write it,
# but for where a call writes what it returns, which is followed below.
val written: u64 = (index as u64) < writes.length ? writes[index] : 0;
var reads := this.reads_of(index);
while reads.more() {
val k := state.followed(reads.next());
continue if k == unfollowed;
val i := reads.operand();
if i == no_operand {
state.read(k);
continue;
}
continue if written != 0 && i + 1 == held.argc;
state.read(k);
state.zero[k] = 0;
}
val traits := held.kind.traits();
if (traits & op_reads) != 0 {
state.read_escaped();
}
if (traits & op_write) != 0 {
state.forget_escaped();
}
if written != 0 {
val k := state.followed(this.arg(index, held.argc - 1));
if k != unfollowed {
state.zero[k] = 0;
state.cover(k, whole_words(0, written), done);
}
}
}
#! Returns from where a copy into the memory a function returns, right before
#! it returns, was copied from.
#! @param this The code.
#! @param done What the pass changes.
def code::forward_returns(&mut this, done: &mut rewrite): void {
return if this.returned == 0;
for b in 0..this.blocks.length {
continue if this.blocks[b].gone;
val last: u32 = this.blocks[b].last;
continue if last == 0 || this.insts[last].kind != op::ret || this.insts[last].argc != 1;
val before := this.before(last);
continue if before == 0 || this.insts[before].kind != op::copy;
val returned := this.arg(last, 0);
val to := this.arg(before, 0);
val from := this.arg(before, 1);
continue if this.insts[before].imm < this.returned as u64 || from == returned;
continue if to != returned && (this.cell_of(to) == no_cell || this.cell_of(to) != this.cell_of(returned));
var args: u32[1] = [from];
this.become(last, op::ret, args[0:1], this.insts[last].aux, this.insts[last].imm);
done.remove(before);
}
}
+186
View File
@@ -0,0 +1,186 @@
#! @file merge.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the merging of the stores filling 16 bytes of a cell into one, of a
#! vector built in a register, which an executable's code is given once it is
#! optimized. A load reading several stores waits until each reaches the cache,
#! where one store of all its bytes is forwarded to it at once, and a struct of
#! four `f32`s or two words, as a `vec3` holding its fourth, is copied out 16
#! bytes at a time, as it is returned: built a field at a time, the copy waited
#! on every field.
#!
#! The 16 bytes from a multiple of 16 in a cell the frame zeroes are merged
#! where every instruction writing them in the code is a store of 4 or 8 bytes,
#! all reals or all words, each in one block, and nothing reads them from the
#! first to the last; what none writes is zero. The cell's address goes only to
#! what reads, writes, copies, clears, and returns it. It is done once nothing
#! more is inlined, so a function copying the code holds its fields as values
#! still, as promoting holds them, and only in an executable's code, which holds
#! vectors.
module sakura::compiler;
#! What merging knows of a write or read of a cell.
struct touch {
var at: u32; #! The instruction.
var offset: u64; #! The first byte.
var size: u64; #! How many bytes.
var writes: bool; #! Whether it writes them.
var how: access; #! For a store, how it writes them; `access::bytes` for any other.
}
#! Merges the stores filling 16 bytes of a cell, as the file says.
#! @param this The code.
#! @returns Whether anything changed.
pub def code::merge_stores(&mut this): bool {
return false if !this.vectors || this.cells.length == 0;
val addresses := this.cell_table();
return false if !addresses.any;
# What each cell's address goes to, where it goes only to what reads and
# writes it, and the order of each instruction within its block.
var touches := vector::<vector<touch>>::new(scratch());
touches.resize(this.cells.length);
var whole := vector::<bool>::new(scratch());
whole.resize(this.cells.length, true);
var place := vector::<u32>::new(scratch());
place.resize(this.insts.length);
for b in 0..this.blocks.length {
continue if this.blocks[b].gone;
var number: u32 = 0;
var walk := this.walk(b as u32);
while walk.more() {
place[walk.next()] = number;
number++;
}
}
var walk := this.walk_all();
var reads := this.reader();
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
reads.start(at);
while reads.more() {
val cell := addresses.cell(reads.next());
continue if cell == 0;
val c := (cell - 1) as u64;
val i := reads.operand();
if i == no_operand {
whole[c] = false;
} else if held.kind == op::load && i == 0 {
touches[c].append(touch { at = at, offset = held.imm, size = (held.aux as access).width(), how = access::bytes });
} else if held.kind == op::store && i == 0 {
val how := held.aux as access;
touches[c].append(touch { at = at, offset = held.imm, size = how.width(), writes = true, how = how });
} else if held.kind == op::clear && i == 0 {
touches[c].append(touch { at = at, size = held.imm, writes = true, how = access::bytes });
} else if held.kind == op::copy && i < 2 {
touches[c].append(touch { at = at, size = held.imm, writes = i == 0, how = access::bytes });
} else if held.kind == op::ret {
touches[c].append(touch { at = at, size = this.cells[c].size as u64, how = access::bytes });
} else {
whole[c] = false;
}
}
}
var done := rewrite::new();
var zeros := zero_values {};
for c in 0..this.cells.length {
val held: cell = this.cells[c];
continue if !whole[c] || (held.kind != ck::temporary && held.kind != ck::local);
var start: u64 = 0;
while start + 16 <= held.size as u64 {
this.merge_region(c as u32, start, touches[c].view(), place.view(), &mut zeros, &mut done);
start += 16;
}
}
this.apply(&done);
return done.changed;
}
#! Merges the stores filling the 16 bytes of a cell from an offset, where they
#! may be merged, as the file says: the last becomes the store of the vector
#! of them all, built before it, and the rest go.
#! @param this The code.
#! @param cell The cell.
#! @param start Where the bytes begin.
#! @param touches What reads and writes the cell.
#! @param place The order of each instruction within its block.
#! @param zeros The zero of each type, made once.
#! @param done What the pass changes.
def code::merge_region(&mut this, cell: u32, start: u64, touches: span<touch>, place: span<u32>, zeros: &mut zero_values, done: &mut rewrite): void {
val end := start + 16;
var stores := vector::<touch>::new(scratch());
var block: u32 = 0;
for &each in touches {
continue if !each.writes || each.offset >= end || each.offset + each.size <= start;
return if each.how == access::bytes || each.offset < start || each.offset + each.size > end;
val one: inst = this.insts[each.at];
if stores.length == 0 {
block = one.block;
}
# One block's stores, each of a word or a real of the same width, at an
# offset of its own, as a struct's fields are written.
return if one.block != block || each.size != stores_width(&stores, each.size) || (each.size != 4 && each.size != 8);
return if stores.length != 0 && (each.how.value_type() != stores[0].how.value_type());
for &other in stores {
return if other.offset == each.offset;
}
stores.append(each);
}
return if stores.length < 2;
var first: u32 = 0xFFFFFFFF;
var last: u32 = 0;
var last_at: u32 = 0;
for &each in stores {
val p := place[each.at];
first = first < p ? first : p;
if p >= last {
last = p;
last_at = each.at;
}
}
# Nothing reads the bytes between the first store and the last.
for &each in touches {
continue if each.writes || each.offset >= end || each.offset + each.size <= start;
val p := place[each.at];
return if this.insts[each.at].block == block && p > first && p < last;
}
val width := stores[0].size;
val real := stores[0].how.value_type() == vt::real;
val lane: u32 = real ? (width == 4 ? lane_f32 : lane_f64) : (width == 4 ? lane_u32 : lane_u64);
val count := 16 / width;
var lanes := vector::<u32>::new(scratch());
lanes.resize(count, 0);
for &each in stores {
lanes[(each.offset - start) / width] = this.arg(each.at, 1);
}
for k in 0..count {
if lanes[k] == 0 {
lanes[k] = zeros.of(this, real ? vt::real : vt::word);
}
}
val held: inst = this.insts[last_at];
var gives: vt[1] = [vt::v128];
val pack := this.detached(op::lanes, lanes.view(), gives[0:1], lanes_pack, lane as u64 | 16 << 8, held.at, held.site);
this.link_before(pack, last_at);
var args: u32[2] = [this.arg(last_at, 0), this.insts[pack].result];
this.become(last_at, op::store, args[0:2], access::v128 as u32, start);
for &each in stores {
if each.at != last_at {
done.remove(each.at);
}
}
done.changed = true;
}
# The width the stores of a region share: that of the first, or the one given
# where there is none yet.
def stores_width(stores: &vector<touch>, size: u64): u64 {
return stores.length == 0 ? size : stores[0].size;
}
+689
View File
@@ -0,0 +1,689 @@
#! @file numbering.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the sixth pass of the optimizer, value numbering: an instruction
#! working out what one before it already worked out, in a block that block
#! dominates, reads that instead, as two reads of `v[i]` share one bounds
#! check's comparison. A check of a condition a dominating check or branch
#! already proved goes, as does a branch's question where it was answered, and
#! a `select` on it is what it chooses. And a read of memory read or written
#! before, with nothing that may write it between, as alias analysis tells,
#! reads what was read or written: within a block, and from the block that
#! dominates it, but for what anything on the way between may write.
import std::containers;
module sakura::compiler;
#! What numbering knows where it is in the walk: the instruction giving each
#! value worked out so far, by its hash, and each condition known, with what
#! each block added, which leaving it takes back.
struct numbering {
var table: scoped_dict<u64, u32>; #! The instruction giving each value worked out, by its hash.
var facts: scoped_dict<u32, u64>; #! What each condition known is.
var loads: vector<known_load>; #! The reads and writes remembered in the block.
var copies: vector<known_copy>; #! The copies into cells remembered in the block.
var writers: runs<u32>; #! The instructions of each block writing memory, in order, a run each.
var writer_runs: vector<u32>; #! The run of `writers` of each block, by block, 0 where none writes, or `no_run` where they are not yet listed.
var kept: runs<known_load>; #! What each block knew of memory where it ended, a run each.
var kept_runs: vector<u32>; #! The run of `kept` each block knew, by block, or 0 where it knew nothing or dominates no block.
var held_run: u32; #! The run of `kept` the reads and writes remembered are, where they were inherited whole and nothing changed them since, or `no_run`.
var aliases: aliases; #! What may write what.
}
#! A read or write of memory numbering remembers: what is at an address, read
#! as an access reads it.
struct known_load {
var address: u32; #! The address.
var how: u32; #! The access.
var value: u32; #! What is there.
var offset: u64; #! How many bytes past the address it is.
var place: region; #! The bytes it is, as alias analysis tells.
}
#! A copy into a cell numbering remembers: the cell holds what is where it
#! copied from, until something writes.
struct known_copy {
var to: u32; #! The cell's address.
var from: u32; #! The address it copied from.
var size: u64; #! How many bytes it copied.
var to_place: region; #! The bytes it wrote, as alias analysis tells.
var from_place: region; #! The bytes it read.
}
#! What `numbering::held_run` holds where what is remembered of memory is no
#! run kept.
const no_run: u32 = 0xFFFFFFFF;
#! A block on numbering's walk down the tree of which dominates which.
struct numbered_block {
var table: u64; #! How many changes the table had before the block, which leaving it takes back.
var facts: u64; #! How many changes the conditions known had before it.
var next: u32; #! The next of the blocks it immediately dominates to walk, or `no_block`.
}
#! Forgets what numbering remembers of memory, as what writes it does.
#! @param this What numbering knows.
def numbering::forget_memory(&mut this): void {
this.loads.clear();
this.copies.clear();
this.held_run = 0;
}
#! Numbers the values of a function's code, knowing what each call writes
#! what it returns to.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether anything changed.
def lowerer::number_values(&mut this, index: u32): bool {
val writes := this.result_writes(index);
return this.program.functions[index].body.number_values(writes.view());
}
#! Numbers the values of the code, as the file says, walking the blocks down
#! the tree of which dominates which.
#! @param this The code.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @returns Whether anything changed.
pub def code::number_values(&mut this, writes: span<u64>): bool {
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.block_order(&mut order, &mut number);
val idom := this.block_dominators();
# The blocks each block immediately dominates.
var first := vector::<u32>::new(scratch());
var after := vector::<u32>::new(scratch());
first.resize(this.blocks.length, no_block);
after.resize(this.blocks.length, no_block);
var k := order.length;
while k > 1 {
k--;
val block: u32 = order[k];
val parent: u32 = idom[block];
after[block] = first[parent];
first[parent] = block;
}
var state := numbering {
table = scoped_dict::<u64, u32>::new(scratch()),
facts = scoped_dict::<u32, u64>::new(scratch()),
loads = vector::<known_load>::new(scratch()),
copies = vector::<known_copy>::new(scratch()),
writers = runs::<u32>::new(scratch()),
writer_runs = vector::<u32>::new(scratch()),
kept = runs::<known_load>::new(scratch()),
kept_runs = vector::<u32>::new(scratch()),
held_run = 0,
aliases = this.aliases_unfound(writes, idom.view())
};
state.writer_runs.resize(this.blocks.length, no_run);
state.kept_runs.resize(this.blocks.length);
var done := rewrite::new();
# The blocks on the walk, each with where its changes begin.
var stack := vector::<numbered_block>::new(scratch());
stack.append(numbered_block { next = first[0] });
this.number_block(0, &mut state, &mut done);
if first[0] != no_block {
this.keep_memory(0, &mut state);
}
while stack.length != 0 {
# The top is written before a block is pushed, which may move it.
val top := &mut stack.last();
val child := top.next;
if child != no_block {
top.next = after[child];
stack.append(numbered_block { table = state.table.mark(), facts = state.facts.mark(), next = first[child] });
this.learn_entry(child, &mut state);
this.inherit_memory(child, idom[child], &mut state);
this.number_block(child, &mut state, &mut done);
# Only the blocks a block dominates ask what it knew where it ended.
if first[child] != no_block {
this.keep_memory(child, &mut state);
}
continue;
}
# Leaving a block takes back what it added.
state.table.rewind(top.table);
state.facts.rewind(top.facts);
stack.truncate();
}
# Numbering a block had what it reads read what replaces it, and what the
# edges leaving it give; so do those of the blocks the entry does not reach,
# never numbered, and the variables bound.
if done.forward.length != 0 {
for b in 0..this.blocks.length {
continue if this.blocks[b].gone || number[b] != 0xFFFFFFFF;
var walk := this.walk(b as u32);
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
for i in 0..held.argc {
val slot := held.args as u64 + i as u64;
this.operands[slot] = done.resolve(this.operands[slot]);
}
}
this.resolve_edges(b as u32, &done);
}
for i in 0..this.bindings.length {
this.bindings[i].value = done.resolve(this.bindings[i].value);
}
}
this.take_out(&done);
return done.changed;
}
#! Has the edges leaving a block give what replaces what they give.
#! @param this The code.
#! @param block The block.
#! @param done What the pass changes.
def code::resolve_edges(&mut this, block: u32, done: &rewrite): void {
var outs := this.edges_of(this.blocks[block].last);
while outs.more() {
val args := this.edges[outs.next()].args.slice();
for a in 0..args.length {
args[a] = done.resolve(args[a]);
}
}
}
#! Learns what the branch into a block says where only it goes there: its
#! condition is not zero along the way it goes where it is not, and is zero
#! along the other.
#! @param this The code.
#! @param block The block.
#! @param state What numbering knows.
def code::learn_entry(&this, block: u32, state: &mut numbering): void {
return if this.blocks[block].preds.length != 1;
val edge: u32 = this.blocks[block].preds[0];
val from: u32 = this.edges[edge].from;
return if this.insts[from].kind != op::branch;
val cond := this.arg(from, 0);
return if state.facts.contains(&cond);
state.facts.set(cond, edge == this.insts[from].aux ? 1 : 0);
}
#! Begins what numbering knows of memory where a block begins: what the block
#! dominating it knew where it ended, but for what anything on a way from
#! there to the block may write, and nothing where the ways pass too many
#! blocks.
#! @param this The code.
#! @param block The block.
#! @param parent The block dominating it.
#! @param state What numbering knows.
def code::inherit_memory(&this, block: u32, parent: u32, state: &mut numbering): void {
state.forget_memory();
val run: u32 = state.kept_runs[parent];
return if run == 0;
var between := vector::<u32>::new(scratch());
return if !this.blocks_between(parent, block, &mut between);
state.loads.extend(state.kept.view(run));
state.held_run = run;
for &each in between {
this.list_writers(each, state);
for &at in state.writers.view(state.writer_runs[each]) {
this.forget_written(at, state);
return if state.loads.length == 0;
}
}
}
#! Lists the instructions of a block writing memory, where numbering it did not
#! list them already.
#! @param this The code.
#! @param block The block.
#! @param state What numbering knows.
def code::list_writers(&this, block: u32, state: &mut numbering): void {
return if state.writer_runs[block] != no_run;
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
val kind := this.insts[at].kind;
if kind != op::load && (kind.traits() & op_write) != 0 {
state.writers.push(at);
}
}
state.writer_runs[block] = state.writers.end();
}
#! Finds the blocks on the ways from where a block ends to where a block it
#! dominates begins. A way going round a loop through the block it ends at
#! passes that block whole, so it is among them; one coming back through the
#! dominating block begins again where that block ends, which knows what it
#! knows anew. Only so many blocks are looked through.
#! @param this The code.
#! @param parent The dominating block.
#! @param block The block it dominates.
#! @param between Where the blocks are written.
#! @returns Whether they are few enough to be looked through.
def code::blocks_between(&this, parent: u32, block: u32, between: &mut vector<u32>): bool {
val preds := &this.blocks[block].preds;
if preds.length == 1 && this.edge_source(preds[0]) == parent {
return true;
}
var todo := vector::<u32>::new(scratch());
for &edge in preds.view() {
todo.append(this.edge_source(edge));
}
while todo.length != 0 {
val at: u32 = todo.last();
todo.truncate();
continue if at == parent || between.view().contains(&at);
return false if between.length >= 32;
between.append(at);
for &edge in this.blocks[at].preds.view() {
todo.append(this.edge_source(edge));
}
}
return true;
}
#! Forgets what numbering remembers of memory that an instruction may write.
#! @param this The code.
#! @param index The instruction.
#! @param state What numbering knows.
def code::forget_written(&this, index: u32, state: &mut numbering): void {
return if state.loads.length == 0 && state.copies.length == 0;
val written := state.aliases.writes_of(this, index);
this.forget_writing(&written, state);
}
#! Forgets what numbering remembers of memory that what an instruction writes
#! may hold.
#! @param this The code.
#! @param written What the instruction writes.
#! @param state What numbering knows.
def code::forget_writing(&this, written: &writing, state: &mut numbering): void {
return if state.loads.length == 0 && state.copies.length == 0;
state.aliases.find_escaped(this);
var kept: u64 = 0;
for i in 0..state.loads.length {
continue if state.aliases.touches(this, written, &state.loads[i].place);
if kept != i {
state.loads[kept] = state.loads[i];
}
kept++;
}
if kept != state.loads.length {
state.loads.resize(kept);
state.held_run = no_run;
}
var held: u64 = 0;
for i in 0..state.copies.length {
val each: known_copy = state.copies[i];
continue if state.aliases.touches(this, written, &each.to_place) || state.aliases.touches(this, written, &each.from_place);
state.copies[held] = each;
held++;
}
state.copies.resize(held);
}
#! Keeps what numbering knows of memory where a block ends, for the blocks it
#! dominates: the run it inherited, where nothing changed it.
#! @param this The code.
#! @param block The block.
#! @param state What numbering knows.
def code::keep_memory(&this, block: u32, state: &mut numbering): void {
state.kept_runs[block] = state.held_run != no_run ? state.held_run : state.kept.add(state.loads.view());
}
#! Numbers the instructions of a block, in order, from what is known of memory
#! where it begins, which then holds what is known where it ends.
#! @param this The code.
#! @param block The block.
#! @param state What numbering knows.
#! @param done What the pass changes.
def code::number_block(&mut this, block: u32, state: &mut numbering, done: &mut rewrite): void {
# What writes memory is listed as it is met, where it is not listed yet.
val listing := state.writer_runs[block] == no_run;
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
for i in 0..held.argc {
val slot := held.args as u64 + i as u64;
this.operands[slot] = done.resolve(this.operands[slot]);
}
match held.kind {
op::check => {
val cond := this.arg(at, 0);
if state.facts.get(&cond) is some(known) {
if known != 0 {
done.remove(at);
}
} else {
state.facts.set(cond, 1);
}
}
op::branch => {
val cond := this.arg(at, 0);
if state.facts.get(&cond) is some(known) {
# Which cells are escaped is found as the code was, before the
# branch no longer reads its condition.
state.aliases.find_escaped(this);
val bits: u64 = known;
this.operands[held.args] = this.word_value(bits != 0 ? 1 : 0);
done.changed = true;
}
}
op::load => {
this.forward_copy(at, 0, (held.aux as access).width() + held.imm, state, done);
this.number_load(at, state, done);
}
op::copy => this.forward_copy(at, 1, held.imm, state, done);
op::select => this.number_select(at, state, done);
else => {
if this.removable(at) && held.count == 1 {
this.number_inst(at, state, done);
}
}
}
# What writes memory makes what was read of what it may write unknown,
# but for what a store of a whole word writes.
if held.kind != op::load && (held.kind.traits() & op_write) != 0 {
if listing {
state.writers.push(at);
}
if held.kind == op::store && (held.aux == access::i64 as u32 || held.aux == access::f64 as u32) {
# What a store writes is the region it then holds.
val written := state.aliases.writes_of(this, at);
this.forget_writing(&written, state);
state.held_run = no_run;
var base: u32 = 0;
val offset := this.address_base(this.arg(at, 0), held.imm, &mut base);
state.loads.append(known_load {
address = base,
how = held.aux,
value = this.arg(at, 1),
offset = offset,
place = written.place
});
} else {
this.forget_written(at, state);
}
# A cell a copy filled holds what it copied, until something writes.
if held.kind == op::copy && this.cell_of(this.arg(at, 0)) != no_cell
&& this.cell_of(this.arg(at, 0)) != this.cell_of(this.arg(at, 1)) {
val to := this.arg(at, 0);
val from := this.arg(at, 1);
state.copies.append(known_copy {
to = to,
from = from,
size = held.imm,
to_place = state.aliases.region_at(this, to, 0, held.imm),
from_place = state.aliases.region_at(this, from, 0, held.imm)
});
}
}
}
if listing {
state.writer_runs[block] = state.writers.end();
}
this.resolve_edges(block, done);
}
#! Numbers a `select`: one on a condition known where it is, as a dominating
#! check or branch made it, is what it chooses, and otherwise it is numbered as
#! any instruction working out its value is.
#! @param this The code.
#! @param index The `select`.
#! @param state What numbering knows.
#! @param done What the pass changes.
def code::number_select(&mut this, index: u32, state: &mut numbering, done: &mut rewrite): void {
val cond := this.arg(index, 0);
if state.facts.get(&cond) is some(known) {
val bits: u64 = known;
done.replace(this.insts[index].result, this.arg(index, bits != 0 ? 1 : 2));
done.remove(index);
return;
}
this.number_inst(index, state, done);
}
#! Reads what a cell a copy filled holds from where it was copied from
#! instead, where nothing wrote since: a load from it, or a copy out of it into
#! another cell.
#! @param this The code.
#! @param index The `load` or `copy`.
#! @param operand The operand reading the cell.
#! @param reach How far past the cell's address it reads.
#! @param state What numbering knows.
#! @param done What the pass changes.
def code::forward_copy(&mut this, index: u32, operand: u32, reach: u64, state: &mut numbering, done: &mut rewrite): void {
val address := this.arg(index, operand);
for i in 0..state.copies.length {
val each := &state.copies[i];
continue if each.to != address || reach > each.size;
val from := each.from;
# A copy out of it goes on only into a cell, which nothing else overlaps.
if operand == 1 {
val into := this.cell_of(this.arg(index, 0));
return if into == no_cell || into == this.cell_of(from);
}
this.operands[this.insts[index].args as u64 + operand as u64] = from;
done.changed = true;
return;
}
}
#! Numbers a read of memory: one of what the block read or wrote before, with
#! nothing writing between, reads that instead, though one reached through a
#! step past the address the other was.
#! @param this The code.
#! @param index The `load`.
#! @param state What numbering knows.
#! @param done What the pass changes.
def code::number_load(&mut this, index: u32, state: &mut numbering, done: &mut rewrite): void {
val held: inst = this.insts[index];
var address: u32 = 0;
val offset := this.address_base(this.arg(index, 0), held.imm, &mut address);
for i in 0..state.loads.length {
val each := &state.loads[i];
continue if each.address != address || each.offset != offset || each.how != held.aux;
done.replace(held.result, each.value);
done.remove(index);
return;
}
state.held_run = no_run;
state.loads.append(known_load {
address = address,
how = held.aux,
value = held.result,
offset = offset,
place = state.aliases.region_of(this, index, 0)
});
}
#! Where a load or store reaches, as a value and how many bytes past it: a step
#! of a constant past another value reaches as far past that one, so the bytes
#! it reaches are known as the same as those reached from it directly.
#! @param this The code.
#! @param address The address the load or store is given.
#! @param offset How many bytes past it the load or store reaches.
#! @param base Where the value it reaches past is written.
#! @returns How many bytes past that value it reaches.
def code::address_base(&this, address: u32, offset: u64, base: &mut u32): u64 {
base = address;
val index := this.defining(address);
return offset if index == 0 || this.insts[index].kind != op::add;
var bits: u64 = 0;
return offset if !this.word_constant(this.arg(index, 1), &mut bits);
base = this.arg(index, 0);
return offset + bits;
}
#! Numbers an instruction that only works out its value: one working out what
#! one dominating it did reads that instead.
#! @param this The code.
#! @param index The instruction.
#! @param state What numbering knows.
#! @param done What the pass changes.
def code::number_inst(&mut this, index: u32, state: &mut numbering, done: &mut rewrite): void {
val hash := this.hash_inst(index);
if state.table.get(&hash) is some(got) {
val other: u32 = got;
if this.same_inst(index, other) {
done.replace(this.insts[index].result, this.insts[other].result);
done.remove(index);
return;
}
}
state.table.set(hash, index);
}
#! The hash of what an instruction works out: its operation, what its `aux`
#! and `imm` hold, the type of its value, and its operands, in either order
#! where the operation does not mind which.
#! @param this The code.
#! @param index The instruction.
#! @returns The hash.
def code::hash_inst(&this, index: u32): u64 {
val held: inst = this.insts[index];
var hash := mix_hash(mix_hash(mix_hash(0xCBF29CE484222325u, held.kind as u64), held.aux as u64), held.imm);
hash = mix_hash(hash, this.origins[held.result].kind as u64);
if held.argc == 2 && commutes(held.kind) {
val a := this.arg(index, 0);
val b := this.arg(index, 1);
hash = mix_hash(mix_hash(hash, (a < b ? a : b) as u64), (a < b ? b : a) as u64);
return hash;
}
for i in 0..held.argc {
hash = mix_hash(hash, this.arg(index, i as u32) as u64);
}
return mix_hash(hash, held.argc as u64);
}
#! Whether two instructions work out the same. Their values are of one type,
#! as a `vzero` of 16 bytes and one of 32 are not the same.
#! @param this The code.
#! @param a One instruction.
#! @param b The other.
#! @returns Whether they do.
def code::same_inst(&this, a: u32, b: u32): bool {
val x: inst = this.insts[a];
val y: inst = this.insts[b];
return false if x.kind != y.kind || x.aux != y.aux || x.imm != y.imm || x.argc != y.argc;
return false if this.origins[x.result].kind != this.origins[y.result].kind;
if x.argc == 2 && commutes(x.kind) {
val a0 := this.arg(a, 0);
val a1 := this.arg(a, 1);
val b0 := this.arg(b, 0);
val b1 := this.arg(b, 1);
return (a0 == b0 && a1 == b1) || (a0 == b1 && a1 == b0);
}
for i in 0..x.argc {
return false if this.arg(a, i as u32) != this.arg(b, i as u32);
}
return true;
}
#! Mixes a word into a hash.
#! @param hash The hash so far.
#! @param value The word.
#! @returns The hash.
def mix_hash(hash: u64, value: u64): u64 {
return (hash ^ value) * 0x100000001B3u;
}
#! Moves each constant made within a loop first into the entry, one of each,
#! so the machine makes it once a call rather than each time the loop goes
#! round, as it does the address of a cell, a global, or a datum. One made
#! outside every loop stays, since making it at the entry would make it where
#! nothing reads it.
#! @param this The code.
#! @returns Whether anything changed.
pub def code::hoist_constants(&mut this): bool {
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.block_order(&mut order, &mut number);
val looped := this.loop_blocks(order.view(), number.view());
var done := rewrite::new();
var words := dict::<u64, u32>::new(scratch());
var reals := dict::<u64, u32>::new(scratch());
var moved := vector::<u32>::new(scratch());
for &block in order {
continue if block != 0 && !looped[block];
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
if block != 0 && (held.kind == op::cell || held.kind == op::global || held.kind == op::datum) {
done.remove(at);
moved.append(at);
} else if held.kind == op::iconst || held.kind == op::fconst {
val seen := held.kind == op::iconst ? &mut words : &mut reals;
if seen.get(&held.imm) is some(got) {
done.replace(held.result, got);
done.remove(at);
} else {
seen.set(held.imm, held.result);
if block != 0 {
done.remove(at);
moved.append(at);
}
}
}
}
}
this.apply(&done);
var i := moved.length;
while i > 0 {
i--;
this.put_first(0, moved[i]);
}
return done.changed;
}
#! Which blocks are within a loop: those from which an edge going back to a
#! block dominating them is reached, without passing that block, and that
#! block.
#! @param this The code.
#! @param order The blocks in reverse postorder.
#! @param number Each block's place in that order.
#! @returns Whether each block is within a loop.
pub def code::loop_blocks(&mut this, order: span<u32>, number: span<u32>): vector<bool> {
var looped := vector::<bool>::new(scratch());
looped.resize(this.blocks.length);
# The dominators are asked for only where an edge may go back.
var back := false;
for &block in order {
for &edge in this.blocks[block].preds {
back = back || number[this.edge_source(edge)] >= number[block];
}
}
return looped if !back;
val idom := this.block_dominators();
var todo := vector::<u32>::new(scratch());
for &block in order {
for &edge in this.blocks[block].preds {
val from := this.edge_source(edge);
continue if number[from] < number[block] || !dominates(&idom, block, from);
# A loop headed by the block: walk back from where it goes back.
looped[block] = true;
todo.append(from);
while todo.length != 0 {
val at: u32 = todo.last();
todo.truncate();
continue if at == block || looped[at] && at != from;
looped[at] = true;
for &inner in this.blocks[at].preds {
val back := this.edge_source(inner);
if back != block && !looped[back] {
todo.append(back);
}
}
}
}
}
return looped;
}
+575
View File
@@ -0,0 +1,575 @@
#! @file optimizer.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the optimizer, which runs passes over the code of each function
#! once the program is lowered. Each pass is small, in a file of its own, and
#! leaves the code well formed, which the verifier checks after each where
#! lowering verifies. `-O0` runs none, `-O1` simplification, control flow
#! cleanup, value numbering, and dead code removal, and `-O2` those with
#! inlining and the promotion of cells to values. Below `-O2`, calls of
#! `@inline` functions are inlined all the same, and nothing else is, so at
#! `-O0` the code is as written but for those, each local of the code copied
#! still in a cell of its own. The slots the passes leave are compacted away
#! at the end, which the backends and the functions inlining the code read.
#! Functions are optimized after the functions they call, so a function
#! inlined is already optimized.
#! At `-O2`, a function of an executable asking which vector instructions the
#! processor has is given a version for x86-64-v3's, as `versions.sakura` says.
import std::containers;
module sakura::compiler;
#! The passes, as a problem a pass leaves names them.
pub enum pass : u8 {
simplify, #! Folding constants and simplifying operations.
dead, #! Taking out what nothing needs.
control, #! Cleaning up how control flows.
inline, #! Inlining calls of small functions.
promote, #! Promoting cells to values.
numbering, #! Numbering values.
hoist, #! Moving constants into the entry.
memory, #! Cleaning up the memory of cells.
loops, #! Rotating loops and moving out of them what they work out the same each time round.
sink, #! Moving what is read past one way out of a block into that way.
count, #! How many passes there are; not a pass itself.
}
#! The name of a pass, as a problem names it.
#! @param this The pass.
#! @returns Its name.
pub def pass::name(&this): strview {
return match this {
pass::simplify => "simplification",
pass::dead => "dead code removal",
pass::control => "control flow cleanup",
pass::inline => "inlining",
pass::promote => "promotion",
pass::numbering => "value numbering",
pass::hoist => "constant hoisting",
pass::memory => "memory cleanup",
pass::loops => "loop optimization",
pass::sink => "code sinking",
else => "a pass"
};
}
#! Optimizes every function lowered and not yet optimized, as its level says,
#! each after those it calls, but for those calling each other, which go in the
#! order met. The order is worked out first, walking the calls, and a function
#! inlines only those before it, so what each is made into is the same however
#! many threads optimize them: as many as the options say work at once, each
#! taking a function once those before it that it calls are done. A function
#! the one calling it alone copies whole is optimized there, so only the passes
#! up to inlining run on it before, and the rest after, where something still
#! reaches it, as a cold call does. The versions of those asking which
#! instructions the processor has are made after, in the order, as each reads
#! what came before its function.
#! @param this The compiler.
pub def lowerer::optimize(&mut this): void {
return if this.options.level == 0 && !this.copies_marked();
var plan := this.plan_optimizing();
val count := plan.order.length;
# What verifying each function finds, kept by its place in the order, so it
# is noted in that order whichever thread found it.
var found := vector::<vector<string>>::new();
found.resize(count);
val compiler := &mut this;
share_out_ordered(count, this.options.threads, &plan.waiting, def(place: u64): void {
compiler.optimize_at(&plan, place, &mut found[place]);
});
# Those left for the function calling them that something still reaches, as
# one whose call is cold, have the rest of their passes run, each on its own,
# whichever optimizing left them.
var finishing := this.left_unfinished();
var alone := groups::<u32>::new(0);
alone.reset(finishing.length);
alone.seal();
var noted := vector::<vector<string>>::new();
noted.resize(finishing.length);
share_out_ordered(finishing.length, this.options.threads, &alone, def(k: u64): void {
compiler.finish_unfinished(finishing[k], &plan.ranks, &mut noted[k]);
});
for &each in found {
for &text in each {
this.problems.append(string::copy_of(&text));
}
}
for &each in noted {
for &text in each {
this.problems.append(string::copy_of(&text));
}
}
if this.versions_made() {
for place in 0..count {
this.make_version(plan.order[place], &mut plan.ranks, (2 * place + 3) as u32);
}
}
this.merge_all();
}
#! Merges the stores filling 16 bytes of a cell, in each function of an
#! executable optimized, once nothing more is inlined, as `merge.sakura` says.
#! @param this The compiler.
def lowerer::merge_all(&mut this): void {
for i in 0..this.program.functions.length {
val function := &mut this.program.functions[i];
continue if !function.optimized || !function.body.vectors;
val point := mark_scratch();
if function.body.merge_stores() {
function.body.compact();
if this.options.verify {
val verdict := function.body.verify();
for &each in verdict.problems {
this.problems.append($"{function.name}: after merging stores: {each}");
}
}
}
release_scratch(point);
}
}
#! Whether calls of `@inline` functions are inlined below `-O2`, which inlines
#! nothing else: but where the program evaluates constants, or runs with its
#! memory checked, as each function's locals end where its frame does then.
#! @param this The compiler.
#! @returns Whether they are.
def lowerer::inlines_marked(&this): bool {
return !this.options.evaluating && !this.options.checks;
}
#! Whether `-O0`, which optimizes nothing, has calls to inline all the same:
#! where a function lowered is `@inline`.
#! @param this The compiler.
#! @returns Whether it has.
def lowerer::copies_marked(&this): bool {
return false if !this.inlines_marked();
for &each in this.program.functions {
return true if each.inline && each.lowered;
}
return false;
}
#! Where a function never optimized is in the order functions are optimized in.
const unranked: u32 = 0xFFFFFFFF;
#! The order functions are optimized in, and what each waits for.
struct optimizing {
var order: vector<u32>; #! The functions, each after those it calls, but for those calling each other.
var ranks: vector<u32>; #! Of each function, `2k + 2` where it is the `k`th in the order, `2k + 3` where it is the version of that one, 0 where it was optimized before, and `unranked` where it is not optimized.
var waiting: groups<u32>; #! The places in the order of those waiting on each, by its place: each calls it, and comes after it.
}
#! A function on the walk of the calls that orders functions to be optimized.
struct calling {
var function: u32; #! The function.
var begin: u64; #! Where the functions it calls begin among the calls of those on the walk.
var end: u64; #! Where they end.
var next: u64; #! The next of them to walk.
}
#! Works out the order functions are optimized in: walking the calls from each
#! function lowered and not yet optimized, each once those it calls are, but
#! for those calling each other, which go in the order met. Each waits for the
#! functions before it that it calls.
#! @param this The compiler.
#! @returns The order.
def lowerer::plan_optimizing(&mut this): optimizing {
val count := this.program.functions.length;
var plan := optimizing {
order = vector::<u32>::new(),
ranks = vector::<u32>::new(),
waiting = groups::<u32>::new(0)
};
var seen := vector::<bool>::new();
seen.resize(count);
plan.ranks.resize(count);
for i in 0..count {
if this.program.functions[i].optimized {
seen[i] = true;
this.ready_to_inline(i as u32);
} else {
plan.ranks[i] = unranked;
}
}
# The functions on the walk, each with the functions it calls in `calls`.
# The callees of each function in the order are kept in `callees`, a run of
# each.
var stack := vector::<calling>::new();
var calls := vector::<u32>::new();
var callees := runs::<u32>::new();
var callee_runs := vector::<u32>::new();
for root in 0..count {
continue if seen[root] || !this.program.functions[root].lowered;
this.walk_into(root as u32, &mut seen, &mut stack, &mut calls);
while stack.length != 0 {
# The top is written before a callee is pushed, which may move it.
val top := &mut stack.last();
if top.next < top.end {
val callee: u32 = calls[top.next];
top.next++;
if !seen[callee] && this.program.functions[callee].lowered {
this.walk_into(callee, &mut seen, &mut stack, &mut calls);
}
continue;
}
callee_runs.append(callees.add(span::<u32>::over(calls.view().data + top.begin, top.end - top.begin)));
plan.ranks[top.function] = (2 * plan.order.length + 2) as u32;
plan.order.append(top.function);
calls.resize(top.begin);
stack.truncate();
}
}
# Each function waits for those before it that it calls, each once, as the
# functions counted for it say.
val placed := plan.order.length;
var counted := stamped_set::new(placed, nothing {});
var pairs := vector::<u64>::new();
plan.waiting.reset(placed);
for p in 0..placed {
counted.next_round();
for &callee in callees.view(callee_runs[p]) {
val rank: u32 = plan.ranks[callee];
continue if rank == 0 || rank == unranked;
val q := (rank - 2) / 2;
continue if q as u64 >= p || !counted.insert(q);
pairs.append(pair_key(q, p as u32));
plan.waiting.count(q);
}
}
plan.waiting.seal();
for &pair in pairs {
plan.waiting.put(pair_high(pair), pair_low(pair));
}
this.find_sole_calls(&plan.order);
# A call of a function this one waits for is settled, and stays so where it is
# inlined into another, which waited for this one.
for p in 0..placed {
val function: u32 = plan.order[p];
val body := &mut this.program.functions[function].body;
var walk := body.walk_all();
while walk.more() {
val at := walk.next();
continue if body.insts[at].kind != op::call;
val rank: u32 = plan.ranks[body.insts[at].aux];
body.insts[at].imm = rank != 0 && rank != unranked && rank < plan.ranks[function] ? call_settled : 0;
}
}
return plan;
}
#! Puts a function on the walk, with the functions it calls.
#! @param this The compiler.
#! @param function The function.
#! @param seen Whether each function was put on the walk.
#! @param stack The functions on the walk.
#! @param calls The callees of the functions on the walk.
def lowerer::walk_into(&mut this, function: u32, seen: &mut vector<bool>, stack: &mut vector<calling>, calls: &mut vector<u32>): void {
seen[function] = true;
val begin := calls.length;
val body := &this.program.functions[function].body;
var walk := body.walk_all();
while walk.more() {
val at := walk.next();
if body.insts[at].kind == op::call {
calls.append(body.insts[at].aux);
}
}
# A function named as a value may be called directly once the value is known,
# so it is waited for as one called is.
for &named in this.program.functions[function].named.view() {
calls.append(named);
}
stack.append(calling { function = function, begin = begin, end = calls.length, next = begin });
}
#! Optimizes the function of a place in the order, then readies it to be
#! inlined.
#! @param this The compiler.
#! @param plan The order.
#! @param place The place.
#! @param found Where what verifying it finds is noted.
def lowerer::optimize_at(&mut this, plan: &optimizing, place: u64, found: &mut vector<string>): void {
val function: u32 = plan.order[place];
this.optimize_function(function, &plan.ranks, (2 * place + 2) as u32, found);
this.program.functions[function].optimized = true;
this.ready_to_inline(function);
}
#! Finds the functions left unfinished that something still reaches.
#! @param this The compiler.
#! @returns The functions, in order.
def lowerer::left_unfinished(&mut this): vector<u32> {
var left := vector::<u32>::new();
val count := this.program.functions.length;
var any := false;
for i in 0..count {
any = any || this.program.functions[i].unfinished;
}
return left if !any;
val point := mark_scratch();
var reached := worklist::new(count, scratch());
this.reach_functions(&mut reached);
for i in 0..count {
if this.program.functions[i].unfinished && reached.has(i as u32) {
left.append(i as u32);
}
}
release_scratch(point);
return left;
}
#! Runs the rest of the passes on a function left unfinished, then readies it
#! to be inlined again, as its code changed.
#! @param this The compiler.
#! @param function The function.
#! @param ranks Where each function is in the order functions are
#! optimized in, which none of the passes left inlines by.
#! @param found Where what verifying it finds is noted.
def lowerer::finish_unfinished(&mut this, function: u32, ranks: &vector<u32>, found: &mut vector<string>): void {
var sweep := passes { ranks = ranks, rank = 0, found = found, compacted = 0xFFFFFFFF };
for i in 0..pass::count as u64 {
sweep.clean[i] = 0xFFFFFFFF;
}
this.finish_function(function, &mut sweep);
val held := &mut this.program.functions[function];
held.unfinished = false;
held.inlining = inline_facts { sole = held.inlining.sole };
held.order.clear();
this.ready_to_inline(function);
}
#! Works out what inlining an optimized function asks of it, as its code no
#! longer changes, rather than leave that to the first function inlining it,
#! as several may at once on threads of their own: what inlining knows of it,
#! and where it may be copied, the order its blocks are copied in.
#! @param this The compiler.
#! @param function The function.
def lowerer::ready_to_inline(&mut this, function: u32): void {
# Below `-O2`, only `@inline` functions are.
return if this.options.level < 2 && !this.program.functions[function].inline;
val point := mark_scratch();
if this.inline_facts(function).fits {
this.order_blocks(function);
}
release_scratch(point);
}
#! Optimizes one function, as its level says. A pass that found nothing to
#! change is not run again until another changes something.
#! @param this The compiler.
#! @param index The function.
#! @param ranks Where each function is in the order functions are optimized
#! in, as `optimizing` says: those before it are inlined.
#! @param rank Where the function is.
#! @param found Where what verifying it finds is noted.
def lowerer::optimize_function(&mut this, index: u32, ranks: &vector<u32>, rank: u32, found: &mut vector<string>): void {
var sweep := passes { ranks = ranks, rank = rank, found = found, compacted = 0xFFFFFFFF };
for i in 0..pass::count as u64 {
sweep.clean[i] = 0xFFFFFFFF;
}
# `-O0` inlines the calls of `@inline` functions, and changes nothing else.
if this.options.level == 0 {
this.sweep(index, &mut sweep, pass::inline);
if sweep.changes != 0 {
this.compact_function(index, &mut sweep);
}
return;
}
this.sweep(index, &mut sweep, pass::simplify);
this.sweep(index, &mut sweep, pass::control);
if this.options.level < 2 && this.inlines_marked() {
this.sweep(index, &mut sweep, pass::inline);
}
if this.options.level >= 2 {
this.sweep(index, &mut sweep, pass::dead);
this.sweep(index, &mut sweep, pass::inline);
this.sweep(index, &mut sweep, pass::promote);
this.sweep(index, &mut sweep, pass::simplify);
this.sweep(index, &mut sweep, pass::control);
# Promoting may show which function a value calls, which is then called and
# inlined as any other.
this.sweep(index, &mut sweep, pass::inline);
this.sweep(index, &mut sweep, pass::promote);
this.sweep(index, &mut sweep, pass::simplify);
this.sweep(index, &mut sweep, pass::control);
# The function calling it copies it whole and optimizes it there, so the
# rest is left until then, and run after only where it is still called.
if this.awaits_caller(index) {
this.program.functions[index].unfinished = true;
return;
}
}
this.finish_function(index, &mut sweep);
}
#! Runs the passes after inlining on a function's code, then compacts it.
#! @param this The compiler.
#! @param index The function.
#! @param sweep What is known of the passes run on it.
def lowerer::finish_function(&mut this, index: u32, sweep: &mut passes): void {
this.sweep(index, sweep, pass::numbering);
this.sweep(index, sweep, pass::memory);
this.sweep(index, sweep, pass::dead);
this.sweep(index, sweep, pass::loops);
this.sweep(index, sweep, pass::numbering);
this.sweep(index, sweep, pass::simplify);
this.sweep(index, sweep, pass::control);
this.sweep(index, sweep, pass::sink);
# What sinking moved past a branch, as a `select` on the condition the branch
# tests, is numbered again where the branch decided it.
this.sweep(index, sweep, pass::numbering);
this.sweep(index, sweep, pass::dead);
this.sweep(index, sweep, pass::hoist);
this.compact_function(index, sweep);
}
#! Whether a function, its calls inlined, is left for the function calling it
#! to optimize: that alone calls it, and copies it whole, as it may be copied,
#! asks nothing of the processor, and leaves that function room to grow.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether it is.
def lowerer::awaits_caller(&this, index: u32): bool {
val held := &this.program.functions[index];
return false if held.inlining.sole == 0 || held.closure || held.evaluation != 0;
var size: u32 = 0;
var walk := held.body.walk_all();
while walk.more() {
match held.body.insts[walk.next()].kind {
op::frame, op::ready, op::reach, op::same, op::cpu => { return false; }
else => {}
}
size++;
}
return size <= sole_growth;
}
#! What optimizing one function knows of the passes run on it.
struct passes {
var ranks: &vector<u32>; #! Where each function is in the order functions are optimized in.
var rank: u32; #! Where the function is.
var found: &mut vector<string>; #! What verifying it finds.
var changes: u32; #! How many passes changed something.
var compacted: u32; #! How many passes had changed something when the code was last compacted, or `0xFFFFFFFF` before it was.
var clean: u32[pass::count as u64]; #! How many passes had changed something when each last found nothing to change.
}
#! Runs a pass over a function's code, but where it found nothing to change
#! since any pass last changed something.
#! @param this The compiler.
#! @param index The function.
#! @param sweep What is known of the passes run on it.
#! @param which The pass.
def lowerer::sweep(&mut this, index: u32, sweep: &mut passes, which: pass): void {
return if sweep.clean[which as u64] == sweep.changes;
if this.run_pass(index, which, sweep) {
sweep.changes++;
} else {
sweep.clean[which as u64] = sweep.changes;
}
}
#! Compacts a function's code where a pass changed it since it was last
#! compacted, then verifies it where lowering verifies.
#! @param this The compiler.
#! @param index The function.
#! @param sweep What is known of the passes run on it.
def lowerer::compact_function(&mut this, index: u32, sweep: &mut passes): void {
return if sweep.compacted == sweep.changes;
sweep.compacted = sweep.changes;
val point := mark_scratch();
this.program.functions[index].body.compact();
if this.options.verify {
val verdict := this.program.functions[index].body.verify();
for &each in verdict.problems {
sweep.found.append($"{this.program.functions[index].name}: after compacting: {each}");
}
}
release_scratch(point);
}
#! Cleans up the memory of the cells of a function's code, knowing what each
#! call writes what it returns to.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether anything changed.
def lowerer::clean_memory(&mut this, index: u32): bool {
val writes := this.result_writes(index);
return this.program.functions[index].body.clean_memory(writes.view());
}
#! How many bytes each call of a function's code writes what it returns to, at
#! the address its last operand gives, as `emitter::call_with` passes it. Each
#! instruction is looked at where it lies, those taken out too, which nothing
#! asks of.
#! @param this The compiler.
#! @param index The function.
#! @returns The bytes, by instruction, or 0 for what writes none.
pub def lowerer::result_writes(&this, index: u32): vector<u64> {
val body := &this.program.functions[index].body;
var writes := vector::<u64>::new(scratch());
writes.resize(body.insts.length);
for at in 1..body.insts.length {
val kind := body.insts[at].kind;
val aux: u32 = body.insts[at].aux;
var signature: u32 = no_function;
if kind == op::call {
signature = this.program.functions[aux].signature;
} else if kind == op::call_trait || kind == op::call_value || kind == op::call_c {
signature = aux;
}
continue if signature == no_function;
val shape := this.layout_at(this.program.signatures[signature].result);
if returned_in_memory(&shape) {
writes[at] = shape.size;
}
}
return writes;
}
#! Runs a pass over a function's code, then verifies it where lowering
#! verifies, noting what is wrong with what the pass left.
#! @param this The compiler.
#! @param index The function.
#! @param which The pass.
#! @param sweep What is known of the passes run on it.
#! @returns Whether the pass changed anything.
def lowerer::run_pass(&mut this, index: u32, which: pass, sweep: &mut passes): bool {
# What the pass and the verifier work out is freed as the pass ends.
val point := mark_scratch();
val body := &mut this.program.functions[index].body;
val changed := match which {
pass::simplify => body.simplify(this.program.data.view()),
pass::dead => body.remove_dead(),
pass::control => body.clean_control(),
pass::inline => this.inline_calls(index, sweep.ranks, sweep.rank),
pass::promote => body.promote_cells(),
pass::numbering => this.number_values(index),
pass::hoist => body.hoist_constants(),
pass::memory => this.clean_memory(index),
pass::loops => this.optimize_loops(index),
pass::sink => this.sink_code(index),
else => false
};
# Each pass forgets the order and dominators the code keeps where it changes
# where blocks lead, or works them out anew, as pruning does after inlining,
# so they hold for the code it leaves.
if this.options.verify && changed {
val verdict := this.program.functions[index].body.verify();
for &each in verdict.problems {
sweep.found.append($"{this.program.functions[index].name}: after {which.name()}: {each}");
}
}
release_scratch(point);
return changed;
}
+887
View File
@@ -0,0 +1,887 @@
#! @file promote.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the fifth pass of the optimizer, which promotes cells to values: a
#! cell whose address is only read from, written to, zeroed, or copied in and
#! out from its start, at offsets that do not overlap, holds values rather than
#! memory. Each word it holds becomes a variable, and the code is rebuilt as it
#! was built, each read reading what the variable holds there, which where
#! control flow joins is a parameter of the block. The bytes a copy moves that
#! nothing reads or writes alone are words of their own, so a value copied from
#! one cell to another and on is promoted whole. Inlining leaves many such
#! cells, where a function took the address of what it was given or returned.
#! A `simd` read and written whole becomes one vector, which an executable holds
#! in a vector register, but 32 bytes only in code for processors with AVX.
import std::containers;
module sakura::compiler;
#! A word a cell promoted holds: where it is in the cell, how wide it is, and
#! the type of value it holds.
struct slot {
var cell: u32; #! The cell.
var offset: u64; #! Where it begins.
var size: u64; #! How many bytes it is.
var kind: vt; #! The type of value it holds.
var signed: bool; #! Whether it is read as a signed integer narrower than a word, which a copy narrows it as too.
var next: u32; #! One more than the next slot of the same cell, or 0.
var used: bool; #! Whether anything reads what it holds, or copies it out.
}
#! What promoting knows of the cells of the code.
struct promotion {
var escaped: vector<bool>; #! Whether each cell's address is used as more than an address read and written through.
var extent: vector<u64>; #! How many bytes from its start the copies in and out of each cell move, which its slots must cover.
var slots: vector<slot>; #! The words of the cells, each once.
var heads: vector<u32>; #! One more than the first slot of each cell, or 0, its others following by `next`.
var addresses: cell_table; #! Which cell each value is the address of.
var ends: dict<u64, u32>; #! The value each slot holds at the end of each block that writes it, by `pair_key(slot, block)`.
var starts: dict<u64, u32>; #! The value each slot holds at the start of each block asked, by `pair_key(slot, block)`.
var zeros: zero_values; #! The zero of each type, made once.
var wide: bool; #! Whether 32 bytes of lanes may be a value.
var vectors: bool; #! Whether 16 bytes of lanes may be, as an executable's code holds them.
var pairs: vector<u32>; #! The copies from one cell into another.
var copies: dict<u64, u32>; #! The read each copy into a cell promoted makes of each slot, by `pair_key(copy, slot)`.
var touch: vector<u32>; #! The instructions naming a cell, as operands or as what their edges give.
var current: vector<u32>; #! What each slot holds where the walk of a block is, where the block wrote it.
var written: stamped_set; #! The slots the block being rewritten wrote so far, a round each block.
var dense: u64; #! How many blocks `ends` and `starts` are held for in `dense_ends` and `dense_starts`, by slot then block, or 0 where they are not.
var dense_ends: vector<u32>; #! What `ends` holds, where it is dense, 0 for nothing.
var dense_starts: vector<u32>; #! What `starts` holds, where it is dense.
}
#! What `promotion::slot_at` gives where a cell has no slot at an offset.
const no_slot: u32 = 0xFFFFFFFF;
#! The most slots of every block the values they hold at each block's ends are
#! held for one after another, rather than by key.
const dense_slot_blocks: u64 = 65536;
#! The value a slot holds where a block ends, where the block writes it.
#! @param this What promoting knows.
#! @param s The slot.
#! @param block The block.
#! @returns The value, or 0.
def promotion::end_at(&this, s: u32, block: u32): u32 {
return this.dense_ends[s as u64 * this.dense + block as u64] if this.dense != 0;
val key := pair_key(s, block);
return this.ends.get_or(&key, 0);
}
#! Notes the value a slot holds where a block ends.
#! @param this What promoting knows.
#! @param s The slot.
#! @param block The block.
#! @param value The value.
def promotion::set_end(&mut this, s: u32, block: u32, value: u32): void {
if this.dense != 0 {
this.dense_ends[s as u64 * this.dense + block as u64] = value;
return;
}
this.ends.set(pair_key(s, block), value);
}
#! The value a slot holds where a block begins, where it is known.
#! @param this What promoting knows.
#! @param s The slot.
#! @param block The block.
#! @returns The value, or 0.
def promotion::start_at(&this, s: u32, block: u32): u32 {
return this.dense_starts[s as u64 * this.dense + block as u64] if this.dense != 0;
val key := pair_key(s, block);
return this.starts.get_or(&key, 0);
}
#! Notes the value a slot holds where a block begins.
#! @param this What promoting knows.
#! @param s The slot.
#! @param block The block.
#! @param value The value.
def promotion::set_start(&mut this, s: u32, block: u32, value: u32): void {
if this.dense != 0 {
this.dense_starts[s as u64 * this.dense + block as u64] = value;
return;
}
this.starts.set(pair_key(s, block), value);
}
#! Promotes the cells that can be, as the file says.
#! @param this The code.
#! @returns Whether any was.
pub def code::promote_cells(&mut this): bool {
return false if this.cells.length == 0;
var state := promotion {
escaped = vector::<bool>::new(scratch()),
extent = vector::<u64>::new(scratch()),
slots = vector::<slot>::new(scratch()),
heads = vector::<u32>::new(scratch()),
addresses = this.cell_table(),
ends = dict::<u64, u32>::new(scratch()),
starts = dict::<u64, u32>::new(scratch()),
copies = dict::<u64, u32>::new(scratch()),
pairs = vector::<u32>::new(scratch()),
touch = vector::<u32>::new(scratch()),
current = vector::<u32>::new(scratch()),
written = stamped_set::new(0, scratch()),
dense_ends = vector::<u32>::new(scratch()),
dense_starts = vector::<u32>::new(scratch()),
wide = this.wide,
vectors = this.vectors
};
return false if !state.addresses.any;
state.escaped.resize(this.cells.length);
state.extent.resize(this.cells.length);
state.heads.resize(this.cells.length);
# A copy from a cell its words cover into another is the reads and writes of
# each word, which then promote as any others, so the words of the cells
# are found again, as many times as a value is copied on.
this.find_touches(&mut state);
var rounds := 0;
while true {
rounds++;
this.find_slots(&mut state);
break if rounds == 4 || !this.split_pairs(&mut state);
for c in 0..this.cells.length {
state.escaped[c] = false;
state.extent[c] = 0;
state.heads[c] = 0;
}
state.slots.clear();
state.pairs.clear();
}
this.settle_pairs(&mut state);
var promoted := false;
for c in 0..this.cells.length {
if !state.escaped[c] {
promoted = true;
}
}
return false if !promoted;
# Where control flow joins, slots are found in the order of the blocks.
if state.slots.length * this.blocks.length <= dense_slot_blocks {
state.dense = this.blocks.length;
state.dense_ends.resize(state.slots.length * state.dense);
state.dense_starts.resize(state.slots.length * state.dense);
}
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.block_order(&mut order, &mut number);
for &block in order {
this.note_ends(block, &mut state);
}
var done := rewrite::new();
state.current.resize(state.slots.length);
state.written = stamped_set::new(state.slots.length, scratch());
for &block in order {
state.written.next_round();
this.rewrite_slots(block, &mut state, &mut done);
}
this.apply(&done);
this.drop_unreached();
this.drop_lone_params();
return true;
}
#! Finds the instructions naming a cell, which are all that finding slots
#! walks.
#! @param this The code.
#! @param state What promoting knows.
def code::find_touches(&this, state: &mut promotion): void {
state.touch.clear();
var walk := this.walk_all();
var reads := this.reader();
while walk.more() {
val at := walk.next();
reads.start(at);
while reads.more() {
if state.addresses.cell(reads.next()) != 0 {
state.touch.append(at);
break;
}
}
}
}
#! Leaves memory the cell each copy between cells neither escaped comes from,
#! where the copy was not split, so the copy is one out of memory into the one
#! it goes to.
#! @param this The code.
#! @param state What promoting knows.
def code::settle_pairs(&this, state: &mut promotion): void {
var changed := false;
for &copy in state.pairs {
val to := state.addresses.cell(this.arg(copy, 0)) - 1;
val from := state.addresses.cell(this.arg(copy, 1)) - 1;
if !state.escaped[to] && !state.escaped[from] {
state.escaped[from] = true;
changed = true;
}
}
if changed {
this.find_uses(state);
}
}
#! Marks the slots of the cells not escaped that something reads, or copies
#! out of its cell, so a copy into the cell reads only those from where it
#! copies, and a slot read only as a copy moves it into another is used where
#! the other's is.
#! @param this The code.
#! @param state What promoting knows.
def code::find_uses(&this, state: &mut promotion): void {
for i in 0..state.slots.length {
state.slots[i].used = false;
}
for t in 0..state.touch.length {
val at: u32 = state.touch[t];
val held: inst = this.insts[at];
continue if held.kind != op::load && held.kind != op::copy;
val operand: u32 = held.kind == op::load ? 0 : 1;
val cell := state.addresses.cell(this.arg(at, operand));
val into := held.kind == op::copy ? state.addresses.cell(this.arg(at, 0)) : 0;
val moved := into != 0 && !state.escaped[into - 1];
continue if cell == 0 || state.escaped[cell - 1] || moved;
var i: u32 = state.heads[cell - 1];
while i != 0 {
val each: slot = state.slots[i - 1];
if (held.kind == op::load && each.offset == held.imm) || (held.kind == op::copy && each.offset < held.imm) {
state.slots[i - 1].used = true;
}
i = each.next;
}
}
var changed := true;
var rounds := 0;
while changed && rounds < 8 {
rounds++;
changed = false;
for p in 0..state.pairs.length {
val copy: u32 = state.pairs[p];
val to := state.addresses.cell(this.arg(copy, 0)) - 1;
val from := state.addresses.cell(this.arg(copy, 1)) - 1;
continue if state.escaped[to] || state.escaped[from];
var i: u32 = state.heads[from];
while i != 0 {
val each: slot = state.slots[i - 1];
if !each.used && each.offset < this.insts[copy].imm && state.used_over(to, each.offset, each.size) {
state.slots[i - 1].used = true;
changed = true;
}
i = each.next;
}
}
}
}
#! Finds how each cell's address is used, and the words each cell not escaped
#! holds, marking escaped a cell its words do not fit, and which of its words
#! are used. Copies between cells are gathered, to be split.
#! @param this The code.
#! @param state What promoting knows, whose instructions naming cells are
#! found.
def code::find_slots(&this, state: &mut promotion): void {
var reads := this.reader();
for t in 0..state.touch.length {
val at: u32 = state.touch[t];
val held: inst = this.insts[at];
reads.start(at);
while reads.more() {
val cell := state.addresses.cell(reads.next());
continue if cell == 0;
val c := cell - 1;
val i := reads.operand();
# A cell's address an edge gives escapes.
if i == no_operand {
state.escaped[c] = true;
continue;
}
match held.kind {
op::load => {
val how := held.aux as access;
state.add_slot(c, held.imm, how.width(), how.value_type(), narrow_signed(how));
}
op::store => {
if i == 0 {
state.add_slot(c, held.imm, (held.aux as access).width(), (held.aux as access).value_type(), false);
} else {
state.escaped[c] = true;
}
}
# A cell's address is never null, which inlining may check.
op::clear => {}
op::check => {
if held.aux != fault::null_reference as u32 {
state.escaped[c] = true;
}
}
op::copy => {
# A copy in or out of the cell from its start, between it and memory
# no cell promoted is, reads or writes each of the words it moves.
if held.imm > this.cells[c].size as u64 {
state.escaped[c] = true;
} else {
if i == 0 && state.addresses.cell(this.arg(at, 1)) != 0 {
state.pairs.append(at);
}
if held.imm > state.extent[c] {
state.extent[c] = held.imm;
}
}
}
else => state.escaped[c] = true;
}
}
}
# A copy between cells moves the words either reads or writes alone, so each
# holds the other's, from one to the next along a chain of copies.
var rounds := 0;
var changed := state.pairs.length != 0;
while changed && rounds < 8 {
rounds++;
changed = false;
for p in 0..state.pairs.length {
val copy: u32 = state.pairs[p];
val to := state.addresses.cell(this.arg(copy, 0)) - 1;
val from := state.addresses.cell(this.arg(copy, 1)) - 1;
val size: u64 = this.insts[copy].imm;
changed = state.share_slots(from, to, size) || changed;
changed = state.share_slots(to, from, size) || changed;
}
}
# Each cell's words must not overlap, and the bytes its copies move that no
# word holds are words of their own.
for c in 0..this.cells.length {
continue if state.escaped[c];
var i: u32 = state.heads[c];
while i != 0 {
val each: slot = state.slots[i - 1];
var j: u32 = each.next;
while j != 0 {
val other: slot = state.slots[j - 1];
if other.offset < each.offset + each.size && each.offset < other.offset + other.size {
state.escaped[c] = true;
}
j = other.next;
}
i = each.next;
}
if !state.escaped[c] && state.extent[c] != 0 {
state.fill_gaps(c as u32);
}
}
# Nor may a clear or a copy end within a word.
for t in 0..state.touch.length {
val at: u32 = state.touch[t];
val held: inst = this.insts[at];
continue if held.kind != op::clear && held.kind != op::copy;
for k in 0..held.argc {
val cell := state.addresses.cell(this.arg(at, k as u32));
continue if cell == 0 || state.escaped[cell - 1];
val c := cell - 1;
var i: u32 = state.heads[c];
while i != 0 {
val each: slot = state.slots[i - 1];
if each.offset < held.imm && held.imm < each.offset + each.size {
state.escaped[c] = true;
}
i = each.next;
}
}
}
this.find_uses(state);
}
#! Gives a cell the words another holds within the bytes a copy between them
#! moves, which it does not hold yet. An escaped cell's words say nothing of
#! the values another holds, as an array indexed holds what is read of it one
#! lane at a time, so it gives none, and a vector copied into it stays one.
#! @param this What promoting knows.
#! @param from The cell whose words are given.
#! @param to The cell given them.
#! @param size How many bytes the copy moves.
#! @returns Whether any was new.
def promotion::share_slots(&mut this, from: u32, to: u32, size: u64): bool {
return false if from == to || this.escaped[to] || this.escaped[from];
var added := false;
var i: u32 = this.heads[from];
while i != 0 {
val each: slot = this.slots[i - 1];
i = each.next;
continue if each.offset >= size || this.slot_at(to, each.offset) != no_slot;
this.add_slot(to, each.offset, each.size, each.kind, each.signed);
added = true;
}
return added;
}
#! Gives the bytes a cell's copies move that no word holds words of their own,
#! each as wide as where it begins and the bytes left allow.
#! @param this What promoting knows.
#! @param cell The cell, whose words do not overlap.
def promotion::fill_gaps(&mut this, cell: u32): void {
# The words it holds, by where each begins.
var held := vector::<u64>::new(scratch());
var i: u32 = this.heads[cell];
while i != 0 {
val each: slot = this.slots[i - 1];
held.append(pair_key(each.offset as u32, each.size as u32));
i = each.next;
}
held.sort();
val extent: u64 = this.extent[cell];
var at: u64 = 0;
for &key in held {
break if at >= extent;
val offset := pair_high(key) as u64;
this.fill(cell, at, offset < extent ? offset : extent);
val end := offset + pair_low(key) as u64;
if end > at {
at = end;
}
}
this.fill(cell, at, extent);
}
#! Gives bytes of a cell no word holds words of their own: in an executable's
#! code, each 16 bytes from a multiple of 16 a vector, which a copy moves with
#! one read and write, or 32 from a multiple of 32 in code for processors with
#! AVX, and the rest words.
#! @param this What promoting knows.
#! @param cell The cell.
#! @param from Where the bytes begin.
#! @param to Where they end.
def promotion::fill(&mut this, cell: u32, from: u64, to: u64): void {
var at := from;
while this.wide && at % 32 == 0 && at + 32 <= to {
this.add_slot(cell, at, 32, vt::v256, false);
at += 32;
}
while this.vectors && at % 16 == 0 && at + 16 <= to {
this.add_slot(cell, at, 16, vt::v128, false);
at += 16;
}
while at < to {
var width: u64 = 8;
while width > 1 && (at % width != 0 || at + width > to) {
width = width / 2;
}
this.add_slot(cell, at, width, vt::word, false);
at += width;
}
}
#! Splits each copy from a cell its words cover whole, and not escaped, into
#! another into a read of each word and a write of it where it goes.
#! @param this The code.
#! @param state What promoting knows.
#! @returns Whether any copy was split.
def code::split_pairs(&mut this, state: &mut promotion): bool {
var done := rewrite::new();
var added := vector::<u32>::new(scratch());
for p in 0..state.pairs.length {
val copy: u32 = state.pairs[p];
val held: inst = this.insts[copy];
val source := state.addresses.cell(this.arg(copy, 1)) - 1;
continue if state.escaped[source];
var covered: u64 = 0;
var i: u32 = state.heads[source];
while i != 0 {
if state.slots[i - 1].offset < held.imm {
covered += state.slots[i - 1].size;
}
i = state.slots[i - 1].next;
}
continue if covered != held.imm;
# Only the words the cell it goes to reads go, where it holds them, each
# after the copy, which goes.
val target := state.addresses.cell(this.arg(copy, 0)) - 1;
var after := copy;
i = state.heads[source];
while i != 0 {
val each: slot = state.slots[i - 1];
i = each.next;
continue if each.offset >= held.imm;
val there := state.slot_at(target, each.offset);
continue if !state.escaped[target] && there != no_slot && !state.slots[there].used;
var from: u32[1] = [this.arg(copy, 1)];
var gives: vt[1] = [each.kind];
val how := slot_access(&each) as u32;
val load := this.detached(op::load, from[0:1], gives[0:1], how, each.offset, held.at, held.site);
this.link_after(load, after);
var to: u32[2] = [this.arg(copy, 0), this.insts[load].result];
val store := this.detached(op::store, to[0:2], span::<vt>::empty(), how, each.offset, held.at, held.site);
this.link_after(store, load);
after = store;
added.append(load);
added.append(store);
}
done.remove(copy);
}
return false if !done.changed;
this.apply(&done);
# The instructions naming cells are those that did but the copies split, and
# the reads and writes they became.
var kept: u64 = 0;
for t in 0..state.touch.length {
val at: u32 = state.touch[t];
if !done.is_removed(at) {
state.touch[kept] = at;
kept++;
}
}
state.touch.resize(kept);
state.touch.extend(added.view());
return true;
}
#! Adds a word to those a cell holds, where it is new, marking the cell
#! escaped where the same offset is read or written as another width or kind,
#! or where it is 32 bytes of lanes and the code may run without AVX, or 64.
#! @param this What promoting knows.
#! @param cell The cell.
#! @param offset Where the word begins.
#! @param size How many bytes it is.
#! @param kind The type of value it holds.
#! @param signed Whether it is read as a signed integer narrower than a word.
def promotion::add_slot(&mut this, cell: u32, offset: u64, size: u64, kind: vt, signed: bool): void {
# 64 bytes of lanes stay in memory, as only code knowing the processor has
# AVX-512 holds them.
if kind == vt::v512 || (kind == vt::v256 && !this.wide) {
this.escaped[cell] = true;
return;
}
var i: u32 = this.heads[cell];
while i != 0 {
val each: slot = this.slots[i - 1];
if each.offset == offset {
if each.size != size || each.kind != kind {
this.escaped[cell] = true;
}
if signed {
this.slots[i - 1].signed = true;
}
return;
}
i = each.next;
}
this.slots.append(slot { cell = cell, offset = offset, size = size, kind = kind, signed = signed, next = this.heads[cell] });
this.heads[cell] = this.slots.length as u32;
}
#! The slot of a cell at an offset, or `no_slot`.
#! @param this What promoting knows.
#! @param cell The cell.
#! @param offset Where the word begins.
#! @returns The slot's index.
def promotion::slot_at(&this, cell: u32, offset: u64): u32 {
var i: u32 = this.heads[cell];
while i != 0 {
return i - 1 if this.slots[i - 1].offset == offset;
i = this.slots[i - 1].next;
}
return no_slot;
}
#! Whether a slot of a cell that bytes of it lie within is used. The cell copied
#! into may hold a word over several of the other's, as a vector over a struct's
#! fields where one cell holds each in turn, so each of those is used where the
#! word over it is.
#! @param this What promoting knows.
#! @param cell The cell.
#! @param offset Where the bytes begin.
#! @param size How many there are.
#! @returns Whether one is.
def promotion::used_over(&this, cell: u32, offset: u64, size: u64): bool {
var i: u32 = this.heads[cell];
while i != 0 {
val each: slot = this.slots[i - 1];
return true if each.used && each.offset < offset + size && offset < each.offset + each.size;
i = each.next;
}
return false;
}
#! Notes the value each slot holds at the end of a block that writes it: what
#! it last stores or copies in, or zero where it last clears it.
#! @param this The code.
#! @param block The block.
#! @param state What promoting knows.
def code::note_ends(&mut this, block: u32, state: &mut promotion): void {
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
continue if held.argc == 0;
val target := state.addresses.cell(this.arg(at, 0));
continue if target == 0 || state.escaped[target - 1];
val c := target - 1;
match held.kind {
op::store => {
state.set_end(state.slot_at(c, held.imm), block, this.arg(at, 1));
}
op::clear => {
var i: u32 = state.heads[c];
while i != 0 {
val s := i - 1;
val each: slot = state.slots[s];
i = each.next;
continue if each.offset >= held.imm;
state.set_end(s, block, state.zeros.of(this, each.kind));
}
}
# A copy in reads each word something reads from where it comes from,
# read here, before any block asks what a slot holds. Where nothing reads
# any, its first is still read, so an address that cannot be read stops
# the program there as the copy did.
op::copy => {
var reads := !this.checked_address(at, this.arg(at, 1));
var i: u32 = state.heads[c];
while i != 0 {
val each: slot = state.slots[i - 1];
if each.offset < held.imm && each.used {
reads = false;
}
i = each.next;
}
var after := at;
i = state.heads[c];
while i != 0 {
val s := i - 1;
val each: slot = state.slots[s];
i = each.next;
continue if each.offset >= held.imm || (!each.used && !(reads && each.offset == 0));
var args: u32[1] = [this.arg(at, 1)];
var gives: vt[1] = [each.kind];
val load := this.detached(op::load, args[0:1], gives[0:1], slot_access(&each) as u32, each.offset, held.at, held.site);
this.link_after(load, after);
after = load;
val value: u32 = this.insts[load].result;
state.copies.set(pair_key(at, s), value);
state.set_end(s, block, value);
}
}
else => {}
}
}
}
#! The value a slot holds at the start of a block: zero at the entry, what it
#! holds at the end of the one block going there, or else a parameter the
#! block takes, given what it holds at the end of each.
#! @param this The code.
#! @param s The slot.
#! @param block The block.
#! @param state What promoting knows.
#! @returns The value.
def code::slot_start(&mut this, s: u32, block: u32, state: &mut promotion): u32 {
val known := state.start_at(s, block);
return known if known != 0;
val kind := state.slots[s].kind;
val preds := this.blocks[block].preds.length;
if block == 0 || preds == 0 {
val zero := state.zeros.of(this, kind);
state.set_start(s, block, zero);
return zero;
}
if preds == 1 {
val edge: u32 = this.blocks[block].preds[0];
val made := this.slot_end(s, this.edge_source(edge), state);
state.set_start(s, block, made);
return made;
}
# Noted before its arguments are found, which may come back to it.
val param := this.add_param(block, kind);
state.set_start(s, block, param);
var edges := this.blocks[block].preds.copied(scratch());
for &edge in edges {
val given := this.slot_end(s, this.edge_source(edge), state);
this.edges[edge].args.append(given);
}
return param;
}
#! The value a slot holds at the end of a block.
#! @param this The code.
#! @param s The slot.
#! @param block The block.
#! @param state What promoting knows.
#! @returns The value.
def code::slot_end(&mut this, s: u32, block: u32, state: &mut promotion): u32 {
val known := state.end_at(s, block);
return known if known != 0;
return this.slot_start(s, block, state);
}
#! Notes what a slot holds where the walk of a block is.
#! @param this What promoting knows.
#! @param s The slot.
#! @param value The value.
def promotion::hold(&mut this, s: u32, value: u32): void {
this.current[s] = value;
this.written.put(s);
}
#! What a slot holds where the walk of a block is: what the block wrote last,
#! or what it holds where the block begins.
#! @param this The code.
#! @param s The slot.
#! @param block The block.
#! @param state What promoting knows.
#! @returns The value.
def code::slot_now(&mut this, s: u32, block: u32, state: &mut promotion): u32 {
return state.current[s] if state.written.contains(s);
return this.slot_start(s, block, state);
}
#! Rewrites the reads and writes of the slots of a block: a read reads what
#! the slot holds there, narrowed as the read narrows, and a write, a clear,
#! and a copy in or out go, a copy becoming reads or writes of its words.
#! @param this The code.
#! @param block The block.
#! @param state What promoting knows.
#! @param done What the pass changes.
def code::rewrite_slots(&mut this, block: u32, state: &mut promotion, done: &mut rewrite): void {
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
if held.kind == op::cell {
if !state.escaped[held.aux] {
done.remove(at);
}
continue;
}
continue if held.argc == 0;
val first := state.addresses.cell(this.arg(at, 0));
val c := first != 0 && !state.escaped[first - 1] ? first - 1 : no_cell;
match held.kind {
op::check => {
if c != no_cell {
done.remove(at);
}
}
op::load => {
if c != no_cell {
val s := state.slot_at(c, held.imm);
val value := this.slot_now(s, block, state);
this.read_slot(at, value, done);
}
}
op::store => {
if c != no_cell {
state.hold(state.slot_at(c, held.imm), this.arg(at, 1));
done.remove(at);
}
}
op::clear => {
if c != no_cell {
var i: u32 = state.heads[c];
while i != 0 {
val each: slot = state.slots[i - 1];
if each.offset < held.imm {
state.hold(i - 1, state.zeros.of(this, each.kind));
}
i = each.next;
}
done.remove(at);
}
}
op::copy => {
val from := state.addresses.cell(this.arg(at, 1));
if c != no_cell {
# Copied in: each word is what was read of where it comes from.
var i: u32 = state.heads[c];
while i != 0 {
val key := pair_key(at, i - 1);
if state.copies.get(&key) is some(got) {
state.hold(i - 1, got);
}
i = state.slots[i - 1].next;
}
done.remove(at);
} else if from != 0 && !state.escaped[from - 1] {
# Copied out: each word is written where it goes, after the copy,
# which goes.
val source := from - 1;
var after := at;
var i: u32 = state.heads[source];
while i != 0 {
val s := i - 1;
val each: slot = state.slots[s];
i = each.next;
continue if each.offset >= held.imm;
val value := this.slot_now(s, block, state);
var args: u32[2] = [this.arg(at, 0), value];
val store := this.detached(op::store, args[0:2], span::<vt>::empty(), slot_access(&each) as u32, each.offset, held.at, held.site);
this.link_after(store, after);
after = store;
}
done.remove(at);
}
}
else => {}
}
}
}
#! How a slot is read and written in memory where a copy moves it: a narrow
#! integer as it is read, so a field of `i32` copied is narrowed as a read of it
#! narrows it again, and the two are one.
#! @param each The slot.
#! @returns The access.
def slot_access(each: &slot): access {
return access::v128 if each.kind == vt::v128;
return access::v256 if each.kind == vt::v256;
return each.kind == vt::real ? (each.size == 4 ? access::f32 : access::f64) : match each.size {
1 => each.signed ? access::i8 : access::u8,
2 => each.signed ? access::i16 : access::u16,
4 => each.signed ? access::i32 : access::u32,
else => access::i64
};
}
#! Whether an access reads a signed integer narrower than a word.
#! @param how The access.
#! @returns Whether it does.
def narrow_signed(how: access): bool {
return how == access::i8 || how == access::i16 || how == access::i32;
}
#! Makes a read of a slot the value it holds, narrowed as the read narrows.
#! @param this The code.
#! @param index The `load`.
#! @param value What the slot holds.
#! @param done What the pass changes.
def code::read_slot(&mut this, index: u32, value: u32, done: &mut rewrite): void {
val how: access = this.insts[index].aux as access;
var args: u32[1] = [value];
match how {
access::i64, access::f64, access::v128, access::v256 => {
done.replace(this.insts[index].result, value);
done.remove(index);
}
access::f32 => this.become(index, op::fsingle, args[0:1], 0, 0);
access::u8 => this.become(index, op::wrap, args[0:1], 8, 0);
access::i8 => this.become(index, op::wrap, args[0:1], 8, 1);
access::u16 => this.become(index, op::wrap, args[0:1], 16, 0);
access::i16 => this.become(index, op::wrap, args[0:1], 16, 1);
access::u32 => this.become(index, op::wrap, args[0:1], 32, 0);
access::i32 => this.become(index, op::wrap, args[0:1], 32, 1);
else => {}
}
done.changed = true;
}
+925
View File
@@ -0,0 +1,925 @@
#! @file simplify.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the first pass of the optimizer, simplification: an operator of
#! constants becomes the constant it gives, worked out exactly as the machine
#! works it out; an operator whose result its operands already say becomes
#! that, as `x + 0` is `x` and `x == x` is 1; a multiplication, division, or
#! remainder of an unsigned word by a power of two becomes a shift or a mask;
#! a comparison with the least or greatest word says what it says of every
#! word, or asks only whether a word is one; a constant added to a word with a
#! constant added becomes one sum; a read of a datum, which is never written,
#! becomes what its bytes hold; a condition another says the opposite of is
#! read through it; a `select` whose choice is known is what it chooses; and a
#! check of what is known to hold goes.
module sakura::compiler;
#! Simplifies the code, as the file says, in one walk of its blocks.
#! @param this The code.
#! @param data The program's datums, which reads of them are read from.
#! @returns Whether anything changed.
pub def code::simplify(&mut this, data: span<datum>): bool {
var done := rewrite::new();
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.block_order(&mut order, &mut number);
for &block in order {
var walk := this.walk(block);
while walk.more() {
this.simplify_inst(walk.next(), data, &mut done);
}
}
this.apply(&done);
return done.changed;
}
#! Simplifies one instruction.
#! @param this The code.
#! @param index The instruction.
#! @param data The program's datums.
#! @param done What the pass changes.
def code::simplify_inst(&mut this, index: u32, data: span<datum>, done: &mut rewrite): void {
val held: inst = this.insts[index];
val kind := held.kind;
val number := kind as u32;
# Operands read what replaced them, so what is worked out of one value is
# worked out of what it was replaced by.
for i in 0..held.argc {
val at := held.args as u64 + i as u64;
this.operands[at] = done.resolve(this.operands[at]);
}
if number >= op::add as u32 && number <= op::leus as u32 {
this.simplify_word(index, done);
return;
}
if number >= op::fadd as u32 && number <= op::fle as u32 {
var x: u64 = 0;
var y: u64 = 0;
if this.real_constant(this.arg(index, 0), &mut x) && this.real_constant(this.arg(index, 1), &mut y) {
var made: u64 = 0;
if fold_real(kind, x, y, &mut made) {
if number >= op::feq as u32 {
this.become_word(index, made);
} else {
this.become_real(index, made);
}
done.changed = true;
}
}
return;
}
if number >= op::neg as u32 && number <= op::bswap as u32 {
this.simplify_unary(index, done);
return;
}
match kind {
op::wrap => this.simplify_wrap(index, done);
op::check => {
var bits: u64 = 0;
val cond := this.arg(index, 0);
if this.word_constant(cond, &mut bits) && bits != 0 {
done.remove(index);
return;
}
# The address of a cell, the globals, or a datum is never null.
val made := this.defining(cond);
if made != 0 && (this.insts[made].kind == op::cell || this.insts[made].kind == op::global || this.insts[made].kind == op::datum) {
done.remove(index);
return;
}
# A check of whether a word is not zero checks the word.
val inner := this.defining(cond);
if inner != 0 && this.insts[inner].kind == op::ne && this.is_zero(this.arg(inner, 1)) {
this.operands[held.args] = this.arg(inner, 0);
done.changed = true;
}
}
op::branch => this.simplify_branch(index, done);
op::select => this.simplify_select(index, done);
op::load => {
this.fold_offset(index, done);
this.read_datum(index, data, done);
}
op::store => {
this.fold_offset(index, done);
this.simplify_store(index, done);
}
else => {}
}
}
#! The offsets a read or write may be given by folding: a page, less the widest
#! access.
const folded_reach: u64 = 4096 - 32;
#! Folds a constant added to the address a read or write is given into its
#! offset, so it is addressed as `[base + offset]` and a cell read at a field is
#! read at that offset of the cell. Only offsets within the page no program
#! maps, which reaching through null faults in on its own; one past it would
#! need an executable to test the base first.
#! @param this The code.
#! @param index The `load` or `store`.
#! @param done What the pass changes.
def code::fold_offset(&mut this, index: u32, done: &mut rewrite): void {
val inner := this.defining(this.arg(index, 0));
return if inner == 0 || this.insts[inner].kind != op::add;
var bits: u64 = 0;
var base: u32 = 0;
if this.word_constant(this.arg(inner, 1), &mut bits) {
base = this.arg(inner, 0);
} else if this.word_constant(this.arg(inner, 0), &mut bits) {
base = this.arg(inner, 1);
} else {
return;
}
val offset := this.insts[index].imm + bits;
return if bits >= folded_reach || offset >= folded_reach;
this.operands[this.insts[index].args as u64] = base;
this.insts[index].imm = offset;
done.changed = true;
}
#! Reads while compiling what a read of a datum reads, since a datum is never
#! written: the word or real its bytes hold, or, for a whole word where a
#! relocation is, the address it holds. A read of an `f32`, of lanes, or across
#! part of an address stays.
#! @param this The code.
#! @param index The `load`.
#! @param data The program's datums.
#! @param done What the pass changes.
def code::read_datum(&mut this, index: u32, data: span<datum>, done: &mut rewrite): void {
val from := this.defining(this.arg(index, 0));
return if from == 0 || this.insts[from].kind != op::datum;
val target: u64 = this.insts[from].aux;
return if target >= data.length;
val held := &data[target];
val how := this.insts[index].aux as access;
return if how == access::f32 || how == access::bytes || how.value_type().lanes();
val width := how.width();
val start := this.insts[from].imm + this.insts[index].imm;
return if start >= held.bytes.length || width > held.bytes.length - start;
for &each in held.relocations {
continue if each.at + word_size <= start || each.at >= start + width;
return if each.at != start || how != access::i64;
this.become(index, op::datum, span::<u32>::empty(), each.target, each.addend);
done.changed = true;
return;
}
var bits: u64 = 0;
for i in 0..width {
bits = bits | ((held.bytes[start + i as u64] as u64) << (8 * i as u64));
}
match how {
access::i8 => bits = wrap_word(bits, 8, true);
access::i16 => bits = wrap_word(bits, 16, true);
access::i32 => bits = wrap_word(bits, 32, true);
access::f64 => {
this.become_real(index, bits);
done.changed = true;
return;
}
else => {}
}
this.become_word(index, bits);
done.changed = true;
}
#! Simplifies a write of a narrow value: one narrowed to at least as many bits
#! as the write keeps, or an `f32` rounded already, is written as it was.
#! @param this The code.
#! @param index The `store`.
#! @param done What the pass changes.
def code::simplify_store(&mut this, index: u32, done: &mut rewrite): void {
val value := this.arg(index, 1);
val inner := this.defining(value);
return if inner == 0;
val how := this.insts[index].aux as access;
val kind := this.insts[inner].kind;
if kind == op::fsingle && how == access::f32 {
this.operands[this.insts[index].args as u64 + 1] = this.arg(inner, 0);
done.changed = true;
return;
}
return if kind != op::wrap || how == access::f32 || how == access::f64 || how == access::bytes;
if this.insts[inner].aux as u64 >= 8 * how.width() {
this.operands[this.insts[index].args as u64 + 1] = this.arg(inner, 0);
done.changed = true;
}
}
#! Whether a value is known to have every bit of a word set: the processor's
#! instruction sets, where a version knows which it has.
#! @param this The code.
#! @param value The value.
#! @param bits The bits.
#! @returns Whether it is.
def code::holds_bits(&this, value: u32, bits: u64): bool {
val made := this.defining(value);
return made != 0 && this.insts[made].kind == op::cpu && (bits & ~this.insts[made].imm) == 0;
}
#! Simplifies an operator of two words.
#! @param this The code.
#! @param index The instruction.
#! @param done What the pass changes.
def code::simplify_word(&mut this, index: u32, done: &mut rewrite): void {
val kind := this.insts[index].kind;
var a := this.arg(index, 0);
var b := this.arg(index, 1);
var x: u64 = 0;
var y: u64 = 0;
val known_a := this.word_constant(a, &mut x);
val known_b := this.word_constant(b, &mut y);
if known_a && known_b {
var made: u64 = 0;
if fold_word(kind, x, y, &mut made) {
this.become_word(index, made);
done.changed = true;
}
return;
}
# A constant goes on the right of what does not mind which side it is on.
var right := known_b;
if known_a && !known_b && commutes(kind) {
var swapped: u32[2] = [b, a];
this.become(index, kind, swapped[0:2], 0, 0);
a = swapped[0];
b = swapped[1];
y = x;
right = true;
done.changed = true;
}
# What the operands say whatever they are.
if a == b {
match kind {
op::sub, op::bxor, op::ne, op::ltu, op::lts => {
this.become_word(index, 0);
done.changed = true;
return;
}
op::eq, op::leu, op::les => {
this.become_word(index, 1);
done.changed = true;
return;
}
op::band, op::bor => {
this.forward_to(index, a, done);
return;
}
else => {}
}
}
# A never-zero address compared with zero.
if (kind == op::eq || kind == op::ne) && this.is_zero(b) && this.never_zero(a) {
this.become_word(index, kind == op::ne ? 1 : 0);
done.changed = true;
return;
}
if known_a && !right {
this.simplify_left_order(index, b, x, done);
return;
}
return if !right;
match kind {
op::add, op::sub => {
if y == 0 {
this.forward_to(index, a, done);
} else {
this.combine_steps(index, a, kind == op::add ? y : 0 - y, done);
}
}
op::bor, op::bxor, op::shl, op::shru, op::shrs => {
if y == 0 {
this.forward_to(index, a, done);
}
}
op::mul => {
if y == 0 {
this.become_word(index, 0);
done.changed = true;
} else if y == 1 {
this.forward_to(index, a, done);
} else if is_power(y) {
this.become_shift(index, op::shl, a, log2(y));
done.changed = true;
}
}
op::divs, op::divu => {
if y == 1 {
this.forward_to(index, a, done);
} else if kind == op::divu && is_power(y) {
this.become_shift(index, op::shru, a, log2(y));
done.changed = true;
}
}
op::rems, op::remu => {
if y == 1 {
this.become_word(index, 0);
done.changed = true;
} else if kind == op::remu && is_power(y) {
var operands: u32[2] = [a, this.word_value(y - 1)];
this.become(index, op::band, operands[0:2], 0, 0);
done.changed = true;
}
}
op::band => {
if y == 0 {
this.become_word(index, 0);
done.changed = true;
} else if y == 0xFFFFFFFFFFFFFFFFu {
this.forward_to(index, a, done);
} else if this.holds_bits(a, y) {
this.become_word(index, y);
done.changed = true;
}
}
op::ltu => {
if y == 0 {
this.become_word(index, 0);
done.changed = true;
} else if y == 1 {
this.become_compare(index, op::eq, a, 0);
done.changed = true;
}
}
op::leu => {
if y == greatest_unsigned {
this.become_word(index, 1);
done.changed = true;
} else if y == 0 {
this.become_compare(index, op::eq, a, 0);
done.changed = true;
}
}
op::lts => {
if y == least_signed {
this.become_word(index, 0);
done.changed = true;
} else if y == least_signed + 1 {
this.become_compare(index, op::eq, a, least_signed);
done.changed = true;
}
}
op::les => {
if y == greatest_signed {
this.become_word(index, 1);
done.changed = true;
} else if y == least_signed {
this.become_compare(index, op::eq, a, least_signed);
done.changed = true;
}
}
else => {}
}
}
#! The greatest unsigned word.
const greatest_unsigned: u64 = 0xFFFFFFFFFFFFFFFFu;
#! The least signed word, as its bits.
const least_signed: u64 = 0x8000000000000000u;
#! The greatest signed word, as its bits.
const greatest_signed: u64 = 0x7FFFFFFFFFFFFFFFu;
#! Simplifies an order whose left operand is a constant, which stays on the
#! left: one no word comes after, or every word does, says what it says of
#! every word, as `MAX < x` is 0, and one only a single word comes after asks
#! whether the word is that one, as `0 < x` asks whether `x` is not zero.
#! @param this The code.
#! @param index The comparison.
#! @param b Its right operand.
#! @param x The constant on its left.
#! @param done What the pass changes.
def code::simplify_left_order(&mut this, index: u32, b: u32, x: u64, done: &mut rewrite): void {
match this.insts[index].kind {
op::ltu => {
if x == greatest_unsigned {
this.become_word(index, 0);
} else if x == 0 {
this.become_compare(index, op::ne, b, 0);
} else {
return;
}
}
op::leu => {
if x == 0 {
this.become_word(index, 1);
} else if x == greatest_unsigned {
this.become_compare(index, op::eq, b, greatest_unsigned);
} else {
return;
}
}
op::lts => {
if x == greatest_signed {
this.become_word(index, 0);
} else if x == least_signed {
this.become_compare(index, op::ne, b, least_signed);
} else {
return;
}
}
op::les => {
if x == least_signed {
this.become_word(index, 1);
} else if x == greatest_signed {
this.become_compare(index, op::eq, b, greatest_signed);
} else {
return;
}
}
else => return;
}
done.changed = true;
}
#! Makes an instruction a comparison of a word with a constant.
#! @param this The code.
#! @param index The instruction.
#! @param kind The comparison.
#! @param a The word.
#! @param bits The constant.
def code::become_compare(&mut this, index: u32, kind: op, a: u32, bits: u64): void {
var operands: u32[2] = [a, this.word_value(bits)];
this.become(index, kind, operands[0:2], 0, 0);
}
#! Adds a constant to a word that is itself a word with a constant added or
#! taken away, as one sum of both, so `(x + 4) + 8` is `x + 12`, and the inner
#! one goes where nothing else reads it.
#! @param this The code.
#! @param index The `add` or `sub`.
#! @param a The word it adds to.
#! @param step What it adds, as a wrapping word: what a `sub` takes away, negated.
#! @param done What the pass changes.
def code::combine_steps(&mut this, index: u32, a: u32, step: u64, done: &mut rewrite): void {
val inner := this.defining(a);
return if inner == 0;
val kind := this.insts[inner].kind;
return if kind != op::add && kind != op::sub;
var bits: u64 = 0;
return if !this.word_constant(this.arg(inner, 1), &mut bits);
val total := step + (kind == op::add ? bits : 0 - bits);
val base := this.arg(inner, 0);
if total == 0 {
this.forward_to(index, base, done);
return;
}
var operands: u32[2] = [base, this.word_value(total)];
this.become(index, op::add, operands[0:2], 0, 0);
done.changed = true;
}
#! Makes an instruction a shift of a word by a constant.
#! @param this The code.
#! @param index The instruction.
#! @param kind The shift.
#! @param a The word.
#! @param by How far it shifts.
def code::become_shift(&mut this, index: u32, kind: op, a: u32, by: u64): void {
var operands: u32[2] = [a, this.word_value(by)];
this.become(index, kind, operands[0:2], 0, 0);
}
#! Replaces what an instruction gives with a value, taking the instruction out.
#! @param this The code.
#! @param index The instruction.
#! @param value The value its result is.
#! @param done What the pass changes.
def code::forward_to(&mut this, index: u32, value: u32, done: &mut rewrite): void {
done.replace(this.insts[index].result, value);
done.remove(index);
}
#! Whether a value is the word zero.
#! @param this The code.
#! @param value The value.
#! @returns Whether it is.
def code::is_zero(&this, value: u32): bool {
var bits: u64 = 0;
return this.word_constant(value, &mut bits) && bits == 0;
}
#! Simplifies an operator of one value.
#! @param this The code.
#! @param index The instruction.
#! @param done What the pass changes.
def code::simplify_unary(&mut this, index: u32, done: &mut rewrite): void {
val kind := this.insts[index].kind;
val a := this.arg(index, 0);
var bits: u64 = 0;
val word := this.word_constant(a, &mut bits);
val real := !word && this.real_constant(a, &mut bits);
if word || real {
var made: u64 = 0;
val gives_real := kind == op::fneg || kind == op::itof || kind == op::utof || kind == op::fsingle || kind == op::fsqrt;
if fold_unary(kind, bits, &mut made) {
if gives_real {
this.become_real(index, made);
} else {
this.become_word(index, made);
}
done.changed = true;
}
return;
}
val inner := this.defining(a);
return if inner == 0;
val from: inst = this.insts[inner];
match kind {
# The opposite of a comparison is the comparison that says it.
op::lnot => {
var flipped := op::count;
var swap := false;
match from.kind {
op::eq => flipped = op::ne;
op::ne => flipped = op::eq;
op::ltu => { flipped = op::leu; swap = true; }
op::leu => { flipped = op::ltu; swap = true; }
op::lts => { flipped = op::les; swap = true; }
op::les => { flipped = op::lts; swap = true; }
op::ltsu => { flipped = op::leus; swap = true; }
op::lesu => { flipped = op::ltus; swap = true; }
op::ltus => { flipped = op::lesu; swap = true; }
op::leus => { flipped = op::ltsu; swap = true; }
op::lnot => {
if this.is_flag(this.arg(inner, 0)) {
this.forward_to(index, this.arg(inner, 0), done);
}
return;
}
else => return;
}
val x := this.arg(inner, 0);
val y := this.arg(inner, 1);
var operands: u32[2] = swap ? [y, x] : [x, y];
this.become(index, flipped, operands[0:2], 0, 0);
done.changed = true;
}
op::fsingle => {
if from.kind == op::fsingle || (from.kind == op::load && from.aux == access::f32 as u32) {
this.forward_to(index, a, done);
}
}
op::neg, op::bnot => {
if from.kind == kind {
this.forward_to(index, this.arg(inner, 0), done);
}
}
else => {}
}
}
#! Whether a word is 0 or 1, as a comparison gives.
#! @param this The code.
#! @param value The word.
#! @returns Whether it is.
def code::is_flag(&this, value: u32): bool {
var bits: u64 = 0;
return bits <= 1 if this.word_constant(value, &mut bits);
val index := this.defining(value);
return false if index == 0;
val number := this.insts[index].kind as u32;
return (number >= op::eq as u32 && number <= op::leus as u32)
|| (number >= op::feq as u32 && number <= op::fle as u32)
|| number == op::lnot as u32;
}
#! Simplifies the narrowing of a word, which goes where the word is already as
#! narrow, and narrows what was narrowed less where it narrows more, or the
#! same, the other way: `wrap(wrap(x, 32, unsigned), 32, signed)` is
#! `wrap(x, 32, signed)`.
#! @param this The code.
#! @param index The instruction.
#! @param done What the pass changes.
def code::simplify_wrap(&mut this, index: u32, done: &mut rewrite): void {
val held: inst = this.insts[index];
val a := this.arg(index, 0);
val bits := held.aux;
val signed := held.imm != 0;
if bits >= 64 {
this.forward_to(index, a, done);
return;
}
var value: u64 = 0;
if this.word_constant(a, &mut value) {
this.become_word(index, wrap_word(value, bits, signed));
done.changed = true;
return;
}
# The bits a word is held in already, and whether they are signed.
var held_bits: u32 = 64;
var held_signed := false;
val inner := this.defining(a);
if inner != 0 {
val from: inst = this.insts[inner];
match from.kind {
op::wrap => {
held_bits = from.aux;
held_signed = from.imm != 0;
# Narrowing more than what was narrowed, or as much the other way, narrows
# the word itself.
if bits < held_bits || (bits == held_bits && signed != held_signed) {
var operands: u32[1] = [this.arg(inner, 0)];
this.become(index, op::wrap, operands[0:1], bits, held.imm);
done.changed = true;
return;
}
}
op::load, op::atomic => {
match from.kind == op::load ? from.aux as access : atomic_access(from.imm) {
access::u8 => held_bits = 8;
access::i8 => { held_bits = 8; held_signed = true; }
access::u16 => held_bits = 16;
access::i16 => { held_bits = 16; held_signed = true; }
access::u32 => held_bits = 32;
access::i32 => { held_bits = 32; held_signed = true; }
else => {}
}
}
else => {
if this.is_flag(a) {
held_bits = 1;
}
}
}
}
if (signed == held_signed && bits >= held_bits) || (!held_signed && bits > held_bits) || this.param_narrow(a, bits, signed) {
this.forward_to(index, a, done);
}
}
#! Whether a block's parameter is a word as narrow as a narrowing makes it
#! already: every edge into the block gives it one so narrowed, or the
#! parameter itself, as a loop keeps a field of `i32` it adds to.
#! @param this The code.
#! @param value The parameter.
#! @param bits The bits it would be narrowed to.
#! @param signed Whether it would be extended by its sign.
#! @returns Whether it is.
def code::param_narrow(&this, value: u32, bits: u32, signed: bool): bool {
return false if value == 0 || (value as u64) >= this.origins.length;
val held: origin = this.origins[value];
return false if !held.param;
val preds := &this.blocks[held.from].preds;
return false if preds.length == 0;
for &e in preds.view() {
val given: u32 = this.edges[e as u64].args[held.index as u64];
continue if given == value;
val made := this.defining(given);
return false if made == 0;
val from: inst = this.insts[made];
var fits := false;
if from.kind == op::wrap {
fits = (from.imm != 0) == signed ? from.aux <= bits : from.imm == 0 && from.aux < bits;
} else if from.kind == op::iconst {
fits = wrap_word(from.imm, bits, signed) == from.imm;
}
return false if !fits;
}
return true;
}
#! Simplifies a `branch`: one on a condition's opposite goes the other way on
#! the condition, and one on whether a word is not zero branches on the word.
#! @param this The code.
#! @param index The `branch`.
#! @param done What the pass changes.
def code::simplify_branch(&mut this, index: u32, done: &mut rewrite): void {
var steps := 0;
while steps < 8 {
steps++;
val cond := this.arg(index, 0);
val inner := this.defining(cond);
return if inner == 0;
val from: inst = this.insts[inner];
if from.kind == op::lnot {
this.operands[this.insts[index].args] = this.arg(inner, 0);
this.swap_branch(index);
done.changed = true;
continue;
}
return if (from.kind != op::ne && from.kind != op::eq) || !this.is_zero(this.arg(inner, 1));
this.operands[this.insts[index].args] = this.arg(inner, 0);
if from.kind == op::eq {
this.swap_branch(index);
}
done.changed = true;
}
}
#! Simplifies a `select`: one on a constant, or between one value either way,
#! is the value it chooses; one on a condition's opposite, or on whether a word
#! is not zero, chooses on the condition or the word the other way round or the
#! same; one choosing 1 or 0 by a word is whether the word is not zero, which
#! is the word where it is 0 or 1, or is zero; and one choosing the condition
#! itself or 0 is the condition.
#! @param this The code.
#! @param index The `select`.
#! @param done What the pass changes.
def code::simplify_select(&mut this, index: u32, done: &mut rewrite): void {
var steps := 0;
while steps < 8 {
steps++;
val cond := this.arg(index, 0);
val a := this.arg(index, 1);
val b := this.arg(index, 2);
var bits: u64 = 0;
if this.word_constant(cond, &mut bits) {
this.forward_to(index, bits != 0 ? a : b, done);
return;
}
if a == b || (a == cond && this.is_zero(b)) {
this.forward_to(index, a, done);
return;
}
var x: u64 = 0;
var y: u64 = 0;
if this.word_constant(a, &mut x) && this.word_constant(b, &mut y) {
if x == 1 && y == 0 && this.is_flag(cond) {
this.forward_to(index, cond, done);
return;
}
if x == 1 && y == 0 {
var operands: u32[2] = [cond, this.word_value(0)];
this.become(index, op::ne, operands[0:2], 0, 0);
done.changed = true;
return;
}
if x == 0 && y == 1 {
var operands: u32[1] = [cond];
this.become(index, op::lnot, operands[0:1], 0, 0);
done.changed = true;
return;
}
}
# A condition worked out from another is read through it.
val inner := this.defining(cond);
return if inner == 0;
val from: inst = this.insts[inner];
val opposite := from.kind == op::lnot || (from.kind == op::eq && this.is_zero(this.arg(inner, 1)));
return if !opposite && (from.kind != op::ne || !this.is_zero(this.arg(inner, 1)));
var operands: u32[3] = opposite ? [this.arg(inner, 0), b, a] : [this.arg(inner, 0), a, b];
this.become(index, op::select, operands[0:3], 0, 0);
done.changed = true;
}
}
#! Whether an operator of two words gives the same whichever side each is on.
#! @param kind The operator.
#! @returns Whether it does.
def commutes(kind: op): bool {
return kind == op::add || kind == op::mul || kind == op::band || kind == op::bor || kind == op::bxor
|| kind == op::eq || kind == op::ne;
}
#! Whether a word is a power of two.
#! @param bits The word.
#! @returns Whether it is.
def is_power(bits: u64): bool {
return bits != 0 && (bits & (bits - 1)) == 0;
}
#! Which power of two a word is.
#! @param bits The word, a power of two.
#! @returns The power.
def log2(bits: u64): u64 {
var at := bits;
var power: u64 = 0;
while at > 1 {
at = at >> 1;
power++;
}
return power;
}
#! A word narrowed to a number of bits, as the machine narrows it.
#! @param value The word.
#! @param bits How many bits it keeps.
#! @param signed Whether it is sign-extended rather than zero-extended.
#! @returns The word narrowed.
pub def wrap_word(value: u64, bits: u32, signed: bool): u64 {
return value if bits >= 64;
val mask := (1u << bits as u64) - 1;
var made := value & mask;
if signed && (made >> (bits as u64 - 1)) != 0 {
made = made | ~mask;
}
return made;
}
#! What an operator of two words gives, as the machine works it out.
#! @param kind The operator.
#! @param a The first word.
#! @param b The second word.
#! @param made Where what it gives is written.
#! @returns Whether it gives anything: not where it divides by zero, which
#! stops the program.
pub def fold_word(kind: op, a: u64, b: u64, made: &mut u64): bool {
match kind {
op::add => made = a + b;
op::sub => made = a - b;
op::mul => made = a * b;
op::divs, op::divu, op::rems, op::remu => {
return false if b == 0;
if kind == op::divu {
made = a / b;
} else if kind == op::remu {
made = a % b;
} else if (b as i64) == -1 {
made = kind == op::divs ? 0 - a : 0;
} else if kind == op::divs {
made = ((a as i64) / (b as i64)) as u64;
} else {
made = ((a as i64) % (b as i64)) as u64;
}
}
op::band => made = a & b;
op::bor => made = a | b;
op::bxor => made = a ^ b;
op::shl => made = a << b;
op::shru => made = a >> b;
op::shrs => made = ((a as i64) >> b) as u64;
op::eq => made = a == b ? 1 : 0;
op::ne => made = a != b ? 1 : 0;
op::lts => made = (a as i64) < (b as i64) ? 1 : 0;
op::ltu => made = a < b ? 1 : 0;
op::les => made = (a as i64) <= (b as i64) ? 1 : 0;
op::leu => made = a <= b ? 1 : 0;
op::eqsu => made = (a as i64) >= 0 && a == b ? 1 : 0;
op::ltsu => made = (a as i64) < 0 || a < b ? 1 : 0;
op::lesu => made = (a as i64) < 0 || a <= b ? 1 : 0;
op::ltus => made = (b as i64) >= 0 && a < b ? 1 : 0;
op::leus => made = (b as i64) >= 0 && a <= b ? 1 : 0;
else => return false;
}
return true;
}
#! What an operator of two reals gives, as the machine works it out: a real's
#! bits, or a word of 0 or 1 for a comparison.
#! @param kind The operator.
#! @param a The bits of the first real.
#! @param b The bits of the second real.
#! @param made Where what it gives is written.
#! @returns Whether it gives anything.
pub def fold_real(kind: op, a: u64, b: u64, made: &mut u64): bool {
val x := real_of(a);
val y := real_of(b);
match kind {
op::fadd => made = bits_of_real(x + y);
op::fsub => made = bits_of_real(x - y);
op::fmul => made = bits_of_real(x * y);
op::fdiv => made = bits_of_real(x / y);
op::frem => made = bits_of_real(x % y);
op::feq => made = x == y ? 1 : 0;
op::fne => made = x != y ? 1 : 0;
op::flt => made = x < y ? 1 : 0;
op::fle => made = x <= y ? 1 : 0;
else => return false;
}
return true;
}
#! What an operator of one value gives, as the machine works it out.
#! @param kind The operator.
#! @param a The bits of the word or real it takes.
#! @param made Where the bits of what it gives are written.
#! @returns Whether it gives anything.
pub def fold_unary(kind: op, a: u64, made: &mut u64): bool {
match kind {
op::neg => made = 0 - a;
op::bnot => made = ~a;
op::lnot => made = a == 0 ? 1 : 0;
op::fneg => made = bits_of_real(-real_of(a));
op::itof => made = bits_of_real((a as i64) as f64);
op::utof => made = bits_of_real(a as f64);
op::ftoi => made = (real_of(a) as i64) as u64;
op::ftou => made = real_of(a) as u64;
op::fsingle => made = bits_of_real((real_of(a) as f32) as f64);
op::fsqrt => made = bits_of_real(root_of(real_of(a)));
op::ones => made = ones_of(a);
op::clz => made = leading_zeros_of(a);
op::ctz => made = trailing_zeros_of(a);
op::bswap => made = bytes_swapped(a);
else => return false;
}
return true;
}
+271
View File
@@ -0,0 +1,271 @@
#! @file sink.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tenth pass of the optimizer, code sinking: an instruction whose
#! values are read only past one way out of its block moves into the block
#! that way goes to, where nothing else goes there, so what it works out is
#! worked out only where it is read. What moves only works out its values and
#! cannot stop the program, or reads memory. A read moves only where nothing
#! after it in its block may write what it reads, as alias analysis tells, and
#! where it cannot stop the program but as it would have: its address is read
#! or written through, or checked, before it, or after it in its block before
#! anything the program would be seen to do. A block one way alone goes into
#! heads no loop, so nothing moves into a loop it was not in. Blocks are walked
#! before those they dominate, each from its end, so what moved may move on
#! again.
import std::containers;
module sakura::compiler;
#! What sinking knows of the code as it goes. What reads ask of is found the
#! first time a read may move, as most code has none that may.
struct sinking {
var idom: vector<u32>; #! The immediate dominator of each block.
var readers: groups<u32>; #! The instructions reading each value, by value, once each time they read it.
var reached: dict<u64, u32>; #! How many instructions read or write through each address, or check it, in each block, by `pair_key(address, block)`.
var list: vector<u32>; #! The instructions of the block walked, in order, each that moved out 0.
var aliases: aliases; #! What may write what.
var writes: span<u64>; #! Of each instruction, the bytes a call writes what it returns to at its last operand, or 0.
var ready: bool; #! Whether `reached` and `aliases` are found.
}
#! Sinks the code of a function, knowing what each call writes what it
#! returns to.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether anything moved.
def lowerer::sink_code(&mut this, index: u32): bool {
val writes := this.result_writes(index);
return this.program.functions[index].body.sink_code(writes.view());
}
#! Sinks the code, as the file says.
#! @param this The code.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @returns Whether anything moved.
pub def code::sink_code(&mut this, writes: span<u64>): bool {
# Only a block going more than one way has anything to move out of it.
var ways := false;
for b in 0..this.blocks.length {
if !this.blocks[b].gone && this.edge_count(this.blocks[b].last) >= 2 {
ways = true;
break;
}
}
return false if !ways;
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.block_order(&mut order, &mut number);
var state := sinking {
idom = this.block_dominators(),
readers = groups::<u32>::new(this.origins.length, scratch()),
reached = dict::<u64, u32>::new(scratch()),
list = vector::<u32>::new(scratch()),
writes = writes
};
# What reads each value, counted then put.
var walk := this.walk_all();
var reads := this.reader();
while walk.more() {
reads.start(walk.next());
while reads.more() {
state.readers.count(reads.next());
}
}
state.readers.seal();
var again := this.walk_all();
while again.more() {
val at := again.next();
reads.start(at);
while reads.more() {
state.readers.put(reads.next(), at);
}
}
var changed := false;
for &block in order {
val last: u32 = this.blocks[block].last;
continue if this.edge_count(last) < 2;
changed = this.sink_block(block, &mut state) || changed;
}
return changed;
}
#! Finds what reads moving ask of the code, where it is not yet found: what
#! may write what, and what reaches through each address in each block, as the
#! code is now.
#! @param this The code.
#! @param state What sinking knows.
def code::ready_sinking(&this, state: &mut sinking): void {
return if state.ready;
state.ready = true;
state.aliases = this.aliases(state.writes, state.idom.view());
var walk := this.walk_all();
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
match held.kind {
op::load, op::store, op::clear, op::copy, op::check => {
val first := this.arg(at, 0);
if this.reaches(at, first) {
val key := pair_key(first, held.block);
state.reached.set(key, state.reached.get_or(&key, 0) + 1);
}
if held.kind == op::copy && held.imm != 0 && this.arg(at, 1) != first {
val key := pair_key(this.arg(at, 1), held.block);
state.reached.set(key, state.reached.get_or(&key, 0) + 1);
}
}
else => {}
}
}
}
#! Whether an instruction reads or writes memory through an address, or checks
#! it is not null, so that it stops the program where the address is null.
#! @param this The code.
#! @param index The instruction.
#! @param address The address.
#! @returns Whether it does.
def code::reaches(&this, index: u32, address: u32): bool {
val held := &this.insts[index];
return match held.kind {
op::load, op::store => this.arg(index, 0) == address,
op::clear => held.imm != 0 && this.arg(index, 0) == address,
op::copy => held.imm != 0 && (this.arg(index, 0) == address || this.arg(index, 1) == address),
op::check => held.aux == fault::null_reference as u32 && this.arg(index, 0) == address,
else => false
};
}
#! Moves what a block works out only for one way out of it into the block
#! that way goes to, from the block's end.
#! @param this The code.
#! @param block The block, which ends going more than one way.
#! @param state What sinking knows.
#! @returns Whether anything moved.
def code::sink_block(&mut this, block: u32, state: &mut sinking): bool {
state.list.clear();
var walk := this.walk(block);
while walk.more() {
state.list.append(walk.next());
}
var changed := false;
var k := state.list.length - 1;
while k > 0 {
k--;
val index: u32 = state.list[k];
val into := this.sink_target(index, block, state);
continue if into == no_block;
val load := this.insts[index].kind == op::load;
if load {
this.ready_sinking(state);
}
continue if load && !this.load_sinks(index, k, block, state);
# Those before it are all still in the block.
val prior: u32 = k == 0 ? 0 : state.list[k - 1];
if prior == 0 {
this.blocks[block].first = this.insts[index].next;
} else {
this.insts[prior].next = this.insts[index].next;
}
this.put_first(into, index);
state.list[k] = 0;
changed = true;
if load {
val address := this.arg(index, 0);
val from := pair_key(address, block);
state.reached.set(from, state.reached.get_or(&from, 1) - 1);
val to := pair_key(address, into);
state.reached.set(to, state.reached.get_or(&to, 0) + 1);
}
}
return changed;
}
#! Where an instruction of a block may move: the block one way out of it goes
#! to, where nothing else goes, past which everything reading its values is.
#! @param this The code.
#! @param index The instruction.
#! @param block Its block.
#! @param state What sinking knows.
#! @returns The block, or `no_block` where it stays.
def code::sink_target(&this, index: u32, block: u32, state: &sinking): u32 {
val held: inst = this.insts[index];
return no_block if held.count == 0 || held.kind.made_anywhere();
return no_block if held.kind != op::load && !this.removable(index);
var target := no_block;
for r in 0..held.count {
for &reader in state.readers.of(held.result + r as u32) {
# The block it dominates most nearly that dominates the reader's.
var at: u32 = this.insts[reader].block;
return no_block if at == block;
var steps := 0;
while true {
val up: u32 = state.idom[at];
break if up == block;
return no_block if up == no_block || up == at || steps > 256;
at = up;
steps++;
}
return no_block if target != no_block && target != at;
target = at;
}
}
return no_block if target == no_block;
val preds := &this.blocks[target].preds;
return no_block if preds.length != 1 || this.edge_source(preds[0]) != block;
return target;
}
#! Whether a read may move to after the end of its block: nothing after it in
#! the block may write what it reads, and its address is not null there, or
#! the program would have stopped as it does now. That it is read or written
#! through, or checked, before the read, in the block or one dominating it,
#! says so, as does its being so after the read in the block, before anything
#! the program would be seen to do.
#! @param this The code.
#! @param index The `load`.
#! @param k Its place among the block's instructions.
#! @param block Its block.
#! @param state What sinking knows.
#! @returns Whether it may.
def code::load_sinks(&this, index: u32, k: u64, block: u32, state: &sinking): bool {
val address := this.arg(index, 0);
val place := state.aliases.region_of(this, index, 0);
var safe := this.never_zero(address);
var quiet := true;
for j in k + 1..state.list.length {
val other: u32 = state.list[j];
continue if other == 0;
val kind := this.insts[other].kind;
return false if kind != op::load && (kind.traits() & op_write) != 0 && state.aliases.clobbers(this, other, &place);
if quiet && this.reaches(other, address) {
safe = true;
}
val stops := kind == op::load ? !this.never_zero(this.arg(other, 0)) : (kind.traits() & op_traps) != 0 && !this.removable(other);
if stops {
quiet = false;
}
}
return true if safe;
for j in 0..k {
return true if this.reaches(state.list[j], address);
}
val home := this.home_of(address);
var at := block;
var steps := 0;
while at != home && at != 0 && steps < 64 {
at = state.idom[at];
val key := pair_key(address, at);
return true if state.reached.get_or(&key, 0) != 0;
steps++;
}
return false;
}
+79
View File
@@ -0,0 +1,79 @@
#! @file unused.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the dropping of the functions nothing reaches once the program is
#! optimized, as those whose every call inlining copied. What is reached is
#! found from what is reached other than by the code's calls: `main`, the code
#! initializing the globals, the function safe points call, each function a
#! vtable holds, each C calls, and each the program takes as a value or the
#! backend calls by name. Each function reached then reaches what its code
#! calls, calls at safe points, and gives C to call, and its version. The rest
#! are dropped as though never lowered, so no code is made of them, each
#! keeping its index, and its name, which a trace of the code inlined from it
#! still gives.
module sakura::compiler;
#! Drops the functions nothing reaches, as the file says, once the program is
#! optimized and nothing more is lowered, but where every function is asked
#! for, or the program evaluates constants.
#! @param this The compiler.
pub def lowerer::drop_unreached_functions(&mut this): void {
return if this.options.everything || this.options.evaluating;
val point := mark_scratch();
val count := this.program.functions.length;
var reached := worklist::new(count, scratch());
this.reach_functions(&mut reached);
for i in 0..count {
if !reached.has(i as u32) {
this.program.functions[i].lowered = false;
}
}
release_scratch(point);
}
#! Finds the functions reached, as the file says.
#! @param this The compiler.
#! @param reached Where the functions reached are put, empty and as long as
#! the functions are; each is in it after.
pub def lowerer::reach_functions(&this, reached: &mut worklist): void {
val count := this.program.functions.length;
for i in 0..count {
if this.program.functions[i].taken || this.program.functions[i].callback {
reached.push_new(i as u32);
}
}
val roots: u32[3] = [this.program.main, this.program.init, this.dispatch];
for r in 0..3u {
if roots[r] != no_function {
reached.push_new(roots[r]);
}
}
for &each in this.program.vtables {
for &function in each.functions {
if function != no_function {
reached.push_new(function);
}
}
}
while !reached.is_empty {
val function := reached.pop();
val held := &this.program.functions[function];
if held.version != 0 {
reached.push_new(held.version - 1);
}
continue if !held.lowered;
var walk := held.body.walk_all();
while walk.more() {
val at := walk.next();
val kind := held.body.insts[at].kind;
if kind == op::call || kind == op::callback || kind == op::safepoint {
reached.push_new(held.body.insts[at].aux);
}
}
}
}
+158
View File
@@ -0,0 +1,158 @@
#! @file versions.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the versions of functions for processors with x86-64-v3's
#! instructions. A function of an executable that asks while running which
#! vector instructions the processor has, as `core::simd`'s operations do, or
#! counts a word's bits, is optimized again as a version knowing it has those of
#! x86-64-v3: SSE through SSE4.2, AVX, AVX2, FMA3, `popcnt`, `lzcnt`, and BMI1's
#! `tzcnt`. There, every operation on 16 or 32 bytes of lanes is worked with
#! instructions, so the lanes written a lane at a time go, 32 bytes of lanes are
#! values held in registers, and a count of bits is one instruction; what asks
#! for more, as 64 bytes ask for AVX-512, still asks. The function itself goes
#! to its version as it begins, where the processor has them, and its version
#! calls the versions of the functions it calls.
#!
#! A function calling one whose version is small enough to inline is given a
#! version too, though it asks nothing itself, so that its version copies the
#! other's: a loop calling `fma` works it with the instruction, rather than
#! calling a function that asks the processor each time.
module sakura::compiler;
#! The instruction sets of x86-64-v3, as the executable keeps them.
pub const cpu_v3: u64 = cpu_sse2 | cpu_ssse3 | cpu_sse41 | cpu_sse42 | cpu_avx | cpu_avx2 | cpu_fma | cpu_popcnt
| cpu_lzcnt | cpu_bmi1;
#! Whether code asks which instructions the processor has, or counts a word's
#! bits, which x86-64-v3 has instructions for. The code is compacted, as each
#! function is once it is optimized, so each instruction it holds is in a block,
#! and is looked at where it lies.
#! @param this The code.
#! @returns Whether it does.
def code::asks_processor(&this): bool {
for i in 1..this.insts.length {
val kind := this.insts[i].kind;
return true if kind == op::cpu || kind == op::ones || kind == op::clz || kind == op::ctz;
}
return false;
}
#! Copies code whole, sharing no memory with it.
#! @param this The code.
#! @returns The copy.
pub def code::duplicate(&this): code {
var made := code::new();
made.insts.clear();
made.origins.clear();
made.blocks.clear();
made.insts.extend(this.insts.view());
made.operands.extend(this.operands.view());
made.origins.extend(this.origins.view());
for &each in this.blocks {
made.blocks.append(block { first = each.first, last = each.last, params = ids::copy_of(&each.params), preds = ids::copy_of(&each.preds), gone = each.gone });
}
for &each in this.edges {
made.edges.append(edge { from = each.from, target = each.target, args = ids::copy_of(&each.args), case = each.case });
}
made.cells.extend(this.cells.view());
made.results.extend(this.results.view());
made.sites.extend(this.sites.view());
made.variables.extend(this.variables.view());
made.bindings.extend(this.bindings.view());
made.returned = this.returned;
made.vectors = this.vectors;
made.wide = this.wide;
return made;
}
#! Whether a function calls one with a version small enough to be inlined
#! whole, or `@inline`, which its own version would copy.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether it does.
def lowerer::calls_small_version(&mut this, index: u32): bool {
val limit := this.options.inline_limit != 0 ? this.options.inline_limit : inline_limit;
val body := &this.program.functions[index].body;
for i in 1..body.insts.length {
continue if body.insts[i].kind != op::call;
val version: u32 = this.program.functions[body.insts[i].aux].version;
continue if version == 0;
val facts := this.inline_facts(version - 1);
return true if facts.fits && (facts.cost <= limit || this.program.functions[version - 1].inline);
}
return false;
}
#! Whether the program's functions are given versions: in an executable
#! optimized at all.
#! @param this The compiler.
#! @returns Whether they are.
def lowerer::versions_made(&this): bool {
return this.options.level >= 1 && !this.options.evaluating
&& this.checker.names.text(this.checker.target.backend) == "native";
}
#! Makes the version of a function optimized for x86-64-v3, where it asks which
#! instructions the processor has, and optimizes it: what the processor has is
#! known to hold those, and each call goes to the version of what it calls,
#! where there is one.
#! @param this The compiler.
#! @param index The function, optimized.
#! @param ranks Where each function is in the order functions are optimized
#! in, as `optimizing` says, which the version is added to.
#! @param rank Where the version is: after the function, and before the
#! next in the order.
pub def lowerer::make_version(&mut this, index: u32, ranks: &mut vector<u32>, rank: u32): void {
return if !this.versions_made() || this.program.functions[index].body.wide;
# One left unfinished is not compacted, and nothing reaches it, so it is
# dropped rather than given a version.
return if this.program.functions[index].unfinished;
return if !this.program.functions[index].body.asks_processor() && !this.calls_small_version(index);
var body := this.program.functions[index].body.duplicate();
body.wide = true;
for i in 0..body.insts.length {
val kind := body.insts[i].kind;
if kind == op::cpu {
body.insts[i].imm = cpu_v3;
} else if kind == op::call {
val version: u32 = this.program.functions[body.insts[i].aux].version;
if version != 0 {
body.insts[i].aux = version - 1;
}
}
}
val original := &this.program.functions[index];
this.program.functions.append(function {
name = string::from(original.name.view(), nothing {}),
decl = original.decl,
instance = original.instance,
node = original.node,
outer = original.outer,
table = original.table,
file = original.file,
offset = original.offset,
signature = original.signature,
body = move(&mut body),
compiled = bytecode::new(),
lowered = true,
order = vector::<u32>::new(),
closure = original.closure,
callback = original.callback,
inline = original.inline
});
val made := (this.program.functions.length - 1) as u32;
this.program.functions[index].version = made + 1;
ranks.append(rank);
var found := vector::<string>::new();
this.optimize_function(made, ranks, rank, &mut found);
this.program.functions[made].optimized = true;
for &each in found {
this.problems.append(string::copy_of(&each));
}
}
+199
View File
@@ -0,0 +1,199 @@
#! @file program.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the program lowering makes: the layouts of its types, the
#! signatures its calls pass arguments by, its functions, each with its
#! intermediate code, the C functions it calls, the vtables of the traits it
#! refers to values through, the bytes it holds for as long as it runs, and
#! the size of its globals. Layouts and signatures are those the C compiler's
#! `sources/program.h` describes, so the runtime reads the image an executable
#! is built with as it reads the C compiler's.
module sakura::compiler;
#! Every frame word, and every scalar in a frame, is this many bytes.
pub const word_size: u64 = 8;
#! The kinds of layout, numbered as `sources/program.h` and the runtime number
#! them.
pub enum lk : u8 {
empty, #! `void`, which holds nothing.
signed, #! A signed integer.
unsigned, #! An unsigned integer.
floating, #! A float.
boolean, #! `bool`.
reference, #! A reference: the address of what it refers to.
trait_reference, #! A reference to a trait: a reference, then its vtable.
fixed, #! A fixed array: its elements, one after another.
record, #! A struct: its fields where `offset` says.
variant, #! A union: its tag, which field it holds, then that field.
function, #! A function value: its function plus one, then its environment.
pointer, #! A pointer: an address the program follows itself.
}
#! The layout of a type: how its values are held in memory and in frames.
pub struct layout {
pub var kind: lk; #! What kind of value it holds.
pub var how: access; #! How a scalar is read and written, or `bytes`.
pub var bits: u32; #! The bits of a number.
pub var size: u64; #! The bytes it takes in memory.
pub var align: u64; #! What its address in memory is a multiple of.
pub var frame: u64; #! The bytes it takes in a frame, where a scalar is widened to a word.
pub var type_id: u32; #! The type laid out.
pub var name: u32; #! The name of a struct, union, or enum, or 0.
pub var element: u32; #! One more than the layout of a fixed array's elements, or of what a reference or pointer reaches, or 0.
pub var fields: u32; #! The first of its fields in the program's `fields`.
pub var count: u32; #! How many fields it has, or elements a fixed array holds.
pub var pointers: bool; #! Whether it may hold a reference, a trait reference, or a function value.
pub var texts: bool; #! Whether it is text, written as the bytes it holds rather than as its fields.
pub var views: bool; #! Whether it is a view, written as the elements it views.
pub var viewed: u32; #! One more than the layout of the elements a view views, or 0.
pub var text: u32; #! The field saying where the bytes or elements begin, the next saying how many.
pub var niche: u32; #! Of a union laid out without a tag: one more than the field it holds wherever its first word is not zero, the other field, which is empty, held where it is.
}
#! A field of a struct or union, or a member of an enum, which its layout
#! names as a field whose offset is its value.
pub struct slot_field {
pub var name: u32; #! The ID of its name.
pub var layout: u32; #! Its layout, or 0 for a member of an enum.
var type_id: u32; #! Its type.
pub var offset: u64; #! Where it begins, or a member's value.
var decl: u32; #! The field's declaration.
var spread: bool; #! Whether it spreads another struct's fields into its own.
}
#! How a call passes arguments and takes a result: each parameter where it is
#! in the frame of the function called, and the result's layout.
pub struct signature {
pub var params: vector<u32>; #! The layout of each parameter.
var offsets: vector<u64>; #! Where each begins among the parameters.
var size: u64; #! The bytes of every parameter, in a frame.
pub var result: u32; #! The result's layout.
}
#! A function of the program.
pub struct function {
pub var name: string; #! Its name, as a trace writes it, as `vec2::normalize`.
pub var decl: u32; #! Its declaration, or 0 for what lowering makes.
pub var instance: u32; #! One more than the instance of a generic it is, or 0.
pub var node: u32; #! The node of an anonymous function, or of a function named as a value of another function type, which an adapter calls; or 0.
pub var adapted: u32; #! Of an adapter, one more than the function it calls as the function type it is of asks, or 0.
pub var outer: u32; #! Of an anonymous function, the declaration of the function it is written in.
pub var table: u32; #! The result table of an anonymous function, which holds its nodes' results.
pub var file: u32; #! The file it is declared in.
pub var offset: u32; #! The byte of the file it is declared at.
pub var signature: u32; #! How it is called.
pub var body: code; #! Its code, once lowered.
pub var compiled: bytecode; #! Its code for the machine, once assembled.
pub var lowered: bool; #! Whether its code is lowered, and kept: what nothing reaches once the program is optimized is dropped, as though never lowered.
var optimized: bool; #! Whether its code is optimized, which is done once.
var unfinished: bool; #! Whether only the passes up to inlining ran on it, as the function alone calling it copies it whole, and optimizes it there.
var inlining: inline_facts; #! What inlining knows of it.
var order: vector<u32>; #! Its blocks in reverse postorder, made once it is first inlined.
var named: vector<u32>; #! The functions its code names as values, and the code inlined into it named, which optimizing it waits for as for those it calls, so a call through one may become a call of it.
var queued: bool; #! Whether it waits to be lowered.
pub var closure: bool; #! Whether its environment follows its parameters.
pub var callback: bool; #! Whether C calls it back, as it was given where a `cfn` is expected.
pub var stepping: bool; #! Whether it is a method an iterator gives its elements by, `next` or `next_back`, or a functor's `invoke`, which a loop calling it inlines though it is larger.
pub var inline: bool; #! Whether it is written `@inline`, so each call of it is copied wherever inlining can copy one, at every level, whatever its size.
pub var taken: bool; #! Whether it is reached other than by the program's calls: as a value code takes or a constant holds, or by the backend calling it by name.
var evaluation: u32; #! One more than the evaluation it computes, of a program evaluating constants, or 0.
var builtin: u32; #! The name of the method it gives a built-in type, or 0.
var owner_type: u32; #! The built-in type it gives the method.
pub var version: u32; #! One more than its version for processors with x86-64-v3's instructions, which it goes to where the processor has them, or 0.
}
#! A C function the program calls by name, which the system finds in the
#! libraries its file's `extern import`s name, or among what the running program
#! has where it names none.
pub struct linked {
pub var name: u32; #! The ID of its name.
pub var library: string; #! The first of its libraries, which is its only one on Windows, or empty.
pub var libraries: vector<string>; #! Every library its file names for the target, which a dynamically linked executable needs.
pub var decl: u32; #! Its declaration.
}
#! The functions a type gives for a trait's methods, in the order the trait's
#! dispatch numbers them.
pub struct vtable {
var type_id: u32; #! The type referred to.
var trait_id: u32; #! The trait's type, given its arguments.
pub var layout: u32; #! The layout of what the trait reference refers to.
pub var functions: vector<u32>; #! The function of each method, or `no_function` for an `@optional` one left out.
pub var owners: vector<u32>; #! The vtable each method's code addresses: this, or a composed trait's whose default it is.
}
#! What stands where a vtable has no function, as for an `@optional` method a
#! type leaves out.
pub const no_function: u32 = 0xFFFFFFFF;
#! Where each vtable of one trait goes as a reference to it converts to a
#! reference to another, once every vtable is made.
pub struct retrait {
var from: u32; #! The trait's type converted from.
var to: u32; #! The trait's type converted to.
pub var vtables: vector<u32>; #! The vtable each becomes, by the vtable it was.
}
#! Where bytes held for as long as the program runs hold the address of other
#! such bytes: `addend` bytes into datum `target`, written at byte `at`.
pub struct relocation {
pub var at: u64; #! The byte the address is written at.
pub var target: u32; #! The datum it points into.
pub var addend: u64; #! The byte within that datum.
}
#! Bytes the program holds for as long as it runs, as text and the elements of
#! a literal viewed, which are never written. Each is followed by a zero the
#! length does not count, so text is also what C reads.
pub struct datum {
pub var bytes: vector<u8>; #! Its bytes.
pub var align: u64; #! What its address is a multiple of.
pub var relocations: vector<relocation>; #! Where its bytes hold the address of a datum.
}
#! The program.
pub struct program {
pub var layouts: vector<layout>; #! Every layout, by index.
pub var fields: vector<slot_field>; #! The fields of every layout, as runs each layout's `fields` begins.
pub var signatures: vector<signature>; #! Every signature, by index.
pub var functions: vector<function>; #! Every function, by index.
pub var linked: vector<linked>; #! The C functions it calls by name.
pub var vtables: vector<vtable>; #! Its vtables.
pub var retraits: vector<retrait>; #! The conversions between references to traits it makes.
pub var data: vector<datum>; #! What it holds for as long as it runs.
pub var globals: u64; #! The bytes of its globals.
pub var preset: vector<u8>; #! The bytes its globals begin with, as far as values known while compiling give them; the rest begin as zeros.
pub var init: u32; #! The function initializing the globals.
pub var main: u32; #! The function `main`, or `no_function`.
}
#! Makes an empty program.
#! @returns The program.
pub def program::new(): program {
return program {
layouts = vector::<layout>::new(),
fields = vector::<slot_field>::new(),
signatures = vector::<signature>::new(),
functions = vector::<function>::new(),
linked = vector::<linked>::new(),
vtables = vector::<vtable>::new(),
retraits = vector::<retrait>::new(),
data = vector::<datum>::new(),
preset = vector::<u8>::new(),
init = no_function,
main = no_function
};
}
#! Rounds a size up to a multiple of an alignment.
#! @param size The size.
#! @param align The alignment, which is not 0.
#! @returns The size rounded.
pub def round_up(size: u64, align: u64): u64 {
return (size + align - 1) / align * align;
}
+113
View File
@@ -0,0 +1,113 @@
#! @file report.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what `check --checks-report` lists: the checks a checked program
#! makes that the optimizer could not leave out, in the code of the program's
#! own functions, each at the line of the function's own source it comes from.
#! A check inlined from std, as `vector::at`'s, is at the line of the call, so
#! the list says where an unchecked build trusts the program, and where a `get`
#! may be better than `[]`.
import sakura::analyzer;
import std::containers;
module sakura::compiler;
#! What a check stops the program for.
pub enum checked : u8 {
index, #! An index or a slice past the end, of a view, a fixed array, or a container.
field, #! The field a union does not hold, read.
member, #! An integer converted to an enum none of whose members has its value, or a `match` finding no arm.
fault, #! A contract, or a check std makes itself, which faults where it fails.
count, #! How many kinds there are; not a kind itself.
}
#! The checks of one kind a function's code makes at one line of its own
#! source.
pub struct check_site {
pub var function: u32; #! The function.
pub var at: u64; #! Where in its own source: one more than the file, then the byte of the code's own instruction or of the call it was inlined from.
pub var kind: checked; #! What they stop the program for.
pub var count: u32; #! How many there are.
}
#! The checks the code of the program's own functions makes, once lowered and
#! optimized, in the order of the functions and of where each is.
#! @param this The compiler.
#! @returns The checks, those of each place and kind together.
pub def lowerer::checks_left(&mut this): vector<check_site> {
var made := vector::<check_site>::new();
for f in 0..this.program.functions.length {
val held := &this.program.functions[f];
continue if !held.lowered;
val decl := held.decl != 0 ? held.decl : held.outer;
continue if decl == 0 || this.in_std(decl);
var found := dict::<u64, u32>::new();
var places := vector::<u64>::new();
var walk := held.body.walk_all();
while walk.more() {
val each: inst = held.body.insts[walk.next()];
val kind := this.check_kind(&each);
continue if kind == checked::count;
val at := own_place(&held.body, &each);
val key := (at << 3) | kind as u64;
if found.contains(&key) {
found[key] += 1;
} else {
found.set(key, 1);
places.append(key);
}
}
places.sort();
for &key in places {
made.append(check_site { function = f as u32, at = key >> 3, kind = (key & 7) as checked, count = found[key] });
}
}
return made;
}
#! What an instruction checks, or `checked::count` where it checks nothing.
#! @param this The compiler.
#! @param held The instruction.
#! @returns The kind.
def lowerer::check_kind(&mut this, held: &inst): checked {
match held.kind {
op::check => {
return match held.aux {
fault::out_of_bounds as u32 => checked::index,
fault::not_held as u32 => checked::field,
fault::not_member as u32 => checked::member,
else => checked::count
};
}
op::trap => return held.aux == fault::not_member as u32 ? checked::member : checked::count;
op::fault => return checked::fault;
op::call => {
# A container's own check calls `past_end` only where it fails.
val decl := this.program.functions[held.aux].decl;
return checked::count if decl == 0 || !this.in_std(decl);
return this.checker.names.text(this.checker.decls.names.p[decl]) == "past_end" ? checked::index : checked::count;
}
else => return checked::count;
}
}
#! Where an instruction is in the source of the function whose code holds it:
#! its own place, or, inlined, that of the outermost call it was inlined from.
#! @param body The code.
#! @param held The instruction.
#! @returns The place: one more than the file, then the byte.
def own_place(body: &code, held: &inst): u64 {
var site := held.site;
var at := held.at;
var steps := 0;
while site != 0 && steps < 256 {
val from: inline_site = body.sites[site - 1];
at = from.at;
site = from.parent;
steps++;
}
return at;
}
+145
View File
@@ -0,0 +1,145 @@
#! @file scratch.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the arenas what the compiler works out only for a while is held in:
#! what a pass of the optimizer finds before it changes the code, and what
#! lowering, verifying, and assembling a function find as they go. Each of those
#! marks the arena where it begins and rewinds it to the mark where it ends, so
#! what it took is freed at once, and the next takes the same memory again.
#! Handing out a block is then an addition, and giving it back nothing at all.
#!
#! Each thread has an arena of its own, as a mark and a rewind on one thread
#! would otherwise free what another still holds. The first thread takes from
#! one of its own; the threads `share_out` starts, its crew, each take from one
#! of the crew's arenas, which each finds by the number the system knows its
#! thread by, while the crew works. Where none works, as while the compiler
#! works alone, nothing is looked for.
import std::thread;
import std::allocators;
module sakura::compiler;
#! The arena the first thread's scratch memory comes from, in chunks of 256 KiB,
#! which the compiler never closes.
var scratch_arena := arena::new(262144);
#! The arenas of the crew, which stay where they are while it works, so the
#! room for them is made before any of it starts. They are kept, with their
#! chunks, for the next crew.
var crew_arenas := vector::<arena>::new();
#! The number the system knows each thread of the crew by, by its place, or 0
#! until it starts. Every thread reads these, and none writes them once the
#! crew has started, so they stay in every processor's cache.
var crew_threads := vector::<atomic<u64>>::new();
#! The arena each thread of the crew takes from, by its place, which only that
#! thread reads and writes once the crew has started, each on a line of the
#! processor's cache of its own, so one writing its own makes no other read
#! again.
var crew_hands := vector::<hand>::new();
#! How many threads the crew has, or 0 where none works.
var crew_size := atomic::<u32>::new(0);
#! The arena a thread of the crew takes from, padded to a line of the
#! processor's cache.
struct hand {
var arena: u32; #! Its place in `crew_arenas`.
var pad: u64[7]; #! What fills the rest of the line.
}
#! Memory for what the compiler works out only while it does one thing, which
#! is freed where that ends.
#! @returns The arena of the thread calling, as an allocator.
#! @remarks Nothing taken from it may be kept past the mark it was taken after:
#! a vector of it is closed before the mark is rewound to, and never
#! moved into what outlives it, as the code of a function does.
pub def scratch(): maybe<&mut allocator> {
return own_arena();
}
#! Where the scratch memory of the thread calling has been handed out to, which
#! `release_scratch` frees what was handed out after.
#! @returns The mark.
pub def mark_scratch(): arena::point {
return own_arena().mark();
}
#! Frees the scratch memory the thread calling had handed out after a mark.
#! @param to The mark, which `mark_scratch` gave on the same thread.
pub def release_scratch(to: arena::point): void {
own_arena().rewind(to);
}
#! The arena the thread calling takes its scratch memory from: that of its place
#! in the crew, or the first thread's.
#! @returns The arena.
def own_arena(): &mut arena {
val size := crew_size.load(order::acquire);
if size != 0 {
val me := thread::id();
for k in 0..size as u64 {
if crew_threads[k].load(order::relaxed) == me {
return &mut crew_arenas[crew_hands[k].arena as u64];
}
}
}
return &mut scratch_arena;
}
#! Makes the room a crew works in, before any of it starts: a place for each
#! thread, the `k`th taking from the `k`th arena until it takes from another,
#! and as many arenas as are asked for, at least one for each thread.
#! @param threads How many threads the crew has.
#! @param arenas How many arenas it takes from.
pub def gather_crew(threads: u32, arenas: u32): void {
expects(crew_size.load(order::acquire) == 0);
val wanted := arenas > threads ? arenas : threads;
while crew_arenas.length < wanted as u64 {
crew_arenas.append(arena::new(262144));
}
crew_threads.clear();
crew_hands.clear();
for k in 0..threads {
crew_threads.append(atomic::<u64>::new(0));
crew_hands.append(hand { arena = k });
}
crew_size.store(threads, order::release);
}
#! Says the thread calling is the one of a place in the crew, which takes its
#! scratch memory from that place's arena from then on.
#! @param place Its place.
pub def join_crew(place: u32): void {
crew_threads[place as u64].store(thread::id(), order::release);
}
#! Has the thread of a place in the crew, which calls it, take its scratch
#! memory from another arena.
#! @param place Its place.
#! @param arena The arena, by its place among the crew's.
pub def take_scratch_from(place: u32, arena: u32): void {
crew_hands[place as u64].arena = arena;
}
#! One of the crew's arenas, for the thread that holds it alone, as to reset it.
#! @param index Its place among the crew's.
#! @returns The arena.
pub def crew_arena(index: u32): &mut arena {
return &mut crew_arenas[index as u64];
}
#! Says no crew works any more, once every thread of it has ended. Its arenas
#! are reset, keeping their chunks for the next.
pub def dismiss_crew(): void {
crew_size.store(0, order::release);
crew_threads.clear();
crew_hands.clear();
for &mut each in crew_arenas {
each.reset();
}
}
+211
View File
@@ -0,0 +1,211 @@
#! @file tracking.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the small containers the compiler's passes keep track of what they
#! find with: a worklist, which takes each index once, a set emptied at once
#! each round, and a dictionary whose changes are taken back as a scope ends.
import std::containers;
module sakura::compiler;
#! A worklist of indices below a count, as of the blocks a walk reaches or the
#! values a pass finds needed: each is pushed once, and is known to have been
#! pushed after it is popped.
pub struct worklist {
var seen: vector<bool>; #! Whether each index was pushed.
var todo: vector<u32>; #! The indices pushed and not popped yet, the next last.
}
#! Makes an empty worklist.
#! @param count How many indices there are.
#! @param alloc The optional allocator its memory is taken from.
#! @returns The worklist.
pub def worklist::new(count: u64, alloc: maybe<&mut allocator>): worklist {
var made := worklist { seen = vector::<bool>::new(alloc), todo = vector::<u32>::new(alloc) };
made.seen.resize(count);
return made;
}
#! Whether no index pushed is left to pop.
#! @param this The worklist.
#! @returns Whether none is.
pub val worklist::is_empty: bool {
get => this.todo.length == 0;
}
#! Pushes an index, where it was never pushed before.
#! @param this The worklist.
#! @param index The index.
#! @returns Whether it was new.
pub def worklist::push_new(&mut this, index: u32): bool {
return false if this.seen[index];
this.push(index);
return true;
}
# Pushes an index never pushed before, apart from `push_new`, so that what
# asks whether it was is small enough to be inlined.
def worklist::push(&mut this, index: u32): void {
this.seen[index] = true;
this.todo.append(index);
}
#! Pops the index pushed last of those left.
#! @param this The worklist, which holds one, or else the program stops.
#! @returns The index.
pub def worklist::pop(&mut this): u32 {
val index: u32 = this.todo.last();
this.todo.truncate();
return index;
}
#! Whether an index was ever pushed.
#! @param this The worklist.
#! @param index The index.
#! @returns Whether it was.
pub def worklist::has(&this, index: u32): bool {
return this.seen[index];
}
#! A set of indices below a count, emptied at once as each round begins, as
#! what one function, or one block, of many counted: an index is in the set
#! where it was put in during the round.
pub struct stamped_set {
var stamps: vector<u32>; #! The round each index was last put in during, or 0.
var round: u32; #! The round now, from 1.
}
#! Makes an empty set, in its first round.
#! @param count How many indices there are.
#! @param alloc The optional allocator its memory is taken from.
#! @returns The set.
pub def stamped_set::new(count: u64, alloc: maybe<&mut allocator>): stamped_set {
var made := stamped_set { stamps = vector::<u32>::new(alloc), round = 1 };
made.stamps.resize(count);
return made;
}
#! Begins the next round, which empties the set.
#! @param this The set.
pub def stamped_set::next_round(&mut this): void {
this.round++;
}
#! Puts an index in the set, whether or not it is in it already.
#! @param this The set.
#! @param index The index.
pub def stamped_set::put(&mut this, index: u32): void {
this.stamps[index] = this.round;
}
#! Puts an index in the set.
#! @param this The set.
#! @param index The index.
#! @returns Whether it was new to the set this round.
pub def stamped_set::insert(&mut this, index: u32): bool {
return false if this.stamps[index] == this.round;
this.stamps[index] = this.round;
return true;
}
#! Whether an index was put in the set this round.
#! @param this The set.
#! @param index The index.
#! @returns Whether it was.
pub def stamped_set::contains(&this, index: u32): bool {
return this.stamps[index] == this.round;
}
#! A dictionary of plain keys and values, as indices, whose changes are taken
#! back as a scope ends: each value set is noted with what its key held before,
#! and rewinding to a mark puts back what each key held then, the last change
#! first, as a walk down a tree takes back what each node added as it leaves.
#! @tparam K The type of its keys, which a `dict` takes.
#! @tparam V The type of its values.
pub struct scoped_dict<K, V> {
var map: dict<K, V>; #! What each key holds now.
var changes: vector<scoped_dict<K, V>::change>; #! Each change made, in order.
}
#! A change a scoped dictionary made: the key set, and what it held before.
pub struct scoped_dict<K, V>::change {
var key: K; #! The key.
var old: V; #! The value it held before, where it held one.
var had: bool; #! Whether it held one.
}
#! Makes an empty dictionary.
#! @param alloc The optional allocator its memory is taken from.
#! @returns The dictionary.
pub def scoped_dict<K, V>::new(alloc: maybe<&mut allocator>): scoped_dict<K, V> {
return scoped_dict::<K, V> {
map = dict::<K, V>::new(alloc),
changes = vector::<scoped_dict<K, V>::change>::new(alloc)
};
}
#! Reads the value of a key.
#! @param this The dictionary.
#! @param key The key.
#! @returns Maybe the value; otherwise, `nothing`.
pub def scoped_dict<K, V>::get(&this, key: &K): maybe<&V> {
return this.map.get(key);
}
#! The value of a key, or another value where it holds none.
#! @param this The dictionary.
#! @param key The key.
#! @param fallback What is given where the key holds no value.
#! @returns The value, or `fallback`.
pub def scoped_dict<K, V>::get_or(&this, key: &K, fallback: V): V {
return this.map.get_or(key, fallback);
}
#! Whether a key holds a value.
#! @param this The dictionary.
#! @param key The key.
#! @returns Whether it does.
pub def scoped_dict<K, V>::contains(&this, key: &K): bool {
return this.map.contains(key);
}
#! Sets the value of a key, noting what it held before.
#! @param this The dictionary.
#! @param key The key.
#! @param value The value.
pub def scoped_dict<K, V>::set(&mut this, key: K, value: V): void {
if this.map.insert(key, value) {
this.changes.append(scoped_dict::<K, V>::change { key = key, old = value, had = false });
return;
}
this.changes.append(scoped_dict::<K, V>::change { key = key, old = this.map.get_or(&key, value), had = true });
this.map.set(key, value);
}
#! How many changes were made, which `rewind` takes back those made since.
#! @param this The dictionary.
#! @returns The mark.
pub def scoped_dict<K, V>::mark(&this): u64 {
return this.changes.length;
}
#! Takes back the changes made since a mark, the last first.
#! @param this The dictionary.
#! @param mark How many changes were made before.
pub def scoped_dict<K, V>::rewind(&mut this, mark: u64): void {
return if this.changes.length <= mark;
var at := this.changes.length;
while at > mark {
at--;
val each: scoped_dict<K, V>::change = this.changes[at];
if each.had {
this.map.set(each.key, each.old);
} else {
this.map.remove(&each.key);
}
}
this.changes.resize(mark);
}
+145
View File
@@ -0,0 +1,145 @@
#! @file workers.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains how the compiler shares work out among threads: a crew of them,
#! with the thread asking, takes the indexes of what is to be done, each the
#! next one none has taken, until none is left. What each does is its own, as
#! the code of one function, and what they all read stays as it is while they
#! work, so they never wait on one another but to take an index. Each thread of
#! the crew has scratch memory of its own, as `scratch.sakura` says.
#!
#! Where one thread is asked for, none starts, and the thread asking does every
#! index, in order: the compiler then works as it would with no threads at all.
import std::containers;
import std::thread;
module sakura::compiler;
#! Does something for each index below a count, on as many threads as asked,
#! the one calling among them, each taking the next index none has taken.
#! @param count How many indexes there are.
#! @param threads How many threads work, the one calling among them; where
#! more are asked for than there are indexes, one is started
#! for each index but the first, and where some cannot be
#! started, those that were do it all.
#! @param each What is done for an index, which may be done on any of the
#! threads, at the same time as for others.
pub def share_out(count: u64, threads: u32, each: def(u64): void): void {
val helpers := crew_for(count, threads);
if helpers == 0 {
for i in 0..count {
each(i);
}
return;
}
var next := atomic::<u64>::new(0);
run_crew(helpers, def(): void {
take_each(&mut next, count, each);
});
}
#! Does something for each index below a count, as `share_out` does, but for
#! each only once it is done for those the index waits for, each of which is
#! below it, so one thread doing them all does them in order.
#! @param count How many indexes there are.
#! @param threads How many threads work, the one calling among them.
#! @param waiting The indexes waiting for each index, grouped by it, sealed,
#! each once in a group.
#! @param each What is done for an index, which may be done on any of the
#! threads, at the same time as for others it does not wait
#! for.
pub def share_out_ordered(count: u64, threads: u32, waiting: &groups<u32>, each: def(u64): void): void {
val helpers := crew_for(count, threads);
if helpers == 0 {
for i in 0..count {
each(i);
}
return;
}
# Each index is handed out once nothing it waits for is left undone, and the
# thread doing the last closes the channel, which ends every thread taking
# from it.
var waits := vector::<u32>::new();
waits.resize(count);
for i in 0..count {
for &after in waiting.of(i) {
waits[after] = waits[after] + 1;
}
}
var left := vector::<atomic<u32>>::new();
var ready := thread::channel::<u64>::new(0);
var done := atomic::<u64>::new(0);
for i in 0..count {
left.append(atomic::<u32>::new(waits[i]));
if waits[i] == 0 {
_ = ready.send(i);
}
}
val work := def(): void {
while ready.receive() is some(index) {
each(index);
for &after in waiting.of(index) {
if left[after].fetch_sub(1) == 1 {
_ = ready.send(after as u64);
}
}
if done.fetch_add(1) + 1 == count {
ready.close();
}
}
};
run_crew(helpers, work);
}
#! Runs work on a crew of threads started beside the one calling, which runs it
#! too, each with scratch memory of its own, and waits for every one to end.
#! @param helpers How many threads to start; where some cannot be started,
#! those that were and the one calling do the work.
#! @param work What each thread runs, which shares out what it does with
#! the others.
pub def run_crew(helpers: u32, work: def(): void): void {
gather_crew(helpers, helpers);
var started := vector::<thread::handle<void>>::new();
for k in 0..helpers {
var made := thread::spawn_with::<u32>(def(place: u32): void {
join_crew(place);
work();
}, k) else (_) { break; };
started.append(move(&mut made));
}
work();
for &mut handle in started {
handle.join();
}
dismiss_crew();
}
#! How many threads to start beside the one calling, for a count of indexes and
#! the threads asked for.
#! @param count How many indexes there are.
#! @param threads How many threads are asked for, the one calling among them.
#! @returns How many, 0 where the one calling does it all.
pub def crew_for(count: u64, threads: u32): u32 {
return 0 if threads <= 1 || count <= 1;
return (count - 1) as u32 if count - 1 < (threads - 1) as u64;
return threads - 1;
}
#! Takes the next index none has taken, and does what is done for it, until
#! none is left.
#! @param next The next index none has taken.
#! @param count How many indexes there are.
#! @param each What is done for each.
def take_each(next: &mut atomic<u64>, count: u64, each: def(u64): void): void {
while true {
val index := next.fetch_add(1);
return if index >= count;
each(index);
}
}