#! @file inline.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the fourth pass of the optimizer, inlining: a call of a function #! small enough is replaced by a copy of the function's code. The block the #! call is in ends going into the copy, which is given the call's arguments as #! its parameters, its own copy of each one taken as memory, and zeroed cells #! of its own; each `return` of the copy goes to the rest of the block, which #! takes what was returned. Functions are inlined into those calling them #! once their own calls are, so what is copied is already small. #! #! A function of any size is copied where the program calls it but once and #! nothing else reaches it, as it is then left unused, and one of up to twice #! the size where the call gives a constant deciding where its entry goes, #! which folds the entry's branch and what only the other way leads to. A #! function too large whose entry tests something and one way only returns #! has just the test and that way copied, going on to call the function the #! other way, which tests again. A call is left as it is where every way on #! from it stops the program, as what inlining it would save never matters #! there. #! #! A function written `@inline` is copied wherever it is called, whatever its #! size, how much the function calling it has grown, or whether the call is #! cold, at every level: below `-O2`, its calls are the only ones inlined. A #! call it cannot be copied at stays a call: one of a function after the one #! calling it in the order, as where it closes a loop of calls, or one through #! a trait reference or a function value. #! #! A trace still names a function inlined, where it was, then where it was #! called: each instruction copied names the site it was inlined at, which #! names the function, the call, and the site that call was itself at. module sakura::compiler; #! The most instructions a function inlined may have, but for its constants, #! jumps, and returns. pub const inline_limit: u32 = 16; #! The most instructions a method an iterator gives its elements by, or a #! functor's `invoke`, may have, but for constants, jumps, and returns, where a #! loop calls it: so each element of a chain of adapters is worked out within #! the loop walking it, as a loop written out would. pub const step_limit: u32 = 96; #! The most instructions a function may grow to by inlining what it calls. pub const inline_growth: u32 = 6000; #! What a call's `imm` is where the function it calls was optimized before the #! function holding it began, as one it waited for, or one that one waited for: #! only such a function's code and facts are read, since any other may still #! be changing on a thread of its own. Any other call's is 0. pub const call_settled: u64 = 1; #! The most instructions a function may grow to by inlining a function it #! alone calls: past it, optimizing the larger function costs more than the #! call saves, and the code it makes is no smaller. pub const sole_growth: u32 = 3000; #! The most instructions the test of a function's entry and the way it only #! returns may have, but for constants, jumps, and returns, where a call copies #! them and calls the function the other way. pub const partial_limit: u32 = 4; #! What inlining knows of a function. All but `sole` is worked out once the #! function is optimized, as its code no longer changes then; `sole` is worked #! out with the order functions are optimized in, before any is. pub struct inline_facts { var known: bool; #! Whether what is worked out once it is optimized is. var fits: bool; #! Whether its code may be copied where it is called: it is lowered, takes no environment, computes no evaluation, and does nothing that needs a frame of its own, as asking where its frame is. var cost: u32; #! Its instructions, but for constants, jumps, returns, and vectors' reads, writes, and operations. var size: u32; #! All its instructions. var tested: u64; #! Which of its first 64 parameters decide where its entry goes, one bit each, as `entry_tests` says. var returns: bool; #! Whether any way through it returns. var asks: bool; #! Whether it asks which instructions the processor has, so its version, which calls of versions inline, does better than a copy of it would. var short: u32; #! One more than the block its entry goes to one way that only returns, as `short_way` finds it, or 0. var head: u32; #! What the test going there and that block cost, counted as `cost` is. var sole: u32; #! One more than the function making the only call of it, where nothing else reaches it, or 0. } #! Finds, of the functions about to be optimized, those the program calls but #! once and reaches no other way: not as a value, through a vtable, from C, at #! a safe point, nor by name, as `main`, the code initializing the globals, and #! what the backend calls are. Each notes the function calling it, which copies #! it whole, whatever its size, where the call is not cold. The calls are #! counted before any function is optimized, so what each is made into is the #! same however many threads optimize them. #! @param this The compiler. #! @param order The functions about to be optimized, which are all that call #! them, as each calls only what was lowered with it or before. pub def lowerer::find_sole_calls(&mut this, order: &vector): void { return if this.options.level < 2; val point := mark_scratch(); val count := this.program.functions.length; var calls := vector::::new(scratch()); calls.resize(count); var callers := vector::::new(scratch()); callers.resize(count); var other := vector::::new(scratch()); other.resize(count); for &function in order.view() { val body := &this.program.functions[function].body; var walk := body.walk_all(); while walk.more() { val at := walk.next(); val kind := body.insts[at].kind; val callee: u32 = body.insts[at].aux; if kind == op::call { calls[callee] = calls[callee] + 1; callers[callee] = function; } else if kind == op::callback || kind == op::safepoint { other[callee] = true; } } } for &each in this.program.vtables { for &function in each.functions { if function != no_function { other[function] = true; } } } val roots: u32[3] = [this.program.main, this.program.init, this.dispatch]; for r in 0..3u { if roots[r] != no_function { other[roots[r]] = true; } } for &function in order.view() { val held := &mut this.program.functions[function]; held.inlining.sole = 0; continue if calls[function] != 1 || callers[function] == function || other[function] || held.taken || held.callback; held.inlining.sole = callers[function] + 1; } release_scratch(point); } #! Whether a function may be inlined wherever it is called, being small enough. #! @param this The compiler. #! @param index The function. #! @returns Whether it may. pub def lowerer::inlinable(&mut this, index: u32): bool { val facts := this.inline_facts(index); val limit := this.options.inline_limit != 0 ? this.options.inline_limit : inline_limit; return facts.fits && facts.cost <= limit; } #! What inlining knows of a function, worked out once its own calls are #! inlined, after which its code no longer changes, so what is found is kept. #! @param this The compiler. #! @param index The function. #! @returns What it knows. pub def lowerer::inline_facts(&mut this, index: u32): inline_facts { if !this.program.functions[index].inlining.known { this.work_out_facts(index); } return this.program.functions[index].inlining; } #! Works out what inlining knows of an optimized function, keeping `sole`. #! @param this The compiler. #! @param index The function. def lowerer::work_out_facts(&mut this, index: u32): void { val held := &this.program.functions[index]; val body := &held.body; var facts: inline_facts = held.inlining; facts.known = true; facts.fits = held.lowered && !held.closure && held.evaluation == 0; var walk := body.walk_all(); while walk.more() { val at := walk.next(); val kind := body.insts[at].kind; facts.size++; facts.cost += body.inline_cost(at); match kind { op::frame, op::ready, op::reach, op::same => facts.fits = false; op::ret => facts.returns = true; op::cpu => facts.asks = true; else => {} } } facts.tested = body.entry_tests(); if facts.fits { var head: u32 = 0; facts.short = this.short_way(index, &mut head); facts.head = head; } this.program.functions[index].inlining = facts; } #! Which parameters decide where code's entry goes, so a constant given for #! one folds the entry's branch or switch, and what it alone leads to goes: #! the word it branches or switches on, or what the entry compares with a #! constant to give that word. #! @param this The code. #! @returns The parameters of its first 64, one bit each. def code::entry_tests(&this): u64 { val last: u32 = this.blocks[0].last; return 0 if last == 0 || (this.insts[last].kind != op::branch && this.insts[last].kind != op::switch); var tested: u64 = 0; val cond := this.arg(last, 0); var subjects: u32[2] = [cond, 0]; val made := this.defining(cond); if made != 0 && this.insts[made].block == 0 && this.insts[made].argc == 2 { match this.insts[made].kind { op::eq, op::ne, op::lts, op::ltu, op::les, op::leu, op::eqsu, op::ltsu, op::lesu, op::ltus, op::leus, op::feq, op::fne, op::flt, op::fle => { var bits: u64 = 0; val a := this.arg(made, 0); val b := this.arg(made, 1); if this.word_constant(b, &mut bits) || this.real_constant(b, &mut bits) { subjects[1] = a; } else if this.word_constant(a, &mut bits) || this.real_constant(a, &mut bits) { subjects[1] = b; } } else => {} } } for k in 0..2u { continue if subjects[k] == 0; val held: origin = this.origins[subjects[k]]; if held.param && held.from == 0 && held.index < 64 { tested = tested | (1u << held.index as u64); } } return tested; } #! What an instruction costs inlined: nothing for a constant, a jump, or a #! return, which becomes a jump to the rest of the caller's block, as copied #! they mostly fold or merge away; nor for vectors' reads, writes, and #! operations, which inlined become values held in registers where the #! caller's cells are promoted, or asking for the processor's instructions, #! which code for those it has knows; and 1 for anything else. #! @param this The code. #! @param index The instruction. #! @returns What it costs. def code::inline_cost(&this, index: u32): u32 { return match this.insts[index].kind { op::iconst, op::fconst, op::jump, op::ret, op::cpu, op::vzero, op::lanes => 0, op::load, op::store => (this.insts[index].aux as access).value_type().lanes() ? 0 : 1, else => 1 }; } #! Inlines the calls a function makes of functions that come before it in the #! order functions are optimized in, so their own calls are inlined already. #! Each call is copied whole where the function it calls is small enough, is #! called by it alone, or is given a constant deciding where its entry goes and #! is up to twice as large; or else, where the function calling is itself too large to be #! inlined whole, as far as the way the entry only returns. A call in a cold #! block is left as it is, as is one of a function too large that asks which #! instructions the processor has, but that a call of an `@inline` function is #! copied whole wherever it is. Below `-O2`, those are the only calls copied, #! and no call through a function value is made a call of the function. #! @param this The compiler. #! @param index The function. #! @param ranks Where each function is in the order, as `optimizing` says. #! @param rank Where the function is. #! @returns Whether any call was. pub def lowerer::inline_calls(&mut this, index: u32, ranks: &vector, rank: u32): bool { val called := this.options.level >= 2 && this.devirtualize(index, ranks, rank); val changed := this.inline_each(index, ranks, rank); return called || changed; } #! Inlines the calls a function makes of functions that come before it, as #! `inline_calls` says, or below `-O2`, only those of `@inline` functions. #! @param this The compiler. #! @param index The function. #! @param ranks Where each function is in the order, as `optimizing` says. #! @param rank Where the function is. #! @returns Whether any call was. def lowerer::inline_each(&mut this, index: u32, ranks: &vector, rank: u32): bool { val every := this.options.level >= 2; val marks := this.inlines_marked(); var calls := vector::::new(scratch()); var cost: u32 = 0; val body := &this.program.functions[index].body; var walk := body.walk_all(); while walk.more() { val at := walk.next(); cost += body.inline_cost(at); if body.insts[at].kind == op::call && (every || marks && this.program.functions[body.insts[at].aux].inline) { calls.append(at); } } return false if calls.length == 0; # Only what inlines more than `@inline` functions asks which calls are cold, # or in a loop. var hot := vector::::new(scratch()); var in_loop := vector::::new(scratch()); if every { val cold := this.cold_blocks(index, ranks, rank); val looped := this.looped_blocks(index); for &call in calls { hot.append(!cold[body.insts[call].block]); in_loop.append(looped[body.insts[call].block]); } } # What each call gave is replaced once every call is inlined. var changed := false; var done := rewrite::new(); var size := this.program.functions[index].body.size(); val limit := this.options.inline_limit != 0 ? this.options.inline_limit : inline_limit; for c in 0..calls.length { val call: u32 = calls[c]; val callee: u32 = this.program.functions[index].body.insts[call].aux; val marked := marks && this.program.functions[callee].inline; continue if !marked && (size > inline_growth || !hot[c]); continue if callee == index || ranks[callee] >= rank || this.program.functions[index].body.insts[call].imm != call_settled; val facts := this.inline_facts(callee); continue if !facts.fits; var whole := marked || facts.cost <= limit; if !whole && facts.cost <= step_limit && this.program.functions[callee].stepping { whole = in_loop[c]; } continue if !whole && facts.asks; if !whole && facts.sole == index + 1 && size + facts.size <= sole_growth { whole = calls_of(&this.program.functions[index].body, &calls, callee) == 1; } if !whole && facts.tested != 0 && facts.cost <= 2 * limit { whole = this.program.functions[index].body.gives_tested(call, facts.tested); } if whole { if this.inline_call(index, call, &mut done) { size += facts.size; cost += facts.cost; changed = true; this.names_of(index, callee, ranks); } continue; } # A function small enough to be inlined whole stays so, as copying the test # would leave it calling all the same, only larger. continue if cost <= limit || facts.short == 0 || facts.head > partial_limit; continue if !this.head_fits(index, call, facts.short - 1); this.inline_head(index, call, facts.short - 1, &mut done); size += facts.head; cost += facts.head; changed = true; this.names_of(index, callee, ranks); } if changed { this.program.functions[index].body.apply(&done); this.program.functions[index].body.prune(); } return changed; } #! Gives a function the functions named by one inlined into it, whose values #! its code may now hold: those that one waited for, so they were optimized #! before the function began. #! @param this The compiler. #! @param index The function. #! @param callee The function inlined. #! @param ranks Where each function is in the order. def lowerer::names_of(&mut this, index: u32, callee: u32, ranks: &vector): void { val count := this.program.functions[callee].named.length; for i in 0..count { val named: u32 = this.program.functions[callee].named[i]; if ranks[named] < ranks[callee] { this.names(index, named); } } } #! Calls the function a function value holds directly where it is known, as #! where the value was made in the code calling it, once what made it is #! inlined: a call of it is then inlined as any other is, where the function was #! named by the code, so optimizing it waited for it. One a constant's data #! holds is called directly, but not inlined. A function taking an environment #! is left called through the value. What made the value marked the function #! `taken`, so nothing else learns of the call. #! @param this The compiler. #! @param index The function. #! @param ranks Where each function is in the order, as `optimizing` says. #! @param rank Where the function is. #! @returns Whether any call changed. def lowerer::devirtualize(&mut this, index: u32, ranks: &vector, rank: u32): bool { var changed := false; val count := this.program.functions.length as u64; var found := vector::::new(scratch()); var walk := this.program.functions[index].body.walk_all(); while walk.more() { val at := walk.next(); if this.program.functions[index].body.insts[at].kind == op::call_value { found.append(at); } } for &at in found { val body := &mut this.program.functions[index].body; var bits: u64 = 0; continue if !body.word_constant(body.arg(at, 0), &mut bits) || bits == 0 || bits > count; val callee := (bits - 1) as u32; continue if this.program.functions[callee].closure || this.program.functions[callee].signature != body.insts[at].aux; var args := vector::::new(scratch()); for i in 2..body.insts[at].argc { args.append(body.arg(at, i)); } val settled := ranks[callee] < rank && this.named_by(index, callee); body.become(at, op::call, args.view(), callee, settled ? call_settled : 0); changed = true; } return changed; } #! Whether a function's code, or code inlined into it, names another as a value. #! @param this The compiler. #! @param index The function. #! @param callee The other. #! @returns Whether it does. def lowerer::named_by(&this, index: u32, callee: u32): bool { for &each in this.program.functions[index].named.view() { return true if each == callee; } return false; } #! Which blocks of a function's code are within a loop of it. #! @param this The compiler. #! @param index The function. #! @returns Whether each block is, by block, in scratch memory. def lowerer::looped_blocks(&mut this, index: u32): vector { var made := vector::::new(scratch()); val body := &mut this.program.functions[index].body; made.resize(body.blocks.length); val view := body.view_loops(); for b in 0..body.blocks.length { made[b] = b < view.nest.inner.length && view.nest.inner[b] != no_loop; } return made; } #! How many of the calls code makes call a function, of those not yet #! inlined. #! @param body The code. #! @param calls The calls. #! @param callee The function. #! @returns How many. def calls_of(body: &code, calls: &vector, callee: u32): u32 { var count: u32 = 0; for &each in calls { if body.insts[each].kind == op::call && body.insts[each].aux == callee { count++; } } return count; } #! Whether a call gives a constant for a parameter that decides where the entry #! of the function it calls goes, which folds once the function is copied. #! @param this The code. #! @param call The call. #! @param tested Which parameters decide it, as `entry_tests` says. #! @returns Whether it does. def code::gives_tested(&this, call: u32, tested: u64): bool { val count := this.insts[call].argc; for i in 0..(count < 64 ? count : 64) { continue if (tested & (1u << i as u64)) == 0; 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; } #! Finds the cold blocks of a function's code: those every way on from which #! stops the program, by a trap, or what never returns, as an `abort`, or a #! call of a function before it in the order that never returns, each block #! then cold once every block it goes to is. #! @param this The compiler. #! @param index The function. #! @param ranks Where each function is in the order functions are optimized #! in, as `optimizing` says. #! @param rank Where the function is. #! @returns Whether each block is cold, by its index. def lowerer::cold_blocks(&mut this, index: u32, ranks: &vector, rank: u32): vector { val body := &this.program.functions[index].body; var cold := vector::::new(scratch()); cold.resize(body.blocks.length); var any := false; for b in 0..body.blocks.length { continue if body.blocks[b].gone; var walk := body.walk(b as u32); while walk.more() { val at := walk.next(); val kind := body.insts[at].kind; if kind == op::trap || kind == op::unreachable || kind == op::abort || kind == op::fault { cold[b] = true; } else if kind == op::call { val callee: u32 = body.insts[at].aux; if ranks[callee] < rank && body.insts[at].imm == call_settled && !this.inline_facts(callee).returns { cold[b] = true; } } } any = any || cold[b]; } return cold if !any; # A loop never cold of itself stays as it is, as each of its blocks waits on # another. var changed := true; while changed { changed = false; var b := body.blocks.length; while b > 0 { b--; continue if cold[b] || body.blocks[b].gone; val last: u32 = body.blocks[b].last; continue if last == 0 || body.edge_count(last) == 0; var all := true; var edges := body.edges_of(last); while edges.more() { if !cold[body.edges[edges.next()].target] { all = false; break; } } if all { cold[b] = true; changed = true; } } } return cold; } #! Works out the order a function's blocks are copied in where it is inlined, #! once, as its code no longer changes once it may be. #! @param this The compiler. #! @param index The function. pub def lowerer::order_blocks(&mut this, index: u32): void { return if this.program.functions[index].order.length != 0; var order := vector::::new(); var number := vector::::new(scratch()); this.program.functions[index].body.block_order(&mut order, &mut number); this.program.functions[index].order = move(&mut order); } #! How a function takes each of the values its entry block takes: whether each #! is the address of a parameter taken as memory, and the parameter's layout. #! @param this The compiler. #! @param signature The function's signature. #! @param memory Where whether each is held in memory is written. #! @param layouts Where the layout of each one held in memory is written. def lowerer::entry_values(&this, signature: u32, memory: &mut vector, layouts: &mut vector): void { val held := &this.program.signatures[signature]; for i in 0..held.params.length { val index: u32 = held.params[i]; val shape := this.layout_at(index); if in_memory(&shape) { memory.append(true); layouts.append(index); continue; } for _ in 0..word_count(&shape) { memory.append(false); layouts.append(index); } } } #! Ends the block a call is in at the call, the rest of it a block of its own #! taking what the call gives, which what read that reads instead once every #! call is inlined. #! @param this The code. #! @param call The call. #! @param done Where what reads what the call gave is noted. #! @returns The rest of the block. def code::split_at(&mut this, call: u32, done: &mut rewrite): u32 { val held: inst = this.insts[call]; val home := held.block; val rest := this.add_block(); this.blocks[rest].first = held.next; this.blocks[rest].last = this.blocks[home].last; var moved := this.walk(rest); while moved.more() { this.insts[moved.next()].block = rest; } this.insts[call].next = 0; this.blocks[home].last = call; for r in 0..held.count { val result := held.result + r as u32; val param := this.add_param(rest, this.type_of(result)); done.replace(result, param); } return rest; } #! The site, among those of the code a function is copied into at a call, of #! code of the function: the site of the call, for the function's own code, or #! for code inlined into the function, a copy of the site it was inlined at, #! within the copy of the site that was within. Each is made the first time it #! is asked for, so none is made of a site whose code was taken out of the #! function, or is left out of the copy. #! @param this The code copied into. #! @param callee The code of the function. #! @param index The function. #! @param held The call. #! @param sites One more than the site made for the function's own code, #! then for each of its sites, or 0 for each not made yet. #! @param site One more than the function's site, or 0 for its own code. #! @returns One more than the site made. def code::site_in(&mut this, callee: &code, index: u32, held: &inst, sites: &mut vector, site: u32): u32 { return sites[site] if sites[site] != 0; var made := inline_site { function = index, at = held.at, parent = held.site }; if site != 0 { val each: inline_site = callee.sites[site - 1]; made = inline_site { function = each.function, at = each.at, parent = this.site_in(callee, index, held, sites, each.parent) }; } this.sites.append(made); sites[site] = this.sites.length as u32; return sites[site]; } #! Replaces a call with a copy of the code of the function it calls. #! @param this The compiler. #! @param caller The function calling. #! @param call The `call`. #! @param done What reads what the call gave reads instead, applied once #! every call is inlined. #! @returns Whether it was replaced, which it is not where the call does not #! give what the function takes. def lowerer::inline_call(&mut this, caller: u32, call: u32, done: &mut rewrite): bool { val callee_index: u32 = this.program.functions[caller].body.insts[call].aux; this.order_blocks(callee_index); val callee := &this.program.functions[callee_index].body; val body := &mut this.program.functions[caller].body; val held: inst = body.insts[call]; var memory := vector::::new(scratch()); var layouts := vector::::new(scratch()); this.entry_values(this.program.functions[callee_index].signature, &mut memory, &mut layouts); val takes := callee.blocks[0].params.length; val returns_memory := callee.returned != 0; val given := held.argc as u64 - (returns_memory ? 1 : 0); return false if takes != given || memory.length != takes || held.count as u64 != callee.results.length; # The rest of the block, after the call, is a block of its own, taking what # the call gives. val rest := body.split_at(call, done); val dst: u32 = returns_memory ? body.arg(call, held.argc - 1) : 0; # Where the function inlined was called, which each instruction copied names. var sites := vector::::new(scratch()); sites.resize(callee.sites.length + 1); # Its cells follow the caller's, cleared where the copy begins rather than # as the frame does, but those it declares `undefined`. val base := body.cells.length as u32; for &each in callee.cells { val kind := each.kind == ck::undefined ? ck::undefined : ck::inlined; body.cells.append(cell { size = each.size, align = each.align, kind = kind, name = each.name }); } # A block of the caller for each of its blocks, taking what it takes. var map := vector::::new(scratch()); map.resize(callee.origins.length); var blocks := vector::::new(scratch()); blocks.resize(callee.blocks.length); for b in 0..callee.blocks.length { continue if callee.blocks[b].gone; val made := body.add_block(); blocks[b] = made; continue if b == 0; for ¶m in callee.blocks[b].params { map[param] = body.add_param(made, callee.type_of(param)); } } # The copy begins zeroing its cells, as a call's frame begins zeroed, but for # those the function's own frame would not zero, as every word of them some # path reads is written first, and taking its own copy of each parameter held # in memory. val entry: u32 = blocks[0]; var gives: vt[1] = [vt::word]; var ordered := vector::::new(scratch()); var places := vector::::new(scratch()); callee.copy_order(&mut ordered, &mut places); val writes := this.result_writes(callee_index); val zeroed := zeroed_cells(callee, ordered.view(), places.view(), writes.view()); for c in 0..callee.cells.length { continue if callee.cells[c].kind == ck::undefined || !zeroed[c]; val address := body.append(entry, op::cell, span::::empty(), gives[0:1], base + c as u32, 0, held.at); body.insts[address].site = held.site; var args: u32[1] = [body.insts[address].result]; val clear := body.append(entry, op::clear, args[0:1], span::::empty(), 0, callee.cells[c].size as u64, held.at); body.insts[clear].site = held.site; } var copies := vector::::new(scratch()); copies.resize(takes); for i in 0..takes { val param: u32 = callee.blocks[0].params[i]; val arg := body.arg(call, i as u32); if !memory[i] { map[param] = arg; continue; } val shape := this.layout_at(layouts[i]); val cell := body.add_cell(round_up(shape.size, word_size) as u32, shape.align < word_size ? word_size as u32 : shape.align as u32, ck::inlined, 0); val address := body.append(entry, op::cell, span::::empty(), gives[0:1], cell, 0, held.at); body.insts[address].site = held.site; val copy_of := body.insts[address].result; var args: u32[2] = [copy_of, arg]; val copied := body.append(entry, op::copy, args[0:2], span::::empty(), 0, shape.size, held.at); body.insts[copied].site = held.site; map[param] = copy_of; copies[i] = cell + 1; } # Its instructions, in an order each value is made before it is read, each # one's copy noted. var copied := vector::::new(scratch()); copied.resize(callee.insts.length); val order := &this.program.functions[callee_index].order; var args := vector::::new(scratch()); var types := vector::::new(scratch()); for &b in order.view() { val into: u32 = blocks[b]; var walk := callee.walk(b); while walk.more() { val at := walk.next(); val from: inst = callee.insts[at]; val site := body.site_in(callee, callee_index, &held, &mut sites, from.site); args.clear(); for i in 0..from.argc { args.append(map[callee.arg(at, i as u32)]); } if from.kind == op::ret { # A return goes on to the rest of the caller's block, giving what it # returns, or copying the memory it returns where the call said. if returns_memory { var copy_args: u32[2] = [dst, args.last()]; val copied := body.append(into, op::copy, copy_args[0:2], span::::empty(), 0, callee.returned as u64, from.at); body.insts[copied].site = site; args.clear(); } body.jump_with(into, rest, args.view(), from.at, site); continue; } types.clear(); for r in 0..from.count { types.append(callee.type_of(from.result + r as u32)); } val aux := from.kind == op::cell ? from.aux + base : from.aux; val made := body.append(into, from.kind, args.view(), types.view(), aux, from.imm, from.at); body.insts[made].site = site; copied[at] = made; for r in 0..from.count { map[from.result + r as u32] = body.insts[made].result + r as u32; } # Its edges, made one after another, go where the copies of their blocks # are, giving what the copies of their arguments are. val count := callee.edge_count(at); if count != 0 { var first: u32 = 0; for e in 0..count { val out := &callee.edges[from.aux + e as u32]; val copy := body.add_edge(made, blocks[out.target], out.case); if e == 0 { first = copy; } for &each in out.args { body.edges[copy].args.append(map[each]); } } body.insts[made].aux = first; } } } # Its variables are the caller's too, where it was inlined, held where the # copies of what held them are, or as the constants their bindings keep. val first_variable := body.variables.length as u32; for &each in callee.variables { var made: variable_info = each; made.site = body.site_in(callee, callee_index, &held, &mut sites, each.site); made.first = 0; made.end = 0; if each.cell != 0 { made.cell = base + each.cell; } else if each.given != 0 { made.cell = copies[each.given as u64 - 1]; made.given = 0; } body.variables.append(made); } for &each in callee.bindings { val value: u32 = map[each.value]; var known := each.known; var bits := each.bits; if value == 0 && known == vt::none { known = callee.constant_kind(each.value, &mut bits); } continue if value == 0 && known == vt::none; val gone := each.block == no_block || callee.blocks[each.block].gone; body.bindings.append(binding { variable = first_variable + each.variable, word = each.word, value = value, after = each.after != 0 ? copied[each.after] : 0, block = gone ? no_block : blocks[each.block], known = known, bits = bits }); } # The call goes into the copy. val edge := body.add_edge(call, entry, 0); body.become(call, op::jump, span::::empty(), edge, 0); body.insts[call].count = 0; body.insts[call].result = 0; return true; } #! Ends a block jumping to another, giving it values. #! @param this The code. #! @param from The block. #! @param target The block it jumps to. #! @param args What it gives the target's parameters. #! @param pos Where in the source the jump is from. #! @param site One more than the site of the function it was inlined from. def code::jump_with(&mut this, from: u32, target: u32, args: span, pos: u64, site: u32): void { val jump := this.append(from, op::jump, span::::empty(), span::::empty(), 0, 0, pos); this.insts[jump].site = site; val edge := this.add_edge(jump, target, 0); this.insts[jump].aux = edge; for &each in args { this.edges[edge].args.append(each); } } # Inlining the test of an entry. #! Finds the way a function's entry only returns, which a call of it may copy #! with the entry's test, calling the function the other way: the entry ends #! branching, and before only computes, reads memory, or checks, taking no #! cell's address, so the call made the other way, running it again, does #! what the function would have; and one way goes to a block other than the #! entry that returns, calling nothing and taking no cell's address. The #! function takes nothing in memory, nor returns memory, so the copy reads #! only what the call gives. Of two such ways, the one costing less is taken. #! @param this The compiler. #! @param index The function. #! @param cost Where what the test and that way cost is written, counting #! only what of the entry the test needs, as `head_needs` says. #! @returns One more than the block it goes to, or 0 where it has none. def lowerer::short_way(&this, index: u32, cost: &mut u32): u32 { val held := &this.program.functions[index]; val body := &held.body; val last: u32 = body.blocks[0].last; return 0 if body.returned != 0 || last == 0 || body.insts[last].kind != op::branch; var memory := vector::::new(scratch()); var layouts := vector::::new(scratch()); this.entry_values(held.signature, &mut memory, &mut layouts); return 0 if memory.length != body.blocks[0].params.length || memory.view().contains(&true); var walk := body.walk(0); while walk.more() { val at := walk.next(); val kind := body.insts[at].kind; val traits := kind.traits(); return 0 if kind == op::cell || (at != last && (traits & op_pure) == 0 && kind != op::load && traits != op_traps); } var found: u32 = 0; var least: u32 = 0xFFFFFFFF; val first: u32 = body.insts[last].aux; for side in 0..2u { val way: u32 = body.edges[first + side].target; continue if way == 0 || way == body.edges[first + 1 - side].target; val end: u32 = body.blocks[way].last; continue if end == 0 || body.insts[end].kind != op::ret; var spent: u32 = 0; var fits := true; var steps := body.walk(way); while steps.more() { val at := steps.next(); val kind := body.insts[at].kind; if kind == op::cell || (kind.traits() & op_calls) == op_calls { fits = false; break; } spent += body.inline_cost(at); } continue if !fits; var needed := vector::::new(scratch()); body.head_needs(way, &mut needed); var entry := body.walk(0); while entry.more() { val at := entry.next(); if needed[at] { spent += body.inline_cost(at); } } if spent < least { least = spent; found = way + 1; } } cost = found != 0 ? least : 0; return found; } #! Marks which instructions of code's entry the test going to a way that only #! returns needs: the branch, what may stop the program but a read, what the #! edge going that way gives, and what the way reads, each with what it reads #! in turn. The rest only computes, or reads memory, which a copy leaves out #! where the address read is never zero. #! @param this The code. #! @param way The block the way begins at. #! @param needed Where whether each instruction is needed is written, by #! its index. def code::head_needs(&this, way: u32, needed: &mut vector): void { needed.resize(this.insts.length); var values := vector::::new(scratch()); val last: u32 = this.blocks[0].last; var walk := this.walk(0); while walk.more() { val at := walk.next(); val kind := this.insts[at].kind; if at == last || ((kind.traits() & op_pure) == 0 && kind != op::load) { needed[at] = true; for i in 0..this.insts[at].argc { values.append(this.arg(at, i as u32)); } } } val first: u32 = this.insts[last].aux; for side in 0..2u { continue if this.edges[first + side].target != way; for &each in this.edges[first + side].args { values.append(each); } } var reads := this.reader(); var steps := this.walk(way); while steps.more() { reads.start(steps.next()); while reads.more() { values.append(reads.next()); } } while values.length != 0 { val value: u32 = values.last(); values.truncate(); val made := this.defining(value); continue if made == 0 || this.insts[made].block != 0 || needed[made]; needed[made] = true; for i in 0..this.insts[made].argc { values.append(this.arg(made, i as u32)); } } } #! Whether a call may copy the test of the function it calls and the way it #! only returns, leaving out what of the entry the test does not need: each #! read left out reads an address never zero, as the call gives it, so leaving #! it out never leaves out a stop. #! @param this The compiler. #! @param caller The function calling. #! @param call The `call`. #! @param way The block the way begins at. #! @returns Whether it may. def lowerer::head_fits(&this, caller: u32, call: u32, way: u32): bool { val body := &this.program.functions[caller].body; val callee := &this.program.functions[body.insts[call].aux].body; return false if body.insts[call].argc as u64 != callee.blocks[0].params.length || body.insts[call].count as u64 != callee.results.length; var needed := vector::::new(scratch()); callee.head_needs(way, &mut needed); var walk := callee.walk(0); while walk.more() { val at := walk.next(); continue if needed[at] || callee.insts[at].kind != op::load; return false if !never_zero_given(body, call, callee, callee.arg(at, 0)); } return true; } #! Whether an address a function's entry reads is never zero where a call #! gives the function its arguments: a small step past a parameter the call #! gives an address never zero, or past one the function's code never has zero. #! @param body The code calling. #! @param call The `call`. #! @param callee The code of the function called. #! @param address The address, in the function's code. #! @returns Whether it is never zero. def never_zero_given(body: &code, call: u32, callee: &code, address: u32): bool { var at := address; var steps := 0; while steps < 8 { val held: origin = callee.origins[at]; if held.param { return held.from == 0 && body.never_zero(body.arg(call, held.index)); } return callee.never_zero(at) if callee.insts[held.from].kind != op::add; var step: u64 = 0; return false if !callee.word_constant(callee.arg(held.from, 1), &mut step) || step >= 0x100000000u; at = callee.arg(held.from, 0); steps++; } return false; } #! Replaces a call with a copy of the test the entry of the function it calls #! makes, and of the way the entry only returns, which goes on to the rest of #! the block; the other way calls the function, which tests again. #! @param this The compiler. #! @param caller The function calling. #! @param call The `call`, which `head_fits` says may be replaced so. #! @param way The block the way begins at. #! @param done What reads what the call gave reads instead, applied once #! every call is inlined. def lowerer::inline_head(&mut this, caller: u32, call: u32, way: u32, done: &mut rewrite): void { val callee_index: u32 = this.program.functions[caller].body.insts[call].aux; val callee := &this.program.functions[callee_index].body; val body := &mut this.program.functions[caller].body; val held: inst = body.insts[call]; val rest := body.split_at(call, done); var sites := vector::::new(scratch()); sites.resize(callee.sites.length + 1); # The test, of what the entry does that it needs, each value's copy noted. var needed := vector::::new(scratch()); callee.head_needs(way, &mut needed); var map := vector::::new(scratch()); map.resize(callee.origins.length); for i in 0..callee.blocks[0].params.length { map[callee.blocks[0].params[i]] = body.arg(call, i as u32); } val head := body.add_block(); val quick := body.add_block(); val slow := body.add_block(); var args := vector::::new(scratch()); var types := vector::::new(scratch()); val last: u32 = callee.blocks[0].last; var walk := callee.walk(0); while walk.more() { val at := walk.next(); continue if !needed[at]; val from: inst = callee.insts[at]; val site := body.site_in(callee, callee_index, &held, &mut sites, from.site); args.clear(); types.clear(); for i in 0..from.argc { args.append(map[callee.arg(at, i as u32)]); } for r in 0..from.count { types.append(callee.type_of(from.result + r as u32)); } val made := body.append(head, from.kind, args.view(), types.view(), from.aux, from.imm, from.at); body.insts[made].site = site; for r in 0..from.count { map[from.result + r as u32] = body.insts[made].result + r as u32; } continue if at != last; # The branch goes the way that only returns, giving its parameters what the # edge going there gives them, and calls the function the other way. for side in 0..2u { val out := &callee.edges[from.aux + side]; val copy := body.add_edge(made, out.target == way ? quick : slow, 0); if side == 0 { body.insts[made].aux = copy; } continue if out.target != way; for p in 0..out.args.length { map[callee.blocks[way].params[p]] = map[out.args[p]]; } } } # The way, whose return goes on to the rest of the block. var steps := callee.walk(way); while steps.more() { val at := steps.next(); val from: inst = callee.insts[at]; val site := body.site_in(callee, callee_index, &held, &mut sites, from.site); args.clear(); types.clear(); for i in 0..from.argc { args.append(map[callee.arg(at, i as u32)]); } if from.kind == op::ret { body.jump_with(quick, rest, args.view(), from.at, site); break; } for r in 0..from.count { types.append(callee.type_of(from.result + r as u32)); } val made := body.append(quick, from.kind, args.view(), types.view(), from.aux, from.imm, from.at); body.insts[made].site = site; for r in 0..from.count { map[from.result + r as u32] = body.insts[made].result + r as u32; } } # The call the other way, giving the rest what it returns. args.clear(); types.clear(); for i in 0..held.argc { args.append(body.arg(call, i as u32)); } for r in 0..held.count { types.append(body.type_of(held.result + r as u32)); } val again := body.append(slow, op::call, args.view(), types.view(), held.aux, held.imm, held.at); body.insts[again].site = held.site; args.clear(); for r in 0..held.count { args.append(body.insts[again].result + r as u32); } body.jump_with(slow, rest, args.view(), held.at, held.site); # The call goes into the test. val edge := body.add_edge(call, head, 0); body.become(call, op::jump, span::::empty(), edge, 0); body.insts[call].count = 0; body.insts[call].result = 0; }