Repository navigation
fix(mir): lower BinaryOp::Cmp - #147
Merged
Merged
Conversation
Signed-off-by: advpropsys <[email protected]>
Conflicts resolved: - README.md: keep the PR's new ord_cmp examples-table row alongside main's updated gemm_sol row (column padding re-aligned). - crates/mir-lower/src/convert/ops/arithmetic.rs: keep the PR's convert_three_way_cmp / emit_cmp_value / emit_discriminant_const additions; adopt main's removal of the empty #[cfg(test)] mod in favor of the integration-test coverage note. Also regenerated examples/ord_cmp/Cargo.lock against the v0.2.1 workspace (the PR locked the pre-bump 0.2.0 crate versions).
…ared discriminant values PR NVIDIA#147 threads per-variant discriminant VALUES through MirEnumType (fixing the issue NVIDIA#146 class of miscompiles where tags were variant indices), but selects the tag TYPE via Ty::discriminant_ty(), which is isize for default-repr enums. That is the type 'discriminant reads are performed at', not the physical tag storage: a default-repr 3-variant enum stores an i8 tag, not an i64. The width mismatch corrupts the in-memory model for every enum that round-trips through memory. Replace the tag-type selection with the layout-truth dispatch over rustc's VariantsShape (identical text to the tested PR NVIDIA#119 branch, so the future rebase is trivial): - Direct-tag enums take width AND signedness from the layout scalar. repr(uN/iN), repr(usize/isize), repr(C), sparse discriminants (u32 tag for { A = 0, B = 1_000_000 }) and negative discriminants (SIGNED i8 tag for { N = -1, Z = 0 }, so 'e as i32' sign-extends) all fall out of the one arm. Total size / ABI alignment are recorded on the type (new MirEnumType::get_with_layout; 0 = unknown). - Niched, single-variant (all-but-one-uninhabited) and fully uninhabited enums keep the synthetic unsigned variant-count tag: the un-niched MirEnumType model is deliberately self-consistent rather than memory-faithful there. The PR's variant_discriminants threading is KEPT, with the u128 -> u64 narrowing now checked: discriminant_for_variant().val that does not fit in 64 bits input_errs instead of silently truncating. The same checked narrowing is applied to both SwitchInt sites in terminator/mod.rs (single-branch and multi-way chain) so switch values and stored discriminants share one 64-bit contract. Issue NVIDIA#136 (BinOp::Cmp), issue NVIDIA#146 (discriminant-value tags).
PR NVIDIA#147 threaded an expected_result_type parameter through translate_rvalue, precomputed in statement.rs from the assignment destination, purely so the BinOp::Cmp arm could name its Ordering result type. rustc already knows that type: BinOp::ty(lhs_ty, rhs_ty) returns core::cmp::Ordering for Cmp in the pinned toolchain, exactly like the existing place.ty(...) usages resolve types elsewhere. Compute the Ordering Ty inside the Cmp arm from the operand types and translate_type it there. No behavior change; reverts the signature churn on translate_rvalue and the destination-type precomputation in statement.rs. Issue NVIDIA#136.
…lation With tags now carrying declared discriminant VALUES (not variant indices), every site that guessed, defaulted, or conflated the two semantics is a latent miscompile. Make them all fail loudly: - aggregate.rs convert_construct_enum: a variant_index outside variant_discriminants now input_errs instead of unwrap_or-ing back to the raw index (which would silently resurrect the issue NVIDIA#146 bug for malformed enum types). - aggregate.rs: the '.map(|t| t.width()).unwrap_or(8)' silent 8-bit tag assumption input_errs when the discriminant type is not an integer type. - arithmetic.rs convert_three_way_cmp: the float OLT/OGT arm is now a loud input_err ('BinOp::Cmp on floats is never emitted by rustc; total-order lowering unimplemented'). The old select chain yielded Equal for NaN, since NaN compares false on both ordered predicates. emit_cmp_value is integer-only accordingly. - cast.rs emit_scalar_to_niched_enum: niche_variant_idx / untagged_variant_idx are variant INDICES from NicheEncodingAttr; map them through the result enum's variant_discriminants before storing into field 0, so the tag slot carries ONE semantic (declared discriminant value) everywhere. Behavior-neutral for Option-likes (discriminants [0, 1]); groundwork for the issue NVIDIA#132 fix. - mir-importer rvalue.rs enum_variant_index_from_bytes: a Direct tag value that matches no declared discriminant now input_errs instead of unwrap_or-ing 'value == index'. - dialect-mir MirCmpOp::verify: operands must be integers (bool/char included; floats rejected before they can reach the lowering) and the result must be a FIELDLESS 3-variant enum. New negative tests for payload variants and float operands in ops_test.rs. Issue NVIDIA#136, issue NVIDIA#146; niche mapping is groundwork for issue NVIDIA#132.
The enum tag changed meaning: it now stores the variant's DECLARED discriminant value (from rustc's discriminant_for_variant), not the variant index, and the tag type is rustc's layout-truth type rather than a variant-count guess. Update the prose that still described the old model: - mir-lower aggregate.rs: enum-representation header + the get_discriminant doc now state the field-0 slot carries declared discriminant values, with the issue NVIDIA#146 Ordering example. - mir-lower convert/types.rs: enum representation example gains the discriminants vector and the value-vs-index clarification. - dialect-mir types.rs: MirEnumType type-level doc no longer claims the discriminant is 'based on variant count'. - dialect-mir README: mir.enum textual example updated for the format that gained a discriminants vector (plus size/align), with the Ordering::Less = -1 / bit pattern 255 worked example.
Exposed by the new ord_cmp enum_repr_kernel lane: materializing a
'Neg::N' constant (enum { N = -5, Z }, default repr) failed with
'Enum constant tag value 251 matches no declared discriminant'.
The tag bytes read from a constant's allocation are the discriminant
truncated to the PHYSICAL tag width (i8: -5 -> 0xFB = 251), while
discriminant_for_variant().val reports the value at the declared
discriminant type's width (isize: -5 -> 0xFFFF_FFFF_FFFF_FFFB). The
old lookup compared the two raw, so any negative (or otherwise
truncated) discriminant never matched; before the loud-error
hardening, the unwrap_or fallback would then have used 251 as a
variant INDEX.
discriminant_to_variant_index now takes the raw u128 tag plus the tag
width's unsigned mask (from the layout scalar, same derivation as the
existing Niche arm) and masks both sides before comparing.
Issue NVIDIA#146 (tag semantics), follow-up to the enum tag hardening.
New coverage in the ord_cmp example (compile-verified; GPU execution asserts host-side, main() exits 1 on any mismatch): - cmp_kernel lanes 18-26: i8/u8/i16/u16/char comparisons. Signedness is observable: i8::MIN vs i8::MAX is -1 only under icmp slt (ult would see 0x80 > 0x7F); u8::MAX vs 0 is 1 only under icmp ult. The generated IR uses slt/sgt for i8/i16 and ult/ugt for u8/u16/char. - cmp_cast_kernel: 'cmp(..) as i8' and 'as i32' lanes asserting -1. Ordering is repr(i8) with Less = -1; the .ll stores tag i8 255 and widens with sext (a variant-index tag or zext would not yield -1). - ordering_match_kernel: the issue NVIDIA#146 shape ported from the triage repro - a helper returning Ordering LITERALS, matched in the kernel. The Less constant now materializes as tag 255, matching the Less arm instead of Equal. - enum_repr_kernel: default-repr sparse enum { A = 0, B = 1000 } (u16 tag holding 0/1000, zext-widened) and default-repr negative enum { N = -5, Z } (SIGNED i8 tag holding 251/252 = -5/-4, sext-widened so 'as i32' yields -5/-4). Decisive .ll lines (sm_90 compile): %v26 = sext i8 %v25 to i64 ; Neg tag sign-extends %v28 = insertvalue { i8 } undef, i8 251, 0 ; Neg::N = -5 %v36 = insertvalue { i16 } undef, i16 1000, 0 ; Sparse::B = 1000 %v47 = insertvalue { i8 } undef, i8 255, 0 ; Ordering::Less = -1 Issue NVIDIA#136, issue NVIDIA#146.
…/binaryop-cmp main advanced while this branch was in flight; clean auto-merge (the new address-walker work in mir-importer rvalue.rs touches different regions than the Cmp/enum-tag changes). Re-ran mir-importer / mir-lower / dialect-mir suites green and re-verified the ord_cmp and closure_index_miscompile examples compile at sm_90.
…0.2.1 The example landed on main (PR NVIDIA#121) with a lock generated before the v0.2.1 workspace bump; building it locally regenerates the lock. Same regeneration already applied to ord_cmp in the merge commit.
…nto fix/binaryop-cmp Semantic merge of the enum work: main's NVIDIA#119 (layout-truth tag, enum total_size/abi_align, divergence guard) meets this branch's variant_discriminants threading. - dialect-mir MirEnumType: kept this branch's variant_discriminants field/format/constructor arity, main's richer layout doc text. - importer translate_type: kept the discriminant-value loop and the variant_discriminants argument on top of the canonical layout-tag selection both sides share. - mir-lower convert_construct_enum: main's converted-type construction (type converter is the single source of the padded struct) composed with this branch's declared-discriminant tag writes and loud errors. - mir-lower memory.rs unit tests: enum constructors gain sequential discriminants (the layout tests exercise width/size, not values). Known issue carried forward (pre-existing on main, fixed in a follow-up commit on this branch): the NVIDIA#119 divergence guard rejects in-kernel loads of multi-payload enums, breaking the enum_array_match example that merged via PR NVIDIA#156.
Clean auto-merge plus one test-arity fix: the slot-map unit test's MirEnumType::get call gains the variant_discriminants argument this branch added.
The PR NVIDIA#119 guard rejected every load/store/GEP of a multi-payload enum whose concatenated {tag, fields...} model is larger than rustc's layout. That premise is too broad: device-LOCAL memory (allocas, in-kernel arrays) is written and read through the same lowered struct type, so the structural layout is self-consistent and correct. The guard broke the enum_array_match example (PR NVIDIA#156) on main, which builds [E; 4] arrays of a two-payload enum entirely in-kernel. Divergence only bites where device code traverses memory laid out by RUST's real layout: kernel parameters (by value via cuLaunchKernel, or behind pointers/slices into DeviceBuffer memory). So: - convert_func now walks each KERNEL parameter's pre-conversion MIR type (through pointers, slices, arrays, structs, tuples and enum payloads, cycle-safe) and rejects the first divergent enum with a host/device ABI boundary diagnostic. Non-kernel device functions are internal (both sides structural) and stay unchecked. - The load/store/ptr_offset rejections are removed. - Unit tests updated: device-local GEP+load of a divergent enum must lower; a gpu_kernel-attributed function with a divergent-enum pointer param must fail with the boundary message. GPU-verified on sm_120: enum_array_match passes again; ord_cmp, repr_u32_enum_stride, struct_layout_repro, option_ref_unwrap_or and the 10-example sweep all pass.
…erge A git add -A during the main-merge conflict resolution staged 14 untracked local triage dirs (examples/issue*_repro*). They are working scratch from issue triage, superseded by the tracked regression examples (enum_array_match, option_ref_unwrap_or, struct_layout_repro, issue150_repro, ord_cmp, repr_u32_enum_stride, closure_index_miscompile), and one of them fails the fmt gate. Remove them from tracking; the local copies stay on disk as untracked files.
- derive_ord_xor_partial_ord (deny-by-default): keep the hand-written Ord (it is the test subject - it lowers through BinOp::Cmp) and pair it with a manual PartialOrd delegating to it, the canonical pattern, instead of the derived one. - take is_multiple_of for the incidental parity selectors. GPU re-verified: all four kernels pass on sm_120.
Collaborator
|
Thanks for the PR. LGTM 👍🏾 Added a few things on top:
|
This was referenced Jun 10, 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.
Summary
This adds support for MIR
BinaryOp::Cmp, which is emitted byOrd::cmp, and lowers it to an enum-shapedcore::cmp::Orderingvalue.The change also preserves declared enum discriminants in
MirEnumType, soOrdering::Less,Ordering::Equal, andOrdering::Greateruse Rust's actual discriminant values rather than variant indices.Testing
cargo fmt --checkcargo check -p dialect-mir -p mir-importer -p mir-lowercargo test -p dialect-mircargo check --manifest-path crates/rustc-codegen-cuda/examples/ord_cmp/Cargo.toml --offlinecargo oxide run ord_cmp --arch sm_103The
ord_cmpexample coversu32,i32,u64,i64,usize, andisizecomparisons across less, equal, and greater outcomes.Fixes #136.