Files
sakurac/tests/compiler/optimizer.sakura
T
2026-10-28 22:13:49 -05:00

698 lines
20 KiB
Plaintext

#! @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.view());
out.append("\n");
}
var wanted := string::from(names, nothing {});
for name in wanted.split(' ') {
for &function in lowering.program.functions {
if function.name.view() == name {
var text := function.body.print();
out.append(text.view());
}
}
}
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.view() == "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 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.view().find("mul") is some && large.view().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.is_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);
}