Files
2026-11-19 04:54:17 -06:00

1625 lines
66 KiB
Plaintext

#! @file bytecode.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the code the machine runs, made from each function's intermediate
#! code. Every value is held in a word of the frame, and values whose lives do
#! not overlap share one, as a linear scan over where each is held finds. What
#! a block takes is moved into its words on each edge into it. Cells follow the
#! words, and the parameters, which a call copies into the frame of the
#! function it calls, come first.
#!
#! The code is words: an operation, then its operands, most of them words of
#! the frame. Where in the source each instruction is from is kept beside it,
#! for the trace of a fault.
#!
#! Where the machine has an operation doing the work of two, the code uses it:
#! a constant fitting a word of the code is taken into the instruction reading
#! it, and a comparison only a branch or a check reads, or an addition only a
#! load or a store of a byte reads as its address, is made part of that, where
#! that is, so it reads its operands there. A constant every instruction
#! reading takes so is not made at all, nor what is made part of another. The
#! last move of an edge, or an addition of a constant just before a block's
#! jump, jumps as the jump following it would.
import std::containers;
module sakura::compiler;
#! The operations of the machine's code, each with the operands it is followed
#! by. A frame word is written as its index, a label as the place in the code
#! it stands for, and a word of 64 bits as its low and then its high half.
pub enum bc : u8 {
konst, #! dst, low, high: a word.
move, #! dst, src: copies a word.
# Operators of two words, dst, a, b, in the order `op` declares them.
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,
# Operators of one word, dst, a, in the order `op` declares them.
neg, bnot, lnot, fneg, itof, utof, ftoi, ftou, fsingle, fsqrt, ones, clz, ctz, bswap,
wrap, #! dst, a, bits, signed: the word narrowed to its bits.
select, #! dst, condition, a, b: `a` where the condition is not zero, and `b` where it is.
cell, #! dst, offset: the address that many bytes into the frame.
global, #! dst, offset: the address that many bytes into the globals.
datum, #! dst, datum, offset: the address that many bytes into a datum.
# Reading memory, dst, address, offset, each as its access says.
load_i8, load_u8, load_i16, load_u16, load_i32, load_u32, load_i64, load_f32,
# Writing memory, address, offset, value, each as wide as it says.
store_8, store_16, store_32, store_64, store_f32,
copy, #! to, from, size: copies bytes.
clear, #! address, size: zeroes bytes.
allocate, #! dst, size, uncleared: memory the program gives back itself, zeroed unless uncleared is 1.
release, #! address: gives memory back.
resize, #! dst, address, size: memory holding what the address's did.
call, #! function, argc, args..., resc, results...
call_trait, #! signature, slot, argc, args..., resc, results...
call_value, #! signature, argc, args..., resc, results...
call_c, #! signature, argc, args..., resc, results...
c_address, #! dst, index: the address of a C function.
callback, #! dst, function: the address C calls a function through.
equal, #! dst, a, b, layout: whether the values at the addresses are equal.
retrait, #! dst, vtable, map: the vtable a reference to another trait takes.
check, #! condition, fault: stops the program where the word is zero.
syscall, #! dst, number, a, b, c, d, e, f: what the kernel gives.
frame, #! dst: the frame pointer, in an executable.
image, #! dst: the image an executable was built with.
environ, #! dst: where the system put the variables the program started with.
signals, #! dst: the signals that came since last asked.
catch, #! dst, number: has the signal noted.
safepoint, #! function: calls it where a signal the program handles came.
exit, #! code: ends the program with the status.
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.
format, #! Begins text.
format_text, #! datum: adds the datum's bytes.
format_value, #! layout, count, words...: adds a value.
format_bytes, #! pointer, length: adds the bytes.
format_owned, #! pointer, length: the text made, in memory the program gives back.
jump, #! label.
jump_if, #! condition, label: goes there where the word is not zero.
jump_zero, #! condition, label: goes there where the word is zero.
switch, #! value, count, (low, high, label)..., label: goes where the word is the case.
ret, #! count, words...: returns the words.
ret_memory, #! address: returns the memory there.
trap, #! fault: stops the program.
trap_word, #! word: stops the program with the fault the word is.
unreachable, #! Is never reached.
ready, #! evaluation: stops unless the constant is evaluated, while compiling.
reach, #! pointer, count, size: stops unless the elements are memory the program holds, while compiling.
same, #! a, b: stops unless the pointers are within the same memory, while compiling.
atomic, #! dst, operation, imm, address, a, b: an atomic operation, of the access and sign `imm` gives, on the address, with the operands `a` and `b`.
start, #! dst, function, environment, context: starts a thread running the function value, given the context.
# Operations doing the work of two of those above, where code does it often.
# A constant is a word of the code standing for the 64 bits its sign extends
# to, which no word of the frame holds.
# Operators of a word and a constant, dst, a, constant, as their operators.
add_k, mul_k, band_k, shl_k, shrs_k, shru_k,
# Writing a constant to memory, address, offset, constant, each as wide as it
# says, of which `store_k64` takes the constant's low and then its high half.
store_k8, store_k16, store_k32, store_k64,
# Comparisons going to the label where they hold: of two words, a, b, label,
jump_eq, jump_ne, jump_lts, jump_ltu, jump_les, jump_leu,
# and of a word and a constant, a, constant, label.
jump_eq_k, jump_ne_k, jump_lts_k, jump_ltu_k, jump_les_k, jump_leu_k, jump_gts_k, jump_gtu_k, jump_ges_k, jump_geu_k,
check_ltu, #! a, b, fault: stops the program unless a < b, unsigned, as a check of an index does.
check_ltu_k, #! a, constant, fault: stops the program unless a is below the constant, unsigned.
load_u8_x, #! dst, a, b, offset: reads a byte unsigned at the sum of two words and the offset, as indexing bytes does.
store_8_x, #! a, b, offset, value: writes a byte at the sum of two words and the offset.
move_jump, #! dst, src, label: copies a word, then goes to the label, as the last move of an edge does.
add_k_jump, #! dst, a, constant, label: adds, then goes to the label, as the step of a loop does.
# Operators of two reals rounded to an `f32`, dst, a, b, as the operator of
# `f32`s an `fsingle` alone reads is, which it is made part of.
fadd_f32, fsub_f32, fmul_f32, fdiv_f32,
# What only a run checking its memory has.
forget, #! address, size: marks bytes as never written.
watch_read, #! address, offset, size: stops the program where a byte the load after reads was never written.
watch_write, #! address, offset, size: marks the bytes the store after writes as written.
count, #! How many operations there are; not an operation itself.
}
#! How many words each operation of the machine's code takes, its operation
#! included. An operation followed by a count of words takes those too: a
#! call's operands and results, `format_value`'s words, `switch`'s cases, three
#! words each, and `ret`'s words.
pub const bc_widths: u64[bc::count as u64] = [
4, 3, # konst, move
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, # add to shru
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, # eq to leus
4, 4, 4, 4, 4, 4, 4, 4, 4, # fadd to fle
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, # neg to bswap
5, # wrap
5, # select
3, 3, 4, # cell, global, datum
4, 4, 4, 4, 4, 4, 4, 4, # load_i8 to load_f32
4, 4, 4, 4, 4, # store_8 to store_f32
4, 3, 4, 2, 4, # copy, clear, allocate, release, resize
4, 5, 4, 4, # call, call_trait, call_value, call_c, before their counts
3, 3, # c_address, callback
5, 4, 3, # equal, retrait, check
9, 2, 2, 2, 2, 3, 2, 2, 1, 3, # syscall to fault
1, 2, 3, 3, 3, # format to format_owned, `format_value` before its count
2, 3, 3, 4, 2, 2, 2, 2, 1, # jump to unreachable, `switch` and `ret` before their counts
2, 4, 3, # ready, reach, same
8, 5, # atomic, start
4, 4, 4, 4, 4, 4, # add_k to shru_k
4, 4, 4, 5, # store_k8 to store_k64
4, 4, 4, 4, 4, 4, # jump_eq to jump_leu
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, # jump_eq_k to jump_geu_k
4, 4, # check_ltu, check_ltu_k
5, 5, # load_u8_x, store_8_x
4, 5, # move_jump, add_k_jump
4, 4, 4, 4, # fadd_f32 to fdiv_f32
3, 4, 4 # forget, watch_read, watch_write
];
#! Where an instruction of the code is from: from `pc` on, until the next mark.
pub struct line_mark {
pub var pc: u32; #! The first word of the code it holds for.
pub var at: u64; #! Where in the source: one more than the file, then the byte.
pub var site: u32; #! One more than the site of the function inlined there, or 0 for the function's own code.
}
#! How a function takes a parameter into its frame.
pub struct param_slot {
pub var memory: bool; #! Whether it is held in memory, its own copy given by address.
pub var words: u32; #! How many words it is, where it is not held in memory.
pub var offset: u64; #! Where it begins in the frame, in bytes.
pub var size: u64; #! The bytes of one held in memory.
}
#! A function's code for the machine.
pub struct bytecode {
pub var code: vector<u32>; #! The code.
pub var lines: vector<line_mark>; #! Where each run of it is from.
pub var sites: vector<inline_site>; #! Where the functions inlined into it were called, which its marks name.
pub var params: vector<param_slot>; #! How each parameter is taken.
pub var frame: u64; #! The bytes of the frame.
pub var cells: u64; #! Where the cells begin, the first of which are zeroed as it starts.
pub var zeroed: u64; #! Where the cells zeroed as it starts end, those it need not zero following.
pub var env: u64; #! Where a closure's environment is.
pub var returned: u64; #! The bytes of the memory it returns, or 0 where it returns words.
pub var done: bool; #! Whether it is made.
}
#! Makes an empty function code.
#! @returns The code.
pub def bytecode::new(): bytecode {
return bytecode {
code = vector::<u32>::new(),
lines = vector::<line_mark>::new(),
sites = vector::<inline_site>::new(),
params = vector::<param_slot>::new()
};
}
#! What stands for no value, label, or position.
const none: u32 = 0xFFFFFFFF;
#! A read of a value: the block it is in, and where.
struct value_read {
var block: u32;
var place: u32;
}
#! What assembling one function keeps track of, which makes the moves between
#! the words of its values.
struct assembler : move_maker<word_move> {
var order: vector<u32>; #! The blocks, in the order they are laid out.
var number: vector<u32>; #! Each block's place in that order.
var starts: vector<u32>; #! Where each block begins, which its parameters are held from.
var ends: vector<u32>; #! Where each block's edges leave, which their arguments are held to.
var places: vector<u32>; #! Where each instruction reads; it writes one after.
var lows: vector<u32>; #! Where each value is first held.
var highs: vector<u32>; #! Where each value is last held.
var slots: vector<u32>; #! The word of the frame holding each value.
var cells: vector<u64>; #! Where each cell begins in the frame.
var out: vector<u32>; #! The code made.
var lines: vector<line_mark>; #! Where each run of it is from.
var labels: vector<u32>; #! Where each label is in the code: those of the blocks, then others.
var fixups: vector<u32>; #! The words of the code naming a label, which is written there.
var scratch: u32; #! A word no value is held in, for moves going round in a cycle.
var last_at: u64; #! Where the instruction made last is from.
var last_site: u32; #! The site of the function the instruction made last was inlined from.
var left: vector<u32>; #! How many reads of each value read its word: all but those taking it as a constant, and that of what is made part of its reader.
var takes: vector<u8>; #! Which operand of each instruction it takes as a constant, or `no_take`.
var folds: vector<u32>; #! The instruction each comparison or addition is made part of, or `none`.
var prior: u32; #! The instruction before the one being made, in its block, or 0.
var watches: bool; #! Whether each load and store not of a cell is watched for memory never written, as a run checking its memory asks.
var copies: bool; #! Whether it is a function copying bytes, whose loads are not watched.
var escaped: vector<bool>; #! Whether each cell's address is taken as a value, as by a closure taking a local, which a run checking its memory watches as it watches what is not a cell.
}
#! What stands for no operand taken as a constant.
const no_take: u8 = 0xFF;
#! Makes the machine's code of every function lowered that has none yet, each
#! freeing the scratch memory it took as it ends. Each function's code is made
#! from its own alone, so as many threads as the options say make them at once.
#! @param this The compiler.
pub def lowerer::assemble_all(&mut this): void {
val compiler := &mut this;
share_out(this.program.functions.length, this.options.threads, def(i: u64): void {
return if !compiler.program.functions[i].finished || compiler.program.functions[i].compiled.done;
val point := mark_scratch();
compiler.assemble(i as u32);
release_scratch(point);
});
}
#! Makes the machine's code of a function.
#! @param this The compiler.
#! @param index The function.
pub def lowerer::assemble(&mut this, index: u32): void {
val signature: u32 = this.program.functions[index].signature;
var made := bytecode::new();
made.done = true;
# The parameters come first in the frame, where the call copies them, then
# the environment of a closure.
var pinned := vector::<u32>::new();
var copies := vector::<u64>::new();
val count := this.program.signatures[signature].params.length;
for i in 0..count {
val shape := this.layout_at(this.program.signatures[signature].params[i]);
val offset: u64 = this.program.signatures[signature].offsets[i];
if in_memory(&shape) {
made.params.append(param_slot { memory = true, offset = offset, size = shape.size });
pinned.append(none);
copies.append(offset);
continue;
}
val words := word_count(&shape);
made.params.append(param_slot { words = words, offset = offset });
for w in 0..words {
pinned.append((offset / word_size) as u32 + w as u32);
copies.append(0);
}
}
var area: u64 = this.program.signatures[signature].size;
made.env = area;
if this.program.functions[index].closure {
pinned.append((area / word_size) as u32);
copies.append(0);
area += word_size;
}
val body := &this.program.functions[index].body;
made.returned = body.returned as u64;
var work := assembler {
order = vector::<u32>::new(),
number = vector::<u32>::new(),
starts = vector::<u32>::new(),
ends = vector::<u32>::new(),
places = vector::<u32>::new(),
lows = vector::<u32>::new(),
highs = vector::<u32>::new(),
slots = vector::<u32>::new(),
cells = vector::<u64>::new(),
out = vector::<u32>::new(),
lines = vector::<line_mark>::new(),
labels = vector::<u32>::new(),
fixups = vector::<u32>::new(),
left = vector::<u32>::new(),
takes = vector::<u8>::new(),
folds = vector::<u32>::new(),
watches = this.options.checks,
copies = this.options.checks && this.copies_bytes(index),
escaped = this.options.checks ? escaped_cells(body) : vector::<bool>::new()
};
body.copy_order(&mut work.order, &mut work.number);
work.place(body);
work.fuse(body);
work.live(body);
val words := work.allocate(body, &pinned, (area / word_size) as u32);
# The cells follow the words, each aligned as it asks: first those the frame
# zeroes, as an executable's prologue does, then those it need not: those of
# functions inlined, whose code clears them, those `undefined`, and those
# every read of which some write comes before.
val writes := this.result_writes(index);
val zeroed := zeroed_cells(body, work.order.span, work.number.span, writes.span);
var at := words as u64 * word_size;
made.cells = round_up(at, 16);
at = made.cells;
work.cells.resize(body.cells.length);
for pass in 0..2u {
for i in 0..body.cells.length {
val each: cell = body.cells[i];
val zeroes := each.kind != ck::inlined && each.kind != ck::undefined && zeroed[i];
continue if zeroes != (pass == 0);
at = round_up(at, each.align as u64);
work.cells[i] = at;
at += each.size as u64;
}
if pass == 0 {
made.zeroed = at;
}
}
made.frame = round_up(at, 16);
# A parameter held in memory is the address of the frame's copy of it.
val entry := &body.blocks[0];
for i in 0..entry.params.length {
continue if i >= copies.length || pinned[i] != none;
val value: u32 = entry.params[i];
work.emit3(bc::cell, work.slots[value], copies[i] as u32);
}
work.emit_all(body);
made.code = move(&mut work.out);
made.lines = move(&mut work.lines);
made.sites.extend(body.sites.span);
this.program.functions[index].compiled = move(&mut made);
}
#! Says where each block and instruction is, in the order the blocks are laid
#! out: a block's parameters are held from its start, each instruction reads
#! where it is and writes one past it, and the arguments of the edges leaving a
#! block are read at its end.
#! @param this The assembler.
#! @param body The code.
def assembler::place(&mut this, body: &code): void {
this.starts.resize(body.blocks.length);
this.ends.resize(body.blocks.length);
this.places.resize(body.insts.length);
var pos: u32 = 0;
for k in 0..this.order.length {
val block: u32 = this.order[k];
this.starts[block] = pos;
pos += 2;
var walk := body.walk(block);
while walk.more() {
this.places[walk.next()] = pos;
pos += 2;
}
this.ends[block] = pos;
pos += 2;
}
}
#! Works out which instructions the code makes part of others: each operand
#! that is a constant fitting a word of the code, where the machine has a form
#! of the instruction reading it taking one, each comparison only a branch or a
#! check in its block reads, where the machine has a form of the two together,
#! which takes a constant of the comparison too, each addition of words only a
#! load or a store of a byte in its block reads, as its address, and each
#! arithmetic of reals only an `fsingle` in its block reads, as an `f32`'s.
#! @param this The assembler.
#! @param body The code.
def assembler::fuse(&mut this, body: &code): void {
this.left.resize(body.origins.length);
this.takes.resize(body.insts.length, no_take);
this.folds.resize(body.insts.length, none);
var given := body.reader();
for &block in this.order {
var walk := body.walk(block);
while walk.more() {
given.start(walk.next());
while given.more() {
val value := given.next();
this.left[value] = this.left[value] + 1;
}
}
}
for k in 0..this.order.length {
var walk := body.walk(this.order[k]);
while walk.more() {
val index := walk.next();
match body.insts[index].kind {
op::add, op::mul, op::band => {
if !this.take(body, index, 1, false) {
_ = this.take(body, index, 0, false);
}
}
op::sub => {
_ = this.take(body, index, 1, true);
}
op::shl, op::shrs, op::shru => {
_ = this.take(body, index, 1, false);
}
op::load => this.fold_address(body, index);
op::store => {
this.take_stored(body, index);
if this.takes[index] == no_take {
this.fold_address(body, index);
}
}
op::branch, op::check => this.fold(body, index);
op::fsingle => this.fold_single(body, index);
else => {}
}
}
}
}
#! Takes an operand of an instruction as a constant, where it is one fitting a
#! word of the code.
#! @param this The assembler.
#! @param body The code.
#! @param index The instruction.
#! @param at The operand's position.
#! @param negated Whether the code takes the constant negated, as it makes a
#! subtraction an addition.
#! @returns Whether it is taken.
def assembler::take(&mut this, body: &code, index: u32, at: u32, negated: bool): bool {
val value := body.arg(index, at);
val from: origin = body.origins[value];
return false if from.param || body.insts[from.from].kind != op::iconst;
val bits := bits_of(body, value);
return false if !fits_word(negated ? 0 - bits : bits);
this.takes[index] = at as u8;
this.left[value] = this.left[value] - 1;
return true;
}
#! Takes the value a store writes as a constant, where it is one: the bits of
#! a word or a real, which `store_k64` takes whole, and the narrower stores the
#! low bits of, as they write them, but none `store_f32` rounds.
#! @param this The assembler.
#! @param body The code.
#! @param index The store.
def assembler::take_stored(&mut this, body: &code, index: u32): void {
val how := body.insts[index].aux as access;
return if how.value_type().lanes() || how == access::f32;
val value := body.arg(index, 1);
val from: origin = body.origins[value];
return if from.param;
val kind := body.insts[from.from].kind;
return if kind != op::iconst && kind != op::fconst;
this.takes[index] = 1;
this.left[value] = this.left[value] - 1;
}
#! Makes the comparison a branch or a check reads part of it, where nothing
#! else reads it, it is in the same block, and the machine has a form of the
#! two together: a branch on any comparison of words as equal or ordered, and
#! a check of an index below a count, or of a word not zero, which is a check
#! of the word itself.
#! @param this The assembler.
#! @param body The code.
#! @param index The branch or check.
def assembler::fold(&mut this, body: &code, index: u32): void {
val cond := body.arg(index, 0);
val from: origin = body.origins[cond];
return if from.param || this.left[cond] != 1;
val compare: u32 = from.from;
val held: inst = body.insts[compare];
return if held.block != body.insts[index].block;
if body.insts[index].kind == op::branch {
return if (held.kind as u32) < op::eq as u32 || (held.kind as u32) > op::leu as u32;
this.folds[compare] = index;
this.left[cond] = 0;
if !this.take(body, compare, 1, false) {
_ = this.take(body, compare, 0, false);
}
return;
}
if held.kind != op::ltu {
return if held.kind != op::ne;
val zero: origin = body.origins[body.arg(compare, 1)];
return if zero.param || body.insts[zero.from].kind != op::iconst || body.insts[zero.from].imm != 0;
}
this.folds[compare] = index;
this.left[cond] = 0;
_ = this.take(body, compare, 1, false);
}
#! Makes the arithmetic of reals an `fsingle` rounds part of it, where nothing
#! else reads it and it is in the same block, so the machine works it as one
#! operation of `f32`s.
#! @param this The assembler.
#! @param body The code.
#! @param index The `fsingle`.
def assembler::fold_single(&mut this, body: &code, index: u32): void {
val real := body.arg(index, 0);
val from: origin = body.origins[real];
return if from.param || this.left[real] != 1;
val held: inst = body.insts[from.from];
return if held.block != body.insts[index].block;
return if held.kind != op::fadd && held.kind != op::fsub && held.kind != op::fmul && held.kind != op::fdiv;
this.folds[from.from] = index;
this.left[real] = 0;
}
#! The arithmetic of reals made part of an `fsingle`.
#! @param this The assembler.
#! @param body The code.
#! @param index The `fsingle`.
#! @returns The arithmetic, or `none` where none is.
def assembler::single_of(&this, body: &code, index: u32): u32 {
val from: origin = body.origins[body.arg(index, 0)];
return none if from.param || this.folds[from.from] != index;
return from.from;
}
#! Makes the addition giving a load's or a store's address part of it, where
#! nothing else reads it, it is in the same block, it adds two words, and the
#! machine has a form of the load or the store at a sum.
#! @param this The assembler.
#! @param body The code.
#! @param index The load or store.
def assembler::fold_address(&mut this, body: &code, index: u32): void {
return if this.watches || indexed_of(body, index) == bc::count;
val address := body.arg(index, 0);
val from: origin = body.origins[address];
return if from.param || this.left[address] != 1;
val sum: u32 = from.from;
val held: inst = body.insts[sum];
return if held.kind != op::add || held.block != body.insts[index].block || this.takes[sum] != no_take;
this.folds[sum] = index;
this.left[address] = 0;
}
#! Whether a function is one of `core`'s that copy bytes, `memcpy` and those it
#! calls, whose reads a run checking its memory does not watch: copying bytes
#! never written uses none of them, as moving a block that is partly written
#! does, so the bytes copied count as written where they go.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether it is.
def lowerer::copies_bytes(&mut this, index: u32): bool {
val decl := this.program.functions[index].decl;
return false if decl == 0 || !this.in_std(decl);
val name := this.checker.names.text(this.checker.decls.names.p[decl]);
return name == "memcpy" || name == "copyfwd" || name == "copybwd";
}
#! Whether each cell's address is taken as a value, rather than only read,
#! written, copied, or cleared through, so what another function or thread
#! reaches through it is the cell: what a closure takes of a local, or a
#! reference to one given away.
#! @param body The code.
#! @returns Whether each is.
def escaped_cells(body: &code): vector<bool> {
var made := vector::<bool>::new();
made.resize(body.cells.length, false);
for i in 0..body.insts.length {
val held: inst = body.insts[i];
val through := held.kind == op::load || held.kind == op::store || held.kind == op::copy
|| held.kind == op::clear || held.kind == op::forget;
for k in 0..held.argc {
val from: origin = body.origins[body.arg(i as u32, k)];
continue if from.param || body.insts[from.from].kind != op::cell;
continue if through && (k == 0 || held.kind == op::copy && k == 1);
made[body.insts[from.from].aux as u64] = true;
}
}
return made;
}
#! Watches the bytes a load reads or a store writes, running with memory
#! checked: those of a cell the frame holds are left alone, as each is written
#! before it is read or was zeroed as the frame began, but for a cell
#! `undefined`, and one whose address is taken, which another thread may reach
#! as this one reaches it, as the race checker watches. A closure's
#! environment, which the frame writes again each time it makes the closure,
#! with the same references, is left alone too.
#! @param this The assembler.
#! @param body The code.
#! @param index The load or store.
#! @param kind `watch_read` or `watch_write`.
def assembler::watch(&mut this, body: &code, index: u32, kind: bc): void {
return if !this.watches || (this.copies && kind == bc::watch_read);
val held: inst = body.insts[index];
val address := body.arg(index, 0);
val from: origin = body.origins[address];
if !from.param && body.insts[from.from].kind == op::cell {
val cell := body.insts[from.from].aux;
return if body.cells[cell].kind != ck::undefined && (!this.escaped[cell as u64] || body.cells[cell].kind == ck::environment);
}
this.emit4(kind, this.arg(body, index, 0), held.imm as u32, (held.aux as access).width() as u32);
}
#! The form of a load or a store at the sum of two words, where the machine has
#! one: reading a byte unsigned, or writing a byte.
#! @param body The code.
#! @param index The load or store.
#! @returns The operation, or `bc::count` where it has none.
def indexed_of(body: &code, index: u32): bc {
val how := body.insts[index].aux as access;
if body.insts[index].kind == op::load {
return how == access::u8 ? bc::load_u8_x : bc::count;
}
return how == access::i8 || how == access::u8 ? bc::store_8_x : bc::count;
}
#! The addition made part of a load or a store, giving its address.
#! @param this The assembler.
#! @param body The code.
#! @param index The load or store.
#! @returns The addition, or `none` where none is.
def assembler::sum_of(&this, body: &code, index: u32): u32 {
val from: origin = body.origins[body.arg(index, 0)];
return none if from.param || this.folds[from.from] != index;
return from.from;
}
#! Whether an instruction makes no code of its own: a comparison or an addition
#! made part of another, or a constant no instruction reads from its word.
#! @param this The assembler.
#! @param body The code.
#! @param index The instruction.
#! @returns Whether it does not.
def assembler::omitted(&this, body: &code, index: u32): bool {
return true if this.folds[index] != none;
val held: inst = body.insts[index];
return (held.kind == op::iconst || held.kind == op::fconst) && this.left[held.result] == 0;
}
#! Whether an instruction's read of a value reads its word: where it neither
#! takes it as a constant, nor makes the instruction giving it part of itself.
#! @param this The assembler.
#! @param body The code.
#! @param index The instruction.
#! @param operand The position of the operand read, or `no_operand` for an
#! argument of an edge.
#! @param value The value.
#! @returns Whether it does.
def assembler::reads_word(&this, body: &code, index: u32, operand: u32, value: u32): bool {
return false if operand != no_operand && this.takes[index] != no_take && operand == this.takes[index] as u32;
val from: origin = body.origins[value];
return from.param || this.folds[from.from] != index;
}
#! The bits of a constant.
#! @param body The code.
#! @param value The constant.
#! @returns Its bits.
def bits_of(body: &code, value: u32): u64 {
return body.insts[body.origins[value].from].imm;
}
#! Whether a constant is one a word of the code stands for.
#! @param bits The constant.
#! @returns Whether it is.
def fits_word(bits: u64): bool {
return bits == bc_constant((bits & 0xFFFFFFFF) as u32);
}
#! The constant a word of the code stands for: the 64 bits its sign extends to.
#! @param word The word.
#! @returns The constant.
pub def bc_constant(word: u32): u64 {
return ((word as i32) as i64) as u64;
}
#! Works out where each value is held, from where it is made to where it is
#! last read, and over every block it is held into along the way, as a value
#! read in a loop is held around it.
#! @param this The assembler.
#! @param body The code.
def assembler::live(&mut this, body: &code): void {
val values := body.origins.length;
this.lows.resize(values, none);
this.highs.resize(values);
for k in 0..this.order.length {
val block: u32 = this.order[k];
for &param in body.blocks[block].params {
this.lows[param] = this.starts[block];
this.highs[param] = this.starts[block];
}
var insts := body.walk(block);
while insts.more() {
val at := insts.next();
val held: inst = body.insts[at];
for r in 0..held.count {
this.lows[held.result as u64 + r as u64] = this.places[at] + 1;
this.highs[held.result as u64 + r as u64] = this.places[at] + 1;
}
}
}
# Each value's reads, gathered together: the block and position of each.
var reads := groups::<value_read>::new(values);
this.each_read(body, &mut reads);
reads.seal();
this.each_read(body, &mut reads);
# A value read in a block other than its own is held into that block, and
# out of every block before it on the way back to its own, laid out or not.
var walk := live_walk::new(body.blocks.length, nothing {});
for v in 1..values {
continue if this.lows[v] == none || reads.length(v) == 0;
walk.begin(v as u32, body.home_of(v as u32));
for &read in reads.of(v) {
this.extend(v as u32, read.place);
walk.read(read.block, read.place);
}
walk.walk(body, &this.number, false);
for &block in walk.touched {
val reach: block_reach = walk.reaches[block];
if reach.into {
this.extend(v as u32, this.starts[block]);
}
if reach.out {
this.extend(v as u32, this.ends[block]);
}
}
}
}
#! Walks every read of a value's word, in the blocks laid out: each operand of
#! an instruction, read where the instruction it is made part of is, if any,
#! and each argument of an edge, read at the end of the block it leaves.
#! Counts the reads of each value, or, once the reads are sealed, puts where
#! each is.
#! @param this The assembler.
#! @param body The code.
#! @param reads The reads of each value.
def assembler::each_read(&this, body: &code, reads: &mut groups<value_read>): void {
val fill := reads.is_sealed;
var given := body.reader();
for &block in this.order {
var walk := body.walk(block);
while walk.more() {
val index := walk.next();
val at: u32 = this.folds[index] != none ? this.folds[index] : index;
given.start(index);
while given.more() {
val value := given.next();
continue if !this.reads_word(body, index, given.operand(), value);
if fill {
val place := given.operand() != no_operand ? this.places[at] : this.ends[block];
reads.put(value, value_read { block = block, place = place });
} else {
reads.count(value);
}
}
}
}
}
#! Holds a value at a position too.
#! @param this The assembler.
#! @param value The value.
#! @param pos The position.
def assembler::extend(&mut this, value: u32, pos: u32): void {
if pos < this.lows[value] {
this.lows[value] = pos;
}
if pos > this.highs[value] {
this.highs[value] = pos;
}
}
#! Gives each value a word of the frame, sharing one between values whose lives
#! do not overlap, but those of instructions making no code of their own. The
#! function's parameters are where the call copies them.
#! @param this The assembler.
#! @param body The code.
#! @param pinned The word of each parameter of the entry, or `none` for one
#! given a word as any other value is.
#! @param first The first word not taken by the parameters.
#! @returns How many words the values take, the parameters' included.
def assembler::allocate(&mut this, body: &code, pinned: &vector<u32>, first: u32): u32 {
this.slots.resize(body.origins.length, none);
val entry := &body.blocks[0];
for i in 0..entry.params.length {
if i < pinned.length && pinned[i] != none {
this.slots[entry.params[i]] = pinned[i];
}
}
var next := first;
var free := vector::<u32>::new();
var active := vector::<u32>::new();
for k in 0..this.order.length {
val block: u32 = this.order[k];
for &param in body.blocks[block].params {
this.assign(param, &mut next, &mut free, &mut active);
}
var walk := body.walk(block);
while walk.more() {
val index := walk.next();
continue if this.omitted(body, index);
val held: inst = body.insts[index];
for r in 0..held.count {
this.assign(held.result + r as u32, &mut next, &mut free, &mut active);
}
}
}
this.scratch = next;
return next + 1;
}
#! Gives a value a word, once the values no longer held where it begins give
#! theirs back.
#! @param this The assembler.
#! @param value The value.
#! @param next The next word never given.
#! @param free The words given back.
#! @param active The values holding words.
def assembler::assign(&mut this, value: u32, next: &mut u32, free: &mut vector<u32>, active: &mut vector<u32>): void {
return if this.slots[value] != none;
val begins: u32 = this.lows[value];
var i := active.length;
while i > 0 {
i--;
val held: u32 = active[i];
continue if this.highs[held] >= begins;
free.append(this.slots[held]);
active[i] = active.last;
active.truncate();
}
if free.length != 0 {
this.slots[value] = free.last;
free.truncate();
} else {
this.slots[value] = next;
next = next + 1;
}
active.append(value);
}
#! Adds a word to the code.
#! @param this The assembler.
#! @param word The word.
def assembler::put(&mut this, word: u32): void {
this.out.append(word);
}
#! Adds an operation of one operand.
#! @param this The assembler.
#! @param kind The operation.
#! @param a Its operand.
def assembler::emit1(&mut this, kind: bc, a: u32): void {
this.out.append(kind as u32);
this.out.append(a);
}
#! Adds an operation of two operands.
#! @param this The assembler.
#! @param kind The operation.
#! @param a Its first operand.
#! @param b Its second.
def assembler::emit3(&mut this, kind: bc, a: u32, b: u32): void {
this.out.append(kind as u32);
this.out.append(a);
this.out.append(b);
}
#! Adds an operation of three operands.
#! @param this The assembler.
#! @param kind The operation.
#! @param a Its first operand.
#! @param b Its second.
#! @param c Its third.
def assembler::emit4(&mut this, kind: bc, a: u32, b: u32, c: u32): void {
this.out.append(kind as u32);
this.out.append(a);
this.out.append(b);
this.out.append(c);
}
#! Adds an operation of four operands.
#! @param this The assembler.
#! @param kind The operation.
#! @param a Its first operand.
#! @param b Its second.
#! @param c Its third.
#! @param d Its fourth.
def assembler::emit5(&mut this, kind: bc, a: u32, b: u32, c: u32, d: u32): void {
this.out.append(kind as u32);
this.out.append(a);
this.out.append(b);
this.out.append(c);
this.out.append(d);
}
#! Adds a word naming a label, written once the label is placed.
#! @param this The assembler.
#! @param label The label.
def assembler::put_label(&mut this, label: u32): void {
this.fixups.append(this.out.length as u32);
this.out.append(label);
}
#! Makes a label, not yet placed.
#! @param this The assembler.
#! @returns The label.
def assembler::new_label(&mut this): u32 {
this.labels.append(none);
return (this.labels.length - 1) as u32;
}
#! The word holding a value.
#! @param this The assembler.
#! @param body The code.
#! @param index The instruction.
#! @param at The position of the operand.
#! @returns The word.
def assembler::arg(&this, body: &code, index: u32, at: u32): u32 {
return this.slots[body.arg(index, at)];
}
#! The word holding a result of an instruction.
#! @param this The assembler.
#! @param body The code.
#! @param index The instruction.
#! @param at Which result.
#! @returns The word.
def assembler::result(&this, body: &code, index: u32, at: u32): u32 {
return this.slots[body.insts[index].result + at];
}
#! Adds the code of every block, in the order laid out, then writes where each
#! label is.
#! @param this The assembler.
#! @param body The code.
def assembler::emit_all(&mut this, body: &code): void {
this.labels.resize(body.blocks.length, none);
this.last_at = 0xFFFFFFFFFFFFFFFF;
for k in 0..this.order.length {
val block: u32 = this.order[k];
this.labels[block] = this.out.length as u32;
val next: u32 = k + 1 < this.order.length ? this.order[k + 1] : none;
this.prior = 0;
var walk := body.walk(block);
while walk.more() {
val index := walk.next();
this.emit_inst(body, index, next);
this.prior = index;
}
}
for f in 0..this.fixups.length {
val word: u32 = this.fixups[f];
this.out[word] = this.labels[this.out[word]];
}
}
#! Adds the code of an instruction.
#! @param this The assembler.
#! @param body The code.
#! @param index The instruction.
#! @param next The block laid out next, which a jump to needs no jump.
def assembler::emit_inst(&mut this, body: &code, index: u32, next: u32): void {
return if this.omitted(body, index);
val held: inst = body.insts[index];
if held.at != this.last_at || held.site != this.last_site {
this.lines.append(line_mark { pc = this.out.length as u32, at = held.at, site = held.site });
this.last_at = held.at;
this.last_site = held.site;
}
val kind := held.kind;
val number := kind as u32;
if number >= op::add as u32 && number <= op::fle as u32 {
if this.takes[index] != no_take {
this.emit_taking(body, index);
return;
}
this.emit4((bc::add as u32 + (number - op::add as u32)) as bc, this.result(body, index, 0),
this.arg(body, index, 0), this.arg(body, index, 1));
return;
}
if kind == op::fsingle {
val arithmetic := this.single_of(body, index);
if arithmetic != none {
val which := body.insts[arithmetic].kind as u32 - op::fadd as u32;
this.emit4((bc::fadd_f32 as u32 + which) as bc, this.result(body, index, 0),
this.arg(body, arithmetic, 0), this.arg(body, arithmetic, 1));
return;
}
}
if number >= op::neg as u32 && number <= op::bswap as u32 {
this.emit3((bc::neg as u32 + (number - op::neg as u32)) as bc, this.result(body, index, 0), this.arg(body, index, 0));
return;
}
match kind {
op::iconst, op::fconst => this.emit4(bc::konst, this.result(body, index, 0),
(held.imm & 0xFFFFFFFF) as u32, (held.imm >> 32) as u32);
op::wrap => this.emit5(bc::wrap, this.result(body, index, 0), this.arg(body, index, 0), held.aux, held.imm as u32);
op::select => this.emit5(bc::select, this.result(body, index, 0), this.arg(body, index, 0), this.arg(body, index, 1), this.arg(body, index, 2));
op::cell => this.emit3(bc::cell, this.result(body, index, 0), this.cells[held.aux] as u32);
op::global => this.emit3(bc::global, this.result(body, index, 0), held.imm as u32);
op::datum => this.emit4(bc::datum, this.result(body, index, 0), held.aux, held.imm as u32);
op::load => {
val sum := this.sum_of(body, index);
this.watch(body, index, bc::watch_read);
if (held.aux as access).value_type().lanes() {
this.emit1(bc::trap, 3);
} else if sum != none {
this.emit5(indexed_of(body, index), this.result(body, index, 0), this.arg(body, sum, 0), this.arg(body, sum, 1), held.imm as u32);
} else {
this.emit4(load_of(held.aux as access), this.result(body, index, 0), this.arg(body, index, 0), held.imm as u32);
}
}
op::store => {
val sum := this.sum_of(body, index);
this.watch(body, index, bc::watch_write);
if (held.aux as access).value_type().lanes() {
this.emit1(bc::trap, 3);
} else if this.takes[index] != no_take {
this.emit_stored(body, index);
} else if sum != none {
this.emit5(indexed_of(body, index), this.arg(body, sum, 0), this.arg(body, sum, 1), held.imm as u32, this.arg(body, index, 1));
} else {
this.emit4(store_of(held.aux as access), this.arg(body, index, 0), held.imm as u32, this.arg(body, index, 1));
}
}
op::copy => this.emit4(bc::copy, this.arg(body, index, 0), this.arg(body, index, 1), held.imm as u32);
op::clear => this.emit3(bc::clear, this.arg(body, index, 0), held.imm as u32);
op::forget => this.emit3(bc::forget, this.arg(body, index, 0), held.imm as u32);
op::allocate => this.emit4(bc::allocate, this.result(body, index, 0), this.arg(body, index, 0), body.insts[index].aux);
op::release => this.emit1(bc::release, this.arg(body, index, 0));
op::resize => this.emit4(bc::resize, this.result(body, index, 0), this.arg(body, index, 0), this.arg(body, index, 1));
op::call, op::call_trait, op::call_value, op::call_c => this.emit_call(body, index);
op::c_address => this.emit3(bc::c_address, this.result(body, index, 0), held.aux);
op::callback => this.emit3(bc::callback, this.result(body, index, 0), held.aux);
op::equal => this.emit5(bc::equal, this.result(body, index, 0), this.arg(body, index, 0), this.arg(body, index, 1), held.aux);
op::retrait => this.emit4(bc::retrait, this.result(body, index, 0), this.arg(body, index, 0), held.aux);
op::check => this.emit_check(body, index);
op::syscall => {
this.put(bc::syscall as u32);
this.put(this.result(body, index, 0));
for a in 0..7 {
this.put(a < held.argc ? this.arg(body, index, a as u32) : this.scratch);
}
}
op::frame => this.emit1(bc::frame, this.result(body, index, 0));
op::image => this.emit1(bc::image, this.result(body, index, 0));
op::environ => this.emit1(bc::environ, this.result(body, index, 0));
op::signals => this.emit1(bc::signals, this.result(body, index, 0));
op::catch => this.emit3(bc::catch, this.result(body, index, 0), this.arg(body, index, 0));
op::safepoint => this.emit1(bc::safepoint, held.aux);
op::exit => this.emit1(bc::exit, this.arg(body, index, 0));
op::abort => this.put(bc::abort as u32);
op::fault => this.emit3(bc::fault, this.arg(body, index, 0), this.arg(body, index, 1));
op::format => this.put(bc::format as u32);
op::format_text => this.emit1(bc::format_text, held.aux);
op::format_value => {
this.put(bc::format_value as u32);
this.put(held.aux);
this.put(held.argc);
for a in 0..held.argc {
this.put(this.arg(body, index, a as u32));
}
}
op::format_bytes => this.emit3(bc::format_bytes, this.arg(body, index, 0), this.arg(body, index, 1));
op::format_owned => this.emit3(bc::format_owned, this.result(body, index, 0), this.result(body, index, 1));
op::jump => {
val moved := this.moves(body, held.aux);
if body.edges[held.aux].target != next {
this.put_jump(body.edges[held.aux].target, moved ? bc::move : this.joined(body, index));
}
}
op::branch => this.emit_branch(body, index, next);
op::switch => this.emit_switch(body, index);
op::ret => {
if body.returned != 0 {
this.emit1(bc::ret_memory, this.arg(body, index, 0));
return;
}
this.put(bc::ret as u32);
this.put(held.argc);
for a in 0..held.argc {
this.put(this.arg(body, index, a as u32));
}
}
op::trap => {
if held.argc != 0 {
this.emit1(bc::trap_word, this.arg(body, index, 0));
} else {
this.emit1(bc::trap, held.aux);
}
}
op::unreachable => this.put(bc::unreachable as u32);
op::ready => this.emit1(bc::ready, held.aux);
op::reach => this.emit4(bc::reach, this.arg(body, index, 0), this.arg(body, index, 1), held.imm as u32);
op::same => this.emit3(bc::same, this.arg(body, index, 0), this.arg(body, index, 1));
# The machine has no vector instructions, so no processor's, and never works
# the lanes with them.
op::atomic => {
# The machine works one thread at a time, so it works every operation as
# `seq_cst`; the order, which comes after the operands, and for
# `compare_exchange` the one where it succeeds, is what the race checker
# orders the threads by.
val fence := held.aux == atomic_fence;
val operands: u32 = fence || held.aux == atomic_load ? 0 : held.aux == atomic_compare_exchange ? 2 : 1;
this.put(bc::atomic as u32);
this.put(atomic_gives(held.aux) ? this.result(body, index, 0) : this.scratch);
this.put(held.aux);
this.put(held.imm as u32);
this.put(fence ? this.scratch : this.arg(body, index, 0));
this.put(operands >= 1 ? this.arg(body, index, 1) : this.scratch);
this.put(operands >= 2 ? this.arg(body, index, 2) : this.scratch);
this.put(this.arg(body, index, fence ? 0u : operands + 1));
}
op::start => {
this.put(bc::start as u32);
this.put(this.result(body, index, 0));
for a in 0..3u {
this.put(this.arg(body, index, a as u32));
}
}
op::current, op::clone => this.emit1(bc::trap, 3);
op::cpu => this.emit4(bc::konst, this.result(body, index, 0), 0, 0);
op::lanes, op::vzero => this.emit1(bc::trap, 3);
else => this.put(bc::unreachable as u32);
}
}
#! The operation reading memory as an access says, of which a float's bits are
#! read as a word's are.
#! @param how The access.
#! @returns The operation.
def load_of(how: access): bc {
return match how {
access::i8 => bc::load_i8,
access::u8 => bc::load_u8,
access::i16 => bc::load_i16,
access::u16 => bc::load_u16,
access::i32 => bc::load_i32,
access::u32 => bc::load_u32,
access::f32 => bc::load_f32,
else => bc::load_i64
};
}
#! The operation writing memory as an access says, which only needs its width.
#! @param how The access.
#! @returns The operation.
def store_of(how: access): bc {
return match how {
access::i8, access::u8 => bc::store_8,
access::i16, access::u16 => bc::store_16,
access::i32, access::u32 => bc::store_32,
access::f32 => bc::store_f32,
else => bc::store_64
};
}
#! Adds an operator of a word and the constant it takes: an addition, which a
#! subtraction is of the constant negated, a multiplication, an `&`, or a
#! shift.
#! @param this The assembler.
#! @param body The code.
#! @param index The instruction.
def assembler::emit_taking(&mut this, body: &code, index: u32): void {
val held: inst = body.insts[index];
val at := this.takes[index] as u32;
var bits := bits_of(body, body.arg(index, at));
if held.kind == op::sub {
bits = 0 - bits;
}
val kind := match held.kind {
op::add, op::sub => bc::add_k,
op::mul => bc::mul_k,
op::band => bc::band_k,
op::shl => bc::shl_k,
op::shrs => bc::shrs_k,
else => bc::shru_k
};
this.emit4(kind, this.result(body, index, 0), this.arg(body, index, 1 - at), (bits & 0xFFFFFFFF) as u32);
}
#! Adds a store of the constant it takes, as wide as its access says.
#! @param this The assembler.
#! @param body The code.
#! @param index The store.
def assembler::emit_stored(&mut this, body: &code, index: u32): void {
val held: inst = body.insts[index];
val bits := bits_of(body, body.arg(index, 1));
val kind := match store_of(held.aux as access) {
bc::store_8 => bc::store_k8,
bc::store_16 => bc::store_k16,
bc::store_32 => bc::store_k32,
else => bc::store_k64
};
this.emit4(kind, this.arg(body, index, 0), held.imm as u32, (bits & 0xFFFFFFFF) as u32);
if kind == bc::store_k64 {
this.put((bits >> 32) as u32);
}
}
#! Adds a check: of the word of its condition, or of the comparison made part
#! of it, an index below a count, of words or a word and a constant, or a word
#! not zero, which is a check of the word.
#! @param this The assembler.
#! @param body The code.
#! @param index The check.
def assembler::emit_check(&mut this, body: &code, index: u32): void {
val held: inst = body.insts[index];
val cond := body.arg(index, 0);
val from: origin = body.origins[cond];
if from.param || this.folds[from.from] != index {
this.emit3(bc::check, this.slots[cond], held.aux);
return;
}
val compare: u32 = from.from;
val word := this.arg(body, compare, 0);
if body.insts[compare].kind == op::ne {
this.emit3(bc::check, word, held.aux);
} else if this.takes[compare] != no_take {
this.emit4(bc::check_ltu_k, word, (bits_of(body, body.arg(compare, 1)) & 0xFFFFFFFF) as u32, held.aux);
} else {
this.emit4(bc::check_ltu, word, this.arg(body, compare, 1), held.aux);
}
}
#! Adds a call: what it calls, its operands, then the words of its results.
#! @param this The assembler.
#! @param body The code.
#! @param index The instruction.
def assembler::emit_call(&mut this, body: &code, index: u32): void {
val held: inst = body.insts[index];
val kind := match held.kind {
op::call => bc::call,
op::call_trait => bc::call_trait,
op::call_value => bc::call_value,
else => bc::call_c
};
this.put(kind as u32);
this.put(held.aux);
# A trait's method is called through the slot of its vtable.
if held.kind == op::call_trait {
this.put(held.imm as u32);
}
this.put(held.argc);
for a in 0..held.argc {
this.put(this.arg(body, index, a as u32));
}
this.put(held.count as u32);
for r in 0..held.count {
this.put(this.result(body, index, r as u32));
}
}
#! Adds a branch: to where the condition is not zero, and otherwise to the
#! other edge, each moving what its block takes, and neither jumping to the
#! block laid out next.
#! @param this The assembler.
#! @param body The code.
#! @param index The instruction.
#! @param next The block laid out next.
def assembler::emit_branch(&mut this, body: &code, index: u32, next: u32): void {
val held: inst = body.insts[index];
val then := held.aux;
val other := held.aux + 1;
val then_target: u32 = body.edges[then].target;
val other_target: u32 = body.edges[other].target;
val then_moves := this.has_moves(body, then);
val other_moves := this.has_moves(body, other);
if !then_moves && !other_moves {
if then_target == next {
this.put_test(body, index, false);
this.put_label(other_target);
return;
}
this.put_test(body, index, true);
this.put_label(then_target);
if other_target != next {
this.put(bc::jump as u32);
this.put_label(other_target);
}
return;
}
# The moves of each edge are made down its own path.
val otherwise := this.new_label();
this.put_test(body, index, false);
this.put_label(otherwise);
val moved := this.moves(body, then);
this.put_jump(then_target, moved ? bc::move : bc::count);
this.labels[otherwise] = this.out.length as u32;
val moved_other := this.moves(body, other);
if other_target != next {
this.put_jump(other_target, moved_other ? bc::move : bc::count);
}
}
#! Adds a jump to a label, which the instruction made last takes part of,
#! where that is the last move of the edge the jump follows, or the addition
#! of a constant `joined` finds.
#! @param this The assembler.
#! @param label The label.
#! @param last The operation of the instruction made last that takes the
#! jump, `move` or `add_k`, or `count` where none does.
def assembler::put_jump(&mut this, label: u32, last: bc): void {
if last == bc::count {
this.put(bc::jump as u32);
} else {
this.out[this.out.length - bc_widths[last as u64]] = (last == bc::move ? bc::move_jump : bc::add_k_jump) as u32;
}
this.put_label(label);
}
#! The operation of the instruction made last, which a block's jump moving
#! nothing may be made part of: the addition of a constant just before it,
#! from the same place in the source, so a trace of the two reads the same.
#! @param this The assembler.
#! @param body The code.
#! @param index The jump.
#! @returns `add_k`, or `count` where it is not that.
def assembler::joined(&this, body: &code, index: u32): bc {
return bc::count if this.prior == 0;
val before: inst = body.insts[this.prior];
val held: inst = body.insts[index];
return bc::count if (before.kind != op::add && before.kind != op::sub) || this.takes[this.prior] == no_take;
return before.at == held.at && before.site == held.site ? bc::add_k : bc::count;
}
#! The relation each comparison going to a label tests, by its place from
#! `jump_eq_k` on: `==`, `!=`, `<` signed and unsigned, `<=`, `>`, and `>=`,
#! of which those of two words are the first six, as `>` and `>=` are `<` and
#! `<=` with the words the other way round. The comparisons of the code are in
#! the same order from `op::eq`. The relation holding of the operands the other
#! way round, of each:
const relation_mirrored: u8[10] = [0, 1, 6, 7, 8, 9, 2, 3, 4, 5];
#! The relation holding where each does not.
const relation_negated: u8[10] = [1, 0, 8, 9, 6, 7, 4, 5, 2, 3];
#! Adds an instruction going to a label where a branch's condition is as
#! asked, but for the label, which follows: a jump on the word of the
#! condition, or the comparison made part of the branch, of two words or of a
#! word and a constant, as a jump on the word where the constant is zero and
#! the relation holds where the word is zero, or where it is not.
#! @param this The assembler.
#! @param body The code.
#! @param index The branch.
#! @param holds Whether it goes where the condition holds, or where it does not.
def assembler::put_test(&mut this, body: &code, index: u32, holds: bool): void {
val cond := body.arg(index, 0);
val from: origin = body.origins[cond];
if from.param || this.folds[from.from] != index {
this.emit1(holds ? bc::jump_if : bc::jump_zero, this.slots[cond]);
return;
}
val compare: u32 = from.from;
val at := this.takes[compare];
var relation := (body.insts[compare].kind as u32 - op::eq as u32) as u64;
if at == 0 {
relation = relation_mirrored[relation] as u64;
}
if !holds {
relation = relation_negated[relation] as u64;
}
if at == no_take {
var a := this.arg(body, compare, 0);
var b := this.arg(body, compare, 1);
if relation >= 6 {
relation = relation_mirrored[relation] as u64;
val first := a;
a = b;
b = first;
}
this.emit3((bc::jump_eq as u64 + relation) as bc, a, b);
return;
}
val word := this.arg(body, compare, 1 - at as u32);
val bits := bits_of(body, body.arg(compare, at as u32));
# Of zero, `==` and `<=` unsigned hold where the word is zero, and `!=` and
# `>` unsigned where it is not.
if bits == 0 && (relation == 0 || relation == 5) {
this.emit1(bc::jump_zero, word);
} else if bits == 0 && (relation == 1 || relation == 7) {
this.emit1(bc::jump_if, word);
} else {
this.emit3((bc::jump_eq_k as u64 + relation) as bc, word, (bits & 0xFFFFFFFF) as u32);
}
}
#! Adds a switch: the cases, each to its edge, then the default, and after them
#! the moves of the edges that move what their blocks take.
#! @param this The assembler.
#! @param body The code.
#! @param index The instruction.
def assembler::emit_switch(&mut this, body: &code, index: u32): void {
val held: inst = body.insts[index];
val edges := held.imm as u32;
val cases := edges - 1;
var targets := vector::<u32>::new();
for e in 0..edges {
val edge := held.aux + e as u32;
if this.has_moves(body, edge) {
targets.append(this.new_label());
} else {
targets.append(body.edges[edge].target);
}
}
this.put(bc::switch as u32);
this.put(this.arg(body, index, 0));
this.put(cases);
for e in 0..cases {
val edge := held.aux + e as u32;
val case: u64 = body.edges[edge].case;
this.put((case & 0xFFFFFFFF) as u32);
this.put((case >> 32) as u32);
this.put_label(targets[e]);
}
this.put_label(targets[cases]);
for e in 0..edges {
val edge := held.aux + e as u32;
continue if !this.has_moves(body, edge);
this.labels[targets[e]] = this.out.length as u32;
val moved := this.moves(body, edge);
this.put_jump(body.edges[edge].target, moved ? bc::move : bc::count);
}
}
#! Whether an edge moves anything into the words of what its block takes.
#! @param this The assembler.
#! @param body The code.
#! @param edge The edge.
#! @returns Whether it does.
def assembler::has_moves(&this, body: &code, edge: u32): bool {
val target: u32 = body.edges[edge].target;
val params := &body.blocks[target].params;
for i in 0..body.edges[edge].args.length {
continue if i >= params.length;
if this.slots[params[i]] != this.slots[body.edges[edge].args[i]] {
return true;
}
}
return false;
}
#! Adds the moves of an edge into the words of what its block takes, all as if
#! at once, each left waiting moving up in its place: a move whose word another
#! still reads waits for that one, and moves going round in a cycle save one
#! word first.
#! @param this The assembler.
#! @param body The code.
#! @param edge The edge.
#! @returns Whether it added any, the last of which is the code made last.
def assembler::moves(&mut this, body: &code, edge: u32): bool {
val target: u32 = body.edges[edge].target;
var pending := vector::<word_move>::new();
for i in 0..body.edges[edge].args.length {
break if i >= body.blocks[target].params.length;
val to := this.slots[body.blocks[target].params[i]];
val from := this.slots[body.edges[edge].args[i]];
continue if to == from;
pending.append(word_move { to = to, from = from });
}
val any := pending.length != 0;
make_moves::<word_move, assembler>(&mut pending, this, false);
return any;
}
#! A move of the machine's code: a word of the frame written with another.
struct word_move {
var to: u32; #! The word written.
var from: u32; #! The word read.
}
#! Whether a move reads the word another writes.
#! @param this The assembler.
#! @param reader The move that may read it.
#! @param writer The move writing it.
#! @returns Whether it does.
def assembler::move_reads(&this, reader: &word_move, writer: &word_move): bool {
return reader.from == writer.to;
}
#! Adds a move.
#! @param this The assembler.
#! @param made The move.
def assembler::move_one(&mut this, made: &word_move): void {
this.emit3(bc::move, made.to, made.from);
}
#! The move saving what a move would write over, which a cycle of moves still
#! reads, in the word no value is held in.
#! @param this The assembler.
#! @param written The move.
#! @param pending The moves waiting.
#! @returns The move saving it.
def assembler::move_saving(&mut this, written: &word_move, pending: span<word_move>): word_move {
return word_move { to = this.scratch, from = written.to };
}
#! Has a move read what another saved from where it was saved.
#! @param this The assembler.
#! @param reader The move.
#! @param saved The move saving what it reads.
def assembler::move_reread(&this, reader: &mut word_move, saved: &word_move): void {
reader.from = saved.to;
}
#! How many words an instruction of the code takes, its operation included.
#! @param code The code.
#! @param pc Where the instruction begins.
#! @returns How many: 1 for what is no operation.
pub def bc_width(code: span<u32>, pc: u64): u64 {
val kind := code[pc];
return 1 if kind >= bc::count as u32;
val fixed := bc_widths[kind as u64];
return match kind {
bc::call as u32, bc::call_trait as u32, bc::call_value as u32, bc::call_c as u32 => fixed + call_counts(code, pc + fixed - 2),
bc::format_value as u32 => fixed + code[pc + 2] as u64,
bc::switch as u32 => fixed + 3 * code[pc + 2] as u64,
bc::ret as u32 => fixed + code[pc + 1] as u64,
else => fixed
};
}
#! How many operands and results a call has.
#! @param code The code.
#! @param at Where the count of its operands is.
#! @returns How many.
def call_counts(code: span<u32>, at: u64): u64 {
val argc := code[at] as u64;
val resc := code[at + 1 + argc] as u64;
return argc + resc;
}
#! The name of each operation of the machine's code, as it is printed.
const bc_names: strview[bc::count as u64] = [
"konst", "move",
"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_i8", "load_u8", "load_i16", "load_u16", "load_i32", "load_u32", "load_i64", "load_f32",
"store_8", "store_16", "store_32", "store_64", "store_f32",
"copy", "clear", "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",
"jump", "jump_if", "jump_zero", "switch", "ret", "ret_memory", "trap", "trap_word", "unreachable",
"ready", "reach", "same",
"atomic", "start",
"add_k", "mul_k", "band_k", "shl_k", "shrs_k", "shru_k",
"store_k8", "store_k16", "store_k32", "store_k64",
"jump_eq", "jump_ne", "jump_lts", "jump_ltu", "jump_les", "jump_leu",
"jump_eq_k", "jump_ne_k", "jump_lts_k", "jump_ltu_k", "jump_les_k", "jump_leu_k",
"jump_gts_k", "jump_gtu_k", "jump_ges_k", "jump_geu_k",
"check_ltu", "check_ltu_k",
"load_u8_x", "store_8_x",
"move_jump", "add_k_jump",
"fadd_f32", "fsub_f32", "fmul_f32", "fdiv_f32",
"forget", "watch_read", "watch_write",
];
#! Writes a function's code for the machine, one instruction a line, each its
#! place, its operation, and its operand words.
#! @param this The code.
#! @returns The text.
pub def bytecode::print(&this): string {
var out := string::new(nothing {});
out.append($"frame {this.frame}, cells from {this.cells}\n");
val code := this.code.span;
var pc: u64 = 0;
while pc < code.length {
val kind := code[pc];
val width := bc_width(code, pc);
out.append($"{pc}: ");
out.append(kind < bc::count as u32 ? bc_names[kind as u64] : "?");
for i in 1..width {
break if pc + i >= code.length;
out.append($" {code[pc + i]}");
}
out.append("\n");
pc += width;
}
return out;
}