Files
sakurac/compiler/optimizer/worth.sakura
T
2026-11-19 04:54:17 -06:00

430 lines
15 KiB
Plaintext

#! @file worth.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what a call is worth inlining, worked out for each call rather
#! than once for the function, as LLVM's inliner works out a call's cost and
#! threshold. A function too large to inline at every call may be small at
#! one: the copy is costed as it would be once optimized there, which is the
#! function's code walked from its entry with what the call gives it.
#!
#! - What the call gives as constants folds: an operator of constants is the
#! constant it gives, a branch or switch on one goes one way, and what only
#! the ways not gone lead to is never copied, so costs nothing.
#! - A parameter that is an address only read, written, copied, and cleared
#! through, directly or at steps of constants from it, reaches a cell of the
#! caller's where it is taken as memory, which the copy copies into a cell of
#! its own, or where the call gives the address of a cell: promoting the cell
#! then holds what it reaches as values, so those reads and writes cost
#! nothing, as LLVM counts what its SROA takes out.
#!
#! The threshold the cost is held to grows where the call is worth more: by
#! half within a loop, where the call runs again and again, and by a quarter
#! where the copy is one block, whose code the caller's block then simply
#! holds. Only functions within a few times the limit are walked, so a large
#! function costs nothing to turn down.
module sakura::compiler;
#! How many times the limit a function's cost may be for a call of it to be
#! walked for what it is worth there.
pub const worth_reach: u32 = 4;
#! The most vectors of lanes living through a loop where a call within it may
#! be inlined past the limit. The backend gives values 11 vector registers, so
#! past this, what a copy promotes out of memory into values would only be
#! spilled to the stack again, a value at a time, which costs more than the
#! call did.
const vector_room: u32 = 6;
#! What a copy of a function at a call costs.
struct call_worth {
var cost: u32; #! Its instructions, counted as `inline_cost` counts them, but for those that fold or promote away.
var blocks: u32; #! How many of its blocks the call reaches.
}
#! Whether a call of a function too large to be inlined everywhere is worth
#! inlining where it is, as the file says.
#! @param this The compiler.
#! @param caller The function calling.
#! @param call The call.
#! @param callee The function called.
#! @param facts What inlining knows of the function called.
#! @param limit The most a function inlined everywhere may cost.
#! @param looped 0 where the call is in no loop, and otherwise one more than
#! the vectors of lanes living through the innermost loop it is
#! in, as `loop_pressure` counts them.
#! @returns Whether it is.
def lowerer::worth_inlining(&mut this, caller: u32, call: u32, callee: u32, facts: &inline_facts, limit: u32, looped: u32): bool {
return false if looped > vector_room + 1;
# Where nothing the call gives folds, the copy costs no less than what the
# function does but for its reads and writes through what it takes, so
# where that is past the most it may cost, it is not walked.
val most := limit + limit / 4 + (looped != 0 ? limit / 2 : 0);
return false if facts.cost > most + facts.reaches && !this.program.functions[caller].body.gives_constants(call);
var threshold := limit;
val worth := this.call_cost(caller, call, callee, facts);
if worth.blocks == 1 {
threshold += limit / 4;
if looped != 0 {
threshold += limit / 2;
}
}
return worth.cost <= threshold;
}
#! Whether a call gives any constant.
#! @param this The code.
#! @param call The call.
#! @returns Whether it does.
def code::gives_constants(&this, call: u32): bool {
for i in 0..this.insts[call].argc {
val made := this.defining(this.arg(call, i as u32));
return true if made != 0 && (this.insts[made].kind == op::iconst || this.insts[made].kind == op::fconst);
}
return false;
}
#! Works out what a copy of a function at a call costs, as the file says.
#! @param this The compiler.
#! @param caller The function calling.
#! @param call The call.
#! @param callee The function called.
#! @param facts What inlining knows of the function called.
#! @returns What it costs: what the function costs everywhere, where the
#! function's blocks were never ordered to be copied.
def lowerer::call_cost(&mut this, caller: u32, call: u32, callee: u32, facts: &inline_facts): call_worth {
var worth := call_worth { cost = facts.cost, blocks = 2 };
var memory := vector::<bool>::new(scratch());
var layouts := vector::<u32>::new(scratch());
this.entry_values(this.program.functions[callee].signature, &mut memory, &mut layouts);
val code := &this.program.functions[callee].body;
val body := &this.program.functions[caller].body;
val order := &this.program.functions[callee].order;
val takes := code.blocks[0].params.length;
return worth if order.length == 0 || memory.length != takes || takes > body.insts[call].argc as u64;
# What each value is known to be: a constant's bits, or an address whose
# reads and writes promote.
var walking := worth_walk {
known = vector::<u64>::new(scratch()),
fixed = vector::<bool>::new(scratch()),
free = vector::<bool>::new(scratch()),
taken = vector::<bool>::new(scratch())
};
walking.known.resize(code.origins.length);
walking.fixed.resize(code.origins.length);
walking.free.resize(code.origins.length);
walking.taken.resize(code.edges.length);
for i in 0..takes {
val param: u32 = code.blocks[0].params[i];
val arg := body.arg(call, i as u32);
val contained := i < 64 && (facts.contained & (1u << i)) != 0;
if memory[i] {
walking.free[param] = contained;
continue;
}
var bits: u64 = 0;
if body.word_constant(arg, &mut bits) || body.real_constant(arg, &mut bits) {
walking.known[param] = bits;
walking.fixed[param] = true;
} else if contained && body.cell_of(arg) != no_cell {
walking.free[param] = true;
}
}
# The blocks in the order they are copied in, which is the order they run
# in, each walked where a way gone reaches it.
var place := vector::<u32>::new(scratch());
place.resize(code.blocks.length, 0xFFFFFFFF);
for k in 0..order.length {
place[order[k]] = k as u32;
}
var live := vector::<bool>::new(scratch());
live.resize(code.blocks.length);
live[0] = true;
worth.cost = 0;
worth.blocks = 0;
for &b in order.span {
continue if !live[b];
worth.blocks++;
if b != 0 {
code.join_known(b, &place, &live, &mut walking);
}
var walk := code.walk(b);
while walk.more() {
worth.cost += code.cost_at(walk.next(), &mut walking);
}
var outs := code.edges_of(code.blocks[b].last);
while outs.more() {
val edge := outs.next();
if walking.taken[edge] {
live[code.edges[edge].target] = true;
}
}
}
return worth;
}
#! What walking a function's code for what a call is worth knows.
struct worth_walk {
var known: vector<u64>; #! The bits of each value known to be a constant.
var fixed: vector<bool>; #! Whether each value is known to be a constant.
var free: vector<bool>; #! Whether each value is an address whose reads and writes promote.
var taken: vector<bool>; #! Whether each edge is gone along.
}
#! Learns which parameters of a block are known constants: those every edge
#! gone into it gives the same constant, where no edge comes back into it from
#! a block not walked yet, as round a loop.
#! @param this The code.
#! @param block The block.
#! @param place Each block's place in the order they are walked in.
#! @param live Whether each block is reached.
#! @param walking What the walk knows.
def code::join_known(&this, block: u32, place: &vector<u32>, live: &vector<bool>, walking: &mut worth_walk): void {
val held := &this.blocks[block];
for p in 0..held.params.length {
var bits: u64 = 0;
var any := false;
var same := true;
for &edge in held.preds {
val from := this.edge_source(edge);
if place[from] >= place[block] {
same = false;
break;
}
continue if !live[from] || !walking.taken[edge];
val arg: u32 = this.edges[edge].args[p];
if !walking.fixed[arg] || (any && walking.known[arg] != bits) {
same = false;
break;
}
bits = walking.known[arg];
any = true;
}
if same && any {
val param: u32 = held.params[p];
walking.known[param] = bits;
walking.fixed[param] = true;
}
}
}
#! What an instruction of a copy costs, as the file says, noting what it gives
#! where that is known, and which ways out of its block it goes where it ends
#! one.
#! @param this The code.
#! @param index The instruction.
#! @param walking What the walk knows.
#! @returns What it costs.
def code::cost_at(&this, index: u32, walking: &mut worth_walk): u32 {
val held: inst = this.insts[index];
val kind := held.kind;
match kind {
op::jump => {
walking.taken[held.aux] = true;
return 0;
}
op::branch => {
val cond := this.arg(index, 0);
if walking.fixed[cond] {
walking.taken[walking.known[cond] != 0 ? held.aux : held.aux + 1] = true;
return 0;
}
walking.taken[held.aux] = true;
walking.taken[held.aux + 1] = true;
return 1;
}
op::switch => {
val word := this.arg(index, 0);
val count := held.imm as u32;
if walking.fixed[word] {
# The last way out is the one for every other word.
var chosen := held.aux + count - 1;
for e in held.aux..(held.aux + count - 1) {
if this.edges[e].case == walking.known[word] {
chosen = e;
break;
}
}
walking.taken[chosen] = true;
return 0;
}
for e in held.aux..(held.aux + count) {
walking.taken[e] = true;
}
return 1;
}
op::iconst, op::fconst => {
walking.known[held.result] = held.imm;
walking.fixed[held.result] = true;
return 0;
}
else => {}
}
# What only works out a constant from constants folds.
if held.count == 1 && held.argc >= 1 {
var all := true;
for i in 0..held.argc {
all = all && walking.fixed[this.arg(index, i as u32)];
}
if all {
var made: u64 = 0;
if fold_known(kind, &held, this, walking, &mut made) {
walking.known[held.result] = made;
walking.fixed[held.result] = true;
return 0;
}
}
}
if kind == op::select && walking.fixed[this.arg(index, 0)] {
val chosen := this.arg(index, walking.known[this.arg(index, 0)] != 0 ? 1 : 2);
if walking.fixed[chosen] {
walking.known[held.result] = walking.known[chosen];
walking.fixed[held.result] = true;
}
return 0;
}
# What reaches a cell that promotes costs nothing, nor do the steps to it.
match kind {
op::add => {
val a := this.arg(index, 0);
val b := this.arg(index, 1);
if (walking.free[a] && walking.fixed[b]) || (walking.free[b] && walking.fixed[a]) {
walking.free[held.result] = true;
return 0;
}
}
op::load, op::store, op::clear => {
return 0 if walking.free[this.arg(index, 0)];
}
op::copy => {
return 0 if walking.free[this.arg(index, 0)] && walking.free[this.arg(index, 1)];
}
else => {}
}
return this.inline_cost(index);
}
#! What an operator of constants gives, as the machine works it out.
#! @param kind The operator.
#! @param held The instruction.
#! @param body The code.
#! @param walking What the walk knows, which knows each operand.
#! @param made Where what it gives is written.
#! @returns Whether it gives anything: not where it divides by zero, or is
#! not an operator worked out so.
def fold_known(kind: op, held: &inst, body: &code, walking: &worth_walk, made: &mut u64): bool {
val number := kind as u32;
val x: u64 = walking.known[body.operands[held.args]];
var y: u64 = 0;
if held.argc >= 2 {
y = walking.known[body.operands[held.args as u64 + 1]];
}
return fold_word(kind, x, y, made) if number >= op::add as u32 && number <= op::leus as u32;
return fold_real(kind, x, y, made) if number >= op::fadd as u32 && number <= op::fle as u32;
return fold_unary(kind, x, made) if number >= op::neg as u32 && number <= op::bswap as u32;
if kind == op::wrap {
made = wrap_word(x, held.aux, held.imm != 0);
return true;
}
if kind == op::select {
made = x != 0 ? y : walking.known[body.operands[held.args as u64 + 2]];
return true;
}
return false;
}
#! Which of code's first 64 parameters are addresses read, written, copied,
#! and cleared through alone, directly or at steps of constants from them:
#! nothing else learns them, nor what they reach, so where what they reach is
#! a cell of the caller's, a copy of the code leaves the cell to promote.
#! @param this The code.
#! @param reaches Where how many reads, writes, copies, and clears are
#! through those parameters is written.
#! @returns The parameters, one bit each.
pub def code::contained_params(&this, reaches: &mut u32): u64 {
reaches = 0;
val params := &this.blocks[0].params;
val count := params.length < 64 ? params.length : 64;
# One more than the parameter each value steps from, or 0.
var root := vector::<u32>::new(scratch());
root.resize(this.origins.length);
var any := false;
for p in 0..count {
val param: u32 = params[p];
if this.type_of(param) == vt::word {
root[param] = p as u32 + 1;
any = true;
}
}
return 0 if !any;
# The steps of constants from each, until no more are found.
var grew := true;
while grew {
grew = false;
var walk := this.walk_all();
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
continue if held.kind != op::add || held.argc != 2 || root[held.result] != 0;
var bits: u64 = 0;
val a := this.arg(at, 0);
val b := this.arg(at, 1);
if root[a] != 0 && this.word_constant(b, &mut bits) {
root[held.result] = root[a];
grew = true;
} else if root[b] != 0 && this.word_constant(a, &mut bits) {
root[held.result] = root[b];
grew = true;
}
}
}
# Any other read of one, as a call's argument, a value stored, or what an
# edge gives, lets it out.
var out: u64 = 0;
var accesses: u32[64];
var walk := this.walk_all();
var reads := this.reader();
while walk.more() {
val at := walk.next();
val held: inst = this.insts[at];
val stepping := held.kind == op::add && root[held.result] != 0;
reads.start(at);
while reads.more() {
val from: u32 = root[reads.next()];
continue if from == 0;
val i := reads.operand();
var direct := false;
if i != no_operand {
match held.kind {
op::load, op::store, op::clear => direct = i == 0;
op::copy => direct = i < 2;
op::add => direct = stepping;
else => {}
}
}
if !direct {
out = out | (1u << (from - 1) as u64);
} else if held.kind != op::add {
accesses[from - 1] = accesses[from - 1] + 1;
}
}
}
var all: u64 = 0;
for p in 0..count {
if root[params[p]] != 0 && (out & (1u << p as u64)) == 0 {
all = all | (1u << p as u64);
reaches = reaches + accesses[p];
}
}
return all;
}