diff --git a/src/engine/Metrics.v3 b/src/engine/Metrics.v3 index d6c0982a1..64b4f361e 100644 --- a/src/engine/Metrics.v3 +++ b/src/engine/Metrics.v3 @@ -31,6 +31,13 @@ component Metrics { "Number of functions successfully compiled by single-pass compiler"); def spc_time_per_byte = r("spc:time_per_byte", spc_time_us, spc_in_bytes, "Ratio of compile time per input bytecode byte"); + def spc_static_calls = m("spc:static_calls", "calls", "Number of call instructions encountered by single-pass compiler"); + def spc_static_inlined_calls = m("spc:static_inlined_calls", "calls", "Number of direct call sites inlined by single-pass compiler"); + // XXX does not include inlined whamm probes, but does include inlining within a whamm inline + def spc_dynamic_calls = m("spc:dynamic_calls", "calls", "Number of call instructions executed at runtime"); + def spc_dynamic_inlined_calls = m("spc:dynamic_inlined_calls", "calls", "Number of inlined call sites executed at runtime"); + def spc_static_remat = m("spc:static_remat", "sites", "Number of sites where stack frame reconstruction is emitted"); + def spc_dynamic_remat = m("spc:dynamic_remat", "sites", "Number of stack frame reconstructions executed at runtime"); // Metrics from executing wasm code. def start_time_us = t("start:time_us", "Time taken to execute wasm module start function(s)."); diff --git a/src/engine/Tuning.v3 b/src/engine/Tuning.v3 index c1c12d3e1..d80718b6e 100644 --- a/src/engine/Tuning.v3 +++ b/src/engine/Tuning.v3 @@ -62,7 +62,7 @@ component SpcTuning { var inlineWhammProbes = true; // inline whamm probe functions var maxInlineBytecodeSize = 100; // max bytecode size to inline var maxInlineParams = 10; // max parameters to inline - var maxInlineDepth = 0; // max inlining nesting depth + var maxInlineDepth = 1; // max inlining nesting depth def probeCallFreesRegs = true; // probe calls frees registers in abstract state def runtimeCallFreesRegs = true; // runtime calls frees registers in abstract state var intrinsifyMemoryProbes = true; diff --git a/src/engine/compiler/MacroAssembler.v3 b/src/engine/compiler/MacroAssembler.v3 index d3868cf1e..7a39cb971 100644 --- a/src/engine/compiler/MacroAssembler.v3 +++ b/src/engine/compiler/MacroAssembler.v3 @@ -21,8 +21,11 @@ class MasmLabel(create_pos: int) { class MacroAssembler(valuerep: Tagging, regConfig: RegConfig) { var unimplemented: void -> void; // function to call for unimplemented bytecodes var trap_labels: Array; // maps TrapReason to a label - var source_locs: Vector<(int, int)>; // list of (offset, source_loc) pairs + var source_locs: Vector<(int, List<(int, int)>)>; // list of (offset, [(fid, pc)]) + var inline_ctx: List<(int, int)>; // list of (fid, pc) var source_loc: int = -1; // current source location, if any + var current_fid: int = -1; // current function id, if any + var newTrapLabel: TrapReason -> MasmLabel; var embeddedRefOffsets: Vector; var offsets = Target.getOffsets(); @@ -80,7 +83,15 @@ class MacroAssembler(valuerep: Tagging, regConfig: RegConfig) { def recordSourceLoc(offset: int) { if (source_loc < 0) return; if (source_locs == null) source_locs = Vector.new(); - source_locs.put(offset, source_loc); + + source_locs.put(offset, List.new((current_fid, source_loc), inline_ctx)); + } + def pushInlineContext(fid: int) { + inline_ctx = List.new((fid, source_loc), inline_ctx); + } + def popInlineContext() { + if (inline_ctx != null) // need more specific than null? + inline_ctx = inline_ctx.tail; } def at(src: int) -> this { source_loc = src; @@ -336,6 +347,7 @@ class MacroAssembler(valuerep: Tagging, regConfig: RegConfig) { def emit_call_runtime_Probe_instr(); def emit_call_runtime_getFrameAccessorMetaRef(); def emit_increment_CountProbe(tmp: Reg, probe: CountProbe, increment: u64); + def emit_inc_metric(metric: Metric); def emit_call_OperandProbe_i_v_fire(probe: OperandProbe_i_v, value_reg: Reg); def emit_call_MemoryReadProbe_fire(probe: MemoryReadProbe); def emit_call_runtime_cast(); diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index ee0cb4765..765dd3b3a 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -1,6 +1,11 @@ // Copyright 2022 Ben L. Titzer. All rights reserved. // See LICENSE for details of Apache 2.0 license. +// Inlining TODO +// - whamm, write tests to explicitly check inlining +// - pre-bump rsp +// - compilation hints proposal + // Describes the register and frame configuration for the single-pass compiler. class SpcExecEnv { // Frame information. @@ -94,7 +99,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl // Other state def trap_labels = Vector<(TrapReason, MasmLabel, Array)>.new(); - var it = BytecodeIterator.new(); + def it = BytecodeIterator.new(); // Frame state (refers to the fields in the top SpcFrame in SpcState) var module: Module; @@ -112,8 +117,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl var ret_label: MasmLabel; var last_probe = 0; var skip_to_end: bool; - // this is Whamm probe inlining, not arbitrary function inlining (yet) - var is_inlined = false; + var whamm_config: WhammInlineConfig; var whamm_probe_ctl_base: u31; // ctl_stack.top when Whamm probe compilation started // XXX: hack var handler_dest_info = Vector.new(); @@ -190,6 +194,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl if (Trace.compiler) traceOpcodeAndStack(false); last_probe = 0; masm.source_loc = it.pc; + masm.current_fid = func.func_index; it.dispatch(this); unrefRegs(); if (Trace.compiler && Trace.asm) { @@ -212,10 +217,12 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl masm.bindLabel(label); + // If trap occurred in inlined function, reconstruct frames if (frames.length > 1) { - // no inlining yet: this should never happen - System.error("SpcError", "attempt to emit trap in inlined context"); + unrefRegs(); + emitReconstructStackFrames(frames); } else { + // otherwise, put pc as before masm.emit_mov_m_i(xenv.pc_slot, label.create_pos); } masm.emit_jump_to_trap_at(reason); @@ -398,7 +405,22 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl if (last_probe == 0) return; var probe = Instrumentation.getLocalProbe(module, func.func_index, last_probe); last_probe = 0; + + // Reconstruct inlined frames before emitting probe (if needed) + var reconstructed_space = 0; + if (isInlined()) { + var frames = snapshotFrames(); + unrefRegs(); + reconstructed_space = emitReconstructStackFrames(frames); + } + emitProbe0(it.pc, probe); + + // Clean up reconstructed frames after the probe returns + if (reconstructed_space > 0) { + masm.emit_addw_r_i(regs.sp, reconstructed_space); + } + if (Trace.compiler) traceOpcodeAndStack(true); } def emitProbe0(pc: int, probe: Probe) { @@ -481,42 +503,191 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl if (!spillMode.free_regs) state.emitRestoreAll(resolver); } + // Emit code for an inlined regular function call + def emitInlinedCall(callee_func: FuncDecl, whamm: WhammProbe) { + var sig = callee_func.sig; + var params_count = u32.view(sig.params.length); + var results_count = u32.view(sig.results.length); + var orig_sp = state.sp; + + // Arguments are already on stack + // Stack: [..., arg0, arg1, ..., argN] <- sp + // We want callee's local 0 = arg0, so: + var new_local_base_sp: u31 = u31.view(orig_sp - params_count); + var new_ctl_base_sp = u31.view(state.ctl_stack.top); + + var num_locals = callee_func.num_slots(); + + // Push an implicit block for the head of the function + var end_label = masm.newLabel(callee_func.cur_bytecode.length); + state.pushBlock(sig.params, sig.results, end_label); + + var m: Module = module; + + // Whamm probe configuration + if (whamm != null) { + def whamm_sig = whamm.sig; + def whamm_wf = WasmFunction.!(whamm.func); + def whamm_instance = whamm_wf.instance; + def whamm_func_decl = whamm_wf.decl; + + m = whamm_instance.module; + new_local_base_sp = u31.view(state.sp) - u31.view(whamm_sig.length); // XXX + } + + // Create and push frame for inlined function + var callee_frame = SpcFrame.new(callee_func, + m, new_local_base_sp, new_ctl_base_sp, num_locals, 0); + + pushSpcFrame(callee_frame); + + // Emit function entry probe, if any. + // XXX expensive because frame materialization required + if (whamm == null && !FeatureDisable.entryProbes && func.entry_probed) { + var probe = Instrumentation.getLocalProbe(module, callee_func.func_index, 0); + + // Reconstruct inlined frames before emitting probe + var reconstructed_space = 0; + if (isInlined()) { + var frames = snapshotFrames(); + unrefRegs(); + reconstructed_space = emitReconstructStackFrames(frames); + } + emitProbe0(0, probe); + // Clean up reconstructed frames after the call returns + if (reconstructed_space > 0) { + masm.emit_addw_r_i(regs.sp, reconstructed_space); + } + } + + // Allocate callee's non-parameter locals + it.dispatchLocalDecls(this); + + // Compile callee's bytecode + if (Trace.compiler) Trace.OUT.puts(" Start inlined function body").ln(); + while (it.more() && success) { + if (Trace.compiler) traceOpcodeAndStack(false); + last_probe = 0; + masm.source_loc = it.pc; + masm.current_fid = func.func_index; + it.dispatch(this); + if (Trace.compiler && Trace.asm) { + OUT.puts("JIT code: "); + masm.printCodeBytes(OUT, codegen_offset, masm.curCodeBytes()); + codegen_offset = masm.curCodeBytes(); + OUT.ln(); + } + unrefRegs(); + if (Debug.compiler) checkRegAlloc(); + it.next(); + if (skip_to_end) doSkipToEndOfBlock(); + } + if (Trace.compiler) Trace.OUT.puts(" End inlined function body").ln(); + + // Check if the inlined function is unreachable (e.g., ended with UNREACHABLE, RETURN, THROW) + var inlined_reachable = state.ctl_stack.peek().reachable; + + // Restore caller context by popping frame + popSpcFrame(); // Automatically restores cached fields + + // Note: Control stack cleanup (popping implicit BLOCK) is handled by visit_END + + // If inlined function is unreachable, no results to clean up + if (!inlined_reachable) { + if (Trace.compiler) { + Trace.OUT.puts(" Inlined function unreachable, skipping result cleanup").ln(); + Trace.OUT.put3(" state.sp=%d, new_local_base_sp=%d, callee_slots=%d", + state.sp, new_local_base_sp, state.sp - new_local_base_sp).ln(); + } + // Drop all callee state (params + locals, no results) + var callee_slots = state.sp - new_local_base_sp; + if (callee_slots > 0) dropN(u32.view(callee_slots)); + if (Trace.compiler) Trace.OUT.put1(" After dropN: state.sp=%d", state.sp).ln(); + setUnreachable(); + return; + } + + // Clean up stack: + // Before: [..., arg0, arg1, ..., argN, local0, local1, ..., localM, result0, ..., resultK] + // After: [..., result0, ..., resultK] + + var total_callee_slots = state.sp - new_local_base_sp; // All callee state + var slots_to_drop = total_callee_slots - results_count; + + // for whamm probes, results_count SHOULD be zero + if (slots_to_drop > 0 && results_count > 0) { + // Need to move results down over parameters and locals + for (i < results_count) { + var result_slot = state.sp - results_count + u32.view(i); + var target_slot = new_local_base_sp + u32.view(i); + if (Trace.compiler) { + Trace.OUT.put3(" Moving result %d: slot %d -> slot %d", i, result_slot, target_slot).ln(); + } + if (result_slot != target_slot) { + var rv = state.state[result_slot]; + if (Trace.compiler) { + Trace.OUT.put2(" rv: flags=%x, const=%d", rv.flags, rv.const).ln(); + } + if (rv.inReg()) { + regAlloc.reassign(rv.reg, int.!(result_slot), int.!(target_slot)); + } else { + // Move in memory (rarely needed if results are in regs) + resolver.addMove((target_slot, rv), (result_slot, rv)); + } + state.state[target_slot] = rv; + } else { + // Result already in the right place + if (Trace.compiler) Trace.OUT.puts(" (already in place)").ln(); + } + } + resolver.emitMoves(); + + // Drop everything above results + for (slot = new_local_base_sp + results_count; slot < state.sp; slot++) { + unrefSlot(slot); + } + state.sp = new_local_base_sp + results_count; + } else if (slots_to_drop > 0) { + // No results, just drop everything + if (Trace.compiler) Trace.OUT.put1("dropping %d slots\n", slots_to_drop); + dropN(u32.view(slots_to_drop)); + } + // If slots_to_drop <= 0, results are already in the right place + + if (Trace.compiler) { + Trace.OUT.put1(" Inlined call complete, sp=%d", state.sp).ln(); + } + } + // saves the overhead of using a runtime call by directly invoking the wasm function associated with the whamm probe def emitWhammProbe(probe: WhammProbe) { + if (Trace.compiler) Trace.OUT.puts("emitting whamm probe\n"); // set up args and push to frame slots. var whamm_sig = probe.sig; - var inline_config = InlineConfig(false, false, false); - var new_local_base_sp = 0; var orig_sp = state.sp; var callee_func = WasmFunction.!(probe.func); + def inline_decision = shouldInline(this, callee_func.decl) && SpcTuning.inlineWhammProbes; // TODO move to shouldInline + var swap_instance = false; + var swap_membase = false; - if (SpcTuning.inlineWhammProbes) { - inline_config = InlineConfig(probe.spc_swap_membase, probe.spc_swap_instance, probe.spc_inline_func); - if (!probe.inline_heuristic_checked) { - inline_config = funcCanInline(callee_func.decl); - probe.inline_heuristic_checked = true; - probe.spc_swap_instance = inline_config.swap_instance; - probe.spc_swap_membase = inline_config.swap_membase; - probe.spc_inline_func = inline_config.can_inline; - } + if (inline_decision) { + probe.checkSwap(); + swap_instance = probe.swap_instance; + swap_membase = probe.swap_membase; - if (inline_config.swap_instance) { // push whamm instance onto abstract stack directly + if (swap_instance) { masm.emit_mov_r_Instance(regs.scratch, callee_func.instance); masm.emit_mov_m_r(ValueKind.REF, frame.inlined_instance_slot, regs.scratch); } - - // overwrite mem0_base with whamm instance's memory base, restore from frame slot later - if (inline_config.swap_membase) { - var membase = callee_func.instance.memories[0].getMemBase64(); - masm.emit_mov_r_l(regs.mem0_base, i64.view(membase)); + if (swap_membase) { + if (callee_func.instance.memories.length > 0) { + var membase = callee_func.instance.memories[0].getMemBase64(); + masm.emit_mov_r_l(regs.mem0_base, i64.view(membase)); + } masm.emit_mov_m_r(ValueKind.REF, frame.inlined_mem0_base_slot, regs.mem0_base); } - } - - if (!inline_config.can_inline) { - state.emitSaveAll(resolver, probeSpillMode); } else { - new_local_base_sp = int.view(state.sp); + state.emitSaveAll(resolver, probeSpillMode); } for (i < whamm_sig.length) { @@ -525,13 +696,13 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl var kind: byte; match(whamm_sig[i]) { FrameAccessor => { - if (inline_config.can_inline) state.emitSaveAll(resolver, probeSpillMode); // spill entire value stack. + if (inline_decision) state.emitSaveAll(resolver, probeSpillMode); // spill entire value stack. masm.emit_call_runtime_getFrameAccessorMetaRef(); emit_reload_regs(); - if (inline_config.can_inline && !probeSpillMode.free_regs) state.emitRestoreAll(resolver); + if (inline_decision && !probeSpillMode.free_regs) state.emitRestoreAll(resolver); // move result to mem slot or reg, depending on inlining - if (inline_config.can_inline) { + if (inline_decision) { var reg = allocRegTos(ValueKind.REF); masm.emit_mov_r_r(ValueKind.REF, reg, xenv.runtime_ret0); state.push(KIND_REF | IN_REG, reg, 0); @@ -543,7 +714,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl Val(val) => { match (val) { I31(v) => { - if (inline_config.can_inline) { + if (inline_decision) { var reg = allocRegTos(ValueKind.REF); masm.emit_mov_r_i(reg, i32.view(v) << 1); state.push(KIND_REF | IN_REG, reg, 0); @@ -553,7 +724,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl kind = ValueKind.REF.code; } I32(v) => { - if (inline_config.can_inline) { + if (inline_decision) { state.push(KIND_I32 | IS_CONST, NO_REG, i32.view(v)); } else { masm.emit_mov_m_d(slot_addr, v); @@ -561,7 +732,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl kind = ValueKind.I32.code; } I64(v) => { - if (inline_config.can_inline) { + if (inline_decision) { var reg = allocRegTos(ValueKind.I64); masm.emit_mov_r_l(reg, i64.view(v)); state.push(KIND_I64 | IN_REG, reg, 0); @@ -571,7 +742,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl kind = ValueKind.I64.code; } F32(v) => { - if (inline_config.can_inline) { + if (inline_decision) { var reg = allocRegTos(ValueKind.F32); masm.emit_mov_r_f32(reg, v); state.push(KIND_F32 | IN_REG, reg, 0); @@ -581,7 +752,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl kind = ValueKind.F32.code; } F64(v) => { - if (inline_config.can_inline) { + if (inline_decision) { var reg = allocRegTos(ValueKind.F64); masm.emit_mov_r_d64(reg, v); state.push(KIND_F64 | IN_REG, reg, 0); @@ -591,7 +762,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl kind = ValueKind.F64.code; } V128(l, h) => { - if (inline_config.can_inline) { + if (inline_decision) { var reg = allocRegTos(ValueKind.V128); masm.emit_mov_r_q(reg, l, h); state.push(KIND_V128 | IN_REG, reg, 0); @@ -602,7 +773,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl kind = ValueKind.V128.code; } Ref(v) => { - if (inline_config.can_inline) { + if (inline_decision) { var reg = allocRegTos(ValueKind.REF); masm.emit_mov_r_Object(reg, v); state.push(KIND_REF | IN_REG, reg, 0); @@ -613,7 +784,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl kind = ValueKind.REF.code; } Cont(v) => { - if (inline_config.can_inline) { + if (inline_decision) { var reg = allocRegTos(ValueKind.REF_U64); masm.emit_mov_r_Cont(reg, v); state.push(KIND_REF_U64 | IN_REG, reg, 0); @@ -628,15 +799,15 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl } Operand(_, i) => { var index = orig_sp + u32.view(i) - 1; - if (inline_config.can_inline) { - visit_LOCAL_GET(u31.view(index)); + if (inline_decision) { + visit_LOCAL_GET(u31.view(index - local_base_sp)); } else { masm.emit_mov_m_m(state.state[index].kind(), slot_addr, masm.slotAddr(index)); } kind = state.state[index].kind().code; } Local(_, i) => { - if (inline_config.can_inline) { + if (inline_decision) { visit_LOCAL_GET(u31.view(i)); } else { masm.emit_mov_m_m(state.state[u31.view(i)].kind(), slot_addr, masm.slotAddr(u32.view(i))); @@ -645,7 +816,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl } Null => System.error("whamm", "null whamm arg!"); } - if (!inline_config.can_inline) { + if (!inline_decision) { masm.emit_mov_m_i(slot_tag_addr, kind); } } @@ -653,49 +824,14 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl var func_id = callee_func.decl.func_index; var whamm_module = whamm_instance.module; var whamm_func_decl = callee_func.decl; - if (inline_config.can_inline) { - var prev_it = it; - it = BytecodeIterator.new().reset(whamm_func_decl); - var orig_module = module; - - // prepare spc for inlining - this.local_base_sp = u31.view(new_local_base_sp); - this.module = whamm_module; - this.func = whamm_func_decl; - this.sig = whamm_func_decl.sig; - - // inline codegen - it.dispatchLocalDecls(this); - this.is_inlined = true; - if (Trace.compiler) Trace.OUT.puts("Start compiling inlined whamm probe").ln(); - while (it.more() && success) { - if (Trace.compiler) traceOpcodeAndStack(false); - last_probe = 0; - masm.source_loc = it.pc; - it.dispatch(this); - if (Trace.compiler && Trace.asm) { - OUT.puts("JIT code: "); - masm.printCodeBytes(OUT, codegen_offset, masm.curCodeBytes()); - codegen_offset = masm.curCodeBytes(); - OUT.ln(); - } - unrefRegs(); - if (Debug.compiler) checkRegAlloc(); - it.next(); + if (inline_decision) { + whamm_config = WhammInlineConfig(swap_membase, swap_instance, true); + emitInlinedCall(whamm_func_decl, probe); + whamm_config = WhammInlineConfig(false, false, false); + // Restore mem0_base after probe + if (module.memories.length > 0) { + masm.emit_mov_r_m(ValueKind.REF, regs.mem0_base, frame.mem0_base_slot); } - if (Trace.compiler) Trace.OUT.puts("Finished compiling inlined whamm probe").ln(); - - // restore spc after inlining - it = prev_it; - this.local_base_sp = 0; - this.is_inlined = false; - this.module = orig_module; - this.func = it.func; - this.sig = it.func.sig; - masm.emit_mov_r_m(ValueKind.REF, regs.mem0_base, frame.mem0_base_slot); - - // clear callee params/locals from abstract state - dropN(state.sp - orig_sp); } else { var vsp_reg = allocTmpFixed(ValueKind.REF, regs.vsp); var func_reg = allocTmpFixed(ValueKind.REF, regs.func_arg); @@ -738,7 +874,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl state.prepareLoop(resolver); masm.bindLabel(ctl_top.label); emitProbe(); - if (it.pc == osr_pc) { + if (it.pc == osr_pc && !isInlined()) { osr_state = state.ctl_stack.peek().copyMerge(); osr_loop_label = masm.newLabel(it.pc); masm.bindLabel(osr_loop_label); @@ -791,37 +927,38 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl setUnreachable(); } def visit_END() { - if (!this.is_inlined) { - var ctl_top = state.ctl_stack.peek(); - if (ctl_top.opcode == Opcode.LOOP.code) { - state.ctl_stack.pop(); - if (!ctl_top.reachable) setUnreachable(); - } else if (ctl_top.opcode == Opcode.IF.code) { - // simulate empty if-true block - state.emitFallthru(resolver); - masm.emit_br(ctl_top.label); - masm.bindLabel(ctl_top.else_label); - state.doElse(); - ctl_top.opcode = Opcode.ELSE.code; - state.emitFallthru(resolver); - masm.bindLabel(ctl_top.label); - state.resetToMerge(ctl_top); - state.ctl_stack.pop(); - } else if (ctl_top.opcode == Opcode.BLOCK.code || ctl_top.opcode == Opcode.ELSE.code) { - state.emitFallthru(resolver); - masm.bindLabel(ctl_top.label); - state.resetToMerge(ctl_top); - state.ctl_stack.pop(); - } else if (ctl_top.opcode == Opcode.RETURN.code) { - state.emitFallthru(resolver); - masm.bindLabel(ctl_top.label); - state.resetToMerge(ctl_top); - emitProbe(); - if (ctl_top.merge_count > 1) emitReturn(ctl_top); - state.ctl_stack.pop(); - } + var frame = state.frame_stack.peek(); + var is_implicit_function_block = isInlined() && state.ctl_stack.top == frame.ctl_base_sp + 1; + + var ctl_top = state.ctl_stack.peek(); + if (ctl_top.opcode == Opcode.LOOP.code) { + state.ctl_stack.pop(); + if (!ctl_top.reachable) setUnreachable(); + } else if (ctl_top.opcode == Opcode.IF.code) { + // simulate empty if-true block + state.emitFallthru(resolver); + masm.emit_br(ctl_top.label); + masm.bindLabel(ctl_top.else_label); + state.doElse(); + ctl_top.opcode = Opcode.ELSE.code; + state.emitFallthru(resolver); + masm.bindLabel(ctl_top.label); + state.resetToMerge(ctl_top); + state.ctl_stack.pop(); + } else if (ctl_top.opcode == Opcode.BLOCK.code || ctl_top.opcode == Opcode.ELSE.code) { + state.emitFallthru(resolver); + masm.bindLabel(ctl_top.label); + state.resetToMerge(ctl_top); + state.ctl_stack.pop(); + } else if (ctl_top.opcode == Opcode.RETURN.code) { + state.emitFallthru(resolver); + masm.bindLabel(ctl_top.label); + state.resetToMerge(ctl_top); emitProbe(); + if (ctl_top.merge_count > 1) emitReturn(ctl_top); + state.ctl_stack.pop(); } + emitProbe(); } def visit_BR(depth: u31) { var target = state.getControl(depth); @@ -858,6 +995,29 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl } def visitCallDirect(op: Opcode, index: u31, tailCall: bool) { var func = module.functions[index]; + if (op == Opcode.CALL) Metrics.spc_static_calls.val++; + + // Try inlining for intra-module, non-tail calls + if (!tailCall && shouldInline(this, func)) { + if (Trace.compiler) Trace.OUT.put2("Inlining call to func #%d (%d bytes)", index, func.orig_bytecode.length).ln(); + if (op == Opcode.CALL) { + Metrics.spc_static_inlined_calls.val++; + masm.emit_inc_metric(Metrics.spc_dynamic_inlined_calls); + masm.emit_inc_metric(Metrics.spc_dynamic_calls); + } + emitInlinedCall(func, null); + return; + } + if (op == Opcode.CALL) masm.emit_inc_metric(Metrics.spc_dynamic_calls); + // Reconstruct inlined frames before the call, skip whamm probes + var reconstructed_space = 0; + if (isInlined() && !whamm_config.is_inlined) { + var frames = snapshotFrames(); + unrefRegs(); + reconstructed_space = emitReconstructStackFrames(frames); + } + + // Existing non-inlined call path var retpt = masm.newLabel(it.pc), wasmcall_label = masm.newLabel(it.pc); // Load the instance (which must happen before frame is unwound). var vsp_reg = allocTmpFixed(ValueKind.REF, regs.vsp); @@ -870,6 +1030,12 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl masm.emit_v3_Array_elem_r_ri(ValueKind.REF, func_reg, func_reg, func.func_index); emitCallToReg(func.sig, func_reg, vsp_reg, tmp, func.imp != null, tailCall); + + // Clean up reconstructed frames after the call returns + if (reconstructed_space > 0) { + masm.emit_addw_r_i(regs.sp, reconstructed_space); + } + } def emitCallToReg(sig: SigDecl, func_reg: Reg, vsp_reg: Reg, tmp: Reg, checkHostCall: bool, tailCall: bool) { var retpt = masm.newLabel(it.pc), wasmcall_label = masm.newLabel(it.pc); @@ -877,6 +1043,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl if (tailCall) emitMoveTailCallArgs(sig); // transfer tail call args else state.emitSaveAll(resolver, SpillMode.SAVE_AND_FREE_REGS); // spill entire value stack + // Compute the value stack pointer. emit_compute_vsp(vsp_reg, state.sp); if (checkHostCall) { @@ -899,8 +1066,10 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl masm.emit_jump_r(tmp); setUnreachable(); } else { + masm.emit_call_r(tmp); masm.bindLabel(retpt); + emit_reload_regs(); state.popArgsAndPushResults(sig); } @@ -1934,12 +2103,21 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl state.emitSaveAll(resolver, runtimeSpillMode); emit_compute_vsp(regs.vsp, state.sp); masm.emit_store_curstack_vsp(regs.vsp); + // Reconstruct stack frames across runtime calls that might (Wasm-level) trap. + // XXX expensive operation: + // - either SPC needs to be refactored so that runtime calls can be avoided, or + // - do a lazy reconstruction only if it traps (where?) + var inlined_space = 0; + if (canTrap && isInlined()) + inlined_space = emitReconstructStackFrames(snapshotFrames()); masm.emit_get_curstack(regs.runtime_arg0); masm.emit_v3_set_X86_64Stack_rsp_r_r(regs.runtime_arg0, regs.sp); masm.emit_push_X86_64Stack_rsp_r_r(regs.runtime_arg0); emit_load_instance(regs.runtime_arg1); masm.emit_mov_r_i(regs.runtime_arg2, arg1); masm.emit_call_runtime_op(op); + if (inlined_space > 0) + masm.emit_addw_r_i(regs.sp, inlined_space); masm.emit_get_curstack(regs.scratch); masm.emit_pop_X86_64Stack_rsp_r_r(regs.scratch); dropN(args); @@ -1951,6 +2129,10 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl state.emitSaveAll(resolver, runtimeSpillMode); emit_compute_vsp(regs.vsp, state.sp); masm.emit_store_curstack_vsp(regs.vsp); + // Reconstruct stack frames across runtime calls that might (Wasm-level) trap. + var inlined_space = 0; + if (canTrap && isInlined()) + inlined_space = emitReconstructStackFrames(snapshotFrames()); masm.emit_get_curstack(regs.runtime_arg0); masm.emit_v3_set_X86_64Stack_rsp_r_r(regs.runtime_arg0, regs.sp); masm.emit_push_X86_64Stack_rsp_r_r(regs.runtime_arg0); @@ -1958,6 +2140,8 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl masm.emit_mov_r_i(regs.runtime_arg2, arg1); masm.emit_mov_r_i(regs.runtime_arg3, arg2); masm.emit_call_runtime_op(op); + if (inlined_space > 0) + masm.emit_addw_r_i(regs.sp, inlined_space); masm.emit_get_curstack(regs.scratch); masm.emit_pop_X86_64Stack_rsp_r_r(regs.scratch); dropN(args); @@ -2075,8 +2259,90 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl masm.emit_addw_r_i(regs.sp, frame.frameSize); masm.emit_ret(); } + def getTrapStubIp(reason: TrapReason) -> long; + def getSpcInlinedFrameIp() -> long; + // Emit code to materialize stack frames for each inlined function. + // The frames array is in the same order as frame_stack: outermost first, innermost last. + def emitReconstructStackFrames(frames: Array) -> int { + Metrics.spc_static_remat.val++; + masm.emit_inc_metric(Metrics.spc_dynamic_remat); + def real_frame = frames[0]; + masm.emit_mov_m_i(xenv.pc_slot, real_frame.pc); + + // Use inlined frame stub IP as return address for all reconstructed frames + var return_addr = getSpcInlinedFrameIp(); + var total_space = 0; + + // load instance + var inst_reg = allocTmp(ValueKind.REF); + //emit_load_instance(inst_reg); + masm.emit_mov_r_m(ValueKind.REF, inst_reg, frame.instance_slot); + var mem_reg = allocTmp(ValueKind.REF); + masm.emit_mov_r_m(ValueKind.REF, mem_reg, frame.mem0_base_slot); + // Load instance.functions + def func_reg = allocTmp(ValueKind.REF); + masm.emit_v3_Instance_functions_r_r(func_reg, inst_reg); + // use same vfp for all frames + def vfp_reg = allocTmp(ValueKind.REF); + masm.emit_mov_r_m(ValueKind.REF, vfp_reg, frame.vfp_slot); + var wasm_func_reg = allocTmp(ValueKind.REF); + + var inl_inst_reg: Reg, inl_mem0_reg: Reg; + if (whamm_config.is_inlined) { + inl_inst_reg = allocTmp(ValueKind.REF); + inl_mem0_reg = allocTmp(ValueKind.REF); + masm.emit_mov_r_m(ValueKind.REF, inl_inst_reg, frame.inlined_instance_slot); + masm.emit_mov_r_m(ValueKind.REF, inl_mem0_reg, frame.inlined_mem0_base_slot); + } + + // Process the inlined frames (skip the outermost which already exists on native stack) + for (i = 1; i < frames.length; i++) { + var frame_info = frames[i]; + + // Push inlined frame stub IP as return address + masm.emit_subw_r_i(regs.sp, 8); + masm.emit_mov_m_l(MasmAddr(regs.sp, 0), return_addr); + total_space += 8; + + // Allocate concrete stack frame for inlined function + masm.emit_subw_r_i(regs.sp, frame.frameSize); + total_space += frame.frameSize; + + // get functions[func_index] and save into frame + masm.emit_v3_Array_elem_r_ri(ValueKind.REF, wasm_func_reg, func_reg, frame_info.func.func_index); + masm.emit_mov_m_r(ValueKind.REF, frame.wasm_func_slot, wasm_func_reg); + + // Save instance to frame.instance_slot + masm.emit_mov_m_r(ValueKind.REF, frame.instance_slot, inst_reg); + + // Save mem0 base + masm.emit_mov_m_r(ValueKind.REF, frame.mem0_base_slot, mem_reg); + + // use same vfp for all frames + // TODO different vfps? + masm.emit_mov_m_r(ValueKind.REF, frame.vfp_slot, vfp_reg); + + // Save PC to frame.pc_slot + masm.emit_mov_m_i(frame.pc_slot, frame_info.pc); // exact pc of each frame + + // Clear FrameAccessor and inlined_instance_slot + masm.emit_mov_m_l(frame.accessor_slot, 0); + + // if an inlined whamm probe, also grab inlined slots + if (whamm_config.is_inlined) { + masm.emit_mov_m_r(ValueKind.REF, frame.inlined_instance_slot, inl_inst_reg); + masm.emit_mov_m_r(ValueKind.REF, frame.inlined_mem0_base_slot, inl_mem0_reg); + } else { + masm.emit_mov_m_l(frame.inlined_instance_slot, 0); + masm.emit_mov_m_l(frame.inlined_mem0_base_slot, 0); + } + } + + return total_space; + } def newTrapLabel(reason: TrapReason) -> MasmLabel { var label = masm.newLabel(it.pc); + // Snapshot frame_stack for trap reconstruction var frames = snapshotFrames(); trap_labels.put((reason, label, frames)); return label; @@ -2175,7 +2441,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl // XXX: recompute VFP from VSP - #slots? masm.emit_mov_r_m(ValueKind.REF, regs.vfp, frame.vfp_slot); if (module.memories.length > 0) { - if (is_inlined) { + if (whamm_config.swap_membase) { masm.emit_mov_r_m(ValueKind.REF, regs.mem0_base, frame.inlined_mem0_base_slot); } else { masm.emit_mov_r_m(ValueKind.REF, regs.mem0_base, frame.mem0_base_slot); @@ -2183,7 +2449,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl } } def emit_load_instance(reg: Reg) { - if (is_inlined) { // inline compilation + if (whamm_config.swap_instance) { masm.emit_mov_r_m(ValueKind.REF, reg, frame.inlined_instance_slot); } else { masm.emit_mov_r_m(ValueKind.REF, reg, frame.instance_slot); @@ -2508,6 +2774,9 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl // frame stack (for inlining) operations //==================================================================== def pushSpcFrame(frame: SpcFrame) { + if (func != null) + masm.pushInlineContext(func.func_index); + def current = state.frame_stack.peek(); if (current != null) current.pc = it.pc; @@ -2522,6 +2791,8 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl } // inlining is not supported, so popping is not either def popSpcFrame() -> SpcFrame { + masm.popInlineContext(); + var frame = state.frame_stack.pop(); // Restore cached copies from new top frame var current = state.frame_stack.peek(); @@ -2658,6 +2929,20 @@ type SpcVal(flags: byte, reg: Reg, const: int) #unboxed { } } +// A frame in the compilation frame stack (for inlining). +// TODO keep track of which instance state is cached? (cache immutable things, globals) +// - clear cache on snapshot +class SpcFrame { + var func: FuncDecl; + var module: Module; + var local_base_sp: u31; // Base index into SpcState.state + var ctl_base_sp: u31; // Base index into SpcState.ctl_stack + var num_locals: int; + var pc: int; // XXX pc only initialized during snapshots + + new(func, module, local_base_sp, ctl_base_sp, num_locals, pc) {} +} + // An entry in the abstract control stack. class SpcControl { var opcode: u16; @@ -2693,19 +2978,7 @@ class SpcControl { def isNotZero = int.!=(0, _); def trueToOne(z: bool) -> int { return if(z, 1, 0); } -// Contains both the abstract control and abstract value stack. -// Represents the compiler state for one function frame in the inlining stack. -class SpcFrame { - var func: FuncDecl; - var module: Module; - var local_base_sp: u31; // Base index into SpcState.state - var ctl_base_sp: u31; // Base index into SpcState.ctl_stack - var num_locals: int; - var pc: int; - - new(func, module, local_base_sp, ctl_base_sp, num_locals, pc) {} -} - +// Contains both the abstract control, value, and frame stack. class SpcState(regAlloc: RegAlloc) { // Abstract state of the value stack (shared across frames) var state = Array.new(INITIAL_VALUE_STACK_SIZE); @@ -3255,38 +3528,52 @@ class MoveNode { var dstNext: MoveNode; // next in a list of successors } -// checks function bytecode to see if it can be inlined based on -// simple heuristics: length <= maxInlineBytecodeSize and straightline code. -def funcCanInline(decl: FuncDecl) -> InlineConfig { - var default = InlineConfig(false, false, false); - if (decl.orig_bytecode.length > SpcTuning.maxInlineBytecodeSize || decl.sig.params.length > SpcTuning.maxInlineParams) return default; - var bi = BytecodeIterator.new().reset(decl); - var swap_instance = false; - var swap_membase = false; +// Determine if a regular function call should be inlined +def shouldInline(spc: SinglePassCompiler, func: FuncDecl) -> bool { + if (Trace.compiler) OUT.put1("deciding on inlining call to func #%d: ", func.func_index); + + if (func.imp != null) { + if (Trace.compiler) OUT.puts("NO (imported)\n"); + return false; + } + if (spc.inlineDepth() >= SpcTuning.maxInlineDepth) { + if (Trace.compiler) OUT.puts("NO (max inline depth exceeded)\n"); + return false; + } + if (func.orig_bytecode.length > SpcTuning.maxInlineBytecodeSize) { + if (Trace.compiler) OUT.puts("NO (too large)\n"); + return false; + } + if (func.sig.params.length > SpcTuning.maxInlineParams) { + if (Trace.compiler) OUT.puts("NO (too many params)\n"); + return false; + } + + // Scan bytecode for unsupported instructions + var bi = BytecodeIterator.new().reset(func); while (bi.more()) { - var op = bi.current(); - match (op) { - // Cannot handle control flow yet. - IF, BR, BR_IF, BR_TABLE, BR_ON_NULL, BR_ON_NON_NULL, BR_ON_CAST, BR_ON_CAST_FAIL, RETURN => return default; - // These opcodes require swapping the instance. - THROW, CALL, CALL_INDIRECT, MEMORY_INIT, MEMORY_SIZE, MEMORY_GROW, MEMORY_COPY, MEMORY_FILL, REF_FUNC, DATA_DROP, - ELEM_DROP, TABLE_INIT, TABLE_SIZE, TABLE_COPY, TABLE_GROW, GLOBAL_SET, GLOBAL_GET, TABLE_SET, TABLE_GET => swap_instance = true; - // Load/store opcodes require either the memory base or the instance. - I32_STORE, I64_STORE, F32_STORE, F64_STORE, I32_STORE8, I32_STORE16, I64_STORE8, I64_STORE16, I64_STORE32, - V128_STORE, I32_LOAD, I64_LOAD, F32_LOAD, F64_LOAD, I32_LOAD8_S, I32_LOAD8_U, I32_LOAD16_S, I32_LOAD16_U, - I64_LOAD8_S, I64_LOAD8_U, I64_LOAD16_S, I64_LOAD16_U, I64_LOAD32_S, I64_LOAD32_U, V128_LOAD => { - var memarg = bi.immptr().read_MemArg(); - if (memarg.memory_index == 0) swap_membase = true; - else swap_instance = true; + match (bi.current()) { + RETURN, RETURN_CALL, RETURN_CALL_INDIRECT, RETURN_CALL_REF => { + if (Trace.compiler) OUT.puts("NO (has return instructions)\n"); + return false; + } + TRY, CATCH, THROW, RETHROW, THROW_REF, DELEGATE, CATCH_ALL, TRY_TABLE => { + if (Trace.compiler) OUT.puts("NO (has exception handling instructions)\n"); + return false; + } + CONT_NEW, CONT_BIND, SUSPEND, RESUME, RESUME_THROW, RESUME_THROW_REF, SWITCH => { + if (Trace.compiler) OUT.puts("NO (has stack switching instructions)\n"); + return false; } _ => ; } bi.next(); } - return InlineConfig(swap_membase, swap_instance, true); -} -type InlineConfig(swap_membase: bool, swap_instance: bool, can_inline: bool); + if (Trace.compiler) OUT.puts("YES\n"); + return true; +} +type WhammInlineConfig(swap_membase: bool, swap_instance: bool, is_inlined: bool); // Used to record the entry point of exception/suspension handlers. Jumping to {stub_label} allows // control transfer to its corresponding handler without falling back to fast-int. diff --git a/src/engine/x86-64/X86_64MacroAssembler.v3 b/src/engine/x86-64/X86_64MacroAssembler.v3 index 181aa9696..835db433e 100644 --- a/src/engine/x86-64/X86_64MacroAssembler.v3 +++ b/src/engine/x86-64/X86_64MacroAssembler.v3 @@ -801,6 +801,11 @@ class X86_64MacroAssembler extends MacroAssembler { def emit_jump_r(reg: Reg) { asm.ijmp_r(G(reg)); } + def emit_inc_metric(metric: Metric) { + if (!metric.enabled) return; + asm.movq_r_l(scratch, Pointer.atField(metric.val) - Pointer.NULL); + asm.q.inc_m(scratch.plus(0)); + } def emit_increment_CountProbe(tmp: Reg, probe: CountProbe, increment: u64) { var r1 = G(tmp); var refOffset = asm.movq_r_p(r1, long.view(Pointer.atObject(probe))); @@ -1700,4 +1705,4 @@ def TRUNC_i32_f64_u = FloatTrunc.new(false, true, false); def TRUNC_i64_f32_s = FloatTrunc.new(true, false, true); def TRUNC_i64_f32_u = FloatTrunc.new(true, false, false); def TRUNC_i64_f64_s = FloatTrunc.new(true, true, true); -def TRUNC_i64_f64_u = FloatTrunc.new(true, true, false); \ No newline at end of file +def TRUNC_i64_f64_u = FloatTrunc.new(true, true, false); diff --git a/src/engine/x86-64/X86_64SinglePassCompiler.v3 b/src/engine/x86-64/X86_64SinglePassCompiler.v3 index f3c6ee02e..e26359845 100644 --- a/src/engine/x86-64/X86_64SinglePassCompiler.v3 +++ b/src/engine/x86-64/X86_64SinglePassCompiler.v3 @@ -34,6 +34,13 @@ class X86_64SinglePassCompiler extends SinglePassCompiler { mmasm.trap_stubs = TRAPS_STUB; } + def getTrapStubIp(reason: TrapReason) -> long { + return mmasm.trap_stubs.getIpForReason(reason) - Pointer.NULL; + } + def getSpcInlinedFrameIp() -> long { + return INLINED_FRAME_STUB.start - Pointer.NULL; + } + private def visitCompareI(asm: X86_64Assembler, cond: X86_64Cond) -> bool { var b = pop(), a = popReg(); if (b.isConst()) asm.cmp_r_i(G(a.reg), b.const); @@ -1133,6 +1140,7 @@ class X86_64SinglePassCompiler extends SinglePassCompiler { } def ucontext_rip_offset = 168; +def ucontext_rsp_offset = 160; def SIGFPE = 8; def SIGBUS = 10; def SIGSEGV = 11; @@ -1185,7 +1193,7 @@ class X86_64SpcCode extends RiUserCode { class X86_64SpcModuleCode extends X86_64SpcCode { def mapping: Mapping; var codeEnd: int; // for dynamically adding code to the end - var sourcePcs: Vector<(int, int)>; + var sourcePcs: Vector<(int, List<(int, int)>)>; var embeddedRefOffsets: Vector; new(mapping) super("spc-module", mapping.range.start, mapping.range.end) { @@ -1229,35 +1237,77 @@ class X86_64SpcModuleCode extends X86_64SpcCode { return false; } // Updates the siginfo's {ucontext} to set the handler %rip and to write the PC of the fault location - // into the stack frame for the handler. + // into the stack frame for the handler, along with any inlined frames at the program location. private def updateUContextToTrapsStub(ucontext: Pointer, reason: TrapReason) { var p_rip = ucontext + ucontext_rip_offset; var p_rsp = RiOs.getSp(ucontext); if (!RiRuntime.inStackRedZone(p_rsp)) { // Update the current PC in the JIT frame, if it is accessible. var ip = p_rip.load(); - var pc = lookupPc(ip, false); - (p_rsp + X86_64InterpreterFrame.curpc.offset).store(pc); + var inline_ctx = lookupPc(ip, false); + if (inline_ctx == null) { + // old case: lookupPc failed (returned -1) + (p_rsp + X86_64InterpreterFrame.curpc.offset).store(-1); + } else if (inline_ctx.tail == null) { + // old case: store pc directly into stack + (p_rsp + X86_64InterpreterFrame.curpc.offset).store(inline_ctx.head.1); + } else { + // new case: reconstruct inlined frames + p_rsp = reconstructInlinedFramesForTrap(p_rsp, inline_ctx); + (ucontext + ucontext_rsp_offset).store(p_rsp); + } } var handler_ip = TRAPS_STUB.getIpForReason(reason); (p_rip).store(handler_ip); } - // Look up the source {pc} of a location {i} in this code. Returns {-1} if no exact entry is found. + // Reconstructs inlined interpreter frames for an inlined hardware trap context. + // Returns the new rsp to write into the ucontext (top of stack). + private def reconstructInlinedFramesForTrap(r_rsp: Pointer, inline_ctx: List<(int, int)>) -> Pointer { + def frames: Array<(int, int)> = Lists.toArray(inline_ctx); + def outer = frames[frames.length - 1]; + def inlined = frames[0 ... (frames.length - 1)]; + def count = inlined.length; + + // set outermost pc in the real frame + (r_rsp + X86_64InterpreterFrame.curpc.offset).store(outer.1); + + // Read instance from the real outer frame (shared across all inlined frames). + var instance = (r_rsp + X86_64InterpreterFrame.instance.offset).load(); + + // Push inlined frames + for (i = count - 1; i >= 0; i--) { + var fid = inlined[i].0; + var pc = inlined[i].1; + + r_rsp += -8; + r_rsp.store(INLINED_FRAME_STUB.start); + + r_rsp += -X86_64InterpreterFrame.size; // move rsp? + // write func, pc, frame accessor + var wasm_func = WasmFunction.!(instance.functions[fid]); + (r_rsp + X86_64InterpreterFrame.wasm_func.offset).store(wasm_func); + (r_rsp + X86_64InterpreterFrame.curpc.offset).store(pc); + (r_rsp + X86_64InterpreterFrame.accessor.offset).store(null); + } + return r_rsp; + } + // Look up the inline context for a location {ip} in this code. Returns {null} if no exact + // entry is found. The returned list head is the innermost (fid, pc), tail leads to outermost caller. // Return addresses are treated differently than other addresses in the code. - def lookupPc(ip: Pointer, isRetAddr: bool) -> int { + def lookupPc(ip: Pointer, isRetAddr: bool) -> List<(int, int)> { if (Trace.compiler) Trace.OUT.put2("SpcCode.lookupPc(0x%x, ret=%z)", (ip - Pointer.NULL), isRetAddr).ln(); - if (sourcePcs == null) return -1; - if (!mapping.range.contains(ip)) return -1; + if (sourcePcs == null) return null; + if (!mapping.range.contains(ip)) return null; var offset = ip - mapping.range.start - if(isRetAddr, 1); // XXX: use binary search for looking up source PCs in SPC code if (Trace.compiler) Trace.OUT.put1(" looking for offset=%d", offset).ln(); for (i < sourcePcs.length) { var entry = sourcePcs[i]; - if (Trace.compiler) Trace.OUT.put2(" (offset=%d, pc=%d)", entry.0, entry.1).ln(); + if (Trace.compiler) Trace.OUT.put1(" (offset=%d, ctx=[...])", entry.0).ln(); // TODO print full context if (offset == entry.0) return entry.1; } - return -1; + return null; } // Appends code to the end of this module. def appendCode(masm: X86_64MacroAssembler) -> Pointer { @@ -1307,6 +1357,13 @@ class X86_64SpcTrapsStub extends X86_64SpcCode { } } +// Marker for reconstructed inlined frames in stack traces. +// Used as the return address for frames materialized during frame reconstruction. +class X86_64SpcInlinedFrame extends X86_64SpcCode { + new() super("inlined-frame", Pointer.NULL, Pointer.NULL) { } +} + + // The lazy-compile stub needs special handling in the Virgil runtime because it has // a frame that stores the function being compiled. class X86_64SpcCompileStub extends RiUserCode { @@ -1348,6 +1405,9 @@ def LAZY_COMPILE_STUB = X86_64PreGenStub.new("spc-lazy-compile", X86_64SpcCompil def TIERUP_COMPILE_STUB = X86_64PreGenStub.new("spc-tierup-compile", X86_64SpcCompileStub.new("tierup"), genTierUpCompileStub); def TRAPS_STUB = X86_64SpcTrapsStub.new(); def TRAPS_PREGEN = X86_64PreGenStub.new("spc-trap", TRAPS_STUB, genTrapsStub); +def INLINED_FRAME_STUB = X86_64SpcInlinedFrame.new(); +def INLINED_FRAME_PREGEN = X86_64PreGenStub.new("spc-inlined-frame", INLINED_FRAME_STUB, genSpcInlinedFrame); + def genSpcEntryFunc(ic: X86_64InterpreterCode, w: DataWriter) { if (SpcTuning.disable) return; @@ -1452,6 +1512,10 @@ def genTrapsStub(ic: X86_64InterpreterCode, w: DataWriter) { w.skipN(skip); } } +def genSpcInlinedFrame(ic: X86_64InterpreterCode, w: DataWriter) { + var masm = X86_64MacroAssembler.new(w, X86_64MasmRegs.CONFIG); + masm.emit_intentional_crash(); // do not execute this +} def codePointer(f: P -> R) -> Pointer { return CiRuntime.unpackClosure(f).0; } @@ -1478,7 +1542,10 @@ component X86_64Spc { return addr; } def estimateCodeSizeFor(decl: FuncDecl) -> int { - return 60 + decl.orig_bytecode.length * 20; // TODO: huge overestimate + var bc = decl.orig_bytecode.length; + var size = 60 + bc * 20; + if (SpcTuning.maxInlineDepth > 0) size = size << byte.view(SpcTuning.maxInlineDepth + 1); + return size; } private def lazyCompile(wf: WasmFunction) -> (WasmFunction, Pointer, Throwable) { // The global stub simply consults the execution strategy. diff --git a/src/engine/x86-64/X86_64Stack.v3 b/src/engine/x86-64/X86_64Stack.v3 index a47b8665a..dacb2687a 100644 --- a/src/engine/x86-64/X86_64Stack.v3 +++ b/src/engine/x86-64/X86_64Stack.v3 @@ -145,6 +145,7 @@ class X86_64Stack extends WasmStack { x: X86_64InterpreterCode => if (f != null && !f(retip, code, pos, param)) return (true, pos); x: X86_64SpcModuleCode => if (f != null && !f(retip, code, pos, param)) return (true, pos); x: X86_64SpcTrapsStub => if (f != null && !f(retip, code, pos, param)) return (true, pos); + x: X86_64SpcInlinedFrame => if (f != null && !f(retip, code, pos, param)) return (true, pos); x: X86_64ReturnParentStub => { if (stack.parent == null || !continue_to_parent) { if (Trace.stack && Debug.stack) Trace.OUT.puts("walk finished").ln(); @@ -954,9 +955,14 @@ class X86_64FrameAccessor(stack: X86_64Stack, sp: Pointer, decl: FuncDecl) exten var ip = readIp(); var code = RiRuntime.findUserCode(ip); match (code) { - x: X86_64SpcModuleCode => cached_pc = x.lookupPc(ip, true); + x: X86_64SpcModuleCode => { + def chain = x.lookupPc(ip, true); + cached_pc = if(chain != null, chain.head.1, -1); + } x: X86_64InterpreterCode => cached_pc = X86_64Interpreter.computePCFromFrame(sp); x: X86_64SpcTrapsStub => cached_pc = (sp + X86_64InterpreterFrame.curpc.offset).load(); + x: X86_64SpcInlinedFrame => cached_pc = (sp + X86_64InterpreterFrame.curpc.offset).load(); + // An inlined frame reads the PC from the reconstructed frame, while regular code looks it up. _ => cached_pc = -1; } return cached_pc; @@ -982,6 +988,9 @@ class X86_64FrameAccessor(stack: X86_64Stack, sp: Pointer, decl: FuncDecl) exten match (code) { x: X86_64InterpreterCode => ; x: X86_64SpcCode => ; + x: X86_64SpcInlinedFrame => ; + // if quantity of inline frame is ever held in the frame, we can use that + // to skip some of the depth-searching process _ => return depth; } depth++; @@ -1069,6 +1078,8 @@ class X86_64FrameAccessor(stack: X86_64Stack, sp: Pointer, decl: FuncDecl) exten return X86_64SpcCode.?(code); } + // XXX inlined frames may be unwound without the function actually returning, + // i.e. shrinkwrapping around out-calls private def checkNotUnwound() { if (isUnwound()) System.error("FrameAccessorError", "frame has been unwound"); } diff --git a/src/util/Whamm.v3 b/src/util/Whamm.v3 index 9b93b746d..ddc0d2344 100644 --- a/src/util/Whamm.v3 +++ b/src/util/Whamm.v3 @@ -175,10 +175,9 @@ component Whamm { class WhammProbe(func: Function, sig: Array) extends Probe { var trampoline: TargetCode; // properties set by the spc to make inlining optimization decisions. - var inline_heuristic_checked = false; - var spc_inline_func = false; - var spc_swap_instance = false; - var spc_swap_membase = false; + var swap_checked = false; + var swap_instance = false; + var swap_membase = false; private def args = if(sig.length == 0, Values.NONE, Array.new(sig.length)); @@ -203,6 +202,31 @@ class WhammProbe(func: Function, sig: Array) extends Probe { } return ProbeAction.Continue; } + + + def checkSwap() { + if (swap_checked) return; + var bi = BytecodeIterator.new().reset(WasmFunction.!(func).decl); + while (bi.more()) { + var op = bi.current(); + match (op) { + // These opcodes require swapping the instance. + THROW, CALL, CALL_INDIRECT, MEMORY_INIT, MEMORY_SIZE, MEMORY_GROW, MEMORY_COPY, MEMORY_FILL, REF_FUNC, DATA_DROP, + ELEM_DROP, TABLE_INIT, TABLE_SIZE, TABLE_COPY, TABLE_GROW, GLOBAL_SET, GLOBAL_GET, TABLE_SET, TABLE_GET => swap_instance = true; + // Load/store opcodes require either the memory base or the instance. + I32_STORE, I64_STORE, F32_STORE, F64_STORE, I32_STORE8, I32_STORE16, I64_STORE8, I64_STORE16, I64_STORE32, + V128_STORE, I32_LOAD, I64_LOAD, F32_LOAD, F64_LOAD, I32_LOAD8_S, I32_LOAD8_U, I32_LOAD16_S, I32_LOAD16_U, + I64_LOAD8_S, I64_LOAD8_U, I64_LOAD16_S, I64_LOAD16_U, I64_LOAD32_S, I64_LOAD32_U, V128_LOAD => { + var memarg = bi.immptr().read_MemArg(); + if (memarg.memory_index == 0) swap_membase = true; + else swap_instance = true; + } + _ => ; + } + bi.next(); + } + swap_checked = true; + } } def parseParam0(r: TextReader) -> WhammParam { diff --git a/test/wizeng/failures.x86-64-linux b/test/wizeng/failures.x86-64-linux index 7c5348aae..e69de29bb 100644 --- a/test/wizeng/failures.x86-64-linux +++ b/test/wizeng/failures.x86-64-linux @@ -1,6 +0,0 @@ -wizeng/inline_test_arithmetic.wasm -wizeng/inline_test_locals_control.wasm -wizeng/inline_test_nesting.wasm -wizeng/inline_trap_memory.wasm -wizeng/inline_trap_tableoob.wasm -wizeng/inline_trap_unreachable.wasm diff --git a/test/wizeng/failures.x86-64-linux.spc b/test/wizeng/failures.x86-64-linux.spc index b8636ed97..8a22f4152 100644 --- a/test/wizeng/failures.x86-64-linux.spc +++ b/test/wizeng/failures.x86-64-linux.spc @@ -1 +1,4 @@ +wizeng/inline_test_arithmetic.wasm +wizeng/inline_test_locals_control.wasm +wizeng/inline_test_nesting.wasm wizeng/add.wasm diff --git a/test/wizeng/inline_test_arithmetic.wasm.flags b/test/wizeng/inline_test_arithmetic.wasm.flags index d6ad59add..0c2fe67af 100644 --- a/test/wizeng/inline_test_arithmetic.wasm.flags +++ b/test/wizeng/inline_test_arithmetic.wasm.flags @@ -1 +1 @@ ---mode=jit --metrics=spc*calls --inline-max-depth=1 +--metrics=spc*calls --inline-max-depth=1 diff --git a/test/wizeng/inline_test_arithmetic.wasm.out b/test/wizeng/inline_test_arithmetic.wasm.out new file mode 100644 index 000000000..816760310 --- /dev/null +++ b/test/wizeng/inline_test_arithmetic.wasm.out @@ -0,0 +1,4 @@ +spc:static_calls : 8 calls +spc:static_inlined_calls : 8 calls +spc:dynamic_calls : 8 calls +spc:dynamic_inlined_calls : 8 calls diff --git a/test/wizeng/inline_test_locals_control.wasm.flags b/test/wizeng/inline_test_locals_control.wasm.flags index d6ad59add..0c2fe67af 100644 --- a/test/wizeng/inline_test_locals_control.wasm.flags +++ b/test/wizeng/inline_test_locals_control.wasm.flags @@ -1 +1 @@ ---mode=jit --metrics=spc*calls --inline-max-depth=1 +--metrics=spc*calls --inline-max-depth=1 diff --git a/test/wizeng/inline_test_locals_control.wasm.out b/test/wizeng/inline_test_locals_control.wasm.out new file mode 100644 index 000000000..e9a0b0cfd --- /dev/null +++ b/test/wizeng/inline_test_locals_control.wasm.out @@ -0,0 +1,4 @@ +spc:static_calls : 10 calls +spc:static_inlined_calls : 10 calls +spc:dynamic_calls : 10 calls +spc:dynamic_inlined_calls : 10 calls diff --git a/test/wizeng/inline_test_nesting.wasm.flags b/test/wizeng/inline_test_nesting.wasm.flags index cada94339..047d1fee0 100644 --- a/test/wizeng/inline_test_nesting.wasm.flags +++ b/test/wizeng/inline_test_nesting.wasm.flags @@ -1 +1 @@ ---mode=jit --metrics=spc*calls --inline-max-depth=2 +--metrics=spc*calls --inline-max-depth=2 diff --git a/test/wizeng/inline_test_nesting.wasm.out b/test/wizeng/inline_test_nesting.wasm.out new file mode 100644 index 000000000..0f54fe191 --- /dev/null +++ b/test/wizeng/inline_test_nesting.wasm.out @@ -0,0 +1,4 @@ +spc:static_calls : 19 calls +spc:static_inlined_calls : 17 calls +spc:dynamic_calls : 11 calls +spc:dynamic_inlined_calls : 10 calls diff --git a/test/wizeng/inline_test_osr.wasm b/test/wizeng/inline_test_osr.wasm new file mode 100644 index 000000000..088c78832 Binary files /dev/null and b/test/wizeng/inline_test_osr.wasm differ diff --git a/test/wizeng/inline_test_osr.wasm.exit b/test/wizeng/inline_test_osr.wasm.exit new file mode 100644 index 000000000..573541ac9 --- /dev/null +++ b/test/wizeng/inline_test_osr.wasm.exit @@ -0,0 +1 @@ +0 diff --git a/test/wizeng/inline_test_osr.wasm.flags b/test/wizeng/inline_test_osr.wasm.flags new file mode 100644 index 000000000..cb17b2abc --- /dev/null +++ b/test/wizeng/inline_test_osr.wasm.flags @@ -0,0 +1 @@ +--inline-max-depth=1 diff --git a/test/wizeng/inline_test_osr.wat b/test/wizeng/inline_test_osr.wat new file mode 100644 index 000000000..fabf69432 --- /dev/null +++ b/test/wizeng/inline_test_osr.wat @@ -0,0 +1,42 @@ +;; Test case for OSR + inlining interaction bug. +(module + ;; $inner(n): loops n times and returns n. + (func $inner (param i32) (result i32) + (local i32) + loop + local.get 1 + i32.const 1 + i32.add + local.tee 1 + local.get 0 + i32.lt_s + br_if 0 + end + local.get 0 + ) + + ;; Expected return value: n * 10. + (func $outer (param i32) (result i32) + (local i32) + loop + i32.const 10 + call $inner + local.get 1 + i32.add + local.set 1 + local.get 0 + i32.const 1 + i32.sub + local.tee 0 + br_if 0 + end + local.get 1 + ) + + (func (export "main") (result i32) + i32.const 100000 + call $outer + i32.const 1000000 + i32.ne + ) +) diff --git a/test/wizeng/inline_trap_memory.wasm.flags b/test/wizeng/inline_trap_memory.wasm.flags index 85dace623..cb17b2abc 100644 --- a/test/wizeng/inline_trap_memory.wasm.flags +++ b/test/wizeng/inline_trap_memory.wasm.flags @@ -1 +1 @@ ---mode=jit --inline-max-depth=1 +--inline-max-depth=1 diff --git a/test/wizeng/inline_trap_tableoob.wasm.flags b/test/wizeng/inline_trap_tableoob.wasm.flags index 85dace623..cb17b2abc 100644 --- a/test/wizeng/inline_trap_tableoob.wasm.flags +++ b/test/wizeng/inline_trap_tableoob.wasm.flags @@ -1 +1 @@ ---mode=jit --inline-max-depth=1 +--inline-max-depth=1 diff --git a/test/wizeng/inline_trap_unreachable.wasm.flags b/test/wizeng/inline_trap_unreachable.wasm.flags index 85dace623..cb17b2abc 100644 --- a/test/wizeng/inline_trap_unreachable.wasm.flags +++ b/test/wizeng/inline_trap_unreachable.wasm.flags @@ -1 +1 @@ ---mode=jit --inline-max-depth=1 +--inline-max-depth=1