hn.today

Hacking the Go compiler to efficiently map IPv4 to IPv6

vincent.bernat.ch6 points0 comments
Screenshot of Hacking the Go compiler to efficiently map IPv4 to IPv6

This explains why converting an IPv4 value into an IPv6 netip.Addr in Go is much slower when written as netip.AddrFrom16(ip.As16()) than a hypothetical native Map/To6 method, and shows how to teach the compiler to fold that idiom into a no-op copy. netip.Addr stores addresses as a 128-bit uint plus a small unique handle that encodes family/zone; AddrFrom4 constructs an IPv4-mapped IPv6 by storing bytes and setting a z4 handle. The convenient As16/AddrFrom16 chain currently emits stores, moves and byte-swaps in SSA and assembly, producing eight times the cost of a direct mapping.

The fix is to add SSA rewrite rules so the compiler recognizes and cancels the intermediate memory operations: a load through a Move, forwarding a Load past a prior Store to the same address, and eliminating paired Bswap64 operations. These rules rely on pointer-equality and disjointness checks (ssa.IsSamePtr, ssa.Disjoint) and size/type compatibility; variants that look through multiple stores already exist in generic.rules and Go 1.27 added load-through-move. Applying those three rewrites turns the complex SSA into two simple copies (input hi/lo copied to output hi/lo), restoring native performance without changing the standard library API.

Read on vincent.bernat.ch0 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.