Skip to content

refactor(codegen): parse targets once, one vocabulary owner - #1184

Merged
nihalpasham merged 10 commits into
NVIDIA:mainfrom
almightychang:spelling-newtype
Aug 30, 2026
Merged

nihalpasham merged 10 commits into
NVIDIA:mainfrom
almightychang:spelling-newtype

Conversation

@almightychang

@almightychang almightychang commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Implements the direction proposed in #1183. The three boundary choices it raises -- parse at the resolution
boundary, direct import with the re-export kept, one migration rather than a staged one -- were confirmed
aligned in review.

Rebased onto main now that #1105 has landed, so the range below is this PR's own diff. The patch is
byte-identical to the pre-rebase range (same patch ID, git range-diff maps all six commits =).

Problem 1 — targets flow as strings

  BEFORE

  CLI/env ──┐
  hint ─────┼──▶ ((Str)) ──parse──▶ resolve ──returns String──┐
  catalog ──┘       ▲                                         │
                    └─────────────────────────────────────────┘
                    │
                    ├──parse──▶ feature check          the same target string
                    ├──parse──▶ LLVM gate              parsed 3+ times along
                    └──parse──▶ PTX selection          one production path

  AFTER

  CLI/env ──parse──┐
  hint ────parse───┼──▶   CudaArch   ──▶ every check (typed, no reparse)
  catalog ──parse──┘    (proof-carrying)     │
   (partial: once,                           └──render──▶ llc args /
    at the boundary)                                      diagnostics only

Problem 2 — consumers re-encode leaf facts

  BEFORE

  cuda-target-spec                          cuda-oxide-codegen / probe
  ┌──────────────────────┐                  ┌──────────────────────────────┐
  │ spelling set + order │ ═══ hand iso ══▶ │ PtxIsaRequirement enum       │
  │ recorded floor keys  │ ═══ hand copy ═▶ │ candidate string list + order│
  │ floor / render arrows│ ═ re-assembled ▶ │ compare+render, per crate ×2 │
  └──────────────────────┘                  └──────────────────────────────┘
        each ═▶ pinned by a hand-maintained test, correct until someone drifts

  AFTER

  cuda-target-spec                          cuda-oxide-codegen / probe
  ┌──────────────────────────────────┐      ┌──────────────────────────────┐
  │ PtxSpelling  (membership proven, │ ───▶ │ PtxIsaRequirement            │
  │   Ord = numeric, render total)   │      │   = Option<PtxSpelling>      │
  │ RECORDED_PTX_FLOORS order        │ ───▶ │ candidates derived from table│
  │ PtxSpelling::feature_beyond_floor│ ───▶ │ both consumers call it       │
  └──────────────────────────────────┘      └──────────────────────────────┘
        three pinning tests deleted: the properties hold by construction

Changes

  • Targets parse into CudaArch once at the resolution boundary; resolution returns the typed value plus its source label. Internal checks take &CudaArch; rendering happens only at llc arguments and diagnostics.
  • PtxSpelling (new, in cuda-target-spec): construction proves vocabulary membership, Ord is numeric, feature rendering is total. PtxIsaRequirement wraps Option<PtxSpelling> — .max() merges hold by construction, and the enum variants had no external consumers.
  • RECORDED_PTX_FLOORS order is now documented as the selection preference (existing order preserved exactly); the duplicate candidate list is deleted.
  • Three pinning tests deleted because their properties became definitional (spelling round-trip, requirement ordering, candidate/key-set equality).

Behaviour

Accepted inputs keep identical selected targets, feature strings, and error text.

Two rejection paths do change, both deliberately. sm_05 was accepted before and is now rejected
(compute capability must contain at least two digits); sm_ now reports compute capability is not a valid integer where it previously reported a different message. The unchanged-error-text claim holds on the accept
paths only.

One legacy asymmetry is deliberately kept and pinned by a regression test: the PTX path ignores compute_XX
device hints while the NVVM path normalizes them. #1189 tracks that question rather than carrying it here.

