The 8x Inefficiency of "Let the Compiler Optimize It": Inside Go's SSA and netip.Addr
When high-throughput network daemons process NetFlow records or BGP telemetry at line rate, converting an IPv4 address to its IPv4-mapped IPv6 representation...
When high-throughput network daemons process NetFlow records or BGP telemetry at line rate, converting an IPv4 address to its IPv4-mapped IPv6 representation occurs millions of times per second. In the Go standard library, netip.Addr provides an Unmap() method to strip the prefix from an IPv4-mapped address, but deliberately omits any reverse Map() or To6() method. When issue #51833 proposed adding Addr.To6(), standard library maintainers declined it on the premise that callers should write netip.AddrFrom16(ip.As16()) and rely on the Go compiler to optimize the sequence into a trivial register update.
That optimization never arrived. In Go 1.26 and 1.27, the idiomatic AddrFrom16(ip.As16()) call chain runs roughly eight times slower than a direct internal field write, burning 7.14 nanoseconds versus 0.88 nanoseconds per operation on modern x86-64 hardware. At 10 million packet evaluations per second, that performance differential translates directly to 62 milliseconds of wasted CPU time every second on stack spilling and redundant byte swapping.
The gap exposes a recurring failure mode in language ecosystem design: shifting mechanical complexity from a four-line standard library method into the compiler's Static Single Assignment (SSA) optimization pipeline. When SSA pass ordering prevents the backend from proving that a store-load pair is an identity transform, the resulting machine code litters hot loops with stack frames and vector copies.
The Standard Library Trap: When AddrFrom16(As16()) Costs 7 Nanoseconds
The net/netip package was introduced in Go 1.18 to replace the older, allocation-heavy net.IP slice representation. Under the hood, netip.Addr is defined as an immutable value type fitting into two 64-bit integer words and a pointer-sized interned handle:
type Addr struct {
addr uint128
z unique.Handle[addrDetail]
}
type addrDetail struct {
isV6 bool
zoneV6 string
}
var (
z0 unique.Handle[addrDetail]
z4 = unique.Make(addrDetail{})
z6noz = unique.Make(addrDetail{isV6: true})
)
Every IPv4 address in netip.Addr is internally encoded as an IPv4-mapped IPv6 address within the 128-bit integer, with the upper 64 bits set to zero and the lower 64 bits holding 0xffff00000000 bitwise OR-ed with the 4-byte address. The distinction between an IPv4 address and an IPv6 address lives entirely in the z field. An IPv4 address holds z4, while an IPv6 address without a zone holds z6noz.
Because of this uniform internal representation, converting an IPv4 address to an IPv4-mapped IPv6 address requires exactly one mechanical modification: replacing the z4 handle with z6noz. The 128-bit payload remains completely untouched. The standard library already exploits this exact symmetry in reverse inside Unmap():
func (ip Addr) Unmap() Addr {
if ip.Is4In6() {
ip.z = z4
}
return ip
}
If an internal To6() method existed, its implementation would mirror Unmap() with zero heap allocations and three CPU instructions:
func (ip Addr) To6() Addr {
if ip.Is4() {
ip.z = z6noz
}
return ip
}
Instead, external callers must use public APIs. The idiomatic approach chains As16() to dump the address into a 16-byte array, followed by AddrFrom16() to reconstruct the struct. A secondary approach uses the unsafe package to overlay a struct layout and reassign z directly:
type addrProxy struct {
addr [2]uint64
z unsafe.Pointer
}
var netipZ6noz = (*addrProxy)(unsafe.Pointer(&anyIPv6)).z
func AddrTo6Unsafe(ip netip.Addr) netip.Addr {
if !ip.Is4() {
return ip
}
(*addrProxy)(unsafe.Pointer(&ip)).z = netipZ6noz
return ip
}
Benchmarking these three strategies on an AMD Ryzen 5 5600X under Go 1.27.1 demonstrates the operational penalty of the idiomatic pattern:
- AddrTo6Safe (AddrFrom16 + As16): 7.137 ns/op, 0 B/op, 0 allocs/op
- AddrTo6Unsafe (unsafe.Pointer proxy): 0.868 ns/op, 0 B/op, 0 allocs/op
- AddrTo6Builtin (Standard library patch): 0.878 ns/op, 0 B/op, 0 allocs/op
The safe function costs 8.1 times more CPU execution time than the native or unsafe alternatives. To understand why an inlineable 16-byte copy incurs such an overhead, we must inspect the disassembly generated by cmd/compile.
Dissecting the Assembly: Why MOVBEQ Leaves Stack Baggage
Both As16() and AddrFrom16() are small enough to satisfy the compiler's inlining budget. When AddrTo6Safe is compiled, the compiler inlines both function bodies directly into the caller:
func AddrTo6Safe(input netip.Addr) netip.Addr {
if !input.Is4() {
return input
}
var a16 [16]byte
byteorder.BEPutUint64(a16[:8], input.addr.hi)
byteorder.BEPutUint64(a16[8:], input.addr.lo)
addr := a16
var output netip.Addr
output.addr.hi = byteorder.BEUint64(addr[:8])
output.addr.lo = byteorder.BEUint64(addr[8:])
output.z = netip.z6noz
return output
}
To an engineer reading this inlined logic, the optimization opportunity is obvious. Storing a 64-bit word in big-endian order and immediately reading it back as a big-endian word is mathematically an identity operation. The entire byte-packing dance should collapse into output.addr = input.addr, keeping values strictly inside CPU registers without touching RAM or the stack.
When compiling this code under Go 1.26.8 with GOAMD64=v3, the compiler produces assembly that reveals deep optimization limitations:
// AX = input.addr.hi, BX = input.addr.lo, CX = input.z
PUSHQ BP
MOVQ SP, BP
SUBQ $32, SP
CMPQ net/netip.z4(SB), CX
JNE end
// Pack: byteorder.BEPutUint64
MOVBEQ AX, 16(SP)
MOVBEQ BX, 24(SP)
// Inter-buffer copy: addr = a16 via SSE register
MOVUPS 16(SP), X0
MOVUPS X0, 0(SP)
// Swap z handle
MOVQ net/netip.z6noz(SB), CX
// Unpack: byteorder.BEUint64
MOVBEQ 0(SP), AX
MOVBEQ 8(SP), BX
end:
ADDQ $32, SP
POPQ BP
RET
The compiler successfully lowers BEPutUint64 and BEUint64 into MOVBEQ instructions (move big-endian quadword), avoiding multi-instruction bit-shift sequences. However, it fails to connect the store with the subsequent load. Instead, it allocates a 32-byte frame on the stack, performs two byte-swapped writes to memory, executes a 16-byte vector transfer via MOVUPS across stack slots, and then executes two byte-swapped reads back into AX and BX.
Contrast this with the assembly generated for AddrTo6Builtin or the unsafe variant:
// AX = input.addr.hi, BX = input.addr.lo, CX = input.z
CMPQ net/netip.z4(SB), CX
JNE end
MOVQ net/netip.z6noz(SB), CX
end:
RET
The built-in version requires no stack pointer adjustment, zero memory reads or writes, and no register clobbering. The safe pattern wastes cycles because the compiler cannot prove that the data read from 0(SP) is identical to the data written to 16(SP) after passing through vector register X0.
The AST Noder Hack: Injecting Syntactic Sugar Too Early
To eliminate this assembly bloat, the most direct strategy is to teach the Go compiler to rewrite the call pattern during frontend processing. In Go's compiler architecture, source code transitions through five major stages:
- Syntax Parser: Tokenizes source code into an Abstract Syntax Tree (AST).
- Type Checker: Resolves identifiers, computes types, and validates exported boundaries.
- Noder / IR Construction: Translates typed AST nodes into the compiler's unified Intermediate Representation (IR).
- Middle End: Executes inlining, escape analysis, and dead-code elimination.
- Generic SSA: Lowers IR into Static Single Assignment form for machine-independent and machine-dependent optimization passes.
A frontend prototype implemented by Vincent Bernat intercepted the pattern inside the noder (cmd/compile/internal/noder/reader.go). In the exprCall evaluation branch, a custom hook detected whenever netip.AddrFrom16() took netip.Addr.As16() as its single argument:
func rewriteAddrFrom16As16(n ir.Node) ir.Node {
call, ok := n.(*ir.CallExpr)
if !ok || call.Op() != ir.OCALLFUNC || len(call.Args) != 1 || !isNetipFunc(call.Fun, "AddrFrom16") {
return nil
}
inner, ok := call.Args[0].(*ir.CallExpr)
if !ok || inner.Op() != ir.OCALLFUNC || len(inner.Args) != 1 || !isNetipFunc(inner.Fun, "Addr.As16") {
return nil
}
x := inner.Args[0] // original netip.Addr receiver
z6noz, err := lookupVar(ir.StaticCalleeName(call.Fun).Sym().Pkg, "z6noz")
if err != nil {
return nil
}
pos := call.Pos()
fields := []ir.Node{
ir.NewStructKeyExpr(pos, fieldAddr, typecheck.DotField(pos, x, 0)),
ir.NewStructKeyExpr(pos, fieldZ, z6noz),
}
lit := ir.NewCompLitExpr(pos, ir.OSTRUCTLIT, call.Type(), fields)
lit.SetTypecheck(1)
return lit
}
This noder hook transforms the function call into a direct struct composite literal during IR construction. The compiler emitted identical assembly to the built-in standard library function, dropping execution time to 0.88 nanoseconds.
Yet compiler maintainers will never merge such a patch. The noder's sole responsibility is faithful translation of type-checked AST into IR. Injecting standard-library-specific hacks into the noder bypasses visibility controls to read unexported struct fields (addr and z), tightly coupling the compiler core to package-private implementation details.
The Generic SSA Wall: Why memcombine Misses the Late Opt Window
The architecturally sound location for low-level memory and register optimizations is the Generic SSA stage in cmd/compile/internal/ssa. In this pipeline, the compiler applies machine-independent rewrite rules to simplify arithmetic, eliminate dead stores, and merge contiguous memory operations.
One of the critical optimization passes in this phase is memcombine. The pass scans sequences of byte and word loads or stores to merge them into single 32-bit or 64-bit operations, leveraging hardware capabilities such as unaligned access and byte-swapped instructions. The execution order of Go's SSA passes is strictly linear:
- Early Opt: Applies core rewrite rules to simplify basic expressions.
- Memcombine: Merges adjacent small loads and stores into wider operations.
- Late Opt: Executes copy propagation, dead-code pruning, and pointer move-forwarding.
- Lowering: Rewrites generic SSA primitives into target-specific machine instructions.
The compiler fails to optimize AddrTo6Safe due to a classic compiler phase-ordering hazard. When memcombine executes, the intermediate copy between a16 and addr still exists as an explicit memory transfer. The compiler cannot yet prove that the memory location read by BEUint64 contains the exact bytes stored by BEPutUint64 because the vector copy separates them.
During the subsequent late opt pass, copy propagation simplifies the stack addresses. However, because memcombine has already completed, the compiler cannot loop backward to merge the now-adjacent store and load instructions. The byte-swapped writes and reads remain pinned to the stack frame.
To test this hypothesis, Vincent Bernat modified the SSA compiler schedule to run an additional memcombine pass immediately before late opt. Rebuilding the toolchain and compiling the unpatched AddrTo6Safe code yielded immediate results:
// Assembly generated with reordered memcombine
// AX = input.addr.hi, BX = input.addr.lo, CX = input.z
CMPQ net/netip.z4(SB), CX
JNE end
MOVQ net/netip.z6noz(SB), CX
end:
RET
With the additional pass in place, the compiler recognized the byte-swap store followed by the byte-swap load as a redundant identity cycle. It eliminated the entire 32-byte stack frame, pruned the vector register instructions, and matched the native implementation. Benchmarks confirmed parity:
goos: linux goarch: amd64
cpu: AMD Ryzen 5 5600X 6-Core Processor
Go 1.26.8 SSA Patched Branch
AddrTo6/safe 6.547 ns/op 0.894 ns/op (-86.34%)
AddrTo6/unsafe 0.907 ns/op 0.868 ns/op (-4.28%)
AddrTo6/builtin 0.887 ns/op 0.878 ns/op (~0%)
Despite this 86% latency drop, Go maintainers are hesitant to accept extra SSA passes. Unlike LLVM, which trades aggressive multi-second compile times for peak runtime performance, the Go compiler prioritizes compilation speed as a core language constraint. Adding an SSA pass traverses the entire function graph for every compiled function across every package, imposing a universal compile-time tax on millions of Go builds worldwide to benefit a narrow standard library idiom.
The Cost of API Minimalism: When Language Dogma Shifts Burden to Users
The impasse around Addr.To6() illustrates the operational friction generated when API minimalism overrides mechanical efficiency. By declining issue #51833, standard library maintainers defended a minimal public API surface at the expense of systems engineers running packet-processing pipelines.
High-throughput network services cannot absorb an 8x latency penalty on a function invoked in per-packet ingress paths. When the compiler fails to optimize an approved idiom, engineers are forced into three undesirable workarounds:
- Accept Performance Regressions: Absorb 7.14 nanoseconds per conversion, consuming valuable CPU headroom in 10GbE and 40GbE network gateways.
- Maintain Unsafe Struct Proximities: Deploy
unsafe.Pointercasts againstnetip.Addr. This pattern works at 0.87 nanoseconds but introduces catastrophic fragility. When Go 1.24 alterednetip.Addrby migrating internal pointers fromintern.Valuetounique.Handle, code relying on unverified memory offsets broke without warning. - Build Toolchain Overlays: Use the
-overlayflag ingo buildto substitute patched standard library files during compilation. While functionally viable, overlays require absolute path mappings in GOROOT and fail to integrate cleanly with developer tooling and language servers.
The assumption that "the compiler will optimize it eventually" is an unhedged operational promise. Compiler optimizations that require cross-pass SSA reordering or multi-stage store-to-load forwarding are notoriously difficult to implement, prone to regressions across minor toolchain releases, and often rejected to preserve compiler throughput. Issue #81994 reopens the proposal for a dedicated netip.Addr.To6() method. Providing four lines of explicit code in the standard library remains vastly more practical than expecting an SSA compiler to turn backflips around an unexported handle.