Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-12-06 13:52:57 -06:00
commit 528ccf1523
782 files changed
+145156

No files matched your search

+510
View File
@@ -0,0 +1,510 @@
#! @file compiler.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of lowering: small programs are checked and lowered, and
#! the code of their functions printed and compared with what is expected,
#! after the verifier has found nothing wrong with any of it.
import std::io;
import std::testing;
import sakura::analyzer;
module sakura::compiler;
#! Checks the files as one program, lowers every function of it, and gives the
#! code of those named, printed one after another, or what went wrong.
#! @param names The names of the functions, separated by spaces.
#! @param texts The files' texts.
#! @returns The code.
def lowered(names: strview, texts: strview...): string {
var held := names::new();
var notes := vector::<note>::new();
var sources := vector::<source>::new();
var syntaxes := vector::<syntax>::new();
var roots := vector::<u32>::new();
sources.reserve(texts.length);
syntaxes.reserve(texts.length);
for i in 0..texts.length {
sources.append(source::from(i == 0 ? "test.sakura" : "other.sakura", texts.at(i)));
syntaxes.append(syntax::new());
}
for i in 0..texts.length {
var lexing := lexer::new(sources.at(i), &mut held, &mut notes, i as u32);
lexing.tokenize_all(syntaxes.at(i));
var parsing := parser::new(syntaxes.at(i), &held, &mut notes, i as u32);
roots.append(parsing.parse());
}
var checker := checker::new(&mut held, &mut notes);
for i in 0..texts.length {
checker.add(sources.at(i), syntaxes.at(i), roots.at(i));
}
checker.check();
var out := string::new(nothing {});
if notes.length != 0 {
out.append("the program does not check");
return out;
}
var lowering := lowerer::new(&mut checker, lowering { verify = true, everything = true });
lowering.compile();
for &each in lowering.problems {
out.append(each.span);
out.append("\n");
}
var wanted := string::from(names, nothing {});
for name in wanted.split(' ') {
for &function in lowering.program.functions {
if function.name.span == name {
var text := function.body.print();
out.append(text.span);
}
}
}
return out;
}
#! Whether code printed is what is expected, but for the line breaks ending
#! them, printing what it is where it is not.
#! @param got The code printed.
#! @param want The code expected.
#! @returns Whether it is.
def lowers_as(got: &string, want: strview): bool {
var x := got.length;
var y := want.length;
while x > 0 && got.at(x - 1) == '\n' { x--; }
while y > 0 && want.at(y - 1) == '\n' { y--; }
val same := got.substr(0, x) == want.substr(0, y);
if !same {
println(got);
}
return same;
}
@test def arithmetic_narrows_to_its_type(t: &mut tester): void {
# Arithmetic on words wraps at 64 bits, so a result narrower than a word is
# narrowed again, and an `f32` is rounded to its precision.
val got := lowered("add neg mix", """
def add(a: u8, b: u8): u8 { return a + b; }
def neg(a: i16): i16 { return -a; }
def mix(a: i32, b: f32): f32 { return a as f32 * b; }
def clamp(a: i64): i64 { return a < 0 ? 0 : a; }
def both(a: bool, b: bool): bool { return a && !b; }
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = add v0, v1
v3 = wrap v2, 8, unsigned
ret v3
b0(v0: i64):
v1 = neg v0
v2 = wrap v1, 16, signed
ret v2
b0(v0: i64, v1: f64):
v2 = itof v0
v3 = fsingle v2
v4 = fmul v3, v1
v5 = fsingle v4
ret v5
"""));
}
@test def and_or_branch_rather_than_compute(t: &mut tester): void {
# `&&` goes to its right only where its left holds, and `!` swaps where a
# condition goes rather than computing a value.
val got := lowered("both", """
def add(a: u8, b: u8): u8 { return a + b; }
def neg(a: i16): i16 { return -a; }
def mix(a: i32, b: f32): f32 { return a as f32 * b; }
def clamp(a: i64): i64 { return a < 0 ? 0 : a; }
def both(a: bool, b: bool): bool { return a && !b; }
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
branch v0, b1, b3
b1:
branch v1, b3, b2
b2:
v2 = iconst 1
jump b4(v2)
b3:
v3 = iconst 0
jump b4(v3)
b4(v4: i64):
ret v4
"""));
}
@test def structs_live_in_cells_and_return_by_address(t: &mut tester): void {
# A struct is built in a cell, what its fields given do not write cleared
# and its default given; a local referred to where the reference cannot be
# kept is held in a cell, and a struct returned in memory is written where
# the call says.
val got := lowered("make main", """
struct pair { var a: i64; var b: i32 = 7; }
def sum(p: pair): i64 { return p.a + p.b as i64; }
def make(): pair { return pair { a = 1 }; }
def bump(x: &mut i64): void { x = x + 1; }
def main(): void {
var n: i64 = 1;
bump(&mut n);
val p := make();
sum(p);
}
""");
t.expects(lowers_as(&got, """
c0: 16, 8
b0:
v0 = cell c0
v1 = iconst 0
store.i64 v0+8, v1
v2 = iconst 1
store.i64 v0, v2
v3 = iconst 7
store.i32 v0+8, v3
ret v0
c0: 8, 8
c1: 16, 8
c2: 16, 8
b0:
v0 = cell c0
v1 = iconst 1
store.i64 v0, v1
call f4(v0)
v2 = cell c1
v3 = cell c2
call f3(v3)
copy v2, v3, 16
v4 = cell c2
copy v4, v2, 16
v5 = call f2(v4)
ret
"""));
}
@test def tests_and_matches_read_the_tag(t: &mut tester): void {
# A union's tag says which field it holds, which a test names and a match
# goes by; a match used as a value without `else` traps where none holds.
val got := lowered("size", """
union shape { var circle: f64; var square: i64; }
def size(s: &shape): i64 {
if s is square(w) {
return w;
}
return match s {
circle(r) => r as i64,
square(w) => w
};
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64):
v1 = iconst 0
v2 = load.i64 v0
v3 = iconst 1
v4 = eq v2, v3
branch v4, b1, b2(v1)
b1:
v5 = load.i64 v0+8
jump b2(v5)
b2(v6: i64):
branch v4, b9, b3
b3:
v7 = load.i64 v0
v8 = iconst 0
v9 = eq v7, v8
branch v9, b7, b4
b4:
v10 = load.i64 v0
v11 = iconst 1
v12 = eq v10, v11
branch v12, b6, b5
b5:
trap not_member
b6:
v13 = load.i64 v0+8
jump b8(v13)
b7:
v14 = load.f64 v0+8
v15 = ftoi v14
jump b8(v15)
b8(v16: i64):
ret v16
b9:
ret v6
"""));
}
@test def traits_dispatch_through_vtables_and_closures_capture_where_they_can_be_reached(t: &mut tester): void {
# A call through a trait reference goes through its vtable, and a reference to
# a value becomes one to a trait by its vtable, the value known while compiling
# held where the statement holds it. A local an anonymous function captures is
# held where its environment refers to it, both cells of the frame.
val got := lowered("call main <lambda>", """
trait named { def name(&this): i64; }
struct one : named { var n: i64; }
def one::name(&this): i64 { return this.n; }
def call(x: &named): i64 { return x.name(); }
def main(): void {
val o := one { n = 3 };
call(&o);
var k: i64 = 5;
val f := def(x: i64): i64 { return x + k; };
f(1);
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = call_trait s2[0](v0, v1)
ret v2
c0: 8, 8
c1: 8, 8
c2: 8, 8
c3: 8, 8
b0:
v0 = cell c0
v1 = cell c1
v2 = iconst 3
store.i64 v1, v2
copy v0, v1, 8
v3 = iconst 0
v4 = call f3(v0, v3)
v5 = cell c2
v6 = iconst 5
store.i64 v5, v6
v7 = iconst 5
v8 = cell c3
store.i64 v8, v5
v9 = iconst 1
v10 = call_value s3(v7, v8, v9)
ret
b0(v0: i64, v1: i64):
v2 = load.i64 v1
v3 = load.i64 v2
v4 = add v0, v3
ret v4
"""));
}
# What a walk of the escape tests walks.
struct escape_body {
var n: i64; # Its number.
}
# A walk holding a reference to what it walks.
struct escape_walk {
var of: &escape_body; # What it walks.
}
# A walk of a body, which holds a reference to it.
def escape_body::walk(&this): escape_walk {
return escape_walk { of = this };
}
# The number a walk of a body local to the frame reads.
def escape_walked(n: i64): i64 {
var made := escape_body { n = n };
val walk := made.walk();
return walk.of.n;
}
# Gives each element of a vector to a function.
def escape_each_of(xs: &vector<i64>, f: def(&i64): void): void {
for &x in xs {
f(x);
}
}
# The sum of a vector's elements, through a closure writing a local of the frame.
def escape_sum_of(xs: &vector<i64>): i64 {
var total: i64 = 0;
escape_each_of(xs, def(x: &i64): void { total += x; });
return total;
}
@test def references_and_closures_refer_to_what_their_frames_hold(t: &mut tester): void {
# A walk and a closure refer to what the frame making them holds, where it is,
# so each sees it changed, and those made in a function read and write its
# frame while it runs.
var held := escape_body { n = 4 };
val a := held.walk();
var k: i64 = 5;
val f := def(): i64 { return k; };
held.n = 11;
k = 9;
var xs := vector::<i64>::new();
xs.append(1);
xs.append(2);
xs.append(3);
t.expects(a.of.n == 11 && escape_walked(7) == 7 && f() == 9 && escape_sum_of(&xs) == 6);
}
@test def a_value_called_through_invoke_is_referred_to_where_it_is(t: &mut tester): void {
# A value called as `a(2)` is the `this` of its `invoke`, which cannot keep it,
# so it stays in a cell of the frame as it does for `a.invoke(2)`, and a
# function calling a parameter so keeps nothing of it.
val got := lowered("main apply", """
struct adder { var total: i64; }
def adder::invoke(&mut this, by: i64): i64 { this.total += by; return this.total; }
def apply(f: &mut adder): i64 { return f(1); }
def main(): void {
var a := adder { total = 0 };
a(2);
apply(&mut a);
}
""");
val text := got.span;
var boxed := false;
for i in 0..text.length {
boxed = boxed || text.substr(i, 3) == "box";
}
t.expects(text.substr(0, 4) == "c0: " && !boxed);
}
@test def values_made_down_one_branch_close_where_made(t: &mut tester): void {
# What a statement makes that closes is closed where it ends, where it was made,
# and a local where its scope ends.
val got := lowered("pick hold", """
import std;
struct handle : owning { var n: i64; }
def handle::close(&mut this): void { this.n = 0; }
def make(): handle { return handle { n = 1 }; }
def peek(h: &handle): i64 { return h.n; }
def pick(c: bool): i64 { return c ? peek(&make()) : 0; }
def hold(): void {
val h := make();
peek(&h);
}
""", """
module std; module core;
pub trait owning { def close(&mut this): void; }
""");
t.expects(lowers_as(&got, """
c0: 8, 8
b0(v0: i64):
v1 = iconst 0
branch v0, b2, b1
b1:
v2 = iconst 0
jump b3(v2, v1)
b2:
v3 = cell c0
call f2(v3)
v4 = iconst 1
v5 = call f3(v3)
jump b3(v5, v4)
b3(v6: i64, v7: i64):
branch v7, b4, b5
b4:
v8 = cell c0
call f1(v8)
v9 = iconst 0
jump b5
b5:
ret v6
c0: 8, 8
c1: 8, 8
b0:
v0 = cell c0
v1 = cell c1
call f2(v1)
v2 = iconst 1
copy v0, v1, 8
v3 = call f3(v0)
call f1(v0)
ret
"""));
}
@test def loops_lower_with_their_variables_at_their_heads(t: &mut tester): void {
# Variables a loop changes arrive at its head as parameters, and a loop over a
# fixed array walks its elements by address.
val got := lowered("steps total", """
def steps(start: u64): u64 {
var n := start;
var count: u64 = 0;
while n != 1 {
if n % 2 == 0 { n = n / 2; } else { n = 3 * n + 1; }
count += 1;
}
return count;
}
def total(xs: &i64[4]): i64 {
var sum: i64 = 0;
for x in xs {
sum += x;
}
return sum;
}
def first_even(xs: &i64[4]): i64 {
for i in 0..4 {
if xs[i] % 2 == 0 { return xs[i]; }
if xs[i] < 0 { break; }
}
return -1;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64):
v1 = iconst 0
jump b1(v0, v1)
b1(v2: i64, v3: i64):
v4 = iconst 1
v5 = ne v2, v4
branch v5, b3, b2
b2:
ret v3
b3:
v6 = iconst 2
v7 = remu v2, v6
v8 = iconst 0
v9 = eq v7, v8
branch v9, b5, b4
b4:
v10 = iconst 3
v11 = mul v10, v2
v12 = iconst 1
v13 = add v11, v12
jump b6(v13)
b5:
v14 = iconst 2
v15 = divu v2, v14
jump b6(v15)
b6(v16: i64):
v17 = iconst 1
v18 = add v3, v17
jump b7
b7:
jump b1(v16, v18)
b0(v0: i64):
v1 = iconst 0
v2 = iconst 4
v3 = iconst 0
jump b1(v3, v1)
b1(v4: i64, v5: i64):
v6 = ltu v4, v2
branch v6, b3, b2
b2:
ret v5
b3:
v7 = iconst 8
v8 = mul v4, v7
v9 = add v0, v8
v10 = load.i64 v9
v11 = add v5, v10
jump b4
b4:
v12 = iconst 1
v13 = add v4, v12
jump b1(v13, v11)
"""));
}
+298
View File
@@ -0,0 +1,298 @@
#! @file intermediate.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of the intermediate code: building it with variables,
#! which become the parameters of blocks where control flow joins, taking out
#! what stands for one value, verifying it, printing it, and walking it, and
#! the lists of indices its blocks and edges hold.
import std::io;
import std::testing;
module sakura::compiler;
#! Whether two texts are the same but for the line breaks ending them, which
#! printed code ends with and a block of text does not.
#! @param a One text.
#! @param b The other.
#! @returns Whether they are.
def same_text(a: strview, b: strview): bool {
var x := a.length;
var y := b.length;
while x > 0 && a.at(x - 1) == '\n' { x--; }
while y > 0 && b.at(y - 1) == '\n' { y--; }
val same := a.substr(0, x) == b.substr(0, y);
if !same {
println(a);
}
return same;
}
#! Builds the loop of `steps`, which counts the steps of the Collatz sequence:
#!
#! ```
#! def steps(start: u64): u64 {
#! var n := start;
#! var count: u64 = 0;
#! while n != 1 {
#! if n % 2 == 0 { n = n / 2; } else { n = 3 * n + 1; }
#! count += 1;
#! }
#! return count;
#! }
#! ```
#! @returns Its code.
def build_steps(): code {
var params: vt[1] = [vt::word];
var made := builder::new(params[0:1]);
val n := made.variable(vt::word);
val count := made.variable(vt::word);
made.assign(n, made.param(0));
made.assign(count, made.word(0));
val head := made.new_block();
val body := made.new_block();
val exit := made.new_block();
made.jump(head);
made.switch_to(head);
val done := made.binary(op::ne, made.read(n), made.word(1));
made.branch(done, body, exit);
made.seal(body);
made.seal(exit);
made.switch_to(body);
val even := made.binary(op::eq, made.binary(op::remu, made.read(n), made.word(2)), made.word(0));
val half := made.new_block();
val odd := made.new_block();
val next := made.new_block();
made.branch(even, half, odd);
made.seal(half);
made.seal(odd);
made.switch_to(half);
made.assign(n, made.binary(op::divu, made.read(n), made.word(2)));
made.jump(next);
made.switch_to(odd);
made.assign(n, made.binary(op::add, made.binary(op::mul, made.word(3), made.read(n)), made.word(1)));
made.jump(next);
made.seal(next);
made.switch_to(next);
made.assign(count, made.binary(op::add, made.read(count), made.word(1)));
made.jump(head);
made.seal(head);
made.switch_to(exit);
var result: u32[1] = [made.read(count)];
made.ret(result[0:1]);
return made.finish();
}
@test def loops_take_their_variables_as_parameters(t: &mut tester): void {
var made := build_steps();
made.results.append(vt::word);
val verdict := made.verify();
t.expects(verdict.ok());
for &each in verdict.problems {
println(each);
}
val printed := made.print();
val want := """
b0(v0: i64):
v1 = iconst 0
jump b1(v0, v1)
b1(v2: i64, v3: i64):
v4 = iconst 1
v5 = ne v2, v4
branch v5, b3, b2
b2:
ret v3
b3:
v6 = iconst 2
v7 = remu v2, v6
v8 = iconst 0
v9 = eq v7, v8
branch v9, b5, b4
b4:
v10 = iconst 3
v11 = mul v10, v2
v12 = iconst 1
v13 = add v11, v12
jump b6(v13)
b5:
v14 = iconst 2
v15 = divu v2, v14
jump b6(v15)
b6(v16: i64):
v17 = iconst 1
v18 = add v3, v17
jump b1(v16, v18)
""";
t.expects(same_text(printed.span, want));
}
@test def parameters_standing_for_one_value_are_taken_out(t: &mut tester): void {
# `x` is given before the branch, and neither side changes it, so the join
# takes nothing.
var params: vt[1] = [vt::word];
var made := builder::new(params[0:1]);
val x := made.variable(vt::word);
made.assign(x, made.param(0));
val then := made.new_block();
val other := made.new_block();
val join := made.new_block();
made.branch(made.param(0), then, other);
made.seal(then);
made.seal(other);
made.switch_to(then);
made.jump(join);
made.switch_to(other);
made.jump(join);
made.seal(join);
made.switch_to(join);
var result: u32[1] = [made.read(x)];
made.ret(result[0:1]);
var code := made.finish();
code.results.append(vt::word);
t.expects(code.verify().ok());
t.expects(same_text(code.print().span, """
b0(v0: i64):
branch v0, b2, b1
b1:
jump b3
b2:
jump b3
b3:
ret v0
"""));
}
@test def what_nothing_reaches_is_taken_out(t: &mut tester): void {
var made := builder::new(span::<vt>::blank());
var none: u32[1] = [0];
made.ret(none[0:0]);
# Code after a `return` goes in a block nothing reaches.
made.word(5);
made.ret(none[0:0]);
var code := made.finish();
t.expects(code.verify().ok());
t.expects(same_text(code.print().span, "b0:\n ret"));
}
@test def the_verifier_finds_uses_not_dominated(t: &mut tester): void {
var params: vt[1] = [vt::word];
var made := builder::new(params[0:1]);
val then := made.new_block();
val other := made.new_block();
val join := made.new_block();
made.branch(made.param(0), then, other);
made.seal(then);
made.seal(other);
made.switch_to(then);
val only_here := made.word(1);
made.jump(join);
made.switch_to(other);
made.jump(join);
made.seal(join);
made.switch_to(join);
var result: u32[1] = [only_here];
made.ret(result[0:1]);
var code := made.finish();
code.results.append(vt::word);
val verdict := code.verify();
t.expects(!verdict.ok());
}
@test def lists_of_indices_hold_four_themselves_and_more_in_memory(t: &mut tester): void {
var list := ids {};
for i in 0..4u {
list.append(i as u32 * 3);
}
t.expects(list.length == 4 && list.at(3) == 9);
# Past four the indices move to memory of the list's own, and stay in order.
for i in 4..100u {
list.append(i as u32 * 3);
}
var total: u64 = 0;
for &each in list {
total += each as u64;
}
t.expects(list.length == 100 && list.at(0) == 0 && list.at(99) == 297 && total == 14850);
list.at(5) = 1;
var other := list.copied(nothing {});
t.expects(other.at(5) == 1 && other.length == 100);
var same := ids {};
for &each in other {
same.append(each);
}
t.expects(same.same(&list));
same.clear();
t.expects(same.length == 0 && !same.same(&list));
}
@test def walks_give_each_instruction_and_what_each_reads(t: &mut tester): void {
var made := build_steps();
# Every instruction of the blocks not removed, each once.
var count: u32 = 0;
var all := made.walk_all();
while all.more() {
all.next();
count++;
}
t.expects(count != 0 && count == made.size());
# The loop's head, block 1, compares and branches.
var found := vector::<u32>::new();
var head := made.walk(1);
while head.more() {
found.append(head.next());
}
t.expects(found.length == 3 && made.insts[found[0]].kind == op::iconst
&& made.insts[found[1]].kind == op::ne && made.insts[found[2]].kind == op::branch);
# The comparison reads its operands, in order.
var operands := made.reads_of(found[1]);
var places: u32 = 0;
while operands.more() {
operands.next();
t.expects(operands.operand() == places);
places++;
}
t.expects(places == 2);
# The branch leaves by two edges, one after another.
var outs := made.edges_of(found[2]);
t.expects(outs.more() && outs.next() == made.insts[found[2]].aux);
t.expects(outs.more() && outs.next() == made.insts[found[2]].aux + 1 && !outs.more());
# The jump back to the head reads only what its edge gives.
val jump: u32 = made.blocks[6].last;
val first: u32 = made.edges[made.insts[jump].aux].args[0];
var given := made.reads_of(jump);
var values := vector::<u32>::new();
while given.more() {
values.append(given.next());
t.expects(given.operand() == no_operand);
}
t.expects(values.length == 2 && values[0] == first);
# A walk reads where each instruction goes on to as it gives it, so taking
# the one given out of its block's order does not end the walk.
var cut: u32 = 0;
var again := made.walk(1);
while again.more() {
made.insts[again.next()].next = 0;
cut++;
}
t.expects(cut == 3);
}
+983
View File
@@ -0,0 +1,983 @@
#! @file optimizer.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of the optimizer: small programs are checked, lowered,
#! and optimized at a level, the verifier running after every pass, and the
#! code of their functions printed and compared with what is expected. Each
#! test shows what one pass does, with the others cleaning up after it. The
#! containers the passes keep track of what they find with are tested too.
import std::io;
import std::testing;
import sakura::analyzer;
module sakura::compiler;
#! Checks the files as one program, lowers and optimizes every function of it
#! at a level, and gives the code of those named, printed one after another,
#! or what went wrong, the verifier's problems among it. At level 0, every named
#! local is kept in a cell of its own, as `-O0` keeps them.
#! @param level How much the code is optimized.
#! @param names The names of the functions, separated by spaces.
#! @param texts The files' texts.
#! @returns The code.
def optimized(level: u32, names: strview, texts: strview...): string {
return optimized_on(1, level, names, ...texts);
}
#! Checks the files as one program, lowers and optimizes every function of it
#! at a level on a number of threads, and gives the code of those named,
#! printed one after another, or what went wrong, as `optimized` does.
#! @param threads How many threads optimize the functions.
#! @param level How much the code is optimized.
#! @param names The names of the functions, separated by spaces.
#! @param texts The files' texts.
#! @returns The code.
def optimized_on(threads: u32, level: u32, names: strview, texts: strview...): string {
var held := names::new();
var notes := vector::<note>::new();
var sources := vector::<source>::new();
var syntaxes := vector::<syntax>::new();
var roots := vector::<u32>::new();
sources.reserve(texts.length);
syntaxes.reserve(texts.length);
for i in 0..texts.length {
sources.append(source::from(i == 0 ? "test.sakura" : "other.sakura", texts.at(i)));
syntaxes.append(syntax::new());
}
for i in 0..texts.length {
var lexing := lexer::new(sources.at(i), &mut held, &mut notes, i as u32);
lexing.tokenize_all(syntaxes.at(i));
var parsing := parser::new(syntaxes.at(i), &held, &mut notes, i as u32);
roots.append(parsing.parse());
}
var checker := checker::new(&mut held, &mut notes);
for i in 0..texts.length {
checker.add(sources.at(i), syntaxes.at(i), roots.at(i));
}
checker.check();
var out := string::new(nothing {});
if notes.length != 0 {
out.append("the program does not check");
return out;
}
var lowering := lowerer::new(&mut checker, lowering { verify = true, everything = true, level = level, keep_locals = level == 0, threads = threads });
lowering.compile();
for &each in lowering.problems {
out.append(each.span);
out.append("\n");
}
var wanted := string::from(names, nothing {});
for name in wanted.split(' ') {
for &function in lowering.program.functions {
if function.name.span == name {
var text := function.body.print();
out.append(text.span);
}
}
}
return out;
}
#! Checks the files as one program, lowers it checked and optimizes it with
#! inlining, and lists the checks left in its functions as
#! `check --checks-report` counts them: for each, the function, the line, the
#! kind, and how many, each followed by a space.
#! @param texts The files' texts.
#! @returns The list, or what went wrong.
def checks_left_in(texts: strview...): string {
var held := names::new();
var notes := vector::<note>::new();
var sources := vector::<source>::new();
var syntaxes := vector::<syntax>::new();
var roots := vector::<u32>::new();
sources.reserve(texts.length);
syntaxes.reserve(texts.length);
for i in 0..texts.length {
sources.append(source::from(i == 0 ? "test.sakura" : "other.sakura", texts.at(i)));
syntaxes.append(syntax::new());
}
for i in 0..texts.length {
var lexing := lexer::new(sources.at(i), &mut held, &mut notes, i as u32);
lexing.tokenize_all(syntaxes.at(i));
var parsing := parser::new(syntaxes.at(i), &held, &mut notes, i as u32);
roots.append(parsing.parse());
}
var checker := checker::new(&mut held, &mut notes);
for i in 0..texts.length {
checker.add(sources.at(i), syntaxes.at(i), roots.at(i));
}
checker.check();
var out := string::new(nothing {});
if notes.length != 0 {
out.append("the program does not check");
return out;
}
var lowering := lowerer::new(&mut checker, lowering { verify = true, everything = true, level = 2 });
lowering.compile();
val kinds: strview[4] = ["index", "field", "member", "fault"];
for &each in lowering.checks_left() {
val line := sources.at(pair_high(each.at) as u64 - 1).lines.place_of(pair_low(each.at)).line;
out.append($"{lowering.program.functions[each.function].name}:{line}:{kinds[each.kind as u64]}:{each.count} ");
}
return out;
}
@test def the_checks_the_optimizer_leaves_are_listed_by_line(t: &mut tester): void {
# A check inlined is listed at the call, and one the code proved before, or
# a loop's own test answers, is not left.
val got := checks_left_in("""
union shape { var round: f64; var square: i64; }
enum color: u8 { red, green, blue }
def pick(xs: &i64[8], i: u64): i64 { return xs[i]; }
def side(s: shape): i64 { return s.square; }
def hue(n: u8): color { return n as color; }
def total(xs: &i64[8]): i64 { var t: i64 = 0; for i in 0..8u { t += xs[i]; } return t; }
def twice(xs: &i64[8], i: u64): i64 {
return pick(xs, i) + pick(xs, i);
}
""");
t.expects(got.span == "pick:3:index:1 side:4:field:1 hue:5:member:1 twice:8:index:1 ");
}
@test def constants_fold_and_powers_of_two_shift(t: &mut tester): void {
# Operators of constants are worked out, and an unsigned division and
# remainder by a power of two become a shift and a mask.
val got := optimized(1, "fold", """
def fold(x: u64): u64 { return x / 8 + x % 16 + 2 * 3; }
""");
t.expects(lowers_as(&got, """
b0(v0: i64):
v1 = iconst 15
v2 = iconst 3
v3 = shru v0, v2
v4 = band v0, v1
v5 = add v3, v4
v6 = iconst 6
v7 = add v5, v6
ret v7
"""));
}
@test def narrowings_of_bits_known_or_never_read_go(t: &mut tester): void {
# Only the low 8 bits of `t` are read, which narrowing to 32 bits never
# changes, so the sum and product are narrowed nowhere; and the mask leaves
# nothing past bit 7, so narrowing what it gives changes nothing either.
val got := optimized(1, "mix", """
def mix(a: i32, b: i32, c: u8): i32 {
val t := (a + b) * 3 + (c as i32);
return (t >> 2) & 0xFF;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64, v2: i64):
v3 = add v0, v1
v4 = iconst 3
v5 = mul v3, v4
v6 = add v5, v2
v7 = iconst 2
v8 = shrs v6, v7
v9 = iconst 255
v10 = band v8, v9
ret v10
"""));
# A byte read is never 300 nor below 0, and a sum of three is narrow enough
# that an `f32` holds it exactly.
val bytes := optimized(1, "wide gray", """
struct pixel { var r: u8; var g: u8; var b: u8; }
def wide(p: &pixel): bool { return (p.r as u32) == 300 || (p.g as i32) < 0; }
def gray(p: &pixel): f32 { return ((p.r as u32 + p.g as u32 + p.b as u32) / 3) as f32; }
""");
t.expects(lowers_as(&bytes, """
b0(v0: i64):
v1 = load.u8 v0
v2 = iconst 0
v3 = load.u8 v0+1
ret v2
b0(v0: i64):
v1 = load.u8 v0
v2 = load.u8 v0+1
v3 = add v1, v2
v4 = load.u8 v0+2
v5 = add v3, v4
v6 = iconst 3
v7 = divu v5, v6
v8 = utof v7
ret v8
"""));
}
@test def constants_are_grouped_and_kept_last(t: &mut tester): void {
# `(i + 1) << 3` is `(i << 3) + 8`, so the elements after `xs[i]` are read
# at offsets from its address; constants applied one after another are
# applied as one; a constant added before a comparison is taken from what
# it is compared with; and a division by 4 is a product with its reciprocal.
val got := optimized(1, "next chain found half", """
def next(xs: *u64, i: u64): u64 { return xs[i] + xs[i + 1] + xs[i + 2]; }
def chain(x: u64): u64 { return ((x * 3) * 5) << 2 << 3; }
def found(x: u64): bool { return x + 1 == 5; }
def half(x: f64): f64 { return x / 4 + x * 1; }
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = iconst 3
check v0, null_reference
v3 = shl v1, v2
v4 = add v0, v3
v5 = load.i64 v4
v6 = load.i64 v4+8
v7 = add v5, v6
v8 = load.i64 v4+16
v9 = add v7, v8
ret v9
b0(v0: i64):
v1 = iconst 5
v2 = iconst 15
v3 = mul v0, v2
v4 = shl v3, v1
ret v4
b0(v0: i64):
v1 = iconst 4
v2 = eq v0, v1
ret v2
b0(v0: f64):
v1 = fconst 0.25
v2 = fmul v0, v1
v3 = fadd v2, v0
ret v3
"""));
}
@test def what_both_ways_work_out_is_worked_out_before_the_branch(t: &mut tester): void {
# Both ways read `p.a * p.b` first, so it is worked out before the branch,
# and where they join it is read rather than worked out again; what is
# left only chooses which sum it adds.
val got := optimized(1, "pick", """
struct pair { var a: f32; var b: f32; }
def pick(p: &pair, flag: bool): f32 {
var r: f32 = 0;
if flag { r = p.a * p.b; } else { r = p.a * p.b + 1; }
return r + p.a * p.b;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = load.f32 v0
v3 = load.f32 v0+4
v4 = fmul v2, v3
v5 = fsingle v4
v6 = fconst 1
v7 = fadd v5, v6
v8 = fsingle v7
v9 = select v1, v5, v8
v10 = fadd v9, v5
v11 = fsingle v10
ret v11
"""));
}
@test def a_read_after_a_write_in_both_ways_is_not_lifted_before_it(t: &mut tester): void {
# Both ways read `a` after writing it, and `a`'s address is given away, so
# neither read may move before the branch, ahead of the writes: each reads
# what its own way wrote.
val got := optimized(1, "arms", """
def touch(p: &mut u64): void { p += 1; }
def arms(flag: bool, x: u64): u64 {
var a: u64 = x;
touch(&mut a);
if flag { a = 5; return a + 1; }
a = 7;
return a + 2;
}
""");
t.expects(lowers_as(&got, """
c0: 8, 8
b0(v0: i64, v1: i64):
v2 = cell c0
store.i64 v2, v1
call f1(v2)
branch v0, b2, b1
b1:
v3 = iconst 7
store.i64 v2, v3
v4 = iconst 9
ret v4
b2:
v5 = iconst 5
store.i64 v2, v5
v6 = iconst 6
ret v6
"""));
}
@test def a_word_a_branch_found_equal_to_a_constant_is_that_constant(t: &mut tester): void {
# Where `n == 4`, `n * 10` is 40.
val got := optimized(1, "sides", """
def sides(n: u64, k: u64): u64 {
if n == 4 { return n * 10 + k; }
return 0;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = iconst 4
v3 = eq v0, v2
branch v3, b2, b1
b1:
v4 = iconst 0
ret v4
b2:
v5 = iconst 40
v6 = add v1, v5
ret v6
"""));
}
@test def what_a_loop_works_out_of_two_values_it_keeps_is_regrouped_out(t: &mut tester): void {
# `i + a + b` adds `a` and `b`, which the loop never changes, together
# before it, and only that sum to `i` within it.
val got := optimized(1, "sum", """
def sum(xs: &u64[64], a: u64, b: u64, n: u64): u64 {
var total: u64 = 0;
for i in 0..n { total += xs[(i + a + b) & 63]; }
return total;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64, v2: i64, v3: i64):
v4 = iconst 0
v5 = iconst 1
v6 = iconst 63
v7 = iconst 3
branch v3, b1, b3(v4)
b1:
v8 = add v1, v2
jump b2(v4, v4)
b2(v9: i64, v10: i64):
v11 = add v9, v8
v12 = band v11, v6
v13 = shl v12, v7
v14 = add v0, v13
v15 = load.i64 v14
v16 = add v10, v15
v17 = add v9, v5
v18 = ltu v17, v3
branch v18, b2(v17, v16), b3(v16)
b3(v19: i64):
ret v19
"""));
}
@test def a_call_is_inlined_by_what_its_copy_would_cost_there(t: &mut tester): void {
# `mix` costs more than the limit, but its reads of what it takes as
# memory read the copies the call makes, which promote: so at each call it
# costs less, is inlined, and the fields are each read once.
val got := optimized(2, "both", """
struct v4 { var x: f32; var y: f32; var z: f32; var w: f32; }
def mix(a: v4, b: v4): f32 { return a.x * b.y - a.y * b.x + a.z * b.w - a.w * b.z + a.x * b.z - a.z * b.x; }
def both(p: v4, q: v4): f32 { return mix(p, q) + mix(q, p); }
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = load.f32 v0+12
v3 = load.f32 v0+8
v4 = load.f32 v0+4
v5 = load.f32 v0
v6 = load.f32 v1+8
v7 = load.f32 v1+12
v8 = load.f32 v1
v9 = load.f32 v1+4
v10 = fmul v5, v9
v11 = fsingle v10
v12 = fmul v4, v8
v13 = fsingle v12
v14 = fsub v11, v13
v15 = fsingle v14
v16 = fmul v3, v7
v17 = fsingle v16
v18 = fadd v15, v17
v19 = fsingle v18
v20 = fmul v2, v6
v21 = fsingle v20
v22 = fsub v19, v21
v23 = fsingle v22
v24 = fmul v5, v6
v25 = fsingle v24
v26 = fadd v23, v25
v27 = fsingle v26
v28 = fmul v3, v8
v29 = fsingle v28
v30 = fsub v27, v29
v31 = fsingle v30
v32 = fmul v8, v4
v33 = fsingle v32
v34 = fmul v9, v5
v35 = fsingle v34
v36 = fsub v33, v35
v37 = fsingle v36
v38 = fmul v6, v2
v39 = fsingle v38
v40 = fadd v37, v39
v41 = fsingle v40
v42 = fmul v7, v3
v43 = fsingle v42
v44 = fsub v41, v43
v45 = fsingle v44
v46 = fmul v8, v3
v47 = fsingle v46
v48 = fadd v45, v47
v49 = fsingle v48
v50 = fmul v6, v5
v51 = fsingle v50
v52 = fsub v49, v51
v53 = fsingle v52
v54 = fadd v31, v53
v55 = fsingle v54
ret v55
"""));
}
@test def values_nothing_needs_go_even_around_loops(t: &mut tester): void {
# `waste` is only ever added to, and read by nothing else, so the loop no
# longer carries it. The loop is rotated: whether to go round again is asked
# at its bottom, and once before it.
val got := optimized(1, "count", """
def count(n: u64): u64 {
var waste: u64 = 0;
var i: u64 = 0;
while i < n { waste += i; i += 1; }
return i;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64):
v1 = iconst 0
v2 = iconst 1
branch v0, b1(v1), b2(v1)
b1(v3: i64):
v4 = add v3, v2
v5 = ltu v4, v0
branch v5, b1(v4), b2(v4)
b2(v6: i64):
ret v6
"""));
}
@test def conditions_joined_as_constants_go_straight_where_they_lead(t: &mut tester): void {
# `a && !b` joins the constant it works out before branching on it; each
# edge giving a constant goes straight where the branch would send it.
val got := optimized(1, "both", """
def both(a: bool, b: bool): i64 {
if a && !b { return 1; }
return 2;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
branch v0, b1, b3
b1:
branch v1, b3, b2
b2:
v2 = iconst 1
ret v2
b3:
v3 = iconst 2
ret v3
"""));
}
@test def flags_worked_out_from_constants_go_straight_where_they_lead(t: &mut tester): void {
# The join works out `found == 1` from the constant each way gives it, so
# each goes straight where the test sends it, and the value it gave `at`
# reaches what reads it as a parameter of where it went.
val got := optimized(1, "first", """
def first(a: bool, x: i64): i64 {
var found: u64 = 0;
var at: i64 = 0;
if a { found = 1; at = x; }
if found == 1 { return at + 1; }
return 0;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = iconst 0
branch v0, b2, b1
b1:
ret v2
b2:
v3 = iconst 1
v4 = add v1, v3
ret v4
"""));
}
@test def branches_choosing_values_become_selects(t: &mut tester): void {
# The `if` only chooses the value `x` joins with, so it becomes a `select`.
val got := optimized(1, "pick", """
def pick(c: bool, a: i64, b: i64): i64 {
var x := b;
if c { x = a; }
return x;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64, v2: i64):
v3 = select v0, v1, v2
ret v3
"""));
# Where `n` is zero, `k` is 0 either way, which is `n`.
val zeros := optimized(1, "nonzero", """
def nonzero(n: u64): u64 {
var k: u64 = 0;
if n != 0 { k = n; }
return k;
}
""");
t.expects(lowers_as(&zeros, """
b0(v0: i64):
ret v0
"""));
# Within the `if`, `c` is known not to be zero, so the choice is known.
val known := optimized(1, "known", """
def known(c: bool, a: i64, b: i64): i64 {
if c { return c ? a : b; }
return 0;
}
""");
t.expects(lowers_as(&known, """
b0(v0: i64, v1: i64, v2: i64):
branch v0, b2, b1
b1:
v3 = iconst 0
ret v3
b2:
ret v1
"""));
}
@test def a_check_a_dominating_one_made_goes(t: &mut tester): void {
# The second `v[i]` compares what the first did, which was checked, and
# reads what it read.
val got := optimized(1, "twice", """
def twice(v: &i64[8], i: u64): i64 { return v[i] + v[i]; }
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = iconst 3
v3 = iconst 8
v4 = ltu v1, v3
check v4, out_of_bounds
v5 = shl v1, v2
v6 = add v0, v5
v7 = load.i64 v6
v8 = add v7, v7
ret v8
"""));
}
@test def a_read_a_loop_writing_nothing_repeats_reads_what_was_read_before(t: &mut tester): void {
# Nothing in the loop writes, so `p.key` reads what it read before the loop
# each time round.
val got := optimized(1, "scan", """
struct pair { var key: i64; var other: i64; }
def scan(p: &pair, v: &i64[8]): u64 {
if p.key < 0 { return 8; }
var i: u64 = 0;
while i < 8 { if v[i] == p.key { return i; } i += 1; }
return i;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = iconst 1
v3 = iconst 8
v4 = iconst 3
v5 = load.i64 v0
v6 = iconst 0
v7 = lts v5, v6
branch v7, b6, b1
b1:
jump b2(v6)
b2(v8: i64):
v9 = shl v8, v4
v10 = add v1, v9
v11 = load.i64 v10
v12 = eq v11, v5
branch v12, b5, b3
b3:
v13 = add v8, v2
v14 = ltu v13, v3
branch v14, b2(v13), b4
b4:
ret v13
b5:
ret v8
b6:
ret v3
"""));
}
@test def a_choice_sunk_past_the_branch_deciding_it_is_what_it_chooses(t: &mut tester): void {
# `s` is only read where `c != 0`, so the `select` making it is sunk there,
# where the branch decides its condition, and becomes what it chooses.
val got := optimized(1, "pick", """
def pick(a: *u64): u64 {
val c := a[0];
val s := c != 0 ? c + 1 : 5;
if c != 0 { return s * 3; }
return 7;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64):
v1 = iconst 1
v2 = load.i64 v0
branch v2, b2, b1
b1:
v3 = iconst 7
ret v3
b2:
v4 = add v2, v1
v5 = iconst 3
v6 = mul v4, v5
ret v6
"""));
}
@test def loops_rotate_and_what_they_work_out_the_same_moves_out(t: &mut tester): void {
# The loop asks whether to go round again at its bottom, and once before it,
# where the size is read. Nothing in it writes, so the size is read there
# only, and where the pointer is read and checked is before the loop, as its
# first pass reads and checks it before anything else.
val got := optimized(1, "find", """
struct table { var data: *i64; var size: u64; }
def find(t: &table, key: i64): u64 {
var i: u64 = 0;
while i < t.size { if t.data[i] == key { return i; } i += 1; }
return t.size;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = iconst 0
v3 = iconst 1
v4 = iconst 3
v5 = load.i64 v0+8
branch v5, b1, b4
b1:
v6 = load.i64 v0
check v6, null_reference
jump b2(v2)
b2(v7: i64):
v8 = shl v7, v4
v9 = add v6, v8
v10 = load.i64 v9
v11 = eq v10, v1
branch v11, b5, b3
b3:
v12 = add v7, v3
v13 = ltu v12, v5
branch v13, b2(v12), b4
b4:
ret v5
b5:
ret v7
"""));
}
@test def writes_known_not_to_touch_a_read_leave_it_known(t: &mut tester): void {
# Writing `p.b` does not write `p.a`, so `p.a` is read once.
val fields := optimized(1, "bump", """
struct pair { var a: i64; var b: i64; }
def bump(p: &mut pair): i64 { val x := p.a; p.b = x; return p.a + 1; }
""");
t.expects(lowers_as(&fields, """
b0(v0: i64):
v1 = load.i64 v0
store.i64 v0+8, v1
v2 = iconst 1
v3 = add v1, v2
ret v3
"""));
# A call cannot write a cell whose address it is not given, so what was
# stored there is read again without the cell.
val called := optimized(1, "kept", """
def tick(): void {}
def kept(n: i64): i64 { var x := n * 3; tick(); return x + 1; }
""");
t.expects(lowers_as(&called, """
b0(v0: i64):
v1 = iconst 3
v2 = mul v0, v1
call f1()
v3 = iconst 1
v4 = add v2, v3
ret v4
"""));
# Writing the frame's array does not write what `p` points at, so the loop
# reads `p.a` once, before it.
val looped := optimized(2, "fill", """
struct pair { var a: i64; var b: i64; }
def fill(p: &pair): i64 {
var buf: i64[4] = [0, 0, 0, 0];
var i: u64 = 0;
while i < 4 { buf[i] = p.a; i += 1; }
return buf[0] + buf[3];
}
""");
t.expects(lowers_as(&looped, """
c0: 32, 8
b0(v0: i64):
v1 = iconst 1
v2 = iconst 4
v3 = iconst 3
v4 = cell c0
v5 = iconst 0
v6 = load.i64 v0
jump b1(v5)
b1(v7: i64):
v8 = shl v7, v3
v9 = add v4, v8
store.i64 v9, v6
v10 = add v7, v1
v11 = ltu v10, v2
branch v11, b1(v10), b2
b2:
v12 = load.i64 v4
v13 = load.i64 v4+24
v14 = add v12, v13
ret v14
"""));
}
@test def what_one_way_out_reads_moves_into_that_way(t: &mut tester): void {
# The limit and the step are read only where `go` holds, so they are read
# there, after the count that both ways read.
val got := optimized(1, "advance", """
struct counter { var count: u64; var limit: u64; var step: u64; }
def advance(c: &counter, go: bool): u64 {
val limit := c.limit;
val step := c.step;
val count := c.count;
if go { return limit + step + count; }
return count;
}
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = load.i64 v0
branch v1, b2, b1
b1:
ret v2
b2:
v3 = load.i64 v0+8
v4 = load.i64 v0+16
v5 = add v3, v4
v6 = add v5, v2
ret v6
"""));
}
@test def small_functions_inline_and_their_cells_become_values(t: &mut tester): void {
# `sum` is inlined, and the point it was given the address of, and the copy
# of its literal, become the values they hold.
val got := optimized(2, "made", """
struct point { var x: i64; var y: i64; }
def point::sum(&this): i64 { return this.x + this.y; }
def made(a: i64, b: i64): i64 { val p := point { x = a, y = b }; return p.sum(); }
""");
t.expects(lowers_as(&got, """
b0(v0: i64, v1: i64):
v2 = add v0, v1
ret v2
"""));
# `% 2 == 0` becomes a mask, and `/ 2` a shift; both ways of the `if` are
# worked out and a `select` of the mask chooses between them, and the loop,
# rotated, goes round without making its constants again.
val looped := optimized(2, "steps", """
def steps(start: u64): u64 {
var n := start;
var count: u64 = 0;
while n != 1 {
if n % 2 == 0 { n = n / 2; } else { n = 3 * n + 1; }
count += 1;
}
return count;
}
""");
t.expects(lowers_as(&looped, """
b0(v0: i64):
v1 = iconst 3
v2 = iconst 1
v3 = iconst 0
v4 = ne v0, v2
branch v4, b1(v0, v3), b2(v3)
b1(v5: i64, v6: i64):
v7 = band v5, v2
v8 = mul v5, v1
v9 = add v8, v2
v10 = shru v5, v2
v11 = select v7, v9, v10
v12 = add v6, v2
v13 = ne v11, v2
branch v13, b1(v11, v12), b2(v12)
b2(v14: i64):
ret v14
"""));
}
@test def inline_functions_are_copied_at_every_level(t: &mut tester): void {
val text := """
struct inline {}
@inline def twice(x: i64): i64 { val y := x * 2; return y; }
def thrice(x: i64): i64 { return x * 3; }
@inline def count(n: i64): i64 { return n == 0 ? 0 : count(n - 1) + 1; }
def f(a: i64): i64 { return thrice(twice(a)) + count(a); }
""";
# At `-O0`, the calls of `twice` and `count` are copied, each parameter and
# local still in a cell of its own, and nothing else changes: `thrice` is
# called, and so is `count` within its copy, as that call closes a loop. The
# copies clear none of their cells, as each is written before it is read, so
# the functions' own frames would zero none of them.
val none := optimized(0, "f", text);
t.expects(lowers_as(&none, """
c0: 8, 8
c1: 8, 8
c2: 8, 8
c3: 8, 8
b0(v0: i64):
v1 = cell c0
store.i64 v1, v0
v2 = load.i64 v1
jump b1
b1:
v3 = cell c1
store.i64 v3, v2
v4 = cell c2
v5 = load.i64 v3
v6 = iconst 2
v7 = mul v5, v6
store.i64 v4, v7
v8 = load.i64 v4
jump b2
b2:
v9 = call f2(v8)
v10 = load.i64 v1
jump b3
b3:
v11 = cell c3
store.i64 v11, v10
v12 = load.i64 v11
v13 = iconst 0
v14 = eq v12, v13
branch v14, b5, b4
b4:
v15 = load.i64 v11
v16 = iconst 1
v17 = sub v15, v16
v18 = call f3(v17)
v19 = iconst 1
v20 = add v18, v19
jump b6(v20)
b5:
v21 = iconst 0
jump b6(v21)
b6(v22: i64):
jump b7
b7:
v23 = add v9, v22
ret v23
"""));
# At `-O1`, the copies are folded into what calls them as any code is.
val local := optimized(1, "f", text);
t.expects(lowers_as(&local, """
b0(v0: i64):
v1 = iconst 1
v2 = shl v0, v1
v3 = call f2(v2)
v4 = iconst 0
branch v0, b1, b2(v4)
b1:
v5 = sub v0, v1
v6 = call f3(v5)
v7 = add v6, v1
jump b2(v7)
b2(v8: i64):
v9 = add v3, v8
ret v9
"""));
# At `-O2`, one of any size is copied, past `--inline N`, though it is called
# more than once.
val large := optimized(2, "g", """
struct inline {}
@inline def mix(x: u64): u64 {
var h := x;
h = (h ^ (h >> 33)) * 0xFF51AFD7ED558CCD;
h = (h ^ (h >> 33)) * 0xC4CEB9FE1A85EC53;
h = (h ^ (h >> 29)) * 0xFF51AFD7ED558CCD;
h = (h ^ (h >> 31)) * 0xC4CEB9FE1A85EC53;
h = (h ^ (h >> 30)) * 0xFF51AFD7ED558CCD;
h = (h ^ (h >> 27)) * 0xC4CEB9FE1A85EC53;
return h ^ (h >> 31);
}
def g(a: u64, b: u64): u64 { return mix(a) + mix(b); }
""");
t.expects(large.span.find("mul") is some && large.span.find("call") is none);
}
@test def worklists_take_each_index_once_and_scopes_take_back_what_they_set(t: &mut tester): void {
var work := worklist::new(8, nothing {});
t.expects(work.push_new(3) && work.push_new(5) && !work.push_new(3));
t.expects(work.pop() == 5 && work.pop() == 3 && work.empty);
t.expects(work.has(3) && !work.has(4) && !work.push_new(5));
# A stamped set empties as each round begins.
var counted := stamped_set::new(8, nothing {});
t.expects(counted.insert(2) && !counted.insert(2) && counted.contains(2));
counted.next_round();
t.expects(!counted.contains(2) && counted.insert(2));
# Rewinding puts back what each key held at the mark, or takes it out.
val one: u32 = 1;
val two: u32 = 2;
var scoped := scoped_dict::<u32, u32>::new(nothing {});
scoped.set(1, 10);
val mark := scoped.mark();
scoped.set(1, 11);
scoped.set(2, 20);
t.expects(scoped.get_or(&one, 0) == 11 && scoped.contains(&two));
scoped.rewind(mark);
t.expects(scoped.get_or(&one, 0) == 10 && !scoped.contains(&two));
scoped.rewind(0);
t.expects(!scoped.contains(&one) && scoped.mark() == 0);
}
+137
View File
@@ -0,0 +1,137 @@
#! @file workers.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tests of sharing the compiler's work out among threads: each
#! index done once, each after those it waits for, each thread with scratch
#! memory of its own, and functions optimized on threads made into what one
#! thread makes them.
import std::containers;
import std::testing;
import sakura::analyzer;
module sakura::compiler;
@test def work_shared_out_is_done_once_for_each_index(t: &mut tester): void {
val count: u64 = 2000;
for threads in 1..6u {
var done := vector::<atomic<u32>>::new();
for _ in 0..count {
done.append(atomic::<u32>::new(0));
}
share_out(count, threads as u32, def(index: u64): void { _ = done[index].fetch_add(1); });
var once := true;
for i in 0..count {
once = once && done[i].load() == 1;
}
t.expects(once);
}
}
@test def work_shared_out_in_order_waits_for_what_it_waits_for(t: &mut tester): void {
# Each index but the first waits for the one halfway to it, as in a heap,
# and is stamped as it is done, after the one it waits for.
val count: u64 = 1023;
var waiting := groups::<u32>::new(count);
for child in 1..count {
waiting.count((child - 1) / 2);
}
waiting.seal();
for child in 1..count {
waiting.put((child - 1) / 2, child as u32);
}
for threads in 1..6u {
var stamps := vector::<atomic<u64>>::new();
for _ in 0..count {
stamps.append(atomic::<u64>::new(0));
}
var clock := atomic::<u64>::new(0);
share_out_ordered(count, threads as u32, &waiting, def(index: u64): void {
stamps[index].store(clock.fetch_add(1) + 1);
});
var ordered := true;
for i in 1..count {
ordered = ordered && stamps[i].load() != 0 && stamps[(i - 1) / 2].load() < stamps[i].load();
}
t.expects(ordered && stamps[0].load() != 0);
}
}
@test def each_thread_takes_scratch_memory_of_its_own(t: &mut tester): void {
# Each index fills scratch memory it marked, then reads it back; another
# thread marking, taking, or rewinding the same memory meanwhile would change
# what it reads.
var wrong := atomic::<u32>::new(0);
share_out(256, 5, def(index: u64): void {
val point := mark_scratch();
var filled := vector::<u64>::new(scratch());
for k in 0..4000u {
filled.append(index * 4000 + k);
}
var also := vector::<u64>::new(scratch());
also.resize(512);
for k in 0..4000u {
if filled[k] != index * 4000 + k {
_ = wrong.fetch_add(1);
}
}
also.close();
filled.close();
release_scratch(point);
});
t.expects(wrong.load() == 0);
}
@test def functions_optimized_on_threads_are_made_what_one_thread_makes_them(t: &mut tester): void {
# Functions calling each other, in a cycle and through several levels, which
# inlining copies into one another, so one optimized before or after what it
# inlines would come out otherwise.
val text := """
def leaf(x: i64): i64 { return x * 2 + 1; }
def twice(x: i64): i64 { return leaf(x) + leaf(x + 1); }
def even(n: i64): bool { return n == 0 ? true : odd(n - 1); }
def odd(n: i64): bool { return n == 0 ? false : even(n - 1); }
def sum(n: i64): i64 {
var total: i64 = 0;
for i in 0..n { total += twice(i); }
return total;
}
def pick(n: i64): i64 { return even(n) ? sum(n) : twice(n); }
def main(): void { if pick(10) == 0 { return; } }
""";
val names := "leaf twice even odd sum pick main";
for level in 1..3u {
val one := optimized_on(1, level as u32, names, text);
t.expects(one.length > 200 && !one.span.starts_with("the program"));
for threads in 2..6u {
val many := optimized_on(threads as u32, level as u32, names, text);
t.expects(one.span == many.span);
}
}
# The same, where some are `@inline`, and so copied at `-O0` too.
val marked := """
struct inline {}
@inline def leaf(x: i64): i64 { return x * 2 + 1; }
@inline def twice(x: i64): i64 { return leaf(x) + leaf(x + 1); }
@inline def even(n: i64): bool { return n == 0 ? true : odd(n - 1); }
def odd(n: i64): bool { return n == 0 ? false : even(n - 1); }
def sum(n: i64): i64 {
var total: i64 = 0;
for i in 0..n { total += twice(i); }
return total;
}
def pick(n: i64): i64 { return even(n) ? sum(n) : twice(n); }
def main(): void { if pick(10) == 0 { return; } }
""";
for level in 0..3u {
val one := optimized_on(1, level as u32, names, marked);
t.expects(one.length > 200 && !one.span.starts_with("the program"));
for threads in 2..6u {
val many := optimized_on(threads as u32, level as u32, names, marked);
t.expects(one.span == many.span);
}
}
}