Skip to content

feat: link libdevice.10.bc at IR level via llvm-link on the PTX path - #410

Merged
nihalpasham merged 4 commits into
NVIDIA:mainfrom
honeyspoon:fix-f16-libdevice-conflict
Jul 22, 2026
Merged

nihalpasham merged 4 commits into
NVIDIA:mainfrom
honeyspoon:fix-f16-libdevice-conflict

Conversation

@honeyspoon

Copy link
Copy Markdown
Contributor

Summary

When a kernel uses both f16 types (MMA/WMMA) and libdevice calls (__nv_* math functions), the pipeline auto-forces NVVM IR mode. On pre-Blackwell targets (sm<100), this selects the legacy LLVM 7 dialect which rejects f16 -- making f16 and libdevice mutually exclusive. Fix: link libdevice.10.bc at the LLVM IR level via llvm-link before opt and llc, keeping everything on the PTX path which has no f16 restrictions.

Motivation

The PTX path (llc) handles f16 natively. The NVVM IR path uses legalize_for_nvvm() which rewrites the module to LLVM 7 syntax and rejects f16 on pre-Blackwell. Libdevice calls (__nv_sinf, __nv_sqrtf, etc.) currently force the NVVM IR path because libNVVM resolves them -- but this creates an impossible constraint for kernels that also use f16.

The fix matches what build_and_run.sh already does (line 91): llvm-link kernel.ll libdevice.10.bc -o linked.bc, then opt -O2, then llc. The __nv_* calls get resolved and inlined during opt, producing self-contained PTX.

Implementation

  • cuda-oxide-codegen (llvm_tools.rs): add llvm_link: Option<OptTool> to LlvmToolchain, resolved with the same co-located/sysroot/PATH discovery as opt. Add generic resolve_sibling_tool() and sibling_tool_candidates() helpers.
  • cuda-oxide-codegen (ptx.rs): add link_libdevice() function that runs llvm-link -S. Insert linking step before opt -O2 in generate_ptx_impl(). Pass libdevice_path: Option<&Path> through generate_ptx() and generate_ptx_with_toolchain().
  • cuda-oxide-codegen (pipeline.rs): modify should_emit_nvvm_ir() so needs_libdevice only forces NVVM IR when libdevice.10.bc is not found. Discover libdevice.10.bc early via libnvvm_sys::find_libdevice() so the backend decision accounts for IR-level linking availability.
  • cuda-oxide-codegen (api.rs): resolve llvm-link as sibling tool in Toolchain::from_paths().

Pipeline with libdevice: .ll → llvm-link libdevice.10.bc → opt -O2 → llc → .ptx

Fallback (no libdevice.10.bc or no llvm-link): existing NVVM IR path unchanged.

Testing

Validated on RTX A2000 (sm_86), nightly-2026-04-03:

cargo test -p cuda-oxide-codegen   # 120 passed (107 unit + 12 integration + 1 doc)
cargo test -p mir-importer         # 805 passed
cargo fmt --all -- --check         # clean
cargo clippy -p cuda-oxide-codegen --tests -- -D warnings  # clean
scripts/smoketest.sh               # 133/141 passed (8 failures are sm_90+ features)

Related

@honeyspoon
honeyspoon force-pushed the fix-f16-libdevice-conflict branch 2 times, most recently from 08dd92b to 827b027 Compare July 22, 2026 01:16
@nihalpasham nihalpasham added enhancement New feature or request bug Something isn't working codegen Device code-generation pipeline (Rust MIR to IR to PTX) build-related Build scripts, toolchain discovery, or compilation setup intrinsics Device intrinsics and libdevice math mappings labels Jul 22, 2026
@honeyspoon
honeyspoon force-pushed the fix-f16-libdevice-conflict branch from 9b016f9 to d89786a Compare July 22, 2026 13:28
@nihalpasham
nihalpasham force-pushed the fix-f16-libdevice-conflict branch from d89786a to 9b016f9 Compare July 22, 2026 15:17
honeyspoon and others added 4 commits July 22, 2026 20:49
When a kernel uses both f16 types and libdevice calls (__nv_* math
functions), the pipeline previously auto-forced the NVVM IR path, which
selects the legacy LLVM 7 dialect on pre-Blackwell targets -- and that
dialect rejects f16. This meant f16 and libdevice were mutually
exclusive.

Fix: link libdevice.10.bc at the LLVM IR level using llvm-link before
opt and llc. The __nv_* calls get resolved and inlined during opt -O2,
and llc generates clean PTX. The PTX path has no f16 restrictions, so
both features work together.

Changes:
- Add llvm-link resolution to LlvmToolchain (same discovery pattern as
  opt: env var, co-located sibling, sysroot, versioned on PATH)
- Add link_libdevice() function in ptx.rs that runs llvm-link -S
- Insert libdevice linking step before opt -O2 in generate_ptx_impl()
- Modify should_emit_nvvm_ir() so needs_libdevice only forces NVVM IR
  when IR-level linking is unavailable (libdevice.10.bc not found)
- Discover libdevice.10.bc early in compile_translated_module() via
  libnvvm_sys::find_libdevice() so the backend decision accounts for
  IR-level linking availability

Pipeline with libdevice: .ll -> llvm-link libdevice.10.bc -> opt -O2 -> llc -> .ptx
Fallback (no libdevice.10.bc): existing NVVM IR path unchanged

Signed-off-by: abder <[email protected]>
…lvm-link

Repair two defects in the new IR-level libdevice linking path:

- `llvm-link` ran without `--internalize --only-needed`. libdevice
  bodies have plain external linkage, so all ~350 definitions were
  pulled into the module, survived GlobalDCE, and llc exported each
  one: a one-call kernel's PTX ballooned from ~130 to ~22,000 lines
  with 349 `.visible .func __nv_*` definitions, plus duplicate-symbol
  collisions for any later cuLink/nvJitLink step. Link with the
  clang-shaped flags (LinkOnlyNeeded | InternalizeLinkedSymbols) and
  pin the behavior with a regression test asserting the linked PTX
  keeps the kernel `.visible .entry` with no unreferenced `__nv_*`
  definitions.

- The PTX-vs-NVVM backend decision keyed on libdevice.10.bc file
  existence alone, before llvm-link availability was known. With the
  bitcode present but no same-major llvm-link, the pipeline committed
  to the PTX path and shipped PTX with unresolved
  `.extern .func __nv_*` that failed only at cuModuleLoad, where the
  NVVM IR path used to work. Probe for a resolvable same-major
  llvm-link at decision time (or consult the explicit toolchain) and
  fall back to the NVVM IR path exactly as before when it is missing.
  Once the PTX path is chosen, a link failure is a hard pipeline
  error instead of a warn-and-continue that emits broken PTX.

Signed-off-by: nihalp <[email protected]>
- register `<name>.linked.ll` in the stale-artifact cleanup so a
  previous IR-linked module cannot linger next to fresh outputs
- reconcile the `Toolchain::discover` / `from_paths` and
  `BackendOptions::from_env` doc contracts with the new
  CUDA_OXIDE_LLVM_LINK env read and the same-major llvm-link rule
- fold `sibling_opt_candidates` into the generic
  `sibling_tool_candidates` helper introduced for llvm-link

Signed-off-by: nihalp <[email protected]>
Three fixes to the libdevice IR-linking regression coverage:

- The exported-body assertion only matched the substring
  `.visible .func __nv_`, which llc emits for void-returning functions.
  Value-returning libdevice bodies print as
  `.visible .func  (.param .b32 func_retval0) __nv_clz(` and slipped
  past: on a bloated (un-internalized) link the old check saw 5 of 349
  exported definitions. Parse `.visible .func` lines past the optional
  return-parameter clause and flag any declared `__nv_*` symbol.

- `unreferenced_nv_definitions` marked a definition as referenced when
  any call line contained it as a substring, so a call to `__nv_sinf`
  wrongly vouched for an unreferenced `__nv_sin` body. Referenced-by-call
  detection now requires an exact identifier token match.

- The pipeline's opt stage names its intermediate after its input, so a
  libdevice-linked build leaves `<name>.linked.opt.ll` next to
  `<name>.linked.ll` (verified via a verbose libdevice_math build).
  Register the `linked.opt.ll` suffix in mir-importer's
  stale_compilation_artifact_paths and extend the invalidation test.

Both detectors also gain toolchain-free unit coverage, since the full
regression test skips on machines without llc/opt/llvm-link/libdevice.

Signed-off-by: nihalp <[email protected]>
@nihalpasham
nihalpasham force-pushed the fix-f16-libdevice-conflict branch from 9b016f9 to 429adb8 Compare July 22, 2026 15:21
@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks for the PR. LGTM

  • I pushed maintainer commits completing it:
    • the llvm-link invocation now passes --internalize --only-needed (clang's LinkOnlyNeeded | InternalizeLinkedSymbols); without them every libdevice body has external linkage, survives GlobalDCE, and a one-call kernel's PTX ballooned from ~132 to ~21,800 lines with 349 exported __nv_* bodies. A regression test links a real kernel and asserts no unreferenced __nv_* definition survives;
    • the PTX-vs-NVVM decision now requires a resolvable same-major llvm-link at decision time (not just a libdevice file on disk) and falls back to the NVVM-IR path exactly as before the PR; once the PTX path is chosen, a link failure is a hard error instead of warn-and-continue emitting PTX with unresolved .extern .func __nv_*;
    • plus cleanups: linked.ll/linked.opt.ll in stale-artifact cleanup, toolchain doc contracts reconciled with CUDA_OXIDE_LLVM_LINK, sibling-tool discovery deduplicated, and the regression detector hardened (value-returning .visible .func (.param ...) __nv_* forms and identifier-boundary reference matching — proven against the 349-definition bloat).

For example:

#[kernel] fn k(out: &mut [f32], h: f16, x: f32) {
    out[0] = f32::from(h) + x.sin();     // f16 AND __nv_sinf together
}

before: __nv_sinf forces the NVVM-IR path; legacy dialect rejects f16
after:  llvm-link --internalize --only-needed -> 527-line self-contained PTX via llc

Reviewer note: cuda-oxide-codegen tests pass; libdevice_math and math_atan PASS on an RTX 5090 via the new path with zero __nv_* residue in PTX; the fallback path (llvm-link unresolvable) still runs via NVVM-IR; an sm_90 build assembles under ptxas -arch=sm_90; fuzzer seed 162 passes with the new PTX artifact kind. Land after #415 (both rework cuda-oxide-codegen; the reconciliation is spelled out in the review record). Related: #414 is closed by #395; #390/#380/#386 stay open. All hosted CI checks passed on the final head.

@nihalpasham
nihalpasham merged commit 2b12699 into NVIDIA:main Jul 22, 2026
33 checks passed
nihalpasham added a commit to niklebedenko/cuda-oxide that referenced this pull request Jul 23, 2026
The NVIDIA#410 libdevice test predates public_symbols; pass the module's
kernel as the internalization root so the test now also covers the
llvm-link + internalize composition.
nihalpasham added a commit to niklebedenko/cuda-oxide that referenced this pull request Jul 23, 2026
Threading public_symbols through generate_ptx alongside NVIDIA#410's libdevice
parameter pushed both entry points past clippy's argument limit. The
module-shaped inputs (IR path, PTX output path, symbol roots) already
had a struct inside the impl; take PtxModule at the public boundary too
instead of three loose parameters.
nihalpasham added a commit that referenced this pull request Jul 23, 2026
* fix(ptx): internalize non-root device helpers

Signed-off-by: nik <[email protected]>

* refactor(llvm-export): compute one root list for @llvm.used and internalization

emit_llvm_used and public_symbols each re-implemented the
kernels-if-any-else-device-functions rule, so the @llvm.used set and the
internalize public-API list could silently drift apart. Compute the root
list once, as the union of kernel entries and #[device] definitions:
a #[device] export now stays visible even in a module that also has
kernels, while anonymous helpers carry neither marker and remain
internalizable.

* test(codegen): thread the kernel root through the libdevice PTX test

The #410 libdevice test predates public_symbols; pass the module's
kernel as the internalization root so the test now also covers the
llvm-link + internalize composition.

* refactor(codegen): group PTX module inputs into one parameter struct

Threading public_symbols through generate_ptx alongside #410's libdevice
parameter pushed both entry points past clippy's argument limit. The
module-shaped inputs (IR path, PTX output path, symbol roots) already
had a struct inside the impl; take PtxModule at the public boundary too
instead of three loose parameters.

* test(smoke): pin helper_fn's nested-helper contract in the pre-opt IR

The compile-only gate required the two nested_identity monomorphizations
to survive as .visible .func in the final PTX. Internalizing non-root
helpers deliberately inlines and deletes them there, which is the
optimization this branch adds. What the #358 regression actually needs
pinned is canonical mangling and non-kernel classification, and both
are decided before the middle-end runs: assert them in the pre-opt
LLVM IR instead, and keep the PTX assertions for the single kernel
entry and the absence of _TID_ helper symbols.

---------

Signed-off-by: nik <[email protected]>
Co-authored-by: nihalpasham <[email protected]>
@honeyspoon
honeyspoon deleted the fix-f16-libdevice-conflict branch July 23, 2026 13:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working build-related Build scripts, toolchain discovery, or compilation setup codegen Device code-generation pipeline (Rust MIR to IR to PTX) enhancement New feature or request intrinsics Device intrinsics and libdevice math mappings

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants