Files
sakurac/compiler/intermediate/verifier.sakura
T

383 lines
13 KiB
Plaintext
Raw Normal View History

2026-10-26 10:14:11 -05:00
#! @file verifier.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the verifier, which checks that code is well formed: each block
#! ends in exactly one instruction ending it, each value is defined before
#! every use, in a block dominating the use, each edge gives the block it goes
#! to an argument of the right type for each parameter, and each instruction
#! takes operands of the types its operation does. The tests run it on what
#! lowering makes and after every pass.
module sakura::compiler;
#! What verifying code found wrong.
pub struct verdict {
var problems: vector<string>; #! Each problem, said in words.
}
#! Whether verifying found nothing wrong.
#! @param this The verdict.
#! @returns Whether it did.
pub def verdict::ok(&this): bool {
return this.problems.length == 0;
}
#! Verifies the code.
#! @param this The code.
#! @returns What is wrong with it, which is nothing where it is well formed.
pub def code::verify(&this): verdict {
var made := verdict { problems = vector::<string>::new() };
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.reverse_postorder(&mut order, &mut number);
var idom := this.dominators(order.view(), number.view());
this.check_kept_order(order.view(), idom.view(), &mut made.problems);
# Where each instruction is in its block, so a use within one is after the
# value it uses.
var place := vector::<u32>::new(scratch());
place.resize(this.insts.length);
for b in 0..this.blocks.length {
continue if this.blocks[b].gone;
var walk := this.walk(b as u32);
var index: u32 = 1;
while walk.more() {
place[walk.next()] = index;
index++;
}
}
for b in 0..this.blocks.length {
continue if this.blocks[b].gone;
if b != 0 && number[b] == 0xFFFFFFFF {
made.problems.append($"b{b} is not reached from the entry, but is not removed.");
}
if b == 0 && this.blocks[b].preds.length != 0 {
made.problems.append("The entry has edges into it.");
}
if this.blocks[b].first == 0 {
made.problems.append($"b{b} is empty.");
continue;
}
var walk := this.walk(b as u32);
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
if held.block != b as u32 {
made.problems.append($"Instruction {at} is in b{b} but says it is in b{held.block}.");
}
if held.kind.ends() && held.next != 0 {
made.problems.append($"b{b} goes on past `{held.kind.name()}`, which ends it.");
}
if !held.kind.ends() && held.next == 0 {
made.problems.append($"b{b} does not end with what ends a block.");
}
for i in 0..held.argc {
val value := this.arg(at, i as u32);
this.verify_use(value, b as u32, place[at], &idom, &place, &mut made, held.kind.name());
}
this.verify_types(at, &mut made);
if held.kind.ends() {
this.verify_edges(at, &idom, &place, &mut made);
}
}
}
return made;
}
#! Checks that a value is defined where it is used: before the use in the same
#! block, or in a block dominating the block of the use.
#! @param this The code.
#! @param value The value used.
#! @param block The block of the use.
#! @param index Where in the block the use is, past every instruction for an
#! edge's argument.
#! @param idom The immediate dominator of each block.
#! @param place Where each instruction is in its block.
#! @param made Where problems are noted.
#! @param what What uses it, for the note.
def code::verify_use(
&this,
value: u32,
block: u32,
index: u32,
idom: &vector<u32>,
place: &vector<u32>,
made: &mut verdict,
what: strview
): void {
if value == 0 || value as u64 >= this.origins.length {
made.problems.append($"b{block}: `{what}` uses value {value}, which is none.");
return;
}
val held: origin = this.origins[value];
val home := this.home_of(value);
if this.blocks[home].gone {
made.problems.append($"b{block}: `{what}` uses v{value}, of b{home}, which is removed.");
return;
}
if held.param && this.blocks[home].params.length <= held.index as u64 {
made.problems.append($"b{block}: `{what}` uses v{value}, a parameter b{home} no longer takes.");
return;
}
if home == block {
if !held.param && place[held.from] >= index {
made.problems.append($"b{block}: `{what}` uses v{value} before it is defined.");
}
return;
}
if !dominates(idom, home, block) {
made.problems.append($"b{block}: `{what}` uses v{value}, defined in b{home}, which does not dominate it.");
}
}
#! Checks that an instruction ending a block gives each block it goes to an
#! argument of the right type for each of its parameters.
#! @param this The code.
#! @param index The instruction.
#! @param idom The immediate dominator of each block.
#! @param place Where each instruction is in its block.
#! @param made Where problems are noted.
def code::verify_edges(&this, index: u32, idom: &vector<u32>, place: &vector<u32>, made: &mut verdict): void {
val held: inst = this.insts[index];
var outs := this.edges_of(index);
while outs.more() {
val edge := outs.next();
val target: u32 = this.edges[edge].target;
val args := this.edges[edge].args.length;
val params := this.blocks[target].params.length;
if args != params {
made.problems.append($"b{held.block}: an edge into b{target} gives {args} arguments for {params} parameters.");
continue;
}
for i in 0..args {
val given: u32 = this.edges[edge].args[i];
this.verify_use(given, held.block, 0xFFFFFFFF, idom, place, made, "an edge");
val want := this.type_of(this.blocks[target].params[i]);
if given != 0 && (given as u64) < this.origins.length && this.type_of(given) != want {
made.problems.append($"b{held.block}: an edge gives parameter {i} of b{target} a value of another type.");
}
}
}
}
#! Checks that an instruction takes operands of the types its operation does.
#! @param this The code.
#! @param index The instruction.
#! @param made Where problems are noted.
def code::verify_types(&this, index: u32, made: &mut verdict): void {
val held: inst = this.insts[index];
val name := held.kind.name();
var wants := vector::<vt>::new(scratch());
var exact := true;
match held.kind {
op::add, op::sub, op::mul, op::divs, op::divu, op::rems, op::remu, op::band, op::bor, op::bxor,
op::shl, op::shrs, op::shru, op::eq, op::ne, op::lts, op::ltu, op::les, op::leu, op::eqsu,
op::ltsu, op::lesu, op::ltus, op::leus, op::copy, op::equal, op::resize, op::format_bytes, op::fault,
op::reach, op::same => {
wants.append(vt::word);
wants.append(vt::word);
}
op::fadd, op::fsub, op::fmul, op::fdiv, op::frem, op::feq, op::fne, op::flt, op::fle => {
wants.append(vt::real);
wants.append(vt::real);
}
op::neg, op::bnot, op::lnot, op::itof, op::utof, op::ones, op::clz, op::ctz, op::bswap, op::wrap, op::load,
op::clear, op::forget, op::allocate, op::release, op::retrait, op::check, op::catch, op::exit, op::branch,
op::switch => wants.append(vt::word);
op::fneg, op::ftoi, op::ftou, op::fsingle, op::fsqrt => wants.append(vt::real);
op::select => {
# A word chosen by a word, between two words or two reals, of the type it
# gives.
val chosen := held.count == 1 ? this.type_of(held.result) : vt::none;
if chosen != vt::word && chosen != vt::real {
made.problems.append($"b{held.block}: `{name}` gives no word or real.");
}
wants.append(vt::word);
wants.append(chosen);
wants.append(chosen);
}
op::store => {
wants.append(vt::word);
val how: access = held.aux as access;
wants.append(how.value_type());
}
op::syscall => {
for _ in 0..7 { wants.append(vt::word); }
}
op::call_trait, op::call_value => {
for _ in 0..2 { wants.append(vt::word); }
exact = false;
}
op::call_c => {
wants.append(vt::word);
exact = false;
}
op::call, op::format_value, op::lanes => exact = false;
op::start => {
for _ in 0..3 { wants.append(vt::word); }
}
op::clone => wants.append(vt::word);
op::atomic => {
# Words: the address but of a fence, its operands, and its orders.
val count: u32 = held.aux == atomic_fence ? 1 : held.aux == atomic_load ? 2 : held.aux == atomic_compare_exchange ? 5 : 3;
for _ in 0..count { wants.append(vt::word); }
}
op::trap => {
# The runtime stops with an error it is given, as a word.
if held.argc != 0 {
wants.append(vt::word);
}
}
op::ret => {
wants.extend(this.results.view());
if this.returned != 0 {
wants.append(vt::word);
}
}
else => {}
}
if exact && held.argc as u64 != wants.length {
made.problems.append($"b{held.block}: `{name}` takes {wants.length} operands, but is given {held.argc}.");
return;
}
if !exact && (held.argc as u64) < wants.length {
made.problems.append($"b{held.block}: `{name}` takes at least {wants.length} operands, but is given {held.argc}.");
return;
}
for i in 0..wants.length {
val given := this.arg(index, i as u32);
continue if given == 0 || given as u64 >= this.origins.length;
if this.type_of(given) != wants[i] {
made.problems.append($"b{held.block}: operand {i} of `{name}` is v{given}, of another type than it takes.");
}
}
}
#! Orders the blocks the entry reaches so each comes before those it goes to,
#! but along edges going back, and numbers each by its place in that order.
#! @param this The code.
#! @param order Where the blocks are written, in that order.
#! @param number Where each block's place is written, by its index, or
#! `0xFFFFFFFF` for one the entry does not reach.
pub def code::reverse_postorder(&this, order: &mut vector<u32>, number: &mut vector<u32>): void {
# Each block's number marks it seen, from where it is put on the walk, and is
# its place once the walk is done.
number.clear();
number.resize(this.blocks.length, 0xFFFFFFFF);
order.clear();
# Each block on the walk with the next of its edges to follow, as
# `pair_key(block, next)`; the blocks are written as each is left, which is
# postorder, then turned round.
var stack := vector::<u64>::new(scratch());
stack.append(pair_key(0, 0));
number[0] = 0;
while stack.length != 0 {
# The top is written before a block is pushed, which may move it.
val top := &mut stack.last();
val block := pair_high(top);
val next := pair_low(top);
val last: u32 = this.blocks[block].last;
val count := last == 0 ? 0 : this.edge_count(last);
if next >= count {
order.append(block);
stack.truncate();
continue;
}
top = pair_key(block, next + 1);
val target: u32 = this.edges[this.insts[last].aux + next].target;
if number[target] == 0xFFFFFFFF {
number[target] = 0;
stack.append(pair_key(target, 0));
}
}
val length := order.length;
for i in 0..length / 2 {
val other := length - 1 - i;
val held: u32 = order[i];
order[i] = order[other];
order[other] = held;
}
for i in 0..length {
number[order[i]] = i as u32;
}
}
#! The immediate dominator of each block the entry reaches, as Cooper, Harvey,
#! and Kennedy's "A Simple, Fast Dominance Algorithm" finds them.
#! @param this The code.
#! @param order The blocks in reverse postorder.
#! @param number Each block's place in that order.
#! @returns The immediate dominator of each block, by its index: the entry's is
#! itself, and that of a block not reached `no_block`.
pub def code::dominators(&this, order: span<u32>, number: span<u32>): vector<u32> {
var idom := vector::<u32>::new(scratch());
idom.resize(this.blocks.length, no_block);
return idom if order.length == 0;
idom[0] = 0;
var changed := true;
while changed {
changed = false;
for i in 1..order.length {
val block := order[i];
var chosen := no_block;
for &edge in this.blocks[block].preds {
val pred := this.edge_source(edge);
continue if idom[pred] == no_block;
chosen = chosen == no_block ? pred : intersect(&idom, number, pred, chosen);
}
if chosen != no_block && idom[block] != chosen {
idom[block] = chosen;
changed = true;
}
}
}
return idom;
}
#! The nearest block dominating both blocks.
#! @param idom The immediate dominator of each block so far.
#! @param number Each block's place in reverse postorder.
#! @param a One block.
#! @param b The other.
#! @returns The block.
def intersect(idom: &vector<u32>, number: span<u32>, a: u32, b: u32): u32 {
var x := a;
var y := b;
while x != y {
while number[x] > number[y] {
x = idom[x];
}
while number[y] > number[x] {
y = idom[y];
}
}
return x;
}
#! Whether a block dominates another: every path from the entry to the other
#! goes through it.
#! @param idom The immediate dominator of each block.
#! @param a The block that may dominate.
#! @param b The block it may dominate.
#! @returns Whether it does.
pub def dominates(idom: &vector<u32>, a: u32, b: u32): bool {
var at := b;
var steps := 0;
while at != a && steps < 1000000 {
return false if at == 0 || at == no_block;
at = idom[at];
steps++;
}
return at == a;
}