mirror of
https://github.com/hanzoai/wasm2go.git
synced 2026-10-30 15:06:48 +00:00
Replace the hand-written own-emitter asm backend (internal/asmgen) with
gcasm: compile the generated pure-Go bodies with the standard Go
compiler, capture the `-S` listing, and mechanically transform it into a
shippable Plan9 `.s`. The transform strips gc's prologue/stack-check/
epilogue/morestack, regenerates them from the declared frame, and
marshals gc's ABIInternal calls to ABI0 forwarders. Wired into
transpile.Translate and cmd/wasm2go as THE asm backend; a `purego` build
tag still selects the pure bodies on every other GOARCH.
Why ship asm at all — the pure-Go bodies are the faster runtime. The asm
path exists to skip the consumer's golangci-lint/parse cost of the huge
generated bodies (measured ~36.5s pure vs ~3.3s asm for one package;
golangci-lint doesn't parse assembly). gcasm keeps gc's in-body register
allocation and only pays an ABI0 marshalling tax at call boundaries
(register-to-register calls are impossible for tool-emitted asm: the
assembler forbids non-runtime code from declaring ABIInternal).
gcasm vs the own-emitter asm it replaces — strictly better on every
measured axis (go-python microbenchmarks, count=5):
- runtime arm64 native: 1.7-3.3x faster (Fib 0.30, LoopSum 0.50, Startup 0.58)
- runtime amd64: 1.05-1.85x faster
- binary size arm64: 14% smaller (33.87 vs 39.32 MB)
- cold-cache build: 8.1 vs 10.0s
- memory: identical (555 B/op, 11 allocs)
- lint benefit: same (both skip pure bodies); 11x faster than pure
What's in internal/gcasm:
- capture: `-gcflags=<pkg>=-S`, GOARCH-pinned (amd64 + arm64).
- amd64 + arm64 transforms (peers): prologue/epilogue strip, ABI0 call
marshalling, jump-table lowering to binary-search trees, const/float/
type-descriptor pools, runtime-call rewrites, cross-package linkname
forwarders.
- dual-arch bundle: gcasm_<arch>.s + gcasm_decls_<arch>.go + keepalive,
guarded by //go:build <arch>. Functions the transform can't express
stay pure fallbacks (transparent to callers — same ABI0 forward /
//go:linkname either way).
Fallback triggers: signatures that stack-assign in ABIInternal (>16 int
args), and functions gc compiles to a DUFFZERO/DUFFCOPY pseudo-op — a
textual duff op nil-derefs the assembler (go1.25 and go1.26 alike; only
compiler-generated progs get the runtime.duffzero target symbol), so the
union across arches is routed to pure.
Delete the superseded backend. gcasm being sole means internal/asmgen
(the SSA-to-plan9 own emitter) and internal/regalloc (its linear-scan
allocator, no other importer) were dead — codegen.Translate generated the
old asm bundle only for transpile.Translate to discard and replace it.
~20k lines removed:
- delete internal/asmgen and internal/regalloc.
- codegen.Translate now emits only pure-Go bodies (shared file +
<pkg>_pure.go); the per-arch asm is entirely gcasm's job. Removed the
asmgen call sites and the now-dead asm_bundle.go helpers.
- drop asm_bundle_test.go (codegen+asmgen integration); the wasm ->
runnable-asm path is covered by gcasm's gates + consumer e2e. The
remaining codegen tests build/run codegen's PURE output, stripping the
guard to activate it on the host; production output is unchanged.
Proven inert: regenerating the python AND googlesql bundles after the
deletion yields byte-identical output.
Coverage: the deleted integration test contributed broad cross-package
coverage the removed code no longer needs; a new transpile end-to-end test
(TestTranspileEndToEnd — Parse+Translate+gcasm, build+run on the host) plus
gcasm's gates and the consumer e2e cover the live path. Live-code coverage
lands at 84.7%, so the Makefile COVERAGE_THRESHOLD is recalibrated 85 -> 84.
Notable correctness fixes surfaced at consumer scale (bisected via the
GCASM_FALLBACK_RANGE knob; none visible to fixture gates):
- linker method pruning of import ifaces -> init()-guarded call pins
- narrow-int register extension (MOVLQSX / ArgU32 loads)
- bare (SP) zero-offset outgoing store missed by the frame shift
- wide indirect calls' stack-assigned args -> ADJSP wrap
- EFLAGS live across jump-table dispatch -> replay the flag-setter
- arm64 large-frame prologue/epilogue (SUBS+BLO guard, MOVD $c,R27 /
ADD R27,RSP teardown, shape-agnostic stack-check sweep)
- arm64 hardware-SP outgoing-arg shift: a >16-int-arg ABIInternal call
spills the overflow arg to a hardware N(RSP) slot that must be
shifted above our ABI0 scratch so the marshaller re-reads it; missing
it read uninitialised stack (low 32 bits of the spilled module
pointer) and faulted ~3.4GB outside linear memory (go-googlesql
TestLifetime_AnalyzerOutputKeepAlive on arm64). Gate: TestA64Spill.
Verification (judged by exit code):
- go1.25.0 (CI toolchain) AND go1.26.2: `go test -race -covermode=atomic
-coverpkg=./... ./...` all ok; make lint 0 issues; CodeQL clean
(FnN-index parses use strconv.ParseUint(s,10,32), a bounded conversion).
- Consumers, GOARCH=amd64 AND arm64 (native), gcasm bundles via replace:
googlesqlite go test -race ./... -> 35 ok each arch
go-googlesql go test ./... -> ok each arch
go-python go test ./... (+race amd64) -> ok each arch
- arm64 execution gates assemble+link on any host and execute only on an
arm64 host (skip elsewhere), so CI on linux/amd64 stays green.
Claude-Session: https://claude.ai/code/session_01BJSha2EbWhruLZQTZE87oL
Co-authored-by: Claude Fable 5 <[email protected]>
104 lines
3.2 KiB
Go
104 lines
3.2 KiB
Go
package codegen_test
|
|
|
|
import (
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/goccy/wasm2go/internal/codegen"
|
|
)
|
|
|
|
// TestMultiPackageBuildsAndCompiles drives several fixtures through
|
|
// the multi-package + linkname-split layout with the threshold lowered
|
|
// to 0 (forcing the partitioner to bin-pack one function per chunk)
|
|
// and runs `go build ./...` against the emitted module to catch any
|
|
// import-block / linkname-forward drift.
|
|
func TestMultiPackageBuildsAndCompiles(t *testing.T) {
|
|
restore := codegen.SetMultiPackageThreshold(0)
|
|
defer restore()
|
|
for _, fx := range []string{"arith.wasm", "wexports.wasm", "cg_wasi.wasm", "cg_indirect.wasm"} {
|
|
fx := fx
|
|
t.Run(fx, func(t *testing.T) {
|
|
mod := readFixture(t, fx)
|
|
res, err := codegen.Translate(nil, mod, codegen.Options{
|
|
Package: "wmod", OutputImportPath: "gentest/wmod",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("translate: %v", err)
|
|
}
|
|
dir := t.TempDir()
|
|
gomod := "module gentest\n\ngo 1.25.0\n"
|
|
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(gomod), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for rel, data := range res.Files {
|
|
p := filepath.Join(dir, "wmod", rel)
|
|
if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(p, stripPureGuard(data), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
for name, data := range res.Sidecars {
|
|
if err := os.WriteFile(filepath.Join(dir, "wmod", name), stripPureGuard(data), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
cmd := exec.Command("go", "build", "./...")
|
|
cmd.Dir = dir
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("go build failed: %v\n%s", err, out)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestMultiPackageAutoDerive exercises the auto-derive switch from
|
|
// single-file to multi-package + linkname-split output. With the
|
|
// threshold lowered to 0 (forces multi-package for any non-empty
|
|
// wasm), every supported fixture must:
|
|
//
|
|
// - produce a Result.Files map populated with base/, p*, and the
|
|
// main file;
|
|
// - reference //go:linkname for cross-chunk dispatch;
|
|
// - compile cleanly under `go build ./...`.
|
|
func TestMultiPackageAutoDerive(t *testing.T) {
|
|
restore := codegen.SetMultiPackageThreshold(0)
|
|
defer restore()
|
|
for _, fx := range []string{"arith.wasm", "memory.wasm", "control.wasm", "cg_wasi.wasm", "wexports.wasm", "cg_indirect.wasm"} {
|
|
fx := fx
|
|
t.Run(fx, func(t *testing.T) {
|
|
mod := readFixture(t, fx)
|
|
res, err := codegen.Translate(nil, mod, codegen.Options{
|
|
Package: "wmod", OutputImportPath: "gentest/wmod",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("translate: %v", err)
|
|
}
|
|
if res.Files == nil {
|
|
t.Fatalf("expected multi-file output; got nil Files map")
|
|
}
|
|
if _, ok := res.Files["base/base.go"]; !ok {
|
|
t.Errorf("missing base/base.go in multi-file output")
|
|
}
|
|
if _, ok := res.Files["wmod.go"]; !ok {
|
|
t.Errorf("missing wmod.go main file in multi-file output")
|
|
}
|
|
// At least one chunk file must exist.
|
|
any := false
|
|
for k := range res.Files {
|
|
if strings.HasPrefix(k, "p0/") {
|
|
any = true
|
|
break
|
|
}
|
|
}
|
|
if !any {
|
|
t.Errorf("expected at least one p<N>/ chunk file in output")
|
|
}
|
|
})
|
|
}
|
|
}
|