Files
5bd861b54c gcasm: gc-capture assembly backend (amd64 + arm64), replacing internal/asmgen (#19)
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]>
2026-07-06 21:01:27 +09:00

37 lines
1.4 KiB
Go

package gcasm
import (
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
)
// runArm64Gate assembles + links the generated arm64 test binary — which
// drives the emitted .s through the real Go assembler and linker, and so
// catches bad operands, undefined symbols, and frame/pcsp errors on ANY
// host arch — and then executes it ONLY when the host can run arm64
// binaries. A non-arm64 runner (e.g. linux/amd64 CI) cannot exec an arm64
// binary ("exec format error"), so there we assemble-verify and skip the
// value check. On an arm64 host (or `GOARCH=arm64 go test` on Apple
// Silicon) the binary runs natively and the asm-vs-pure parity is checked.
func runArm64Gate(t *testing.T, dir, pkg, runName, diag string) {
t.Helper()
bin := filepath.Join(dir, "gcasm_gate.test")
build := exec.Command("go", "test", "-c", "-o", bin, pkg)
build.Dir = dir
build.Env = append(os.Environ(), "GOARCH=arm64")
if out, err := build.CombinedOutput(); err != nil {
t.Fatalf("arm64 assemble/link failed: %v\n%s\n--- asm ---\n%s", err, out, diag)
}
if runtime.GOARCH != "arm64" {
t.Skipf("assembled+linked OK; skipping arm64 execution on %s/%s host", runtime.GOOS, runtime.GOARCH)
}
cmd := exec.Command(bin, "-test.run", runName, "-test.v")
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("arm64 execution failed: %v\n%s\n--- asm ---\n%s", err, out, diag)
}
}