Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions crates/rustc_codegen_spirv/src/builder/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use rspirv::dr::Operand;
use rspirv::spirv::GlslStd450Op as GLOp;
use rustc_abi::Align;
use rustc_codegen_ssa::RetagInfo;
use rustc_codegen_ssa::common::IntPredicate;
use rustc_codegen_ssa::mir::IntrinsicResult;
use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue};
Expand Down Expand Up @@ -59,6 +60,39 @@ impl Builder<'_, '_> {
let result_bits = self.or(val_masked, sign_masked);
self.bitcast(result_bits, val.ty)
}

/// Bitwise equality of two values of the same type, as required by `raw_eq`.
///
/// Only types `core` calls `raw_eq` with are supported: (nested) arrays of integers and
/// `bool`s (the `BytewiseEq` types). Arrays are compared element by element.
fn raw_eq_values(&mut self, lhs: SpirvValue, rhs: SpirvValue) -> SpirvValue {
assert_ty_eq!(self, lhs.ty, rhs.ty);
let count = match self.lookup_type(lhs.ty) {
SpirvType::Bool | SpirvType::Integer(..) => {
return self.icmp(IntPredicate::IntEQ, lhs, rhs);
}
SpirvType::Array { count, .. } => self
.builder
.lookup_const_scalar(count)
.expect("array count is always a constant"),
other => {
let bool_ty = SpirvType::Bool.def(self.span(), self);
return self.undef_zombie(
bool_ty,
&format!("raw_eq not implemented for {}", other.debug(lhs.ty, self)),
);
}
};

let mut result = self.constant_bool(self.span(), true);
for i in 0..count as u64 {
let lhs_element = self.extract_value(lhs, i);
let rhs_element = self.extract_value(rhs, i);
let element_eq = self.raw_eq_values(lhs_element, rhs_element);
result = self.and(result, element_eq);
}
result
}
}

