Skip to content

feat(ptx): add structured surface dialect - #915

Closed
lucifer1004 wants to merge 11 commits into
NVIDIA:mainfrom
lucifer1004:pr/ptx-v2-surface-dialect
Closed

lucifer1004 wants to merge 11 commits into
NVIDIA:mainfrom
lucifer1004:pr/ptx-v2-surface-dialect

Conversation

@lucifer1004

@lucifer1004 lucifer1004 commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does

Adds dialect-ptx: a pliron dialect that models a PTX module as first-class IR, a projection that builds it from the ptx-parse CST, and a deterministic canonical emitter.

Motivation

Strings cannot be safely transformed. To instrument, canonicalize, or one day emit PTX, the structure has to be IR the framework can verify:

ptx.module
 └── ptx.callable [callable_kind: Entry, callable_name: "countdown", ...]
      ├── ptx.directive    ".reg .b32 %r<4>;"
      ├── ptx.instruction  [head: "mov.u32", operands: ["%r1","10"]]
      ├── ptx.label        "$L_loop"
      └── ptx.instruction  [head: "bra", predicate: {%p1}, ...]

What changed (including the review redesigns)

  • the dialect: module/callable/scope/directive/instruction/label ops via #[pliron_op], typed CallableKindAttr, projection with byte-span lineage, canonical emitter
  • typed attrs are the enforced truth. Review found the emitter printed only the raw header string, so renaming a callable through its typed attr silently emitted stale PTX:
callable_name   = "saxpy"          <- typed attr, was decorative
callable_header = ".visible ..."   <- what the emitter actually printed

Verify now re-parses the header and cross-checks name/kind/external with targeted messages, and the emitter verifies before printing, so a desynced op cannot emit. ptx.scope gets the mirror check (including refusing a scope header that smuggles a whole callable). The contract is documented on the ops: typed attrs = queryable truth, header = print carrier for unmodeled syntax, Verify enforces agreement

  • predicates are a typed attribute: PredicateAttr { register, negated } replaces the flattened instruction_prefix string entirely; the emitter derives @%p1 / @!%p1 from the attr. Nothing but predicate text ever rode in the string (verified), so the field is removed, not deprecated
  • instruction interiors stay strings by design: typing is added incrementally as consumers need it, catalog-style, rather than transcribing the full ISA up front

Testing and validation

  • dialect-ptx unit tests incl. predicated round-trips (@%p1 add, @!%p1 bra), negated projection, and every desync case asserting its error message
  • all 176 real generated PTX files canonicalize through the new verify path, 0 failures
  • full workspace green; a demo_pipeline example walks build -> print -> emit -> reparse

Landing

Merges as one unit via #917; this PR then closes as already-fixed.

lucifer1004 and others added 5 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.
…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 pushed a commit to lucifer1004/cuda-oxide that referenced this pull request Aug 17, 2026
Extracted from PR NVIDIA#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.
@nihalpasham

Copy link
Copy Markdown
Collaborator

This PR is now dialect-only (the example migrations moved down to #914 where they belong) and carries the two redesigns from review. Both address the same disease: load-bearing facts living in strings.

1. Typed attrs are now the enforced truth on ptx.callable / ptx.scope (e2383ac). The review found this:

callable_name   = "saxpy"        <- typed attr, was decorative
callable_header = ".visible..."  <- string, was the only thing the emitter read
set_attr_callable_name("v2")  ->  emitted PTX still said "saxpy". silently.

Now Verify re-parses the header and cross-checks all three typed attrs against it, with targeted messages ("header names "kernel" but callable_name is "renamed""), and the emitter verifies before printing, so a desynced op can never emit. ptx.scope gets the mirror check, including refusing a scope header that smuggles a whole callable past the typed attrs. The contract is documented on the ops: typed attrs = queryable truth, header = print carrier for unmodeled syntax, Verify enforces agreement.

2. Predicates are a typed attribute (238b5aa): PredicateAttr { register, negated } replaces the instruction_prefix string entirely; the projection maps the parser's already-parsed predicate straight in, and the emitter derives @%p1 / @!%p1 from the attr. Grep confirmed nothing but predicate text ever rode in the prefix string, so the field is gone, not deprecated.

Verified:

  • dialect-ptx tests incl. predicated round-trips (@%p1 add, @!%p1 bra), negated projection, and each desync case asserting its error message; full workspace green
  • all 176 real generated PTX files canonicalize through the new verify path, 0 failures
  • demo example (945ec5a) walks build -> print -> emit -> reparse end to end

Closes as already-fixed when #917 merges the stack.

nihalpasham and others added 6 commits August 17, 2026 12:29
Extracted from PR NVIDIA#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.
…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.
…cate 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.
…it, 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.
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.
@nihalpasham
nihalpasham force-pushed the pr/ptx-v2-surface-dialect branch from 750b6ba to c23661e Compare August 17, 2026 07:01
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.

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 codegen Device code-generation pipeline (Rust MIR to IR to PTX) enhancement New feature or request ptx-dialect Native PTX dialect series: structured PTX IR, CFG analysis, direct-to-PTX path

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants