From 62952887146ba77044d34676a31c25f2bf0526cf Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Mon, 23 Mar 2026 03:37:07 -0400 Subject: [PATCH 01/18] The first of the final inlinings --- src/engine/compiler/SinglePassCompiler.v3 | 417 ++++++++++++++-------- src/util/Whamm.v3 | 32 +- test/inline/failures.x86-64-linux | 3 - 3 files changed, 298 insertions(+), 154 deletions(-) delete mode 100644 test/inline/failures.x86-64-linux diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index b4f0d4569..a366cb31f 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -112,9 +112,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_probe_ctl_base: u31; // ctl_stack.top when Whamm probe compilation started + var whamm_config: WhammInlineConfig; // XXX: hack var handler_dest_info = Vector.new(); @@ -486,40 +484,33 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl // 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(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) { @@ -528,13 +519,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); @@ -546,7 +537,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); @@ -556,7 +547,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); @@ -564,7 +555,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); @@ -574,7 +565,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); @@ -584,7 +575,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); @@ -594,7 +585,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); @@ -605,7 +596,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); @@ -616,7 +607,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); @@ -631,15 +622,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))); @@ -648,7 +639,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); } } @@ -656,49 +647,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); @@ -799,37 +755,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); @@ -871,6 +828,18 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl } var func = module.functions[index]; + // Try inlining for intra-module, non-tail calls + if (!tailCall && shouldInline(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; + } + withReconstructedInlinedFrames(fun { var retpt = masm.newLabel(it.pc), wasmcall_label = masm.newLabel(it.pc); // Load the instance (which must happen before frame is unwound). @@ -886,6 +855,160 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl emitCallToReg(func.sig, func_reg, vsp_reg, tmp, func.imp != null, tailCall); }); } + 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(); + } + } 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); // Handle the current stack state. @@ -2134,7 +2257,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl var wasm_func_reg = allocTmp(ValueKind.REF); var inl_inst_reg: Reg, inl_mem0_reg: Reg; - if (is_inlined) { + if (whamm_config.is_inlined) { // TODO investigate, check individual configs? 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); @@ -2194,7 +2317,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl masm.emit_mov_m_l(accessor_slot, 0); // if an inlined whamm probe, also grab inlined slots - if (is_inlined) { + if (whamm_config.is_inlined) { def inl_instance_slot = frame.inlined_instance_slot.plus(frame_offset); masm.emit_mov_m_r(ValueKind.REF, inl_instance_slot, inl_inst_reg); def inl_mem0_base_slot = frame.inlined_mem0_base_slot.plus(frame_offset); @@ -2315,7 +2438,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.is_inlined) { 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); @@ -2323,7 +2446,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl } } def emit_load_instance(reg: Reg) { - if (is_inlined) { // inline compilation + if (whamm_config.is_inlined) { // inline compilation masm.emit_mov_r_m(ValueKind.REF, reg, frame.inlined_instance_slot); } else { masm.emit_mov_r_m(ValueKind.REF, reg, frame.instance_slot); @@ -2691,6 +2814,37 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl } return frames; } + // Determine if a regular function call should be inlined + def shouldInline(func: FuncDecl) -> bool { + if (Trace.compiler) OUT.put1("deciding on inlining call to func #%d: ", func.func_index); + + if (func.imp != null) return no("imported"); + if (inlineDepth() >= SpcTuning.maxInlineDepth) return no("max inline depth exceeded"); + if (func.orig_bytecode.length > SpcTuning.maxInlineBytecodeSize) return no("func too large"); + if (func.sig.params.length > SpcTuning.maxInlineParams) return no("too many parameters"); + + // Scan bytecode for unsupported instructions + var bi = BytecodeIterator.new().reset(func); + while (bi.more()) { + match (bi.current()) { + RETURN, RETURN_CALL, RETURN_CALL_INDIRECT, RETURN_CALL_REF => + return no("uses return instruction"); + TRY, CATCH, THROW, RETHROW, THROW_REF, DELEGATE, CATCH_ALL, TRY_TABLE => + return no("uses exception handling instruction"); + CONT_NEW, CONT_BIND, SUSPEND, RESUME, RESUME_THROW, RESUME_THROW_REF, SWITCH => + return no("uses stack switching instruction"); + _ => ; + } + bi.next(); + } + + if (Trace.compiler) OUT.puts("YES\n"); + return true; + } + private def no(reason: string) -> bool { + if (Trace.compiler) OUT.puts("NO (").puts(reason).putc(')').ln(); + return false; + } } // Different branch instructions have different repush enum BrRepush(taken: bool, not_taken: bool) { @@ -3397,38 +3551,7 @@ 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; - 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; - } - _ => ; - } - bi.next(); - } - return InlineConfig(swap_membase, swap_instance, true); -} - -type InlineConfig(swap_membase: bool, swap_instance: bool, can_inline: bool); +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/util/Whamm.v3 b/src/util/Whamm.v3 index 9b93b746d..ae1649d8b 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; } + + // If function is to be inlined, check to see if instance or mem0_base need to be swapped. + 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/inline/failures.x86-64-linux b/test/inline/failures.x86-64-linux deleted file mode 100644 index 925e70891..000000000 --- a/test/inline/failures.x86-64-linux +++ /dev/null @@ -1,3 +0,0 @@ -inline_test_arithmetic.wasm -inline_test_locals_control.wasm -inline_test_nesting.wasm From 4b31fb92f00ef3aa09756f0e8cb11d2ee743d428 Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Mon, 23 Mar 2026 03:38:34 -0400 Subject: [PATCH 02/18] Remove dead lines --- src/engine/compiler/SinglePassCompiler.v3 | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index a366cb31f..123d72f1d 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -755,9 +755,6 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl setUnreachable(); } def visit_END() { - 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(); From 286708589ea1f7fe29121a97a6d10ace1ba866d4 Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Mon, 23 Mar 2026 03:43:24 -0400 Subject: [PATCH 03/18] Remove extra metric increment --- src/engine/compiler/SinglePassCompiler.v3 | 1 - 1 file changed, 1 deletion(-) diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index 123d72f1d..a95f5902b 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -831,7 +831,6 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl 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; From 378c7baba4e546d8ea5f4e5b64e5b16774c0f95e Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Mon, 23 Mar 2026 03:49:25 -0400 Subject: [PATCH 04/18] Fix osr bug on dyn --- src/engine/compiler/SinglePassCompiler.v3 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index a95f5902b..b77e8abda 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -700,7 +700,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); From 667952fe7cfae2adf26003b5b8283bc44bd960c0 Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Wed, 25 Mar 2026 01:35:09 -0400 Subject: [PATCH 05/18] Support RETURN instruction * we now use RETURN for SpcControl for inlined functions instead of BLOCK * RETURN instructions are now supported * ret_labels are now eagerly instantiated and added to SpcState * added pushFuncBody to abstract control push of RETURN --- src/engine/compiler/SinglePassCompiler.v3 | 47 +++++++---- test/inline/inline_test_return.wasm | Bin 0 -> 182 bytes test/inline/inline_test_return.wasm.exit | 1 + test/inline/inline_test_return.wasm.flags | 1 + test/inline/inline_test_return.wasm.out | 4 + test/inline/inline_test_return.wat | 97 ++++++++++++++++++++++ 6 files changed, 134 insertions(+), 16 deletions(-) create mode 100644 test/inline/inline_test_return.wasm create mode 100644 test/inline/inline_test_return.wasm.exit create mode 100644 test/inline/inline_test_return.wasm.flags create mode 100644 test/inline/inline_test_return.wasm.out create mode 100644 test/inline/inline_test_return.wat diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index b77e8abda..a1ba2acea 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -102,6 +102,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl var sig: SigDecl; var num_locals: int; var local_base_sp: u31; // can use a Range for 0-indexing instead of from offset + var ctl_base_sp: u31; // index of the RETURN control in ctl_stack for the current frame var success = true; var osr_pc: int; @@ -164,7 +165,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl // Push initial frame for top-level function state.frame_stack.clear(); - var initial_frame = SpcFrame.new(func, module, 0, 0, func.num_slots(), 0); + var initial_frame = SpcFrame.new(func, module, 0, 0, func.num_slots(), 0, masm.newLabel(func.cur_bytecode.length)); pushSpcFrame(initial_frame); // Emit prologue, which allocates the frame and initializes various registers. @@ -782,6 +783,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl emitProbe(); if (ctl_top.merge_count > 1) emitReturn(ctl_top); state.ctl_stack.pop(); + return; } emitProbe(); } @@ -812,9 +814,8 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl setUnreachable(); } def visit_RETURN() { - var target = state.ctl_stack.elems[0]; + var target = state.ctl_stack.elems[ctl_base_sp]; state.emitTransfer(target, resolver); - if (ret_label == null) ret_label = masm.newLabel(func.cur_bytecode.length); masm.emit_br(ret_label); setUnreachable(); } @@ -865,9 +866,11 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl var num_locals = callee_func.num_slots(); - // Push an implicit block for the head of the function + // Push a RETURN control for the inlined callee's function body. var end_label = masm.newLabel(callee_func.cur_bytecode.length); - state.pushBlock(sig.params, sig.results, end_label); + var func_body_ctl = state.pushFuncBody(sig.params, sig.results, end_label); + func_body_ctl.merge_state = state.getInMemoryMergeWithArgs(int.view(func_body_ctl.val_stack_top), sig.results); // preserve outer frame state below callee's results + func_body_ctl.merge_count = 1; var m: Module = module; @@ -883,8 +886,8 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl } // 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); + var callee_frame = SpcFrame.new(callee_func, + m, new_local_base_sp, new_ctl_base_sp, num_locals, 0, masm.newLabel(callee_func.cur_bytecode.length)); pushSpcFrame(callee_frame); @@ -2181,10 +2184,8 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl } def emitReturn(ctl: SpcControl) { // All explicit RETURN instructions branch here. - if (ret_label != null) { - masm.bindLabel(ret_label); - ret_label = null; - } + masm.bindLabel(ret_label); + var results = sig.results; if (masm.valuerep.tagged) { // update mismatched value tags @@ -2195,6 +2196,9 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl masm.emit_mov_m_i(masm.tagAddr(state.sp - u32.view(results.length) + u32.view(i)), rtag.code); } } + + if (isInlined()) return; + // Compute VSP = VFP + state.sp emit_compute_vsp(regs.vsp, state.sp); // Return to caller @@ -2770,7 +2774,10 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl if (func != null) masm.pushInlineContext(func.func_index); def current = state.frame_stack.peek(); - if (current != null) current.pc = it.pc; + if (current != null) { + current.pc = it.pc; + current.ret_label = ret_label; + } state.frame_stack.push(frame); // Update cached copies from new top frame it.reset(frame.func).at(frame.pc, -1); @@ -2779,6 +2786,8 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl sig = func.sig; num_locals = frame.num_locals; local_base_sp = frame.local_base_sp; + ctl_base_sp = frame.ctl_base_sp; + ret_label = frame.ret_label; } def popSpcFrame() -> SpcFrame { masm.popInlineContext(); @@ -2792,6 +2801,8 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl sig = func.sig; num_locals = current.num_locals; local_base_sp = current.local_base_sp; + ctl_base_sp = current.ctl_base_sp; + ret_label = current.ret_label; return frame; } @@ -2806,7 +2817,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl for (i < state.frame_stack.top) { var f = state.frame_stack.elems[i]; var pc = if(i == state.frame_stack.top - 1, it.pc, f.pc); - frames[i] = SpcFrame.new(f.func, f.module, f.local_base_sp, f.ctl_base_sp, f.num_locals, pc); + frames[i] = SpcFrame.new(f.func, f.module, f.local_base_sp, f.ctl_base_sp, f.num_locals, pc, null); } return frames; } @@ -2823,7 +2834,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl var bi = BytecodeIterator.new().reset(func); while (bi.more()) { match (bi.current()) { - RETURN, RETURN_CALL, RETURN_CALL_INDIRECT, RETURN_CALL_REF => + RETURN_CALL, RETURN_CALL_INDIRECT, RETURN_CALL_REF => return no("uses return instruction"); TRY, CATCH, THROW, RETHROW, THROW_REF, DELEGATE, CATCH_ALL, TRY_TABLE => return no("uses exception handling instruction"); @@ -2994,8 +3005,9 @@ class SpcFrame { var ctl_base_sp: u31; // Base index into SpcState.ctl_stack var num_locals: int; var pc: int; + var ret_label: MasmLabel; - new(func, module, local_base_sp, ctl_base_sp, num_locals, pc) {} + new(func, module, local_base_sp, ctl_base_sp, num_locals, pc, ret_label) {} } class SpcState(regAlloc: RegAlloc) { @@ -3012,7 +3024,7 @@ class SpcState(regAlloc: RegAlloc) { ctl_stack.clear(); // manually set up first control entry and return merge state var results = sig.results; - var ctl = pushControl(Opcode.RETURN.code, ValueTypes.NONE, results, ret_label); + var ctl = pushFuncBody(ValueTypes.NONE, results, ret_label); var merge_state = Array.new(results.length); for (i < results.length) { // request the merged values be stored to the stack, but don't require tags @@ -3044,6 +3056,9 @@ class SpcState(regAlloc: RegAlloc) { def pushBlock(params: Array, results: Array, end_label: MasmLabel) -> SpcControl { return pushControl(Opcode.BLOCK.code, params, results, end_label); } + def pushFuncBody(params: Array, results: Array, end_label: MasmLabel) -> SpcControl { + return pushControl(Opcode.RETURN.code, params, results, end_label); + } def pushLoop(params: Array, results: Array, start_label: MasmLabel) -> SpcControl { var ctl = pushControl(Opcode.LOOP.code, params, results, start_label); return ctl; diff --git a/test/inline/inline_test_return.wasm b/test/inline/inline_test_return.wasm new file mode 100644 index 0000000000000000000000000000000000000000..d7bcbbaa0b658f86faa93be8c09ba06cbf0b59e7 GIT binary patch literal 182 zcmXZSF%H5o429umCsk2Aq+(>s#5rm)1aXRX1W|@EBad7gr*!(iJO}f8Apmp?6PuAu z!M1=b!~o*{KyjJxFL3%&ID@S~`N^XPw>TF12ZbJ4L_8uV6n|gaHH(wmM{bl0G-w>4 beRY_ltE<{Jv8z*P8faTTyWxA@o$4w-Cl(w8 literal 0 HcmV?d00001 diff --git a/test/inline/inline_test_return.wasm.exit b/test/inline/inline_test_return.wasm.exit new file mode 100644 index 000000000..573541ac9 --- /dev/null +++ b/test/inline/inline_test_return.wasm.exit @@ -0,0 +1 @@ +0 diff --git a/test/inline/inline_test_return.wasm.flags b/test/inline/inline_test_return.wasm.flags new file mode 100644 index 000000000..0c2fe67af --- /dev/null +++ b/test/inline/inline_test_return.wasm.flags @@ -0,0 +1 @@ +--metrics=spc*calls --inline-max-depth=1 diff --git a/test/inline/inline_test_return.wasm.out b/test/inline/inline_test_return.wasm.out new file mode 100644 index 000000000..79d1497bf --- /dev/null +++ b/test/inline/inline_test_return.wasm.out @@ -0,0 +1,4 @@ +spc:static_calls : 6 calls +spc:static_inlined_calls : 6 calls +spc:dynamic_calls : 6 calls +spc:dynamic_inlined_calls : 6 calls diff --git a/test/inline/inline_test_return.wat b/test/inline/inline_test_return.wat new file mode 100644 index 000000000..c1dd8b196 --- /dev/null +++ b/test/inline/inline_test_return.wat @@ -0,0 +1,97 @@ +;; Test inlined functions with explicit RETURN, including nested control flow +;; and paths where extra values are on the stack at the time of return. +(module + ;; Two levels of nested ifs; in the early-return path, 2*a is an extra value + ;; on the value stack below the returned a+b. + (func $weighted (param i32) (param i32) (result i32) + block (result i32) + local.get 0 + i32.const 2 + i32.mul ;; [2a] -- extra below when early return fires + block + local.get 0 + i32.const 0 + i32.gt_s + if + local.get 1 + i32.const 0 + i32.gt_s + if + ;; both positive: return a+b; 2a is extra on stack + local.get 0 + local.get 1 + i32.add + return + end + end + end + local.get 1 + i32.add ;; fallthrough: 2a+b + end + ) + + ;; Clamp x to [lo, hi]; two levels of nesting, returns on multiple paths. + (func $clamp (param i32) (param i32) (param i32) (result i32) + local.get 0 + local.get 1 + i32.lt_s + if + local.get 1 + return + end + local.get 0 + local.get 2 + i32.gt_s + if + local.get 2 + return + end + local.get 0 + ) + + (func (export "main") (result i32) + i32.const 3 + i32.const 4 + call $weighted + i32.const 7 ;; both positive: 3+4=7 + i32.ne + + i32.const 3 + i32.const -1 + call $weighted + i32.const 5 ;; b<=0: 2*3+(-1)=5 + i32.ne + i32.or + + i32.const -1 + i32.const 4 + call $weighted + i32.const 2 ;; a<=0: 2*(-1)+4=2 + i32.ne + i32.or + + i32.const 5 + i32.const 0 + i32.const 10 + call $clamp + i32.const 5 + i32.ne + i32.or + + i32.const -3 + i32.const 0 + i32.const 10 + call $clamp + i32.const 0 + i32.ne + i32.or + + i32.const 15 + i32.const 0 + i32.const 10 + call $clamp + i32.const 10 + i32.ne + i32.or + ) +) From 2f379406cef22aecbf0d635aa67f347a21ba0ba0 Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Wed, 25 Mar 2026 01:39:31 -0400 Subject: [PATCH 06/18] Remove manual result slot cleanup (using merge state transfer instead) q --- src/engine/compiler/SinglePassCompiler.v3 | 47 ----------------------- 1 file changed, 47 deletions(-) diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index a1ba2acea..838ccceda 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -957,53 +957,6 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl 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(); } From 6ee4626afee79bee03497185eaaaaf9fce673c73 Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Wed, 25 Mar 2026 02:06:12 -0400 Subject: [PATCH 07/18] Revert "Remove manual result slot cleanup (using merge state transfer instead)" This reverts commit 112716e1942feda187004249639502131730f592. --- src/engine/compiler/SinglePassCompiler.v3 | 47 +++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index 838ccceda..a1ba2acea 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -957,6 +957,53 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl 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(); } From d60b5f4ca109beb7b50f78f11493047445b2880b Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Wed, 25 Mar 2026 02:21:30 -0400 Subject: [PATCH 08/18] Fix whamm arg for merge state --- src/engine/compiler/SinglePassCompiler.v3 | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index a1ba2acea..1b53cc181 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -869,8 +869,6 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl // Push a RETURN control for the inlined callee's function body. var end_label = masm.newLabel(callee_func.cur_bytecode.length); var func_body_ctl = state.pushFuncBody(sig.params, sig.results, end_label); - func_body_ctl.merge_state = state.getInMemoryMergeWithArgs(int.view(func_body_ctl.val_stack_top), sig.results); // preserve outer frame state below callee's results - func_body_ctl.merge_count = 1; var m: Module = module; @@ -883,8 +881,13 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl m = whamm_instance.module; new_local_base_sp = u31.view(state.sp) - u31.view(whamm_sig.length); // XXX + func_body_ctl.val_stack_top = new_local_base_sp; // correct val_stack_top for whamm arg count } + // create merge state based on outer function's base sp given inlined function's results + func_body_ctl.merge_state = state.getInMemoryMergeWithArgs(int.view(new_local_base_sp), sig.results); + func_body_ctl.merge_count = 1; + // 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, masm.newLabel(callee_func.cur_bytecode.length)); From acc4d1ecec04f97f5c76643cc67c55fbe2c16904 Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Wed, 25 Mar 2026 02:27:55 -0400 Subject: [PATCH 09/18] Reapply "Remove manual result slot cleanup (using merge state transfer instead)" This reverts commit 7c09bfc5ea27573da05b85a996cffd36a82170bd. --- src/engine/compiler/SinglePassCompiler.v3 | 47 ----------------------- 1 file changed, 47 deletions(-) diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index 1b53cc181..44c2f5de6 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -960,53 +960,6 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl 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(); } From 6fc3ec35a8c19ef18f7f8fcfbf35edc8a7358301 Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Wed, 25 Mar 2026 11:58:02 -0400 Subject: [PATCH 10/18] Add return test to failures on dyn --- test/inline/failures.x86-64-linux.dyn | 1 + 1 file changed, 1 insertion(+) diff --git a/test/inline/failures.x86-64-linux.dyn b/test/inline/failures.x86-64-linux.dyn index da02fa079..50325688b 100644 --- a/test/inline/failures.x86-64-linux.dyn +++ b/test/inline/failures.x86-64-linux.dyn @@ -1,4 +1,5 @@ inline_test_arithmetic.wasm inline_test_locals_control.wasm inline_test_nesting.wasm +inline_test_return.wasm From 94b1d8ef02c7a447a1b888d68114f6b07faa823c Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Tue, 31 Mar 2026 14:38:13 -0400 Subject: [PATCH 11/18] Use withReconstruct on inlined function entry probes --- src/engine/compiler/SinglePassCompiler.v3 | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index 44c2f5de6..d95d9df7f 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -898,19 +898,8 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl // 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); - } + withReconstructedInlinedFrames(fun => + emitProbe0(0, probe)); } // Allocate callee's non-parameter locals From f582175121d11f8d97968e0cdbd3bff5f7eee09b Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Tue, 31 Mar 2026 23:30:47 -0400 Subject: [PATCH 12/18] Prohibit nested frame reconstruction (Whamm probe hackfix when nesting depth > 1) --- src/engine/compiler/SinglePassCompiler.v3 | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index d95d9df7f..1ff91f92f 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -114,6 +114,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl var last_probe = 0; var skip_to_end: bool; var whamm_config: WhammInlineConfig; + var frames_reconstructed = false; // XXX: hack var handler_dest_info = Vector.new(); @@ -2277,9 +2278,20 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl // Guards compiler code with frame reconstruction (if necessary). def withReconstructedInlinedFrames(emit: void -> void) { if (isInlined()) { + if (frames_reconstructed) { + // XXX this should not happen (but does), in the case of deep nesting + // when one layer is a Whamm probe + if (Trace.compiler) Trace.OUT.puts(" nested frame reconstruction inhibited\n"); + // need to save vfp into the frame (because Whamm probe doesn't?) + masm.emit_mov_m_r(ValueKind.REF, frame.vfp_slot, regs.vfp); + emit(); + return; + } unrefRegs(); + frames_reconstructed = true; def space = emitReconstructStackFrames(snapshotFrames()); emit(); + frames_reconstructed = false; if (space > 0) { masm.emit_addw_r_i(regs.sp, space); masm.emit_mov_r_m(ValueKind.REF, regs.vfp, frame.vfp_slot); From 8cd762ab822c8cc32130588d8ebc863d2c6c02ab Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Tue, 31 Mar 2026 23:40:47 -0400 Subject: [PATCH 13/18] Increase code size estimate when inlining is enabled --- src/engine/x86-64/X86_64SinglePassCompiler.v3 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/engine/x86-64/X86_64SinglePassCompiler.v3 b/src/engine/x86-64/X86_64SinglePassCompiler.v3 index c277b9b98..20fbc427b 100644 --- a/src/engine/x86-64/X86_64SinglePassCompiler.v3 +++ b/src/engine/x86-64/X86_64SinglePassCompiler.v3 @@ -1535,7 +1535,7 @@ component X86_64Spc { return addr; } def estimateCodeSizeFor(decl: FuncDecl) -> int { - return 60 + decl.orig_bytecode.length * 20; // TODO: huge overestimate + return 60 + decl.orig_bytecode.length * 20 * (2 << byte.view(SpcTuning.maxInlineDepth)); // TODO: huge overestimate } private def lazyCompile(wf: WasmFunction) -> (WasmFunction, Pointer, Throwable) { // The global stub simply consults the execution strategy. From 4387fb5a6076bf028860fdb882990b3f6ea77cd8 Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Wed, 1 Apr 2026 11:18:04 -0400 Subject: [PATCH 14/18] Move vfp fixing to emitWhammProbe --- src/engine/compiler/SinglePassCompiler.v3 | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index 1ff91f92f..e7a4a7574 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -651,6 +651,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl var whamm_func_decl = callee_func.decl; if (inline_decision) { whamm_config = WhammInlineConfig(swap_membase, swap_instance, true); + masm.emit_mov_m_r(ValueKind.REF, frame.vfp_slot, regs.vfp); emitInlinedCall(whamm_func_decl, probe); whamm_config = WhammInlineConfig(false, false, false); // Restore mem0_base after probe @@ -2279,11 +2280,10 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl def withReconstructedInlinedFrames(emit: void -> void) { if (isInlined()) { if (frames_reconstructed) { - // XXX this should not happen (but does), in the case of deep nesting - // when one layer is a Whamm probe + // FIXME this should not happen (but does): + // - in the case of deep nesting when one layer is a Whamm probe + // - when refactoring to avoid `with` clause, GC test fails (inlining depth 2) if (Trace.compiler) Trace.OUT.puts(" nested frame reconstruction inhibited\n"); - // need to save vfp into the frame (because Whamm probe doesn't?) - masm.emit_mov_m_r(ValueKind.REF, frame.vfp_slot, regs.vfp); emit(); return; } From ab4a707773688f53c3baad467c139b3493d1a578 Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Fri, 3 Apr 2026 14:47:19 -0400 Subject: [PATCH 15/18] Clean up comments --- src/engine/compiler/SinglePassCompiler.v3 | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-) diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index e7a4a7574..bde3dbf30 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -860,9 +860,6 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl 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); @@ -897,7 +894,6 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl 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); withReconstructedInlinedFrames(fun => @@ -928,16 +924,11 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl } 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 + // Restore caller spc context + popSpcFrame(); // If inlined function is unreachable, no results to clean up - if (!inlined_reachable) { + if (!state.ctl_stack.peek().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", @@ -950,10 +941,6 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl setUnreachable(); return; } - - if (Trace.compiler) { - Trace.OUT.put1(" Inlined call complete, sp=%d", state.sp).ln(); - } } 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); From d5f500d50c3ec42f65739fa53eed01af3524d64c Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Fri, 3 Apr 2026 15:31:14 -0400 Subject: [PATCH 16/18] Update code size estimate --- src/engine/x86-64/X86_64SinglePassCompiler.v3 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/engine/x86-64/X86_64SinglePassCompiler.v3 b/src/engine/x86-64/X86_64SinglePassCompiler.v3 index 20fbc427b..0ab68d3bc 100644 --- a/src/engine/x86-64/X86_64SinglePassCompiler.v3 +++ b/src/engine/x86-64/X86_64SinglePassCompiler.v3 @@ -1535,7 +1535,8 @@ component X86_64Spc { return addr; } def estimateCodeSizeFor(decl: FuncDecl) -> int { - return 60 + decl.orig_bytecode.length * 20 * (2 << byte.view(SpcTuning.maxInlineDepth)); // TODO: huge overestimate + // TODO: very imprecise estimate + return 60 + decl.orig_bytecode.length * 20 * (4 << byte.view(SpcTuning.maxInlineDepth)); } private def lazyCompile(wf: WasmFunction) -> (WasmFunction, Pointer, Throwable) { // The global stub simply consults the execution strategy. From 98c0daddf3591b6882d84a16cadd4d154942ee84 Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Fri, 3 Apr 2026 15:37:40 -0400 Subject: [PATCH 17/18] Remove unreachable function cleanup --- src/engine/compiler/SinglePassCompiler.v3 | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index bde3dbf30..bace6c55b 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -926,21 +926,6 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl // Restore caller spc context popSpcFrame(); - - // If inlined function is unreachable, no results to clean up - if (!state.ctl_stack.peek().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; - } } 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); From 3cb3c7ad29a9298537d1aef39f40a0b227a16794 Mon Sep 17 00:00:00 2001 From: Matthew Schneider Date: Fri, 3 Apr 2026 15:42:21 -0400 Subject: [PATCH 18/18] Update TODO to XXX --- src/engine/compiler/SinglePassCompiler.v3 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/engine/compiler/SinglePassCompiler.v3 b/src/engine/compiler/SinglePassCompiler.v3 index bace6c55b..96d8fc5c5 100644 --- a/src/engine/compiler/SinglePassCompiler.v3 +++ b/src/engine/compiler/SinglePassCompiler.v3 @@ -2176,7 +2176,7 @@ class SinglePassCompiler(xenv: SpcExecEnv, masm: MacroAssembler, regAlloc: RegAl var wasm_func_reg = allocTmp(ValueKind.REF); var inl_inst_reg: Reg, inl_mem0_reg: Reg; - if (whamm_config.is_inlined) { // TODO investigate, check individual configs? + if (whamm_config.is_inlined) { // XXX check individual configs? 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);