Skip to content

codegen: opt-in libdevice linking for the standalone PTX API - #596

Merged
nihalpasham merged 10 commits into
NVIDIA:mainfrom
alejandro-soto-franco:feat/standalone-libdevice-linking
Jul 31, 2026
Merged

nihalpasham merged 10 commits into
NVIDIA:mainfrom
alejandro-soto-franco:feat/standalone-libdevice-linking

Conversation

@alejandro-soto-franco

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

Copy link
Copy Markdown
Contributor

Closes #485.

A frontend driving cuda_oxide_codegen::experimental stops at the first sqrt. Float intrinsics lower to libdevice __nv_* calls, and v1 rejects every unresolved external symbol. The rejection at pipeline.rs:364 sits directly above the IR-level libdevice link at pipeline.rs:417, so a module is refused for symbols the step below it would have resolved.

pub enum Linking { SelfContained, Libdevice }

impl CompileOptions {
    pub fn with_linking(self, linking: Linking) -> Self;
    pub fn linking(&self) -> Linking;
}

Linking::SelfContained is the default and changes no compilation that succeeds today: no link runs, and the symbol filter is the identity.

Design decisions and rejected alternatives

1. The option belongs in experimental v1

Chosen: a default-off option on the existing surface.

Alternative: hold it for a v2 that redesigns linking properly.

No existing consumer changes, and a v2 stays free to supersede it. It is the smallest shape that unblocks an out-of-tree frontend and the cheapest to withdraw.

2. A CompileOptions field

Chosen: a field, with discovery inside the pipeline.

Alternative: the caller passes a path to libdevice.10.bc.

Discovery reuses the libnvvm_sys::find_libdevice() call compile_translated_module already makes on this path, so the API gains no filesystem search it did not already perform. A caller-supplied path adds a parameter that duplicates work already done.

3. No NVVM IR fallback for standalone callers

Chosen: one path in, one artifact kind out.

Alternative: fall back to NVVM IR when the link is unavailable, as ExternalLinkAllowed does.

should_emit_nvvm_ir returns false for SelfContainedPtx whatever the flag holds, and a test loops all eight combinations of the flag, strict-libdevice use and link availability to pin it. When the link is needed and unavailable, compilation fails with a new CompileError::LibdeviceUnavailable naming which piece is missing, since an absent libdevice.10.bc and an absent llvm-link have different fixes.

What the filter admits

Symbols beginning __nv_. The predicate sits beside unresolved_external_symbols, so the libdevice detector, the surviving-declaration scan and the filter read one definition. Unresolved symbols that are not libdevice are still rejected, and a module carrying both loses only the libdevice half.

This admits any __nv_* symbol, including one a frontend names itself. Several libdevice functions have no Rust intrinsic and so no placeholder callee for mir-lower to recognise, __nv_erff and __nv_rhypotf among them. The alternative for such a frontend is a polynomial approximation, which gives up bit-exactness against nvcc for a function CUDA already ships. Both routes have tests.

Fixing a precision defect

The first test asserting which instruction libdevice produces failed. libdevice selects an implementation by reading reflect variables, and NVVMReflectPass resolves an unset one to 0.

reflect variable unset nvcc default this PR
__CUDA_PREC_SQRT 0, selects sqrt.approx.f32 -prec-sqrt=true passes 1
__CUDA_FTZ 0 -ftz=false, already matches leaves unset
__CUDA_ARCH resolved from -mcpu leaves unset

Nothing in the tree passed a reflect variable to llc, so every sqrt reaching libdevice compiled to sqrt.approx.f32 where nvcc produces sqrt.rn.f32.

This reaches the rustc frontend too. The arguments are keyed on a link having happened rather than on the output policy, and sqrt has no entry in llvm_intrinsic_name, so any kernel calling f32::sqrt moves to sqrt.rn.f32 wherever IR-level linking is available. That is the result Rust specifies for f32::sqrt and the one nvcc produces by default, and it removes a disagreement between this path and the libNVVM fallback. Callers wanting the fast path have cuda_device::float::sqrt_approx_f32. Nothing in the tree asserts sqrt.approx.f32 as a libdevice-path output, and rustc-codegen-cuda is a separate workspace with no PTX assertions, so no written expectation changes.

Happy to split this into its own pull request if you would rather judge it on numerics. It touches only ptx.rs and applies cleanly to main.

A caveat

llvm-link --only-needed resolves what it has and stays silent about the rest. A __nv_* name libdevice does not define survived into the PTX as .extern .func and failed at cuModuleLoad; ptxas accepts such PTX, so nothing downstream caught it. The pipeline now scans for surviving __nv_* declarations after linking and reports them through UnsupportedLinking.

That scan is scoped to SelfContainedPtx. can_ir_link_libdevice is computed from tool availability alone, so ExternalLinkAllowed { request_nvvm_ir: false } can also reach the direct-PTX-with-linked-libdevice route on a machine holding both pieces, and the same class of unresolved symbol stays reachable there. That predates this branch and is untouched by it.

Verification and testing

160 tests across 6 suites, debug and release. fmt, clippy --workspace --all-targets -D warnings and rustdoc clean. +915/−26 against main, seven files.

ptxas -arch=sm_120 accepts every generated artifact. On device (RTX 5060 Laptop, sm_120) the sqrt kernel is bit-exact against f32::sqrt over 256 values; before the precision fix it computed the approximate result.

The integration tests require llvm-link and a discoverable libdevice.10.bc, which are new requirements for this crate. The cuda-oxide-codegen job sets needs_cuda: true and rust-toolchain.toml includes llvm-tools, so CI has both.

Threads a single allow_libdevice flag from the experimental compile
options into OutputPolicy::SelfContainedPtx. Nothing reads the flag yet,
so behaviour is unchanged and Linking::SelfContained stays the default.

should_emit_nvvm_ir keeps returning false for the self-contained policy
whatever the flag holds, so the standalone surface still has exactly one
artifact kind out. A loop over both flag values pins that.
The rejection sat above the IR-level libdevice link, so a module was
refused for symbols the step below it would have resolved. Under
Linking::Libdevice the collected symbols are narrowed to the ones that
are not libdevice before the check decides.

is_libdevice_symbol gives the __nv_ prefix one definition, which both
the filter and the existing detector now read.
Opting into libdevice on a host with no libdevice.10.bc, or with no
llvm-link sharing the llc major, previously produced PTX carrying
unresolved .extern .func __nv_* declarations that failed at
cuModuleLoad. The compilation now stops at the linking stage and the
message names which of the two pieces is missing, since the fixes
differ.
A debug_assert let a release build read a non-PTX artifact from the PTX
path and hand it back as PTX. The policy makes that unreachable today;
the check keeps it unreachable if a later policy variant reaches this
code.
libdevice picks between correctly-rounded and approximate implementations
by reading __CUDA_PREC_SQRT and __CUDA_PREC_DIV through __nvvm_reflect.
LLVM resolves an unset reflect variable to 0, which selects the
approximate branch, while nvcc defaults both to true. A sqrt kernel
therefore compiled to sqrt.approx.f32 with nothing reporting the
divergence.

Both are now passed to llc whenever libdevice is linked. __CUDA_FTZ
stays unset, since nvcc defaults -ftz=false and 0 already matches.

The arguments are keyed on a link having happened rather than on the
output policy, so this reaches the rustc frontend as well: a kernel
calling f32::sqrt moves from sqrt.approx.f32 to sqrt.rn.f32 wherever
IR-level linking is available. That is the result Rust specifies for
f32::sqrt and the one nvcc produces by default, and it removes a
disagreement between this path and the libNVVM fallback. Callers who
want the fast path have cuda_device::float::sqrt_approx_f32.
Builds out[i] = sqrt(a[i]) in dialect-mir and compiles it under both
linking policies. The default still fails with UnsupportedLinking naming
__nv_sqrtf; the opt-in produces PTX carrying sqrt.rn.f32, no residual
.extern .func __nv_ declaration, and a cubin that ptxas accepts at
sm_120.

The inlined-instruction assertion is deliberate: a check that the __nv_
symbol is merely absent would also pass if the declaration had been
dropped without linking.
__nv_erff has no Rust intrinsic behind it, so a frontend reaches it by
naming the symbol. The filter admits any __nv_ symbol, which is what
makes that route work, and this pins the detector agreement the pipeline
refuses to continue without.

A device extern under the same opt-in still fails, so UnsupportedLinking
keeps its meaning.
The contract stated the self-contained rule without qualification. It
now covers the option, its default, and the two ways a compilation can
still fail under it.
…olved

llvm-link --only-needed resolves whatever __nv_* symbols it finds in
libdevice.10.bc and stays silent about the rest; opt and llc both exit
0 on what remains, and ptxas accepts the resulting PTX. Before this
branch that input produced a compile-time UnsupportedLinking; under
Linking::Libdevice it instead produced a PTX artifact that only fails
at cuModuleLoad on the device, with no diagnostic. The realistic
trigger is version skew: a frontend names a __nv_* function a newer
toolkit added but the installed libdevice lacks.

Scan the emitted PTX for surviving `.extern .func __nv_*` declarations
after PTX generation and fail with UnsupportedLinking naming them. The
scan runs only under OutputPolicy::SelfContainedPtx, which promises a
single, already-loadable artifact with no further link step. Under
ExternalLinkAllowed (the rustc frontend) an unresolved __nv_* stays
legitimate: that consumer owns a later libNVVM/nvJitLink step and
resolves it there, so the scan leaves that policy untouched.

Also add end-to-end coverage for LibdeviceUnavailable by pointing
CUDA_OXIDE_LLVM_LINK at a nonexistent path. The mutation runs in a
re-exec'd child process so it cannot race the other tests in this file
that call Compiler::discover() and expect a working llvm-link.
- Drop the internal "Task 6" reference from a test comment; it names
  nothing a reader of this repository can resolve.
- Drop "genuinely" from the add_llvm_declaration doc comment.
- Rename linked_libdevice_honours_nvcc_precision_defaults to
  ...honors..., matching the American spelling already used elsewhere
  in this crate (link_capable_pipeline_honors_requests_and_libdevice,
  and "honors" in api.rs).
- Reword the reflect-arguments comment so it states a fact about
  current libdevice builds rather than the toolkit on one machine.
- State the erff resolution assertion affirmatively instead of as a
  contrastive "not left extern".
@alejandro-soto-franco

alejandro-soto-franco commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Re-verified on CUDA 13.3.1, having been developed against 13.1.

  • 160 tests and 6 suites are unchanged.
  • sqrt.rn.f32 in the emitted PTX.
  • On device, sm_120: bit-exact against f32::sqrt over 256 values.

13.3's libdevice also references only __CUDA_ARCH, __CUDA_FTZ and __CUDA_PREC_SQRT, so __CUDA_PREC_DIV is inert on that build too.

@nihalpasham nihalpasham added enhancement New feature or request bug Something isn't working miscompile Produces incorrect PTX/IR (wrong generated code) codegen Device code-generation pipeline (Rust MIR to IR to PTX) intrinsics Device intrinsics and libdevice math mappings interop Interop with external compilers / frontends labels Jul 31, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

LGTM.

Verified on hardware:

  • all cuda-oxide-codegen suites pass locally (162 tests) with llvm-link, libdevice, and ptxas present.
  • the other fix reaches the rustc frontend as intended: libdevice_math passes on GPU and its PTX carries sqrt.rn.f32 for f32::sqrt; the only approx form left is rsqrt, which has no precision knob. sqrt_approx_f32 remains the explicit fast path.
  • one correction to the PR's write-up: clang doesn't actually match nvcc here. I checked clang-21 and 22 - both leave __CUDA_PREC_SQRT unset and ship approximate sqrt, same hole we had. nvcc and libNVVM are the ones that default precise, and Rust documents f32::sqrt as correctly rounded, so this is the right call. Will release-note the sqrt change.

Merging;

closes #485.

@nihalpasham
nihalpasham merged commit a39a089 into NVIDIA:main Jul 31, 2026
33 checks passed
@alejandro-soto-franco
alejandro-soto-franco deleted the feat/standalone-libdevice-linking branch September 9, 2026 17:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working codegen Device code-generation pipeline (Rust MIR to IR to PTX) enhancement New feature or request interop Interop with external compilers / frontends intrinsics Device intrinsics and libdevice math mappings miscompile Produces incorrect PTX/IR (wrong generated code)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Experimental standalone API cannot compile libdevice calls, though the pipeline can now link them

2 participants