Skip to content

cuda-oxide-codegen: rustc-independent dialect-mir to PTX backend - #314

Merged
nihalpasham merged 2 commits into
NVIDIA:mainfrom
alejandro-soto-franco:feat/compile-module-to-ptx
Jul 4, 2026
Merged

nihalpasham merged 2 commits into
NVIDIA:mainfrom
alejandro-soto-franco:feat/compile-module-to-ptx

Conversation

@alejandro-soto-franco

@alejandro-soto-franco alejandro-soto-franco commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR adds an experimental, rustc-independent PTX backend for frontends that already produce cuda-oxide's dialect-mir representation.

Previously, another frontend had to depend on rustc-private code or reproduce part of the compiler pipeline. The new cuda-oxide-codegen crate keeps frontend translation separate and owns one shared post-translation path used by both mir-importer and standalone frontends.

The API is intentionally experimental. Consumers must pin cuda-oxide, Pliron, dialect-mir, and dialect-nvvm to the same exact revision.

What changed

One rustc-free backend pipeline

  • Adds cuda-oxide-codegen without rustc_private or rustc_driver.
  • Moves verification, mem2reg, annotated unrolling, device-extern insertion, MIR-to-LLVM lowering, libdevice/NVVM selection, final verification, LLVM export, and PTX generation behind one orchestrator.
  • Keeps Rust MIR collection and translation in mir-importer.
  • Makes the existing Rust path call that same orchestrator while retaining its NVVM/libdevice and artifact-sidecar workflow.

Experimental public API

The supported standalone surface is cuda_oxide_codegen::experimental:

  • CodegenModule owns its Pliron context and root module together.
  • Compiler reuses an explicit Toolchain.
  • Target and CompileOptions validate compilation inputs.
  • Compilation, Diagnostic, and CompileError report structured results and failures.
  • Kernel entries are marked by symbol through the owned module.

Implementation modules are private. The doc-hidden __private bridge exists only for the matching mir-importer revision and is not a supported frontend contract.

Safety and failure behavior

  • Compilation clones the input before destructive passes, so caller IR remains available after success or failure.
  • Input and lowered LLVM IR are both verified.
  • The standalone v1 rejects libdevice and other unresolved external functions instead of returning PTX that cannot be loaded.
  • Requested standalone optimization fails clearly when opt is missing or fails.
  • The legacy Rust path keeps its warning-and-unoptimized fallback.
  • LLVM tool discovery is explicit and reusable; library code does not print unless the caller supplies a trace sink.
  • Scratch artifacts use unique, atomically created RAII directories.

Experimental v1 contract

Rust MIR frontend -+
Other frontend ----+-> owned dialect-mir module
                       -> one shared backend
                       +-> standalone: self-contained PTX
                       `-> Rust path: PTX or existing NVVM/libdevice workflow

V1 deliberately does not promise:

  • a stable cross-revision API or stable in-memory IR format;
  • libdevice, device-extern, NVVM bitcode, or object linking through the standalone API;
  • source translation, runtime module loading, kernel launching, caching, or cancellation;
  • Send support for CodegenModule.

Compilation uses LLVM llc and, for Optimization::O2, a matching opt. LLVM 21 is the general floor; PTX 9.0 targets require LLVM 22.

Testing

Final repaired head: a4a1ff34fd8e6f9929944ab855b3e9c10d0c1b06

  • cargo test -p cuda-oxide-codegen -p mir-importer --all-targets
    • 56 codegen unit tests
    • 10 experimental API/adversarial tests
    • 1 eight-thread compiler-reuse test
    • 1 real llc -> ptxas spine test
    • 17 mir-importer tests
  • cargo clippy -p cuda-oxide-codegen -p mir-importer --all-targets -- -D warnings
  • cargo +stable check -p cuda-oxide-codegen
  • RUSTDOCFLAGS='-D warnings' cargo +stable doc -p cuda-oxide-codegen --no-deps
  • cargo check --workspace --locked
  • cargo check --manifest-path crates/rustc-codegen-cuda/Cargo.toml --all-targets --locked
  • External stable-Rust consumer: passed.
  • cargo oxide build vecadd --arch sm_80: passed; generated PTX assembled with ptxas.
  • NVVM/PTX mode switching, automatic libdevice targeting, explicit targeting, and WGMMA NVVM targeting: passed.

No GPU kernel was executed. The downstream CubeCL repository was not revalidated and is not claimed as evidence for this repaired API.

Checklist

  • Public standalone API is explicitly experimental.
  • cuda-oxide-codegen remains rustc-free.
  • Rust and standalone callers use one shared post-translation orchestrator.
  • Caller IR is preserved across success and failure.
  • Standalone output rejects unresolved external functions.
  • Rust NVVM/libdevice behavior and artifact publication are retained.
  • Formatting, checks, tests, and ptxas validation pass.
  • Contributor and maintainer commits carry DCO sign-off.
  • GPU execution performed.
  • Downstream CubeCL integration revalidated.

@nihalpasham nihalpasham added enhancement New feature or request safety Memory safety, soundness, or undefined behavior miscompile Produces incorrect PTX/IR (wrong generated code) codegen Device code-generation pipeline (Rust MIR to IR to PTX) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) interop Interop with external compilers / frontends on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves maintainer-owned labels Jul 2, 2026
@alejandro-soto-franco
alejandro-soto-franco force-pushed the feat/compile-module-to-ptx branch from 5826ac9 to 3c3bfe4 Compare July 3, 2026 07:57
@alejandro-soto-franco alejandro-soto-franco changed the title mir-importer: non-rustc compile_module_to_ptx entry cuda-oxide-codegen: rustc-independent dialect-mir to PTX backend Jul 3, 2026
@alejandro-soto-franco
alejandro-soto-franco force-pushed the feat/compile-module-to-ptx branch from 3c3bfe4 to fa65ac4 Compare July 3, 2026 09:24
@nihalpasham nihalpasham removed on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves miscompile Produces incorrect PTX/IR (wrong generated code) maintainer-owned safety Memory safety, soundness, or undefined behavior labels Jul 3, 2026
Extract the post-translation pipeline tail out of mir-importer into a new
rustc-free crate, cuda-oxide-codegen. Its public boundary is dialect-mir: a
frontend assembles a dialect-mir module and calls
compile_to_ptx(context, module, options) to get PTX with no rustc per kernel
and no nvrtc.

The crate owns module verification, lowering to the LLVM dialect, LLVM-IR
export, architecture feature detection and PTX target selection, and the
opt/llc invocation. Every CUDA_OXIDE_* environment read inside the backend is
replaced by an explicit BackendOptions; mir-importer builds one at its own
boundary and re-exports the codegen surface, so rustc-codegen-cuda and
cargo-oxide are unchanged.

The Rust MIR path (run_pipeline) keeps its rustc-specific passes (mem2reg,
loop unroll, device externs, libdevice and NVVM linking) and calls the same
backend primitives, so the lowering pipeline exists once with no duplicate
copy. The fma-contraction policy (--no-fmad) threads through both the IR-level
contract flag and the llc -fp-contract gate via BackendOptions.

Public surface: register_backend_dialects, compile_to_ptx, PtxConfig,
PtxError, PipelineError, DeviceExternDecl, DeviceExternAttrs, DeviceExternType.
PtxConfig and PtxError are non_exhaustive; the run_pipeline plumbing items are
doc(hidden). The backend has no rustc linkage, so a consumer needs neither the
rustc_private feature nor a nightly matched to rustc_driver.

Signed-off-by: Alejandro Soto Franco <[email protected]>
@alejandro-soto-franco
alejandro-soto-franco force-pushed the feat/compile-module-to-ptx branch from fa65ac4 to b0aa828 Compare July 3, 2026 16:19
Route rustc and standalone frontends through one post-translation orchestrator. Own the public module context, clone before compiler passes, expose typed experimental options and errors, reject unresolved linking, and preserve the Rust path's NVVM and artifact behavior.

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

Copy link
Copy Markdown
Collaborator

I added a follow-up so we can land it as a experimental v1.

The final branch puts the public surface under cuda_oxide_codegen::experimental,

  • makes context/module ownership explicit, and routes standalone and Rust callers through the same post-translation pipeline.
  • it also adds reusable toolchain discovery, structured options, diagnostics and results, preserves caller IR across compilation, and fails clearly for unresolved externals or unsupported optimization instead of returning incomplete PTX.
  • hardened the temporary-file path and public/private API boundaries as well.

The experimental label is intentional:

  • v1 is revision-pinned and standalone compilation does not yet provide libdevice/device-extern linking, runtime loading.
  • unit, public API, adversarial, multithreaded, stable-consumer, llc -> ptxas, workspace, clippy, rustdoc, and real cuda-oxide codegen checks all pass.

From my side this is merge-ready as an experimental v1. Thanks for opening up this path.

@nihalpasham
nihalpasham merged commit 7efa409 into NVIDIA:main Jul 4, 2026
28 checks passed
@alejandro-soto-franco
alejandro-soto-franco deleted the feat/compile-module-to-ptx branch July 4, 2026 13:16
alejandro-soto-franco added a commit to alejandro-soto-franco/cuda-rust that referenced this pull request Jul 20, 2026
Follow-up to NVIDIA#314's cuda-oxide-codegen extraction. Fixes from a full review
of the merged PR:

- Compiler::compile no longer leaks the cloned IR if compile_clone panics;
  the erase now runs from an RAII guard instead of a plain post-call.
- Add Compiler::compile_owned for single-use callers, so the module clone
  Compiler::compile always pays for is opt-in rather than unconditional.
- Target/feature-floor validation failures from the standalone API no
  longer reference the legacy CUDA_OXIDE_TARGET env var they never touched,
  and are classified as CompilationStage::Input instead of Codegen.
  BackendOptions carries a target_arch_source label so both the env-driven
  rustc pipeline and the standalone API describe their own provenance.
- The explicit-Toolchain compile path no longer discards pipeline
  diagnostics; CompileOptions gains with_verbose/verbose so the standalone
  API can actually request them (previously unreachable through the public
  surface). Toolchain::from_paths now also reports what it selected instead
  of always returning empty diagnostics.
- ScratchDirectory is now backed by tempfile::Builder instead of a
  hand-rolled RAII implementation. The workspace tempfile floor is raised
  from 3.3 to 3.9, the first release exposing Builder::permissions, which
  the 0o700 scratch-dir mode relies on; 3.3-3.8 would fail to compile.
- Deduplicate the module-liveness check shared by mark_kernel_entry and
  Compiler::compile into one helper.
- Document (rather than attempt) the double LLVM-IR-render on the libdevice
  path: the preview and final renders are of genuinely different module
  states through different export configs, so caching one for the other
  would be unsound; a real fix needs feature detection to move off rendered
  text entirely.

Signed-off-by: Alejandro Soto Franco <[email protected]>
nihalpasham pushed a commit that referenced this pull request Jul 22, 2026
…stic paths (#415)

Follow-up to #314's cuda-oxide-codegen extraction, covering the review
findings that stand on their own.

Compiler::compile clones the caller's module and erases the clone once the
destructive pipeline has run. The erase ran as a plain statement after the
call, so a panic inside compile_clone unwound past it and leaked the clone
in the shared Context arena for the process lifetime. An RAII guard now owns
the erase. Operation::erase still runs from Drop, so a panic inside the erase
during an unwind aborts; that is left alone and documented, since an erase
fails only once the arena is already inconsistent and swallowing the second
panic would trade a loud abort for a silent leak.

Callers with no further use for a module paid for that clone regardless.
Compiler::compile_owned consumes the module and runs the pipeline on the
caller's IR directly.

mark_kernel_entry and the compile entry points each re-checked that a stored
Pliron pointer still names a live builtin.module, in duplicated form. The
check is now one helper, validate_live_module_op.

CompileOptions gains with_verbose/verbose. The pipeline has always produced
progress and target-selection diagnostics behind BackendOptions::verbose,
and the standalone API had no way to ask for them. Two paths dropped them
even when asked: generate_ptx_with_toolchain discarded everything but the
resolved target string, and compile_clone never copied the pipeline's
diagnostics into the Compilation. generate_ptx_with_toolchain now returns
GeneratedPtx, matching the discovery path, and compile_clone forwards what
it receives.

Toolchain::discover and Toolchain::from_paths both record which llc and opt
they settled on. Reporting nothing left a caller unable to tell which of
several installed LLVM versions produced an artifact.

The double LLVM-IR render on the libdevice path is now documented in place.
The preview renders pre-legalization and the export renders post-
legalization through a different export config, so the two texts describe
different module states and caching one for the other would be unsound.
Removing the second render needs feature detection that works off the IR
rather than off rendered text.

Signed-off-by: Alejandro Soto Franco <[email protected]>
meefs pushed a commit to meefs/cuda-oxide that referenced this pull request Sep 30, 2026
Signed-off-by: Melih Elibol <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codegen Device code-generation pipeline (Rust MIR to IR to PTX) enhancement New feature or request interop Interop with external compilers / frontends IR-lowering Lowering between dialects (dialect-mir to LLVM dialect)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants