Repository navigation
codegen: opt-in libdevice linking for the standalone PTX API - #596
Merged
nihalpasham merged 10 commits intoJul 31, 2026
Merged
nihalpasham merged 10 commits into
nihalpasham merged 10 commits into
Conversation
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".
Contributor
Author
|
Re-verified on CUDA 13.3.1, having been developed against 13.1.
13.3's libdevice also references only |
Collaborator
|
LGTM. Verified on hardware:
Merging; closes #485. |
nihalpasham
approved these changes
Jul 31, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #485.
A frontend driving
cuda_oxide_codegen::experimentalstops at the firstsqrt. Float intrinsics lower to libdevice__nv_*calls, and v1 rejects every unresolved external symbol. The rejection atpipeline.rs:364sits directly above the IR-level libdevice link atpipeline.rs:417, so a module is refused for symbols the step below it would have resolved.Linking::SelfContainedis 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
CompileOptionsfieldChosen: a field, with discovery inside the pipeline.
Alternative: the caller passes a path to
libdevice.10.bc.Discovery reuses the
libnvvm_sys::find_libdevice()callcompile_translated_modulealready 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
ExternalLinkAlloweddoes.should_emit_nvvm_irreturnsfalseforSelfContainedPtxwhatever 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 newCompileError::LibdeviceUnavailablenaming which piece is missing, since an absentlibdevice.10.bcand an absentllvm-linkhave different fixes.What the filter admits
Symbols beginning
__nv_. The predicate sits besideunresolved_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 formir-lowerto recognise,__nv_erffand__nv_rhypotfamong 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
NVVMReflectPassresolves an unset one to 0.__CUDA_PREC_SQRTsqrt.approx.f32-prec-sqrt=true__CUDA_FTZ-ftz=false, already matches__CUDA_ARCH-mcpuNothing in the tree passed a reflect variable to
llc, so everysqrtreaching libdevice compiled tosqrt.approx.f32where nvcc producessqrt.rn.f32.This reaches the rustc frontend too. The arguments are keyed on a link having happened rather than on the output policy, and
sqrthas no entry inllvm_intrinsic_name, so any kernel callingf32::sqrtmoves tosqrt.rn.f32wherever IR-level linking is available. That is the result Rust specifies forf32::sqrtand the one nvcc produces by default, and it removes a disagreement between this path and the libNVVM fallback. Callers wanting the fast path havecuda_device::float::sqrt_approx_f32. Nothing in the tree assertssqrt.approx.f32as a libdevice-path output, andrustc-codegen-cudais 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.rsand applies cleanly tomain.A caveat
llvm-link --only-neededresolves what it has and stays silent about the rest. A__nv_*name libdevice does not define survived into the PTX as.extern .funcand failed atcuModuleLoad;ptxasaccepts such PTX, so nothing downstream caught it. The pipeline now scans for surviving__nv_*declarations after linking and reports them throughUnsupportedLinking.That scan is scoped to
SelfContainedPtx.can_ir_link_libdeviceis computed from tool availability alone, soExternalLinkAllowed { 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 warningsand rustdoc clean. +915/−26 againstmain, seven files.ptxas -arch=sm_120accepts every generated artifact. On device (RTX 5060 Laptop, sm_120) thesqrtkernel is bit-exact againstf32::sqrtover 256 values; before the precision fix it computed the approximate result.The integration tests require
llvm-linkand a discoverablelibdevice.10.bc, which are new requirements for this crate. Thecuda-oxide-codegenjob setsneeds_cuda: trueandrust-toolchain.tomlincludesllvm-tools, so CI has both.