mirror of
https://github.com/hanzoai/wasm2go.git
synced 2026-10-30 15:06:48 +00:00
* Support the wasm SIMD proposal with native asm lowering (arm64/amd64) One revision spanning the SIMD (0xfd v128) proposal end to end: SSA representation, lowering, scalar reference helpers, and a gcasm asm backend that turns the hot paths into native SIMD — measured on a full llama.cpp build transpiled to pure Go, which this makes run at V8-class speed (prompt eval beats V8 on arm64). Frontend and SSA: - v128 values are [2]uint64 pairs in little-endian lane order; pure ops lower to CSE-able helper calls, memory ops keep statement order, v128.const/shuffle ride as [2]uint64 aux. The full scalar helper set is the reference semantics (saturation, NaN propagation, round-to-even, swizzle OOB, shift masking). - Exception handling lowers to plain branches instead of panic/recover — a check-and-branch after each may-raise call, a per-try dispatch block running the catch-clause chain — covering the C++-shaped patterns (multi-clause catch, delegate targets, rethrow depths) without runtime unwinding, so EH bodies stay eligible for the asm backend. This replaces the closure/recover lowering that #39 extended; its tests are retained unchanged. - Giant functions outline into tractable units (whole loops included, packed u64 boundaries for v128 values), keeping gc compile times and register pressure sane on llama.cpp-sized modules. gcasm backend: - SIMD helper calls splice inline as native NEON/SSE instead of marshalled calls; v128 SSA values travel register-to-register in pair form. Call-tree windows fuse into single splices with region invariant hoisting, bounds-check coalescing, store sinks and scalar-chain internalization; whole countdown loops fuse with an in-splice unroll lane. - Superinstruction selection inside fused regions: 8-bit dot patterns (SMULL+SADALP), SDOT for full 16-byte dots, FMUL by element, scale-lookup addressing, inlined integer division, the software fp32->fp16 idiom lowered to FCVT (both the table-gather and the packed store form), and ggml q8_0 row/column pairing via the traits nrows patch with an SMMLA 2x2 tile kernel. - Runtime CPU-feature dispatch gates spliced bodies (dotprod on arm64, x86-64-v2 SSE on amd64); WASM2GO_FAST_MATH opts into raw-SDOT/FMLA/dual-accumulator forms that trade wasm bit-exactness for native-build-style rounding, validated by token-level equivalence against native llama.cpp. - Guard-page linear memory eliminates per-access bounds checks; jump tables replace the compare tree for br_table. Tooling and CI: - WASM2GO_F16_TABLE asserts the address of ggml's runtime-built f16 table; the transpiler warns when the asserted address matches no gather site (the address moves with every data-layout shift, and a stale assertion silently costs ~7% decode throughput). - The coverage gate runs with -count=1: a cached package result merges incomplete coverage data into the -coverpkg profile, deflating the total by 10+ points depending on what the runner's restored cache contained — the gate must never consume cached results. - Coverage threshold moves to 83% for the enlarged tree; transpile output is deterministic and outline rejections are explained in the build log. Co-Authored-By: Claude Fable 5 <[email protected]> * Replace environment-variable switches with typed Options; drop debug code Configuration now flows through one channel: transpile.Options gains OutlineMinValues, SIMDUnroll, FuseLoops, FuseLoopUnroll, F16TableAddr and FastMath (with matching CLI flags), the gcasm backend receives them as a Config threaded through ModuleOffsets, and no code path branches on an environment variable anymore. Integrator entry points (the wasmify protoc plugin, the CLI) convert their external configuration into these options exactly once. Deleted outright, per the no-env rule and because they were diagnostics rather than build modes: - every WASM2GO_NO_* kill switch and bisection knob (SSA pass disabling, fallback ranges, fuse-window caps, outline limits, inliner windows) — git history keeps them for the next hunt; - every env-gated debug printer (fuse/inline/outline/nrc2/f16/SSA dumps and the near-miss tracers) and the capture-tree keepers; - the dormant multi-exit loop structuring (opt-in, measured slower) and the SSA f32->f16 rewrite entry superseded by the gcasm peephole (its shared idiom matchers stay for the f16 store pass); - the runtime WASM2GO_CPU_PORTABLE override in the generated CPU feature probes. The nil-offsets error paths exposed by the threading get nil-safe Config accessors, and the outline share/v128-min/inliner caps become plain constants at their measured production values. Behavior under default options is unchanged: transpiled output for the non-SIMD and EH fixtures is byte-identical to the previous commit, and the only SIMD-bundle difference is the removed env check in the emitted cpufeat runtime files. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
180 lines
5.4 KiB
Go
180 lines
5.4 KiB
Go
package transpile_test
|
|
|
|
import (
|
|
"bytes"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/goccy/wasm2go/internal/testfixture"
|
|
"github.com/goccy/wasm2go/transpile"
|
|
)
|
|
|
|
// TestInlineLeafEndToEnd pins the wasm-level leaf inliner: both leaf
|
|
// callees of the inline_leaf fixture are spliced into the caller (no
|
|
// call survives in the caller body), and the generated program
|
|
// computes the exact called-semantics results, exercising params,
|
|
// declared-local zero-init, an early return joined by phi, a loop and
|
|
// memory stores inside an inlined body.
|
|
//
|
|
// Expected values: memleaf writes [0,1,2,3] at 64..80 so mem[72]=2;
|
|
// leaf(3,5)=8 → run(3)=10; leaf(0,_)=7 (early return) → run(0)=9.
|
|
func TestInlineLeafEndToEnd(t *testing.T) {
|
|
bin := testfixture.Wasm(t, "inline_leaf")
|
|
m, err := transpile.Parse(bytes.NewReader(bin))
|
|
if err != nil {
|
|
t.Fatalf("Parse: %v", err)
|
|
}
|
|
restore := transpile.SetMultiPackageThreshold(1 << 30)
|
|
defer restore()
|
|
var buf bytes.Buffer
|
|
res, err := transpile.Translate(&buf, m, transpile.Options{
|
|
Package: "pkg",
|
|
OutputImportPath: "inltest/pkg",
|
|
PureOnly: true, // pure keeps the caller body inspectable
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Translate: %v", err)
|
|
}
|
|
|
|
// Shape assertion: the caller (fn2) must contain no calls to fn0/fn1.
|
|
var all strings.Builder
|
|
all.Write(buf.Bytes())
|
|
for _, d := range res.Files {
|
|
all.Write(d)
|
|
}
|
|
src := all.String()
|
|
i := strings.Index(src, "func fn2(")
|
|
if i < 0 {
|
|
t.Fatalf("caller fn2 not found in output")
|
|
}
|
|
body := src[i:]
|
|
if j := strings.Index(body, "\n}"); j >= 0 {
|
|
body = body[:j]
|
|
}
|
|
if strings.Contains(body, "fn0(") || strings.Contains(body, "fn1(") {
|
|
t.Errorf("caller still calls a leaf that should have been inlined:\n%s", body)
|
|
}
|
|
|
|
// Behavior assertion: build and run.
|
|
dir := t.TempDir()
|
|
writeFile := func(rel string, data []byte) {
|
|
p := filepath.Join(dir, rel)
|
|
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(p, data, 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
writeFile("go.mod", []byte("module inltest\n\ngo 1.25.0\n"))
|
|
writeFile("pkg/gen.go", buf.Bytes())
|
|
for rel, data := range res.Files {
|
|
writeFile("pkg/"+rel, data)
|
|
}
|
|
for name, data := range res.Sidecars {
|
|
writeFile("pkg/"+name, data)
|
|
}
|
|
writeFile("main.go", []byte(`package main
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"inltest/pkg"
|
|
)
|
|
|
|
func main() {
|
|
m := pkg.New()
|
|
fmt.Println(m.Run(3), m.Run(0))
|
|
}
|
|
`))
|
|
cmd := exec.Command("go", "run", ".")
|
|
cmd.Dir = dir
|
|
out, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("go run failed: %v\n%s", err, out)
|
|
}
|
|
if got := strings.TrimSpace(string(out)); got != "10 9" {
|
|
t.Fatalf("run(3), run(0) printed %q, want \"10 9\"", got)
|
|
}
|
|
}
|
|
|
|
// TestInlineConstBaseLargeOffsetViaConstsTable pins the arm64
|
|
// literal-pool guard for the address shape inlining creates: a callee
|
|
// whose address PARAM is a large constant at the call site. After
|
|
// inlining + constprop the loads' base is an SSA constant that is
|
|
// HOISTED into a local (usage ≥ 2), so the old AST-shape check missed
|
|
// it, gc constant-folded the local back into the addressing mode, and
|
|
// arm64 assembly failed with "LDPSW ...: constant is not in pool" on
|
|
// the SpiderMonkey bundle. The emitter must detect SSA-constant bases
|
|
// and route large totals through the _consts table.
|
|
func TestInlineConstBaseLargeOffsetViaConstsTable(t *testing.T) {
|
|
bin := testfixture.Wasm(t, "inline_constaddr")
|
|
m, err := transpile.Parse(bytes.NewReader(bin))
|
|
if err != nil {
|
|
t.Fatalf("Parse: %v", err)
|
|
}
|
|
restore := transpile.SetMultiPackageThreshold(1 << 30)
|
|
defer restore()
|
|
var buf bytes.Buffer
|
|
res, err := transpile.Translate(&buf, m, transpile.Options{
|
|
Package: "pkg",
|
|
OutputImportPath: "inlconst/pkg",
|
|
PureOnly: true,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Translate: %v", err)
|
|
}
|
|
var all strings.Builder
|
|
all.Write(buf.Bytes())
|
|
for _, d := range res.Files {
|
|
all.Write(d)
|
|
}
|
|
src := all.String()
|
|
if !strings.Contains(src, "_consts[") {
|
|
t.Errorf("large constant base addresses must route through _consts; none found:\n%s", src)
|
|
}
|
|
// The raw multi-MB literal must not appear inside an unsafe.Add
|
|
// operand (bare or in a fold-visible `vN + off` shape).
|
|
if strings.Contains(src, "unsafe.Add(mBase, 27000000") || strings.Contains(src, "unsafe.Add(mBase, uint32(27000000") {
|
|
t.Errorf("multi-MB literal reached unsafe.Add directly:\n%s", src)
|
|
}
|
|
}
|
|
|
|
// TestInlineKeepsCalleeBodies pins the exported-shape invariant:
|
|
// fn0/fn1 bodies are still emitted even when inlined into callers
|
|
// (table/export references may need them; whole-function DCE
|
|
// decides, not the inliner).
|
|
func TestInlineKeepsCalleeBodies(t *testing.T) {
|
|
bin := testfixture.Wasm(t, "inline_leaf")
|
|
m, err := transpile.Parse(bytes.NewReader(bin))
|
|
if err != nil {
|
|
t.Fatalf("Parse: %v", err)
|
|
}
|
|
restore := transpile.SetMultiPackageThreshold(1 << 30)
|
|
defer restore()
|
|
var buf bytes.Buffer
|
|
res, err := transpile.Translate(&buf, m, transpile.Options{
|
|
Package: "pkg",
|
|
OutputImportPath: "inltest/pkg",
|
|
PureOnly: true,
|
|
KeepDeadFuncs: true, // keep bodies regardless of DCE policy
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Translate: %v", err)
|
|
}
|
|
var all strings.Builder
|
|
all.Write(buf.Bytes())
|
|
for _, d := range res.Files {
|
|
all.Write(d)
|
|
}
|
|
src := all.String()
|
|
for _, fn := range []string{"func fn0(", "func fn1("} {
|
|
if !strings.Contains(src, fn) {
|
|
t.Errorf("inliner must not delete callee bodies (%s missing); that is DCE's job", fn)
|
|
}
|
|
}
|
|
}
|