Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-28 22:13:49 -05:00
commit 05756094ac
706 files changed
+135430

No files matched your search

+393
View File
@@ -0,0 +1,393 @@
#! @file alias.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains alias analysis, which the passes of the optimizer ask whether an
#! instruction writing memory may write what a read reads, or what they know
#! memory holds. An access touches a region: bytes from a base, which its
#! address steps from by constants, as `add`s of constants and the steps loads
#! and stores take give them. An address stepping by what is not known from one
#! within a cell, the globals, a datum, or memory made, as indexing an array
#! does, is anywhere within the same.
#!
#! Two regions may hold a byte in common but where it is known they do not.
#! Regions of one base, of one cell, or both of the globals, do not where their
#! bytes do not overlap, and two cells do not. A cell that is not escaped, its
#! address going nowhere but to the instructions reading, writing, copying, and
#! clearing it, and to calls as where to write what they return, as the memory
#! pass finds, is touched by nothing reaching through another address, nor by
#! a call, or anything else writing memory the code does not name, but where it
#! writes what it returns. No cell is what an address the function was given,
#! the globals, or the heap holds, none of which is the frame. Memory a `box` or
#! `allocate` made is not what an address the function was given, the globals,
#! other memory made so, or an address read before it was made holds, as none
#! could point at what was not yet there. And nothing writes a datum.
#!
#! Sakura has no rule that memory of one type is not read or written as
#! another: std and the runtime reach through pointers cast to other types, as
#! `float_bits` is written as an `f64` and read as a `u64`, and loads and stores say only how they read and
#! write, not what they reach. So no region is told apart from another by the
#! type of what it holds.
module sakura::compiler;
#! What the base of a region is.
pub enum base_kind : u8 {
other, #! A value nothing more is known of.
cell, #! The address of a cell of the frame.
global, #! The start of the globals, a global's address stepping from it.
datum, #! The address of a datum, which nothing writes.
fresh, #! The address of memory a `box` or `allocate` made.
given, #! A parameter of the entry: an address the function was given.
loaded, #! An address read from memory.
}
#! What a region's size is where it is not known.
pub const unknown_size: u64 = 0xFFFFFFFFFFFFFFFF;
#! The bytes an access touches: a base, how far past it they begin, and how
#! many there are.
pub struct region {
pub var base: u32; #! The value the address steps from by constants.
pub var offset: u64; #! How far past the base the bytes begin, wrapping as addresses do; for a global, past the start of the globals.
pub var size: u64; #! How many bytes, or `unknown_size`.
pub var kind: base_kind; #! What the base is.
pub var cell: u32; #! The cell, where the base is a cell's address.
}
#! What alias analysis knows of code: which cell each value is the address
#! of, which cells are escaped, the bytes each call writes what it returns to,
#! and which block dominates which, where that is known.
pub struct aliases {
var addresses: cell_table; #! Which cell each value is the address of.
var escaped: vector<bool>; #! Whether each cell is escaped.
var writes: vector<u64>; #! Of each instruction, the bytes a call writes what it returns to at its last operand, or 0.
var idom: vector<u32>; #! The immediate dominator of each block, or nothing where it is not known.
var found: bool; #! Whether which cells are escaped is found.
}
#! Finds what alias analysis knows of the code.
#! @param this The code.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @param idom The immediate dominator of each block, or nothing, where
#! memory made after an address was read is not told apart
#! from what it points at, but within a block.
#! @returns What it knows, in scratch memory.
pub def code::aliases(&this, writes: span<u64>, idom: span<u32>): aliases {
var made := this.aliases_unfound(writes, idom);
made.find_escaped(this);
return made;
}
#! Begins what alias analysis knows of the code, but for which cells are
#! escaped, which `aliases::find_escaped` finds before anything asks whether
#! one region may hold a byte of another, and before anything changes which
#! cells are escaped.
#! @param this The code.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @param idom The immediate dominator of each block, or nothing.
#! @returns What it knows, in scratch memory.
pub def code::aliases_unfound(&this, writes: span<u64>, idom: span<u32>): aliases {
var made := aliases {
escaped = vector::<bool>::new(scratch()),
writes = vector::<u64>::new(scratch()),
idom = vector::<u32>::new(scratch())
};
made.writes.extend(writes);
made.idom.extend(idom);
return made;
}
#! Finds which cells are escaped, where that is not found yet.
#! @param this What alias analysis knows.
#! @param body The code.
pub def aliases::find_escaped(&mut this, body: &code): void {
return if this.found;
this.found = true;
this.addresses = body.cell_table();
this.escaped = body.escaped_cells(&this.addresses, this.writes.view());
}
#! Which cells are escaped: their address goes anywhere but to the instructions
#! reading, writing, copying, and clearing them, to `ret`, or to a call as
#! where to write what it returns.
#! @param this The code.
#! @param addresses Which cell each value is the address of.
#! @param writes Of each instruction, the bytes a call writes what it
#! returns to at its last operand, or 0.
#! @returns Whether each cell is, in scratch memory.
pub def code::escaped_cells(&this, addresses: &cell_table, writes: span<u64>): vector<bool> {
var escaped := vector::<bool>::new(scratch());
escaped.resize(this.cells.length);
return escaped if !addresses.any;
var walk := this.walk_all();
var reads := this.reader();
while walk.more() {
val at := walk.next();
val held := &this.insts[at];
reads.start(at);
while reads.more() {
val cell := addresses.cell(reads.next());
continue if cell == 0;
# A cell's address an edge gives escapes.
val i := reads.operand();
val direct := i != no_operand && match held.kind {
op::load, op::store, op::clear => i == 0,
op::copy => i < 2,
op::ret => true,
else => i + 1 == held.argc && (at as u64) < writes.length && writes[at] != 0
};
if !direct {
escaped[cell - 1] = true;
}
}
}
return escaped;
}
#! The region an access touches.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param index The `load`, `store`, `copy`, or `clear`.
#! @param operand Which address: of a `copy`, 0 for where it writes, 1 for
#! where it reads.
#! @returns The region.
pub def aliases::region_of(&this, body: &code, index: u32, operand: u32): region {
val held: inst = body.insts[index];
if held.kind == op::load || held.kind == op::store {
val how: access = held.aux as access;
return this.region_at(body, body.arg(index, 0), held.imm, how == access::bytes ? unknown_size : how.width());
}
return this.region_at(body, body.arg(index, operand), 0, held.imm);
}
#! The region of bytes past an address.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param address The address.
#! @param offset How far past it the bytes begin.
#! @param size How many there are, or `unknown_size`.
#! @returns The region.
pub def aliases::region_at(&this, body: &code, address: u32, offset: u64, size: u64): region {
var made := region { offset = offset, size = size };
this.find_base(body, address, &mut made, 0);
return made;
}
#! Finds the base of a region at an address, and how far past it the address
#! is, adding that to the region's offset. An address stepping by what is not
#! known from one within a cell, the globals, a datum, or memory made, and from
#! nothing else such, is somewhere within the same, as indexing an array is,
#! so the region is any of it.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param address The address.
#! @param made The region.
#! @param depth How many such steps were followed to the address.
def aliases::find_base(&this, body: &code, address: u32, made: &mut region, depth: u32): void {
var at := address;
var steps := 0;
while steps < 8 {
val index := body.defining(at);
break if index == 0 || body.insts[index].kind != op::add;
var step: u64 = 0;
if body.word_constant(body.arg(index, 1), &mut step) {
at = body.arg(index, 0);
} else if body.word_constant(body.arg(index, 0), &mut step) {
at = body.arg(index, 1);
} else {
break if depth >= 2;
var one := region {};
var two := region {};
this.find_base(body, body.arg(index, 0), &mut one, depth + 1);
this.find_base(body, body.arg(index, 1), &mut two, depth + 1);
break if one.within_object() == two.within_object();
val inside: region = one.within_object() ? one : two;
made.base = inside.base;
made.kind = inside.kind;
made.cell = inside.cell;
made.offset = 0;
made.size = unknown_size;
return;
}
made.offset = made.offset + step;
steps++;
}
made.base = at;
val held: origin = body.origins[at];
if held.param {
made.kind = held.from == 0 ? base_kind::given : base_kind::other;
return;
}
val from: inst = body.insts[held.from];
match from.kind {
op::cell => {
made.kind = base_kind::cell;
made.cell = from.aux;
}
op::global => {
made.kind = base_kind::global;
made.offset = made.offset + from.imm;
}
op::datum => made.kind = base_kind::datum;
op::allocate => made.kind = base_kind::fresh;
op::load => made.kind = base_kind::loaded;
else => made.kind = base_kind::other;
}
}
#! Whether a region's base is within a cell, the globals, a datum, or memory
#! made, which a number never is.
#! @param this The region.
#! @returns Whether it is.
def region::within_object(&this): bool {
return match this.kind {
base_kind::cell, base_kind::global, base_kind::datum, base_kind::fresh => true,
else => false
};
}
#! Whether two regions may hold a byte in common, as the file says.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param a One region.
#! @param b The other.
#! @returns Whether they may.
pub def aliases::may_alias(&this, body: &code, a: &region, b: &region): bool {
return false if a.size == 0 || b.size == 0;
return false if a.kind == base_kind::datum || b.kind == base_kind::datum;
if a.kind == base_kind::cell && b.kind == base_kind::cell {
return a.cell == b.cell && overlaps(a, b);
}
if a.kind == base_kind::cell {
return this.escaped[a.cell] && !b.outside_frame();
}
if b.kind == base_kind::cell {
return this.escaped[b.cell] && !a.outside_frame();
}
if a.kind == base_kind::global && b.kind == base_kind::global {
return overlaps(a, b);
}
return overlaps(a, b) if a.base == b.base;
if a.kind == base_kind::fresh {
return this.may_point_at(body, b, a.base);
}
if b.kind == base_kind::fresh {
return this.may_point_at(body, a, b.base);
}
return true;
}
#! Whether a region may hold bytes of memory a `box` or `allocate` made, its
#! base being other than that memory's address.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param other The region.
#! @param fresh The address of the memory made.
#! @returns Whether it may.
def aliases::may_point_at(&this, body: &code, other: &region, fresh: u32): bool {
return match other.kind {
base_kind::fresh, base_kind::given, base_kind::global => false,
base_kind::loaded => !this.read_before(body, other.base, fresh),
else => true
};
}
#! Whether an address was read before memory was made, wherever both are
#! known: the read is before the `box` or `allocate` in its block, or in a
#! block dominating its block.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param loaded The address read.
#! @param fresh The address of the memory made.
#! @returns Whether it was.
def aliases::read_before(&this, body: &code, loaded: u32, fresh: u32): bool {
val read := body.defining(loaded);
val made := body.defining(fresh);
val at: u32 = body.insts[read].block;
val home: u32 = body.insts[made].block;
if at == home {
var walk := body.walk(at);
while walk.more() {
val each := walk.next();
return true if each == read;
return false if each == made;
}
return false;
}
return (home as u64) < this.idom.length && dominates(&this.idom, at, home);
}
#! Whether the bytes of two regions of one base overlap.
#! @param a One region.
#! @param b The other.
#! @returns Whether they do.
def overlaps(a: &region, b: &region): bool {
return b.offset - a.offset < a.size || a.offset - b.offset < b.size;
}
#! Whether a region is outside the frame, so within no cell: the globals, the
#! heap, or what an address the function was given points at.
#! @param this The region.
#! @returns Whether it is.
def region::outside_frame(&this): bool {
return this.kind == base_kind::global || this.kind == base_kind::fresh || this.kind == base_kind::given;
}
#! What an instruction writes, as alias analysis tells it.
pub struct writing {
pub var place: region; #! The region a store, copy, or clear writes, or that a call writes what it returns to, or none of no bytes.
pub var wide: bool; #! Whether it may write any memory but an unescaped cell's, as a call does.
}
#! What an instruction writes: a store, copy, or clear its region; a call or
#! anything else writing memory the code does not name any but an unescaped
#! cell's, and where it writes what it returns; and anything else nothing.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param index The instruction.
#! @returns What it writes.
pub def aliases::writes_of(&this, body: &code, index: u32): writing {
val held: inst = body.insts[index];
var made := writing {};
if held.kind == op::store || held.kind == op::clear || held.kind == op::copy {
made.place = this.region_of(body, index, 0);
return made;
}
return made if held.kind == op::load || (held.kind.traits() & op_write) == 0;
made.wide = true;
val result: u64 = (index as u64) < this.writes.length ? this.writes[index] : 0;
if result != 0 {
made.place = this.region_at(body, body.arg(index, held.argc - 1), 0, result);
}
return made;
}
#! Whether what an instruction writes may hold a byte of a region.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param written What the instruction writes.
#! @param place The region.
#! @returns Whether it may.
pub def aliases::touches(&this, body: &code, written: &writing, place: &region): bool {
if written.wide {
return false if place.kind == base_kind::datum;
return true if place.kind != base_kind::cell || this.escaped[place.cell];
}
return this.may_alias(body, &written.place, place);
}
#! Whether an instruction may write a byte of a region.
#! @param this What alias analysis knows.
#! @param body The code.
#! @param index The instruction.
#! @param place The region.
#! @returns Whether it may.
pub def aliases::clobbers(&this, body: &code, index: u32, place: &region): bool {
val written := this.writes_of(body, index);
return this.touches(body, &written, place);
}
File diff suppressed because it is too large. Load diff
+224
View File
@@ -0,0 +1,224 @@
#! @file dead.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the second pass of the optimizer, which takes out what nothing
#! needs: an instruction whose results nothing reads, where taking it out
#! changes nothing else, a parameter of a block that nothing reads, and a
#! cell whose address nothing takes, which leaves the frame smaller. What
#! is needed is found from what must stay, as a store or a call: what it
#! reads is needed, then what that reads in turn, and a parameter needed
#! needs the argument each edge into its block gives it. So a value carried
#! around a loop only to be carried around again goes too.
module sakura::compiler;
#! Takes out what nothing needs, as the file says.
#! @param this The code.
#! @returns Whether anything changed.
pub def code::remove_dead(&mut this): bool {
var live := worklist::new(this.origins.length, scratch());
var reached := vector::<bool>::new(scratch());
reached.resize(this.insts.length);
# What must stay needs what it reads, but for writes to cells nothing reads.
val read := this.read_cells();
var walk := this.walk_all();
while walk.more() {
val at := walk.next();
if !this.removable(at) && !this.unread_write(at, &read) {
reached[at] = true;
this.need_operands(at, &mut live);
}
}
# The entry's parameters are what the function takes, which stay.
for &each in this.blocks[0].params {
live.push_new(each);
}
while !live.is_empty {
val value := live.pop();
val held: origin = this.origins[value];
if held.param {
for &edge in this.blocks[held.from].preds {
val given: u32 = this.edges[edge].args[held.index];
live.push_new(given);
}
continue;
}
if !reached[held.from] {
reached[held.from] = true;
this.need_operands(held.from, &mut live);
}
}
var done := rewrite::new();
var sweep := this.walk_all();
while sweep.more() {
val at := sweep.next();
if !reached[at] {
done.remove(at);
}
}
this.apply(&done);
# Each parameter nothing needs goes, with what each edge gives it.
var changed := done.changed;
var keeps := vector::<bool>::new(scratch());
for b in 1..this.blocks.length {
continue if this.blocks[b].gone;
keeps.clear();
for &param in this.blocks[b].params.view() {
keeps.append(live.has(param));
}
continue if !keeps.view().contains(&false);
changed = true;
this.drop_params(b as u32, keeps.view());
}
return this.drop_cells() || changed;
}
#! Takes out the cells whose address nothing takes, numbering those left in
#! the order they were.
#! @param this The code.
#! @returns Whether any was taken out.
def code::drop_cells(&mut this): bool {
return false if this.cells.length == 0;
var used := vector::<bool>::new(scratch());
used.resize(this.cells.length);
var walk := this.walk_all();
while walk.more() {
val at := walk.next();
if this.insts[at].kind == op::cell {
used[this.insts[at].aux] = true;
}
}
var renumbered := vector::<u32>::new(scratch());
var kept := vector::<cell>::new();
for c in 0..this.cells.length {
renumbered.append(kept.length as u32);
if used[c] {
kept.append(this.cells[c]);
}
}
return false if kept.length == this.cells.length;
var again := this.walk_all();
while again.more() {
val at := again.next();
if this.insts[at].kind == op::cell {
this.insts[at].aux = renumbered[this.insts[at].aux];
}
}
this.cells = move(&mut kept);
for i in 0..this.variables.length {
val held: u32 = this.variables[i].cell;
continue if held == 0;
this.variables[i].cell = used[held - 1] ? renumbered[held - 1] + 1 : 0;
}
return true;
}
#! Which cells something reads: by loading from them, copying out of them,
#! or anything else their address is given to, which may read them.
#! @param this The code.
#! @returns Whether each cell is read.
def code::read_cells(&this): vector<bool> {
var read := vector::<bool>::new(scratch());
return read if this.cells.length == 0;
read.resize(this.cells.length);
var walk := this.walk_all();
var reads := this.reader();
while walk.more() {
val at := walk.next();
# Writing a cell at its address does not read it.
val kind := this.insts[at].kind;
val writes := kind == op::store || kind == op::clear || kind == op::copy;
reads.start(at);
while reads.more() {
val cell := this.cell_of(reads.next());
if cell != no_cell && !(writes && reads.operand() == 0) {
read[cell] = true;
}
}
}
return read;
}
#! Whether an instruction only writes a cell nothing reads, which goes: a store
#! or a clear of it, or a copy into it from an address that cannot be null.
#! @param this The code.
#! @param index The instruction.
#! @param read Which cells something reads.
#! @returns Whether it does.
def code::unread_write(&this, index: u32, read: &vector<bool>): bool {
val held: inst = this.insts[index];
return false if held.kind != op::store && held.kind != op::clear && held.kind != op::copy;
val cell := this.cell_of(this.arg(index, 0));
return false if cell == no_cell || read[cell];
return held.kind != op::copy || this.checked_address(index, this.arg(index, 1));
}
#! Whether an address an instruction reads cannot be null there: one never
#! zero, or a step from a pointer a check before it in its block found not
#! null.
#! @param this The code.
#! @param index The instruction.
#! @param address The address.
#! @returns Whether it cannot.
pub def code::checked_address(&this, index: u32, address: u32): bool {
return true if this.never_zero(address);
var base := address;
var steps := 0;
while steps < 8 {
val made := this.defining(base);
break if made == 0 || this.insts[made].kind != op::add;
base = this.arg(made, 0);
steps++;
}
var walk := this.walk(this.insts[index].block);
while walk.more() {
val at := walk.next();
break if at == index;
val held := &this.insts[at];
if held.kind == op::check && held.aux == fault::null_reference as u32 && this.arg(at, 0) == base {
return true;
}
}
return false;
}
#! Marks what an instruction reads as needed.
#! @param this The code.
#! @param index The instruction.
#! @param live The values needed, those newly needed waiting for their own
#! needs to be marked.
def code::need_operands(&this, index: u32, live: &mut worklist): void {
val held := &this.insts[index];
for i in 0..held.argc {
live.push_new(this.operands[held.args as u64 + i as u64]);
}
}
#! Whether an instruction may be taken out where nothing reads what it gives:
#! one that only works out its results, a division by a constant other than
#! zero, which never stops the program, and a read of an address never zero.
#! @param this The code.
#! @param index The instruction.
#! @returns Whether it may.
pub def code::removable(&this, index: u32): bool {
val held: inst = this.insts[index];
return false if held.count == 0 || held.kind.ends();
return true if (held.kind.traits() & op_pure) != 0;
match held.kind {
op::divs, op::divu, op::rems, op::remu => {
var bits: u64 = 0;
return this.word_constant(this.arg(index, 1), &mut bits) && bits != 0;
}
op::load => return this.never_zero(this.arg(index, 0));
else => return false;
}
return false;
}
+592
View File
@@ -0,0 +1,592 @@
#! @file edit.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what the passes of the optimizer share to change code: a rewrite,
#! which gathers the values a pass replaces and the instructions it takes out
#! and applies them in one sweep once the pass is done, and the changes made
#! in place, as an instruction becoming another that gives the same values, an
#! instruction put first in a block or before another, and a branch whose ways
#! out are swapped. Also what the passes ask of code: the constant a value is,
#! whether a value is never zero, and how often each value is used.
module sakura::compiler;
#! What a pass changes as it goes: the value each use of another reads instead,
#! and the instructions taken out, which `code::apply` applies in one sweep.
pub struct rewrite {
var forward: vector<u32>; #! The value read instead of each value, or 0.
var removed: vector<bool>; #! Whether each instruction is taken out.
var changed: bool; #! Whether the pass changed anything.
}
#! Makes a rewrite that changes nothing yet.
#! @returns The rewrite.
pub def rewrite::new(): rewrite {
return rewrite { forward = vector::<u32>::new(scratch()), removed = vector::<bool>::new(scratch()) };
}
#! The value read where a value is, following each value replaced to what
#! replaces it.
#! @param this The rewrite.
#! @param value The value.
#! @returns The value read.
pub def rewrite::resolve(&this, value: u32): u32 {
return follow_replaced(this.forward.view().data, this.forward.length, value);
}
#! The value read where a value is, following each value replaced to what
#! replaces it, until one not replaced, or a million steps, past which the
#! replacements are taken to go round.
#! @param forward The value replacing each value, by index, or 0 where it is
#! not replaced.
#! @param count How many values `forward` holds, past which none is
#! replaced.
#! @param value The value.
#! @returns The value read.
pub def follow_replaced(forward: *u32, count: u64, value: u32): u32 {
var at := value;
var steps := 0;
while (at as u64) < count && forward[at] != 0 && steps < 1000000 {
at = forward[at];
steps++;
}
return at;
}
#! Makes each use of a value read another.
#! @param this The rewrite.
#! @param from The value replaced.
#! @param to The value read instead.
pub def rewrite::replace(&mut this, from: u32, to: u32): void {
return if from == to || this.resolve(to) == from;
if this.forward.length <= from as u64 {
this.forward.resize(from as u64 + 1);
}
this.forward[from] = to;
this.changed = true;
}
#! Takes an instruction out of its block.
#! @param this The rewrite.
#! @param index The instruction.
pub def rewrite::remove(&mut this, index: u32): void {
if this.removed.length <= index as u64 {
this.removed.resize(index as u64 + 1);
}
this.removed[index] = true;
this.changed = true;
}
#! Whether an instruction is taken out.
#! @param this The rewrite.
#! @param index The instruction.
#! @returns Whether it is.
pub def rewrite::is_removed(&this, index: u32): bool {
return (index as u64) < this.removed.length && this.removed[index];
}
#! Applies a rewrite: each operand and argument reads what replaces the value
#! it named, and the instructions taken out leave their blocks.
#! @param this The code.
#! @param done The rewrite.
pub def code::apply(&mut this, done: &rewrite): void {
val count := done.forward.length;
if count != 0 {
# Read and written where the elements are, as this runs over every operand.
val forward := done.forward.view().data;
val operands := this.operands.slice().data;
for i in 0..this.operands.length {
operands[i] = follow_replaced(forward, count, operands[i]);
}
for e in 0..this.edges.length {
val args := this.edges[e].args.slice().data;
for a in 0..this.edges[e].args.length {
args[a] = follow_replaced(forward, count, args[a]);
}
}
# A variable takes what replaces a value it took.
for i in 0..this.bindings.length {
this.bindings[i].value = follow_replaced(forward, count, this.bindings[i].value);
}
}
this.take_out(done);
}
#! Takes the instructions a rewrite takes out out of their blocks.
#! @param this The code.
#! @param done The rewrite.
pub def code::take_out(&mut this, done: &rewrite): void {
return if done.removed.length == 0;
# Only the blocks holding what is taken out are linked anew.
var touched := vector::<bool>::new(scratch());
touched.resize(this.blocks.length);
for i in 0..done.removed.length {
if done.removed[i] && (this.insts[i].block as u64) < touched.length {
touched[this.insts[i].block] = true;
}
}
for b in 0..this.blocks.length {
continue if this.blocks[b].gone || !touched[b];
var walk := this.walk(b as u32);
var kept: u32 = 0;
this.blocks[b].first = 0;
this.blocks[b].last = 0;
while walk.more() {
val at := walk.next();
continue if done.is_removed(at);
if kept == 0 {
this.blocks[b].first = at;
} else {
this.insts[kept].next = at;
}
kept = at;
}
if kept != 0 {
this.insts[kept].next = 0;
}
this.blocks[b].last = kept;
}
}
#! The instruction giving a value, or 0 for one a block takes.
#! @param this The code.
#! @param value The value.
#! @returns The instruction.
pub def code::defining(&this, value: u32): u32 {
return 0 if value == 0 || (value as u64) >= this.origins.length;
val held: origin = this.origins[value];
return held.param ? 0 : held.from;
}
#! The block a value is made in: the block taking it, or holding the
#! instruction giving it.
#! @param this The code.
#! @param value The value.
#! @returns The block.
pub def code::home_of(&this, value: u32): u32 {
val held: origin = this.origins[value];
return held.param ? held.from : this.insts[held.from].block;
}
#! What `code::cell_of` gives for a value that is the address of no cell.
pub const no_cell: u32 = 0xFFFFFFFF;
#! The cell a value is the address of, as the instruction giving it says.
#! @param this The code.
#! @param value The value.
#! @returns The cell, or `no_cell`.
pub def code::cell_of(&this, value: u32): u32 {
val index := this.defining(value);
return no_cell if index == 0 || this.insts[index].kind != op::cell;
return this.insts[index].aux;
}
#! Which cell each value of code is the address of, found once from the `cell`
#! instructions of the blocks not removed, for a pass that asks it of many
#! values.
pub struct cell_table {
var of: vector<u32>; #! One more than the cell each value is the address of, or 0.
var any: bool; #! Whether any value is.
}
#! Finds which cell each value is the address of.
#! @param this The code.
#! @returns The table, in scratch memory.
pub def code::cell_table(&this): cell_table {
var made := cell_table { of = vector::<u32>::new(scratch()) };
# Code with no cells has no value that is the address of one.
return made if this.cells.length == 0;
made.of.resize(this.origins.length);
var walk := this.walk_all();
while walk.more() {
val held := &this.insts[walk.next()];
if held.kind == op::cell {
made.of[held.result] = held.aux + 1;
made.any = true;
}
}
return made;
}
#! The cell a value is the address of, as the table found it.
#! @param this The table.
#! @param value The value.
#! @returns One more than the cell, or 0, as for a value made after the table.
pub def cell_table::cell(&this, value: u32): u32 {
return (value as u64) < this.of.length ? this.of[value] : 0;
}
#! Whether a value is a constant word, and its bits.
#! @param this The code.
#! @param value The value.
#! @param bits Where its bits are written, where it is one.
#! @returns Whether it is.
pub def code::word_constant(&this, value: u32, bits: &mut u64): bool {
val index := this.defining(value);
return false if index == 0 || this.insts[index].kind != op::iconst;
bits = this.insts[index].imm;
return true;
}
#! Whether a value is a constant real, and its bits.
#! @param this The code.
#! @param value The value.
#! @param bits Where the bits of the `f64` are written, where it is one.
#! @returns Whether it is.
pub def code::real_constant(&this, value: u32, bits: &mut u64): bool {
val index := this.defining(value);
return false if index == 0 || this.insts[index].kind != op::fconst;
bits = this.insts[index].imm;
return true;
}
#! The type of the constant a value is, and its bits, read where the
#! instruction making it lies, taken out of its block or not, as a binding
#! naming the value keeps the constant once that instruction goes.
#! @param this The code.
#! @param value The value.
#! @param bits Where its bits are written, where it is one.
#! @returns Its type, or `none` where it is no constant.
pub def code::constant_kind(&this, value: u32, bits: &mut u64): vt {
return vt::word if this.word_constant(value, bits);
return vt::real if this.real_constant(value, bits);
return vt::none;
}
#! Whether a word is never zero: the address of a cell, a global, or a datum,
#! or a small step past one.
#! @param this The code.
#! @param value The word.
#! @returns Whether it is never zero.
pub def code::never_zero(&this, value: u32): bool {
var at := value;
var steps := 0;
while steps < 8 {
val index := this.defining(at);
return false if index == 0;
val held: inst = this.insts[index];
match held.kind {
op::cell, op::global, op::datum => return true;
op::iconst => return held.imm != 0;
op::add => {
var step: u64 = 0;
return false if !this.word_constant(this.arg(index, 1), &mut step) || step >= 0x100000000u;
at = this.arg(index, 0);
}
else => return false;
}
steps++;
}
return false;
}
#! How many times each value is read, by operands and by the arguments of
#! edges, in the blocks not removed.
#! @param this The code.
#! @returns The count of each value.
pub def code::use_counts(&this): vector<u32> {
var counts := vector::<u32>::new(scratch());
counts.resize(this.origins.length);
var walk := this.walk_all();
var reads := this.reader();
while walk.more() {
reads.start(walk.next());
while reads.more() {
val value := reads.next();
counts[value] = counts[value] + 1;
}
}
return counts;
}
#! Makes an instruction another that gives the same values, in place, so what
#! reads them reads what it gives now.
#! @param this The code.
#! @param index The instruction.
#! @param kind What it does now.
#! @param args Its operands now.
#! @param aux What its kind says `aux` holds.
#! @param imm What its kind says `imm` holds.
pub def code::become(&mut this, index: u32, kind: op, args: span<u32>, aux: u32, imm: u64): void {
# Operands fit where its old ones were, or else go after every other.
var first: u32 = this.insts[index].args;
if args.length > this.insts[index].argc as u64 {
first = this.operands.length as u32;
this.operands.resize(this.operands.length + args.length);
}
for i in 0..args.length {
this.operands[first as u64 + i] = args[i];
}
this.insts[index].kind = kind;
this.insts[index].args = first;
this.insts[index].argc = args.length as u32;
this.insts[index].aux = aux;
this.insts[index].imm = imm;
}
#! Makes an instruction the constant word it gives.
#! @param this The code.
#! @param index The instruction.
#! @param bits The word's bits.
pub def code::become_word(&mut this, index: u32, bits: u64): void {
this.become(index, op::iconst, span::<u32>::empty(), 0, bits);
this.origins[this.insts[index].result].kind = vt::word;
}
#! Makes an instruction the constant real it gives.
#! @param this The code.
#! @param index The instruction.
#! @param bits The bits of the `f64` it is.
pub def code::become_real(&mut this, index: u32, bits: u64): void {
this.become(index, op::fconst, span::<u32>::empty(), 0, bits);
}
#! Adds an instruction, in no block yet.
#! @param this The code.
#! @param kind What it does.
#! @param args Its operands.
#! @param gives The types of its results, in order.
#! @param aux What its kind says `aux` holds.
#! @param imm What its kind says `imm` holds.
#! @param pos Where in the source it is from.
#! @param site One more than the site of the function it was inlined from,
#! or 0.
#! @returns Its index.
pub def code::detached(
&mut this,
kind: op,
args: span<u32>,
gives: span<vt>,
aux: u32,
imm: u64,
pos: u64,
site: u32
): u32 {
val index := this.insts.length as u32;
val first := this.operands.length as u32;
# Appended one by one, which is inlined, where `extend` is a call for each
# instruction.
for &each in args {
this.operands.append(each);
}
val result := this.origins.length as u32;
for i in 0..gives.length {
this.origins.append(origin { kind = gives[i], from = index, index = i as u32 });
}
this.insts.append(inst {
kind = kind,
count = gives.length as u8,
aux = aux,
imm = imm,
args = first,
argc = args.length as u32,
result = gives.length == 0 ? 0 : result,
at = pos,
site = site
});
return index;
}
#! Puts an instruction made in no block before another in its block.
#! @param this The code.
#! @param index The instruction.
#! @param before The instruction it goes before.
pub def code::link_before(&mut this, index: u32, before: u32): void {
val block: u32 = this.insts[before].block;
val prior := this.before(before);
this.insts[index].block = block;
this.insts[index].next = before;
if prior == 0 {
this.blocks[block].first = index;
} else {
this.insts[prior].next = index;
}
}
#! The instruction before another in its block.
#! @param this The code.
#! @param index The instruction, which its block holds.
#! @returns The instruction before it, or 0 where it is the first.
pub def code::before(&this, index: u32): u32 {
var prior: u32 = 0;
var walk := this.walk(this.insts[index].block);
while walk.more() {
val at := walk.next();
break if at == index;
prior = at;
}
return prior;
}
#! Puts an instruction made in no block after another in its block.
#! @param this The code.
#! @param index The instruction.
#! @param after The instruction it goes after.
pub def code::link_after(&mut this, index: u32, after: u32): void {
val block: u32 = this.insts[after].block;
this.insts[index].block = block;
this.insts[index].next = this.insts[after].next;
this.insts[after].next = index;
if this.blocks[block].last == after {
this.blocks[block].last = index;
}
}
#! A constant word, made first in the entry, where it stands before everything
#! that may read it.
#! @param this The code.
#! @param bits Its bits.
#! @returns The value.
pub def code::word_value(&mut this, bits: u64): u32 {
var gives: vt[1] = [vt::word];
val index := this.detached(op::iconst, span::<u32>::empty(), gives[0:1], 0, bits, 0, 0);
this.put_first(0, index);
return this.insts[index].result;
}
#! A constant real, made first in the entry.
#! @param this The code.
#! @param bits The bits of the `f64` it is.
#! @returns The value.
pub def code::real_value(&mut this, bits: u64): u32 {
var gives: vt[1] = [vt::real];
val index := this.detached(op::fconst, span::<u32>::empty(), gives[0:1], 0, bits, 0, 0);
this.put_first(0, index);
return this.insts[index].result;
}
#! The zero of a type of value, made first in the entry: the word 0, the real
#! 0, or a vector of zero bytes.
#! @param this The code.
#! @param kind The type.
#! @returns The value.
pub def code::zero_value(&mut this, kind: vt): u32 {
return this.real_value(0) if kind == vt::real;
return this.word_value(0) if !kind.lanes();
var gives: vt[1] = [kind];
val index := this.detached(op::vzero, span::<u32>::empty(), gives[0:1], 0, 0, 0, 0);
this.put_first(0, index);
return this.insts[index].result;
}
#! The zero of each type of value a pass asks for, each made once, as
#! `code::zero_value` makes it.
pub struct zero_values {
var held: u32[vt::count as u64]; #! The zero of each type made, or 0.
}
#! The zero of a type of value, made first in the entry the first time it is
#! asked for.
#! @param this The zeros.
#! @param body The code.
#! @param kind The type.
#! @returns The value.
pub def zero_values::of(&mut this, body: &mut code, kind: vt): u32 {
val at := kind as u64;
if this.held[at] == 0 {
this.held[at] = body.zero_value(kind);
}
return this.held[at];
}
#! Takes an edge out of the edges into its block.
#! @param this The code.
#! @param edge The edge.
pub def code::drop_pred(&mut this, edge: u32): void {
this.forget_order();
val target: u32 = this.edges[edge].target;
var kept := ids {};
for &each in this.blocks[target].preds {
if each != edge {
kept.append(each);
}
}
this.blocks[target].preds = move(&mut kept);
}
#! Takes out the parameters of a block that do not stay, with the argument each
#! edge into the block gives them, numbering those left in the order they were.
#! @param this The code.
#! @param block The block.
#! @param keeps Whether each of its parameters stays, by its position.
pub def code::drop_params(&mut this, block: u32, keeps: span<bool>): void {
var kept := ids {};
for p in 0..keeps.length {
continue if !keeps[p];
val param: u32 = this.blocks[block].params[p];
this.origins[param].index = kept.length as u32;
kept.append(param);
}
for &edge in this.blocks[block].preds.view() {
var args := ids {};
for p in 0..keeps.length {
if keeps[p] {
args.append(this.edges[edge].args[p]);
}
}
this.edges[edge].args = move(&mut args);
}
this.blocks[block].params = move(&mut kept);
}
#! Makes an instruction ending a block go along one of its edges only, as a
#! `jump`, taking the others out of the blocks they went to.
#! @param this The code.
#! @param index The instruction.
#! @param kept The edge it goes along.
pub def code::jump_only(&mut this, index: u32, kept: u32): void {
this.forget_order();
var outs := this.edges_of(index);
while outs.more() {
val edge := outs.next();
if edge != kept {
this.drop_pred(edge);
}
}
this.become(index, op::jump, span::<u32>::empty(), kept, 0);
}
#! Swaps where a `branch` goes, so it goes where it went where its condition
#! was zero where it is not, as a branch on a condition's opposite does.
#! @param this The code.
#! @param index The `branch`.
pub def code::swap_branch(&mut this, index: u32): void {
this.forget_order();
val one: u32 = this.insts[index].aux;
val two := one + 1;
val first: u32 = this.edges[one].target;
val second: u32 = this.edges[two].target;
var args := move(&mut this.edges[one].args);
this.edges[one].args = move(&mut this.edges[two].args);
this.edges[two].args = move(&mut args);
this.edges[one].target = second;
this.edges[two].target = first;
return if first == second;
for i in 0..this.blocks[first].preds.length {
if this.blocks[first].preds[i] == one {
this.blocks[first].preds[i] = two;
}
}
for i in 0..this.blocks[second].preds.length {
if this.blocks[second].preds[i] == two {
this.blocks[second].preds[i] = one;
}
}
}
#! How many instructions the code holds, in the blocks not removed.
#! @param this The code.
#! @returns How many.
pub def code::size(&this): u32 {
var count: u32 = 0;
var walk := this.walk_all();
while walk.more() {
walk.next();
count++;
}
return count;
}
File diff suppressed because it is too large. Load diff
+985
View File
@@ -0,0 +1,985 @@
#! @file loops.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the ninth pass of the optimizer, which works on loops. A loop is
#! natural: its header dominates each block whose edge goes back to it, and it
#! holds the blocks from which those are reached without passing the header.
#!
#! A loop whose header asks whether to go round again, where no block going
#! back to it asks so too, is rotated: the header's code is copied into a guard
#! before the loop, which goes into it or past it as the header would have the
#! first time, and the header itself moves to the bottom, asking each time
#! round whether to go round again. Its edge back to the block after it is then
#! the loop's only jump. What the header made and the loop read is what the
#! block after it takes, from the guard's copy or from the header, as is what
#! it made and code past the loop read, where that is past the way out.
#!
#! Then what each loop works out the same each time round moves into the block
#! before it, its preheader, which is made where the loop has none: what only
#! works out its value from what is made outside the loop, and cannot stop the
#! program; a read of memory nothing in the loop may write, as alias analysis
#! tells, through an address read or written through, or checked, before the
#! loop; and a check of what is made outside the loop, or such a read through
#! an address that may be null, where it runs each time the loop is gone into
#! before anything the program would be seen to do in it, so that it stops the
#! program where it would have, and only where the loop is gone into. Inner
#! loops go first, so what moves out of one may move out of the loop holding it
#! in turn.
import std::containers;
module sakura::compiler;
#! What stands for no loop.
const no_loop: u32 = 0xFFFFFFFF;
#! The most instructions a header copied into a guard may hold, but for its
#! constants and the branch ending it.
const rotate_limit: u32 = 12;
#! The most loops of one function rotated, past which the rest stay as they
#! are.
const rotate_most: u32 = 256;
#! The natural loops of code. Two loops hold no block in common, or one holds
#! the other.
struct loop_nest {
var headers: vector<u32>; #! The block heading each loop, those holding fewer blocks first, so each comes before the loops holding it.
var parents: vector<u32>; #! The loop most nearly holding each loop, or `no_loop`.
var members: runs<u32>; #! The blocks of the loops, a run each, its header first.
var runs_of: vector<u32>; #! The run of `members` holding each loop's blocks.
var inner: vector<u32>; #! The loop most nearly holding each block, by block, or `no_loop`.
}
#! Whether a loop holds a block.
#! @param this The loops.
#! @param loop The loop.
#! @param block The block, which may be newer than the loops, and so in none.
#! @returns Whether it does.
def loop_nest::holds(&this, loop: u32, block: u32): bool {
var at: u32 = (block as u64) < this.inner.length ? this.inner[block] : no_loop;
# A loop holding another comes after it.
while at != no_loop && at <= loop {
return true if at == loop;
at = this.parents[at];
}
return false;
}
#! Which block dominates which, and the natural loops, as a pass over loops
#! asks of them.
struct loop_view {
var order: vector<u32>; #! The blocks in reverse postorder.
var number: vector<u32>; #! Each block's place in that order.
var idom: vector<u32>; #! The immediate dominator of each block.
var first: vector<u32>; #! The first block each block immediately dominates, or `no_block`.
var after: vector<u32>; #! The next block the immediate dominator of each immediately dominates, or `no_block`.
var nest: loop_nest; #! The natural loops.
}
#! A value a header makes that is read outside it, which rotating has read
#! what stands for it there.
struct header_read {
var place: u64; #! Where it is read: an operand's place among the code's operands, or an argument's among its edge's.
var edge: u32; #! The edge whose argument it is, or `no_block` for an operand.
var slot: u32; #! Which of the values the header makes it is.
var past: bool; #! Whether it is read past the way out of the loop, rather than past the way in.
}
#! Optimizes the loops of a function's code, knowing what each call writes
#! what it returns to.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether anything changed.
def lowerer::optimize_loops(&mut this, index: u32): bool {
val writes := this.result_writes(index);
return this.program.functions[index].body.optimize_loops(writes.view());
}
#! Optimizes the loops of the code, as the file says: rotating each that may
#! be, then moving out of each what it works out the same each time round.
#! @param this The code.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @returns Whether anything changed.
pub def code::optimize_loops(&mut this, writes: span<u64>): bool {
# Rotating a loop changes which block dominates which, so the loops are
# found again after each, but after the last that may rotate. A loop found
# not to rotate is not asked again. Code found to have no loops has nothing
# to move out of them either.
var refused := vector::<bool>::new(scratch());
var rotated: u32 = 0;
var looped := true;
var last := false;
while rotated < rotate_most && !last {
refused.resize(this.blocks.length);
val point := mark_scratch();
val more := this.rotate_one(&mut refused, &mut looped, &mut last);
release_scratch(point);
break if !more;
rotated++;
}
return rotated != 0 if !looped;
return this.hoist_invariants(writes) || rotated != 0;
}
#! Finds which block dominates which, and the natural loops, from the order
#! and dominators the code keeps where it keeps them.
#! @param this The code.
#! @returns What was found, in scratch memory.
def code::view_loops(&mut this): loop_view {
var made := loop_view {
order = vector::<u32>::new(scratch()),
number = vector::<u32>::new(scratch()),
idom = vector::<u32>::new(scratch()),
first = vector::<u32>::new(scratch()),
after = vector::<u32>::new(scratch())
};
this.block_order(&mut made.order, &mut made.number);
made.idom = this.block_dominators();
made.first.resize(this.blocks.length, no_block);
made.after.resize(this.blocks.length, no_block);
var k := made.order.length;
while k > 1 {
k--;
val block: u32 = made.order[k];
val parent: u32 = made.idom[block];
made.after[block] = made.first[parent];
made.first[parent] = block;
}
made.nest = this.find_loops(made.order.view(), made.number.view(), &made.idom);
return made;
}
#! Finds the natural loops of the code: each block an edge goes back to from a
#! block it dominates heads one, holding the blocks from which those edges are
#! reached without passing it.
#! @param this The code.
#! @param order The blocks in reverse postorder.
#! @param number Each block's place in that order.
#! @param idom The immediate dominator of each block.
#! @returns The loops, in scratch memory.
pub def code::find_loops(&this, order: span<u32>, number: span<u32>, idom: &vector<u32>): loop_nest {
var nest := loop_nest {
headers = vector::<u32>::new(scratch()),
parents = vector::<u32>::new(scratch()),
members = runs::<u32>::new(scratch()),
runs_of = vector::<u32>::new(scratch()),
inner = vector::<u32>::new(scratch())
};
nest.inner.resize(this.blocks.length, no_loop);
# Where no edge goes to a block at or before the block it leaves in the
# order, none goes back, and there is no loop.
var back := false;
for &block in order {
for &edge in this.blocks[block].preds {
val from := this.edge_source(edge);
back = back || (number[from] != 0xFFFFFFFF && number[from] >= number[block]);
}
}
return nest if !back;
# Each loop as it is found, its header first among its blocks, in the order
# the headers are in.
var heads := vector::<u32>::new(scratch());
var found := vector::<u32>::new(scratch());
var marks := stamped_set::new(this.blocks.length, scratch());
var todo := vector::<u32>::new(scratch());
for &block in order {
var any := false;
marks.next_round();
for &edge in this.blocks[block].preds {
val from := this.edge_source(edge);
continue if number[from] == 0xFFFFFFFF || number[from] < number[block] || !dominates(idom, block, from);
if !any {
any = true;
marks.put(block);
nest.members.push(block);
}
if marks.insert(from) {
nest.members.push(from);
todo.append(from);
}
}
continue if !any;
while todo.length != 0 {
val at: u32 = todo.last();
todo.truncate();
for &edge in this.blocks[at].preds {
val back := this.edge_source(edge);
if number[back] != 0xFFFFFFFF && marks.insert(back) {
nest.members.push(back);
todo.append(back);
}
}
}
heads.append(block);
found.append(nest.members.end());
}
# The loops holding fewer blocks first, then in the order found, so each
# comes before those holding it. The largest first, each says which it is
# most nearly held by, as the loop holding its header is then.
var keys := vector::<u64>::new(scratch());
for i in 0..heads.length {
keys.append(pair_key(nest.members.length(found[i]) as u32, i as u32));
}
keys.sort();
for &key in keys {
nest.headers.append(heads[pair_low(key)]);
nest.runs_of.append(found[pair_low(key)]);
}
val count := nest.headers.length;
nest.parents.resize(count, no_loop);
var k := count;
while k > 0 {
k--;
nest.parents[k] = nest.inner[nest.headers[k]];
for &block in nest.members.view(nest.runs_of[k]) {
nest.inner[block] = k as u32;
}
}
return nest;
}
# Rotation.
#! Rotates the first loop that may be rotated, innermost loops first.
#! @param this The code.
#! @param refused Whether each block heads a loop found not to rotate.
#! @param looped Where whether the code has any loop is written.
#! @param last Where whether no other loop may rotate is written.
#! @returns Whether one was.
def code::rotate_one(&mut this, refused: &mut vector<bool>, looped: &mut bool, last: &mut bool): bool {
val view := this.view_loops();
looped = view.nest.headers.length != 0;
for k in 0..view.nest.headers.length {
val header: u32 = view.nest.headers[k];
continue if refused[header];
if this.rotate(&view, k as u32) {
this.forget_order();
# The loop rotated is headed by the block after its header now, which
# does not rotate: it only jumps on, or the header, going back to it,
# leaves the loop too. So where every other loop was found not to
# rotate, none may.
var others := false;
for j in 0..view.nest.headers.length {
others = others || (j != k && !refused[view.nest.headers[j]]);
}
last = !others;
return true;
}
refused[header] = true;
}
return false;
}
#! Rotates a loop, as the file says, where its header asks whether to go round
#! again, no edge back into it is from a block asking so too, as each is once
#! the loop is rotated, and it holds few instructions. Each value the header
#! makes that is read outside it must be read where the block after it in the
#! loop dominates, or where the block it leaves to does, every edge into which
#! is then from the header or from where the block after it dominates.
#! @param this The code.
#! @param view Which block dominates which, and the loops.
#! @param loop The loop.
#! @returns Whether it was rotated.
def code::rotate(&mut this, view: &loop_view, loop: u32): bool {
val nest := &view.nest;
val header: u32 = nest.headers[loop];
val last: u32 = this.blocks[header].last;
return false if last == 0 || this.insts[last].kind != op::branch;
val one: u32 = this.insts[last].aux;
val first_in := nest.holds(loop, this.edges[one].target);
return false if first_in == nest.holds(loop, this.edges[one + 1].target);
val stay := first_in ? one : one + 1;
val leave := first_in ? one + 1 : one;
val into: u32 = this.edges[stay].target;
val out: u32 = this.edges[leave].target;
return false if into == header;
for &edge in this.blocks[header].preds {
val from := this.edges[edge].from;
continue if !nest.holds(loop, this.insts[from].block);
var outs := this.edges_of(from);
while outs.more() {
return false if !nest.holds(loop, this.edges[outs.next()].target);
}
}
var size: u32 = 0;
var sized := this.walk(header);
while sized.more() {
val at := sized.next();
val kind := this.insts[at].kind;
continue if at == last || kind == op::iconst || kind == op::fconst;
size++;
return false if size > rotate_limit;
}
# The values the header makes, its parameters first, each one more than its
# slot among them by value. Its constants go into the entry, where both it
# and the guard read them.
var slots := vector::<u32>::new(scratch());
slots.resize(this.origins.length);
var made := vector::<u32>::new(scratch());
for &param in this.blocks[header].params {
made.append(param);
slots[param] = made.length as u32;
}
var walk := this.walk(header);
while walk.more() {
val held: inst = this.insts[walk.next()];
continue if held.kind.made_anywhere();
for r in 0..held.count {
made.append(held.result + r as u32);
slots[held.result + r as u32] = made.length as u32;
}
}
# Where each is read outside the header, and whether past the way in or out:
# within what the header dominates, as what reads a value is.
var reads := vector::<header_read>::new(scratch());
var inside := vector::<bool>::new(scratch());
var past := vector::<bool>::new(scratch());
inside.resize(made.length);
past.resize(made.length);
var below := vector::<u32>::new(scratch());
var child: u32 = view.first[header];
while child != no_block {
below.append(child);
child = view.after[child];
}
var next_below: u64 = 0;
while next_below < below.length {
val b: u32 = below[next_below];
next_below++;
child = view.first[b];
while child != no_block {
below.append(child);
child = view.after[child];
}
var side: u8 = 0;
var each := this.walk(b);
while each.more() {
val at := each.next();
val held: inst = this.insts[at];
for i in 0..held.argc {
val place := held.args as u64 + i as u64;
val slot: u32 = slots[this.operands[place]];
continue if slot == 0;
side = side == 0 ? this.side_of(view, into, out, b) : side;
return false if side == 3;
reads.append(header_read { place = place, edge = no_block, slot = slot - 1, past = side == 2 });
}
}
# Only the last instruction of a block leaves it by edges.
var outs := this.edges_of(this.blocks[b].last);
while outs.more() {
val edge := outs.next();
for a in 0..this.edges[edge].args.length {
val slot: u32 = slots[this.edges[edge].args[a]];
continue if slot == 0;
side = side == 0 ? this.side_of(view, into, out, b) : side;
return false if side == 3;
reads.append(header_read { place = a, edge = edge, slot = slot - 1, past = side == 2 });
}
}
}
var any_past := false;
for &read in reads {
if read.past {
past[read.slot] = true;
any_past = true;
} else {
inside[read.slot] = true;
}
}
# The block left to takes what the header made where it is read past it,
# which each edge into it gives: the header, and the guard's copy, and from
# within the loop, what the block after the header took.
var exits := this.blocks[out].preds.copied(scratch());
val leaving := this.edges[leave].args.copied(scratch());
val staying := this.edges[stay].args.copied(scratch());
if any_past {
for &edge in exits {
continue if edge == leave;
return false if !dominates(&view.idom, into, this.edge_source(edge));
for s in 0..made.length {
inside[s] = inside[s] || past[s];
}
}
}
# The block after the header in the loop takes what the loop reads of what
# the header made; where other edges go into it too, a block of its own,
# going on to it, does.
var after := into;
var given := vector::<u32>::new(scratch());
if this.blocks[into].preds.length != 1 {
after = this.add_block();
for p in 0..this.blocks[into].params.length {
given.append(this.add_param(after, this.type_of(this.blocks[into].params[p])));
}
}
var taken := vector::<u32>::new(scratch());
taken.resize(made.length);
var left := vector::<u32>::new(scratch());
left.resize(made.length);
for s in 0..made.length {
if inside[s] {
taken[s] = this.add_param(after, this.type_of(made[s]));
}
if past[s] {
left[s] = this.add_param(out, this.type_of(made[s]));
}
}
for &edge in exits {
for s in 0..made.length {
continue if !past[s];
val given_out: u32 = edge == leave ? made[s] : taken[s];
this.edges[edge].args.append(given_out);
}
}
# The header's constants go first in the entry.
var prior: u32 = 0;
var moving := this.walk(header);
while moving.more() {
val at := moving.next();
if !this.insts[at].kind.made_anywhere() {
prior = at;
continue;
}
if prior == 0 {
this.blocks[header].first = this.insts[at].next;
} else {
this.insts[prior].next = this.insts[at].next;
}
this.put_first(0, at);
}
# The guard takes what the header took from outside the loop, and copies its
# code, each copy reading the copies of what the header made. Where one edge
# goes into the loop, the guard reads what it gives instead.
val guard := this.add_block();
var copies := vector::<u32>::new(scratch());
copies.resize(made.length);
var entries := vector::<u32>::new(scratch());
for &edge in this.blocks[header].preds {
if !nest.holds(loop, this.edge_source(edge)) {
entries.append(edge);
}
}
for p in 0..this.blocks[header].params.length {
if entries.length == 1 {
copies[p] = this.edges[entries[0]].args[p];
} else {
copies[p] = this.add_param(guard, this.type_of(this.blocks[header].params[p]));
}
}
for &edge in entries {
this.drop_pred(edge);
this.edges[edge].target = guard;
this.blocks[guard].preds.append(edge);
if entries.length == 1 {
this.edges[edge].args.clear();
}
}
var pairs := vector::<u64>::new(scratch());
var args := vector::<u32>::new(scratch());
var types := vector::<vt>::new(scratch());
var copying := this.walk(header);
while copying.more() {
val at := copying.next();
break if at == last;
val from: inst = this.insts[at];
args.clear();
for i in 0..from.argc {
args.append(copy_of_read(&slots, &copies, this.arg(at, i as u32)));
}
types.clear();
for r in 0..from.count {
types.append(this.type_of(from.result + r as u32));
}
val copy := this.append(guard, from.kind, args.view(), types.view(), from.aux, from.imm, from.at);
this.insts[copy].site = from.site;
for r in 0..from.count {
copies[slots[from.result + r as u32] - 1] = this.insts[copy].result + r as u32;
}
pairs.append(pair_key(at, copy));
}
# The guard goes into the loop through a preheader, or out as the header
# would have the first time.
val pre := this.add_block();
var cond: u32[1] = [copy_of_read(&slots, &copies, this.arg(last, 0))];
val test := this.append(guard, op::branch, cond[0:1], span::<vt>::empty(), 0, 0, this.insts[last].at);
this.insts[test].site = this.insts[last].site;
val first := this.add_edge(test, first_in ? pre : out, 0);
this.add_edge(test, first_in ? out : pre, 0);
this.insts[test].aux = first;
val past_guard := first_in ? first + 1 : first;
for &each in leaving {
this.edges[past_guard].args.append(copy_of_read(&slots, &copies, each));
}
for s in 0..made.length {
if past[s] {
this.edges[past_guard].args.append(copies[s]);
}
}
val jump := this.append(pre, op::jump, span::<u32>::empty(), span::<vt>::empty(), 0, 0, this.insts[last].at);
this.insts[jump].site = this.insts[last].site;
val going := this.add_edge(jump, after, 0);
this.insts[jump].aux = going;
for &each in staying {
this.edges[going].args.append(copy_of_read(&slots, &copies, each));
}
# The header, now the bottom of the loop, gives the block after it what it
# made.
if after != into {
this.drop_pred(stay);
this.edges[stay].target = after;
this.blocks[after].preds.append(stay);
val on := this.append(after, op::jump, span::<u32>::empty(), span::<vt>::empty(), 0, 0, this.insts[last].at);
this.insts[on].site = this.insts[last].site;
val edge := this.add_edge(on, into, 0);
this.insts[on].aux = edge;
for &each in given {
this.edges[edge].args.append(each);
}
}
for s in 0..made.length {
if inside[s] {
this.edges[stay].args.append(made[s]);
this.edges[going].args.append(copies[s]);
}
}
# What read what the header made reads what stands for it.
for &read in reads {
val value: u32 = read.past ? left[read.slot] : taken[read.slot];
if read.edge == no_block {
this.operands[read.place] = value;
} else {
var held := this.edges[read.edge].args.slice();
held[read.place] = value;
}
}
this.rebind_rotated(view, header, guard, into, out, &slots, &copies, &taken, &left, pairs.view());
return true;
}
#! Whether an operation makes a constant, or the address of a cell, a global,
#! or a datum, which may be made anywhere, and which constant hoisting moves
#! out of loops into the entry.
#! @param this The operation.
#! @returns Whether it does.
def op::made_anywhere(&this): bool {
return match this {
op::iconst, op::fconst, op::cell, op::global, op::datum => true,
else => false
};
}
#! Which side of a loop being rotated a block reading what its header made is.
#! @param this The code.
#! @param view Which block dominates which, and the loops.
#! @param into The block after the header in the loop.
#! @param out The block the header leaves the loop to.
#! @param block The block.
#! @returns 1 where the block after the header dominates it, 2 where the block
#! left to does, and 3 where neither does.
def code::side_of(&this, view: &loop_view, into: u32, out: u32, block: u32): u8 {
return 1 if dominates(&view.idom, into, block);
return 2 if dominates(&view.idom, out, block);
return 3;
}
#! What the guard's copy of a header reads where the header read a value: the
#! copy of what the header made, or the value itself.
#! @param slots One more than each value's slot among those the header
#! made, or 0.
#! @param copies The guard's copy of each value the header made.
#! @param value The value.
#! @returns The value read.
def copy_of_read(slots: &vector<u32>, copies: &vector<u32>, value: u32): u32 {
return value if value as u64 >= slots.length || slots[value] == 0;
return copies[slots[value] - 1];
}
#! Binds the variables a rotated loop's header bound in the guard too, to the
#! copies, and those bound where the parameters standing for what the header
#! made are read, to those parameters.
#! @param this The code.
#! @param view Which block dominated which before the loop was rotated.
#! @param header The header.
#! @param guard The guard.
#! @param into The block after the header in the loop.
#! @param out The block the header leaves the loop to.
#! @param slots One more than each value's slot among those the header
#! made, or 0.
#! @param copies The guard's copy of each value the header made.
#! @param taken What the block after the header takes for each, or 0.
#! @param left What the block left to takes for each, or 0.
#! @param pairs Each instruction of the header with its copy, as
#! `pair_key(instruction, copy)`.
def code::rebind_rotated(
&mut this,
view: &loop_view,
header: u32,
guard: u32,
into: u32,
out: u32,
slots: &vector<u32>,
copies: &vector<u32>,
taken: &vector<u32>,
left: &vector<u32>,
pairs: span<u64>
): void {
val count := this.bindings.length;
for i in 0..count {
val each: binding = this.bindings[i];
continue if each.block == no_block || each.block as u64 >= view.idom.length || this.blocks[each.block].gone;
if each.block == header {
var copy: binding = each;
copy.block = guard;
copy.value = copy_of_read(slots, copies, each.value);
copy.after = 0;
for &pair in pairs {
if pair_high(pair) == each.after {
copy.after = pair_low(pair);
}
}
this.bindings.append(copy);
continue;
}
continue if each.value as u64 >= slots.length || slots[each.value] == 0;
val slot := slots[each.value] - 1;
if taken[slot] != 0 && dominates(&view.idom, into, each.block) {
this.bindings[i].value = taken[slot];
} else if left[slot] != 0 && dominates(&view.idom, out, each.block) {
this.bindings[i].value = left[slot];
}
}
}
# Hoisting.
#! What moving out of loops knows of the code as it goes.
struct hoisting {
var reached: hashset<u64>; #! Each address read or written through, or checked not null, with the block it is so in, as `pair_key(address, block)`.
var moved: stamped_set; #! The instructions moved out of the loop worked on, a round each loop.
var aliases: aliases; #! What may write what.
var writers: vector<writing>; #! What each instruction writing memory in the loop worked on writes.
var before: u32; #! The block most nearly dominating the loop's header.
}
#! Moves what each loop works out the same each time round into its
#! preheader, inner loops first, as the file says. A loop with something to
#! move but no block before it that only jumps into it is given one first.
#! @param this The code.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @returns Whether anything moved.
def code::hoist_invariants(&mut this, writes: span<u64>): bool {
var view := this.view_loops();
return false if view.nest.headers.length == 0;
var state := hoisting {
reached = this.reached_addresses(&view),
moved = stamped_set::new(this.insts.length + view.nest.headers.length, scratch()),
aliases = this.aliases(writes, view.idom.view()),
writers = vector::<writing>::new(scratch())
};
var made := false;
for k in 0..view.nest.headers.length {
continue if this.preheader_of(&view, k as u32) != no_block;
continue if !this.hoist_loop(&view, k as u32, no_block, &mut state);
this.make_preheader(&view, k as u32);
made = true;
}
if made {
this.forget_order();
view = this.view_loops();
state.aliases = this.aliases(writes, view.idom.view());
}
var changed := false;
for k in 0..view.nest.headers.length {
val pre := this.preheader_of(&view, k as u32);
continue if pre == no_block;
changed = this.hoist_loop(&view, k as u32, pre, &mut state) || changed;
}
return changed;
}
#! Every address read or written through, or checked not null, with the block
#! it is so in, of those a read within a loop reads through, which are all that
#! is asked of. Reaching through null stops the program, so an address so in a
#! block dominating another is not null there. An instruction moving moves to
#! a block dominating the one it was in, where it is so still.
#! @param this The code.
#! @param view Which block dominates which, and the loops.
#! @returns Each, as `pair_key(address, block)`, in scratch memory.
def code::reached_addresses(&this, view: &loop_view): hashset<u64> {
var made := hashset::<u64>::new(scratch());
var asked := vector::<bool>::new(scratch());
asked.resize(this.origins.length);
var any := false;
for &block in view.order {
continue if view.nest.inner[block] == no_loop;
var inside := this.walk(block);
while inside.more() {
val at := inside.next();
if this.insts[at].kind == op::load {
asked[this.arg(at, 0)] = true;
any = true;
}
}
}
return made if !any;
var walk := this.walk_all();
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
val sized := (held.kind == op::copy || held.kind == op::clear) && held.imm != 0;
if (held.kind == op::load || held.kind == op::store || sized
|| (held.kind == op::check && held.aux == fault::null_reference as u32)) && asked[this.arg(at, 0)] {
made.insert(pair_key(this.arg(at, 0), held.block));
}
if held.kind == op::copy && sized && asked[this.arg(at, 1)] {
made.insert(pair_key(this.arg(at, 1), held.block));
}
}
return made;
}
#! Whether an address is not null where a block ends: it is never zero, or is
#! read or written through, or checked, in that block or one dominating it.
#! @param this The code.
#! @param view Which block dominates which, and the loops.
#! @param reached Each address read or written through, or checked, with
#! the block it is so in.
#! @param address The address.
#! @param block The block.
#! @returns Whether it is.
def code::reached_before(&this, view: &loop_view, reached: &hashset<u64>, address: u32, block: u32): bool {
return true if this.never_zero(address);
val home := this.home_of(address);
var at := block;
var steps := 0;
while steps < 64 && at != no_block && (at as u64) < view.idom.length {
val key := pair_key(address, at);
return true if reached.contains(&key);
return false if at == home || at == 0;
at = view.idom[at];
steps++;
}
return false;
}
#! The preheader of a loop: the one block outside it going into its header,
#! where that block only jumps there.
#! @param this The code.
#! @param view Which block dominates which, and the loops.
#! @param loop The loop.
#! @returns The block, or `no_block` where the loop has none.
def code::preheader_of(&this, view: &loop_view, loop: u32): u32 {
val header: u32 = view.nest.headers[loop];
var found := no_block;
for &edge in this.blocks[header].preds {
val from := this.edge_source(edge);
continue if view.nest.holds(loop, from);
return no_block if found != no_block;
found = from;
}
return no_block if found == no_block || this.insts[this.blocks[found].last].kind != op::jump;
return found;
}
#! Makes a preheader for a loop: a block taking what its header took from
#! outside it, every edge from outside going there, which jumps into the
#! header giving it that.
#! @param this The code.
#! @param view Which block dominates which, and the loops.
#! @param loop The loop.
def code::make_preheader(&mut this, view: &loop_view, loop: u32): void {
val header: u32 = view.nest.headers[loop];
val pre := this.add_block();
var given := vector::<u32>::new(scratch());
for p in 0..this.blocks[header].params.length {
given.append(this.add_param(pre, this.type_of(this.blocks[header].params[p])));
}
var entries := vector::<u32>::new(scratch());
for &edge in this.blocks[header].preds {
if !view.nest.holds(loop, this.edge_source(edge)) {
entries.append(edge);
}
}
for &edge in entries {
this.drop_pred(edge);
this.edges[edge].target = pre;
this.blocks[pre].preds.append(edge);
}
val first: u32 = this.blocks[header].first;
val jump := this.append(pre, op::jump, span::<u32>::empty(), span::<vt>::empty(), 0, 0, this.insts[first].at);
this.insts[jump].site = this.insts[first].site;
val edge := this.add_edge(jump, header, 0);
this.insts[jump].aux = edge;
for &each in given {
this.edges[edge].args.append(each);
}
}
#! Moves what a loop works out the same each time round into its preheader, in
#! the order the loop worked it out, or only finds whether anything would move.
#! The blocks running first each time the loop is gone into, its header and
#! each a jump goes on to in turn, run what may stop the program before
#! anything the program would be seen to do, until one of those that does not
#! move.
#! @param this The code.
#! @param view Which block dominates which, and the loops.
#! @param loop The loop.
#! @param pre The preheader, or `no_block` to only find whether anything
#! would move.
#! @param state What moving out of loops knows.
#! @returns Whether anything moved, or would.
def code::hoist_loop(&mut this, view: &loop_view, loop: u32, pre: u32, state: &mut hoisting): bool {
val nest := &view.nest;
val header: u32 = nest.headers[loop];
var keys := vector::<u64>::new(scratch());
for &block in nest.members.view(nest.runs_of[loop]) {
keys.append(pair_key(view.number[block], block));
}
keys.sort();
state.moved.next_round();
state.before = view.idom[header];
state.writers.clear();
for &key in keys {
var walk := this.walk(pair_low(key));
while walk.more() {
val at := walk.next();
val kind := this.insts[at].kind;
if kind != op::load && (kind.traits() & op_write) != 0 {
state.writers.append(state.aliases.writes_of(this, at));
}
}
}
# The blocks running first, each jumping to the next.
var firsts := vector::<u32>::new(scratch());
var at := header;
while true {
firsts.append(at);
val last: u32 = this.blocks[at].last;
break if this.insts[last].kind != op::jump;
at = this.edges[this.insts[last].aux].target;
break if !nest.holds(loop, at) || firsts.view().contains(&at);
}
var any := false;
var seen := false;
var tail: u32 = 0;
for &key in keys {
val block := pair_low(key);
val first := firsts.view().contains(&block);
var prior: u32 = 0;
var walk := this.walk(block);
while walk.more() {
val index := walk.next();
if this.invariant(index, view, loop, state, first && !seen) {
any = true;
state.moved.put(index);
continue if pre == no_block;
# It leaves its block, and follows what moved before it, but for a
# constant or the address of a cell, a global, or a datum, which goes
# first in the entry, as constant hoisting would put it.
val next: u32 = this.insts[index].next;
if prior == 0 {
this.blocks[block].first = next;
} else {
this.insts[prior].next = next;
}
if this.insts[index].kind.made_anywhere() {
this.put_first(0, index);
continue;
}
if tail == 0 {
this.link_before(index, this.blocks[pre].last);
} else {
this.link_after(index, tail);
}
tail = index;
continue;
}
if first && this.seen_to_run(index, view, state) {
seen = true;
}
prior = index;
}
}
return any;
}
#! Whether an instruction of a loop works out the same each time round and may
#! move into the preheader: everything it reads is made outside the loop, or
#! moves; and it works out only its values, but for a division by zero; it
#! reads memory nothing in the loop writes, through an address not null before
#! the loop, or where it runs first; or it is a check, where it runs first.
#! @param this The code.
#! @param index The instruction.
#! @param view Which block dominates which, and the loops.
#! @param loop The loop.
#! @param state What moving out of loops knows.
#! @param first Whether it runs each time the loop is gone into before
#! anything the program would be seen to do in it.
#! @returns Whether it may.
def code::invariant(&this, index: u32, view: &loop_view, loop: u32, state: &hoisting, first: bool): bool {
val held: inst = this.insts[index];
return false if held.kind.ends() || (held.count == 0 && held.kind != op::check);
for i in 0..held.argc {
val value := this.arg(index, i as u32);
val from := this.defining(value);
continue if from != 0 && state.moved.contains(from);
return false if view.nest.holds(loop, this.home_of(value));
}
return match held.kind {
op::check => first,
op::load => !this.written_in_loop(index, state) && (first || this.reached_before(view, &state.reached, this.arg(index, 0), state.before)),
else => this.removable(index)
};
}
#! Whether anything in the loop worked on may write what a read reads.
#! @param this The code.
#! @param index The `load`.
#! @param state What moving out of loops knows.
#! @returns Whether it may.
def code::written_in_loop(&this, index: u32, state: &hoisting): bool {
return false if state.writers.length == 0;
val place := state.aliases.region_of(this, index, 0);
for &each in state.writers {
return true if state.aliases.touches(this, &each, &place);
}
return false;
}
#! Whether an instruction that does not move does what the program would be
#! seen to do: writing memory, calling, or what may stop the program, as a read
#! through an address that may be null before the loop.
#! @param this The code.
#! @param index The instruction.
#! @param view Which block dominates which, and the loops.
#! @param state What moving out of loops knows.
#! @returns Whether it does.
def code::seen_to_run(&this, index: u32, view: &loop_view, state: &hoisting): bool {
val held := &this.insts[index];
return !this.reached_before(view, &state.reached, this.arg(index, 0), state.before) if held.kind == op::load;
return (held.kind.traits() & (op_traps | op_write)) != 0 && !this.removable(index);
}
+500
View File
@@ -0,0 +1,500 @@
#! @file memory.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the eighth pass of the optimizer, which cleans up what the code does
#! with the memory of its cells, of which building values and inlining leave
#! much. Where each cell is known to hold zero is followed through the blocks,
#! from what the frame zeroes and what the blocks before each leave: clearing
#! what is zero already, or storing zero to it, goes; copying from what is zero
#! clears instead; and reading it reads the zero. A clear whose bytes are all
#! written before anything reads them goes. Then a copy into the memory a
#! function returns, right before it returns, is returned from where it was
#! copied from.
#!
#! A cell whose address goes anywhere but to the instructions reading, writing,
#! copying, and clearing it, or to a call as where to write what it returns, is
#! escaped, as alias analysis finds: anything that may read or write memory the
#! code does not name may read or write it, but for what reaches through an
#! address outside the frame.
module sakura::compiler;
#! The most words of a cell the pass follows, a bit each.
const memory_words: u64 = 64;
#! What stands for a cell the pass does not follow.
const unfollowed: u32 = 0xFFFFFFFF;
#! The most words the ends of the blocks may take, past which no block begins
#! knowing what the blocks before it left.
const memory_ends_limit: u64 = 1048576;
#! What the pass knows of the cells of the code.
struct memory_known {
var addresses: cell_table; #! Which cell each value is the address of.
var escaped: vector<bool>; #! Whether each cell's address goes where it may be read or written without the code saying.
var place: vector<u32>; #! The place of each cell among those followed, or `unfollowed`.
var cells: vector<u32>; #! The cell followed at each place.
var exposed: vector<u32>; #! The places of the escaped cells followed.
var zero: vector<u64>; #! The words known zero of each cell followed, where the walk is, a bit each.
var clears: vector<u32>; #! Of each cell followed, the clear of it nothing has read since, or 0.
var cleared: vector<u64>; #! The words that clear zeroes.
var covered: vector<u64>; #! The words of it written whole since.
var ends: vector<u64>; #! The words known zero where each block ends, a word for each place, block after block.
var walked: vector<bool>; #! Whether each block was walked.
var zeros: zero_values; #! The zero of each type, made once.
}
#! The place among those followed of the cell an address is.
#! @param this What the pass knows.
#! @param value The address.
#! @returns The place, or `unfollowed`.
def memory_known::followed(&this, value: u32): u32 {
val cell := this.addresses.cell(value);
return cell == 0 ? unfollowed : this.place[cell - 1];
}
#! Says a cell was read, so the clear of it nothing had read stays.
#! @param this What the pass knows.
#! @param place The cell's place.
def memory_known::read(&mut this, place: u32): void {
this.clears[place] = 0;
}
#! Says memory the code does not name was read, which may be any escaped cell.
#! @param this What the pass knows.
def memory_known::read_escaped(&mut this): void {
for &k in this.exposed {
this.clears[k] = 0;
}
}
#! Says memory the code does not name was written, which may be any escaped
#! cell, so none is known zero.
#! @param this What the pass knows.
def memory_known::forget_escaped(&mut this): void {
for &k in this.exposed {
this.zero[k] = 0;
}
}
#! Says words of a cell were written whole, taking out the clear of it they
#! write over all of.
#! @param this What the pass knows.
#! @param place The cell's place.
#! @param words The words, a bit each.
#! @param done What the pass changes.
def memory_known::cover(&mut this, place: u32, words: u64, done: &mut rewrite): void {
return if this.clears[place] == 0;
this.covered[place] = this.covered[place] | words;
if (this.covered[place] & this.cleared[place]) == this.cleared[place] {
done.remove(this.clears[place]);
this.clears[place] = 0;
}
}
#! Says a cell was cleared by an instruction that stays.
#! @param this What the pass knows.
#! @param place The cell's place.
#! @param index The clear.
#! @param size How many bytes it clears.
#! @param done What the pass changes.
def memory_known::clear(&mut this, place: u32, index: u32, size: u64, done: &mut rewrite): void {
val whole := whole_words(0, size);
this.cover(place, whole, done);
this.clears[place] = index;
this.cleared[place] = touched_words(0, size);
this.covered[place] = 0;
this.zero[place] = this.zero[place] | whole;
}
#! The words bytes touch, a bit each.
#! @param offset Where they begin.
#! @param size How many there are.
#! @returns The words.
def touched_words(offset: u64, size: u64): u64 {
return 0 if size == 0;
return 0xFFFFFFFFFFFFFFFFu if offset + size > memory_words * word_size;
val first := offset / word_size;
val last := (offset + size - 1) / word_size;
return words_between(first, last + 1);
}
#! The words bytes cover whole, a bit each.
#! @param offset Where they begin.
#! @param size How many there are.
#! @returns The words.
def whole_words(offset: u64, size: u64): u64 {
return 0 if offset + size > memory_words * word_size;
val first := (offset + word_size - 1) / word_size;
val end := (offset + size) / word_size;
return first >= end ? 0 : words_between(first, end);
}
#! The words from one to before another, a bit each.
#! @param first The first.
#! @param end The one after the last.
#! @returns The words.
def words_between(first: u64, end: u64): u64 {
val high := end >= 64 ? 0xFFFFFFFFFFFFFFFFu : (1u << end) - 1;
return high & ~((1u << first) - 1);
}
#! Whether an address is within no cell: a step from a global, a datum, what
#! the program holds on the heap, or an address the function was given, which
#! points outside its frame.
#! @param this The code.
#! @param address The address.
#! @returns Whether it is.
def code::outside_cells(&this, address: u32): bool {
var at := address;
for _ in 0..8 {
val index := this.defining(at);
if index == 0 {
val held: origin = this.origins[at];
return held.param && held.from == 0;
}
match this.insts[index].kind {
op::global, op::datum, op::allocate => return true;
op::add => at = this.arg(index, 0);
else => return false;
}
}
return false;
}
#! Whether a value is a word or real all of whose bits are zero.
#! @param this The code.
#! @param value The value.
#! @returns Whether it is.
def code::zero_bits(&this, value: u32): bool {
var bits: u64 = 1;
val origin: origin = this.origins[value];
return true if !origin.param && this.insts[origin.from].kind == op::vzero;
return (this.word_constant(value, &mut bits) || this.real_constant(value, &mut bits)) && bits == 0;
}
#! Cleans up the memory of the cells, as the file says.
#! @param this The code.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @returns Whether anything changed.
pub def code::clean_memory(&mut this, writes: span<u64>): bool {
return false if this.cells.length == 0;
var state := memory_known {
addresses = this.cell_table(),
escaped = vector::<bool>::new(scratch()),
place = vector::<u32>::new(scratch()),
cells = vector::<u32>::new(scratch()),
exposed = vector::<u32>::new(scratch()),
zero = vector::<u64>::new(scratch()),
clears = vector::<u32>::new(scratch()),
cleared = vector::<u64>::new(scratch()),
covered = vector::<u64>::new(scratch()),
ends = vector::<u64>::new(scratch()),
walked = vector::<bool>::new(scratch())
};
return false if !state.addresses.any;
state.escaped = this.escaped_cells(&state.addresses, writes);
state.place.resize(this.cells.length, unfollowed);
for c in 0..this.cells.length {
continue if this.cells[c].size as u64 > memory_words * word_size;
state.place[c] = state.cells.length as u32;
if state.escaped[c] {
state.exposed.append(state.cells.length as u32);
}
state.cells.append(c as u32);
}
val count := state.cells.length;
state.zero.resize(count);
state.clears.resize(count);
state.cleared.resize(count);
state.covered.resize(count);
var done := rewrite::new();
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.block_order(&mut order, &mut number);
val inherits := count != 0 && this.blocks.length * count <= memory_ends_limit;
if inherits {
state.ends.resize(this.blocks.length * count);
state.walked.resize(this.blocks.length);
}
for &block in order {
continue if count == 0;
this.begin_memory(block, &mut state, inherits);
this.walk_memory(block, &mut state, writes, &mut done);
if inherits {
for k in 0..count {
state.ends[block as u64 * count + k] = state.zero[k];
}
state.walked[block] = true;
}
}
this.apply(&done);
var returns := rewrite::new();
this.forward_returns(&mut returns);
this.apply(&returns);
return done.changed || returns.changed;
}
#! Begins what is known zero where a block begins: every word of each cell the
#! frame zeroes at the entry, and elsewhere what every block going there left,
#! where each was walked.
#! @param this The code.
#! @param block The block.
#! @param state What the pass knows.
#! @param inherits Whether what the blocks before it left is known.
def code::begin_memory(&this, block: u32, state: &mut memory_known, inherits: bool): void {
val count := state.cells.length;
for k in 0..count {
state.zero[k] = 0;
state.clears[k] = 0;
}
val preds := &this.blocks[block].preds;
if block == 0 && preds.length == 0 {
for k in 0..count {
val held: cell = this.cells[state.cells[k]];
if held.kind == ck::temporary || held.kind == ck::local {
state.zero[k] = touched_words(0, held.size as u64);
}
}
return;
}
return if !inherits || preds.length == 0;
for &edge in preds.view() {
return if !state.walked[this.edge_source(edge)];
}
for k in 0..count {
state.zero[k] = 0xFFFFFFFFFFFFFFFFu;
}
for &edge in preds.view() {
val from := this.edge_source(edge) as u64;
for k in 0..count {
state.zero[k] = state.zero[k] & state.ends[from * count + k];
}
}
}
#! Walks the instructions of a block, as the file says.
#! @param this The code.
#! @param block The block.
#! @param state What the pass knows.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @param done What the pass changes.
def code::walk_memory(&mut this, block: u32, state: &mut memory_known, writes: span<u64>, done: &mut rewrite): void {
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
match held.kind {
op::load => this.memory_load(at, &held, state, done);
op::store => this.memory_store(at, &held, state, done);
op::clear => this.memory_clear(at, &held, state, done);
op::copy => this.memory_copy(at, &held, state, done);
else => this.memory_other(at, &held, state, writes, done);
}
}
}
#! Follows a read: of a cell's words known zero, it is that zero.
#! @param this The code.
#! @param index The `load`.
#! @param held The instruction.
#! @param state What the pass knows.
#! @param done What the pass changes.
def code::memory_load(&mut this, index: u32, held: &inst, state: &mut memory_known, done: &mut rewrite): void {
val address := this.arg(index, 0);
if state.addresses.cell(address) == 0 {
if !this.outside_cells(address) {
state.read_escaped();
}
return;
}
val k := state.followed(address);
return if k == unfollowed;
state.read(k);
val words := touched_words(held.imm, (held.aux as access).width());
return if (state.zero[k] & words) != words;
done.replace(held.result, state.zeros.of(this, this.type_of(held.result)));
done.remove(index);
}
#! Follows a write of a word: zero to words known zero goes.
#! @param this The code.
#! @param index The `store`.
#! @param held The instruction.
#! @param state What the pass knows.
#! @param done What the pass changes.
def code::memory_store(&mut this, index: u32, held: &inst, state: &mut memory_known, done: &mut rewrite): void {
val address := this.arg(index, 0);
if state.addresses.cell(address) == 0 {
if !this.outside_cells(address) {
state.forget_escaped();
}
return;
}
val k := state.followed(address);
return if k == unfollowed;
val width := (held.aux as access).width();
val words := touched_words(held.imm, width);
val whole := whole_words(held.imm, width);
if this.zero_bits(this.arg(index, 1)) {
if (state.zero[k] & words) == words {
done.remove(index);
return;
}
state.zero[k] = state.zero[k] | whole;
} else {
state.zero[k] = state.zero[k] & ~words;
}
state.cover(k, whole, done);
}
#! Follows a clear: of words known zero already, it goes.
#! @param this The code.
#! @param index The `clear`.
#! @param held The instruction.
#! @param state What the pass knows.
#! @param done What the pass changes.
def code::memory_clear(&mut this, index: u32, held: &inst, state: &mut memory_known, done: &mut rewrite): void {
val address := this.arg(index, 0);
if state.addresses.cell(address) == 0 {
if !this.outside_cells(address) {
state.forget_escaped();
}
return;
}
val k := state.followed(address);
return if k == unfollowed;
val words := touched_words(0, held.imm);
if (state.zero[k] & words) == words {
done.remove(index);
return;
}
state.clear(k, index, held.imm, done);
}
#! Follows a copy: from words known zero, it clears instead, or goes where what
#! it writes is known zero already.
#! @param this The code.
#! @param index The `copy`.
#! @param held The instruction.
#! @param state What the pass knows.
#! @param done What the pass changes.
def code::memory_copy(&mut this, index: u32, held: &inst, state: &mut memory_known, done: &mut rewrite): void {
val to := this.arg(index, 0);
val from := this.arg(index, 1);
val words := touched_words(0, held.imm);
var zero := false;
if state.addresses.cell(from) == 0 {
if !this.outside_cells(from) {
state.read_escaped();
}
} else {
val s := state.followed(from);
if s != unfollowed {
zero = (state.zero[s] & words) == words;
if !zero {
state.read(s);
}
}
}
if zero {
val d := state.followed(to);
if d != unfollowed && (state.zero[d] & words) == words {
done.remove(index);
return;
}
var args: u32[1] = [to];
this.become(index, op::clear, args[0:1], 0, held.imm);
done.changed = true;
if d != unfollowed {
state.clear(d, index, held.imm, done);
return;
}
}
if state.addresses.cell(to) == 0 {
if !this.outside_cells(to) {
state.forget_escaped();
}
return;
}
val d := state.followed(to);
return if d == unfollowed || zero;
state.zero[d] = state.zero[d] & ~words;
state.cover(d, whole_words(0, held.imm), done);
}
#! Follows any other instruction: one reading or writing memory the code does
#! not name may read or write any escaped cell, and a call writes what it
#! returns to the cell its last operand is.
#! @param this The code.
#! @param index The instruction.
#! @param held The instruction.
#! @param state What the pass knows.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @param done What the pass changes.
def code::memory_other(&mut this, index: u32, held: &inst, state: &mut memory_known, writes: span<u64>, done: &mut rewrite): void {
# What a cell's address is given to may read it, and as an operand write it,
# but for where a call writes what it returns, which is followed below.
val written: u64 = (index as u64) < writes.length ? writes[index] : 0;
var reads := this.reads_of(index);
while reads.more() {
val k := state.followed(reads.next());
continue if k == unfollowed;
val i := reads.operand();
if i == no_operand {
state.read(k);
continue;
}
continue if written != 0 && i + 1 == held.argc;
state.read(k);
state.zero[k] = 0;
}
val traits := held.kind.traits();
if (traits & op_reads) != 0 {
state.read_escaped();
}
if (traits & op_write) != 0 {
state.forget_escaped();
}
if written != 0 {
val k := state.followed(this.arg(index, held.argc - 1));
if k != unfollowed {
state.zero[k] = 0;
state.cover(k, whole_words(0, written), done);
}
}
}
#! Returns from where a copy into the memory a function returns, right before
#! it returns, was copied from.
#! @param this The code.
#! @param done What the pass changes.
def code::forward_returns(&mut this, done: &mut rewrite): void {
return if this.returned == 0;
for b in 0..this.blocks.length {
continue if this.blocks[b].gone;
val last: u32 = this.blocks[b].last;
continue if last == 0 || this.insts[last].kind != op::ret || this.insts[last].argc != 1;
val before := this.before(last);
continue if before == 0 || this.insts[before].kind != op::copy;
val returned := this.arg(last, 0);
val to := this.arg(before, 0);
val from := this.arg(before, 1);
continue if this.insts[before].imm < this.returned as u64 || from == returned;
continue if to != returned && (this.cell_of(to) == no_cell || this.cell_of(to) != this.cell_of(returned));
var args: u32[1] = [from];
this.become(last, op::ret, args[0:1], this.insts[last].aux, this.insts[last].imm);
done.remove(before);
}
}
+186
View File
@@ -0,0 +1,186 @@
#! @file merge.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the merging of the stores filling 16 bytes of a cell into one, of a
#! vector built in a register, which an executable's code is given once it is
#! optimized. A load reading several stores waits until each reaches the cache,
#! where one store of all its bytes is forwarded to it at once, and a struct of
#! four `f32`s or two words, as a `vec3` holding its fourth, is copied out 16
#! bytes at a time, as it is returned: built a field at a time, the copy waited
#! on every field.
#!
#! The 16 bytes from a multiple of 16 in a cell the frame zeroes are merged
#! where every instruction writing them in the code is a store of 4 or 8 bytes,
#! all reals or all words, each in one block, and nothing reads them from the
#! first to the last; what none writes is zero. The cell's address goes only to
#! what reads, writes, copies, clears, and returns it. It is done once nothing
#! more is inlined, so a function copying the code holds its fields as values
#! still, as promoting holds them, and only in an executable's code, which holds
#! vectors.
module sakura::compiler;
#! What merging knows of a write or read of a cell.
struct touch {
var at: u32; #! The instruction.
var offset: u64; #! The first byte.
var size: u64; #! How many bytes.
var writes: bool; #! Whether it writes them.
var how: access; #! For a store, how it writes them; `access::bytes` for any other.
}
#! Merges the stores filling 16 bytes of a cell, as the file says.
#! @param this The code.
#! @returns Whether anything changed.
pub def code::merge_stores(&mut this): bool {
return false if !this.vectors || this.cells.length == 0;
val addresses := this.cell_table();
return false if !addresses.any;
# What each cell's address goes to, where it goes only to what reads and
# writes it, and the order of each instruction within its block.
var touches := vector::<vector<touch>>::new(scratch());
touches.resize(this.cells.length);
var whole := vector::<bool>::new(scratch());
whole.resize(this.cells.length, true);
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 number: u32 = 0;
var walk := this.walk(b as u32);
while walk.more() {
place[walk.next()] = number;
number++;
}
}
var walk := this.walk_all();
var reads := this.reader();
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
reads.start(at);
while reads.more() {
val cell := addresses.cell(reads.next());
continue if cell == 0;
val c := (cell - 1) as u64;
val i := reads.operand();
if i == no_operand {
whole[c] = false;
} else if held.kind == op::load && i == 0 {
touches[c].append(touch { at = at, offset = held.imm, size = (held.aux as access).width(), how = access::bytes });
} else if held.kind == op::store && i == 0 {
val how := held.aux as access;
touches[c].append(touch { at = at, offset = held.imm, size = how.width(), writes = true, how = how });
} else if held.kind == op::clear && i == 0 {
touches[c].append(touch { at = at, size = held.imm, writes = true, how = access::bytes });
} else if held.kind == op::copy && i < 2 {
touches[c].append(touch { at = at, size = held.imm, writes = i == 0, how = access::bytes });
} else if held.kind == op::ret {
touches[c].append(touch { at = at, size = this.cells[c].size as u64, how = access::bytes });
} else {
whole[c] = false;
}
}
}
var done := rewrite::new();
var zeros := zero_values {};
for c in 0..this.cells.length {
val held: cell = this.cells[c];
continue if !whole[c] || (held.kind != ck::temporary && held.kind != ck::local);
var start: u64 = 0;
while start + 16 <= held.size as u64 {
this.merge_region(c as u32, start, touches[c].view(), place.view(), &mut zeros, &mut done);
start += 16;
}
}
this.apply(&done);
return done.changed;
}
#! Merges the stores filling the 16 bytes of a cell from an offset, where they
#! may be merged, as the file says: the last becomes the store of the vector
#! of them all, built before it, and the rest go.
#! @param this The code.
#! @param cell The cell.
#! @param start Where the bytes begin.
#! @param touches What reads and writes the cell.
#! @param place The order of each instruction within its block.
#! @param zeros The zero of each type, made once.
#! @param done What the pass changes.
def code::merge_region(&mut this, cell: u32, start: u64, touches: span<touch>, place: span<u32>, zeros: &mut zero_values, done: &mut rewrite): void {
val end := start + 16;
var stores := vector::<touch>::new(scratch());
var block: u32 = 0;
for &each in touches {
continue if !each.writes || each.offset >= end || each.offset + each.size <= start;
return if each.how == access::bytes || each.offset < start || each.offset + each.size > end;
val one: inst = this.insts[each.at];
if stores.length == 0 {
block = one.block;
}
# One block's stores, each of a word or a real of the same width, at an
# offset of its own, as a struct's fields are written.
return if one.block != block || each.size != stores_width(&stores, each.size) || (each.size != 4 && each.size != 8);
return if stores.length != 0 && (each.how.value_type() != stores[0].how.value_type());
for &other in stores {
return if other.offset == each.offset;
}
stores.append(each);
}
return if stores.length < 2;
var first: u32 = 0xFFFFFFFF;
var last: u32 = 0;
var last_at: u32 = 0;
for &each in stores {
val p := place[each.at];
first = first < p ? first : p;
if p >= last {
last = p;
last_at = each.at;
}
}
# Nothing reads the bytes between the first store and the last.
for &each in touches {
continue if each.writes || each.offset >= end || each.offset + each.size <= start;
val p := place[each.at];
return if this.insts[each.at].block == block && p > first && p < last;
}
val width := stores[0].size;
val real := stores[0].how.value_type() == vt::real;
val lane: u32 = real ? (width == 4 ? lane_f32 : lane_f64) : (width == 4 ? lane_u32 : lane_u64);
val count := 16 / width;
var lanes := vector::<u32>::new(scratch());
lanes.resize(count, 0);
for &each in stores {
lanes[(each.offset - start) / width] = this.arg(each.at, 1);
}
for k in 0..count {
if lanes[k] == 0 {
lanes[k] = zeros.of(this, real ? vt::real : vt::word);
}
}
val held: inst = this.insts[last_at];
var gives: vt[1] = [vt::v128];
val pack := this.detached(op::lanes, lanes.view(), gives[0:1], lanes_pack, lane as u64 | 16 << 8, held.at, held.site);
this.link_before(pack, last_at);
var args: u32[2] = [this.arg(last_at, 0), this.insts[pack].result];
this.become(last_at, op::store, args[0:2], access::v128 as u32, start);
for &each in stores {
if each.at != last_at {
done.remove(each.at);
}
}
done.changed = true;
}
# The width the stores of a region share: that of the first, or the one given
# where there is none yet.
def stores_width(stores: &vector<touch>, size: u64): u64 {
return stores.length == 0 ? size : stores[0].size;
}
+689
View File
@@ -0,0 +1,689 @@
#! @file numbering.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the sixth pass of the optimizer, value numbering: an instruction
#! working out what one before it already worked out, in a block that block
#! dominates, reads that instead, as two reads of `v[i]` share one bounds
#! check's comparison. A check of a condition a dominating check or branch
#! already proved goes, as does a branch's question where it was answered, and
#! a `select` on it is what it chooses. And a read of memory read or written
#! before, with nothing that may write it between, as alias analysis tells,
#! reads what was read or written: within a block, and from the block that
#! dominates it, but for what anything on the way between may write.
import std::containers;
module sakura::compiler;
#! What numbering knows where it is in the walk: the instruction giving each
#! value worked out so far, by its hash, and each condition known, with what
#! each block added, which leaving it takes back.
struct numbering {
var table: scoped_dict<u64, u32>; #! The instruction giving each value worked out, by its hash.
var facts: scoped_dict<u32, u64>; #! What each condition known is.
var loads: vector<known_load>; #! The reads and writes remembered in the block.
var copies: vector<known_copy>; #! The copies into cells remembered in the block.
var writers: runs<u32>; #! The instructions of each block writing memory, in order, a run each.
var writer_runs: vector<u32>; #! The run of `writers` of each block, by block, 0 where none writes, or `no_run` where they are not yet listed.
var kept: runs<known_load>; #! What each block knew of memory where it ended, a run each.
var kept_runs: vector<u32>; #! The run of `kept` each block knew, by block, or 0 where it knew nothing or dominates no block.
var held_run: u32; #! The run of `kept` the reads and writes remembered are, where they were inherited whole and nothing changed them since, or `no_run`.
var aliases: aliases; #! What may write what.
}
#! A read or write of memory numbering remembers: what is at an address, read
#! as an access reads it.
struct known_load {
var address: u32; #! The address.
var how: u32; #! The access.
var value: u32; #! What is there.
var offset: u64; #! How many bytes past the address it is.
var place: region; #! The bytes it is, as alias analysis tells.
}
#! A copy into a cell numbering remembers: the cell holds what is where it
#! copied from, until something writes.
struct known_copy {
var to: u32; #! The cell's address.
var from: u32; #! The address it copied from.
var size: u64; #! How many bytes it copied.
var to_place: region; #! The bytes it wrote, as alias analysis tells.
var from_place: region; #! The bytes it read.
}
#! What `numbering::held_run` holds where what is remembered of memory is no
#! run kept.
const no_run: u32 = 0xFFFFFFFF;
#! A block on numbering's walk down the tree of which dominates which.
struct numbered_block {
var table: u64; #! How many changes the table had before the block, which leaving it takes back.
var facts: u64; #! How many changes the conditions known had before it.
var next: u32; #! The next of the blocks it immediately dominates to walk, or `no_block`.
}
#! Forgets what numbering remembers of memory, as what writes it does.
#! @param this What numbering knows.
def numbering::forget_memory(&mut this): void {
this.loads.clear();
this.copies.clear();
this.held_run = 0;
}
#! Numbers the values of a function's code, knowing what each call writes
#! what it returns to.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether anything changed.
def lowerer::number_values(&mut this, index: u32): bool {
val writes := this.result_writes(index);
return this.program.functions[index].body.number_values(writes.view());
}
#! Numbers the values of the code, as the file says, walking the blocks down
#! the tree of which dominates which.
#! @param this The code.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @returns Whether anything changed.
pub def code::number_values(&mut this, writes: span<u64>): bool {
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.block_order(&mut order, &mut number);
val idom := this.block_dominators();
# The blocks each block immediately dominates.
var first := vector::<u32>::new(scratch());
var after := vector::<u32>::new(scratch());
first.resize(this.blocks.length, no_block);
after.resize(this.blocks.length, no_block);
var k := order.length;
while k > 1 {
k--;
val block: u32 = order[k];
val parent: u32 = idom[block];
after[block] = first[parent];
first[parent] = block;
}
var state := numbering {
table = scoped_dict::<u64, u32>::new(scratch()),
facts = scoped_dict::<u32, u64>::new(scratch()),
loads = vector::<known_load>::new(scratch()),
copies = vector::<known_copy>::new(scratch()),
writers = runs::<u32>::new(scratch()),
writer_runs = vector::<u32>::new(scratch()),
kept = runs::<known_load>::new(scratch()),
kept_runs = vector::<u32>::new(scratch()),
held_run = 0,
aliases = this.aliases_unfound(writes, idom.view())
};
state.writer_runs.resize(this.blocks.length, no_run);
state.kept_runs.resize(this.blocks.length);
var done := rewrite::new();
# The blocks on the walk, each with where its changes begin.
var stack := vector::<numbered_block>::new(scratch());
stack.append(numbered_block { next = first[0] });
this.number_block(0, &mut state, &mut done);
if first[0] != no_block {
this.keep_memory(0, &mut state);
}
while stack.length != 0 {
# The top is written before a block is pushed, which may move it.
val top := &mut stack.last();
val child := top.next;
if child != no_block {
top.next = after[child];
stack.append(numbered_block { table = state.table.mark(), facts = state.facts.mark(), next = first[child] });
this.learn_entry(child, &mut state);
this.inherit_memory(child, idom[child], &mut state);
this.number_block(child, &mut state, &mut done);
# Only the blocks a block dominates ask what it knew where it ended.
if first[child] != no_block {
this.keep_memory(child, &mut state);
}
continue;
}
# Leaving a block takes back what it added.
state.table.rewind(top.table);
state.facts.rewind(top.facts);
stack.truncate();
}
# Numbering a block had what it reads read what replaces it, and what the
# edges leaving it give; so do those of the blocks the entry does not reach,
# never numbered, and the variables bound.
if done.forward.length != 0 {
for b in 0..this.blocks.length {
continue if this.blocks[b].gone || number[b] != 0xFFFFFFFF;
var walk := this.walk(b as u32);
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
for i in 0..held.argc {
val slot := held.args as u64 + i as u64;
this.operands[slot] = done.resolve(this.operands[slot]);
}
}
this.resolve_edges(b as u32, &done);
}
for i in 0..this.bindings.length {
this.bindings[i].value = done.resolve(this.bindings[i].value);
}
}
this.take_out(&done);
return done.changed;
}
#! Has the edges leaving a block give what replaces what they give.
#! @param this The code.
#! @param block The block.
#! @param done What the pass changes.
def code::resolve_edges(&mut this, block: u32, done: &rewrite): void {
var outs := this.edges_of(this.blocks[block].last);
while outs.more() {
val args := this.edges[outs.next()].args.slice();
for a in 0..args.length {
args[a] = done.resolve(args[a]);
}
}
}
#! Learns what the branch into a block says where only it goes there: its
#! condition is not zero along the way it goes where it is not, and is zero
#! along the other.
#! @param this The code.
#! @param block The block.
#! @param state What numbering knows.
def code::learn_entry(&this, block: u32, state: &mut numbering): void {
return if this.blocks[block].preds.length != 1;
val edge: u32 = this.blocks[block].preds[0];
val from: u32 = this.edges[edge].from;
return if this.insts[from].kind != op::branch;
val cond := this.arg(from, 0);
return if state.facts.contains(&cond);
state.facts.set(cond, edge == this.insts[from].aux ? 1 : 0);
}
#! Begins what numbering knows of memory where a block begins: what the block
#! dominating it knew where it ended, but for what anything on a way from
#! there to the block may write, and nothing where the ways pass too many
#! blocks.
#! @param this The code.
#! @param block The block.
#! @param parent The block dominating it.
#! @param state What numbering knows.
def code::inherit_memory(&this, block: u32, parent: u32, state: &mut numbering): void {
state.forget_memory();
val run: u32 = state.kept_runs[parent];
return if run == 0;
var between := vector::<u32>::new(scratch());
return if !this.blocks_between(parent, block, &mut between);
state.loads.extend(state.kept.view(run));
state.held_run = run;
for &each in between {
this.list_writers(each, state);
for &at in state.writers.view(state.writer_runs[each]) {
this.forget_written(at, state);
return if state.loads.length == 0;
}
}
}
#! Lists the instructions of a block writing memory, where numbering it did not
#! list them already.
#! @param this The code.
#! @param block The block.
#! @param state What numbering knows.
def code::list_writers(&this, block: u32, state: &mut numbering): void {
return if state.writer_runs[block] != no_run;
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
val kind := this.insts[at].kind;
if kind != op::load && (kind.traits() & op_write) != 0 {
state.writers.push(at);
}
}
state.writer_runs[block] = state.writers.end();
}
#! Finds the blocks on the ways from where a block ends to where a block it
#! dominates begins. A way going round a loop through the block it ends at
#! passes that block whole, so it is among them; one coming back through the
#! dominating block begins again where that block ends, which knows what it
#! knows anew. Only so many blocks are looked through.
#! @param this The code.
#! @param parent The dominating block.
#! @param block The block it dominates.
#! @param between Where the blocks are written.
#! @returns Whether they are few enough to be looked through.
def code::blocks_between(&this, parent: u32, block: u32, between: &mut vector<u32>): bool {
val preds := &this.blocks[block].preds;
if preds.length == 1 && this.edge_source(preds[0]) == parent {
return true;
}
var todo := vector::<u32>::new(scratch());
for &edge in preds.view() {
todo.append(this.edge_source(edge));
}
while todo.length != 0 {
val at: u32 = todo.last();
todo.truncate();
continue if at == parent || between.view().contains(&at);
return false if between.length >= 32;
between.append(at);
for &edge in this.blocks[at].preds.view() {
todo.append(this.edge_source(edge));
}
}
return true;
}
#! Forgets what numbering remembers of memory that an instruction may write.
#! @param this The code.
#! @param index The instruction.
#! @param state What numbering knows.
def code::forget_written(&this, index: u32, state: &mut numbering): void {
return if state.loads.length == 0 && state.copies.length == 0;
val written := state.aliases.writes_of(this, index);
this.forget_writing(&written, state);
}
#! Forgets what numbering remembers of memory that what an instruction writes
#! may hold.
#! @param this The code.
#! @param written What the instruction writes.
#! @param state What numbering knows.
def code::forget_writing(&this, written: &writing, state: &mut numbering): void {
return if state.loads.length == 0 && state.copies.length == 0;
state.aliases.find_escaped(this);
var kept: u64 = 0;
for i in 0..state.loads.length {
continue if state.aliases.touches(this, written, &state.loads[i].place);
if kept != i {
state.loads[kept] = state.loads[i];
}
kept++;
}
if kept != state.loads.length {
state.loads.resize(kept);
state.held_run = no_run;
}
var held: u64 = 0;
for i in 0..state.copies.length {
val each: known_copy = state.copies[i];
continue if state.aliases.touches(this, written, &each.to_place) || state.aliases.touches(this, written, &each.from_place);
state.copies[held] = each;
held++;
}
state.copies.resize(held);
}
#! Keeps what numbering knows of memory where a block ends, for the blocks it
#! dominates: the run it inherited, where nothing changed it.
#! @param this The code.
#! @param block The block.
#! @param state What numbering knows.
def code::keep_memory(&this, block: u32, state: &mut numbering): void {
state.kept_runs[block] = state.held_run != no_run ? state.held_run : state.kept.add(state.loads.view());
}
#! Numbers the instructions of a block, in order, from what is known of memory
#! where it begins, which then holds what is known where it ends.
#! @param this The code.
#! @param block The block.
#! @param state What numbering knows.
#! @param done What the pass changes.
def code::number_block(&mut this, block: u32, state: &mut numbering, done: &mut rewrite): void {
# What writes memory is listed as it is met, where it is not listed yet.
val listing := state.writer_runs[block] == no_run;
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
for i in 0..held.argc {
val slot := held.args as u64 + i as u64;
this.operands[slot] = done.resolve(this.operands[slot]);
}
match held.kind {
op::check => {
val cond := this.arg(at, 0);
if state.facts.get(&cond) is some(known) {
if known != 0 {
done.remove(at);
}
} else {
state.facts.set(cond, 1);
}
}
op::branch => {
val cond := this.arg(at, 0);
if state.facts.get(&cond) is some(known) {
# Which cells are escaped is found as the code was, before the
# branch no longer reads its condition.
state.aliases.find_escaped(this);
val bits: u64 = known;
this.operands[held.args] = this.word_value(bits != 0 ? 1 : 0);
done.changed = true;
}
}
op::load => {
this.forward_copy(at, 0, (held.aux as access).width() + held.imm, state, done);
this.number_load(at, state, done);
}
op::copy => this.forward_copy(at, 1, held.imm, state, done);
op::select => this.number_select(at, state, done);
else => {
if this.removable(at) && held.count == 1 {
this.number_inst(at, state, done);
}
}
}
# What writes memory makes what was read of what it may write unknown,
# but for what a store of a whole word writes.
if held.kind != op::load && (held.kind.traits() & op_write) != 0 {
if listing {
state.writers.push(at);
}
if held.kind == op::store && (held.aux == access::i64 as u32 || held.aux == access::f64 as u32) {
# What a store writes is the region it then holds.
val written := state.aliases.writes_of(this, at);
this.forget_writing(&written, state);
state.held_run = no_run;
var base: u32 = 0;
val offset := this.address_base(this.arg(at, 0), held.imm, &mut base);
state.loads.append(known_load {
address = base,
how = held.aux,
value = this.arg(at, 1),
offset = offset,
place = written.place
});
} else {
this.forget_written(at, state);
}
# A cell a copy filled holds what it copied, until something writes.
if held.kind == op::copy && this.cell_of(this.arg(at, 0)) != no_cell
&& this.cell_of(this.arg(at, 0)) != this.cell_of(this.arg(at, 1)) {
val to := this.arg(at, 0);
val from := this.arg(at, 1);
state.copies.append(known_copy {
to = to,
from = from,
size = held.imm,
to_place = state.aliases.region_at(this, to, 0, held.imm),
from_place = state.aliases.region_at(this, from, 0, held.imm)
});
}
}
}
if listing {
state.writer_runs[block] = state.writers.end();
}
this.resolve_edges(block, done);
}
#! Numbers a `select`: one on a condition known where it is, as a dominating
#! check or branch made it, is what it chooses, and otherwise it is numbered as
#! any instruction working out its value is.
#! @param this The code.
#! @param index The `select`.
#! @param state What numbering knows.
#! @param done What the pass changes.
def code::number_select(&mut this, index: u32, state: &mut numbering, done: &mut rewrite): void {
val cond := this.arg(index, 0);
if state.facts.get(&cond) is some(known) {
val bits: u64 = known;
done.replace(this.insts[index].result, this.arg(index, bits != 0 ? 1 : 2));
done.remove(index);
return;
}
this.number_inst(index, state, done);
}
#! Reads what a cell a copy filled holds from where it was copied from
#! instead, where nothing wrote since: a load from it, or a copy out of it into
#! another cell.
#! @param this The code.
#! @param index The `load` or `copy`.
#! @param operand The operand reading the cell.
#! @param reach How far past the cell's address it reads.
#! @param state What numbering knows.
#! @param done What the pass changes.
def code::forward_copy(&mut this, index: u32, operand: u32, reach: u64, state: &mut numbering, done: &mut rewrite): void {
val address := this.arg(index, operand);
for i in 0..state.copies.length {
val each := &state.copies[i];
continue if each.to != address || reach > each.size;
val from := each.from;
# A copy out of it goes on only into a cell, which nothing else overlaps.
if operand == 1 {
val into := this.cell_of(this.arg(index, 0));
return if into == no_cell || into == this.cell_of(from);
}
this.operands[this.insts[index].args as u64 + operand as u64] = from;
done.changed = true;
return;
}
}
#! Numbers a read of memory: one of what the block read or wrote before, with
#! nothing writing between, reads that instead, though one reached through a
#! step past the address the other was.
#! @param this The code.
#! @param index The `load`.
#! @param state What numbering knows.
#! @param done What the pass changes.
def code::number_load(&mut this, index: u32, state: &mut numbering, done: &mut rewrite): void {
val held: inst = this.insts[index];
var address: u32 = 0;
val offset := this.address_base(this.arg(index, 0), held.imm, &mut address);
for i in 0..state.loads.length {
val each := &state.loads[i];
continue if each.address != address || each.offset != offset || each.how != held.aux;
done.replace(held.result, each.value);
done.remove(index);
return;
}
state.held_run = no_run;
state.loads.append(known_load {
address = address,
how = held.aux,
value = held.result,
offset = offset,
place = state.aliases.region_of(this, index, 0)
});
}
#! Where a load or store reaches, as a value and how many bytes past it: a step
#! of a constant past another value reaches as far past that one, so the bytes
#! it reaches are known as the same as those reached from it directly.
#! @param this The code.
#! @param address The address the load or store is given.
#! @param offset How many bytes past it the load or store reaches.
#! @param base Where the value it reaches past is written.
#! @returns How many bytes past that value it reaches.
def code::address_base(&this, address: u32, offset: u64, base: &mut u32): u64 {
base = address;
val index := this.defining(address);
return offset if index == 0 || this.insts[index].kind != op::add;
var bits: u64 = 0;
return offset if !this.word_constant(this.arg(index, 1), &mut bits);
base = this.arg(index, 0);
return offset + bits;
}
#! Numbers an instruction that only works out its value: one working out what
#! one dominating it did reads that instead.
#! @param this The code.
#! @param index The instruction.
#! @param state What numbering knows.
#! @param done What the pass changes.
def code::number_inst(&mut this, index: u32, state: &mut numbering, done: &mut rewrite): void {
val hash := this.hash_inst(index);
if state.table.get(&hash) is some(got) {
val other: u32 = got;
if this.same_inst(index, other) {
done.replace(this.insts[index].result, this.insts[other].result);
done.remove(index);
return;
}
}
state.table.set(hash, index);
}
#! The hash of what an instruction works out: its operation, what its `aux`
#! and `imm` hold, the type of its value, and its operands, in either order
#! where the operation does not mind which.
#! @param this The code.
#! @param index The instruction.
#! @returns The hash.
def code::hash_inst(&this, index: u32): u64 {
val held: inst = this.insts[index];
var hash := mix_hash(mix_hash(mix_hash(0xCBF29CE484222325u, held.kind as u64), held.aux as u64), held.imm);
hash = mix_hash(hash, this.origins[held.result].kind as u64);
if held.argc == 2 && commutes(held.kind) {
val a := this.arg(index, 0);
val b := this.arg(index, 1);
hash = mix_hash(mix_hash(hash, (a < b ? a : b) as u64), (a < b ? b : a) as u64);
return hash;
}
for i in 0..held.argc {
hash = mix_hash(hash, this.arg(index, i as u32) as u64);
}
return mix_hash(hash, held.argc as u64);
}
#! Whether two instructions work out the same. Their values are of one type,
#! as a `vzero` of 16 bytes and one of 32 are not the same.
#! @param this The code.
#! @param a One instruction.
#! @param b The other.
#! @returns Whether they do.
def code::same_inst(&this, a: u32, b: u32): bool {
val x: inst = this.insts[a];
val y: inst = this.insts[b];
return false if x.kind != y.kind || x.aux != y.aux || x.imm != y.imm || x.argc != y.argc;
return false if this.origins[x.result].kind != this.origins[y.result].kind;
if x.argc == 2 && commutes(x.kind) {
val a0 := this.arg(a, 0);
val a1 := this.arg(a, 1);
val b0 := this.arg(b, 0);
val b1 := this.arg(b, 1);
return (a0 == b0 && a1 == b1) || (a0 == b1 && a1 == b0);
}
for i in 0..x.argc {
return false if this.arg(a, i as u32) != this.arg(b, i as u32);
}
return true;
}
#! Mixes a word into a hash.
#! @param hash The hash so far.
#! @param value The word.
#! @returns The hash.
def mix_hash(hash: u64, value: u64): u64 {
return (hash ^ value) * 0x100000001B3u;
}
#! Moves each constant made within a loop first into the entry, one of each,
#! so the machine makes it once a call rather than each time the loop goes
#! round, as it does the address of a cell, a global, or a datum. One made
#! outside every loop stays, since making it at the entry would make it where
#! nothing reads it.
#! @param this The code.
#! @returns Whether anything changed.
pub def code::hoist_constants(&mut this): bool {
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.block_order(&mut order, &mut number);
val looped := this.loop_blocks(order.view(), number.view());
var done := rewrite::new();
var words := dict::<u64, u32>::new(scratch());
var reals := dict::<u64, u32>::new(scratch());
var moved := vector::<u32>::new(scratch());
for &block in order {
continue if block != 0 && !looped[block];
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
if block != 0 && (held.kind == op::cell || held.kind == op::global || held.kind == op::datum) {
done.remove(at);
moved.append(at);
} else if held.kind == op::iconst || held.kind == op::fconst {
val seen := held.kind == op::iconst ? &mut words : &mut reals;
if seen.get(&held.imm) is some(got) {
done.replace(held.result, got);
done.remove(at);
} else {
seen.set(held.imm, held.result);
if block != 0 {
done.remove(at);
moved.append(at);
}
}
}
}
}
this.apply(&done);
var i := moved.length;
while i > 0 {
i--;
this.put_first(0, moved[i]);
}
return done.changed;
}
#! Which blocks are within a loop: those from which an edge going back to a
#! block dominating them is reached, without passing that block, and that
#! block.
#! @param this The code.
#! @param order The blocks in reverse postorder.
#! @param number Each block's place in that order.
#! @returns Whether each block is within a loop.
pub def code::loop_blocks(&mut this, order: span<u32>, number: span<u32>): vector<bool> {
var looped := vector::<bool>::new(scratch());
looped.resize(this.blocks.length);
# The dominators are asked for only where an edge may go back.
var back := false;
for &block in order {
for &edge in this.blocks[block].preds {
back = back || number[this.edge_source(edge)] >= number[block];
}
}
return looped if !back;
val idom := this.block_dominators();
var todo := vector::<u32>::new(scratch());
for &block in order {
for &edge in this.blocks[block].preds {
val from := this.edge_source(edge);
continue if number[from] < number[block] || !dominates(&idom, block, from);
# A loop headed by the block: walk back from where it goes back.
looped[block] = true;
todo.append(from);
while todo.length != 0 {
val at: u32 = todo.last();
todo.truncate();
continue if at == block || looped[at] && at != from;
looped[at] = true;
for &inner in this.blocks[at].preds {
val back := this.edge_source(inner);
if back != block && !looped[back] {
todo.append(back);
}
}
}
}
}
return looped;
}
+575
View File
@@ -0,0 +1,575 @@
#! @file optimizer.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the optimizer, which runs passes over the code of each function
#! once the program is lowered. Each pass is small, in a file of its own, and
#! leaves the code well formed, which the verifier checks after each where
#! lowering verifies. `-O0` runs none, `-O1` simplification, control flow
#! cleanup, value numbering, and dead code removal, and `-O2` those with
#! inlining and the promotion of cells to values. Below `-O2`, calls of
#! `@inline` functions are inlined all the same, and nothing else is, so at
#! `-O0` the code is as written but for those, each local of the code copied
#! still in a cell of its own. The slots the passes leave are compacted away
#! at the end, which the backends and the functions inlining the code read.
#! Functions are optimized after the functions they call, so a function
#! inlined is already optimized.
#! At `-O2`, a function of an executable asking which vector instructions the
#! processor has is given a version for x86-64-v3's, as `versions.sakura` says.
import std::containers;
module sakura::compiler;
#! The passes, as a problem a pass leaves names them.
pub enum pass : u8 {
simplify, #! Folding constants and simplifying operations.
dead, #! Taking out what nothing needs.
control, #! Cleaning up how control flows.
inline, #! Inlining calls of small functions.
promote, #! Promoting cells to values.
numbering, #! Numbering values.
hoist, #! Moving constants into the entry.
memory, #! Cleaning up the memory of cells.
loops, #! Rotating loops and moving out of them what they work out the same each time round.
sink, #! Moving what is read past one way out of a block into that way.
count, #! How many passes there are; not a pass itself.
}
#! The name of a pass, as a problem names it.
#! @param this The pass.
#! @returns Its name.
pub def pass::name(&this): strview {
return match this {
pass::simplify => "simplification",
pass::dead => "dead code removal",
pass::control => "control flow cleanup",
pass::inline => "inlining",
pass::promote => "promotion",
pass::numbering => "value numbering",
pass::hoist => "constant hoisting",
pass::memory => "memory cleanup",
pass::loops => "loop optimization",
pass::sink => "code sinking",
else => "a pass"
};
}
#! Optimizes every function lowered and not yet optimized, as its level says,
#! each after those it calls, but for those calling each other, which go in the
#! order met. The order is worked out first, walking the calls, and a function
#! inlines only those before it, so what each is made into is the same however
#! many threads optimize them: as many as the options say work at once, each
#! taking a function once those before it that it calls are done. A function
#! the one calling it alone copies whole is optimized there, so only the passes
#! up to inlining run on it before, and the rest after, where something still
#! reaches it, as a cold call does. The versions of those asking which
#! instructions the processor has are made after, in the order, as each reads
#! what came before its function.
#! @param this The compiler.
pub def lowerer::optimize(&mut this): void {
return if this.options.level == 0 && !this.copies_marked();
var plan := this.plan_optimizing();
val count := plan.order.length;
# What verifying each function finds, kept by its place in the order, so it
# is noted in that order whichever thread found it.
var found := vector::<vector<string>>::new();
found.resize(count);
val compiler := &mut this;
share_out_ordered(count, this.options.threads, &plan.waiting, def(place: u64): void {
compiler.optimize_at(&plan, place, &mut found[place]);
});
# Those left for the function calling them that something still reaches, as
# one whose call is cold, have the rest of their passes run, each on its own,
# whichever optimizing left them.
var finishing := this.left_unfinished();
var alone := groups::<u32>::new(0);
alone.reset(finishing.length);
alone.seal();
var noted := vector::<vector<string>>::new();
noted.resize(finishing.length);
share_out_ordered(finishing.length, this.options.threads, &alone, def(k: u64): void {
compiler.finish_unfinished(finishing[k], &plan.ranks, &mut noted[k]);
});
for &each in found {
for &text in each {
this.problems.append(string::copy_of(&text));
}
}
for &each in noted {
for &text in each {
this.problems.append(string::copy_of(&text));
}
}
if this.versions_made() {
for place in 0..count {
this.make_version(plan.order[place], &mut plan.ranks, (2 * place + 3) as u32);
}
}
this.merge_all();
}
#! Merges the stores filling 16 bytes of a cell, in each function of an
#! executable optimized, once nothing more is inlined, as `merge.sakura` says.
#! @param this The compiler.
def lowerer::merge_all(&mut this): void {
for i in 0..this.program.functions.length {
val function := &mut this.program.functions[i];
continue if !function.optimized || !function.body.vectors;
val point := mark_scratch();
if function.body.merge_stores() {
function.body.compact();
if this.options.verify {
val verdict := function.body.verify();
for &each in verdict.problems {
this.problems.append($"{function.name}: after merging stores: {each}");
}
}
}
release_scratch(point);
}
}
#! Whether calls of `@inline` functions are inlined below `-O2`, which inlines
#! nothing else: but where the program evaluates constants, or runs with its
#! memory checked, as each function's locals end where its frame does then.
#! @param this The compiler.
#! @returns Whether they are.
def lowerer::inlines_marked(&this): bool {
return !this.options.evaluating && !this.options.checks;
}
#! Whether `-O0`, which optimizes nothing, has calls to inline all the same:
#! where a function lowered is `@inline`.
#! @param this The compiler.
#! @returns Whether it has.
def lowerer::copies_marked(&this): bool {
return false if !this.inlines_marked();
for &each in this.program.functions {
return true if each.inline && each.lowered;
}
return false;
}
#! Where a function never optimized is in the order functions are optimized in.
const unranked: u32 = 0xFFFFFFFF;
#! The order functions are optimized in, and what each waits for.
struct optimizing {
var order: vector<u32>; #! The functions, each after those it calls, but for those calling each other.
var ranks: vector<u32>; #! Of each function, `2k + 2` where it is the `k`th in the order, `2k + 3` where it is the version of that one, 0 where it was optimized before, and `unranked` where it is not optimized.
var waiting: groups<u32>; #! The places in the order of those waiting on each, by its place: each calls it, and comes after it.
}
#! A function on the walk of the calls that orders functions to be optimized.
struct calling {
var function: u32; #! The function.
var begin: u64; #! Where the functions it calls begin among the calls of those on the walk.
var end: u64; #! Where they end.
var next: u64; #! The next of them to walk.
}
#! Works out the order functions are optimized in: walking the calls from each
#! function lowered and not yet optimized, each once those it calls are, but
#! for those calling each other, which go in the order met. Each waits for the
#! functions before it that it calls.
#! @param this The compiler.
#! @returns The order.
def lowerer::plan_optimizing(&mut this): optimizing {
val count := this.program.functions.length;
var plan := optimizing {
order = vector::<u32>::new(),
ranks = vector::<u32>::new(),
waiting = groups::<u32>::new(0)
};
var seen := vector::<bool>::new();
seen.resize(count);
plan.ranks.resize(count);
for i in 0..count {
if this.program.functions[i].optimized {
seen[i] = true;
this.ready_to_inline(i as u32);
} else {
plan.ranks[i] = unranked;
}
}
# The functions on the walk, each with the functions it calls in `calls`.
# The callees of each function in the order are kept in `callees`, a run of
# each.
var stack := vector::<calling>::new();
var calls := vector::<u32>::new();
var callees := runs::<u32>::new();
var callee_runs := vector::<u32>::new();
for root in 0..count {
continue if seen[root] || !this.program.functions[root].lowered;
this.walk_into(root as u32, &mut seen, &mut stack, &mut calls);
while stack.length != 0 {
# The top is written before a callee is pushed, which may move it.
val top := &mut stack.last();
if top.next < top.end {
val callee: u32 = calls[top.next];
top.next++;
if !seen[callee] && this.program.functions[callee].lowered {
this.walk_into(callee, &mut seen, &mut stack, &mut calls);
}
continue;
}
callee_runs.append(callees.add(span::<u32>::over(calls.view().data + top.begin, top.end - top.begin)));
plan.ranks[top.function] = (2 * plan.order.length + 2) as u32;
plan.order.append(top.function);
calls.resize(top.begin);
stack.truncate();
}
}
# Each function waits for those before it that it calls, each once, as the
# functions counted for it say.
val placed := plan.order.length;
var counted := stamped_set::new(placed, nothing {});
var pairs := vector::<u64>::new();
plan.waiting.reset(placed);
for p in 0..placed {
counted.next_round();
for &callee in callees.view(callee_runs[p]) {
val rank: u32 = plan.ranks[callee];
continue if rank == 0 || rank == unranked;
val q := (rank - 2) / 2;
continue if q as u64 >= p || !counted.insert(q);
pairs.append(pair_key(q, p as u32));
plan.waiting.count(q);
}
}
plan.waiting.seal();
for &pair in pairs {
plan.waiting.put(pair_high(pair), pair_low(pair));
}
this.find_sole_calls(&plan.order);
# A call of a function this one waits for is settled, and stays so where it is
# inlined into another, which waited for this one.
for p in 0..placed {
val function: u32 = plan.order[p];
val body := &mut this.program.functions[function].body;
var walk := body.walk_all();
while walk.more() {
val at := walk.next();
continue if body.insts[at].kind != op::call;
val rank: u32 = plan.ranks[body.insts[at].aux];
body.insts[at].imm = rank != 0 && rank != unranked && rank < plan.ranks[function] ? call_settled : 0;
}
}
return plan;
}
#! Puts a function on the walk, with the functions it calls.
#! @param this The compiler.
#! @param function The function.
#! @param seen Whether each function was put on the walk.
#! @param stack The functions on the walk.
#! @param calls The callees of the functions on the walk.
def lowerer::walk_into(&mut this, function: u32, seen: &mut vector<bool>, stack: &mut vector<calling>, calls: &mut vector<u32>): void {
seen[function] = true;
val begin := calls.length;
val body := &this.program.functions[function].body;
var walk := body.walk_all();
while walk.more() {
val at := walk.next();
if body.insts[at].kind == op::call {
calls.append(body.insts[at].aux);
}
}
# A function named as a value may be called directly once the value is known,
# so it is waited for as one called is.
for &named in this.program.functions[function].named.view() {
calls.append(named);
}
stack.append(calling { function = function, begin = begin, end = calls.length, next = begin });
}
#! Optimizes the function of a place in the order, then readies it to be
#! inlined.
#! @param this The compiler.
#! @param plan The order.
#! @param place The place.
#! @param found Where what verifying it finds is noted.
def lowerer::optimize_at(&mut this, plan: &optimizing, place: u64, found: &mut vector<string>): void {
val function: u32 = plan.order[place];
this.optimize_function(function, &plan.ranks, (2 * place + 2) as u32, found);
this.program.functions[function].optimized = true;
this.ready_to_inline(function);
}
#! Finds the functions left unfinished that something still reaches.
#! @param this The compiler.
#! @returns The functions, in order.
def lowerer::left_unfinished(&mut this): vector<u32> {
var left := vector::<u32>::new();
val count := this.program.functions.length;
var any := false;
for i in 0..count {
any = any || this.program.functions[i].unfinished;
}
return left if !any;
val point := mark_scratch();
var reached := worklist::new(count, scratch());
this.reach_functions(&mut reached);
for i in 0..count {
if this.program.functions[i].unfinished && reached.has(i as u32) {
left.append(i as u32);
}
}
release_scratch(point);
return left;
}
#! Runs the rest of the passes on a function left unfinished, then readies it
#! to be inlined again, as its code changed.
#! @param this The compiler.
#! @param function The function.
#! @param ranks Where each function is in the order functions are
#! optimized in, which none of the passes left inlines by.
#! @param found Where what verifying it finds is noted.
def lowerer::finish_unfinished(&mut this, function: u32, ranks: &vector<u32>, found: &mut vector<string>): void {
var sweep := passes { ranks = ranks, rank = 0, found = found, compacted = 0xFFFFFFFF };
for i in 0..pass::count as u64 {
sweep.clean[i] = 0xFFFFFFFF;
}
this.finish_function(function, &mut sweep);
val held := &mut this.program.functions[function];
held.unfinished = false;
held.inlining = inline_facts { sole = held.inlining.sole };
held.order.clear();
this.ready_to_inline(function);
}
#! Works out what inlining an optimized function asks of it, as its code no
#! longer changes, rather than leave that to the first function inlining it,
#! as several may at once on threads of their own: what inlining knows of it,
#! and where it may be copied, the order its blocks are copied in.
#! @param this The compiler.
#! @param function The function.
def lowerer::ready_to_inline(&mut this, function: u32): void {
# Below `-O2`, only `@inline` functions are.
return if this.options.level < 2 && !this.program.functions[function].inline;
val point := mark_scratch();
if this.inline_facts(function).fits {
this.order_blocks(function);
}
release_scratch(point);
}
#! Optimizes one function, as its level says. A pass that found nothing to
#! change is not run again until another changes something.
#! @param this The compiler.
#! @param index The function.
#! @param ranks Where each function is in the order functions are optimized
#! in, as `optimizing` says: those before it are inlined.
#! @param rank Where the function is.
#! @param found Where what verifying it finds is noted.
def lowerer::optimize_function(&mut this, index: u32, ranks: &vector<u32>, rank: u32, found: &mut vector<string>): void {
var sweep := passes { ranks = ranks, rank = rank, found = found, compacted = 0xFFFFFFFF };
for i in 0..pass::count as u64 {
sweep.clean[i] = 0xFFFFFFFF;
}
# `-O0` inlines the calls of `@inline` functions, and changes nothing else.
if this.options.level == 0 {
this.sweep(index, &mut sweep, pass::inline);
if sweep.changes != 0 {
this.compact_function(index, &mut sweep);
}
return;
}
this.sweep(index, &mut sweep, pass::simplify);
this.sweep(index, &mut sweep, pass::control);
if this.options.level < 2 && this.inlines_marked() {
this.sweep(index, &mut sweep, pass::inline);
}
if this.options.level >= 2 {
this.sweep(index, &mut sweep, pass::dead);
this.sweep(index, &mut sweep, pass::inline);
this.sweep(index, &mut sweep, pass::promote);
this.sweep(index, &mut sweep, pass::simplify);
this.sweep(index, &mut sweep, pass::control);
# Promoting may show which function a value calls, which is then called and
# inlined as any other.
this.sweep(index, &mut sweep, pass::inline);
this.sweep(index, &mut sweep, pass::promote);
this.sweep(index, &mut sweep, pass::simplify);
this.sweep(index, &mut sweep, pass::control);
# The function calling it copies it whole and optimizes it there, so the
# rest is left until then, and run after only where it is still called.
if this.awaits_caller(index) {
this.program.functions[index].unfinished = true;
return;
}
}
this.finish_function(index, &mut sweep);
}
#! Runs the passes after inlining on a function's code, then compacts it.
#! @param this The compiler.
#! @param index The function.
#! @param sweep What is known of the passes run on it.
def lowerer::finish_function(&mut this, index: u32, sweep: &mut passes): void {
this.sweep(index, sweep, pass::numbering);
this.sweep(index, sweep, pass::memory);
this.sweep(index, sweep, pass::dead);
this.sweep(index, sweep, pass::loops);
this.sweep(index, sweep, pass::numbering);
this.sweep(index, sweep, pass::simplify);
this.sweep(index, sweep, pass::control);
this.sweep(index, sweep, pass::sink);
# What sinking moved past a branch, as a `select` on the condition the branch
# tests, is numbered again where the branch decided it.
this.sweep(index, sweep, pass::numbering);
this.sweep(index, sweep, pass::dead);
this.sweep(index, sweep, pass::hoist);
this.compact_function(index, sweep);
}
#! Whether a function, its calls inlined, is left for the function calling it
#! to optimize: that alone calls it, and copies it whole, as it may be copied,
#! asks nothing of the processor, and leaves that function room to grow.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether it is.
def lowerer::awaits_caller(&this, index: u32): bool {
val held := &this.program.functions[index];
return false if held.inlining.sole == 0 || held.closure || held.evaluation != 0;
var size: u32 = 0;
var walk := held.body.walk_all();
while walk.more() {
match held.body.insts[walk.next()].kind {
op::frame, op::ready, op::reach, op::same, op::cpu => { return false; }
else => {}
}
size++;
}
return size <= sole_growth;
}
#! What optimizing one function knows of the passes run on it.
struct passes {
var ranks: &vector<u32>; #! Where each function is in the order functions are optimized in.
var rank: u32; #! Where the function is.
var found: &mut vector<string>; #! What verifying it finds.
var changes: u32; #! How many passes changed something.
var compacted: u32; #! How many passes had changed something when the code was last compacted, or `0xFFFFFFFF` before it was.
var clean: u32[pass::count as u64]; #! How many passes had changed something when each last found nothing to change.
}
#! Runs a pass over a function's code, but where it found nothing to change
#! since any pass last changed something.
#! @param this The compiler.
#! @param index The function.
#! @param sweep What is known of the passes run on it.
#! @param which The pass.
def lowerer::sweep(&mut this, index: u32, sweep: &mut passes, which: pass): void {
return if sweep.clean[which as u64] == sweep.changes;
if this.run_pass(index, which, sweep) {
sweep.changes++;
} else {
sweep.clean[which as u64] = sweep.changes;
}
}
#! Compacts a function's code where a pass changed it since it was last
#! compacted, then verifies it where lowering verifies.
#! @param this The compiler.
#! @param index The function.
#! @param sweep What is known of the passes run on it.
def lowerer::compact_function(&mut this, index: u32, sweep: &mut passes): void {
return if sweep.compacted == sweep.changes;
sweep.compacted = sweep.changes;
val point := mark_scratch();
this.program.functions[index].body.compact();
if this.options.verify {
val verdict := this.program.functions[index].body.verify();
for &each in verdict.problems {
sweep.found.append($"{this.program.functions[index].name}: after compacting: {each}");
}
}
release_scratch(point);
}
#! Cleans up the memory of the cells of a function's code, knowing what each
#! call writes what it returns to.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether anything changed.
def lowerer::clean_memory(&mut this, index: u32): bool {
val writes := this.result_writes(index);
return this.program.functions[index].body.clean_memory(writes.view());
}
#! How many bytes each call of a function's code writes what it returns to, at
#! the address its last operand gives, as `emitter::call_with` passes it. Each
#! instruction is looked at where it lies, those taken out too, which nothing
#! asks of.
#! @param this The compiler.
#! @param index The function.
#! @returns The bytes, by instruction, or 0 for what writes none.
pub def lowerer::result_writes(&this, index: u32): vector<u64> {
val body := &this.program.functions[index].body;
var writes := vector::<u64>::new(scratch());
writes.resize(body.insts.length);
for at in 1..body.insts.length {
val kind := body.insts[at].kind;
val aux: u32 = body.insts[at].aux;
var signature: u32 = no_function;
if kind == op::call {
signature = this.program.functions[aux].signature;
} else if kind == op::call_trait || kind == op::call_value || kind == op::call_c {
signature = aux;
}
continue if signature == no_function;
val shape := this.layout_at(this.program.signatures[signature].result);
if returned_in_memory(&shape) {
writes[at] = shape.size;
}
}
return writes;
}
#! Runs a pass over a function's code, then verifies it where lowering
#! verifies, noting what is wrong with what the pass left.
#! @param this The compiler.
#! @param index The function.
#! @param which The pass.
#! @param sweep What is known of the passes run on it.
#! @returns Whether the pass changed anything.
def lowerer::run_pass(&mut this, index: u32, which: pass, sweep: &mut passes): bool {
# What the pass and the verifier work out is freed as the pass ends.
val point := mark_scratch();
val body := &mut this.program.functions[index].body;
val changed := match which {
pass::simplify => body.simplify(this.program.data.view()),
pass::dead => body.remove_dead(),
pass::control => body.clean_control(),
pass::inline => this.inline_calls(index, sweep.ranks, sweep.rank),
pass::promote => body.promote_cells(),
pass::numbering => this.number_values(index),
pass::hoist => body.hoist_constants(),
pass::memory => this.clean_memory(index),
pass::loops => this.optimize_loops(index),
pass::sink => this.sink_code(index),
else => false
};
# Each pass forgets the order and dominators the code keeps where it changes
# where blocks lead, or works them out anew, as pruning does after inlining,
# so they hold for the code it leaves.
if this.options.verify && changed {
val verdict := this.program.functions[index].body.verify();
for &each in verdict.problems {
sweep.found.append($"{this.program.functions[index].name}: after {which.name()}: {each}");
}
}
release_scratch(point);
return changed;
}
+887
View File
@@ -0,0 +1,887 @@
#! @file promote.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the fifth pass of the optimizer, which promotes cells to values: a
#! cell whose address is only read from, written to, zeroed, or copied in and
#! out from its start, at offsets that do not overlap, holds values rather than
#! memory. Each word it holds becomes a variable, and the code is rebuilt as it
#! was built, each read reading what the variable holds there, which where
#! control flow joins is a parameter of the block. The bytes a copy moves that
#! nothing reads or writes alone are words of their own, so a value copied from
#! one cell to another and on is promoted whole. Inlining leaves many such
#! cells, where a function took the address of what it was given or returned.
#! A `simd` read and written whole becomes one vector, which an executable holds
#! in a vector register, but 32 bytes only in code for processors with AVX.
import std::containers;
module sakura::compiler;
#! A word a cell promoted holds: where it is in the cell, how wide it is, and
#! the type of value it holds.
struct slot {
var cell: u32; #! The cell.
var offset: u64; #! Where it begins.
var size: u64; #! How many bytes it is.
var kind: vt; #! The type of value it holds.
var signed: bool; #! Whether it is read as a signed integer narrower than a word, which a copy narrows it as too.
var next: u32; #! One more than the next slot of the same cell, or 0.
var used: bool; #! Whether anything reads what it holds, or copies it out.
}
#! What promoting knows of the cells of the code.
struct promotion {
var escaped: vector<bool>; #! Whether each cell's address is used as more than an address read and written through.
var extent: vector<u64>; #! How many bytes from its start the copies in and out of each cell move, which its slots must cover.
var slots: vector<slot>; #! The words of the cells, each once.
var heads: vector<u32>; #! One more than the first slot of each cell, or 0, its others following by `next`.
var addresses: cell_table; #! Which cell each value is the address of.
var ends: dict<u64, u32>; #! The value each slot holds at the end of each block that writes it, by `pair_key(slot, block)`.
var starts: dict<u64, u32>; #! The value each slot holds at the start of each block asked, by `pair_key(slot, block)`.
var zeros: zero_values; #! The zero of each type, made once.
var wide: bool; #! Whether 32 bytes of lanes may be a value.
var vectors: bool; #! Whether 16 bytes of lanes may be, as an executable's code holds them.
var pairs: vector<u32>; #! The copies from one cell into another.
var copies: dict<u64, u32>; #! The read each copy into a cell promoted makes of each slot, by `pair_key(copy, slot)`.
var touch: vector<u32>; #! The instructions naming a cell, as operands or as what their edges give.
var current: vector<u32>; #! What each slot holds where the walk of a block is, where the block wrote it.
var written: stamped_set; #! The slots the block being rewritten wrote so far, a round each block.
var dense: u64; #! How many blocks `ends` and `starts` are held for in `dense_ends` and `dense_starts`, by slot then block, or 0 where they are not.
var dense_ends: vector<u32>; #! What `ends` holds, where it is dense, 0 for nothing.
var dense_starts: vector<u32>; #! What `starts` holds, where it is dense.
}
#! What `promotion::slot_at` gives where a cell has no slot at an offset.
const no_slot: u32 = 0xFFFFFFFF;
#! The most slots of every block the values they hold at each block's ends are
#! held for one after another, rather than by key.
const dense_slot_blocks: u64 = 65536;
#! The value a slot holds where a block ends, where the block writes it.
#! @param this What promoting knows.
#! @param s The slot.
#! @param block The block.
#! @returns The value, or 0.
def promotion::end_at(&this, s: u32, block: u32): u32 {
return this.dense_ends[s as u64 * this.dense + block as u64] if this.dense != 0;
val key := pair_key(s, block);
return this.ends.get_or(&key, 0);
}
#! Notes the value a slot holds where a block ends.
#! @param this What promoting knows.
#! @param s The slot.
#! @param block The block.
#! @param value The value.
def promotion::set_end(&mut this, s: u32, block: u32, value: u32): void {
if this.dense != 0 {
this.dense_ends[s as u64 * this.dense + block as u64] = value;
return;
}
this.ends.set(pair_key(s, block), value);
}
#! The value a slot holds where a block begins, where it is known.
#! @param this What promoting knows.
#! @param s The slot.
#! @param block The block.
#! @returns The value, or 0.
def promotion::start_at(&this, s: u32, block: u32): u32 {
return this.dense_starts[s as u64 * this.dense + block as u64] if this.dense != 0;
val key := pair_key(s, block);
return this.starts.get_or(&key, 0);
}
#! Notes the value a slot holds where a block begins.
#! @param this What promoting knows.
#! @param s The slot.
#! @param block The block.
#! @param value The value.
def promotion::set_start(&mut this, s: u32, block: u32, value: u32): void {
if this.dense != 0 {
this.dense_starts[s as u64 * this.dense + block as u64] = value;
return;
}
this.starts.set(pair_key(s, block), value);
}
#! Promotes the cells that can be, as the file says.
#! @param this The code.
#! @returns Whether any was.
pub def code::promote_cells(&mut this): bool {
return false if this.cells.length == 0;
var state := promotion {
escaped = vector::<bool>::new(scratch()),
extent = vector::<u64>::new(scratch()),
slots = vector::<slot>::new(scratch()),
heads = vector::<u32>::new(scratch()),
addresses = this.cell_table(),
ends = dict::<u64, u32>::new(scratch()),
starts = dict::<u64, u32>::new(scratch()),
copies = dict::<u64, u32>::new(scratch()),
pairs = vector::<u32>::new(scratch()),
touch = vector::<u32>::new(scratch()),
current = vector::<u32>::new(scratch()),
written = stamped_set::new(0, scratch()),
dense_ends = vector::<u32>::new(scratch()),
dense_starts = vector::<u32>::new(scratch()),
wide = this.wide,
vectors = this.vectors
};
return false if !state.addresses.any;
state.escaped.resize(this.cells.length);
state.extent.resize(this.cells.length);
state.heads.resize(this.cells.length);
# A copy from a cell its words cover into another is the reads and writes of
# each word, which then promote as any others, so the words of the cells
# are found again, as many times as a value is copied on.
this.find_touches(&mut state);
var rounds := 0;
while true {
rounds++;
this.find_slots(&mut state);
break if rounds == 4 || !this.split_pairs(&mut state);
for c in 0..this.cells.length {
state.escaped[c] = false;
state.extent[c] = 0;
state.heads[c] = 0;
}
state.slots.clear();
state.pairs.clear();
}
this.settle_pairs(&mut state);
var promoted := false;
for c in 0..this.cells.length {
if !state.escaped[c] {
promoted = true;
}
}
return false if !promoted;
# Where control flow joins, slots are found in the order of the blocks.
if state.slots.length * this.blocks.length <= dense_slot_blocks {
state.dense = this.blocks.length;
state.dense_ends.resize(state.slots.length * state.dense);
state.dense_starts.resize(state.slots.length * state.dense);
}
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.block_order(&mut order, &mut number);
for &block in order {
this.note_ends(block, &mut state);
}
var done := rewrite::new();
state.current.resize(state.slots.length);
state.written = stamped_set::new(state.slots.length, scratch());
for &block in order {
state.written.next_round();
this.rewrite_slots(block, &mut state, &mut done);
}
this.apply(&done);
this.drop_unreached();
this.drop_lone_params();
return true;
}
#! Finds the instructions naming a cell, which are all that finding slots
#! walks.
#! @param this The code.
#! @param state What promoting knows.
def code::find_touches(&this, state: &mut promotion): void {
state.touch.clear();
var walk := this.walk_all();
var reads := this.reader();
while walk.more() {
val at := walk.next();
reads.start(at);
while reads.more() {
if state.addresses.cell(reads.next()) != 0 {
state.touch.append(at);
break;
}
}
}
}
#! Leaves memory the cell each copy between cells neither escaped comes from,
#! where the copy was not split, so the copy is one out of memory into the one
#! it goes to.
#! @param this The code.
#! @param state What promoting knows.
def code::settle_pairs(&this, state: &mut promotion): void {
var changed := false;
for &copy in state.pairs {
val to := state.addresses.cell(this.arg(copy, 0)) - 1;
val from := state.addresses.cell(this.arg(copy, 1)) - 1;
if !state.escaped[to] && !state.escaped[from] {
state.escaped[from] = true;
changed = true;
}
}
if changed {
this.find_uses(state);
}
}
#! Marks the slots of the cells not escaped that something reads, or copies
#! out of its cell, so a copy into the cell reads only those from where it
#! copies, and a slot read only as a copy moves it into another is used where
#! the other's is.
#! @param this The code.
#! @param state What promoting knows.
def code::find_uses(&this, state: &mut promotion): void {
for i in 0..state.slots.length {
state.slots[i].used = false;
}
for t in 0..state.touch.length {
val at: u32 = state.touch[t];
val held: inst = this.insts[at];
continue if held.kind != op::load && held.kind != op::copy;
val operand: u32 = held.kind == op::load ? 0 : 1;
val cell := state.addresses.cell(this.arg(at, operand));
val into := held.kind == op::copy ? state.addresses.cell(this.arg(at, 0)) : 0;
val moved := into != 0 && !state.escaped[into - 1];
continue if cell == 0 || state.escaped[cell - 1] || moved;
var i: u32 = state.heads[cell - 1];
while i != 0 {
val each: slot = state.slots[i - 1];
if (held.kind == op::load && each.offset == held.imm) || (held.kind == op::copy && each.offset < held.imm) {
state.slots[i - 1].used = true;
}
i = each.next;
}
}
var changed := true;
var rounds := 0;
while changed && rounds < 8 {
rounds++;
changed = false;
for p in 0..state.pairs.length {
val copy: u32 = state.pairs[p];
val to := state.addresses.cell(this.arg(copy, 0)) - 1;
val from := state.addresses.cell(this.arg(copy, 1)) - 1;
continue if state.escaped[to] || state.escaped[from];
var i: u32 = state.heads[from];
while i != 0 {
val each: slot = state.slots[i - 1];
if !each.used && each.offset < this.insts[copy].imm && state.used_over(to, each.offset, each.size) {
state.slots[i - 1].used = true;
changed = true;
}
i = each.next;
}
}
}
}
#! Finds how each cell's address is used, and the words each cell not escaped
#! holds, marking escaped a cell its words do not fit, and which of its words
#! are used. Copies between cells are gathered, to be split.
#! @param this The code.
#! @param state What promoting knows, whose instructions naming cells are
#! found.
def code::find_slots(&this, state: &mut promotion): void {
var reads := this.reader();
for t in 0..state.touch.length {
val at: u32 = state.touch[t];
val held: inst = this.insts[at];
reads.start(at);
while reads.more() {
val cell := state.addresses.cell(reads.next());
continue if cell == 0;
val c := cell - 1;
val i := reads.operand();
# A cell's address an edge gives escapes.
if i == no_operand {
state.escaped[c] = true;
continue;
}
match held.kind {
op::load => {
val how := held.aux as access;
state.add_slot(c, held.imm, how.width(), how.value_type(), narrow_signed(how));
}
op::store => {
if i == 0 {
state.add_slot(c, held.imm, (held.aux as access).width(), (held.aux as access).value_type(), false);
} else {
state.escaped[c] = true;
}
}
# A cell's address is never null, which inlining may check.
op::clear => {}
op::check => {
if held.aux != fault::null_reference as u32 {
state.escaped[c] = true;
}
}
op::copy => {
# A copy in or out of the cell from its start, between it and memory
# no cell promoted is, reads or writes each of the words it moves.
if held.imm > this.cells[c].size as u64 {
state.escaped[c] = true;
} else {
if i == 0 && state.addresses.cell(this.arg(at, 1)) != 0 {
state.pairs.append(at);
}
if held.imm > state.extent[c] {
state.extent[c] = held.imm;
}
}
}
else => state.escaped[c] = true;
}
}
}
# A copy between cells moves the words either reads or writes alone, so each
# holds the other's, from one to the next along a chain of copies.
var rounds := 0;
var changed := state.pairs.length != 0;
while changed && rounds < 8 {
rounds++;
changed = false;
for p in 0..state.pairs.length {
val copy: u32 = state.pairs[p];
val to := state.addresses.cell(this.arg(copy, 0)) - 1;
val from := state.addresses.cell(this.arg(copy, 1)) - 1;
val size: u64 = this.insts[copy].imm;
changed = state.share_slots(from, to, size) || changed;
changed = state.share_slots(to, from, size) || changed;
}
}
# Each cell's words must not overlap, and the bytes its copies move that no
# word holds are words of their own.
for c in 0..this.cells.length {
continue if state.escaped[c];
var i: u32 = state.heads[c];
while i != 0 {
val each: slot = state.slots[i - 1];
var j: u32 = each.next;
while j != 0 {
val other: slot = state.slots[j - 1];
if other.offset < each.offset + each.size && each.offset < other.offset + other.size {
state.escaped[c] = true;
}
j = other.next;
}
i = each.next;
}
if !state.escaped[c] && state.extent[c] != 0 {
state.fill_gaps(c as u32);
}
}
# Nor may a clear or a copy end within a word.
for t in 0..state.touch.length {
val at: u32 = state.touch[t];
val held: inst = this.insts[at];
continue if held.kind != op::clear && held.kind != op::copy;
for k in 0..held.argc {
val cell := state.addresses.cell(this.arg(at, k as u32));
continue if cell == 0 || state.escaped[cell - 1];
val c := cell - 1;
var i: u32 = state.heads[c];
while i != 0 {
val each: slot = state.slots[i - 1];
if each.offset < held.imm && held.imm < each.offset + each.size {
state.escaped[c] = true;
}
i = each.next;
}
}
}
this.find_uses(state);
}
#! Gives a cell the words another holds within the bytes a copy between them
#! moves, which it does not hold yet. An escaped cell's words say nothing of
#! the values another holds, as an array indexed holds what is read of it one
#! lane at a time, so it gives none, and a vector copied into it stays one.
#! @param this What promoting knows.
#! @param from The cell whose words are given.
#! @param to The cell given them.
#! @param size How many bytes the copy moves.
#! @returns Whether any was new.
def promotion::share_slots(&mut this, from: u32, to: u32, size: u64): bool {
return false if from == to || this.escaped[to] || this.escaped[from];
var added := false;
var i: u32 = this.heads[from];
while i != 0 {
val each: slot = this.slots[i - 1];
i = each.next;
continue if each.offset >= size || this.slot_at(to, each.offset) != no_slot;
this.add_slot(to, each.offset, each.size, each.kind, each.signed);
added = true;
}
return added;
}
#! Gives the bytes a cell's copies move that no word holds words of their own,
#! each as wide as where it begins and the bytes left allow.
#! @param this What promoting knows.
#! @param cell The cell, whose words do not overlap.
def promotion::fill_gaps(&mut this, cell: u32): void {
# The words it holds, by where each begins.
var held := vector::<u64>::new(scratch());
var i: u32 = this.heads[cell];
while i != 0 {
val each: slot = this.slots[i - 1];
held.append(pair_key(each.offset as u32, each.size as u32));
i = each.next;
}
held.sort();
val extent: u64 = this.extent[cell];
var at: u64 = 0;
for &key in held {
break if at >= extent;
val offset := pair_high(key) as u64;
this.fill(cell, at, offset < extent ? offset : extent);
val end := offset + pair_low(key) as u64;
if end > at {
at = end;
}
}
this.fill(cell, at, extent);
}
#! Gives bytes of a cell no word holds words of their own: in an executable's
#! code, each 16 bytes from a multiple of 16 a vector, which a copy moves with
#! one read and write, or 32 from a multiple of 32 in code for processors with
#! AVX, and the rest words.
#! @param this What promoting knows.
#! @param cell The cell.
#! @param from Where the bytes begin.
#! @param to Where they end.
def promotion::fill(&mut this, cell: u32, from: u64, to: u64): void {
var at := from;
while this.wide && at % 32 == 0 && at + 32 <= to {
this.add_slot(cell, at, 32, vt::v256, false);
at += 32;
}
while this.vectors && at % 16 == 0 && at + 16 <= to {
this.add_slot(cell, at, 16, vt::v128, false);
at += 16;
}
while at < to {
var width: u64 = 8;
while width > 1 && (at % width != 0 || at + width > to) {
width = width / 2;
}
this.add_slot(cell, at, width, vt::word, false);
at += width;
}
}
#! Splits each copy from a cell its words cover whole, and not escaped, into
#! another into a read of each word and a write of it where it goes.
#! @param this The code.
#! @param state What promoting knows.
#! @returns Whether any copy was split.
def code::split_pairs(&mut this, state: &mut promotion): bool {
var done := rewrite::new();
var added := vector::<u32>::new(scratch());
for p in 0..state.pairs.length {
val copy: u32 = state.pairs[p];
val held: inst = this.insts[copy];
val source := state.addresses.cell(this.arg(copy, 1)) - 1;
continue if state.escaped[source];
var covered: u64 = 0;
var i: u32 = state.heads[source];
while i != 0 {
if state.slots[i - 1].offset < held.imm {
covered += state.slots[i - 1].size;
}
i = state.slots[i - 1].next;
}
continue if covered != held.imm;
# Only the words the cell it goes to reads go, where it holds them, each
# after the copy, which goes.
val target := state.addresses.cell(this.arg(copy, 0)) - 1;
var after := copy;
i = state.heads[source];
while i != 0 {
val each: slot = state.slots[i - 1];
i = each.next;
continue if each.offset >= held.imm;
val there := state.slot_at(target, each.offset);
continue if !state.escaped[target] && there != no_slot && !state.slots[there].used;
var from: u32[1] = [this.arg(copy, 1)];
var gives: vt[1] = [each.kind];
val how := slot_access(&each) as u32;
val load := this.detached(op::load, from[0:1], gives[0:1], how, each.offset, held.at, held.site);
this.link_after(load, after);
var to: u32[2] = [this.arg(copy, 0), this.insts[load].result];
val store := this.detached(op::store, to[0:2], span::<vt>::empty(), how, each.offset, held.at, held.site);
this.link_after(store, load);
after = store;
added.append(load);
added.append(store);
}
done.remove(copy);
}
return false if !done.changed;
this.apply(&done);
# The instructions naming cells are those that did but the copies split, and
# the reads and writes they became.
var kept: u64 = 0;
for t in 0..state.touch.length {
val at: u32 = state.touch[t];
if !done.is_removed(at) {
state.touch[kept] = at;
kept++;
}
}
state.touch.resize(kept);
state.touch.extend(added.view());
return true;
}
#! Adds a word to those a cell holds, where it is new, marking the cell
#! escaped where the same offset is read or written as another width or kind,
#! or where it is 32 bytes of lanes and the code may run without AVX, or 64.
#! @param this What promoting knows.
#! @param cell The cell.
#! @param offset Where the word begins.
#! @param size How many bytes it is.
#! @param kind The type of value it holds.
#! @param signed Whether it is read as a signed integer narrower than a word.
def promotion::add_slot(&mut this, cell: u32, offset: u64, size: u64, kind: vt, signed: bool): void {
# 64 bytes of lanes stay in memory, as only code knowing the processor has
# AVX-512 holds them.
if kind == vt::v512 || (kind == vt::v256 && !this.wide) {
this.escaped[cell] = true;
return;
}
var i: u32 = this.heads[cell];
while i != 0 {
val each: slot = this.slots[i - 1];
if each.offset == offset {
if each.size != size || each.kind != kind {
this.escaped[cell] = true;
}
if signed {
this.slots[i - 1].signed = true;
}
return;
}
i = each.next;
}
this.slots.append(slot { cell = cell, offset = offset, size = size, kind = kind, signed = signed, next = this.heads[cell] });
this.heads[cell] = this.slots.length as u32;
}
#! The slot of a cell at an offset, or `no_slot`.
#! @param this What promoting knows.
#! @param cell The cell.
#! @param offset Where the word begins.
#! @returns The slot's index.
def promotion::slot_at(&this, cell: u32, offset: u64): u32 {
var i: u32 = this.heads[cell];
while i != 0 {
return i - 1 if this.slots[i - 1].offset == offset;
i = this.slots[i - 1].next;
}
return no_slot;
}
#! Whether a slot of a cell that bytes of it lie within is used. The cell copied
#! into may hold a word over several of the other's, as a vector over a struct's
#! fields where one cell holds each in turn, so each of those is used where the
#! word over it is.
#! @param this What promoting knows.
#! @param cell The cell.
#! @param offset Where the bytes begin.
#! @param size How many there are.
#! @returns Whether one is.
def promotion::used_over(&this, cell: u32, offset: u64, size: u64): bool {
var i: u32 = this.heads[cell];
while i != 0 {
val each: slot = this.slots[i - 1];
return true if each.used && each.offset < offset + size && offset < each.offset + each.size;
i = each.next;
}
return false;
}
#! Notes the value each slot holds at the end of a block that writes it: what
#! it last stores or copies in, or zero where it last clears it.
#! @param this The code.
#! @param block The block.
#! @param state What promoting knows.
def code::note_ends(&mut this, block: u32, state: &mut promotion): void {
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
continue if held.argc == 0;
val target := state.addresses.cell(this.arg(at, 0));
continue if target == 0 || state.escaped[target - 1];
val c := target - 1;
match held.kind {
op::store => {
state.set_end(state.slot_at(c, held.imm), block, this.arg(at, 1));
}
op::clear => {
var i: u32 = state.heads[c];
while i != 0 {
val s := i - 1;
val each: slot = state.slots[s];
i = each.next;
continue if each.offset >= held.imm;
state.set_end(s, block, state.zeros.of(this, each.kind));
}
}
# A copy in reads each word something reads from where it comes from,
# read here, before any block asks what a slot holds. Where nothing reads
# any, its first is still read, so an address that cannot be read stops
# the program there as the copy did.
op::copy => {
var reads := !this.checked_address(at, this.arg(at, 1));
var i: u32 = state.heads[c];
while i != 0 {
val each: slot = state.slots[i - 1];
if each.offset < held.imm && each.used {
reads = false;
}
i = each.next;
}
var after := at;
i = state.heads[c];
while i != 0 {
val s := i - 1;
val each: slot = state.slots[s];
i = each.next;
continue if each.offset >= held.imm || (!each.used && !(reads && each.offset == 0));
var args: u32[1] = [this.arg(at, 1)];
var gives: vt[1] = [each.kind];
val load := this.detached(op::load, args[0:1], gives[0:1], slot_access(&each) as u32, each.offset, held.at, held.site);
this.link_after(load, after);
after = load;
val value: u32 = this.insts[load].result;
state.copies.set(pair_key(at, s), value);
state.set_end(s, block, value);
}
}
else => {}
}
}
}
#! The value a slot holds at the start of a block: zero at the entry, what it
#! holds at the end of the one block going there, or else a parameter the
#! block takes, given what it holds at the end of each.
#! @param this The code.
#! @param s The slot.
#! @param block The block.
#! @param state What promoting knows.
#! @returns The value.
def code::slot_start(&mut this, s: u32, block: u32, state: &mut promotion): u32 {
val known := state.start_at(s, block);
return known if known != 0;
val kind := state.slots[s].kind;
val preds := this.blocks[block].preds.length;
if block == 0 || preds == 0 {
val zero := state.zeros.of(this, kind);
state.set_start(s, block, zero);
return zero;
}
if preds == 1 {
val edge: u32 = this.blocks[block].preds[0];
val made := this.slot_end(s, this.edge_source(edge), state);
state.set_start(s, block, made);
return made;
}
# Noted before its arguments are found, which may come back to it.
val param := this.add_param(block, kind);
state.set_start(s, block, param);
var edges := this.blocks[block].preds.copied(scratch());
for &edge in edges {
val given := this.slot_end(s, this.edge_source(edge), state);
this.edges[edge].args.append(given);
}
return param;
}
#! The value a slot holds at the end of a block.
#! @param this The code.
#! @param s The slot.
#! @param block The block.
#! @param state What promoting knows.
#! @returns The value.
def code::slot_end(&mut this, s: u32, block: u32, state: &mut promotion): u32 {
val known := state.end_at(s, block);
return known if known != 0;
return this.slot_start(s, block, state);
}
#! Notes what a slot holds where the walk of a block is.
#! @param this What promoting knows.
#! @param s The slot.
#! @param value The value.
def promotion::hold(&mut this, s: u32, value: u32): void {
this.current[s] = value;
this.written.put(s);
}
#! What a slot holds where the walk of a block is: what the block wrote last,
#! or what it holds where the block begins.
#! @param this The code.
#! @param s The slot.
#! @param block The block.
#! @param state What promoting knows.
#! @returns The value.
def code::slot_now(&mut this, s: u32, block: u32, state: &mut promotion): u32 {
return state.current[s] if state.written.contains(s);
return this.slot_start(s, block, state);
}
#! Rewrites the reads and writes of the slots of a block: a read reads what
#! the slot holds there, narrowed as the read narrows, and a write, a clear,
#! and a copy in or out go, a copy becoming reads or writes of its words.
#! @param this The code.
#! @param block The block.
#! @param state What promoting knows.
#! @param done What the pass changes.
def code::rewrite_slots(&mut this, block: u32, state: &mut promotion, done: &mut rewrite): void {
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
if held.kind == op::cell {
if !state.escaped[held.aux] {
done.remove(at);
}
continue;
}
continue if held.argc == 0;
val first := state.addresses.cell(this.arg(at, 0));
val c := first != 0 && !state.escaped[first - 1] ? first - 1 : no_cell;
match held.kind {
op::check => {
if c != no_cell {
done.remove(at);
}
}
op::load => {
if c != no_cell {
val s := state.slot_at(c, held.imm);
val value := this.slot_now(s, block, state);
this.read_slot(at, value, done);
}
}
op::store => {
if c != no_cell {
state.hold(state.slot_at(c, held.imm), this.arg(at, 1));
done.remove(at);
}
}
op::clear => {
if c != no_cell {
var i: u32 = state.heads[c];
while i != 0 {
val each: slot = state.slots[i - 1];
if each.offset < held.imm {
state.hold(i - 1, state.zeros.of(this, each.kind));
}
i = each.next;
}
done.remove(at);
}
}
op::copy => {
val from := state.addresses.cell(this.arg(at, 1));
if c != no_cell {
# Copied in: each word is what was read of where it comes from.
var i: u32 = state.heads[c];
while i != 0 {
val key := pair_key(at, i - 1);
if state.copies.get(&key) is some(got) {
state.hold(i - 1, got);
}
i = state.slots[i - 1].next;
}
done.remove(at);
} else if from != 0 && !state.escaped[from - 1] {
# Copied out: each word is written where it goes, after the copy,
# which goes.
val source := from - 1;
var after := at;
var i: u32 = state.heads[source];
while i != 0 {
val s := i - 1;
val each: slot = state.slots[s];
i = each.next;
continue if each.offset >= held.imm;
val value := this.slot_now(s, block, state);
var args: u32[2] = [this.arg(at, 0), value];
val store := this.detached(op::store, args[0:2], span::<vt>::empty(), slot_access(&each) as u32, each.offset, held.at, held.site);
this.link_after(store, after);
after = store;
}
done.remove(at);
}
}
else => {}
}
}
}
#! How a slot is read and written in memory where a copy moves it: a narrow
#! integer as it is read, so a field of `i32` copied is narrowed as a read of it
#! narrows it again, and the two are one.
#! @param each The slot.
#! @returns The access.
def slot_access(each: &slot): access {
return access::v128 if each.kind == vt::v128;
return access::v256 if each.kind == vt::v256;
return each.kind == vt::real ? (each.size == 4 ? access::f32 : access::f64) : match each.size {
1 => each.signed ? access::i8 : access::u8,
2 => each.signed ? access::i16 : access::u16,
4 => each.signed ? access::i32 : access::u32,
else => access::i64
};
}
#! Whether an access reads a signed integer narrower than a word.
#! @param how The access.
#! @returns Whether it does.
def narrow_signed(how: access): bool {
return how == access::i8 || how == access::i16 || how == access::i32;
}
#! Makes a read of a slot the value it holds, narrowed as the read narrows.
#! @param this The code.
#! @param index The `load`.
#! @param value What the slot holds.
#! @param done What the pass changes.
def code::read_slot(&mut this, index: u32, value: u32, done: &mut rewrite): void {
val how: access = this.insts[index].aux as access;
var args: u32[1] = [value];
match how {
access::i64, access::f64, access::v128, access::v256 => {
done.replace(this.insts[index].result, value);
done.remove(index);
}
access::f32 => this.become(index, op::fsingle, args[0:1], 0, 0);
access::u8 => this.become(index, op::wrap, args[0:1], 8, 0);
access::i8 => this.become(index, op::wrap, args[0:1], 8, 1);
access::u16 => this.become(index, op::wrap, args[0:1], 16, 0);
access::i16 => this.become(index, op::wrap, args[0:1], 16, 1);
access::u32 => this.become(index, op::wrap, args[0:1], 32, 0);
access::i32 => this.become(index, op::wrap, args[0:1], 32, 1);
else => {}
}
done.changed = true;
}
+925
View File
@@ -0,0 +1,925 @@
#! @file simplify.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the first pass of the optimizer, simplification: an operator of
#! constants becomes the constant it gives, worked out exactly as the machine
#! works it out; an operator whose result its operands already say becomes
#! that, as `x + 0` is `x` and `x == x` is 1; a multiplication, division, or
#! remainder of an unsigned word by a power of two becomes a shift or a mask;
#! a comparison with the least or greatest word says what it says of every
#! word, or asks only whether a word is one; a constant added to a word with a
#! constant added becomes one sum; a read of a datum, which is never written,
#! becomes what its bytes hold; a condition another says the opposite of is
#! read through it; a `select` whose choice is known is what it chooses; and a
#! check of what is known to hold goes.
module sakura::compiler;
#! Simplifies the code, as the file says, in one walk of its blocks.
#! @param this The code.
#! @param data The program's datums, which reads of them are read from.
#! @returns Whether anything changed.
pub def code::simplify(&mut this, data: span<datum>): bool {
var done := rewrite::new();
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.block_order(&mut order, &mut number);
for &block in order {
var walk := this.walk(block);
while walk.more() {
this.simplify_inst(walk.next(), data, &mut done);
}
}
this.apply(&done);
return done.changed;
}
#! Simplifies one instruction.
#! @param this The code.
#! @param index The instruction.
#! @param data The program's datums.
#! @param done What the pass changes.
def code::simplify_inst(&mut this, index: u32, data: span<datum>, done: &mut rewrite): void {
val held: inst = this.insts[index];
val kind := held.kind;
val number := kind as u32;
# Operands read what replaced them, so what is worked out of one value is
# worked out of what it was replaced by.
for i in 0..held.argc {
val at := held.args as u64 + i as u64;
this.operands[at] = done.resolve(this.operands[at]);
}
if number >= op::add as u32 && number <= op::leus as u32 {
this.simplify_word(index, done);
return;
}
if number >= op::fadd as u32 && number <= op::fle as u32 {
var x: u64 = 0;
var y: u64 = 0;
if this.real_constant(this.arg(index, 0), &mut x) && this.real_constant(this.arg(index, 1), &mut y) {
var made: u64 = 0;
if fold_real(kind, x, y, &mut made) {
if number >= op::feq as u32 {
this.become_word(index, made);
} else {
this.become_real(index, made);
}
done.changed = true;
}
}
return;
}
if number >= op::neg as u32 && number <= op::bswap as u32 {
this.simplify_unary(index, done);
return;
}
match kind {
op::wrap => this.simplify_wrap(index, done);
op::check => {
var bits: u64 = 0;
val cond := this.arg(index, 0);
if this.word_constant(cond, &mut bits) && bits != 0 {
done.remove(index);
return;
}
# The address of a cell, the globals, or a datum is never null.
val made := this.defining(cond);
if made != 0 && (this.insts[made].kind == op::cell || this.insts[made].kind == op::global || this.insts[made].kind == op::datum) {
done.remove(index);
return;
}
# A check of whether a word is not zero checks the word.
val inner := this.defining(cond);
if inner != 0 && this.insts[inner].kind == op::ne && this.is_zero(this.arg(inner, 1)) {
this.operands[held.args] = this.arg(inner, 0);
done.changed = true;
}
}
op::branch => this.simplify_branch(index, done);
op::select => this.simplify_select(index, done);
op::load => {
this.fold_offset(index, done);
this.read_datum(index, data, done);
}
op::store => {
this.fold_offset(index, done);
this.simplify_store(index, done);
}
else => {}
}
}
#! The offsets a read or write may be given by folding: a page, less the widest
#! access.
const folded_reach: u64 = 4096 - 32;
#! Folds a constant added to the address a read or write is given into its
#! offset, so it is addressed as `[base + offset]` and a cell read at a field is
#! read at that offset of the cell. Only offsets within the page no program
#! maps, which reaching through null faults in on its own; one past it would
#! need an executable to test the base first.
#! @param this The code.
#! @param index The `load` or `store`.
#! @param done What the pass changes.
def code::fold_offset(&mut this, index: u32, done: &mut rewrite): void {
val inner := this.defining(this.arg(index, 0));
return if inner == 0 || this.insts[inner].kind != op::add;
var bits: u64 = 0;
var base: u32 = 0;
if this.word_constant(this.arg(inner, 1), &mut bits) {
base = this.arg(inner, 0);
} else if this.word_constant(this.arg(inner, 0), &mut bits) {
base = this.arg(inner, 1);
} else {
return;
}
val offset := this.insts[index].imm + bits;
return if bits >= folded_reach || offset >= folded_reach;
this.operands[this.insts[index].args as u64] = base;
this.insts[index].imm = offset;
done.changed = true;
}
#! Reads while compiling what a read of a datum reads, since a datum is never
#! written: the word or real its bytes hold, or, for a whole word where a
#! relocation is, the address it holds. A read of an `f32`, of lanes, or across
#! part of an address stays.
#! @param this The code.
#! @param index The `load`.
#! @param data The program's datums.
#! @param done What the pass changes.
def code::read_datum(&mut this, index: u32, data: span<datum>, done: &mut rewrite): void {
val from := this.defining(this.arg(index, 0));
return if from == 0 || this.insts[from].kind != op::datum;
val target: u64 = this.insts[from].aux;
return if target >= data.length;
val held := &data[target];
val how := this.insts[index].aux as access;
return if how == access::f32 || how == access::bytes || how.value_type().lanes();
val width := how.width();
val start := this.insts[from].imm + this.insts[index].imm;
return if start >= held.bytes.length || width > held.bytes.length - start;
for &each in held.relocations {
continue if each.at + word_size <= start || each.at >= start + width;
return if each.at != start || how != access::i64;
this.become(index, op::datum, span::<u32>::empty(), each.target, each.addend);
done.changed = true;
return;
}
var bits: u64 = 0;
for i in 0..width {
bits = bits | ((held.bytes[start + i as u64] as u64) << (8 * i as u64));
}
match how {
access::i8 => bits = wrap_word(bits, 8, true);
access::i16 => bits = wrap_word(bits, 16, true);
access::i32 => bits = wrap_word(bits, 32, true);
access::f64 => {
this.become_real(index, bits);
done.changed = true;
return;
}
else => {}
}
this.become_word(index, bits);
done.changed = true;
}
#! Simplifies a write of a narrow value: one narrowed to at least as many bits
#! as the write keeps, or an `f32` rounded already, is written as it was.
#! @param this The code.
#! @param index The `store`.
#! @param done What the pass changes.
def code::simplify_store(&mut this, index: u32, done: &mut rewrite): void {
val value := this.arg(index, 1);
val inner := this.defining(value);
return if inner == 0;
val how := this.insts[index].aux as access;
val kind := this.insts[inner].kind;
if kind == op::fsingle && how == access::f32 {
this.operands[this.insts[index].args as u64 + 1] = this.arg(inner, 0);
done.changed = true;
return;
}
return if kind != op::wrap || how == access::f32 || how == access::f64 || how == access::bytes;
if this.insts[inner].aux as u64 >= 8 * how.width() {
this.operands[this.insts[index].args as u64 + 1] = this.arg(inner, 0);
done.changed = true;
}
}
#! Whether a value is known to have every bit of a word set: the processor's
#! instruction sets, where a version knows which it has.
#! @param this The code.
#! @param value The value.
#! @param bits The bits.
#! @returns Whether it is.
def code::holds_bits(&this, value: u32, bits: u64): bool {
val made := this.defining(value);
return made != 0 && this.insts[made].kind == op::cpu && (bits & ~this.insts[made].imm) == 0;
}
#! Simplifies an operator of two words.
#! @param this The code.
#! @param index The instruction.
#! @param done What the pass changes.
def code::simplify_word(&mut this, index: u32, done: &mut rewrite): void {
val kind := this.insts[index].kind;
var a := this.arg(index, 0);
var b := this.arg(index, 1);
var x: u64 = 0;
var y: u64 = 0;
val known_a := this.word_constant(a, &mut x);
val known_b := this.word_constant(b, &mut y);
if known_a && known_b {
var made: u64 = 0;
if fold_word(kind, x, y, &mut made) {
this.become_word(index, made);
done.changed = true;
}
return;
}
# A constant goes on the right of what does not mind which side it is on.
var right := known_b;
if known_a && !known_b && commutes(kind) {
var swapped: u32[2] = [b, a];
this.become(index, kind, swapped[0:2], 0, 0);
a = swapped[0];
b = swapped[1];
y = x;
right = true;
done.changed = true;
}
# What the operands say whatever they are.
if a == b {
match kind {
op::sub, op::bxor, op::ne, op::ltu, op::lts => {
this.become_word(index, 0);
done.changed = true;
return;
}
op::eq, op::leu, op::les => {
this.become_word(index, 1);
done.changed = true;
return;
}
op::band, op::bor => {
this.forward_to(index, a, done);
return;
}
else => {}
}
}
# A never-zero address compared with zero.
if (kind == op::eq || kind == op::ne) && this.is_zero(b) && this.never_zero(a) {
this.become_word(index, kind == op::ne ? 1 : 0);
done.changed = true;
return;
}
if known_a && !right {
this.simplify_left_order(index, b, x, done);
return;
}
return if !right;
match kind {
op::add, op::sub => {
if y == 0 {
this.forward_to(index, a, done);
} else {
this.combine_steps(index, a, kind == op::add ? y : 0 - y, done);
}
}
op::bor, op::bxor, op::shl, op::shru, op::shrs => {
if y == 0 {
this.forward_to(index, a, done);
}
}
op::mul => {
if y == 0 {
this.become_word(index, 0);
done.changed = true;
} else if y == 1 {
this.forward_to(index, a, done);
} else if is_power(y) {
this.become_shift(index, op::shl, a, log2(y));
done.changed = true;
}
}
op::divs, op::divu => {
if y == 1 {
this.forward_to(index, a, done);
} else if kind == op::divu && is_power(y) {
this.become_shift(index, op::shru, a, log2(y));
done.changed = true;
}
}
op::rems, op::remu => {
if y == 1 {
this.become_word(index, 0);
done.changed = true;
} else if kind == op::remu && is_power(y) {
var operands: u32[2] = [a, this.word_value(y - 1)];
this.become(index, op::band, operands[0:2], 0, 0);
done.changed = true;
}
}
op::band => {
if y == 0 {
this.become_word(index, 0);
done.changed = true;
} else if y == 0xFFFFFFFFFFFFFFFFu {
this.forward_to(index, a, done);
} else if this.holds_bits(a, y) {
this.become_word(index, y);
done.changed = true;
}
}
op::ltu => {
if y == 0 {
this.become_word(index, 0);
done.changed = true;
} else if y == 1 {
this.become_compare(index, op::eq, a, 0);
done.changed = true;
}
}
op::leu => {
if y == greatest_unsigned {
this.become_word(index, 1);
done.changed = true;
} else if y == 0 {
this.become_compare(index, op::eq, a, 0);
done.changed = true;
}
}
op::lts => {
if y == least_signed {
this.become_word(index, 0);
done.changed = true;
} else if y == least_signed + 1 {
this.become_compare(index, op::eq, a, least_signed);
done.changed = true;
}
}
op::les => {
if y == greatest_signed {
this.become_word(index, 1);
done.changed = true;
} else if y == least_signed {
this.become_compare(index, op::eq, a, least_signed);
done.changed = true;
}
}
else => {}
}
}
#! The greatest unsigned word.
const greatest_unsigned: u64 = 0xFFFFFFFFFFFFFFFFu;
#! The least signed word, as its bits.
const least_signed: u64 = 0x8000000000000000u;
#! The greatest signed word, as its bits.
const greatest_signed: u64 = 0x7FFFFFFFFFFFFFFFu;
#! Simplifies an order whose left operand is a constant, which stays on the
#! left: one no word comes after, or every word does, says what it says of
#! every word, as `MAX < x` is 0, and one only a single word comes after asks
#! whether the word is that one, as `0 < x` asks whether `x` is not zero.
#! @param this The code.
#! @param index The comparison.
#! @param b Its right operand.
#! @param x The constant on its left.
#! @param done What the pass changes.
def code::simplify_left_order(&mut this, index: u32, b: u32, x: u64, done: &mut rewrite): void {
match this.insts[index].kind {
op::ltu => {
if x == greatest_unsigned {
this.become_word(index, 0);
} else if x == 0 {
this.become_compare(index, op::ne, b, 0);
} else {
return;
}
}
op::leu => {
if x == 0 {
this.become_word(index, 1);
} else if x == greatest_unsigned {
this.become_compare(index, op::eq, b, greatest_unsigned);
} else {
return;
}
}
op::lts => {
if x == greatest_signed {
this.become_word(index, 0);
} else if x == least_signed {
this.become_compare(index, op::ne, b, least_signed);
} else {
return;
}
}
op::les => {
if x == least_signed {
this.become_word(index, 1);
} else if x == greatest_signed {
this.become_compare(index, op::eq, b, greatest_signed);
} else {
return;
}
}
else => return;
}
done.changed = true;
}
#! Makes an instruction a comparison of a word with a constant.
#! @param this The code.
#! @param index The instruction.
#! @param kind The comparison.
#! @param a The word.
#! @param bits The constant.
def code::become_compare(&mut this, index: u32, kind: op, a: u32, bits: u64): void {
var operands: u32[2] = [a, this.word_value(bits)];
this.become(index, kind, operands[0:2], 0, 0);
}
#! Adds a constant to a word that is itself a word with a constant added or
#! taken away, as one sum of both, so `(x + 4) + 8` is `x + 12`, and the inner
#! one goes where nothing else reads it.
#! @param this The code.
#! @param index The `add` or `sub`.
#! @param a The word it adds to.
#! @param step What it adds, as a wrapping word: what a `sub` takes away, negated.
#! @param done What the pass changes.
def code::combine_steps(&mut this, index: u32, a: u32, step: u64, done: &mut rewrite): void {
val inner := this.defining(a);
return if inner == 0;
val kind := this.insts[inner].kind;
return if kind != op::add && kind != op::sub;
var bits: u64 = 0;
return if !this.word_constant(this.arg(inner, 1), &mut bits);
val total := step + (kind == op::add ? bits : 0 - bits);
val base := this.arg(inner, 0);
if total == 0 {
this.forward_to(index, base, done);
return;
}
var operands: u32[2] = [base, this.word_value(total)];
this.become(index, op::add, operands[0:2], 0, 0);
done.changed = true;
}
#! Makes an instruction a shift of a word by a constant.
#! @param this The code.
#! @param index The instruction.
#! @param kind The shift.
#! @param a The word.
#! @param by How far it shifts.
def code::become_shift(&mut this, index: u32, kind: op, a: u32, by: u64): void {
var operands: u32[2] = [a, this.word_value(by)];
this.become(index, kind, operands[0:2], 0, 0);
}
#! Replaces what an instruction gives with a value, taking the instruction out.
#! @param this The code.
#! @param index The instruction.
#! @param value The value its result is.
#! @param done What the pass changes.
def code::forward_to(&mut this, index: u32, value: u32, done: &mut rewrite): void {
done.replace(this.insts[index].result, value);
done.remove(index);
}
#! Whether a value is the word zero.
#! @param this The code.
#! @param value The value.
#! @returns Whether it is.
def code::is_zero(&this, value: u32): bool {
var bits: u64 = 0;
return this.word_constant(value, &mut bits) && bits == 0;
}
#! Simplifies an operator of one value.
#! @param this The code.
#! @param index The instruction.
#! @param done What the pass changes.
def code::simplify_unary(&mut this, index: u32, done: &mut rewrite): void {
val kind := this.insts[index].kind;
val a := this.arg(index, 0);
var bits: u64 = 0;
val word := this.word_constant(a, &mut bits);
val real := !word && this.real_constant(a, &mut bits);
if word || real {
var made: u64 = 0;
val gives_real := kind == op::fneg || kind == op::itof || kind == op::utof || kind == op::fsingle || kind == op::fsqrt;
if fold_unary(kind, bits, &mut made) {
if gives_real {
this.become_real(index, made);
} else {
this.become_word(index, made);
}
done.changed = true;
}
return;
}
val inner := this.defining(a);
return if inner == 0;
val from: inst = this.insts[inner];
match kind {
# The opposite of a comparison is the comparison that says it.
op::lnot => {
var flipped := op::count;
var swap := false;
match from.kind {
op::eq => flipped = op::ne;
op::ne => flipped = op::eq;
op::ltu => { flipped = op::leu; swap = true; }
op::leu => { flipped = op::ltu; swap = true; }
op::lts => { flipped = op::les; swap = true; }
op::les => { flipped = op::lts; swap = true; }
op::ltsu => { flipped = op::leus; swap = true; }
op::lesu => { flipped = op::ltus; swap = true; }
op::ltus => { flipped = op::lesu; swap = true; }
op::leus => { flipped = op::ltsu; swap = true; }
op::lnot => {
if this.is_flag(this.arg(inner, 0)) {
this.forward_to(index, this.arg(inner, 0), done);
}
return;
}
else => return;
}
val x := this.arg(inner, 0);
val y := this.arg(inner, 1);
var operands: u32[2] = swap ? [y, x] : [x, y];
this.become(index, flipped, operands[0:2], 0, 0);
done.changed = true;
}
op::fsingle => {
if from.kind == op::fsingle || (from.kind == op::load && from.aux == access::f32 as u32) {
this.forward_to(index, a, done);
}
}
op::neg, op::bnot => {
if from.kind == kind {
this.forward_to(index, this.arg(inner, 0), done);
}
}
else => {}
}
}
#! Whether a word is 0 or 1, as a comparison gives.
#! @param this The code.
#! @param value The word.
#! @returns Whether it is.
def code::is_flag(&this, value: u32): bool {
var bits: u64 = 0;
return bits <= 1 if this.word_constant(value, &mut bits);
val index := this.defining(value);
return false if index == 0;
val number := this.insts[index].kind as u32;
return (number >= op::eq as u32 && number <= op::leus as u32)
|| (number >= op::feq as u32 && number <= op::fle as u32)
|| number == op::lnot as u32;
}
#! Simplifies the narrowing of a word, which goes where the word is already as
#! narrow, and narrows what was narrowed less where it narrows more, or the
#! same, the other way: `wrap(wrap(x, 32, unsigned), 32, signed)` is
#! `wrap(x, 32, signed)`.
#! @param this The code.
#! @param index The instruction.
#! @param done What the pass changes.
def code::simplify_wrap(&mut this, index: u32, done: &mut rewrite): void {
val held: inst = this.insts[index];
val a := this.arg(index, 0);
val bits := held.aux;
val signed := held.imm != 0;
if bits >= 64 {
this.forward_to(index, a, done);
return;
}
var value: u64 = 0;
if this.word_constant(a, &mut value) {
this.become_word(index, wrap_word(value, bits, signed));
done.changed = true;
return;
}
# The bits a word is held in already, and whether they are signed.
var held_bits: u32 = 64;
var held_signed := false;
val inner := this.defining(a);
if inner != 0 {
val from: inst = this.insts[inner];
match from.kind {
op::wrap => {
held_bits = from.aux;
held_signed = from.imm != 0;
# Narrowing more than what was narrowed, or as much the other way, narrows
# the word itself.
if bits < held_bits || (bits == held_bits && signed != held_signed) {
var operands: u32[1] = [this.arg(inner, 0)];
this.become(index, op::wrap, operands[0:1], bits, held.imm);
done.changed = true;
return;
}
}
op::load, op::atomic => {
match from.kind == op::load ? from.aux as access : atomic_access(from.imm) {
access::u8 => held_bits = 8;
access::i8 => { held_bits = 8; held_signed = true; }
access::u16 => held_bits = 16;
access::i16 => { held_bits = 16; held_signed = true; }
access::u32 => held_bits = 32;
access::i32 => { held_bits = 32; held_signed = true; }
else => {}
}
}
else => {
if this.is_flag(a) {
held_bits = 1;
}
}
}
}
if (signed == held_signed && bits >= held_bits) || (!held_signed && bits > held_bits) || this.param_narrow(a, bits, signed) {
this.forward_to(index, a, done);
}
}
#! Whether a block's parameter is a word as narrow as a narrowing makes it
#! already: every edge into the block gives it one so narrowed, or the
#! parameter itself, as a loop keeps a field of `i32` it adds to.
#! @param this The code.
#! @param value The parameter.
#! @param bits The bits it would be narrowed to.
#! @param signed Whether it would be extended by its sign.
#! @returns Whether it is.
def code::param_narrow(&this, value: u32, bits: u32, signed: bool): bool {
return false if value == 0 || (value as u64) >= this.origins.length;
val held: origin = this.origins[value];
return false if !held.param;
val preds := &this.blocks[held.from].preds;
return false if preds.length == 0;
for &e in preds.view() {
val given: u32 = this.edges[e as u64].args[held.index as u64];
continue if given == value;
val made := this.defining(given);
return false if made == 0;
val from: inst = this.insts[made];
var fits := false;
if from.kind == op::wrap {
fits = (from.imm != 0) == signed ? from.aux <= bits : from.imm == 0 && from.aux < bits;
} else if from.kind == op::iconst {
fits = wrap_word(from.imm, bits, signed) == from.imm;
}
return false if !fits;
}
return true;
}
#! Simplifies a `branch`: one on a condition's opposite goes the other way on
#! the condition, and one on whether a word is not zero branches on the word.
#! @param this The code.
#! @param index The `branch`.
#! @param done What the pass changes.
def code::simplify_branch(&mut this, index: u32, done: &mut rewrite): void {
var steps := 0;
while steps < 8 {
steps++;
val cond := this.arg(index, 0);
val inner := this.defining(cond);
return if inner == 0;
val from: inst = this.insts[inner];
if from.kind == op::lnot {
this.operands[this.insts[index].args] = this.arg(inner, 0);
this.swap_branch(index);
done.changed = true;
continue;
}
return if (from.kind != op::ne && from.kind != op::eq) || !this.is_zero(this.arg(inner, 1));
this.operands[this.insts[index].args] = this.arg(inner, 0);
if from.kind == op::eq {
this.swap_branch(index);
}
done.changed = true;
}
}
#! Simplifies a `select`: one on a constant, or between one value either way,
#! is the value it chooses; one on a condition's opposite, or on whether a word
#! is not zero, chooses on the condition or the word the other way round or the
#! same; one choosing 1 or 0 by a word is whether the word is not zero, which
#! is the word where it is 0 or 1, or is zero; and one choosing the condition
#! itself or 0 is the condition.
#! @param this The code.
#! @param index The `select`.
#! @param done What the pass changes.
def code::simplify_select(&mut this, index: u32, done: &mut rewrite): void {
var steps := 0;
while steps < 8 {
steps++;
val cond := this.arg(index, 0);
val a := this.arg(index, 1);
val b := this.arg(index, 2);
var bits: u64 = 0;
if this.word_constant(cond, &mut bits) {
this.forward_to(index, bits != 0 ? a : b, done);
return;
}
if a == b || (a == cond && this.is_zero(b)) {
this.forward_to(index, a, done);
return;
}
var x: u64 = 0;
var y: u64 = 0;
if this.word_constant(a, &mut x) && this.word_constant(b, &mut y) {
if x == 1 && y == 0 && this.is_flag(cond) {
this.forward_to(index, cond, done);
return;
}
if x == 1 && y == 0 {
var operands: u32[2] = [cond, this.word_value(0)];
this.become(index, op::ne, operands[0:2], 0, 0);
done.changed = true;
return;
}
if x == 0 && y == 1 {
var operands: u32[1] = [cond];
this.become(index, op::lnot, operands[0:1], 0, 0);
done.changed = true;
return;
}
}
# A condition worked out from another is read through it.
val inner := this.defining(cond);
return if inner == 0;
val from: inst = this.insts[inner];
val opposite := from.kind == op::lnot || (from.kind == op::eq && this.is_zero(this.arg(inner, 1)));
return if !opposite && (from.kind != op::ne || !this.is_zero(this.arg(inner, 1)));
var operands: u32[3] = opposite ? [this.arg(inner, 0), b, a] : [this.arg(inner, 0), a, b];
this.become(index, op::select, operands[0:3], 0, 0);
done.changed = true;
}
}
#! Whether an operator of two words gives the same whichever side each is on.
#! @param kind The operator.
#! @returns Whether it does.
def commutes(kind: op): bool {
return kind == op::add || kind == op::mul || kind == op::band || kind == op::bor || kind == op::bxor
|| kind == op::eq || kind == op::ne;
}
#! Whether a word is a power of two.
#! @param bits The word.
#! @returns Whether it is.
def is_power(bits: u64): bool {
return bits != 0 && (bits & (bits - 1)) == 0;
}
#! Which power of two a word is.
#! @param bits The word, a power of two.
#! @returns The power.
def log2(bits: u64): u64 {
var at := bits;
var power: u64 = 0;
while at > 1 {
at = at >> 1;
power++;
}
return power;
}
#! A word narrowed to a number of bits, as the machine narrows it.
#! @param value The word.
#! @param bits How many bits it keeps.
#! @param signed Whether it is sign-extended rather than zero-extended.
#! @returns The word narrowed.
pub def wrap_word(value: u64, bits: u32, signed: bool): u64 {
return value if bits >= 64;
val mask := (1u << bits as u64) - 1;
var made := value & mask;
if signed && (made >> (bits as u64 - 1)) != 0 {
made = made | ~mask;
}
return made;
}
#! What an operator of two words gives, as the machine works it out.
#! @param kind The operator.
#! @param a The first word.
#! @param b The second word.
#! @param made Where what it gives is written.
#! @returns Whether it gives anything: not where it divides by zero, which
#! stops the program.
pub def fold_word(kind: op, a: u64, b: u64, made: &mut u64): bool {
match kind {
op::add => made = a + b;
op::sub => made = a - b;
op::mul => made = a * b;
op::divs, op::divu, op::rems, op::remu => {
return false if b == 0;
if kind == op::divu {
made = a / b;
} else if kind == op::remu {
made = a % b;
} else if (b as i64) == -1 {
made = kind == op::divs ? 0 - a : 0;
} else if kind == op::divs {
made = ((a as i64) / (b as i64)) as u64;
} else {
made = ((a as i64) % (b as i64)) as u64;
}
}
op::band => made = a & b;
op::bor => made = a | b;
op::bxor => made = a ^ b;
op::shl => made = a << b;
op::shru => made = a >> b;
op::shrs => made = ((a as i64) >> b) as u64;
op::eq => made = a == b ? 1 : 0;
op::ne => made = a != b ? 1 : 0;
op::lts => made = (a as i64) < (b as i64) ? 1 : 0;
op::ltu => made = a < b ? 1 : 0;
op::les => made = (a as i64) <= (b as i64) ? 1 : 0;
op::leu => made = a <= b ? 1 : 0;
op::eqsu => made = (a as i64) >= 0 && a == b ? 1 : 0;
op::ltsu => made = (a as i64) < 0 || a < b ? 1 : 0;
op::lesu => made = (a as i64) < 0 || a <= b ? 1 : 0;
op::ltus => made = (b as i64) >= 0 && a < b ? 1 : 0;
op::leus => made = (b as i64) >= 0 && a <= b ? 1 : 0;
else => return false;
}
return true;
}
#! What an operator of two reals gives, as the machine works it out: a real's
#! bits, or a word of 0 or 1 for a comparison.
#! @param kind The operator.
#! @param a The bits of the first real.
#! @param b The bits of the second real.
#! @param made Where what it gives is written.
#! @returns Whether it gives anything.
pub def fold_real(kind: op, a: u64, b: u64, made: &mut u64): bool {
val x := real_of(a);
val y := real_of(b);
match kind {
op::fadd => made = bits_of_real(x + y);
op::fsub => made = bits_of_real(x - y);
op::fmul => made = bits_of_real(x * y);
op::fdiv => made = bits_of_real(x / y);
op::frem => made = bits_of_real(x % y);
op::feq => made = x == y ? 1 : 0;
op::fne => made = x != y ? 1 : 0;
op::flt => made = x < y ? 1 : 0;
op::fle => made = x <= y ? 1 : 0;
else => return false;
}
return true;
}
#! What an operator of one value gives, as the machine works it out.
#! @param kind The operator.
#! @param a The bits of the word or real it takes.
#! @param made Where the bits of what it gives are written.
#! @returns Whether it gives anything.
pub def fold_unary(kind: op, a: u64, made: &mut u64): bool {
match kind {
op::neg => made = 0 - a;
op::bnot => made = ~a;
op::lnot => made = a == 0 ? 1 : 0;
op::fneg => made = bits_of_real(-real_of(a));
op::itof => made = bits_of_real((a as i64) as f64);
op::utof => made = bits_of_real(a as f64);
op::ftoi => made = (real_of(a) as i64) as u64;
op::ftou => made = real_of(a) as u64;
op::fsingle => made = bits_of_real((real_of(a) as f32) as f64);
op::fsqrt => made = bits_of_real(root_of(real_of(a)));
op::ones => made = ones_of(a);
op::clz => made = leading_zeros_of(a);
op::ctz => made = trailing_zeros_of(a);
op::bswap => made = bytes_swapped(a);
else => return false;
}
return true;
}
+271
View File
@@ -0,0 +1,271 @@
#! @file sink.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the tenth pass of the optimizer, code sinking: an instruction whose
#! values are read only past one way out of its block moves into the block
#! that way goes to, where nothing else goes there, so what it works out is
#! worked out only where it is read. What moves only works out its values and
#! cannot stop the program, or reads memory. A read moves only where nothing
#! after it in its block may write what it reads, as alias analysis tells, and
#! where it cannot stop the program but as it would have: its address is read
#! or written through, or checked, before it, or after it in its block before
#! anything the program would be seen to do. A block one way alone goes into
#! heads no loop, so nothing moves into a loop it was not in. Blocks are walked
#! before those they dominate, each from its end, so what moved may move on
#! again.
import std::containers;
module sakura::compiler;
#! What sinking knows of the code as it goes. What reads ask of is found the
#! first time a read may move, as most code has none that may.
struct sinking {
var idom: vector<u32>; #! The immediate dominator of each block.
var readers: groups<u32>; #! The instructions reading each value, by value, once each time they read it.
var reached: dict<u64, u32>; #! How many instructions read or write through each address, or check it, in each block, by `pair_key(address, block)`.
var list: vector<u32>; #! The instructions of the block walked, in order, each that moved out 0.
var aliases: aliases; #! What may write what.
var writes: span<u64>; #! Of each instruction, the bytes a call writes what it returns to at its last operand, or 0.
var ready: bool; #! Whether `reached` and `aliases` are found.
}
#! Sinks the code of a function, knowing what each call writes what it
#! returns to.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether anything moved.
def lowerer::sink_code(&mut this, index: u32): bool {
val writes := this.result_writes(index);
return this.program.functions[index].body.sink_code(writes.view());
}
#! Sinks the code, as the file says.
#! @param this The code.
#! @param writes Of each instruction, the bytes a call writes what it returns
#! to at its last operand, or 0.
#! @returns Whether anything moved.
pub def code::sink_code(&mut this, writes: span<u64>): bool {
# Only a block going more than one way has anything to move out of it.
var ways := false;
for b in 0..this.blocks.length {
if !this.blocks[b].gone && this.edge_count(this.blocks[b].last) >= 2 {
ways = true;
break;
}
}
return false if !ways;
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
this.block_order(&mut order, &mut number);
var state := sinking {
idom = this.block_dominators(),
readers = groups::<u32>::new(this.origins.length, scratch()),
reached = dict::<u64, u32>::new(scratch()),
list = vector::<u32>::new(scratch()),
writes = writes
};
# What reads each value, counted then put.
var walk := this.walk_all();
var reads := this.reader();
while walk.more() {
reads.start(walk.next());
while reads.more() {
state.readers.count(reads.next());
}
}
state.readers.seal();
var again := this.walk_all();
while again.more() {
val at := again.next();
reads.start(at);
while reads.more() {
state.readers.put(reads.next(), at);
}
}
var changed := false;
for &block in order {
val last: u32 = this.blocks[block].last;
continue if this.edge_count(last) < 2;
changed = this.sink_block(block, &mut state) || changed;
}
return changed;
}
#! Finds what reads moving ask of the code, where it is not yet found: what
#! may write what, and what reaches through each address in each block, as the
#! code is now.
#! @param this The code.
#! @param state What sinking knows.
def code::ready_sinking(&this, state: &mut sinking): void {
return if state.ready;
state.ready = true;
state.aliases = this.aliases(state.writes, state.idom.view());
var walk := this.walk_all();
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
match held.kind {
op::load, op::store, op::clear, op::copy, op::check => {
val first := this.arg(at, 0);
if this.reaches(at, first) {
val key := pair_key(first, held.block);
state.reached.set(key, state.reached.get_or(&key, 0) + 1);
}
if held.kind == op::copy && held.imm != 0 && this.arg(at, 1) != first {
val key := pair_key(this.arg(at, 1), held.block);
state.reached.set(key, state.reached.get_or(&key, 0) + 1);
}
}
else => {}
}
}
}
#! Whether an instruction reads or writes memory through an address, or checks
#! it is not null, so that it stops the program where the address is null.
#! @param this The code.
#! @param index The instruction.
#! @param address The address.
#! @returns Whether it does.
def code::reaches(&this, index: u32, address: u32): bool {
val held := &this.insts[index];
return match held.kind {
op::load, op::store => this.arg(index, 0) == address,
op::clear => held.imm != 0 && this.arg(index, 0) == address,
op::copy => held.imm != 0 && (this.arg(index, 0) == address || this.arg(index, 1) == address),
op::check => held.aux == fault::null_reference as u32 && this.arg(index, 0) == address,
else => false
};
}
#! Moves what a block works out only for one way out of it into the block
#! that way goes to, from the block's end.
#! @param this The code.
#! @param block The block, which ends going more than one way.
#! @param state What sinking knows.
#! @returns Whether anything moved.
def code::sink_block(&mut this, block: u32, state: &mut sinking): bool {
state.list.clear();
var walk := this.walk(block);
while walk.more() {
state.list.append(walk.next());
}
var changed := false;
var k := state.list.length - 1;
while k > 0 {
k--;
val index: u32 = state.list[k];
val into := this.sink_target(index, block, state);
continue if into == no_block;
val load := this.insts[index].kind == op::load;
if load {
this.ready_sinking(state);
}
continue if load && !this.load_sinks(index, k, block, state);
# Those before it are all still in the block.
val prior: u32 = k == 0 ? 0 : state.list[k - 1];
if prior == 0 {
this.blocks[block].first = this.insts[index].next;
} else {
this.insts[prior].next = this.insts[index].next;
}
this.put_first(into, index);
state.list[k] = 0;
changed = true;
if load {
val address := this.arg(index, 0);
val from := pair_key(address, block);
state.reached.set(from, state.reached.get_or(&from, 1) - 1);
val to := pair_key(address, into);
state.reached.set(to, state.reached.get_or(&to, 0) + 1);
}
}
return changed;
}
#! Where an instruction of a block may move: the block one way out of it goes
#! to, where nothing else goes, past which everything reading its values is.
#! @param this The code.
#! @param index The instruction.
#! @param block Its block.
#! @param state What sinking knows.
#! @returns The block, or `no_block` where it stays.
def code::sink_target(&this, index: u32, block: u32, state: &sinking): u32 {
val held: inst = this.insts[index];
return no_block if held.count == 0 || held.kind.made_anywhere();
return no_block if held.kind != op::load && !this.removable(index);
var target := no_block;
for r in 0..held.count {
for &reader in state.readers.of(held.result + r as u32) {
# The block it dominates most nearly that dominates the reader's.
var at: u32 = this.insts[reader].block;
return no_block if at == block;
var steps := 0;
while true {
val up: u32 = state.idom[at];
break if up == block;
return no_block if up == no_block || up == at || steps > 256;
at = up;
steps++;
}
return no_block if target != no_block && target != at;
target = at;
}
}
return no_block if target == no_block;
val preds := &this.blocks[target].preds;
return no_block if preds.length != 1 || this.edge_source(preds[0]) != block;
return target;
}
#! Whether a read may move to after the end of its block: nothing after it in
#! the block may write what it reads, and its address is not null there, or
#! the program would have stopped as it does now. That it is read or written
#! through, or checked, before the read, in the block or one dominating it,
#! says so, as does its being so after the read in the block, before anything
#! the program would be seen to do.
#! @param this The code.
#! @param index The `load`.
#! @param k Its place among the block's instructions.
#! @param block Its block.
#! @param state What sinking knows.
#! @returns Whether it may.
def code::load_sinks(&this, index: u32, k: u64, block: u32, state: &sinking): bool {
val address := this.arg(index, 0);
val place := state.aliases.region_of(this, index, 0);
var safe := this.never_zero(address);
var quiet := true;
for j in k + 1..state.list.length {
val other: u32 = state.list[j];
continue if other == 0;
val kind := this.insts[other].kind;
return false if kind != op::load && (kind.traits() & op_write) != 0 && state.aliases.clobbers(this, other, &place);
if quiet && this.reaches(other, address) {
safe = true;
}
val stops := kind == op::load ? !this.never_zero(this.arg(other, 0)) : (kind.traits() & op_traps) != 0 && !this.removable(other);
if stops {
quiet = false;
}
}
return true if safe;
for j in 0..k {
return true if this.reaches(state.list[j], address);
}
val home := this.home_of(address);
var at := block;
var steps := 0;
while at != home && at != 0 && steps < 64 {
at = state.idom[at];
val key := pair_key(address, at);
return true if state.reached.get_or(&key, 0) != 0;
steps++;
}
return false;
}
+79
View File
@@ -0,0 +1,79 @@
#! @file unused.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the dropping of the functions nothing reaches once the program is
#! optimized, as those whose every call inlining copied. What is reached is
#! found from what is reached other than by the code's calls: `main`, the code
#! initializing the globals, the function safe points call, each function a
#! vtable holds, each C calls, and each the program takes as a value or the
#! backend calls by name. Each function reached then reaches what its code
#! calls, calls at safe points, and gives C to call, and its version. The rest
#! are dropped as though never lowered, so no code is made of them, each
#! keeping its index, and its name, which a trace of the code inlined from it
#! still gives.
module sakura::compiler;
#! Drops the functions nothing reaches, as the file says, once the program is
#! optimized and nothing more is lowered, but where every function is asked
#! for, or the program evaluates constants.
#! @param this The compiler.
pub def lowerer::drop_unreached_functions(&mut this): void {
return if this.options.everything || this.options.evaluating;
val point := mark_scratch();
val count := this.program.functions.length;
var reached := worklist::new(count, scratch());
this.reach_functions(&mut reached);
for i in 0..count {
if !reached.has(i as u32) {
this.program.functions[i].lowered = false;
}
}
release_scratch(point);
}
#! Finds the functions reached, as the file says.
#! @param this The compiler.
#! @param reached Where the functions reached are put, empty and as long as
#! the functions are; each is in it after.
pub def lowerer::reach_functions(&this, reached: &mut worklist): void {
val count := this.program.functions.length;
for i in 0..count {
if this.program.functions[i].taken || this.program.functions[i].callback {
reached.push_new(i as u32);
}
}
val roots: u32[3] = [this.program.main, this.program.init, this.dispatch];
for r in 0..3u {
if roots[r] != no_function {
reached.push_new(roots[r]);
}
}
for &each in this.program.vtables {
for &function in each.functions {
if function != no_function {
reached.push_new(function);
}
}
}
while !reached.is_empty {
val function := reached.pop();
val held := &this.program.functions[function];
if held.version != 0 {
reached.push_new(held.version - 1);
}
continue if !held.lowered;
var walk := held.body.walk_all();
while walk.more() {
val at := walk.next();
val kind := held.body.insts[at].kind;
if kind == op::call || kind == op::callback || kind == op::safepoint {
reached.push_new(held.body.insts[at].aux);
}
}
}
}
+158
View File
@@ -0,0 +1,158 @@
#! @file versions.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the versions of functions for processors with x86-64-v3's
#! instructions. A function of an executable that asks while running which
#! vector instructions the processor has, as `core::simd`'s operations do, or
#! counts a word's bits, is optimized again as a version knowing it has those of
#! x86-64-v3: SSE through SSE4.2, AVX, AVX2, FMA3, `popcnt`, `lzcnt`, and BMI1's
#! `tzcnt`. There, every operation on 16 or 32 bytes of lanes is worked with
#! instructions, so the lanes written a lane at a time go, 32 bytes of lanes are
#! values held in registers, and a count of bits is one instruction; what asks
#! for more, as 64 bytes ask for AVX-512, still asks. The function itself goes
#! to its version as it begins, where the processor has them, and its version
#! calls the versions of the functions it calls.
#!
#! A function calling one whose version is small enough to inline is given a
#! version too, though it asks nothing itself, so that its version copies the
#! other's: a loop calling `fma` works it with the instruction, rather than
#! calling a function that asks the processor each time.
module sakura::compiler;
#! The instruction sets of x86-64-v3, as the executable keeps them.
pub const cpu_v3: u64 = cpu_sse2 | cpu_ssse3 | cpu_sse41 | cpu_sse42 | cpu_avx | cpu_avx2 | cpu_fma | cpu_popcnt
| cpu_lzcnt | cpu_bmi1;
#! Whether code asks which instructions the processor has, or counts a word's
#! bits, which x86-64-v3 has instructions for. The code is compacted, as each
#! function is once it is optimized, so each instruction it holds is in a block,
#! and is looked at where it lies.
#! @param this The code.
#! @returns Whether it does.
def code::asks_processor(&this): bool {
for i in 1..this.insts.length {
val kind := this.insts[i].kind;
return true if kind == op::cpu || kind == op::ones || kind == op::clz || kind == op::ctz;
}
return false;
}
#! Copies code whole, sharing no memory with it.
#! @param this The code.
#! @returns The copy.
pub def code::duplicate(&this): code {
var made := code::new();
made.insts.clear();
made.origins.clear();
made.blocks.clear();
made.insts.extend(this.insts.view());
made.operands.extend(this.operands.view());
made.origins.extend(this.origins.view());
for &each in this.blocks {
made.blocks.append(block { first = each.first, last = each.last, params = ids::copy_of(&each.params), preds = ids::copy_of(&each.preds), gone = each.gone });
}
for &each in this.edges {
made.edges.append(edge { from = each.from, target = each.target, args = ids::copy_of(&each.args), case = each.case });
}
made.cells.extend(this.cells.view());
made.results.extend(this.results.view());
made.sites.extend(this.sites.view());
made.variables.extend(this.variables.view());
made.bindings.extend(this.bindings.view());
made.returned = this.returned;
made.vectors = this.vectors;
made.wide = this.wide;
return made;
}
#! Whether a function calls one with a version small enough to be inlined
#! whole, or `@inline`, which its own version would copy.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether it does.
def lowerer::calls_small_version(&mut this, index: u32): bool {
val limit := this.options.inline_limit != 0 ? this.options.inline_limit : inline_limit;
val body := &this.program.functions[index].body;
for i in 1..body.insts.length {
continue if body.insts[i].kind != op::call;
val version: u32 = this.program.functions[body.insts[i].aux].version;
continue if version == 0;
val facts := this.inline_facts(version - 1);
return true if facts.fits && (facts.cost <= limit || this.program.functions[version - 1].inline);
}
return false;
}
#! Whether the program's functions are given versions: in an executable
#! optimized at all.
#! @param this The compiler.
#! @returns Whether they are.
def lowerer::versions_made(&this): bool {
return this.options.level >= 1 && !this.options.evaluating
&& this.checker.names.text(this.checker.target.backend) == "native";
}
#! Makes the version of a function optimized for x86-64-v3, where it asks which
#! instructions the processor has, and optimizes it: what the processor has is
#! known to hold those, and each call goes to the version of what it calls,
#! where there is one.
#! @param this The compiler.
#! @param index The function, optimized.
#! @param ranks Where each function is in the order functions are optimized
#! in, as `optimizing` says, which the version is added to.
#! @param rank Where the version is: after the function, and before the
#! next in the order.
pub def lowerer::make_version(&mut this, index: u32, ranks: &mut vector<u32>, rank: u32): void {
return if !this.versions_made() || this.program.functions[index].body.wide;
# One left unfinished is not compacted, and nothing reaches it, so it is
# dropped rather than given a version.
return if this.program.functions[index].unfinished;
return if !this.program.functions[index].body.asks_processor() && !this.calls_small_version(index);
var body := this.program.functions[index].body.duplicate();
body.wide = true;
for i in 0..body.insts.length {
val kind := body.insts[i].kind;
if kind == op::cpu {
body.insts[i].imm = cpu_v3;
} else if kind == op::call {
val version: u32 = this.program.functions[body.insts[i].aux].version;
if version != 0 {
body.insts[i].aux = version - 1;
}
}
}
val original := &this.program.functions[index];
this.program.functions.append(function {
name = string::from(original.name.view(), nothing {}),
decl = original.decl,
instance = original.instance,
node = original.node,
outer = original.outer,
table = original.table,
file = original.file,
offset = original.offset,
signature = original.signature,
body = move(&mut body),
compiled = bytecode::new(),
lowered = true,
order = vector::<u32>::new(),
closure = original.closure,
callback = original.callback,
inline = original.inline
});
val made := (this.program.functions.length - 1) as u32;
this.program.functions[index].version = made + 1;
ranks.append(rank);
var found := vector::<string>::new();
this.optimize_function(made, ranks, rank, &mut found);
this.program.functions[made].optimized = true;
for &each in found {
this.problems.append(string::copy_of(&each));
}
}