Files
f30ec292fd Support the wasm SIMD proposal with native asm lowering (arm64/amd64) (#40)
* 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]>
2026-08-08 23:28:14 +09:00

206 lines
6.7 KiB
Go

package lower
import (
"bytes"
"errors"
"testing"
"github.com/goccy/wasm2go/internal/testfixture"
"github.com/goccy/wasm2go/internal/wasm"
)
// TestLowerArith feeds the arith.wasm fixture (already a happy-path
// integer-arith-only module) through LowerFunction and asserts that
// every exported function lowers cleanly. The dump of one
// representative function is checked against a golden string so
// regressions in op selection or value-id assignment show up loudly.
// testThrowSet gives the lowering the module's real throw analysis, the
// same one Translate computes.
func testThrowSet(mod *wasm.Module) *ThrowSet {
ts, err := ComputeThrowSet(mod, nil)
if err != nil {
panic(err)
}
return ts
}
func TestLowerArith(t *testing.T) {
bin := testfixture.Wasm(t, "arith")
mod, err := wasm.Parse(bytes.NewReader(bin))
if err != nil {
t.Fatalf("parse: %v", err)
}
// Find a function we know is straight-line arith: "add".
addFnIdx := ^uint32(0)
for _, e := range mod.Exports {
if e.Kind == wasm.ExportFunc && e.Name == "add" {
addFnIdx = e.Index
break
}
}
if addFnIdx == ^uint32(0) {
t.Fatalf("arith.wasm: missing add export")
}
fn, err := LowerFunction(mod, addFnIdx, "add", testThrowSet(mod))
if err != nil {
t.Fatalf("lower add: %v", err)
}
got := dumpSSAFunc(fn)
// add: (i32, i32) -> i32 { return p0 + p1 }
want := `func add(p0 i32, p1 i32) i32 {
b0:
v1 = OpParam [0] : i32
v2 = OpParam [1] : i32
v3 = OpAdd32 v1 v2 : i32
v4 = OpCopy v3 : i32
Ret
}
`
if got != want {
t.Errorf("add lowering mismatch.\n--want--\n%s\n--got--\n%s", want, got)
}
// Spot-check a few others we expect to lower cleanly: arithmetic,
// shifts, comparisons, rotation, and trapping division.
tryLower := func(t *testing.T, name string, wantUnsupported bool) {
t.Helper()
idx := ^uint32(0)
for _, e := range mod.Exports {
if e.Kind == wasm.ExportFunc && e.Name == name {
idx = e.Index
break
}
}
if idx == ^uint32(0) {
t.Fatalf("missing export %q", name)
}
_, err := LowerFunction(mod, idx, name, testThrowSet(mod))
switch {
case err == nil && wantUnsupported:
t.Fatalf("%s: expected ErrSSAUnsupported, got nil", name)
case err != nil && !wantUnsupported:
t.Fatalf("%s: unexpected error: %v", name, err)
case err != nil && wantUnsupported && !errors.Is(err, ErrSSAUnsupported):
t.Fatalf("%s: expected ErrSSAUnsupported, got %v", name, err)
}
}
tryLower(t, "sub", false)
tryLower(t, "mul64", false)
tryLower(t, "shifts", false)
tryLower(t, "lt_s", false)
tryLower(t, "lt_u", false)
tryLower(t, "rotl", false)
tryLower(t, "div_s", false)
}
// dumpSSAFunc is a thin wrapper around ssa.FuncString so tests don't
// need to import the ssa package directly.
func dumpSSAFunc(f interface{}) string {
type stringer interface{ String() string }
if s, ok := f.(stringer); ok {
return s.String()
}
// f is *ssa.Func; call via reflection-free path through the
// codegen package's helper.
return ssaFuncString(f)
}
// ssaFuncString is implemented in lower.go as a thin wrapper around
// ssa.FuncString so we keep the dependency on internal/ssa internal to
// this file pair (no test-side import of internal/ssa).
var _ = ssaFuncString // referenced by dumpSSAFunc
// TestLowerThrow lowers the $throwing function of eh_trycatch.wat
// (`i32.const 7; throw $e`) and checks the branch-based `throw` lowering:
// the tag and its operand are written into the module's exception state
// (OpExcRaise) and the block branches on to a propagating return.
func TestLowerThrow(t *testing.T) {
bin := testfixture.Wasm(t, "eh_trycatch")
mod, err := wasm.Parse(bytes.NewReader(bin))
if err != nil {
t.Fatalf("parse: %v", err)
}
// $throwing is the first defined function (no imports in the fixture).
fn, err := LowerFunction(mod, 0, "throwing", testThrowSet(mod))
if err != nil {
t.Fatalf("lower throwing: %v", err)
}
dump := dumpSSAFunc(fn)
if !bytes.Contains([]byte(dump), []byte("OpExcRaise")) {
t.Errorf("expected an OpExcRaise for the throw, got:\n%s", dump)
}
// Nothing catches it here, so the function must still return (with the
// flag left set for the caller's post-call check).
if !bytes.Contains([]byte(dump), []byte("Ret")) {
t.Errorf("expected a propagating return after the raise, got:\n%s", dump)
}
}
// TestLowerTryCatch lowers $catching (try/catch/catch_all with an i32 result)
// and checks the TryRegion metadata: a protected body plus two handlers (a
// tagged catch and a catch_all), all merging into a post block.
func TestLowerTryCatch(t *testing.T) {
bin := testfixture.Wasm(t, "eh_trycatch")
mod, err := wasm.Parse(bytes.NewReader(bin))
if err != nil {
t.Fatalf("parse: %v", err)
}
fn, err := LowerFunction(mod, 1, "catching", testThrowSet(mod)) // $catching
if err != nil {
t.Fatalf("lower catching: %v", err)
}
if len(fn.TryRegions) != 1 {
t.Fatalf("TryRegions: got %d, want 1", len(fn.TryRegions))
}
tr := fn.TryRegions[0]
if tr.Entry == nil || tr.Post == nil {
t.Fatalf("TryRegion Entry/Post must be set: %+v", tr)
}
if len(tr.Handlers) != 2 {
t.Fatalf("handlers: got %d, want 2 (catch + catch_all)", len(tr.Handlers))
}
if tr.Handlers[0].CatchAll {
t.Errorf("handler[0] should be a tagged catch, got catch_all")
}
if tr.Handlers[0].NumArgs != 1 {
t.Errorf("handler[0] (catch $e) NumArgs: got %d, want 1", tr.Handlers[0].NumArgs)
}
if !tr.Handlers[1].CatchAll {
t.Errorf("handler[1] should be catch_all")
}
// The tagged handler must materialise the exception operand as OpCatchArg.
dump := dumpSSAFunc(fn)
if !bytes.Contains([]byte(dump), []byte("OpCatchArg")) {
t.Errorf("expected OpCatchArg for the catch operand, got:\n%s", dump)
}
}
// TestLowerTryLocalsAreSSA lowers $withlocal, a try-function that sets a local
// before the try and reads it in the body and the catch handler. Under
// branch-based EH a handler is reached by a real CFG edge, so locals are
// ordinary SSA values — the de-SSA "mutable locals" mode panic/recover needed
// (OpLocalGet/OpLocalSet surviving into the IR) is gone.
func TestLowerTryLocalsAreSSA(t *testing.T) {
bin := testfixture.Wasm(t, "eh_trycatch")
mod, err := wasm.Parse(bytes.NewReader(bin))
if err != nil {
t.Fatalf("parse: %v", err)
}
fn, err := LowerFunction(mod, 4, "withlocal", testThrowSet(mod)) // $withlocal
if err != nil {
t.Fatalf("lower withlocal: %v", err)
}
dump := dumpSSAFunc(fn)
if bytes.Contains([]byte(dump), []byte("OpLocalGet")) || bytes.Contains([]byte(dump), []byte("OpLocalSet")) {
t.Errorf("locals should be promoted to SSA in an EH function, got:\n%s", dump)
}
if fn.MutableLocals {
t.Errorf("MutableLocals should stay false")
}
if len(fn.TryRegions) != 1 {
t.Errorf("TryRegions: got %d, want 1", len(fn.TryRegions))
}
}