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]>
155 lines
5.1 KiB
Go
155 lines
5.1 KiB
Go
// Package gcasm implements the gc-capture asm backend: the pure-Go
|
|
// output is compiled by the Go compiler at BUNDLE GENERATION time,
|
|
// the `-S` listing is captured, and a mechanical, deterministic
|
|
// transform turns it into shippable Plan9 .s files. Consumers get
|
|
// gc-quality function bodies at assembler-only build cost.
|
|
//
|
|
// Determinism contract (the generator must be idempotent): for a
|
|
// fixed toolchain and fixed input source, the emitted .s is
|
|
// byte-identical across runs. Everything the transform iterates is
|
|
// sorted, labels derive from instruction offsets, and no paths,
|
|
// timestamps, or map-order artifacts reach the output.
|
|
package gcasm
|
|
|
|
// ArgKind is the width/class of one ABI value.
|
|
type ArgKind int
|
|
|
|
const (
|
|
ArgPtr ArgKind = iota // pointer-sized integer register (e.g. *Module)
|
|
ArgI32 // SIGNED 32-bit (sign-extended in registers)
|
|
ArgU32 // UNSIGNED 32-bit (zero-extended in registers)
|
|
ArgI64
|
|
ArgF32
|
|
ArgF64
|
|
// ArgV128 is a [2]uint64 (a wasm v128 value). ABIInternal never
|
|
// register-assigns arrays, so v128 params and results are always
|
|
// stack-assigned on both sides — the call marshal copies 16 bytes.
|
|
ArgV128
|
|
)
|
|
|
|
// amd64 ABIInternal register sequences (go/src/cmd/compile/abi-internal.md).
|
|
var amd64IntArgRegs = []string{"AX", "BX", "CX", "DI", "SI", "R8", "R9", "R10", "R11"}
|
|
var amd64FloatArgRegs = []string{"X0", "X1", "X2", "X3", "X4", "X5", "X6", "X7",
|
|
"X8", "X9", "X10", "X11", "X12", "X13", "X14"}
|
|
|
|
// RegAssignment describes where one value lives under ABIInternal
|
|
// and where its ABI0 stack slot sits.
|
|
type RegAssignment struct {
|
|
Kind ArgKind
|
|
Reg string // ABIInternal register; "" when stack-assigned
|
|
StackOf int // ABI0 FP-relative offset (args) or SP-relative (outgoing)
|
|
// SeqOf is the ABIInternal stack-argument sequence offset, valid
|
|
// only when Reg == "". At an ABIInternal call site the caller
|
|
// writes such a value to SeqOf(SP); the callee reads it above its
|
|
// frame. The transform's call marshal copies it from there into
|
|
// the ABI0 slot.
|
|
SeqOf int
|
|
}
|
|
|
|
// AssignABIInternal maps a signature's params (and the single
|
|
// optional result) to ABIInternal registers, mirroring gc's
|
|
// assignment for the integer/float sequences. Params beyond the
|
|
// register file are stack-assigned (Reg == "", SeqOf set) — callers
|
|
// marshal those from the captured outgoing sequence; functions whose
|
|
// OWN signature stack-assigns are not transformed (pure fallback),
|
|
// which Transform enforces by rejecting Reg=="" among opts.Params.
|
|
func AssignABIInternal(params []ArgKind, hasResult bool, result ArgKind) (args []RegAssignment, res *RegAssignment, err error) {
|
|
intN, fltN := 0, 0
|
|
stackOff := 0
|
|
seqOff := 0
|
|
align := func(n, a int) int { return (n + a - 1) &^ (a - 1) }
|
|
for _, k := range params {
|
|
var ra RegAssignment
|
|
ra.Kind = k
|
|
sz, al := 8, 8
|
|
switch k {
|
|
case ArgI32, ArgU32, ArgF32:
|
|
sz, al = 4, 4
|
|
case ArgV128:
|
|
sz = 16
|
|
}
|
|
isFloat := k == ArgF32 || k == ArgF64
|
|
switch {
|
|
case k == ArgV128:
|
|
// Never register-assigned; always the stack sequence.
|
|
seqOff = align(seqOff, al)
|
|
ra.SeqOf = seqOff
|
|
seqOff += sz
|
|
case isFloat && fltN < len(amd64FloatArgRegs):
|
|
ra.Reg = amd64FloatArgRegs[fltN]
|
|
fltN++
|
|
case !isFloat && intN < len(amd64IntArgRegs):
|
|
ra.Reg = amd64IntArgRegs[intN]
|
|
intN++
|
|
default:
|
|
// ABIInternal stack sequence (natural alignment, starts
|
|
// at the caller's 0(SP) at call time).
|
|
seqOff = align(seqOff, al)
|
|
ra.SeqOf = seqOff
|
|
seqOff += sz
|
|
}
|
|
stackOff = align(stackOff, al)
|
|
ra.StackOf = stackOff
|
|
stackOff += sz
|
|
args = append(args, ra)
|
|
}
|
|
if hasResult {
|
|
// ABI0 places the results area at the next POINTER-aligned
|
|
// offset after the arguments, regardless of the result's own
|
|
// alignment (go vet asmdecl enforces this: `(int32) int32`
|
|
// is $...-12 with the result at +8, not +4).
|
|
r := RegAssignment{Kind: result}
|
|
stackOff = align(stackOff, 8)
|
|
r.StackOf = stackOff
|
|
switch result {
|
|
case ArgV128:
|
|
// Stack result on both sides: the ABIInternal caller reads
|
|
// it from its outgoing sequence right after the stack args.
|
|
r.SeqOf = align(seqOff, 8)
|
|
case ArgF32, ArgF64:
|
|
r.Reg = "X0"
|
|
default:
|
|
r.Reg = "AX"
|
|
}
|
|
res = &r
|
|
}
|
|
return args, res, nil
|
|
}
|
|
|
|
// StoreFor returns the Plan9 mnemonic for a register→memory move of
|
|
// a value class (width only — stores never extend).
|
|
func StoreFor(k ArgKind) string {
|
|
switch k {
|
|
case ArgPtr, ArgI64:
|
|
return "MOVQ"
|
|
case ArgI32, ArgU32:
|
|
return "MOVL"
|
|
case ArgF32:
|
|
return "MOVSS"
|
|
case ArgF64:
|
|
return "MOVSD"
|
|
}
|
|
return "MOVQ"
|
|
}
|
|
|
|
// LoadFor returns the Plan9 mnemonic for a memory→register move of a
|
|
// value class. ABIInternal requires narrow integers to be EXTENDED to
|
|
// the full register — sign-extended for int32, zero-extended for
|
|
// uint32 — and captured code downstream of an argument or call result
|
|
// relies on that (64-bit compares, indexing with negative i32).
|
|
func LoadFor(k ArgKind) string {
|
|
switch k {
|
|
case ArgPtr, ArgI64:
|
|
return "MOVQ"
|
|
case ArgI32:
|
|
return "MOVLQSX"
|
|
case ArgU32:
|
|
return "MOVL" // MOVL zero-extends to 64 bits
|
|
case ArgF32:
|
|
return "MOVSS"
|
|
case ArgF64:
|
|
return "MOVSD"
|
|
}
|
|
return "MOVQ"
|
|
}
|