#! @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. What a loop works out of a value it changes and two it does not, #! by one operator that gives the same however grouped, as `(i + a) + b`, is #! regrouped as `i + (a + b)`, and `a + b` moves out too, as LLVM's loop #! invariant code motion regroups arithmetic. 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; #! The block heading each loop, those holding fewer blocks first, so each comes before the loops holding it. var parents: vector; #! The loop most nearly holding each loop, or `no_loop`. var members: runs; #! The blocks of the loops, a run each, its header first. var runs_of: vector; #! The run of `members` holding each loop's blocks. var inner: vector; #! 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; #! The blocks in reverse postorder. var number: vector; #! Each block's place in that order. var idom: vector; #! The immediate dominator of each block. var first: vector; #! The first block each block immediately dominates, or `no_block`. var after: vector; #! 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.span); } #! 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): 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::::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::::new(scratch()), number = vector::::new(scratch()), idom = vector::::new(scratch()), first = vector::::new(scratch()), after = vector::::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.span, made.number.span, &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, number: span, idom: &vector): loop_nest { var nest := loop_nest { headers = vector::::new(scratch()), parents = vector::::new(scratch()), members = runs::::new(scratch()), runs_of = vector::::new(scratch()), inner = vector::::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::::new(scratch()); var found := vector::::new(scratch()); var marks := stamped_set::new(this.blocks.length, scratch()); var todo := vector::::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::::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, 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::::new(scratch()); slots.resize(this.origins.length); var made := vector::::new(scratch()); for ¶m 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::::new(scratch()); var inside := vector::::new(scratch()); var past := vector::::new(scratch()); inside.resize(made.length); past.resize(made.length); var below := vector::::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::::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::::new(scratch()); taken.resize(made.length); var left := vector::::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::::new(scratch()); copies.resize(made.length); var entries := vector::::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::::new(scratch()); var args := vector::::new(scratch()); var types := vector::::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.span, types.span, 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::::blank(), 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::::blank(), span::::blank(), 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::::blank(), span::::blank(), 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.span); 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, copies: &vector, 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, copies: &vector, taken: &vector, left: &vector, pairs: span ): 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; #! 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; #! 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): bool { var view := this.view_loops(); return false if view.nest.headers.length == 0; # Regrouping adds at most one instruction for each there is. var state := hoisting { reached = this.reached_addresses(&view), moved = stamped_set::new(2 * this.insts.length + view.nest.headers.length, scratch()), aliases = this.aliases(writes, view.idom.span), writers = vector::::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.span); } # What a loop works out of a value it changes and of two it does not, as # `(i + a) + b`, is regrouped so the two are worked out together, as # `i + (a + b)`, and moves out too. var uses := vector::::new(scratch()); 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; if this.regroup_invariants(&view, k as u32, &mut uses) { this.hoist_loop(&view, k as u32, pre, &mut state); changed = true; } } return changed; } #! Regroups an operator of a value made outside a loop and one made within it #! by the same operator from another value made outside it, as LLVM's loop #! invariant code motion regroups arithmetic: `(x op a) op b`, where `x` #! changes each time round and `a` and `b` do not, becomes `x op (a op b)`, #! whose `a op b` moves out of the loop. Only sums, products, and the #! operators of bits, which give the same however grouped, of words, and only #! where nothing else reads `x op a`, which goes. #! @param this The code. #! @param view Which block dominates which, and the loops. #! @param loop The loop, what it works out the same each time round moved #! out of it already. #! @param uses How often each value was read where it was first asked, or #! empty before it is. #! @returns Whether anything was regrouped. def code::regroup_invariants(&mut this, view: &loop_view, loop: u32, uses: &mut vector): bool { val nest := &view.nest; var changed := false; for &block in nest.members.view(nest.runs_of[loop]) { var walk := this.walk(block); while walk.more() { val at := walk.next(); val held: inst = this.insts[at]; continue if held.count != 1 || held.argc != 2 || this.type_of(held.result) != vt::word; val kind := held.kind; continue if kind != op::add && kind != op::mul && kind != op::band && kind != op::bor && kind != op::bxor; for side in 0..2u { val outer := this.arg(at, side as u32); val inner := this.arg(at, 1 - side as u32); continue if nest.holds(loop, this.home_of(outer)); val made := this.defining(inner); continue if made == 0 || this.insts[made].kind != kind || !nest.holds(loop, this.insts[made].block); if uses.length == 0 { uses.extend(this.use_counts().span); } continue if (inner as u64) >= uses.length || uses[inner] != 1; val a := this.arg(made, 0); val b := this.arg(made, 1); val a_in := nest.holds(loop, this.home_of(a)); continue if a_in == nest.holds(loop, this.home_of(b)); var gives: vt[1] = [vt::word]; var pair: u32[2] = [a_in ? b : a, outer]; val joined := this.detached(kind, pair[0:2], gives[0:1], 0, 0, held.at, held.site); this.link_before(joined, at); var regrouped: u32[2] = [a_in ? a : b, this.insts[joined].result]; this.become(at, kind, regrouped[0:2], 0, 0); changed = true; break; } } } 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 { var made := hashset::::new(scratch()); var asked := vector::::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, 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::::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::::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::::blank(), span::::blank(), 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::::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::::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.span.contains(&at); } var any := false; var seen := false; var tail: u32 = 0; for &key in keys { val block := pair_low(key); val first := firsts.span.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); }