impl<'a, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'tcx> {
Expand Down Expand Up @@ -358,6 +392,18 @@ impl<'a, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'tcx> {

sym::compare_bytes => self.undef_zombie(ret_ty, "memcmp not implemented"),

sym::raw_eq => {
let layout = self.layout_of(fn_args.type_at(0));
if layout.is_zst() {
self.constant_bool(self.span(), true)
} else {
let ty = layout.spirv_type(self.span(), self);
let lhs = self.load(ty, args[0].immediate(), layout.align.abi);
let rhs = self.load(ty, args[1].immediate(), layout.align.abi);
self.raw_eq_values(lhs, rhs)
}
}

_ => {
// Call the fallback body instead of generating the intrinsic code
return IntrinsicResult::Fallback(Instance::new_raw(def_id, instance.args));
Expand Down
28 changes: 28 additions & 0 deletions tests/compiletests/ui/lang/core/intrinsics/raw_eq.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Test `raw_eq` intrinsic, which `PartialEq` for arrays of integers lowers to
// build-pass
// compile-flags: -C target-feature=+Int8

#![no_std]

use spirv_std::spirv;

#[spirv(compute(threads(1)))]
pub fn main(
#[spirv(descriptor_set = 0, binding = 0, storage_buffer)] input: &[u32; 16],
#[spirv(descriptor_set = 0, binding = 1, storage_buffer)] output: &mut [u32; 4],
) {
let a = *input;
let mut b = a;
b[3] ^= 1;

let a_bytes = [a[0] as u8, a[1] as u8, a[2] as u8, a[3] as u8];
let b_bytes = [b[0] as u8, b[1] as u8, b[2] as u8, b[3] as u8];

let a_nested = [[a[0], a[1]], [a[2], a[3]]];
let b_nested = [[b[0], b[1]], [b[2], b[3]]];

output[0] = (a == b) as u32;
output[1] = (a_bytes != b_bytes) as u32;
output[2] = (a_nested == b_nested) as u32;
output[3] = ([a[0] == 0, a[1] == 0] == [b[0] == 0, b[1] == 0]) as u32;
}
17 changes: 17 additions & 0 deletions tests/difftests/tests/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions tests/difftests/tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ members = [
"lang/core/intrinsics/bit_ops/bit-ops-cpu",
"lang/core/intrinsics/rotate/rotate-rust",
"lang/core/intrinsics/rotate/rotate-cpu",
"lang/core/intrinsics/raw_eq/raw-eq-rust",
"lang/core/intrinsics/raw_eq/raw-eq-cpu",
"lang/core/ops/casts/casts-cpu",
"lang/core/ops/casts/casts-gpu",
"lang/core/ops/unbounded_shift/unbounded-shift-rust",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "raw-eq-cpu"
edition.workspace = true

[lints]
workspace = true

[dependencies]
difftest.workspace = true
raw-eq-rust = { path = "../raw-eq-rust" }
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use difftest::config::{Config, TestMetadata};
use raw_eq_rust::{raw_eq_case, test_data};

fn main() {
let config = Config::from_path(std::env::args().nth(1).unwrap()).unwrap();

let output: Vec<u32> = test_data()
.iter()
.flat_map(|&[a, b]| raw_eq_case(a, b))
.collect();

config.write_result(&output).unwrap();
config
.write_metadata(&TestMetadata::u32())
.expect("Failed to write metadata");
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "raw-eq-rust"
edition.workspace = true

[lints]
workspace = true

# GPU deps
[dependencies]
spirv-std.workspace = true

# CPU deps (for the test harness)
[target.'cfg(not(target_arch = "spirv"))'.dependencies]
difftest.workspace = true
bytemuck.workspace = true
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#![no_std]

use spirv_std::spirv;

pub const WORDS_PER_ARRAY: usize = 8;

pub const RESULTS_PER_CASE: usize = 8;

/// Each case is a pair of arrays, either equal or with a single bit flipped in one word
pub const NUM_CASES: usize = 1 + WORDS_PER_ARRAY * 3;

pub fn test_data() -> [[[u32; WORDS_PER_ARRAY]; 2]; NUM_CASES] {
let base = [
0x0123_4567,
0x89AB_CDEF,
0xFFFF_FFFF,
0,
0x8000_0000,
1,
0xDEAD_BEEF,
0x0F0F_0F0F,
];
let mut data = [[base; 2]; NUM_CASES];
for (i, case) in data.iter_mut().enumerate().skip(1) {
let word = (i - 1) % WORDS_PER_ARRAY;
// Flip the lowest, a middle and the highest bit of a word
let bit = [0, 15, 31][(i - 1) / WORDS_PER_ARRAY];
case[1][word] ^= 1 << bit;
}
data
}

pub fn raw_eq_case(
a: [u32; WORDS_PER_ARRAY],
b: [u32; WORDS_PER_ARRAY],
) -> [u32; RESULTS_PER_CASE] {
let mut a_i32 = [0i32; WORDS_PER_ARRAY];
let mut b_i32 = [0i32; WORDS_PER_ARRAY];
let mut a_u8 = [0u8; WORDS_PER_ARRAY];
let mut b_u8 = [0u8; WORDS_PER_ARRAY];
let mut a_u16 = [0u16; WORDS_PER_ARRAY];
let mut b_u16 = [0u16; WORDS_PER_ARRAY];
let mut a_u64 = [0u64; WORDS_PER_ARRAY / 2];
let mut b_u64 = [0u64; WORDS_PER_ARRAY / 2];
let mut a_nested = [[0u32; 2]; WORDS_PER_ARRAY / 2];
let mut b_nested = [[0u32; 2]; WORDS_PER_ARRAY / 2];
for i in 0..WORDS_PER_ARRAY {
a_i32[i] = a[i] as i32;
b_i32[i] = b[i] as i32;
a_u8[i] = a[i] as u8;
b_u8[i] = b[i] as u8;
a_u16[i] = (a[i] >> 8) as u16;
b_u16[i] = (b[i] >> 8) as u16;
}
for i in 0..WORDS_PER_ARRAY / 2 {
a_u64[i] = u64::from(a[2 * i]) | (u64::from(a[2 * i + 1]) << 32);
b_u64[i] = u64::from(b[2 * i]) | (u64::from(b[2 * i + 1]) << 32);
a_nested[i] = [a[2 * i], a[2 * i + 1]];
b_nested[i] = [b[2 * i], b[2 * i + 1]];
}
let a_bool = msb_bools(&a);
let b_bool = msb_bools(&b);

[
(a == b) as u32,
(a != b) as u32,
(a_i32 == b_i32) as u32,
(a_u8 == b_u8) as u32,
(a_u16 == b_u16) as u32,
(a_bool == b_bool) as u32,
(a_u64 == b_u64) as u32,
(a_nested == b_nested) as u32,
]
}

// `[false; N]` is not supported by rust-gpu, hence explicit elements
fn msb_bools(words: &[u32; WORDS_PER_ARRAY]) -> [bool; WORDS_PER_ARRAY] {
[
words[0] >> 31 != 0,
words[1] >> 31 != 0,
words[2] >> 31 != 0,
words[3] >> 31 != 0,
words[4] >> 31 != 0,
words[5] >> 31 != 0,
words[6] >> 31 != 0,
words[7] >> 31 != 0,
]
}

#[spirv(compute(threads(1)))]
pub fn main_cs(
#[spirv(storage_buffer, descriptor_set = 0, binding = 0)] input: &[u32],
#[spirv(storage_buffer, descriptor_set = 0, binding = 1)] output: &mut [u32],
#[spirv(global_invocation_id)] global_id: spirv_std::glam::UVec3,
) {
let tid = global_id.x as usize;

if tid < NUM_CASES {
let mut a = [0; WORDS_PER_ARRAY];
let mut b = [0; WORDS_PER_ARRAY];
for i in 0..WORDS_PER_ARRAY {
a[i] = input[tid * 2 * WORDS_PER_ARRAY + i];
b[i] = input[tid * 2 * WORDS_PER_ARRAY + WORDS_PER_ARRAY + i];
}
let results = raw_eq_case(a, b);
for i in 0..RESULTS_PER_CASE {
output[tid * RESULTS_PER_CASE + i] = results[i];
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#[cfg(not(target_arch = "spirv"))]
fn main() {
use difftest::config::{Config, TestMetadata};
use difftest::scaffold::compute::{
AshBackend, BufferConfig, BufferUsage, ComputeShaderTest, RustComputeShader,
};
use difftest::spirv_builder::Capability;
use raw_eq_rust::{NUM_CASES, RESULTS_PER_CASE, test_data};

let config = Config::from_path(std::env::args().nth(1).unwrap()).unwrap();

// Skip on macOS due to Vulkan/MoltenVK configuration issues
#[cfg(target_os = "macos")]
{
use difftest::scaffold::Skip;

let skip = Skip::new("Ash tests are skipped on macOS due to MoltenVK configuration issues");
skip.run_test(&config).unwrap();
return;
}

#[cfg(not(target_os = "macos"))]
{
let input_bytes: Vec<u8> = bytemuck::cast_slice(&test_data()).to_vec();
let output_size = (NUM_CASES * RESULTS_PER_CASE * std::mem::size_of::<u32>()) as u64;

let buffers = vec![
BufferConfig {
size: input_bytes.len() as u64,
usage: BufferUsage::StorageReadOnly,
initial_data: Some(input_bytes),
},
BufferConfig {
size: output_size,
usage: BufferUsage::Storage,
initial_data: None,
},
];

// Use Ash backend since wgpu/naga doesn't support Int8, Int16 and Int64
let shader = RustComputeShader::default()
.with_capability(Capability::Int8)
.with_capability(Capability::Int16)
.with_capability(Capability::Int64);
let num_workgroups = NUM_CASES as u32;
let test = ComputeShaderTest::<AshBackend, _>::new(shader, [num_workgroups, 1, 1], buffers)
.unwrap();

config
.write_metadata(&TestMetadata::u32())
.expect("Failed to write metadata");

test.run_test(&config).unwrap();
}
}

#[cfg(target_arch = "spirv")]
fn main() {}
Loading