Skip to content

Stop opt from building .global lookup tables of shared-memory addresses (invalid PTX under LLVM 23) - #1203

Merged
nihalpasham merged 7 commits into
mainfrom
fix/shared-space-lookup-tables
Aug 29, 2026
Merged

nihalpasham merged 7 commits into
mainfrom
fix/shared-space-lookup-tables

Conversation

@nihalpasham

Copy link
Copy Markdown
Collaborator

The bug

A kernel match that picks a per-pipeline-stage shared buffer gets "optimized" into an object that cannot exist:

match stage {                       opt's favorite trick: precompute the
    0 => &SMEM_A0,                  4 answers into a constant table and
    1 => &SMEM_A1,         ──►      index it. Except the answers are
    2 => &SMEM_A2,                  SHARED-MEMORY addresses: per-block
    3 => &SMEM_A3,                  runtime values. A compile-time table
}                                   of them is physically impossible.

the failure chain:
  opt (LLVM 23)   builds the table                       ← trigger
  llc             prints it, exit 0, says nothing        ← silence
  ptxas / JIT     "Variable used as initial value not
                   in .global or .const state space"
                   → CUDA_ERROR_INVALID_PTX (218)        ← too late,
                                                           on a B200

Both PTX encodings are invalid (= {sym} and = {generic(sym)} alike, verified against ptxas 13.0 and 13.3). Affected: gemm_sol_final (loud failure on sm_100) and gemm_sol (same poison, masked — see below).

Why it appeared now

opt decides whether the table trick is worth it from its target GPU, and we pass no -mcpu, so LLVM's built-in default decides:

LLVM 22 default: sm_30  → trick OFF  → we were safe by accident
LLVM 23 default: sm_75  → trick ON   → llvm/llvm-project PR #176021