Size and verification

+938 / −610 overall across six files.

  • Full per-target backend probe on the rebased base: 2,365 configurations / 1,016 routes, evidence identical; generated artifacts byte-current.
  • Crate suites 179 / 8 / 309 / 7 pass; clippy -D warnings; fmt; all 13 guard scripts -- all re-run after the rebase.
  • CI-parity container (CUDA 13.1.115 + LLVM 21.1.8): --all-targets passes, both sm_120 libdevice tests executed by name. Run before the rebase, against the byte-identical patch.
  • Not verified locally: terminal probe revalidation (evidence pins CUDA 13.3 ptxas, not installed).

Can land as one PR or split at maintainers' preference — a per-topic stack exists.

@nihalpasham

nihalpasham commented Aug 28, 2026 •

Copy link
Copy Markdown
Collaborator

Reviewed as a stacked draft. The direction is sound, and I re-derived the key equivalences:

  • floor table matches the old target_minimum_ptx_isa everywhere except the intended sm_90a 7.8 -> 8.0 fix
  • candidate list, its order, and the known-target set are unchanged

Before this leaves draft:

Small body fixes for the same pass:

We'll re-check the CUDA 13.3 ptxas evidence at validation. Labels added.

@nihalpasham nihalpasham added refactor Internal restructuring with no behavior change codegen Device code-generation pipeline (Rust MIR to IR to PTX) intrinsics Device intrinsics and libdevice math mappings build-related Build scripts, toolchain discovery, or compilation setup Depends Blocked on another PR/issue or an upstream dependency labels Aug 28, 2026
Parse external CUDA target spellings at target resolution and retain the CudaArch witness through selection, generated-intrinsic checks, LLVM validation, final-IR validation, and PTX feature selection.

Preserve target provenance, fail-closed recorded PTX floor checks, diagnostics, llc arguments, and generated probe evidence while removing internal render-and-reparse round trips.

Signed-off-by: Sam, Joochul Chang <[email protected]>
Centralize PTX feature selection above a recorded target floor in the shared target-spec leaf and use it from codegen and probe derivation. Pin the derived PtxIsaRequirement ordering to the shared spelling vocabulary so max-based requirement composition stays valid.

Signed-off-by: Sam, Joochul Chang <[email protected]>
Make vocabulary membership and numeric ordering properties of the shared PtxSpelling type. Represent codegen requirements as an optional spelling and thread the proven spelling through probe feature derivation.

Signed-off-by: Sam, Joochul Chang <[email protected]>
Make the shared floor-table order the target-selection preference and iterate it directly in codegen. The prior candidate key-set assertion is now true by construction.

Signed-off-by: Sam, Joochul Chang <[email protected]>
Use the direct cuda-target-spec path in codegen target selection while retaining the libnvvm-sys re-export for other consumers.

Signed-off-by: Sam, Joochul Chang <[email protected]>
Move compare-and-render behavior onto proof-carrying PtxSpelling and route both codegen and probe consumers through it. The off-vocabulary branch disappears because invalid spellings cannot construct the receiver.

Signed-off-by: Sam, Joochul Chang <[email protected]>
…o the module split

Main moved and rewrote code under this PR while it sat:

  PR edited                     main now has
  ---------                     ------------
  src/target.rs (monolith)  ->  src/target/{arch,features,select,
                                 generated_requirements,detect,tests/}
  llc invocation (inline)    ->  base_llc_args() + ptx_isa_with_debug_floor()
  LLVM 22 floor comments     ->  LLVM 23 (nightly 2026-08-28 bump)

Conflict resolutions, all porting the PR's delta onto main's layout:

- target.rs: deleted (as on main); its PR delta is re-applied per module:
  - features.rs: PtxIsaRequirement enum -> struct over Option<PtxSpelling>
  - arch.rs / generated_requirements.rs / select.rs: &str arch params -> &CudaArch,
    is_known_cuda_target folded into recorded_ptx_floor().is_ok()
  - select.rs: candidates derived from RECORDED_PTX_FLOORS (order verified
    identical to the removed KNOWN_CUDA_TARGET_CANDIDATES list)
  - tests/: mechanical parse().unwrap() updates; drift test retired with the
    hardcoded list; new compute_-hint test added
