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

161 lines
4.6 KiB
Go

package pass
import (
"github.com/goccy/wasm2go/internal/ssa"
)
// matchF16IdiomBits is the general matcher: the sign chain's source w
// is either i32_reinterpret_f32(f) — then fv = f — or the raw i32
// bits value itself (the wasm commonly extracts float lanes as i32
// bits); then fv is nil and the caller works from w. In the bits form
// the arithmetic arm references f32_reinterpret_i32(w) as the float.
func matchF16IdiomBits(phi, signChain *ssa.Value) (fvOut, wOut *ssa.Value, ok bool) {
if phi.Op != ssa.OpPhi || len(phi.Args) != 2 {
return nil, nil, false
}
// sign chain: (w >> 16) & 0x8000
w := matchAndShr(signChain, 16, 0x8000)
if w == nil {
return nil, nil, false
}
var fv *ssa.Value
if isHelper(w, "i32_reinterpret_f32") && len(w.Args) == 1 && w.Args[0].Type == ssa.TypeF32 {
fv = w.Args[0]
}
floatOfW := func(x *ssa.Value) bool {
if fv != nil {
return x == fv
}
return isHelper(x, "f32_reinterpret_i32") && len(x.Args) == 1 && x.Args[0] == w
}
// phi arms: one 0x7E00 constant (NaN), one arithmetic chain.
nanIdx := -1
for i, a := range phi.Args {
if isConst32(a, 0x7E00) {
nanIdx = i
}
}
if nanIdx == -1 {
return nil, nil, false
}
nonsign := phi.Args[1-nanIdx]
// nonsign = ((v>>13)&0x7C00) + (v&0xFFF), same v both sides.
if nonsign.Op != ssa.OpAdd32 || len(nonsign.Args) != 2 {
return nil, nil, false
}
var v *ssa.Value
for i := 0; i < 2; i++ {
hi, lo := nonsign.Args[i], nonsign.Args[1-i]
if x := matchAndShr(hi, 13, 0x7C00); x != nil && matchAnd(lo, 0xFFF) == x {
v = x
break
}
}
if v == nil || !isHelper(v, "i32_reinterpret_f32") || len(v.Args) != 1 {
return nil, nil, false
}
// v reinterprets base = mul-chain + reinterpreted bias. Float
// arithmetic lowers as helper calls (f32_add/f32_mul), not
// first-class SSA float ops.
base := v.Args[0]
if !isHelper(base, "f32_add") || len(base.Args) != 2 {
return nil, nil, false
}
okMul := func(m *ssa.Value) bool {
// (f32_abs(f) * 0x1p+112) * 0x1p-110, factors commutative.
if !isHelper(m, "f32_mul") || len(m.Args) != 2 {
return false
}
inner, c2 := m.Args[0], m.Args[1]
if isConstF32(inner, 0x08800000) {
inner, c2 = c2, inner
}
if !isConstF32(c2, 0x08800000) || !isHelper(inner, "f32_mul") || len(inner.Args) != 2 {
return false
}
abs, c1 := inner.Args[0], inner.Args[1]
if isConstF32(abs, 0x77800000) {
abs, c1 = c1, abs
}
// |f| arrives as f32_abs(f), or in the bits form as the sign
// bit cleared integrally: f32_reinterpret_i32(w & 0x7FFFFFFF).
absOK := isHelper(abs, "f32_abs") && len(abs.Args) == 1 && floatOfW(abs.Args[0])
if !absOK && isHelper(abs, "f32_reinterpret_i32") && len(abs.Args) == 1 {
absOK = matchAnd(abs.Args[0], 0x7FFFFFFF) == w
}
return isConstF32(c1, 0x77800000) && absOK
}
okBias := func(rb *ssa.Value) bool {
// f32_reinterpret_i32(((bias>>1) & 0x7F800000) + 0x07800000)
if !isHelper(rb, "f32_reinterpret_i32") || len(rb.Args) != 1 {
return false
}
add := rb.Args[0]
if add.Op != ssa.OpAdd32 || len(add.Args) != 2 {
return false
}
masked, c := add.Args[0], add.Args[1]
if isConst32(masked, 0x07800000) {
masked, c = c, masked
}
bias := matchAndShr(masked, 1, 0x7F800000)
if !isConst32(c, 0x07800000) || bias == nil {
return false
}
// bias = phi(0x71000000, shl1) with shl1 = w << 1 for OUR w.
if bias.Op != ssa.OpPhi || len(bias.Args) != 2 {
return false
}
var shl1 *ssa.Value
for i := 0; i < 2; i++ {
if isConst32(bias.Args[i], 0x71000000) {
shl1 = bias.Args[1-i]
}
}
return shl1 != nil && shl1.Op == ssa.OpShl32 && len(shl1.Args) == 2 &&
shl1.Args[0] == w && isConst32(shl1.Args[1], 1)
}
m0, m1 := base.Args[0], base.Args[1]
matched := (okMul(m0) && okBias(m1)) || (okMul(m1) && okBias(m0))
if !matched {
return nil, nil, false
}
return fv, w, true
}
func isConstF32(v *ssa.Value, bits int64) bool {
return v.Op == ssa.OpConstF32 && v.AuxInt == bits
}
func isHelper(v *ssa.Value, name string) bool {
if v.Op != ssa.OpHelperCall {
return false
}
n, _ := v.Aux.(string)
return n == name
}
// matchAndShr matches (x >> shift) & mask (operands commutative on
// the And) and returns x, or nil.
func matchAnd(v *ssa.Value, mask int64) *ssa.Value {
if v.Op != ssa.OpAnd32 || len(v.Args) != 2 {
return nil
}
a, c := v.Args[0], v.Args[1]
if isConst32(a, mask) {
a, c = c, a
}
if !isConst32(c, mask) {
return nil
}
return a
}
func matchAndShr(v *ssa.Value, shift, mask int64) *ssa.Value {
shr := matchAnd(v, mask)
if shr == nil || shr.Op != ssa.OpShrU32 || len(shr.Args) != 2 || !isConst32(shr.Args[1], shift) {
return nil
}
return shr.Args[0]
}