/performant-golang:go-perf-bounds-check-eliminationfrom performant-golang
Guides bounds-check elimination (BCE) in Go — the compiler checks every slice/array index and the SSA pass removes the ones it proves redundant. Covers seeing surviving checks with go build -gcflags="-d=ssa/check_bce/debug=1", prover-friendly idioms (the _ = b[n-1] / b = b[:n] hint, range loops, constant vs variable offsets), the inlining link, and why -B is a footgun not a fix. Fires on "eliminate bounds checks", "why is this loop slow", "bounds check in hot loop", "optimize this numeric loop". Routes should-I to go-perf-methodology, slices to go-perf-slices.
Ships in performant-golang. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Go is memory-safe: every index b[i] and most slice expressions b[:n] carry an implicit runtime
check that panics on an out-of-range access. The SSA compiler runs a bounds-check elimination (BCE)
pass that proves many of those checks redundant and deletes them. This skill owns making that
pass visible and writing loops it can satisfy.
Decide whether to bother first. BCE wins are small — each check is one well-predicted
compare-and-branch, worth chasing only in a numeric/byte loop a profile has already proven hot. The
"should I optimize this at all" judgment routes to go-perf-methodology; slice growth/aliasing
to go-perf-slices and go-slices-and-maps.
All Go below builds clean under gofmt/go vet; the check_bce output shown was produced on Go
1.26 (go version go1.26.0).
The compiler's SSA passes accept debug flags via -gcflags. The BCE pass reports every check it
could not eliminate:
go build -gcflags="-d=ssa/check_bce/debug=1" .
It prints one line per surviving check — silence means a fully eliminated expression:
./bce.go:4:3: Found IsInBounds # an index check b[i] that was NOT eliminated
./bce.go:26:7: Found IsSliceInBounds # a slice-expression check b[:n] that survived
IsInBounds is the index check (b[i]); IsSliceInBounds is the slice-expression check
(b[:n], b[lo:hi]). The flag applies to the package you build; add all= to instrument
dependencies. This output is the only trustworthy evidence — never claim a loop is
bounds-check-free without it. (To see the compare+branch a check costs, dump assembly with
go build -gcflags=-S and find the branch into panicIndex.)
The most important measured fact: the canonical loop needs no help. Both of these emit zero
Found IsInBounds lines on Go 1.26 — the bound from the loop condition flows to the index:
func sumIndex(b []byte) int {
n := 0
for i := 0; i < len(b); i++ {
n += int(b[i]) // i < len(b) proven by the loop guard → check eliminated
}
return n
}
func sumRange(b []byte) int {
n := 0
for _, v := range b { // range never indexes past len → no check at all
n += int(v)
}
return n
}
First rule: don't fight a problem you don't have. Write the obvious
for i := 0; i < len(b); i++ { b[i] } or for i := range b { b[i] }, run the flag, and only reach
for an idiom if a check survives. Adding _ = b[len(b)-1] to these loops changes nothing — they were
already clean.
Hints matter when you index several positions from one base outside a counted loop. Three writes
to b[i], b[i+1], b[i+2] produce three surviving checks:
func triple(b []byte, i int) {
b[i] = 1 // Found IsInBounds
b[i+1] = 2 // Found IsInBounds
b[i+2] = 3 // Found IsInBounds
}
A single proof up front collapses them. Two forms work — measured to one check total, with the indexed writes free:
func tripleAssertHigh(b []byte) {
_ = b[2] // one IsInBounds here; establishes len(b) > 2
b[0] = 1 // free
b[1] = 2 // free
b[2] = 3 // free
}
func tripleConstSlice(b []byte) {
b = b[:3] // one IsSliceInBounds here
b[0] = 1 // free
b[1] = 2 // free
b[2] = 3 // free
}
The critical, measured caveat: the constant-index trick is what makes that work. With a
variable base it does not fully transfer — because the prover cannot establish i >= 0, so
i and i+1 are not bounded below even after asserting b[i+2]:
func tripleVar(b []byte, i int) {
_ = b[i+2] // Found IsInBounds (the assert itself)
b[i] = 1 // Found IsInBounds — STILL checked (i could be negative)
b[i+1] = 2 // Found IsInBounds — STILL checked
b[i+2] = 3 // free — identical to the asserted expression
}
Asserting b[i+2] only frees the identical expression b[i+2]. The hint is reliable for
constant offsets from a base; for variable offsets, verify with the flag, and prefer
restructuring to a counted loop the prover already handles (§2).
Copying a into b by index checks b[i] every iteration — the range proves a[i] but says
nothing about b:
func copyLoop(a, b []int) {
for i := range a {
b[i] = a[i] // Found IsInBounds on b[i]; a[i] is the range element, free
}
}
Cut b to a's length once before the loop — trading a per-iteration index check for a single
slice check, so the loop body goes clean (measured: one IsSliceInBounds, zero IsInBounds):
func copyLoopBCE(a, b []int) {
b = b[:len(a)] // one IsSliceInBounds; len(b) >= len(a) now known in the loop
for i := range a {
b[i] = a[i] // free
}
}
(For a plain copy use copy(b, a); this pattern is for real per-element work on two slices.)
A bound proven in a caller reaches an index in a callee only if the callee is inlined — across a
real call boundary the compiler re-checks, since it can't assume the caller's invariant. A tiny
helper func at(b []byte, i int) byte { return b[i] } carries its own check at every call site;
inlining it lets the surrounding loop's proof eliminate it. So inlining is frequently the
precondition for elimination. The budget and //go:noinline are owned by go-perf-inlining —
check there first if a check survives only because a helper didn't inline.
-B Is a Footgun, Not a Fix-gcflags=-B disables bounds checking globally — build with it and all Found IsInBounds output
disappears because the checks are simply gone. That is not BCE; it removes the safety net. A program
built with -B will read or write out of bounds silently instead of panicking, turning a clean
panic into memory corruption or a security hole. Use -B for exactly one thing: measuring the
ceiling — build both ways, benchmark, and see how much the surviving checks cost. If the gap is
small (it usually is), leave the checks in. Never ship -B. The same caution applies to unsafe to
dodge a check the compiler would have elided anyway — prove it survives with the flag first.
check_bce build and read
the output — confidence is not evidence.for i := 0; i < len(b); i++ and
for i := range b are already eliminated on 1.26; _ = b[n-1] there is noise (and a panic on the
empty slice)._ = b[i+2] does not
free b[i]/b[i+1] — the prover can't bound i below zero (§3).-gcflags=-B — it deletes the safety check, not the redundancy; use it only to
measure the ceiling (§6), and don't reach for unsafe to skip a check the flag shows is already
gone (try go-perf-simd if a real win remains).go-perf-methodology.This plugin (go-perf-* depth):
go-perf-methodology — the should-I-optimize-this-at-all gate; BCE is a last-mile tweak.go-perf-inlining — why a check survives across a call boundary; inlining as BCE's precondition.go-perf-slices — slice growth, reuse, prealloc; re-slicing cost.go-perf-simd — when scalar BCE isn't enough and the loop wants vectorization.go-perf-compiler-intrinsics — math/bits and microarchitecture levels for hot numeric code.Marketplace (go-* correctness):
go-slices-and-maps — slice-is-a-view, aliasing, 3-index slices, len/cap semantics.go-strings-bytes-runes — []byte/string indexing correctness.go-performance — the measure-first overview this plugin deepens.Wrong/right BCE anti-patterns from LLM-generated Go, each with measured check_bce output and
citations:
Source provenance for every claim in this skill:
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub ctoth/golang-skills-plugin --plugin performant-golang34 skills in this plugin
/go-perf-allocator-internalsWhat a Go heap allocation costs — the ~70 size classes and rounding waste (unsafe.Sizeof vs real slot), the tiny allocator packing sub-16B pointer-free objects, the lock-free per-P mcache → mcentral → mheap hierarchy, and scannable vs noscan spans (pointer-free objects cut GC cost; "1 alloc/op" hides different costs). Fires on "still slow after removing allocs", "reduce GC pressure", "size class", "how does Go allocate". Routes to go-perf-escape-analysis, go-perf-sync-pool, go-perf-gc-tuning, go-perf-struct-layout./go-perf-atomics-vs-locksGuides the atomics-vs-locks performance tradeoff in Go — typed sync/atomic ops (atomic.Int64/Pointer/Bool, 1.19) are a single CAS-style instruction, cheaper than a mutex uncontended but still cache-line-bouncing when contended; sync.Mutex's fast path is itself a CAS that only parks the goroutine when contended; RWMutex wins only for long read sections and is slower (scales worse) than a plain Mutex for short ones; the atomic.Pointer copy-on-write config swap; when lock-free isn't worth the correctness risk. Fires on "atomic vs mutex", "is RWMutex faster", "lock-free counter", "reduce locking overhead", "atomic.Pointer config". Routes copylock/atomic-API correctness to go-sync-primitives, memory ordering to go-race-and-memory-model, measuring to go-perf-block-mutex-profiles./go-perf-audience-and-tradeoffsGuides framing a Go performance decision by audience — the same change is right for one and wrong for another: the library author who can't profile callers and must not pessimize the common case (offer AppendXxx/[]byte forms, no unsafe in the API), the app developer who can profile and optimizes the proven hot path, the SRE who needs the code diagnosable (pprof labels, metrics, GOMEMLIMIT), the next reader who pays for clever micro-opts; the clarity-vs-speed through-line. Fires on "should a library do this", "is this worth optimizing for my users", "make this diagnosable", "premature optimization vs pessimization", "who am I optimizing for". Routes the policy root to go-idiomatic-discipline, measure-first to go-perf-methodology./go-perf-benchmarking-statisticsGuides trustworthy Go benchmark measurement at the command level — running each side with -count≥10 into old.txt/new.txt and feeding both to benchstat, reading its ± confidence interval, p-value (Mann–Whitney U), geomean, and the "~" no-significant-difference result, choosing the right unit (b.SetBytes for MB/s, b.ReportMetric for custom throughput), grouping a matrix with -col/-row/-filter, building a reproducible environment (perflock's 90% governor + serialization, frequency scaling. Auto-invokes when comparing benchmark runs, running benchstat, writing a perf A/B, or stabilizing a bench machine, and on "is this benchmark result real", "compare these benchmarks", "did this actually get faster", "my benchmark is noisy", "set up a perf regression test". Routes benchmark loop mechanics (for b.Loop, the sink/DCE trap, ResetTimer, RunParallel) to go-testing-advanced and the why-one-run-lies concept to go-perf-methodology./go-perf-block-mutex-profilesGuides Go contention diagnosis at depth — the block, mutex, and goroutine profiles, why block/mutex are OFF by default and read empty until runtime.SetBlockProfileRate (nanoseconds, 1=everything) / runtime.SetMutexProfileFraction (1/n sampled) are set, the overhead tradeoff, reading delay-vs-contention in pprof, and the goroutine profile for leak and pile-up detection. Auto-invokes on "why is this contended", "diagnose lock contention", "goroutine leak", "my mutex is slow", "profile blocking", "goroutines are piling up". Routes the fix to go-perf-contention-and-sharding / go-perf-atomics-vs-locks, sync correctness to go-sync-primitives, CPU/heap to go-perf-pprof-profiling./go-perf-budgets-and-lifecycleGuides where Go performance work belongs in the dev lifecycle and how a team keeps perf from rotting — budgets at design, don't pessimize while building, profile in staging, gate regressions in CI, monitor in prod, re-baseline after Go upgrades. Turns "fast enough?" into executable allocs/op and p99 budgets. Auto-invokes on "set a performance budget", "when should I optimize", "stop perf regressions in CI", "performance SLO", "keep our service fast". Routes benchstat mechanics to go-perf-benchmarking-statistics, incidents to go-perf-production-incidents.