Skip to content

fix(mir-lower): lower rounding intrinsics to LLVM instead of libdevice - #466

Merged
nihalpasham merged 8 commits into
NVIDIA:mainfrom
honeyspoon:fix/scalar-float-llvm-intrinsics
Jul 25, 2026
Merged

nihalpasham merged 8 commits into
NVIDIA:mainfrom
honeyspoon:fix/scalar-float-llvm-intrinsics

Conversation

@honeyspoon

@honeyspoon honeyspoon commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Lower Rust math intrinsics with direct LLVM equivalents to their native
LLVM intrinsic names instead of routing through libdevice. The NVPTX
backend lowers each to a single PTX instruction, avoiding the libdevice
function-call overhead.

Partial fix for #390.

Operations routed to LLVM intrinsics

Rust intrinsic LLVM intrinsic PTX instruction
f32::abs() / f64::abs() llvm.fabs.* abs.f32 / abs.f64
f32::copysign() / f64::copysign() llvm.copysign.* copysign.f32 / copysign.f64
f32::floor() / f64::floor() llvm.floor.* cvt.rmi.f32.f32
f32::ceil() / f64::ceil() llvm.ceil.* cvt.rpi.f32.f32
f32::trunc() / f64::trunc() llvm.trunc.* cvt.rzi.f32.f32
f32::round() / f64::round() llvm.round.* round-ties-away
f32::round_ties_even() llvm.roundeven.* cvt.rni.f32.f32

Motivation

These operations are pure register-to-register transforms with exact LLVM
intrinsic equivalents. Routing them through libdevice adds an unnecessary
function call and forces the kernel onto the heavier libNVVM/nvJitLink
pipeline even when no transcendental math is used.

For rounding specifically, this eliminates the need for hand-written
IEEE-754 bit tricks (e.g., a ~10-instruction round_ties_away() function)
in user kernels -- x.floor(), x.ceil(), etc. now compile to single
PTX instructions.

Deliberate exclusions

max/min are intentionally left on the libdevice path. LLVM 21's
maxnum/minnum propagate signaling NaNs, which contradicts Rust's
contract (f32::max returns the non-NaN operand). These need
compare/select lowering instead, as addressed by #391.

Implementation

Added RustFloatMathIntrinsic::llvm_intrinsic_name() in
crates/mir-lower/src/convert/ops/call.rs which returns the width-qualified
LLVM intrinsic name for ops that can bypass libdevice. The existing
convert_rust_float_math_intrinsic() checks this method first, falling
through to libdevice_name() only for transcendentals (sin, cos, exp,
log, pow, etc.) that have no single-instruction PTX equivalent.

Testing

cargo test -p mir-lower --lib   # 136 tests pass
cargo fmt --all -- --check      # clean

Unit test test_llvm_intrinsic_name_routing verifies:

  • fabs returns llvm.fabs.f32 / llvm.fabs.f64
  • copysign returns llvm.copysign.f32 / llvm.copysign.f64
  • All 10 rounding ops (floor/ceil/trunc/round/roundeven x f32/f64) return correct LLVM names
  • MaxNumNsz/MinNumNsz return None (libdevice path, per Simple scalar float operations unnecessarily require libdevice #390)
  • Transcendentals (SinF32, SqrtF64) return None (libdevice path)

… libdevice

`f32::abs()`, `f64::abs()`, `f32::copysign()`, and `f64::copysign()` are
pure sign-bit operations with direct LLVM intrinsic equivalents
(`llvm.fabs.*`, `llvm.copysign.*`). Routing them through libdevice
(`__nv_fabsf`, `__nv_copysignf`) added an unnecessary function call and
forced the kernel onto the heavier libNVVM pipeline even when no
transcendental math was used.

This is the first step toward resolving NVIDIA#390. The `max`/`min` operations
are left on the libdevice path for now because their NaN semantics need
more careful treatment.

Signed-off-by: abder <[email protected]>
@honeyspoon

Copy link
Copy Markdown
Contributor Author

Note: there is overlap between this PR and #391 from @niklebedenko, which takes a broader approach (also covers max_nsz and min_nsz via ordered compare/select). If #391 is preferred, this PR can be closed — the fabs/copysign lowering approach is the same in both.

@honeyspoon honeyspoon changed the title fix(mir-lower): lower fabs and copysign to LLVM intrinsics instead of libdevice fix(mir-lower): lower fabs, copysign, rounding, and min/max to LLVM intrinsics Jul 24, 2026
…evice

Extend llvm_intrinsic_name() to route floor, ceil, trunc, round, and
roundeven through their LLVM intrinsic equivalents instead of libdevice
calls. The NVPTX backend lowers these to single PTX cvt instructions
(cvt.rmi/rpi/rzi/rni), avoiding the libdevice function-call overhead.

max/min are intentionally left on the libdevice path: LLVM 21's
maxnum/minnum propagate signaling NaNs, contradicting Rust's contract.
These need compare/select lowering instead (see NVIDIA#390).

Signed-off-by: abder <[email protected]>
@honeyspoon
honeyspoon force-pushed the fix/scalar-float-llvm-intrinsics branch from b8ee2af to b778635 Compare July 24, 2026 14:58
@honeyspoon honeyspoon changed the title fix(mir-lower): lower fabs, copysign, rounding, and min/max to LLVM intrinsics fix(mir-lower): lower fabs, copysign, and rounding to LLVM intrinsics Jul 24, 2026
The comment claimed every routed intrinsic lowers to a single PTX
instruction and listed `round` among the `cvt` conversions. That is wrong
for `round`: it rounds halfway cases away from zero, and none of the four
hardware `cvt` modes does that (`rni` is ties-to-even), so no single
instruction can express it.

Measured with LLVM 21.1 `llc -march=nvptx64 -mcpu=sm_80`, body only:

  fabs, copysign, floor, ceil, trunc, roundeven -> 1 instruction each
  round                                         -> 11 (f32), 8 (f64)

`round` is still worth routing here: LLVM expands it inline into
compare/select over `cvt.rzi` rather than emitting a `roundf` libcall, so
the libdevice call goes away without leaving an unresolved symbol. The doc
now states that instead of implying a single `cvt`, and carries the table
so the next reader does not have to re-measure.

No functional change.

Signed-off-by: abder <[email protected]>
NVIDIA#391 ("keep scalar float math on the LLVM-to-PTX path") also moves fabs and
copysign off libdevice, and does it as part of a broader change that
additionally handles max/min. That makes it the more general treatment of the
overlap, so this PR drops fabs and copysign and keeps only the rounding
operations, which NVIDIA#391 does not cover.

max/min stay out of scope here for a reason worth stating: they cannot use
`llvm.maxnum`/`llvm.minnum` at all, because under LLVM 21 those propagate
signaling NaNs and contradict Rust's contract. NVIDIA#391 lowers them as an ordered
compare/select instead.

With fabs gone the method no longer needs the context or result type, since
every rounding variant is already type-specific (`FloorF32` vs `FloorF64`), so
the signature loses both parameters. The test now asserts fabs and copysign
return `None` here, which is what pins the scope boundary and will fail
loudly if the two PRs start overlapping again.

Also reduces the conflict surface: both PRs restructure the same fabs path,
this one via a method and NVIDIA#391 via a standalone `fabs_llvm_intrinsic_name`.

Signed-off-by: abder <[email protected]>
@honeyspoon honeyspoon changed the title fix(mir-lower): lower fabs, copysign, and rounding to LLVM intrinsics fix(mir-lower): lower rounding intrinsics to LLVM instead of libdevice Jul 24, 2026
@honeyspoon

Copy link
Copy Markdown
Contributor Author

Narrowed to rounding only, to remove the overlap with #391.

#391 moves fabs and copysign off libdevice as part of a broader change that also handles max/min, so it is the more general treatment of the part we both touched. I have dropped fabs and copysign from this PR; it now covers only floor, ceil, trunc, round, and roundeven, which #391 does not touch. The two should no longer conflict, and the test here asserts fabs/copysign return None so the boundary fails loudly if that changes.

While measuring, one correction to what this PR originally claimed. It said every routed intrinsic lowers to a single PTX instruction and listed round among the cvt conversions. That is wrong for round. With LLVM 21.1 llc -march=nvptx64 -mcpu=sm_80, body only:

floor      -> cvt.rmi             1
ceil       -> cvt.rpi             1
trunc      -> cvt.rzi             1
roundeven  -> cvt.rni             1
round      -> expanded sequence   11 (f32), 8 (f64)

round rounds halfway cases away from zero, and that is not one of the four hardware cvt modes (rni is ties-to-even), so no single instruction can express it. It is still worth routing here: LLVM expands it inline into compare/select over cvt.rzi rather than emitting a roundf libcall, so the libdevice call goes away without leaving an unresolved symbol. The table is now in the doc comment so the next reader does not have to re-measure.

Happy to rebase on top of #391 once it lands if you would prefer these stacked.

@nihalpasham nihalpasham added perf Performance of generated code or of the compiler itself enhancement New feature or request IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) codegen Device code-generation pipeline (Rust MIR to IR to PTX) intrinsics Device intrinsics and libdevice math mappings labels Jul 25, 2026
Pliron identifiers reject dots, so the dotted LLVM names
("llvm.floor.f32", ...) in the new rounding routing table failed
symbol creation inside ensure_intrinsic_declared and every
rounding-only kernel aborted with:

  Failed to declare intrinsic: Invalid intrinsic name 'llvm.floor.f32':
  ... MalformedIdentifierErr("llvm.floor.f32")

Use the underscore encoding ("llvm_floor_f32") that the rest of the
lowering already uses for llvm_ctpop_i*/llvm_bswap_i* and friends; the
textual .ll exporter decodes it back to the dotted LLVM intrinsic name
on export.
…nt libdevice

The ten rounding placeholders (floor/ceil/trunc/round/roundeven x
f32/f64) no longer lower to libdevice on the LLVM NVPTX path; they
lower to the native llvm.floor.*-family intrinsics. Leaving them in
is_libdevice_backed_placeholder made the pre-lowering predictor claim
libdevice for rounding-only kernels while the lowered module contained
no __nv_* symbol, so the pipeline consistency check aborted every
rounding-only compilation with "libdevice backend selection changed
during MIR lowering".

Split the classification in two exact, mutually disjoint allow-lists:

* is_libdevice_backed_placeholder: ops that need libdevice under every
  intrinsic backend (transcendentals, fma, fabs/copysign, max/min).
* is_backend_dependent_libdevice_placeholder: exactly the ten rounding
  ops, which need libdevice only when the pipeline emits NVVM IR (the
  legacy LLVM 7-based NVVM dialect predates llvm.roundeven.*).

The classification test now asserts every placeholder in the module
against both predicates, so the sets stay exact and disjoint.
The rounding routing table applied unconditionally, so a module headed
to libNVVM would receive llvm.roundeven.* and friends: the legacy
LLVM 7-based NVVM IR dialect predates llvm.roundeven (LLVM 11) and
admits only a small intrinsic allow-list, so those forms do not exist
there. Every sibling intrinsic conversion (tma, mbarrier, dotprod,
cp_async) already branches on the pipeline-selected IntrinsicBackend;
do the same for float math:

* LlvmNvptx: rounding uses the native LLVM intrinsics (new capability,
  no libdevice); everything else stays on libdevice.
* LibNvvm: every float-math op stays on libdevice (__nv_floorf, ...),
  the only spelling portable across all libNVVM input dialects.

Make the pre-lowering libdevice prediction backend-aware to match,
keeping the post-lowering consistency check sound in both directions:
only strict libdevice use (transcendentals, direct __nv_* calls) can
force the NVVM IR fallback, and the predicted needs_libdevice adds the
backend-dependent rounding placeholders exactly when the LibNvvm
backend was selected. Without this, a rounding-only kernel built with
--emit-nvvm-ir would emit __nv_floorf while the prediction said no
libdevice, tripping the same consistency abort in the other direction.

Also fixes the stale "(abs, copysign, rounding)" comment at the
routing site (the narrowed scope is rounding only) and generalizes the
typed-MIR walker to take a callee predicate instead of duplicating the
traversal.
A kernel whose only math-library usage is rounding now compiles on the
self-contained PTX path with zero libdevice involvement; this example
locks that capability in (the generated float_rounding.ll must contain
no __nv_ symbols) and pins the rounding semantics on device with
bit-exact host comparisons:

* round is ties-away-from-zero: round(2.5)==3.0, round(-2.5)==-3.0
* round_ties_even is ties-to-even: 2.5 -> 2.0, 3.5 -> 4.0
* signed zero survives: round(-0.4) == -0.0
* floor(-1.5)==-2.0, ceil(-1.5)==-1.0, trunc(-1.7)==-1.0

Both float widths run all five ops over halfway ties, signed zeros,
fractions on both sides of .5, exact integers, and large values.

Before the preceding fixes this example failed to compile: first with
the malformed-identifier error from the dotted intrinsic names, then
(names fixed) with the "libdevice backend selection changed during MIR
lowering" consistency abort from the stale pre-lowering predictor.
@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks, this makes sense. The PTX mapping table in the PR is quite useful. As diffed it could not compile a rounding kernel though, so I pushed four commits on top:

  • pliron identifiers reject dots, so the dotted names (llvm.floor.f32) failed with MalformedIdentifierErr before anything ran. The table now uses the repo's underscore encoding (llvm_floor_f32), which the exporter decodes back to the dotted name (same mechanism as llvm_ctpop_i*).
  • The pre-lowering libdevice predictor still classified the ten rounding placeholders as libdevice-backed, so every rounding-only kernel died on the pipeline consistency check. They are now a separate backend-dependent class.
  • The lowering dispatches on the intrinsic backend: the llc path gets llvm.* (single cvt instructions), the LibNvvm path keeps __nv_* (the legacy LLVM 7 dialect has no llvm.roundeven).
  • Added a rounding-only float_rounding example pinning tie-breaking and signed zero on device.

Verified on an RTX 5090: rounding-only kernels now build self-contained PTX with zero libdevice, --emit-nvvm-ir still compiles via libNVVM with __nv_* rounding, and libm_math/primitive_stress pass. Related to #390; #391 owns the max/min move and now has the backend-aware pattern to follow.

@nihalpasham
nihalpasham merged commit b099f64 into NVIDIA:main Jul 25, 2026
33 checks passed
nihalpasham added a commit to niklebedenko/cuda-oxide that referenced this pull request Jul 28, 2026
…ibdevice prediction

Completes the rebase of NVIDIA#391 onto the IntrinsicBackend dispatch that NVIDIA#466
introduced after the PR was written; this part of the contributor's change
could not be expressed as a rebase of their diff, so it is re-implemented
here as a maintainer integration commit.

Without this, select_pre_lowering_backend still classified fabs/copysign
and the float max/min placeholders as strict libdevice, so kernels using
only those ops were forced onto the NVVM-IR / libdevice route and the
LLVM-to-PTX lowering from the previous commit never engaged (and the
post-lowering consistency check would abort the build once it did).

- rust_intrinsics: move CALLEE_FABS / CALLEE_COPYSIGN_F32/F64 from
  is_libdevice_backed_placeholder to
  is_backend_dependent_libdevice_placeholder (llvm.fabs/llvm.copysign on
  the NVPTX path, __nv_fabs*/__nv_copysign* only under libNVVM), and drop
  CALLEE_MAXNUM_NSZ_* / CALLEE_MINNUM_NSZ_* from both lists (they expand
  to an ordered compare/select under every backend and never use
  libdevice). Classification test arrays updated to match.
- mir-lower: the now-unreachable max/min arms of libdevice_name are a
  hard error, mirroring the f*_fast arm; backend-dispatch test covers the
  fabs/copysign split.
- cuda-oxide-codegen: backend-selection docs updated; new prediction
  tests for sign-only/minmax-only modules on both output policies.
nihalpasham added a commit that referenced this pull request Jul 28, 2026
* fix(mir-lower): keep scalar float math on the LLVM-to-PTX path

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

* fix(dialect-mir): reclassify fabs/copysign and float max/min in the libdevice prediction

Completes the rebase of #391 onto the IntrinsicBackend dispatch that #466
introduced after the PR was written; this part of the contributor's change
could not be expressed as a rebase of their diff, so it is re-implemented
here as a maintainer integration commit.

Without this, select_pre_lowering_backend still classified fabs/copysign
and the float max/min placeholders as strict libdevice, so kernels using
only those ops were forced onto the NVVM-IR / libdevice route and the
LLVM-to-PTX lowering from the previous commit never engaged (and the
post-lowering consistency check would abort the build once it did).

- rust_intrinsics: move CALLEE_FABS / CALLEE_COPYSIGN_F32/F64 from
  is_libdevice_backed_placeholder to
  is_backend_dependent_libdevice_placeholder (llvm.fabs/llvm.copysign on
  the NVPTX path, __nv_fabs*/__nv_copysign* only under libNVVM), and drop
  CALLEE_MAXNUM_NSZ_* / CALLEE_MINNUM_NSZ_* from both lists (they expand
  to an ordered compare/select under every backend and never use
  libdevice). Classification test arrays updated to match.
- mir-lower: the now-unreachable max/min arms of libdevice_name are a
  hard error, mirroring the f*_fast arm; backend-dispatch test covers the
  fabs/copysign split.
- cuda-oxide-codegen: backend-selection docs updated; new prediction
  tests for sign-only/minmax-only modules on both output policies.

---------

Signed-off-by: nik <[email protected]>
Co-authored-by: nihalpasham <[email protected]>
@honeyspoon
honeyspoon deleted the fix/scalar-float-llvm-intrinsics branch July 28, 2026 14:02
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 intrinsics Device intrinsics and libdevice math mappings IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) perf Performance of generated code or of the compiler itself

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants