Repository navigation
fix(mir-lower): keep scalar float math on the LLVM-to-PTX path - #391
nihalpasham merged 2 commits into
Conversation
|
Measurement that may let the min/max path drop from two instructions to one. I checked what LLVM 21.1 actually emits for the NVPTX target ( So the backend already selects the single instruction; the sNaN problem this PR works around is at the IR level, where the optimizer may fold If that reading is right, emitting the PTX instruction directly through inline asm would give the correct Rust semantics in 1 instruction, where the ordered compare/select is Context: this came out of a duplicate branch of mine that I have closed in favour of this PR, since making Separately, on the fabs/copysign overlap with my #466: this PR is the more general treatment, so I am stripping fabs and copysign out of #466 and leaving it as rounding only. No action needed on your side. |
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]>
#466) * fix(mir-lower): lower fabs and copysign to LLVM intrinsics instead of 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 #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]> * fix(mir-lower): lower rounding ops to LLVM intrinsics instead of libdevice 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 #390). Signed-off-by: abder <[email protected]> * docs: correct the PTX mapping claimed for the routed intrinsics 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]> * refactor: narrow to rounding, ceding fabs/copysign to #391 #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 #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. #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 #391 via a standalone `fabs_llvm_intrinsic_name`. Signed-off-by: abder <[email protected]> * fix(mir-lower): encode rounding intrinsic symbols as pliron identifiers 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. * fix(dialect-mir): reclassify rounding placeholders as backend-dependent 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. * fix(codegen): dispatch rounding intrinsics on the intrinsic backend 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. * test(examples): add rounding-only float_rounding example 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. --------- Signed-off-by: abder <[email protected]> Co-authored-by: nihalpasham <[email protected]>
Signed-off-by: nik <[email protected]>
…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.
2e99d30 to
8a58a9b
Compare
|
Thanks, this design makes sense to me. Gist: width-correct It landed after a substantive rebase onto the Validated on 2x RTX 5090 (sm_120): the expanded Closes #390; dropping on-hold. |
Closes #390.
Summary
Simple scalar
abs,copysign,max, andminoperations were routedthrough libdevice even though LLVM and NVPTX can lower them directly. This
keeps those operations on the ordinary LLVM-to-PTX path while preserving
Rust's NaN and signed-zero semantics for both
f32andf64.Before: these operations forced NVVM IR emission and CUDA Toolkit runtime
linking. After: focused kernels containing only these operations emit PTX
directly.
What changed
Direct scalar lowering
absandcopysignselect the width-correctllvm.fabsandllvm.copysignintrinsics._nszmaxandminuse the ordered compare/select definition fromcore::intrinsicsinstead of libdevice.correct LLVM-only route.
Rust semantics and sibling paths
maxnum/minnumbehavior, which propagates signaling NaNs contrary to Rust's contract.
RustFloatMathIntrinsicvariant was audited. Transcendentals, roundingoperations, FMA, and remaining functions retain their
__nv_*lowering.intentionally receive the same direct lowering; unrelated external math
calls and the fast-arithmetic path are unchanged.
Known separate limitations
operations onto the direct PTX path.
available LLVM intrinsic semantics match Rust's signaling-NaN contract.
unnecessary_mut_passedwarnings in unchanged
tests/lowering_test.rs; library and focused-exampleclippy are clean.
Testing
the libdevice fallback.
fmaxmin_smokeacross both widths, quiet/signaling NaNs in eitheroperand, both-NaN results, both signed-zero orders, finite values,
abssignbehavior, and exact
copysignNaN-payload preservation.and width-specific
fabs/copysigndeclarations, without legacymaxnum/minnumor matching__nv_*references.main, the example emitted LTOIR with__nv_fmax{f}/__nv_fmin{f}calls; this branch emits PTX directly.cargo fmt --all -- --checkcargo fmt --manifest-path crates/rustc-codegen-cuda/examples/fmaxmin_smoke/Cargo.toml -- --checkLIBRARY_PATH=/tmp/cuda-oxide-libffi-link cargo test -p mir-lower --all-targetsLIBRARY_PATH=/tmp/cuda-oxide-libffi-link cargo clippy -p mir-lower --lib -- -D warningscargo clippy --manifest-path crates/rustc-codegen-cuda/examples/fmaxmin_smoke/Cargo.toml --all-targets -- -D warningsCUDA_OXIDE_NO_OPT=1GPU executions passed on an NVIDIA RTX3080 (
sm_86).Checklist
main.mainand passes on this branch.