#! @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; #! The instruction giving each value worked out, by its hash. var facts: scoped_dict; #! What each condition known is. var loads: vector; #! The reads and writes remembered in the block. var copies: vector; #! The copies into cells remembered in the block. var writers: runs; #! The instructions of each block writing memory, in order, a run each. var writer_runs: vector; #! 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; #! What each block knew of memory where it ended, a run each. var kept_runs: vector; #! 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): bool { var order := vector::::new(scratch()); var number := vector::::new(scratch()); this.block_order(&mut order, &mut number); val idom := this.block_dominators(); # The blocks each block immediately dominates. var first := vector::::new(scratch()); var after := vector::::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::::new(scratch()), facts = scoped_dict::::new(scratch()), loads = vector::::new(scratch()), copies = vector::::new(scratch()), writers = runs::::new(scratch()), writer_runs = vector::::new(scratch()), kept = runs::::new(scratch()), kept_runs = vector::::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::::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::::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): bool { val preds := &this.blocks[block].preds; if preds.length == 1 && this.edge_source(preds[0]) == parent { return true; } var todo := vector::::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::::new(scratch()); var number := vector::::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::::new(scratch()); var reals := dict::::new(scratch()); var moved := vector::::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, number: span): vector { var looped := vector::::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::::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; }