The bug was always latent, not new: LLVM 22 with an explicit modern -mcpu builds the same bad tables (upstream's validLookupTableConstant never checks address spaces). Confirmed by A/B on byte-identical .ll: opt-22 → 0 tables, opt-23 → 8 (4 of them shared-space), and by an isolation matrix over {old,new} × {opt,llc} × {input IR} — the trigger is the opt default, not our IR and not llc.

The fix

  • One flag at the single choke point both frontends share (optimization_args()): -switch-to-lookup=false. Accepted identically by every supported opt (LLVM 21+); kept permanently since our LLVM floor spans the broken majors (upstream precedent: NVPTX already disables relative lookup tables, llvm#159748). Switches lower to brx.idx code-label tables instead — legal PTX, and faster: a few uniform ALU ops instead of a dependent .global load on the mbarrier/TMA hot path.
  • A safety net independent of the flag: right after llc, the pipeline scans the PTX and fails the build if any .global/.const initializer references a .shared symbol (bare or generic()), printing the offending line. Whatever pass invents this object next, it becomes a compile error, not a runtime 218.

The masked failure this uncovered (examples)

gemm_sol carried the same broken tables yet reported PASS — because its host treated any load failure with error 218 as "right PTX, wrong GPU" and exited 0 via PTX-only verification, even on the sm_100 machine that should have executed it. tcgen05 and tcgen05_matmul shared the pattern.

  • All three now check GPU capability before loading (the model gemm_sol_final already used); error 218 on a capable GPU is a hard failure.
  • The stricter path immediately caught a second real bug: tcgen05's MMA helper mixed cta_group::1 and cta_group::2 in one function, which ptxas 13.x rejects — that module was never assemblable for sm_100, masked by the same fallback. Split into _cg1/_cg2. Its PTX-only verification also now assembles against the module's real .target (was hardcoded sm_120a and never actually succeeded).

Regression coverage

  • New shared_stage_select example: the exact match-over-stage-buffers shape, runs on any GPU; with the flag removed it fails the build via the new scan.
  • smoketest's GPU-gated lanes (tcgen05/wgmma/blackwell-mma) now assemble their PTX with ptxas when one is available, instead of only checking that llc produced a file — closing the hole that let invalid PTX ship: GPU-less CI never assembled, and only sm_100 hardware ever JIT-compiled these modules.

Validation

isolation matrix         opt-22 → 0 tables/PASS; opt-23 → 8 tables/FAIL;
                         old IR through opt-23 → same FAIL (trigger pinned)
ptxas 13.3 sm_100a       regenerated gemm_sol + gemm_sol_final: PASS
PTX sweep, all examples  0 shared-symbol initializers, 0 data tables
cargo test --workspace   5305 passed, 0 failed
full GPU smoketest       221/221 (new example included), ptxas gate active
B200 (sm_100) hardware   gemm_sol_final: 16.7M/16.7M exact BF16 matches,
                         1472 TFLOPS (90.5% of cuBLASLt) — no perf cost
                         from dropping the tables; shared_stage_select and
                         the unmasked gemm_sol/tcgen05 lanes all pass

Note for reviewers

A separate perf regression in gemm_views (naive raw 7218 → 5708 GFLOPS) was found during this investigation. It is not caused by this PR (that example has no switch tables and its PTX is byte-equivalent with and without the flag) — it's an independent llc-23 loop-shape change that defeats ptxas's SASS unroller (register count drops 38 → 26). Tracked separately.

… .shared addresses

LLVM 23 bumped NVPTX's default subtarget from sm_30 to sm_75
(llvm/llvm-project@9fc5fd0ad689, PR #176021). Our `opt` invocation passes
no -mcpu, so the default subtarget now has brx.idx (SmVersion >= 30 &&
PTXVersion >= 60), which legalizes ISD::BR_JT, which flips
TTI::shouldBuildLookupTables() to true, and SimplifyCFG's
switch-to-lookup-table starts firing on the multi-stage pipeline pattern
(a `match stage & 3` over per-stage shared buffers, as in gemm_sol /
gemm_sol_final). The result is unassemblable PTX:

  .global .align 8 .u64 switch_$_table_$_k[4] = {__shared_mem_0, ...};

ptxas rejects .shared symbols in .global/.const initializers in both the
bare and the generic() forms ("Variable used as initial value not in
.global or .const state space"), and driver JIT fails module load with
CUDA_ERROR_INVALID_PTX (218) on sm_100. llc emits the initializers
silently (exit 0), so nothing failed until runtime on gated hardware.

Isolation matrix on byte-identical pre-opt .ll (gemm_sol_final): opt-22
default builds 0 tables, opt-23 builds 8 (4 of them [4 x ptr
addrspace(3)]); llc 22 and 23 both print the bad initializers; ptxas 13.3
rejects every opt-23 combo and accepts every opt-22 combo. The bug is
latent on older majors too: LLVM 22 opt with an explicit modern -mcpu
(sm_70+) builds the same tables.

Two layers:

- pass `-switch-to-lookup=false` on every opt invocation (both the plain
  -O2 and the internalize,default<O2> argument sets). Upstream's
  validLookupTableConstant accepts any GlobalValue with no address-space
  check, so this SimplifyCFG override is the supported control; it exists
  identically on LLVM 21-23 and stays even after upstream learns to
  reject shared-space table constants, because our LLVM floor spans the
  broken majors. Upstream precedent: NVPTX already disables relative
  lookup tables wholesale (llvm/llvm-project#159748). Switches keep
  their branch form; llc lowers dense ones to brx.idx code-label branch
  tables, avoiding a dependent .global data load on the hot path.

- post-llc scan: fail the build if any produced .global/.const
  initializer references a .shared symbol, turning any future variant of
  this class into a loud compile error instead of a runtime 218,
  regardless of which pass produced it.

Regression test: a 4-way stage switch over shared/generic buffer-pointer
phis must not become a data table, and no initializer may reference a
.shared symbol (fails without the flag on the pinned toolchain; the
post-llc scan then rejects the module with the offending line).
…n tcgen05 hosts

gemm_sol, tcgen05, and tcgen05_matmul treated any module-load failure
with CUDA_ERROR_INVALID_PTX (218) as "right PTX, wrong GPU" and degraded
to the PTX-only verification path with exit 0. The driver uses 218 both
for arch-incompatible PTX and for genuinely malformed PTX, so on an
sm_100 machine invalid PTX (the switch-lookup-table miscompile) produced
a false smoketest PASS ("PTX was generated successfully") while
gemm_sol_final, which gates on GPU capability before loading, failed
loudly.

Adopt gemm_sol_final's model in all three: gate execution on
can_execute_tcgen05_ptx(major, minor) BEFORE loading the module; on a
capable GPU any load failure is now a hard error, and 218 names the
compiler bug explicitly. tcgen05's verify_ptx_only also now assembles
the PTX for the arch its .target line records (the old hardcoded
-arch=sm_120a could never succeed against the sm_100a module) and fails
on real assembly errors while skipping on old/missing ptxas.

Also split compile_tcgen05_mma_base into _cg1/_cg2 kernels, mirroring
the existing cp/control zoo split: ptxas enforces one tcgen05
granularity per function ("uses single CTA (.cta_group::1) and CTA pair
granularity (.cta_group::2) and that is not allowed"), so the mixed
kernel made the whole module unassemblable and unloadable. This was
caught by the new smoketest ptxas gate; the smoketest's instruction-form
counts now aggregate over both bodies with per-kernel purity checks.
A runtime `match stage & 3` over four per-stage shared-memory buffers
inside a runtime-trip-count loop: the multi-stage pipeline shape that
LLVM 23's SimplifyCFG turned into .global lookup tables of .shared
addresses. The example is standard-category, so the guard runs on every
GPU and in compile-only CI, not just on tcgen05 hardware: if the tables
ever come back, the build fails (post-llc shared-initializer scan) and
module load fails (CUDA_ERROR_INVALID_PTX). Without the fix this
example forms 4 lookup tables and ptxas rejects its PTX; with the fix
it executes and verifies 32 lanes across 9 staged iterations.
…icts

The tcgen05/wgmma/blackwell-mma verdicts accepted "a .ptx exists" on
hosts that cannot execute them, so PTX that only fails at driver JIT
(e.g. .global initializers referencing .shared symbols,
CUDA_ERROR_INVALID_PTX 218) passed CI silently and only exploded on the
gated hardware.

Resolve a ptxas once (CUDA_OXIDE_PTXAS, PATH, CUDA_HOME,
/usr/local/cuda*), then assemble each gated artifact for the arch its
.target line records as part of the verdict. A real assembly error
fails the lane with ptxas's message; a missing ptxas, or one too old
for the arch or PTX ISA, is a noted skip. The gate applies to the
normal-mode "PTX compiled" verdicts, to --compile-only verdict_compile,
and to the dual-route tcgen05 branch that also emits a .ptx before its
libNVVM run.

This gate immediately caught a real bug: the tcgen05 example's
compile_tcgen05_mma_base kernel mixed cta_group::1 and cta_group::2 in
one function, which ptxas rejects (fixed by splitting the kernel).
…first

Same facts, readable shape: the failure-chain and safety-net diagrams
up front, the LLVM-23 default-subtarget story and the keep-forever
rationale as short bullets.
@nihalpasham nihalpasham added bug Something isn't working build-related Build scripts, toolchain discovery, or compilation setup miscompile Produces incorrect PTX/IR (wrong generated code) codegen Device code-generation pipeline (Rust MIR to IR to PTX) examples Example kernels and host harnesses under crates/rustc-codegen-cuda/examples labels Aug 29, 2026
needless_range_loop on the host-side result check; iterator rewrite,
device kernel untouched (the match-over-stage-buffers pattern under
test lives in the kernel, not here).
… externs loudly

The new ptxas verdict gate exposed that CI's llc-21 floor pin has been
producing unassemblable tcgen05 PTX all along: llc-21 predates
llvm.nvvm.stmatrix.* (gemm_sol, gemm_sol_final) and lowers the unknown
intrinsic by leaking its dotted LLVM name into the PTX as an
.extern .func declaration, exit 0, no diagnostic. ptxas then dies with
an unhelpful parse error; nothing in compile-only CI ever assembled the
file, so it shipped green.

Two changes: the examples-compile floor pin moves to llc-22 (the true
floor for the stmatrix family, verified: 221/221 compile-only with the
ptxas gate active), and the pipeline gains a second post-llc scan that
rejects dotted .extern .func declarations with an error naming the
intrinsic and the remedy, so an under-floor llc fails at build time
with the cause instead of a cryptic assembler error.
@nihalpasham

Copy link
Copy Markdown
Collaborator Author

CI's examples-compile failure here was the new ptxas gate doing its job: it exposed that the job's llc-21 floor pin has been producing unassemblable tcgen05 PTX all along (llc-21 predates llvm.nvvm.stmatrix.* and leaks the dotted intrinsic name into the PTX as an .extern .func, exit 0, silently). Two additions on the branch:

  • the floor gate moves to llc-22 (true floor for the stmatrix family; 221/221 compile-only with the gate active under llc-22)
  • a second post-llc scan rejects leaked dotted externs with the intrinsic named and the remedy stated, so an under-floor llc now fails at build time instead of ptxas dying with Parsing error near '.nvvm'

@nihalpasham
nihalpasham merged commit 1f6972f into main Aug 29, 2026
52 checks passed
nihalpasham added a commit that referenced this pull request Aug 30, 2026
…ies #1202) (#1206)

* docs: correct tcgen05 hardware claims to sm_100a (datacenter Blackwell)

tcgen05/TMEM is a datacenter-Blackwell feature; consumer Blackwell
(sm_120, RTX 50 series) has no TMEM and no tcgen05 instruction set.
Fix every doc site that claimed sm_120 support:

- tcgen05 + tcgen05_matmul READMEs: required GPU is sm_100a, add
  explicit NOT-supported note for consumer Blackwell (sm_120)
- cuda-device tcgen05 rustdoc: drop the "sm_120: RTX 5090" bullet,
  frame the sm_100 TMEM-capable family instead
- book safety-model Tier 3 table: tcgen05/TMEM rows -> sm_100a
  (Blackwell DC), CLC row -> sm_100+ (Blackwell)
- tcgen05 example crate doc: "Blackwell-only (sm_100/sm_120)" ->
  "Blackwell datacenter-only (sm_100a)"

Doc-only slice of PR #1202; the PR's runtime changes were superseded
by the stronger capability gate that landed in #1203.

Signed-off-by: Guilherme Pedroza <[email protected]>

* docs: sync tcgen05 README transcripts with actual output; add sm_101a to family list

- both READMEs showed a "Loading PTX from: ..." line the examples
  never print; transcripts now match the post-#1203 load sequence
- tcgen05_matmul's non-datacenter transcript now quotes the literal
  warning the code prints ("WARNING: tcgen05 requires sm_100
  (datacenter Blackwell)!") plus the full PTX-verification tail
- cuda-device tcgen05 rustdoc family list gains sm_101a: the runtime
  allowlist in the examples accepts cc 10.0 / 10.1 / 10.3 / 11.0, so
  the docs must name all four arches

Signed-off-by: nihalpasham <[email protected]>

---------

Signed-off-by: Guilherme Pedroza <[email protected]>
Signed-off-by: nihalpasham <[email protected]>
Co-authored-by: Guilherme Pedroza <[email protected]>
@nihalpasham
nihalpasham deleted the fix/shared-space-lookup-tables branch September 5, 2026 15:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working build-related Build scripts, toolchain discovery, or compilation setup codegen Device code-generation pipeline (Rust MIR to IR to PTX) examples Example kernels and host harnesses under crates/rustc-codegen-cuda/examples miscompile Produces incorrect PTX/IR (wrong generated code)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant