Files
sakurac/compiler/optimizer/control.sakura
T

1224 lines
45 KiB
Plaintext
Raw Permalink Normal View History

2026-10-26 10:14:11 -05:00
#! @file control.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the third pass of the optimizer, which cleans up how control flows:
#! a `branch` or `switch` on a constant goes the one way it goes, as a `jump`;
#! a block nothing reaches goes; a block only one `jump` goes to is merged into
#! the block jumping; an edge into a block that only jumps on goes straight to
#! where that block goes; and an edge giving a block constants that the block
#! works out its branch from goes straight to where the branch goes for them,
#! as the constants `&&` and `||` join on do, and the flag a `for` loop's
#! cursor gives, what the block makes that is read past it reaching what reads
#! it as parameters of the successor it goes to. A chain of branches testing
#! one word against constants, as a `match` or `if`s comparing it are, becomes
#! one `switch`. A branch going to one block both ways becomes a `jump` giving
#! it a `select` of each argument the ways give differently, and the blocks of
#! a small diamond or triangle that only work out cheap values are worked out
#! before the branch, which then goes to where they join both ways. Then the
#! parameters standing for one value go, as building the code takes them out.
module sakura::compiler;
#! Cleans up how control flows, as the file says, until nothing more changes.
#! @param this The code.
#! @returns Whether anything changed.
pub def code::clean_control(&mut this): bool {
# Code of one block has nowhere to go but out of the function.
var live: u64 = 0;
for b in 0..this.blocks.length {
if !this.blocks[b].gone {
live++;
}
}
return false if live <= 1;
var changed := false;
var settled := false;
var rounds := 0;
while rounds < 8 {
rounds++;
var again := this.fold_branches();
this.drop_unreached();
again = this.merge_blocks() || again;
# How many times each value is read, where sending edges on past blocks
# that only jump on worked it out and sent none.
var uses := vector::<u32>::new(scratch());
again = this.thread_jumps(&mut uses) || again;
again = this.thread_known(&mut uses) || again;
again = this.form_switches() || again;
again = this.form_selects() || again;
settled = !again;
break if settled;
changed = true;
}
# A round that changed nothing took out what the entry does not reach.
if !settled {
this.drop_unreached();
}
val params := this.param_count();
this.drop_lone_params();
return changed || this.param_count() != params;
}
#! How many parameters the blocks take, but for the entry's.
#! @param this The code.
#! @returns How many.
def code::param_count(&this): u64 {
var count: u64 = 0;
for b in 1..this.blocks.length {
if !this.blocks[b].gone {
count += this.blocks[b].params.length;
}
}
return count;
}
#! Makes each `branch` and `switch` whose way is known a `jump`: one on a
#! constant, and a `branch` going the same way with the same arguments either
#! way.
#! @param this The code.
#! @returns Whether any changed.
def code::fold_branches(&mut this): bool {
var changed := false;
for b in 0..this.blocks.length {
continue if this.blocks[b].gone;
val last: u32 = this.blocks[b].last;
continue if last == 0;
val held: inst = this.insts[last];
if held.kind == op::branch {
var bits: u64 = 0;
if this.word_constant(this.arg(last, 0), &mut bits) {
this.jump_only(last, bits != 0 ? held.aux : held.aux + 1);
changed = true;
continue;
}
val one: u32 = held.aux;
if this.edges[one].target == this.edges[one + 1].target
&& this.edges[one].args.same(&this.edges[one + 1].args) {
this.jump_only(last, one);
changed = true;
}
continue;
}
if held.kind == op::switch {
var bits: u64 = 0;
continue if !this.word_constant(this.arg(last, 0), &mut bits);
val count := held.imm as u32;
var chosen := held.aux + count - 1;
for e in 0..count - 1 {
if this.edges[held.aux + e as u32].case == bits {
chosen = held.aux + e as u32;
break;
}
}
this.jump_only(last, chosen);
changed = true;
}
}
return changed;
}
#! Merges each block only one `jump` goes to into the block jumping, its
#! parameters read as the arguments the jump gives.
#! @param this The code.
#! @returns Whether any merged.
def code::merge_blocks(&mut this): bool {
var done := rewrite::new();
for b in 1..this.blocks.length {
continue if this.blocks[b].gone || this.blocks[b].preds.length != 1;
val edge: u32 = this.blocks[b].preds[0];
val jump: u32 = this.edges[edge].from;
continue if this.insts[jump].kind != op::jump;
val into: u32 = this.insts[jump].block;
continue if into == b as u32 || this.blocks[into].gone;
for i in 0..this.blocks[b].params.length {
done.replace(this.blocks[b].params[i], this.edges[edge].args[i]);
}
# The jump goes, and the block's instructions follow what came before it.
val before := this.before(jump);
val first: u32 = this.blocks[b].first;
if before == 0 {
this.blocks[into].first = first;
} else {
this.insts[before].next = first;
}
this.blocks[into].last = this.blocks[b].last;
var moved := this.walk(b as u32);
while moved.more() {
this.insts[moved.next()].block = into;
}
# What was bound where the block began is bound where its code now does.
for i in 0..this.bindings.length {
continue if this.bindings[i].block != b as u32;
this.bindings[i].block = into;
if this.bindings[i].after == 0 {
this.bindings[i].after = before;
}
}
this.blocks[b].first = 0;
this.blocks[b].last = 0;
this.blocks[b].gone = true;
this.blocks[b].preds.clear();
this.blocks[b].params.clear();
this.forget_order();
done.changed = true;
}
this.apply(&done);
return done.changed;
}
#! Sends each edge into a block that only jumps on straight to where it jumps,
#! where nothing but that jump reads what the block takes.
#! @param this The code.
#! @param uses Where how many times each value is read is written, where
#! that is asked; it is left empty where an edge was sent on.
#! @returns Whether any edge was sent on.
def code::thread_jumps(&mut this, uses: &mut vector<u32>): bool {
var changed := false;
for b in 1..this.blocks.length {
continue if this.blocks[b].gone;
val only: u32 = this.blocks[b].first;
continue if only == 0 || only != this.blocks[b].last || this.insts[only].kind != op::jump;
val out: u32 = this.insts[only].aux;
val target: u32 = this.edges[out].target;
continue if target == b as u32;
if uses.length == 0 && this.blocks[b].params.length != 0 {
uses = this.use_counts();
}
continue if this.blocks[b].params.length != 0 && !this.reads_params_only_leaving(b as u32, uses);
var preds := this.blocks[b].preds.copied(scratch());
for &edge in preds {
continue if this.edge_source(edge) == b as u32;
this.send_on(edge, b as u32, out);
changed = true;
}
}
if changed {
uses.clear();
}
return changed;
}
#! Whether the parameters of a block are read nowhere but by its last
#! instruction, and as arguments of the edges leaving it.
#! @param this The code.
#! @param block The block.
#! @param uses How many times each value is read.
#! @returns Whether they are.
def code::reads_params_only_leaving(&this, block: u32, uses: &vector<u32>): bool {
val last: u32 = this.blocks[block].last;
for &param in this.blocks[block].params {
var here: u32 = 0;
var reads := this.reads_of(last);
while reads.more() {
if reads.next() == param {
here++;
}
}
return false if uses[param] != here;
}
return true;
}
#! Sends an edge into a block on along an edge leaving that block, giving the
#! block's parameters the edge's arguments where the edge leaving gives them.
#! @param this The code.
#! @param edge The edge sent on.
#! @param block The block it went to.
#! @param out The edge it goes on along.
def code::send_on(&mut this, edge: u32, block: u32, out: u32): void {
var args := ids {};
for &each in this.edges[out].args {
val held: origin = this.origins[each];
if held.param && held.from == block {
args.append(this.edges[edge].args[held.index]);
} else {
args.append(each);
}
}
this.drop_pred(edge);
val target: u32 = this.edges[out].target;
this.edges[edge].target = target;
this.edges[edge].args = move(&mut args);
this.blocks[target].preds.append(edge);
}
# Threading through known ways.
#! The most instructions a block may hold before its `branch` or `switch` for
#! edges into it to be sent on past it, as its way is worked out for each.
const thread_limit: u32 = 16;
#! What `code::known_way` gives where the way a block goes is not known.
const no_way: u32 = 0xFFFFFFFF;
#! A word an instruction of a block gives along an edge into the block, as the
#! constants the edge gives say it.
struct known_word {
var value: u32; #! The instruction's result.
var bits: u64; #! The word.
}
#! The tree of which block dominates which, as sending edges on past blocks
#! asks it, worked out again once edges have changed, from the order and
#! dominators the code keeps where it keeps them.
struct dom_tree {
var order: vector<u32>; #! The blocks the entry reaches, 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 stale: bool; #! Whether edges changed since it was worked out.
}
#! Makes a tree not yet worked out.
#! @returns The tree.
def dom_tree::new(): dom_tree {
return dom_tree {
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()),
stale = true
};
}
#! Works the tree out again where edges changed since it was.
#! @param this The tree.
#! @param body The code.
def dom_tree::refresh(&mut this, body: &mut code): void {
return if !this.stale;
this.stale = false;
body.block_order(&mut this.order, &mut this.number);
this.idom = body.block_dominators();
this.first.clear();
this.after.clear();
this.first.resize(body.blocks.length, no_block);
this.after.resize(body.blocks.length, no_block);
var k := this.order.length;
while k > 1 {
k--;
val block: u32 = this.order[k];
val parent: u32 = this.idom[block];
this.after[block] = this.first[parent];
this.first[parent] = block;
}
}
#! The blocks a block dominates, itself first.
#! @param this The tree.
#! @param root The block.
#! @param into Where the blocks are written.
def dom_tree::region(&this, root: u32, into: &mut vector<u32>): void {
into.clear();
into.append(root);
var i: u64 = 0;
while i < into.length {
var child: u32 = this.first[into[i]];
while child != no_block {
into.append(child);
child = this.after[child];
}
i++;
}
}
#! Sends each edge giving a block constants that the block works out its way
#! from straight to where the block goes for them. A block of nothing but a
#! branch on a parameter that nothing else reads needs nothing more; otherwise
#! `thread_through` has what the block makes reach what reads it past it.
#! @param this The code.
#! @param uses How many times each value is read, where that is known as
#! the code is now, or empty.
#! @returns Whether any edge was sent on.
def code::thread_known(&mut this, uses: &mut vector<u32>): bool {
var tree := dom_tree::new();
var changed := false;
for b in 1..this.blocks.length {
continue if this.blocks[b].gone;
val last: u32 = this.blocks[b].last;
continue if last == 0;
val kind := this.insts[last].kind;
continue if (kind != op::branch && kind != op::switch) || !this.decides_alone(b as u32);
if this.blocks[b].first == last && this.origins[this.arg(last, 0)].param {
if uses.length == 0 {
uses = this.use_counts();
}
if this.reads_params_only_leaving(b as u32, uses) {
if this.thread_alone(b as u32) {
changed = true;
tree.stale = true;
}
continue;
}
}
if this.thread_through(b as u32, &mut tree) {
changed = true;
tree.stale = true;
uses.clear();
}
}
return changed;
}
#! Whether a block works out its way alone: what it holds before its `branch`
#! or `switch` only works out values, at most `thread_limit` of them, and what
#! it branches on is its own, a parameter or a value it works out.
#! @param this The code.
#! @param block The block, which ends in a `branch` or `switch`.
#! @returns Whether it does.
def code::decides_alone(&this, block: u32): bool {
val last: u32 = this.blocks[block].last;
return false if this.home_of(this.arg(last, 0)) != block;
var count: u32 = 0;
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
break if at == last;
count++;
return false if count > thread_limit || this.insts[at].count != 1 || (this.insts[at].kind.traits() & op_pure) == 0;
}
return true;
}
#! Where a block's `branch` or `switch` goes for an edge into it, working out
#! what it can of the block's instructions from the constants the edge gives.
#! @param this The code.
#! @param block The block, which works out its way alone.
#! @param edge The edge.
#! @param made Where each word worked out is written.
#! @returns The edge the block leaves by, or `no_way` where it is not known.
def code::known_way(&this, block: u32, edge: u32, made: &mut vector<known_word>): u32 {
made.clear();
val last: u32 = this.blocks[block].last;
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
break if at == last;
var bits: u64 = 0;
if this.fold_along(at, block, edge, made, &mut bits) {
made.append(known_word { value = this.insts[at].result, bits = bits });
}
}
var bits: u64 = 0;
return no_way if !this.known_along(block, edge, this.arg(last, 0), made, &mut bits);
val first: u32 = this.insts[last].aux;
if this.insts[last].kind == op::branch {
return bits != 0 ? first : first + 1;
}
val count := this.insts[last].imm as u32;
for e in 0..count - 1 {
return first + e as u32 if this.edges[first + e as u32].case == bits;
}
return first + count - 1;
}
#! The constant a word is along an edge into a block: of a parameter, the
#! constant the edge gives it, and of what the block works out, what is worked
#! out so far.
#! @param this The code.
#! @param block The block.
#! @param edge The edge.
#! @param value The word.
#! @param made The words of the block worked out so far.
#! @param bits Where the constant is written, where it is known.
#! @returns Whether it is known.
def code::known_along(&this, block: u32, edge: u32, value: u32, made: &vector<known_word>, bits: &mut u64): bool {
val held: origin = this.origins[value];
if held.param && held.from == block {
return this.word_constant(this.edges[edge].args[held.index], bits);
}
if !held.param && this.insts[held.from].block == block {
for &each in made {
if each.value == value {
bits = each.bits;
return true;
}
}
return false;
}
return this.word_constant(value, bits);
}
#! Works out the word an instruction of a block gives along an edge into the
#! block, where the constants it is worked out from are known.
#! @param this The code.
#! @param index The instruction.
#! @param block The block.
#! @param edge The edge.
#! @param made The words of the block worked out so far.
#! @param bits Where the word is written, where it is known.
#! @returns Whether it is known.
def code::fold_along(&this, index: u32, block: u32, edge: u32, made: &vector<known_word>, bits: &mut u64): bool {
val held: inst = this.insts[index];
return false if held.count != 1 || this.origins[held.result].kind != vt::word;
if held.kind == op::iconst {
bits = held.imm;
return true;
}
var x: u64 = 0;
return false if held.argc == 0 || !this.known_along(block, edge, this.arg(index, 0), made, &mut x);
if held.kind == op::select {
return this.known_along(block, edge, this.arg(index, x != 0 ? 1 : 2), made, bits);
}
val number := held.kind as u32;
if number >= op::add as u32 && number <= op::leus as u32 {
var y: u64 = 0;
return this.known_along(block, edge, this.arg(index, 1), made, &mut y) && fold_word(held.kind, x, y, bits);
}
match held.kind {
op::wrap => {
bits = wrap_word(x, held.aux, held.imm != 0);
return true;
}
op::neg, op::bnot, op::lnot, op::ones, op::clz, op::ctz, op::bswap => return fold_unary(held.kind, x, bits);
else => return false;
}
return false;
}
#! Sends each edge into a block whose constants say where the block's branch
#! goes straight there, for a block of nothing but a branch on a parameter
#! that nothing else reads.
#! @param this The code.
#! @param block The block.
#! @returns Whether any edge was sent on.
def code::thread_alone(&mut this, block: u32): bool {
var made := vector::<known_word>::new(scratch());
var changed := false;
var preds := this.blocks[block].preds.copied(scratch());
for &edge in preds {
continue if this.edge_source(edge) == block;
val out := this.known_way(block, edge, &mut made);
continue if out == no_way || this.edges[out].target == block;
this.send_on(edge, block, out);
changed = true;
}
return changed;
}
#! Sends each edge into a block whose constants say where the block goes
#! straight there, where what the block makes that is read past it can reach
#! what reads it. Each value read within what a successor taking an edge sent
#! on dominates becomes a parameter of the successor, which the block's edge
#! gives it as the value, and each edge sent on as what the value is along
#! that edge: the argument the edge gave the block, or a constant the block
#! works out. A constant the block makes is made again where the successor
#! begins instead. Where a value is read past the block but within no
#! successor only the block goes to, no edge is sent on.
#! @param this The code.
#! @param block The block, which works out its way alone.
#! @param tree Which block dominates which, worked out again where stale.
#! @returns Whether any edge was sent on.
def code::thread_through(&mut this, block: u32, tree: &mut dom_tree): bool {
# The edges whose constants say where the block goes, each with its way.
var made := vector::<known_word>::new(scratch());
var found := vector::<u64>::new(scratch());
var preds := this.blocks[block].preds.copied(scratch());
for &edge in preds {
continue if this.edge_source(edge) == block;
val out := this.known_way(block, edge, &mut made);
continue if out == no_way || this.edges[out].target == block;
found.append(pair_key(edge, out));
}
return false if found.length == 0;
tree.refresh(this);
var needs := vector::<u64>::new(scratch());
return false if !this.reads_beyond(block, tree, &mut needs);
# A block heading a loop, which an edge from within what it dominates goes
# back to, keeps each edge from outside that would go on into the loop, which
# would enter the loop past its head.
var looped := vector::<bool>::new(scratch());
for &edge in preds {
if dominates(&tree.idom, block, this.edge_source(edge)) {
looped = this.loop_of(block, tree);
break;
}
}
# An edge goes on only where each value its way needs is known along it.
var sent := vector::<u64>::new(scratch());
for &pair in found {
val edge := pair_high(pair);
val out := pair_low(pair);
val target: u32 = this.edges[out].target;
continue if looped.length != 0 && looped[target] && !dominates(&tree.idom, block, this.edge_source(edge));
this.known_way(block, edge, &mut made);
var known := true;
for &each in this.edges[out].args.span {
known = known && this.maps_along(block, edge, each, &made);
}
for &need in needs {
if pair_high(need) == target {
known = known && this.maps_along(block, edge, pair_low(need), &made);
}
}
if known {
sent.append(pair);
}
}
return false if sent.length == 0;
# Each successor an edge goes on to takes what it needs: a constant made again
# where it begins, or a parameter, which the block's edge gives as the value.
var region := vector::<u32>::new(scratch());
for &need in needs {
val target := pair_high(need);
val value := pair_low(need);
var taken := false;
for &pair in sent {
taken = taken || this.edges[pair_low(pair)].target == target;
}
continue if !taken;
var stands: u32 = 0;
val from := this.defining(value);
if from != 0 && (this.insts[from].kind == op::iconst || this.insts[from].kind == op::fconst) {
val held: inst = this.insts[from];
var gives: vt[1] = [this.type_of(value)];
val copy := this.detached(held.kind, span::<u32>::blank(), gives[0:1], 0, held.imm, held.at, held.site);
this.put_first(target, copy);
stands = this.insts[copy].result;
} else {
stands = this.add_param(target, this.type_of(value));
val into: u32 = this.blocks[target].preds[0];
this.edges[into].args.append(value);
}
tree.region(target, &mut region);
this.replace_within(region.span, value, stands);
}
# Each edge goes on, giving what each value its way gives is along it.
for &pair in sent {
val edge := pair_high(pair);
val out := pair_low(pair);
this.known_way(block, edge, &mut made);
var given := this.edges[out].args.copied(scratch());
var args := ids {};
for &each in given {
args.append(this.mapped_along(block, edge, each, &made));
}
this.drop_pred(edge);
val target: u32 = this.edges[out].target;
this.edges[edge].target = target;
this.edges[edge].args = move(&mut args);
this.blocks[target].preds.append(edge);
}
return true;
}
#! Finds what a block makes that is read past it, which is within what the
#! block dominates: each read must be within what a successor only the block
#! goes to dominates, which the successor would need were edges to go to it
#! without the block.
#! @param this The code.
#! @param block The block.
#! @param tree Which block dominates which.
#! @param needs Where each successor and value read within what it dominates
#! is written, as `pair_key` packs them, each once.
#! @returns Whether every read past the block is within such a successor's.
def code::reads_beyond(&this, block: u32, tree: &dom_tree, needs: &mut vector<u64>): bool {
needs.clear();
var region := vector::<u32>::new(scratch());
var reads := this.reader();
var child: u32 = tree.first[block];
while child != no_block {
val preds := &this.blocks[child].preds;
val alone := preds.length == 1 && this.edge_source(preds[0]) == block;
tree.region(child, &mut region);
for &each in region {
var walk := this.walk(each);
while walk.more() {
reads.start(walk.next());
while reads.more() {
val value := reads.next();
continue if this.home_of(value) != block;
return false if !alone;
val key := pair_key(child, value);
if !needs.span.contains(&key) {
needs.append(key);
}
}
}
}
child = tree.after[child];
}
return true;
}
#! The blocks of the loop a block heads: those it dominates from which an edge
#! back to it is reached through blocks it dominates, and itself.
#! @param this The code.
#! @param block The block.
#! @param tree Which block dominates which.
#! @returns Whether each block is within the loop.
def code::loop_of(&this, block: u32, tree: &dom_tree): vector<bool> {
var looped := vector::<bool>::new(scratch());
looped.resize(this.blocks.length);
looped[block] = true;
var todo := vector::<u32>::new(scratch());
for &edge in this.blocks[block].preds {
todo.append(this.edge_source(edge));
}
while todo.length != 0 {
val at: u32 = todo.last;
todo.truncate();
continue if looped[at] || !dominates(&tree.idom, block, at);
looped[at] = true;
for &edge in this.blocks[at].preds {
todo.append(this.edge_source(edge));
}
}
return looped;
}
#! Whether a value an edge sent on past a block needs is known along the edge:
#! one the block does not make, a parameter of the block, a constant it makes,
#! a word it works out from the constants the edge gives, or a `select` whose
#! choice they say, of what is known.
#! @param this The code.
#! @param block The block.
#! @param edge The edge.
#! @param value The value.
#! @param made The words of the block worked out along the edge.
#! @returns Whether it is.
def code::maps_along(&this, block: u32, edge: u32, value: u32, made: &vector<known_word>): bool {
val held: origin = this.origins[value];
return true if held.param || this.insts[held.from].block != block;
val kind := this.insts[held.from].kind;
return true if kind == op::iconst || kind == op::fconst;
var bits: u64 = 0;
return true if this.known_along(block, edge, value, made, &mut bits);
return false if kind != op::select || !this.known_along(block, edge, this.arg(held.from, 0), made, &mut bits);
return this.maps_along(block, edge, this.arg(held.from, bits != 0 ? 1 : 2), made);
}
#! What a value is along an edge into a block, sent on past the block: of a
#! parameter, the argument the edge gave it, of what the block works out, the
#! constant it is, of a `select` whose choice is known, what it chooses there,
#! and otherwise the value itself.
#! @param this The code.
#! @param block The block.
#! @param edge The edge.
#! @param value The value, which `maps_along` says is known.
#! @param made The words of the block worked out along the edge.
#! @returns The value along the edge.
def code::mapped_along(&mut this, block: u32, edge: u32, value: u32, made: &vector<known_word>): u32 {
val held: origin = this.origins[value];
if held.param {
return value if held.from != block;
val given: u32 = this.edges[edge].args[held.index];
return given;
}
val from: inst = this.insts[held.from];
return value if from.block != block;
return this.real_value(from.imm) if from.kind == op::fconst;
var bits: u64 = 0;
return this.word_value(bits) if this.known_along(block, edge, value, made, &mut bits);
this.known_along(block, edge, this.arg(held.from, 0), made, &mut bits);
return this.mapped_along(block, edge, this.arg(held.from, bits != 0 ? 1 : 2), made);
}
#! Makes each read of a value within some blocks read another instead: by their
#! instructions, the edges leaving them, and the variables bound in them.
#! @param this The code.
#! @param blocks The blocks.
#! @param from The value read.
#! @param to The value read instead.
def code::replace_within(&mut this, blocks: span<u32>, from: u32, to: u32): void {
var inside := vector::<bool>::new(scratch());
inside.resize(this.blocks.length);
for &block in blocks {
inside[block] = true;
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;
if this.operands[slot] == from {
this.operands[slot] = to;
}
}
var outs := this.edges_of(at);
while outs.more() {
val args := this.edges[outs.next()].args.slice;
for a in 0..args.length {
if args[a] == from {
args[a] = to;
}
}
}
}
}
for i in 0..this.bindings.length {
val bound: binding = this.bindings[i];
if bound.value == from && bound.block != no_block && inside[bound.block] {
this.bindings[i].value = to;
}
}
}
# Switches.
#! The fewest cases a chain of branches has for it to become a `switch`.
const switch_least: u64 = 4;
#! A branch testing a word against a constant: the word, the constant, the
#! edge taken where the word is it, and the one taken where it is not.
struct test_step {
var subject: u32;
var case: u64;
var hit: u32;
var rest: u32;
}
#! What a block's branch tests: a word against a constant, as `x == k`,
#! `x != k`, or `x` itself, which is the word against 0.
#! @param this The code.
#! @param block The block.
#! @param step Where what it tests is written.
#! @returns Whether it ends in such a branch.
def code::test_of(&this, block: u32, step: &mut test_step): bool {
val last: u32 = this.blocks[block].last;
return false if last == 0 || this.insts[last].kind != op::branch;
val first: u32 = this.insts[last].aux;
val cond := this.arg(last, 0);
return false if this.type_of(cond) != vt::word;
val held: origin = this.origins[cond];
if !held.param {
val made: inst = this.insts[held.from];
if made.kind == op::eq || made.kind == op::ne {
var bits: u64 = 0;
var subject: u32 = 0;
if this.word_constant(this.arg(held.from, 1), &mut bits) {
subject = this.arg(held.from, 0);
} else if this.word_constant(this.arg(held.from, 0), &mut bits) {
subject = this.arg(held.from, 1);
} else {
return false;
}
val equal := made.kind == op::eq;
step = test_step { subject = subject, case = bits, hit = equal ? first : first + 1, rest = equal ? first + 1 : first };
return true;
}
}
step = test_step { subject = cond, case = 0, hit = first + 1, rest = first };
return true;
}
#! Whether a block is a step of a chain past its first: only the edge going on
#! from the step before goes to it, giving it nothing, and it holds nothing but
#! constants, the test of its branch, and the branch. Where how many times
#! each value is read is known, the test must be read by the branch alone.
#! @param this The code.
#! @param block The block, which ends in a branch.
#! @param from The edge going to it.
#! @param uses How many times each value is read, or nothing yet.
#! @returns Whether it is.
def code::chain_step(&this, block: u32, from: u32, uses: &vector<u32>): bool {
return false if block == 0 || this.blocks[block].preds.length != 1 || this.blocks[block].params.length != 0;
return false if this.blocks[block].preds[0] != from;
val last: u32 = this.blocks[block].last;
val cond := this.arg(last, 0);
var walk := this.walk(block);
while walk.more() {
val at := walk.next();
break if at == last;
val held := &this.insts[at];
val tests := held.count == 1 && held.result == cond && (uses.length == 0 || uses[cond] == 1);
return false if held.kind != op::iconst && held.kind != op::fconst && !tests;
}
return true;
}
#! How many steps a chain has, from its first, stopping at as many as make it a
#! switch.
#! @param this The code.
#! @param first The chain's first block.
#! @param head What its first block tests.
#! @param uses How many times each value is read, or nothing yet.
#! @returns How many.
def code::chain_length(&this, first: u32, head: &test_step, uses: &vector<u32>): u64 {
var count: u64 = 1;
var step: test_step = head;
while count < switch_least {
val next: u32 = this.edges[step.rest].target;
var after := test_step {};
break if next == first || !this.test_of(next, &mut after) || after.subject != head.subject;
break if !this.chain_step(next, step.rest, uses);
count++;
step = after;
}
return count;
}
#! Makes each chain of branches testing one word against at least
#! `switch_least` constants one `switch` of the first, which goes where the
#! chain went for each, and where its last step went otherwise. The constants
#! its later steps make are made before the switch instead, where they stand
#! before everything that read them, and the later steps go.
#! @param this The code.
#! @returns Whether any chain became a switch.
def code::form_switches(&mut this): bool {
var uses := vector::<u32>::new(scratch());
val none := vector::<u32>::new(scratch());
var changed := false;
for b in 0..this.blocks.length {
continue if this.blocks[b].gone;
var head := test_step {};
continue if !this.test_of(b as u32, &mut head) || this.type_of(head.subject) != vt::word;
# A block a chain goes on into is part of that chain, not the first of one.
if b != 0 && this.blocks[b].preds.length == 1 {
val into: u32 = this.blocks[b].preds[0];
var before := test_step {};
if this.test_of(this.edge_source(into), &mut before) && before.subject == head.subject && before.rest == into {
continue;
}
}
# The steps, and the constant each goes on, the first of each. Whether a
# step's test is read elsewhere is only asked of a chain long enough.
if this.chain_length(b as u32, &head, &none) < switch_least {
continue;
}
if uses.length == 0 {
uses = this.use_counts();
}
var cases := vector::<u64>::new(scratch());
var hits := vector::<u32>::new(scratch());
var steps := vector::<u32>::new(scratch());
var step := head;
while true {
if !cases.span.contains(&step.case) {
cases.append(step.case);
hits.append(step.hit);
}
val next: u32 = this.edges[step.rest].target;
var after := test_step {};
break if next == b as u32 || !this.test_of(next, &mut after) || after.subject != head.subject;
break if !this.chain_step(next, step.rest, &uses);
steps.append(next);
step = after;
}
continue if cases.length < switch_least;
# The first's branch becomes the switch, its edges new.
val last: u32 = this.blocks[b].last;
val old: u32 = this.insts[last].aux;
val fallback := step.rest;
var first: u32 = 0;
for i in 0..cases.length {
val hit: u32 = hits[i];
val made := this.add_edge(last, this.edges[hit].target, cases[i]);
this.edges[made].args = ids::copy_of(&this.edges[hit].args);
if i == 0 {
first = made;
}
}
val otherwise := this.add_edge(last, this.edges[fallback].target, 0);
this.edges[otherwise].args = ids::copy_of(&this.edges[fallback].args);
this.drop_pred(old);
this.drop_pred(old + 1);
var args: u32[1] = [head.subject];
this.become(last, op::switch, args[0:1], first, cases.length as u64 + 1);
# The constants of the later steps go before the switch, and the steps go.
for &block in steps {
var made := vector::<u32>::new(scratch());
var walk := this.walk(block);
while walk.more() {
val each := walk.next();
val kind := this.insts[each].kind;
if kind == op::iconst || kind == op::fconst {
made.append(each);
}
}
for &moved in made {
this.link_before(moved, last);
}
val ends: u32 = this.blocks[block].last;
val out: u32 = this.insts[ends].aux;
this.drop_pred(out);
this.drop_pred(out + 1);
this.blocks[block].first = 0;
this.blocks[block].last = 0;
this.blocks[block].gone = true;
this.blocks[block].preds.clear();
}
changed = true;
}
return changed;
}
# Selects.
#! The most `select`s a branch becomes, one for each argument its ways give
#! differently.
const select_limit: u32 = 4;
#! The most instructions the blocks of a diamond or triangle may work out, but
#! for constants and addresses, which cost nothing, for them to be worked out
#! before the branch.
const arm_limit: u32 = 4;
#! Makes each `branch` whose ways only work out cheap values a choice between
#! them, as `hoist_arms` and `form_select` say.
#! @param this The code.
#! @returns Whether any branch became one.
def code::form_selects(&mut this): bool {
var changed := false;
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::branch;
this.hoist_arms(b as u32);
changed = this.form_select(b as u32) || changed;
}
return changed;
}
#! How many `select`s a branch on a condition needs to give a block what its
#! two ways give it: one for each argument they give differently, but where
#! the way the condition is not zero gives the condition and the other zero,
#! which is the condition both ways.
#! @param this The code.
#! @param cond The condition.
#! @param one What the way the condition is not zero gives.
#! @param two What the other way gives.
#! @returns How many, or `no_way` where an argument is a vector, which no
#! `select` chooses.
def code::selects_needed(&this, cond: u32, one: span<u32>, two: span<u32>): u32 {
var count: u32 = 0;
for i in 0..one.length {
continue if one[i] == two[i] || (one[i] == cond && this.is_zero(two[i]));
return no_way if this.type_of(one[i]).lanes();
count++;
}
return count;
}
#! Makes a `branch` going to one block both ways, with at most `select_limit`
#! arguments given differently, a `jump` giving the block a `select` of each.
#! @param this The code.
#! @param block The block the branch ends.
#! @returns Whether it became one.
def code::form_select(&mut this, block: u32): bool {
val last: u32 = this.blocks[block].last;
val one: u32 = this.insts[last].aux;
val two := one + 1;
return false if this.edges[one].target != this.edges[two].target;
val cond := this.arg(last, 0);
val count := this.selects_needed(cond, this.edges[one].args.span, this.edges[two].args.span);
return false if count == no_way || count > select_limit;
val held: inst = this.insts[last];
var args := ids {};
for i in 0..this.edges[one].args.length {
val x: u32 = this.edges[one].args[i];
val y: u32 = this.edges[two].args[i];
if x == y || (x == cond && this.is_zero(y)) {
args.append(x);
continue;
}
var operands: u32[3] = [cond, x, y];
var gives: vt[1] = [this.type_of(x)];
val chosen := this.detached(op::select, operands[0:3], gives[0:1], 0, 0, held.at, held.site);
this.link_before(chosen, last);
args.append(this.insts[chosen].result);
}
this.edges[one].args = move(&mut args);
this.jump_only(last, one);
if count == 1 {
this.compare_late(block, cond);
}
return true;
}
#! Moves the comparison a block works out a condition with to just before the
#! one instruction after it reading the condition, its last but one, so the
#! backend compares there for itself, as for a branch. Nothing between may
#! read the condition.
#! @param this The code.
#! @param block The block.
#! @param cond The condition.
def code::compare_late(&mut this, block: u32, cond: u32): void {
val from := this.defining(cond);
return if from == 0 || this.insts[from].block != block;
match this.insts[from].kind {
op::eq, op::ne, op::lts, op::ltu, op::les, op::leu, op::flt, op::fle => {}
else => return;
}
# The instruction reading it, and those between, which must not.
val last: u32 = this.blocks[block].last;
val reading := this.before(last);
return if reading == from;
var at: u32 = this.insts[from].next;
while at != reading {
var reads := this.reads_of(at);
while reads.more() {
return if reads.next() == cond;
}
at = this.insts[at].next;
}
val prior := this.before(from);
if prior == 0 {
this.blocks[block].first = this.insts[from].next;
} else {
this.insts[prior].next = this.insts[from].next;
}
this.link_before(from, reading);
}
#! Works out before a branch what the blocks of a small diamond or triangle
#! after it work out: each block a way of the branch goes to, taking nothing,
#! working out only cheap values that cannot stop the program, at most
#! `arm_limit` of them in all, and jumping on to one block, which the other
#! way goes to or jumps on to too. The branch then goes to that block both
#! ways, giving it what each way gave it, where `form_select` makes it a
#! choice, and the blocks between go. A block other ways go to too may only
#! make constants, which are made again before the branch, as the constants
#! `&&` and `||` join with are, and it stays for those ways.
#! @param this The code.
#! @param block The block the branch ends.
#! @returns Whether the branch now goes to one block both ways.
def code::hoist_arms(&mut this, block: u32): bool {
val last: u32 = this.blocks[block].last;
val one: u32 = this.insts[last].aux;
val two := one + 1;
val first: u32 = this.edges[one].target;
val second: u32 = this.edges[two].target;
return false if first == second;
var cost_one: u32 = 0;
var cost_two: u32 = 0;
val join_one := this.arm_join(first, &mut cost_one);
val join_two := this.arm_join(second, &mut cost_two);
var join := no_block;
var cost: u32 = 0;
if join_one != no_block && join_one == join_two {
join = join_one;
cost = cost_one + cost_two;
} else if join_one == second {
join = second;
cost = cost_one;
} else if join_two == first {
join = first;
cost = cost_two;
}
return false if join == no_block || join == block || cost > arm_limit;
# What each way would give the block they join at.
val gives_one := join == first ? one : this.insts[this.blocks[first].last].aux;
val gives_two := join == second ? two : this.insts[this.blocks[second].last].aux;
val count := this.selects_needed(this.arg(last, 0), this.edges[gives_one].args.span, this.edges[gives_two].args.span);
return false if count == no_way || count > select_limit;
# Each arm's instructions come before the branch, and the way into it goes
# where it went, giving what it gave.
if join != first {
this.hoist_arm(first, one, last, join);
}
if join != second {
this.hoist_arm(second, two, last, join);
}
return true;
}
#! Where a block jumps on to, where it is an arm of a diamond or triangle: it
#! takes nothing, and works out only cheap values that cannot stop the
#! program, as constants, addresses, comparisons, and arithmetic but for
#! dividing, and shifts by constants, before its `jump`, or only constants
#! where more than one way goes to it.
#! @param this The code.
#! @param arm The block.
#! @param cost Where how many it works out, but for constants and addresses,
#! is written.
#! @returns The block it jumps on to, or `no_block` where it is no arm.
def code::arm_join(&this, arm: u32, cost: &mut u32): u32 {
cost = 0;
return no_block if arm == 0 || this.blocks[arm].params.length != 0;
val shared := this.blocks[arm].preds.length != 1;
val last: u32 = this.blocks[arm].last;
return no_block if last == 0 || this.insts[last].kind != op::jump;
var bits: u64 = 0;
var walk := this.walk(arm);
while walk.more() {
val at := walk.next();
break if at == last;
val kind := this.insts[at].kind;
continue if kind == op::iconst || kind == op::fconst;
return no_block if shared;
match kind {
op::cell, op::global, op::datum => {}
op::add, op::sub, op::mul, op::band, op::bor, op::bxor, op::eq, op::ne, op::lts, op::ltu, op::les,
op::leu, op::eqsu, op::ltsu, op::lesu, op::ltus, op::leus, op::neg, op::bnot, op::lnot, op::wrap,
op::select, op::fadd, op::fsub, op::fmul, op::fneg, op::feq, op::fne, op::flt, op::fle, op::itof,
op::fsingle => cost = cost + 1;
op::shl, op::shrs, op::shru => {
return no_block if !this.word_constant(this.arg(at, 1), &mut bits);
cost = cost + 1;
}
else => return no_block;
}
}
return this.edges[this.insts[last].aux].target;
}
#! Moves what an arm works out before a branch, and has the way into the arm
#! go where the arm jumps on to, giving what it gave there; the arm goes. An
#! arm other ways go to too stays, its constants made again before the branch.
#! @param this The code.
#! @param arm The arm.
#! @param edge The way into it.
#! @param last The branch.
#! @param join Where the arm jumps on to.
def code::hoist_arm(&mut this, arm: u32, edge: u32, last: u32, join: u32): void {
val jump: u32 = this.blocks[arm].last;
val out: u32 = this.insts[jump].aux;
val shared := this.blocks[arm].preds.length != 1;
var args := ids::copy_of(&this.edges[out].args);
var moved := vector::<u32>::new(scratch());
var walk := this.walk(arm);
while walk.more() {
val at := walk.next();
if at != jump {
moved.append(at);
}
}
for &each in moved {
if !shared {
this.link_before(each, last);
continue;
}
val held: inst = this.insts[each];
var gives: vt[1] = [this.type_of(held.result)];
val copy := this.detached(held.kind, span::<u32>::blank(), gives[0:1], 0, held.imm, held.at, held.site);
this.link_before(copy, last);
val given := args.slice;
for a in 0..given.length {
if given[a] == held.result {
given[a] = this.insts[copy].result;
}
}
}
this.drop_pred(edge);
this.edges[edge].target = join;
this.edges[edge].args = move(&mut args);
this.blocks[join].preds.append(edge);
return if shared;
this.drop_pred(out);
this.blocks[arm].first = 0;
this.blocks[arm].last = 0;
this.blocks[arm].gone = true;
this.blocks[arm].preds.clear();
}