Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-11-19 04:54:17 -06:00
commit f086abcea6
789 files changed
+149185

No files matched your search

+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>::blank(), 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>::blank(), 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>::blank(), 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>::blank(), 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>::blank(), 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>::blank(), 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>::blank(), 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>::blank(), 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.span.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.span {
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.span {
keeps.append(aliases[param] == 0);
}
if keeps.span.contains(&false) {
this.drop_params(b as u32, keeps.span);
}
}
}
#! 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 => {}
}
}
}
+679
View File
@@ -0,0 +1,679 @@
#! @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.
overflow = 29, #! Integer arithmetic giving what its type cannot hold, checked as `--checks` asks.
}
#! 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.
environment, #! What a closure takes of the locals it uses, which the frame writes as it makes the closure, and again each time it does, as a local is.
}
#! 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(this.origins[: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.span.data;
val values_to := value_to.span.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(this.insts[: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.span);
}
+196
View File
@@ -0,0 +1,196 @@
#! @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
, indexable<u64, u32>
, assignable<u64, u32>
, spannable<u32>
, sliceable<u32>
, 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.span {
made.append(each);
}
return made;
}
#! Lends a view of some of the indices of a list, as `spannable` asks.
#! @param other The list.
#! @param start The place of the first index viewed.
#! @param count How many are viewed, or `~0u` for every one after the start.
#! @returns The view, which refers into the list.
pub def ids::span_of(other: &ids, start: u64 = 0, count: u64 = ~0u): span<u32> {
val whole := span::<u32>::over(other.data(), other._len as u64);
return count == ~0u ? whole[start:] : whole[start:count];
}
#! Lends a view of some of the indices of a list that writes them where they
#! are, as `sliceable` asks.
#! @param other The list, which can be written.
#! @param start The place of the first index viewed.
#! @param count How many are viewed, or `~0u` for every one after the start.
#! @returns The view, which refers into the list.
pub def ids::slice_of(other: &mut ids, start: u64 = 0, count: u64 = ~0u): slice<u32> {
val data := other._cap == 0 ? (&mut other._own) as *mut u32 : other._dat;
val whole := slice::<u32>::over(data, other._len as u64);
return count == ~0u ? whole[start:] : whole[start:count];
}
#! A view of the indices.
#! @param this The list.
#! @returns The view, which refers into the list.
pub val ids::span: span<u32> {
get => span::<u32>::over(this.data(), this._len as u64);
}
#! A view of the indices that writes them where they are, read of a list that
#! can be written.
#! @param this The list.
#! @returns The view, which refers into the list.
pub val ids::slice: slice<u32> {
get mut => slice::<u32>::over(this._cap == 0 ? (&mut this._own) as *mut u32 : this._dat, 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::iterator = span<u32>::iterator;
#! Lends an iterator that reads the indices.
#! @param this The list.
#! @returns The iterator, which refers into the list.
pub def ids::iter(&this): span<u32>::iterator {
return this.span.iter();
}
#! An iterator that reads the indices, as `iter` lends.
#! @param this The list.
#! @returns The iterator, which refers into the list.
pub val ids::iterator: span<u32>::iterator {
get => this.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.span);
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.span);
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.span);
number.clear();
number.extend(this.kept_number.span);
}
#! 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.span);
number.clear();
number.extend(this.kept_number.span);
}
#! 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.span, this.kept_number.span);
this.kept_idom.clear();
this.kept_idom.extend(found.span);
this.idom_kept = true;
}
var made := vector::<u32>::new(scratch());
made.extend(this.kept_idom.span);
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.span != order {
found.append("The order of the blocks kept is not theirs now.");
}
if this.idom_kept && this.kept_idom.span != 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.span, number.span);
this.check_kept_order(order.span, idom.span, &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.span);
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.span.data,
values = this.operands.span.data,
edges = this.edges.span.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;
}