- ptx.rs: kept main's base_llc_args + debug-floor call, fed the PR's typed
  CudaArch through it

Signed-off-by: nihalpasham <[email protected]>
…e crate doc

- adds a tiny before/after visual: N parse sites -> one CudaArch owner
- notes that holding a PtxSpelling is itself the vocabulary-membership proof

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

The list's entry order became load-bearing when candidates started
deriving from it (selection takes the first satisfying entry), but the
old unordered set-equality test was deleted with the list it compared
against. One windows(2) walk freezes the contract:

  [ base asc ][ 'a' asc ][ 'f' asc ]
  preferred ------------> last resort

An out-of-section insert now fails the build instead of silently
reshuffling which target wins.

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

Copy link
Copy Markdown
Collaborator

Gave this the full review it hadn't had yet (the earlier pass only judged direction, back when the diff still bundled #1105), then rebased and validated it ourselves since the conflicts were all fallout from our module split. Your six commits are intact under your authorship; our merge commit only re-homes your target.rs delta into the split target/{arch,detect,features,select,...} modules.

The bar for a refactor is "provably no behavior change", so we proved it:

main (8b41ac1b5):  build backend -> compile all 222 examples --compile-only
this branch:       build backend -> compile all 222 examples --compile-only
byte-compare:      612/612 device artifacts identical (.ll, .opt.ll, .ptx, .target)
probe gate:        2374 target configs / 1025 routes both ways, logs byte-identical
candidate order:   derived-from-floors list == the deleted 28-entry list, element for element

Plus the full battery: workspace tests, clippy -D warnings, all nine repo guards, and a vecadd run on the 5090.

Two deliberate rejection-path tightenings ship with it (unreachable from any supported producer, and better errors): sm_05-style single-digit capabilities now reject at parse, and bare sm_ gets a clearer message. The compute_XX device-hint asymmetry between the PTX and NVVM paths is preserved as-is; that question lives in #1189.

Two small things we added:

  • a crate-doc sketch stating the ownership contract:

    before:  "sm_90a" -> ptx path parses -> nvvm path parses -> probe parses
    after:   "sm_90a" -> CudaArch { capability: 90, suffix: 'a' }  (parse once)
    
  • a guard test for something the refactor quietly made load-bearing: RECORDED_PTX_FLOORS entry order now IS the target-selection preference (first satisfying entry wins), and the old set-equality test died with the list it compared against. One windows(2) walk now freezes [base asc][a asc][f asc], so an out-of-section insert fails the build instead of silently reshuffling which target wins.

Review verdict on the whole final delta: clean. Dropping Depends; CI + landing next, and #1183 gets closed as implemented.

@nihalpasham nihalpasham removed the Depends Blocked on another PR/issue or an upstream dependency label Aug 30, 2026
Measured against current main: sm_05 and sm_ produce identical
TargetSelection errors as explicit overrides on both sides of the
typed-target refactor, and both are ignored as device hints. Pin
that equivalence so the reviewer-raised reject paths stay observable.

Signed-off-by: Sam, Joochul Chang <[email protected]>
@almightychang

Copy link
Copy Markdown
Contributor Author

@nihalpasham
Thanks for the re-home and the byte-level proof — one heads-up: a8711d0 (test-only, pins the sm_05/sm_ reject paths) landed after your verdict, drop it if you'd rather take the reviewed tip; PR body now scopes the error-text claim to accept paths and points the compute_XX question at #1189.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

build-related Build scripts, toolchain discovery, or compilation setup codegen Device code-generation pipeline (Rust MIR to IR to PTX) intrinsics Device intrinsics and libdevice math mappings refactor Internal restructuring with no behavior change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants