Skip to content

feat(ptx): add lossless structural syntax foundation - #914

Closed
lucifer1004 wants to merge 6 commits into
NVIDIA:mainfrom
lucifer1004:pr/ptx-v2-syntax-foundation
Closed

lucifer1004 wants to merge 6 commits into
NVIDIA:mainfrom
lucifer1004:pr/ptx-v2-syntax-foundation

Conversation

@lucifer1004

@lucifer1004 lucifer1004 commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does

Adds ptx-parse, a dependency-free crate that parses PTX text into a lossless concrete syntax tree (CST), plus a span-safe edit layer, and migrates every in-tree PTX text consumer onto it.

Motivation

All PTX in this project is text produced by someone else (llc, external inputs), and main handled it in five places with five independent string hacks:

read the recorded sm target     cargo-oxide      line.starts_with(".target")
merge embedded PTX modules      cuda-host        prefix-match header lines
find libdevice declarations     codegen          misses multi-line .extern .func
strip the debug flag            codegen          substring surgery on .target
match probe instructions        intrinsics-gen   hand-rolled head matcher

One of those had a live bug: the debug-strip failed to remove debug from a .target line with a trailing comment, so "stripped" builds shipped debug-flagged PTX.

What lossless means

coverage over every PTX artifact our pipeline produces:
  176 files, 2.47 MB, 47,813 instructions -> 0 incomplete, 0 unknown bytes
  concatenating token spans reproduces each input byte-for-byte

An instruction the crate has never seen still parses (opcode + operands + semicolon), so new ISA revisions cannot break it. Parser gaps are observable via Coverage, never silent.

What changed

  • the ptx-parse crate: lexer, statement/scope CST with recovery diagnostics, callables/labels/registers/predicates with byte spans, EditScript with overlap and UTF-8 validation
  • the five consumer migrations, each replacing an ad-hoc scan with a structural query and surfacing parse failures as typed errors
  • ten examples' PTX self-checks migrated from brittle find() scans to structural queries (moved here from feat(ptx): add structured surface dialect #915; they depend only on the parser)
  • parse errors now propagate in the intrinsics-gen matcher (Result, not an empty match list), so "unparseable" can never read as "no match"
  • crate renamed from ptx-syntax and made publishable: ptx-parser is taken on crates.io, ptx-parse is free, and publishable cuda-host now depends on it
  • all example lockfiles re-locked against current main

Testing and validation

  • ptx-parse 35 tests (incl. a pseudo-fuzz never-panic test); intrinsics-gen 289; all four consumer crates green
  • audit run: the coverage numbers above
  • compile smoketest 210/210; workspace clippy and both fmt gates clean
  • GPU (sm_120): migrated-assertion examples run and their structural PTX checks pass against freshly built PTX

Landing

The stack (#914 -> #915 -> #916 -> #917) merges as one unit via #917; this PR then closes as already-fixed.

@nihalpasham nihalpasham added enhancement New feature or request codegen Device code-generation pipeline (Rust MIR to IR to PTX) ptx-dialect Native PTX dialect series: structured PTX IR, CFG analysis, direct-to-PTX path refactor Internal restructuring with no behavior change host-apis Host-side runtime APIs (cuda-host, cuda-core, cuda-async) cargo-oxide The `cargo oxide` subcommand and build automation build-related Build scripts, toolchain discovery, or compilation setup labels Aug 16, 2026
lucifer1004 and others added 2 commits August 17, 2026 10:16
Rename the crate directory, package name, workspace entries, and all
dependent imports. Mark the crate publishable since cuda-host (published)
depends on it; the ptx-parse name is free on crates.io.
lucifer1004 and others added 3 commits August 17, 2026 10:21
…ueries

Extracted from PR NVIDIA#915: ten examples' textual PTX assertions move onto
ptx-parse Document queries (callables, directives), with each example
Cargo.lock refreshed for the new path dependency. The dialect half of
that PR is not included.
…ing nothing

instructions_with_matching_head mapped Document::parse errors to an
empty match list, so unparseable PTX read as "no match" and could slip
through the probe validators with a misleading zero-count message.
Return the ParseError instead and propagate it through
matching_instructions, contains_matching_instruction,
InstructionPattern::matches, and selection_matches_policy, matching how
the other migrated call sites surface parse errors.
… dependency

cuda-host now depends on ptx-parse, and every example workspace resolves
cuda-host through its path dependency, so each committed example
Cargo.lock (and the isolated rustc-codegen-cuda lock) gains the two
additive ptx-parse entries. Purely additive, matching the re-lock
pattern from NVIDIA#893.
@nihalpasham
nihalpasham force-pushed the pr/ptx-v2-syntax-foundation branch from 3ced427 to 6f3acfb Compare August 17, 2026 06:43
@nihalpasham

Copy link
Copy Markdown
Collaborator

Reviewed in depth, direction endorsed, and I've rebuilt this branch on current main with the review outcomes applied. What changed and why:

  • crate renamed: ptx-syntax is now ptx-parse, and publish = true. Reasoning: ptx-parser is taken on crates.io, ptx-parse is free, and cuda-host (publishable) now depends on this crate, so it has to be publishable too or cuda-host is stuck git-only
  • feat(ptx): add structured surface dialect #915's example-migration half moved down here (commit 0ebc614, your authorship preserved): the ten examples' PTX self-checks depend only on the parser, not the dialect, so this is their home. Their lockfiles were re-locked against current main rather than carrying the stale copies
  • one catch during that fold: feat(ptx): add structured surface dialect #915's copy of gemm_sol_final/src/main.rs would have reverted the cvt_bf16x2_f32 import migration that landed in refactor(cuda-device): move BF16 conversions out of tcgen05 #887 after you branched; restored main's imports
  • parse errors now propagate in the intrinsics-gen matcher (5c4a272): instructions_with_matching_head returns Result instead of mapping unparseable PTX to an empty match list, so "couldn't parse" can never read as "no match"
  • all 201 remaining example lockfiles re-locked (6f3acfb): every example resolves cuda-host, which now pulls ptx-parse, and the cargo-deny example gate runs --locked

Verified on this branch:

  • ptx-parse 35 tests, intrinsics-gen 289, all four consumer crates green; workspace clippy and both fmt gates clean
  • compile smoketest 210/210
  • the audit example over every PTX artifact our pipeline produces: 176 files, 2.47 MB, 47,813 instructions, 0 incomplete
  • GPU (sm_120): three of the migrated-assertion examples run and their structural PTX checks pass against freshly built PTX

Landing plan for the stack: merges as one unit via #917; this one closes as already-fixed at that point.

nihalpasham added a commit that referenced this pull request Aug 17, 2026
… (stack #914-#917) (#917)

* feat(ptx): add lossless structural syntax foundation

* refactor(ptx-parse): rename ptx-syntax crate to ptx-parse

Rename the crate directory, package name, workspace entries, and all
dependent imports. Mark the crate publishable since cuda-host (published)
depends on it; the ptx-parse name is free on crates.io.

* refactor(examples): migrate PTX self-checks to structural ptx-parse queries

Extracted from PR #915: ten examples' textual PTX assertions move onto
ptx-parse Document queries (callables, directives), with each example
Cargo.lock refreshed for the new path dependency. The dialect half of
that PR is not included.

* fix(cuda-intrinsics-gen): propagate PTX parse errors instead of matching nothing

instructions_with_matching_head mapped Document::parse errors to an
empty match list, so unparseable PTX read as "no match" and could slip
through the probe validators with a misleading zero-count message.
Return the ParseError instead and propagate it through
matching_instructions, contains_matching_instruction,
InstructionPattern::matches, and selection_matches_policy, matching how
the other migrated call sites surface parse errors.

* chore(examples): re-lock example workspaces for cuda-host's ptx-parse dependency

cuda-host now depends on ptx-parse, and every example workspace resolves
cuda-host through its path dependency, so each committed example
Cargo.lock (and the isolated rustc-codegen-cuda lock) gains the two
additive ptx-parse entries. Purely additive, matching the re-lock
pattern from #893.

* chore(repo): register ptx-parse in the crate inventory and license ledger

* feat(ptx): add structured surface dialect

Extracted from PR #915: crates/dialect-ptx only (the example-migration
half already landed with the ptx-parse foundation). Imports adapted from
the renamed ptx-syntax crate to ptx-parse.

* refactor(dialect-ptx): verify header text agrees with typed callable attrs

ptx.callable carried the same facts twice: typed attrs (callable_name,
callable_kind, callable_external) for queries and the header string for
printing. The emitter prints only the string, so mutating a typed attr
silently desynced the emitted PTX from the queryable truth.

The header stays the print carrier (it holds parameter lists and
performance directives the dialect does not model yet), but Verify now
re-parses it with ptx-parse and rejects any disagreement with the typed
attrs, naming both values in the error. ptx.scope's header gets the
matching check: a non-empty header must not carry its own terminator
and must not spell a callable, which would bypass ptx.callable's typed
attrs. The contract is documented on both ops.

* feat(dialect-ptx): replace instruction prefix string with typed predicate attr

PTX defines exactly one instruction prefix, the guard predicate, so
ptx.instruction no longer carries a free-form instruction_prefix string.
It now carries an optional typed PredicateAttr (register + negation),
populated by the projection from ptx-parse's parsed predicate. The
emitter derives the textual "@%p1" / "@!%p1" guard from the attribute,
and attribute verification rejects registers that are not %-prefixed.

PtxBuilder grows predicated_instruction(); plain instruction() drops the
prefix parameter. Repo-wide grep confirms nothing but predicate text
ever rode in the prefix string.

* docs(dialect-ptx): add demo_pipeline example walking build, print, emit, reparse

Builds a kernel with a counting loop through PtxBuilder, prints the typed
IR (the loop back-edge carries the typed ptx.predicate attribute), emits
canonical PTX, and checks the guard survives a lossless ptx-parse round
trip.

* chore(repo): register ptx-parse and dialect-ptx in repo-wide inventories

The license-inventory, crate-overview, and SPDX CI guards require every
workspace member to be listed. Adds dependency-licenses.csv rows and
README Crate Overview rows for both new crates, and the standard SPDX
header on ptx-parse's audit example.

* feat(ptx): analyze CFG and lexical normalization

* feat(dialect-ptx): reject vector-element uses of renamed registers at plan time

'.' is a word byte, so a vector-element use such as v.x lexes as a
single token and never resolves to the binding v. Renaming a nested
binding would leave v.x behind, silently rebinding it to any
same-named outer register and assembling with wrong semantics.
RegisterAlphaPlan now scans the callable body for tokens of the form
R.suffix whenever R is scheduled for renaming and fails closed with a
typed error naming the token and its byte span.

* feat(dialect-ptx): reject rename targets that capture label or callable names

The occupied-token check only avoids names spelled inside the callable
body. A module callable never referenced in the body, or a label equal
to a bank base name (which the bank availability check skips), can
still end up as a rename target; the rewritten register then captures
branch or call targets and the PTX fails ptxas or assembles with wrong
semantics. RegisterAlphaPlan now cross-checks every chosen target
against the callable's labels and the module's callable names and
fails closed with a typed error naming both symbols.

* feat(dialect-ptx): gate rewrite plans behind the shared PTX version ceiling

The UnsupportedPtxVersion ceiling previously gated only the read-only
CFG recovery. Rewrites are higher risk than reads: an unaudited ISA
could bind or spell registers in ways the resolver does not model.
The .version validation moves to a shared version module with a typed
PtxVersionError, and RegisterAlphaPlan and ScopeFlattenPlan now fail
closed on missing, invalid, or newer-than-9.3 versions exactly like
ControlFlow::analyze.

* feat(ptx): materialize and verify native CFG

* fix(dialect-ptx): treat .pragma as scope-sensitive in scope flattening

Pragma strings are tool-defined with placement-dependent meanings, so
deleting the braces around a block-scoped pragma such as
.pragma "nounroll"; can widen its effect to the whole callable. Scope
flattening now fails closed on nested scopes containing .pragma; only
.loc, whose debug-location effect follows lexical order regardless of
braces, remains scope-neutral.

* docs(dialect-ptx): record first native-CFG consumers and transform conventions

* docs(dialect-ptx): raise demo_pipeline output into the native CFG

The example now re-analyzes its own canonical emission with
NativeCfgPlan, prints the raised module and the guarded loop back-edge
ptx.terminator (typed predicate plus real successor edges), and checks
that canonical emission from the raised CFG is byte-identical to the
surface emission.

---------

Co-authored-by: nihalpasham <[email protected]>
@nihalpasham nihalpasham added the already-fixed Resolved on a newer commit or branch; no action needed label Aug 17, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

Landed on main via the stack head #917 (squash 8eb0dcf); this layer's commits are contained in that merge. Closing as already-fixed per the stack landing plan.

nihalpasham added a commit that referenced this pull request Aug 18, 2026
* docs(ptx-parse): the one published crate with no README

Every workspace member except `ptx-parse` ships a `README.md` and declares
`readme = "README.md"` -- 26 of 27 with both, and `ptx-parse` with neither.

It is the wrong crate to have missed. `ptx-parse` is the only member that sets
`publish = true`:

    # Published because cuda-host depends on it (name verified free on crates.io).
    publish = true
    description = "Lossless structural views over PTX source text"

so it is the one crate here whose page on crates.io renders from a README, and
that page would render with the one-line description and nothing else. Its
sibling `dialect-ptx` -- from the same #914-#917 stack -- has both, and its
README sends readers here: "`ptx-parse::Document` owns exact external source,
trivia, unknown syntax, and byte-preserving edits." Following that pointer
currently lands on nothing.

The README is written from the crate's own sources, not from an impression of
them:

* the framing and the deliberate no-ISA-type-checking rule come from the
  `lib.rs` crate doc,
* the six `StatementKind` variants, the `Document` accessors, `diagnostics`,
  `coverage` and `ParseError` from `lib.rs` and `syntax.rs`,
* the `EditScript` surface, including `apply_with_map`/`AppliedEdits` and the
  `MapBias` at edit boundaries, from `edit.rs`,
* the `ptx-parse` / `dialect-ptx` split restated in the same terms
  `dialect-ptx`'s README already uses, so the two agree rather than drift,
* and the consumer table from the actual `ptx_parse::` call sites in
  `cuda-oxide-codegen`, `cuda-host`, `cuda-intrinsics-gen`, `cargo-oxide` and
  `dialect-ptx`.

`readme = "README.md"` is added alongside, matching the other 26 manifests, so
the packaged crate carries it too.

Verified: every backticked API name in the new README resolves in
`crates/ptx-parse/src/`; all 27 members now have both the file and the
manifest field; `cargo metadata --locked` still parses; check-crate-inventory,
check-dependency-licenses and check-spdx-headers pass.

Signed-off-by: Vyncint Ng <[email protected]>

* docs(ptx-parse): use absolute LICENSE link so crates.io does not 404

crates.io rewrites relative README links against the repository root,
so ../../LICENSE escapes the root on the published page.

---------

Signed-off-by: Vyncint Ng <[email protected]>
Co-authored-by: nihalpasham <[email protected]>
nihalpasham pushed a commit that referenced this pull request Aug 18, 2026
`unit-tests.yml`'s matrix covers 21 of the 27 workspace members. Its own
comment block names the intended exclusions:

    # Crates intentionally not in this matrix:
    #   * `cuda-bindings` — generated sys bindings covered transitively.
    #   * `fuzzer` — differential-testing infra with no unit tests.
    #   * `rustc-codegen-cuda` — its own [workspace] ...

Four members are in neither list. They are not declared out; they were left
out, and between them they hold 107 `#[test]` functions that nothing executes:

  dialect-ptx     43   structured terminal PTX dialect (#917)
  ptx-parse       35   lossless CST over PTX source (#917)
  iket-lower      22   dialect-iket -> runtime compatibility profile
  dialect-iket     7   in-kernel event tracing dialect

`dialect-iket` and `iket-lower` have been uncovered for a long time -- they are
the same two crates whose absence from README.md motivated
`check-crate-inventory.sh` ("1,700 lines of compiler across two crates, with no
row between them"). `dialect-ptx` and `ptx-parse` arrived with #914-#917 last
batch. The PTX pair is the one that stings: `dialect-ptx` verifies native CFG
invariants, which is precisely the sort of property a unit test is the only
cheap way to hold, and 43 of them have never gated a merge.

None of the four touches `cuda-bindings`, so none needs the toolkit: their
dependency sets are `pliron`, `pliron-derive`, `thiserror`, `combine`,
`dyn-clone`, `linkme`, and `ptx-parse` has no dependencies at all. They go in
the plain matrix with the default `--all-targets` and no `needs_cuda`, and add
about a second of runtime between them.

The exclusion comment now also says what the list is *for* -- that a member
absent from both the matrix and the list is an omission rather than a decision
-- since the list reading as complete is what made this invisible.

`just test` gets the same four, because its own comment is the contract:
"Mirrors .github/workflows/unit-tests.yml; keep the two in step." `test-cuda`
is unchanged; nothing here links the driver.

Verified locally with the pinned toolchain:

  dialect-iket   7 passed; 0 failed
  iket-lower    22 passed; 0 failed
  ptx-parse     35 passed; 0 failed
  dialect-ptx   43 passed; 0 failed

so this turns CI green-on-nothing into green-on-107 without changing a test.
Also checked by script: the CI matrix and the Justfile's package lists are now
identical, and every workspace member is either in the matrix or named in the
exclusion comment -- no member is silently uncovered. `unit-tests.yml` still
parses, with 25 matrix entries.

Signed-off-by: Vyncint Ng <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

already-fixed Resolved on a newer commit or branch; no action needed build-related Build scripts, toolchain discovery, or compilation setup cargo-oxide The `cargo oxide` subcommand and build automation codegen Device code-generation pipeline (Rust MIR to IR to PTX) enhancement New feature or request host-apis Host-side runtime APIs (cuda-host, cuda-core, cuda-async) ptx-dialect Native PTX dialect series: structured PTX IR, CFG analysis, direct-to-PTX path refactor Internal restructuring with no behavior change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants