From d7f7d586d37cc1d50eb5713e17fe27dbc51c4a35 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:21:03 -0600 Subject: [PATCH 1/2] gpu: bind a texture and sampler to guest draws through descriptor tables (#303) (#336) * gpu: bind a texture and sampler to guest draws through descriptor tables (#303) A guest command list had no way to bind a texture: GraphicsCommand stopped at vertex and index buffers. This adds the smallest D3D12-shaped binding the translated image_sample_lz pixel stage needs: shader-visible CBV_SRV_UAV and sampler heaps, CreateShaderResourceView for one-level RGBA8 and BC1 2D textures, a point/clamp CreateSampler, a root signature with one pixel-stage SRV table and one sampler table, and SetDescriptorHeaps and SetGraphicsRootDescriptorTable. Everything else fails explicitly before any draw. The native path hands the bound level to a textured backend. NativeCompute::render_rgba8_sampled_bc1 binds a BC1 level natively to fragment texture 0 and sampler 0. The software reference point-samples with clamp addressing. BC1 fixtures use only endpoint colours. Apple's hardware decoder gives 171/84 for the interpolated palette entries where the spec-exact decoder gives 170/85. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> * gpu: tighten guest texture binding after independent review (#303) The independent review found binding rules that diverged from D3D12: changing descriptor heaps kept tables bound in the old heaps, setting the same root signature again cleared its tables, and unsupported draw shapes were drawn as one triangle. Now heap changes and a different root signature invalidate tables, while redundant sets keep them. Table bases are checked against the bound heap of their type when bound. Textured draws other than one instance of three vertices fail, and zero vertices or instances draw nothing. Descriptor handle offsets can no longer carry into another heap's ID. SRVs of array or multi-level textures are rejected. A texture whose state excludes pixel-shader reads is not sampled. Vertex buffer offsets are overflow-checked. The tests now cover swapped root parameters, a second sampler slot, off-centre and out-of-range coordinates, state transitions, draw shapes and resource bounds. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> * loader: format the guest texture test (#303) Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> * gpu: close the review's remaining texture-binding gaps (#303) The re-review found three partial fixes. The public software reference could overflow on a huge viewport. A texture in a combined write and read state could be sampled. The sampler-slot test used two identical filled slots. The viewport is now bounded to 4096 pixels. A sampled texture must be COMMON or a read-only state that includes PIXEL_SHADER_RESOURCE. The sampler heap now leaves its middle slot empty. The docs now state the start-instance rule and when table bases are checked. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --------- Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 1 + Cargo.lock | 1 + crates/loader/Cargo.toml | 1 + crates/loader/src/graphics.rs | 1032 +++++++++++++++- crates/loader/tests/graphics_textures.rs | 1228 +++++++++++++++++++ crates/metal/src/render.rs | 42 +- crates/metal/tests/native/translated_bc1.rs | 99 ++ crates/metal/tests/native_compute.rs | 2 + docs/interfaces.md | 44 + scripts/test-gpu.sh | 5 + 10 files changed, 2450 insertions(+), 5 deletions(-) create mode 100644 crates/loader/tests/graphics_textures.rs create mode 100644 crates/metal/tests/native/translated_bc1.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f09a2a..82a17cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ remains unsupported. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. ### Added +- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted. - Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215. - Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending. - Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review. diff --git a/Cargo.lock b/Cargo.lock index e9de1b0..613d3f9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -204,6 +204,7 @@ dependencies = [ "sha2", "xenora-metal", "xenora-shader", + "xenora-texture", ] [[package]] diff --git a/crates/loader/Cargo.toml b/crates/loader/Cargo.toml index c945ce6..f74714e 100644 --- a/crates/loader/Cargo.toml +++ b/crates/loader/Cargo.toml @@ -16,6 +16,7 @@ gpu-tests = [] [dependencies] libc = "0.2" sha2 = "0.10" +xenora-texture = { path = "../texture" } [dev-dependencies] xenora-metal = { path = "../metal" } diff --git a/crates/loader/src/graphics.rs b/crates/loader/src/graphics.rs index 8f626ed..5f4ea58 100644 --- a/crates/loader/src/graphics.rs +++ b/crates/loader/src/graphics.rs @@ -122,6 +122,9 @@ pub enum GraphicsError { /// An indexed draw reads past its index buffer or fetches a vertex, /// after applying the base vertex, outside its vertex buffer. IndexOutOfRange, + /// A descriptor heap, view, sampler, root signature or binding outside + /// the supported texture-binding subset. Nothing is drawn. + Unsupported(&'static str), } impl std::fmt::Display for GraphicsError { @@ -149,6 +152,7 @@ impl std::fmt::Display for GraphicsError { write!(f, "unsupported index buffer format {format}") } Self::IndexOutOfRange => write!(f, "indexed draw outside its index or vertex buffer"), + Self::Unsupported(what) => write!(f, "unsupported texture binding: {what}"), } } } @@ -180,6 +184,9 @@ pub struct GraphicsResource { pub state: ResourceStates, pub guest_backing_addr: Option, pub data: Vec, + /// The texel format of a `Texture2D` that a shader resource view may + /// read; `None` for buffers and textures without a supported format. + pub texture_format: Option, } /// Index size of an index buffer view, as `D3D12_INDEX_BUFFER_VIEW::Format`. @@ -208,6 +215,377 @@ impl IndexFormat { } } +/// Descriptors one shader-visible heap may hold. +pub const MAX_DESCRIPTORS_PER_HEAP: u32 = 64; +/// Largest width and height of a texture that a shader resource view reads. +pub const MAX_TEXTURE_DIMENSION: u32 = 64; +/// `GetDescriptorHandleIncrementSize` for both supported heap types. Guests +/// must query it rather than assume a value, as on D3D12. +pub const DESCRIPTOR_HANDLE_INCREMENT: u32 = 32; +/// `D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND`. +pub const DESCRIPTOR_RANGE_OFFSET_APPEND: u32 = 0xffff_ffff; +/// DXGI format code of `R8G8B8A8_UNORM`. +pub const DXGI_FORMAT_R8G8B8A8_UNORM: u32 = 28; +/// DXGI format code of `BC1_UNORM`. +pub const DXGI_FORMAT_BC1_UNORM: u32 = 71; +/// `D3D12_FILTER_MIN_MAG_MIP_POINT`. +pub const D3D12_FILTER_MIN_MAG_MIP_POINT: u32 = 0; +/// `D3D12_TEXTURE_ADDRESS_MODE_CLAMP`. +pub const D3D12_TEXTURE_ADDRESS_MODE_CLAMP: u32 = 3; + +/// Largest image the software reference draws for a textured draw. +pub const MAX_SOFTWARE_TEXTURED_PIXELS: usize = 4096; +/// The read-only `D3D12_RESOURCE_STATES`: vertex and constant buffer, index +/// buffer, depth read, both shader resources, indirect argument and copy source. +const READ_STATES: u32 = 0x1 | 0x2 | 0x20 | 0x40 | 0x80 | 0x200 | 0x800; + +/// Bit that separates GPU descriptor handles from CPU ones. +const GPU_DESCRIPTOR_SPACE: u64 = 1 << 63; + +/// `D3D12_DESCRIPTOR_HEAP_TYPE`; only the two shader-visible types exist here. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DescriptorHeapType { + CbvSrvUav, + Sampler, +} + +impl DescriptorHeapType { + /// The heap type for a `D3D12_DESCRIPTOR_HEAP_TYPE` value: `CBV_SRV_UAV` + /// (0) or `SAMPLER` (1). `RTV` (2) and `DSV` (3) are not supported. + pub const fn from_d3d12(value: u32) -> Option { + match value { + 0 => Some(Self::CbvSrvUav), + 1 => Some(Self::Sampler), + _ => None, + } + } +} + +/// `D3D12_CPU_DESCRIPTOR_HANDLE`: the destination of descriptor creation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CpuDescriptorHandle(pub u64); + +/// `D3D12_GPU_DESCRIPTOR_HANDLE`: the base of a bound descriptor table. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct GpuDescriptorHandle(pub u64); + +/// `handle + index × increment`, or `None` when the sum leaves the heap's +/// 32-bit offset field and would carry into its heap ID. +const fn offset_handle(handle: u64, index: u32) -> Option { + let offset = (handle as u32 as u64) + index as u64 * DESCRIPTOR_HANDLE_INCREMENT as u64; + if offset > u32::MAX as u64 { + None + } else { + Some(handle & !(u32::MAX as u64) | offset) + } +} + +impl CpuDescriptorHandle { + /// The handle `index` increments past this one, if it stays in its heap's range. + pub const fn offset(self, index: u32) -> Option { + match offset_handle(self.0, index) { + Some(value) => Some(Self(value)), + None => None, + } + } +} + +impl GpuDescriptorHandle { + /// The handle `index` increments past this one, if it stays in its heap's range. + pub const fn offset(self, index: u32) -> Option { + match offset_handle(self.0, index) { + Some(value) => Some(Self(value)), + None => None, + } + } +} + +/// Texel format of a texture a shader resource view reads. Rows are linear +/// and tightly packed: four bytes per texel, or eight bytes per 4×4 block. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextureFormat { + Rgba8Unorm, + Bc1Unorm, +} + +impl TextureFormat { + /// The format for a DXGI format code, `R8G8B8A8_UNORM` (28) or `BC1_UNORM` (71). + pub const fn from_dxgi(format: u32) -> Option { + match format { + DXGI_FORMAT_R8G8B8A8_UNORM => Some(Self::Rgba8Unorm), + DXGI_FORMAT_BC1_UNORM => Some(Self::Bc1Unorm), + _ => None, + } + } + + /// Bytes of one level of `width` × `height` texels. + pub const fn level_size(self, width: u32, height: u32) -> usize { + match self { + Self::Rgba8Unorm => width as usize * height as usize * 4, + Self::Bc1Unorm => width.div_ceil(4) as usize * height.div_ceil(4) as usize * 8, + } + } +} + +/// `D3D12_SRV_DIMENSION`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SrvDimension { + Buffer, + Texture1D, + Texture2D, + Texture2DArray, + Texture3D, + TextureCube, +} + +/// `D3D12_SHADER_RESOURCE_VIEW_DESC` for a single-level 2D texture. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ShaderResourceViewDesc { + /// DXGI format code; it must equal the resource's format. + pub format: u32, + pub view_dimension: SrvDimension, + pub most_detailed_mip: u32, + pub mip_levels: u32, +} + +/// `D3D12_SAMPLER_DESC` without the fields that point sampling ignores. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SamplerDesc { + pub filter: u32, + pub address_u: u32, + pub address_v: u32, + pub address_w: u32, + pub mip_lod_bias: f32, + pub min_lod: f32, + pub max_lod: f32, +} + +impl SamplerDesc { + /// Point filtering with clamp addressing, the one supported state. + pub const fn point_clamp() -> Self { + Self { + filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + address_u: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + address_v: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + address_w: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + mip_lod_bias: 0.0, + min_lod: 0.0, + max_lod: f32::MAX, + } + } + + fn validate(&self) -> Result<(), GraphicsError> { + if self.filter != D3D12_FILTER_MIN_MAG_MIP_POINT { + return Err(GraphicsError::Unsupported( + "sampler filter other than point", + )); + } + if [self.address_u, self.address_v, self.address_w] + .iter() + .any(|&mode| mode != D3D12_TEXTURE_ADDRESS_MODE_CLAMP) + { + return Err(GraphicsError::Unsupported( + "sampler address mode other than clamp", + )); + } + if self.mip_lod_bias != 0.0 + || self.min_lod != 0.0 + || self.max_lod.is_nan() + || self.max_lod < 0.0 + { + return Err(GraphicsError::Unsupported("sampler LOD bias or range")); + } + Ok(()) + } +} + +/// `D3D12_DESCRIPTOR_RANGE_TYPE`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DescriptorRangeType { + Srv, + Uav, + Cbv, + Sampler, +} + +/// `D3D12_DESCRIPTOR_RANGE`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DescriptorRange { + pub range_type: DescriptorRangeType, + pub num_descriptors: u32, + pub base_shader_register: u32, + pub register_space: u32, + pub offset_in_descriptors_from_table_start: u32, +} + +/// `D3D12_SHADER_VISIBILITY`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ShaderVisibility { + All, + Vertex, + Hull, + Domain, + Geometry, + Pixel, +} + +/// `D3D12_ROOT_PARAMETER`, by parameter type. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RootParameter { + DescriptorTable { + ranges: Vec, + visibility: ShaderVisibility, + }, + Constants32Bit { + visibility: ShaderVisibility, + }, + Cbv { + visibility: ShaderVisibility, + }, + Srv { + visibility: ShaderVisibility, + }, + Uav { + visibility: ShaderVisibility, + }, +} + +/// `D3D12_ROOT_SIGNATURE_DESC`, unserialized. Static samplers are counted only: +/// any is unsupported. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RootSignatureDesc { + pub parameters: Vec, + pub static_sampler_count: u32, +} + +/// The supported root signature: one pixel-stage table holding `t0` and +/// one holding `s0`, at these root parameter indices. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct RootSignature { + srv_parameter: u32, + sampler_parameter: u32, +} + +impl RootSignature { + fn from_desc(desc: &RootSignatureDesc) -> Result { + if desc.static_sampler_count != 0 { + return Err(GraphicsError::Unsupported("static samplers")); + } + if desc.parameters.len() != 2 { + return Err(GraphicsError::Unsupported( + "root signature other than one SRV table and one sampler table", + )); + } + let mut srv = None; + let mut sampler = None; + for (index, parameter) in (0u32..).zip(&desc.parameters) { + let RootParameter::DescriptorTable { ranges, visibility } = parameter else { + return Err(GraphicsError::Unsupported( + "root constants or root descriptors", + )); + }; + if *visibility != ShaderVisibility::Pixel { + return Err(GraphicsError::Unsupported("shader stage other than pixel")); + } + let [range] = ranges.as_slice() else { + return Err(GraphicsError::Unsupported( + "descriptor table with other than one range", + )); + }; + if range.num_descriptors != 1 + || range.base_shader_register != 0 + || range.register_space != 0 + || !matches!( + range.offset_in_descriptors_from_table_start, + 0 | DESCRIPTOR_RANGE_OFFSET_APPEND + ) + { + return Err(GraphicsError::Unsupported( + "descriptor range other than one descriptor at register 0, space 0", + )); + } + let slot = match range.range_type { + DescriptorRangeType::Srv => &mut srv, + DescriptorRangeType::Sampler => &mut sampler, + DescriptorRangeType::Uav => return Err(GraphicsError::Unsupported("UAV range")), + DescriptorRangeType::Cbv => return Err(GraphicsError::Unsupported("CBV range")), + }; + if slot.replace(index).is_some() { + return Err(GraphicsError::Unsupported( + "more than one table of one range type", + )); + } + } + match (srv, sampler) { + (Some(srv_parameter), Some(sampler_parameter)) => Ok(Self { + srv_parameter, + sampler_parameter, + }), + _ => Err(GraphicsError::Unsupported( + "root signature without both an SRV and a sampler table", + )), + } + } +} + +/// One filled descriptor. +#[derive(Clone, Copy, Debug)] +enum Descriptor { + Srv { + resource: GraphicsHandle, + format: TextureFormat, + }, + Sampler(SamplerDesc), +} + +/// Per-execution root signature, heap and table bindings. +#[derive(Default)] +struct TableBindings { + root_signature: Option<(GraphicsHandle, RootSignature)>, + srv_heap: Option, + sampler_heap: Option, + tables: [Option; 2], +} + +/// A shader-visible descriptor heap. +struct DescriptorHeap { + handle: GraphicsHandle, + heap_type: DescriptorHeapType, + slots: Vec>, +} + +/// The texture a textured draw samples, as bound through its SRV table. +#[derive(Clone, Copy, Debug)] +pub struct TextureView<'a> { + pub format: TextureFormat, + pub width: u32, + pub height: u32, + /// The single level: tightly packed rows of texels or BC1 blocks. + pub bytes: &'a [u8], +} + +/// One triangle that samples a bound texture in the pixel stage. +/// +/// Each vertex supplies a float4 position and a float4 texture coordinate, +/// whose `xy` are the normalized `uv` the pixel stage samples at. +#[derive(Clone, Copy, Debug)] +pub struct TexturedDraw<'a> { + pub positions: [[f32; 4]; 3], + pub texcoords: [[f32; 4]; 3], + pub viewport: (usize, usize), + pub clear_color: [u8; 4], + pub texture: TextureView<'a>, + pub sampler: SamplerDesc, +} + +/// Backend renderer for textured draws. +pub type TexturedBackendRenderer<'a> = + dyn Fn(&TexturedDraw<'_>) -> Result, GraphicsError> + 'a; + +/// Shared thread-safe textured backend renderer instance. +pub type SharedTexturedBackendRenderer = + Arc) -> Result, GraphicsError> + Send + Sync>; + /// Primitive Draw Command recorded in a Command List. #[derive(Clone, Debug)] pub enum GraphicsCommand { @@ -247,6 +625,19 @@ pub enum GraphicsCommand { base_vertex_location: i32, start_instance_location: u32, }, + /// `SetDescriptorHeaps`: at most one heap of each type. + SetDescriptorHeaps { + heaps: Vec, + }, + /// `SetGraphicsRootSignature`; it clears every bound table. + SetGraphicsRootSignature { + root_signature: GraphicsHandle, + }, + /// `SetGraphicsRootDescriptorTable`. + SetGraphicsRootDescriptorTable { + root_parameter_index: u32, + base: GpuDescriptorHandle, + }, } /// Command List in recording or closed state. @@ -298,9 +689,14 @@ pub struct GraphicsContext { allocators: HashMap, command_lists: HashMap, resources: HashMap, + /// Descriptor heaps by handle ID, which descriptor handles encode. + descriptor_heaps: HashMap, + root_signatures: HashMap, pub last_presentation: Arc>, /// Optional active backend renderer (e.g. Native Metal). backend: Option, + /// Optional backend renderer for textured draws. + textured_backend: Option, backend_id: GraphicsBackendId, } @@ -319,8 +715,11 @@ impl GraphicsContext { allocators: HashMap::new(), command_lists: HashMap::new(), resources: HashMap::new(), + descriptor_heaps: HashMap::new(), + root_signatures: HashMap::new(), last_presentation: Arc::new(Mutex::new(FramePresentation::default())), backend: None, + textured_backend: None, backend_id: GraphicsBackendId::SoftwareReference, } } @@ -337,10 +736,20 @@ impl GraphicsContext { self.backend_id = GraphicsBackendId::MetalNative; } + /// Install a native Metal adapter for draws that sample a bound texture. + pub fn set_metal_textured_backend(&mut self, renderer: F) + where + F: Fn(&TexturedDraw<'_>) -> Result, GraphicsError> + Send + Sync + 'static, + { + self.textured_backend = Some(Arc::new(renderer)); + self.backend_id = GraphicsBackendId::MetalNative; + } + /// Explicitly configure context to require native Metal without an attached backend. /// Useful for verifying that missing/unsupported Metal devices correctly fail execution. pub fn set_require_metal_without_backend(&mut self) { self.backend = None; + self.textured_backend = None; self.backend_id = GraphicsBackendId::MetalNative; } @@ -447,6 +856,8 @@ impl GraphicsContext { return Err(GraphicsError::InvalidDeviceHandle); } let handle = self.allocate_handle(); + let texture_format = (desc.dimension == ResourceDimension::Texture2D && desc.format_rgba8) + .then_some(TextureFormat::Rgba8Unorm); let size = match desc.dimension { ResourceDimension::Buffer => desc.width as usize, ResourceDimension::Texture2D => (desc.width as usize) * (desc.height as usize) * 4, @@ -460,6 +871,7 @@ impl GraphicsContext { state: initial_state, guest_backing_addr: guest_addr, data: vec![0u8; size], + texture_format, }, ); Ok(handle) @@ -559,7 +971,10 @@ impl GraphicsContext { .resources .get(&resource) .ok_or(GraphicsError::InvalidResourceHandle)?; - if offset + stride > res.data.len() && res.guest_backing_addr.is_none() { + let end = offset + .checked_add(stride) + .ok_or(GraphicsError::InvalidDescriptor)?; + if end > res.data.len() && res.guest_backing_addr.is_none() { return Err(GraphicsError::InvalidDescriptor); } cmd_list.commands.push(GraphicsCommand::SetVertexBuffer { @@ -661,6 +1076,319 @@ impl GraphicsContext { Ok(()) } + /// Create a committed single-level 2D texture (`CreateCommittedResource` + /// with a texture format). `format` is a DXGI code: `R8G8B8A8_UNORM` (28) + /// or `BC1_UNORM` (71). BC1 sizes must be multiples of four. + pub fn create_committed_texture2d( + &mut self, + device: GraphicsHandle, + width: u32, + height: u32, + format: u32, + initial_state: ResourceStates, + guest_addr: Option, + ) -> Result { + if !self.devices.contains_key(&device) { + return Err(GraphicsError::InvalidDeviceHandle); + } + let format = + TextureFormat::from_dxgi(format).ok_or(GraphicsError::Unsupported("texture format"))?; + if !(1..=MAX_TEXTURE_DIMENSION).contains(&width) + || !(1..=MAX_TEXTURE_DIMENSION).contains(&height) + { + return Err(GraphicsError::Unsupported("texture size")); + } + if format == TextureFormat::Bc1Unorm + && (!width.is_multiple_of(4) || !height.is_multiple_of(4)) + { + return Err(GraphicsError::Unsupported( + "BC1 size not a multiple of four", + )); + } + let handle = self.allocate_handle(); + self.resources.insert( + handle, + GraphicsResource { + handle, + desc: ResourceDesc { + dimension: ResourceDimension::Texture2D, + width: u64::from(width), + height, + depth_or_array_size: 1, + mip_levels: 1, + format_rgba8: format == TextureFormat::Rgba8Unorm, + }, + state: initial_state, + guest_backing_addr: guest_addr, + data: vec![0; format.level_size(width, height)], + texture_format: Some(format), + }, + ); + Ok(handle) + } + + /// Create a descriptor heap (`CreateDescriptorHeap`). `heap_type` is a + /// `D3D12_DESCRIPTOR_HEAP_TYPE`; only shader-visible `CBV_SRV_UAV` and + /// `SAMPLER` heaps of 1 to [`MAX_DESCRIPTORS_PER_HEAP`] descriptors exist. + pub fn create_descriptor_heap( + &mut self, + device: GraphicsHandle, + heap_type: u32, + num_descriptors: u32, + shader_visible: bool, + ) -> Result { + if !self.devices.contains_key(&device) { + return Err(GraphicsError::InvalidDeviceHandle); + } + let heap_type = DescriptorHeapType::from_d3d12(heap_type) + .ok_or(GraphicsError::Unsupported("descriptor heap type"))?; + if !shader_visible { + return Err(GraphicsError::Unsupported( + "non-shader-visible descriptor heap", + )); + } + if !(1..=MAX_DESCRIPTORS_PER_HEAP).contains(&num_descriptors) { + return Err(GraphicsError::Unsupported("descriptor heap capacity")); + } + let handle = self.allocate_handle(); + if handle.id >= 1 << 31 { + return Err(GraphicsError::Unsupported( + "descriptor heap ID space exhausted", + )); + } + self.descriptor_heaps.insert( + handle.id, + DescriptorHeap { + handle, + heap_type, + slots: vec![None; num_descriptors as usize], + }, + ); + Ok(handle) + } + + fn descriptor_heap(&self, heap: GraphicsHandle) -> Result<&DescriptorHeap, GraphicsError> { + self.descriptor_heaps + .get(&heap.id) + .filter(|found| found.handle == heap) + .ok_or(GraphicsError::InvalidDescriptor) + } + + /// `GetCPUDescriptorHandleForHeapStart`. + pub fn cpu_descriptor_handle_for_heap_start( + &self, + heap: GraphicsHandle, + ) -> Result { + self.descriptor_heap(heap)?; + Ok(CpuDescriptorHandle(u64::from(heap.id) << 32)) + } + + /// `GetGPUDescriptorHandleForHeapStart`. + pub fn gpu_descriptor_handle_for_heap_start( + &self, + heap: GraphicsHandle, + ) -> Result { + self.descriptor_heap(heap)?; + Ok(GpuDescriptorHandle( + GPU_DESCRIPTOR_SPACE | u64::from(heap.id) << 32, + )) + } + + /// `GetDescriptorHandleIncrementSize` for a `D3D12_DESCRIPTOR_HEAP_TYPE`. + pub fn descriptor_handle_increment_size(&self, heap_type: u32) -> Result { + DescriptorHeapType::from_d3d12(heap_type) + .map(|_| DESCRIPTOR_HANDLE_INCREMENT) + .ok_or(GraphicsError::Unsupported("descriptor heap type")) + } + + /// The heap ID and slot index a handle in the given space names, if it is + /// increment-aligned. The heap itself is not checked. + fn decode_descriptor_handle(value: u64, gpu: bool) -> Option<(u32, usize)> { + if (value & GPU_DESCRIPTOR_SPACE != 0) != gpu { + return None; + } + let value = value & !GPU_DESCRIPTOR_SPACE; + let offset = value as u32; + if !offset.is_multiple_of(DESCRIPTOR_HANDLE_INCREMENT) { + return None; + } + Some(( + (value >> 32) as u32, + (offset / DESCRIPTOR_HANDLE_INCREMENT) as usize, + )) + } + + fn write_descriptor( + &mut self, + dest: CpuDescriptorHandle, + heap_type: DescriptorHeapType, + descriptor: Descriptor, + ) -> Result<(), GraphicsError> { + let (heap_id, index) = Self::decode_descriptor_handle(dest.0, false) + .ok_or(GraphicsError::InvalidDescriptor)?; + let heap = self + .descriptor_heaps + .get_mut(&heap_id) + .ok_or(GraphicsError::InvalidDescriptor)?; + if heap.heap_type != heap_type { + return Err(GraphicsError::InvalidDescriptor); + } + let slot = heap + .slots + .get_mut(index) + .ok_or(GraphicsError::InvalidDescriptor)?; + *slot = Some(descriptor); + Ok(()) + } + + /// `CreateShaderResourceView` of a single-level 2D texture into a + /// `CBV_SRV_UAV` heap slot. The view format must equal the resource's. + pub fn create_shader_resource_view( + &mut self, + resource: GraphicsHandle, + desc: &ShaderResourceViewDesc, + dest: CpuDescriptorHandle, + ) -> Result<(), GraphicsError> { + let res = self + .resources + .get(&resource) + .ok_or(GraphicsError::InvalidResourceHandle)?; + if res.desc.dimension != ResourceDimension::Texture2D + || res.desc.depth_or_array_size != 1 + || res.desc.mip_levels != 1 + { + return Err(GraphicsError::Unsupported( + "SRV of a resource other than a single-level, single-slice 2D texture", + )); + } + if desc.view_dimension != SrvDimension::Texture2D { + return Err(GraphicsError::Unsupported( + "SRV dimension other than Texture2D", + )); + } + if desc.most_detailed_mip != 0 || desc.mip_levels != 1 { + return Err(GraphicsError::Unsupported( + "SRV mip range other than level 0", + )); + } + let format = TextureFormat::from_dxgi(desc.format) + .ok_or(GraphicsError::Unsupported("SRV format"))?; + if res.texture_format != Some(format) { + return Err(GraphicsError::Unsupported( + "SRV format differs from the resource", + )); + } + let max = u64::from(MAX_TEXTURE_DIMENSION); + if !(1..=max).contains(&res.desc.width) || !(1..=max).contains(&u64::from(res.desc.height)) + { + return Err(GraphicsError::Unsupported("texture size")); + } + self.write_descriptor( + dest, + DescriptorHeapType::CbvSrvUav, + Descriptor::Srv { resource, format }, + ) + } + + /// `CreateSampler` into a `SAMPLER` heap slot. + pub fn create_sampler( + &mut self, + desc: &SamplerDesc, + dest: CpuDescriptorHandle, + ) -> Result<(), GraphicsError> { + desc.validate()?; + self.write_descriptor( + dest, + DescriptorHeapType::Sampler, + Descriptor::Sampler(*desc), + ) + } + + /// `CreateRootSignature` from an unserialized description. Only one + /// pixel-stage table for `t0` and one for `s0` are supported. + pub fn create_root_signature( + &mut self, + device: GraphicsHandle, + desc: &RootSignatureDesc, + ) -> Result { + if !self.devices.contains_key(&device) { + return Err(GraphicsError::InvalidDeviceHandle); + } + let root_signature = RootSignature::from_desc(desc)?; + let handle = self.allocate_handle(); + self.root_signatures.insert(handle, root_signature); + Ok(handle) + } + + fn recording_list( + &mut self, + list: GraphicsHandle, + ) -> Result<&mut GraphicsCommandList, GraphicsError> { + let cmd_list = self + .command_lists + .get_mut(&list) + .ok_or(GraphicsError::InvalidCommandListHandle)?; + if !cmd_list.is_recording { + return Err(GraphicsError::CommandListNotRecording); + } + Ok(cmd_list) + } + + /// Record `SetDescriptorHeaps`: at most one heap of each type. + pub fn cmd_set_descriptor_heaps( + &mut self, + list: GraphicsHandle, + heaps: &[GraphicsHandle], + ) -> Result<(), GraphicsError> { + let mut types = Vec::with_capacity(heaps.len()); + for &heap in heaps { + let heap_type = self.descriptor_heap(heap)?.heap_type; + if types.contains(&heap_type) { + return Err(GraphicsError::InvalidDescriptor); + } + types.push(heap_type); + } + self.recording_list(list)? + .commands + .push(GraphicsCommand::SetDescriptorHeaps { + heaps: heaps.to_vec(), + }); + Ok(()) + } + + /// Record `SetGraphicsRootSignature`. + pub fn cmd_set_graphics_root_signature( + &mut self, + list: GraphicsHandle, + root_signature: GraphicsHandle, + ) -> Result<(), GraphicsError> { + if !self.root_signatures.contains_key(&root_signature) { + return Err(GraphicsError::InvalidDescriptor); + } + self.recording_list(list)? + .commands + .push(GraphicsCommand::SetGraphicsRootSignature { root_signature }); + Ok(()) + } + + /// Record `SetGraphicsRootDescriptorTable`. When the list executes, the + /// command checks the base against the bound root signature and the bound + /// heap of the table's type. A draw then reads the descriptor it names. + pub fn cmd_set_graphics_root_descriptor_table( + &mut self, + list: GraphicsHandle, + root_parameter_index: u32, + base: GpuDescriptorHandle, + ) -> Result<(), GraphicsError> { + self.recording_list(list)? + .commands + .push(GraphicsCommand::SetGraphicsRootDescriptorTable { + root_parameter_index, + base, + }); + Ok(()) + } + /// Close command list. pub fn close_command_list(&mut self, list: GraphicsHandle) -> Result<(), GraphicsError> { let cmd_list = self @@ -738,6 +1466,11 @@ impl GraphicsContext { backend_renderer: Option<&BackendRenderer<'_>>, backend_id: GraphicsBackendId, ) -> Result { + let textured_backend = self.textured_backend.clone(); + let textured_renderer: Option<&TexturedBackendRenderer<'_>> = match &textured_backend { + Some(arc) => Some(arc.as_ref()), + None => None, + }; let cmd_queue = self .queues .get_mut(&queue) @@ -766,6 +1499,7 @@ impl GraphicsContext { let mut index_buffer: Option<(GraphicsHandle, usize, IndexFormat)> = None; let mut rendered_output: Option> = None; let mut draw_count = 0usize; + let mut bindings = TableBindings::default(); for cmd in &cmd_list.commands { match cmd { @@ -807,6 +1541,59 @@ impl GraphicsContext { offset, format, } => index_buffer = Some((*resource, *offset, *format)), + GraphicsCommand::SetDescriptorHeaps { heaps } => { + let (mut srv_heap, mut sampler_heap) = (None, None); + for &heap in heaps { + match self.descriptor_heap(heap)?.heap_type { + DescriptorHeapType::CbvSrvUav => srv_heap = Some(heap.id), + DescriptorHeapType::Sampler => sampler_heap = Some(heap.id), + } + } + // Changing the heaps invalidates tables bound in the old + // ones; setting the same heaps again keeps them. + if (srv_heap, sampler_heap) != (bindings.srv_heap, bindings.sampler_heap) { + bindings.tables = [None; 2]; + } + bindings.srv_heap = srv_heap; + bindings.sampler_heap = sampler_heap; + } + GraphicsCommand::SetGraphicsRootSignature { root_signature } => { + let layout = *self + .root_signatures + .get(root_signature) + .ok_or(GraphicsError::InvalidDescriptor)?; + // A different root signature invalidates every root + // argument; setting the bound one again keeps them. + if bindings.root_signature.map(|(handle, _)| handle) != Some(*root_signature) { + bindings.tables = [None; 2]; + } + bindings.root_signature = Some((*root_signature, layout)); + } + GraphicsCommand::SetGraphicsRootDescriptorTable { + root_parameter_index, + base, + } => { + let (_, layout) = bindings + .root_signature + .ok_or(GraphicsError::InvalidDescriptor)?; + let bound_heap = if *root_parameter_index == layout.srv_parameter { + bindings.srv_heap + } else if *root_parameter_index == layout.sampler_parameter { + bindings.sampler_heap + } else { + return Err(GraphicsError::InvalidDescriptor); + }; + // The base must name a slot of the bound heap of the + // table's type; its contents are read at the draw. + let (heap_id, index) = Self::decode_descriptor_handle(base.0, true) + .ok_or(GraphicsError::InvalidDescriptor)?; + if bound_heap != Some(heap_id) + || index >= self.descriptor_heaps[&heap_id].slots.len() + { + return Err(GraphicsError::InvalidDescriptor); + } + bindings.tables[*root_parameter_index as usize] = Some(*base); + } GraphicsCommand::DrawIndexedInstanced { index_count_per_instance, instance_count, @@ -823,6 +1610,9 @@ impl GraphicsContext { if *index_count_per_instance == 0 || *instance_count == 0 { continue; } + if bindings.root_signature.is_some() { + return Err(GraphicsError::Unsupported("textured indexed draws")); + } let vertices = self.fetch_indexed_triangle( memory, index_buffer, @@ -848,8 +1638,41 @@ impl GraphicsContext { } GraphicsCommand::DrawInstanced { vertex_count_per_instance, - .. + instance_count, + start_vertex_location, + start_instance_location, } => { + if let Some((_, root_signature)) = bindings.root_signature { + if *vertex_count_per_instance == 0 || *instance_count == 0 { + continue; + } + if *vertex_count_per_instance != 3 + || *instance_count != 1 + || *start_instance_location != 0 + { + return Err(GraphicsError::Unsupported( + "textured draw other than one instance of three vertices", + )); + } + let pixels = self.textured_draw( + memory, + &bindings, + root_signature, + (vertex_resource, vertex_offset, vertex_stride), + *start_vertex_location, + (viewport, clear_color), + (textured_renderer, backend_id), + )?; + draw_count += 1; + if let Some(th) = target_handle + && let Some(target_res) = self.resources.get_mut(&th) + && target_res.data.len() >= pixels.len() + { + target_res.data[..pixels.len()].copy_from_slice(&pixels); + } + rendered_output = Some(pixels); + continue; + } if *vertex_count_per_instance < 3 { continue; } @@ -976,6 +1799,184 @@ impl GraphicsContext { Ok(vertices) } + /// Resolve the SRV and sampler tables, fetch one textured triangle and + /// draw it on the textured backend, or on the software reference when no + /// native backend is required. Every check runs before any drawing. + #[allow(clippy::too_many_arguments)] + fn textured_draw( + &self, + memory: &GuestMemory, + bindings: &TableBindings, + root_signature: RootSignature, + (vertex_resource, vertex_offset, vertex_stride): (Option, usize, usize), + start_vertex: u32, + (viewport, clear_color): ((usize, usize), [u8; 4]), + (renderer, backend_id): (Option<&TexturedBackendRenderer<'_>>, GraphicsBackendId), + ) -> Result, GraphicsError> { + let srv = self.resolve_table(bindings, root_signature.srv_parameter, bindings.srv_heap)?; + let sampler = self.resolve_table( + bindings, + root_signature.sampler_parameter, + bindings.sampler_heap, + )?; + let (Descriptor::Srv { resource, format }, Descriptor::Sampler(sampler)) = (srv, sampler) + else { + return Err(GraphicsError::InvalidDescriptor); + }; + let texture = self + .resources + .get(&resource) + .ok_or(GraphicsError::InvalidResourceHandle)?; + // COMMON promotes to a shader-resource read. Any other state must + // include PIXEL_SHADER_RESOURCE and combine it only with read states. + let state = texture.state.0; + if state != ResourceStates::COMMON.0 + && (state & ResourceStates::PIXEL_SHADER_RESOURCE.0 == 0 || state & !READ_STATES != 0) + { + return Err(GraphicsError::ResourceLifetimeViolation); + } + let width = texture.desc.width as u32; + let height = texture.desc.height; + let mut bytes = vec![0; format.level_size(width, height)]; + Self::read_resource(texture, memory, 0, &mut bytes)?; + + let vertex_res = vertex_resource + .and_then(|handle| self.resources.get(&handle)) + .ok_or(GraphicsError::InvalidResourceHandle)?; + if vertex_stride < 32 { + return Err(GraphicsError::InvalidDescriptor); + } + let mut positions = [[0.0f32; 4]; 3]; + let mut texcoords = [[0.0f32; 4]; 3]; + for (k, (position, texcoord)) in positions.iter_mut().zip(&mut texcoords).enumerate() { + let at = (start_vertex as usize + k) + .checked_mul(vertex_stride) + .and_then(|bytes| bytes.checked_add(vertex_offset)) + .ok_or(GraphicsError::IndexOutOfRange)?; + let mut raw = [0u8; 32]; + Self::read_resource(vertex_res, memory, at, &mut raw)?; + for (value, bytes) in position + .iter_mut() + .chain(texcoord.iter_mut()) + .zip(raw.as_chunks::<4>().0) + { + *value = f32::from_le_bytes(*bytes); + } + } + + let draw = TexturedDraw { + positions, + texcoords, + viewport, + clear_color, + texture: TextureView { + format, + width, + height, + bytes: &bytes, + }, + sampler, + }; + if let Some(renderer) = renderer { + renderer(&draw) + } else if backend_id == GraphicsBackendId::MetalNative { + Err(GraphicsError::NativeMetalRequired) + } else { + Self::execute_software_reference_textured_draw(&draw) + } + } + + /// The descriptor that the table at `parameter` names in the bound heap. + fn resolve_table( + &self, + bindings: &TableBindings, + parameter: u32, + bound_heap: Option, + ) -> Result { + let base = bindings.tables[parameter as usize].ok_or(GraphicsError::InvalidDescriptor)?; + let (heap_id, index) = + Self::decode_descriptor_handle(base.0, true).ok_or(GraphicsError::InvalidDescriptor)?; + if bound_heap != Some(heap_id) { + return Err(GraphicsError::InvalidDescriptor); + } + self.descriptor_heaps + .get(&heap_id) + .and_then(|heap| heap.slots.get(index).copied().flatten()) + .ok_or(GraphicsError::InvalidDescriptor) + } + + /// Software reference for a textured triangle: the coverage rule of + /// [`Self::execute_software_reference_draw`], affine interpolation of the + /// texture coordinate at each pixel center, and point sampling with + /// clamp addressing (`texel = min(floor(clamp(u, 0, 1) * width), width - 1)`). + /// BC1 levels are decoded with `xenora_texture::decode_bc1`. Positions + /// must have `w == 1`. + pub fn execute_software_reference_textured_draw( + draw: &TexturedDraw<'_>, + ) -> Result, GraphicsError> { + if draw.positions.iter().any(|position| position[3] != 1.0) { + return Err(GraphicsError::Unsupported( + "software textured draw with w other than 1", + )); + } + if draw + .positions + .iter() + .chain(&draw.texcoords) + .flatten() + .any(|value| !value.is_finite()) + { + return Err(GraphicsError::InvalidDescriptor); + } + let max = MAX_TEXTURE_DIMENSION; + if !(1..=max).contains(&draw.texture.width) || !(1..=max).contains(&draw.texture.height) { + return Err(GraphicsError::Unsupported("texture size")); + } + let texels = decode_texture(&draw.texture)?; + let (tex_w, tex_h) = (draw.texture.width as usize, draw.texture.height as usize); + let (w, h) = draw.viewport; + let count = w + .checked_mul(h) + .filter(|&count| (1..=MAX_SOFTWARE_TEXTURED_PIXELS).contains(&count)) + .ok_or(GraphicsError::InvalidViewport)?; + let mut pixels = draw.clear_color.repeat(count); + let window = |p: [f32; 4]| [(p[0] + 1.0) * 0.5 * w as f32, (1.0 - p[1]) * 0.5 * h as f32]; + let [p0, p1, p2] = draw.positions.map(window); + let edge = |a: [f32; 2], b: [f32; 2], c: [f32; 2]| -> f32 { + (c[0] - a[0]) * (b[1] - a[1]) - (c[1] - a[1]) * (b[0] - a[0]) + }; + let area = edge(p0, p1, p2); + if area.abs() < 1e-5 { + return Ok(pixels); + } + let nearest = |coord: f32, size: usize| { + ((f64::from(coord.clamp(0.0, 1.0)) * size as f64).floor() as usize).min(size - 1) + }; + for y in 0..h { + for x in 0..w { + let pt = [x as f32 + 0.5, y as f32 + 0.5]; + let b = [edge(p1, p2, pt), edge(p2, p0, pt), edge(p0, p1, pt)]; + let inside = if area > 0.0 { + b.iter().all(|&e| e >= 0.0) + } else { + b.iter().all(|&e| e <= 0.0) + }; + if !inside { + continue; + } + let [u, v] = [0, 1].map(|axis| { + (0..3) + .map(|k| b[k] / area * draw.texcoords[k][axis]) + .sum::() + }); + let texel = (nearest(v, tex_h) * tex_w + nearest(u, tex_w)) * 4; + let idx = (y * w + x) * 4; + pixels[idx..idx + 4].copy_from_slice(&texels[texel..texel + 4]); + } + } + Ok(pixels) + } + /// Read `out.len()` bytes at `offset` of a resource, from its guest backing /// when it has one. The range must lie inside the resource's size. fn read_resource( @@ -1057,3 +2058,30 @@ impl GraphicsContext { Ok(pixels) } } + +/// Row-major RGBA8 texels of a bound texture level. +fn decode_texture(texture: &TextureView<'_>) -> Result, GraphicsError> { + let (width, height) = (texture.width as usize, texture.height as usize); + if texture.bytes.len() != texture.format.level_size(texture.width, texture.height) { + return Err(GraphicsError::InvalidDescriptor); + } + match texture.format { + TextureFormat::Rgba8Unorm => Ok(texture.bytes.to_vec()), + TextureFormat::Bc1Unorm => { + let blocks_wide = width.div_ceil(4); + let mut texels = vec![0; width * height * 4]; + for (block_index, block) in texture.bytes.as_chunks::<8>().0.iter().enumerate() { + let decoded = xenora_texture::decode_bc1(*block); + let (bx, by) = (block_index % blocks_wide * 4, block_index / blocks_wide * 4); + for (i, texel) in decoded.iter().enumerate() { + let (x, y) = (bx + i % 4, by + i / 4); + if x < width && y < height { + let at = (y * width + x) * 4; + texels[at..at + 4].copy_from_slice(texel); + } + } + } + Ok(texels) + } + } +} diff --git a/crates/loader/tests/graphics_textures.rs b/crates/loader/tests/graphics_textures.rs new file mode 100644 index 0000000..3edec4c --- /dev/null +++ b/crates/loader/tests/graphics_textures.rs @@ -0,0 +1,1228 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Guest draws that sample a texture bound through D3D12-style descriptor +//! heaps, a root signature and descriptor tables (#303). +//! +//! Every fixture is synthetic. The expected images are written out by hand +//! from the texel data and the draw geometry, so they depend on neither the +//! software reference nor the native Metal path. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use xenora_loader::graphics::{ + CommandListType, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, DXGI_FORMAT_BC1_UNORM, + DXGI_FORMAT_R8G8B8A8_UNORM, DescriptorRange, DescriptorRangeType, ExecutionOutcome, + GraphicsBackendId, GraphicsContext, GraphicsError, GraphicsHandle, ResourceDesc, + ResourceDimension, ResourceStates, RootParameter, RootSignatureDesc, SamplerDesc, + ShaderResourceViewDesc, ShaderVisibility, SrvDimension, TextureFormat, +}; +use xenora_loader::memory::{GuestMemory, MemoryPermissions}; + +const CBV_SRV_UAV: u32 = 0; +const SAMPLER: u32 = 1; +const VB_ADDR: u64 = 0x10_0000; +const TEX_ADDR: u64 = 0x20_0000; +const STRIDE: usize = 32; + +/// Texel `(x, y)` of the 4×4 texture A is `[64x + 16, 64y + 16, 200, 255]`. +fn texture_a() -> Vec { + (0..16u8) + .flat_map(|i| [(i % 4) * 64 + 16, (i / 4) * 64 + 16, 200, 255]) + .collect() +} + +/// Texel `(x, y)` of the 4×4 texture B is `[7, 11x + 3, 13y + 5, 255]`. +fn texture_b() -> Vec { + (0..16u8) + .flat_map(|i| [7, (i % 4) * 11 + 3, (i / 4) * 13 + 5, 255]) + .collect() +} + +/// An 8×8 BC1 texture of four row-major blocks. Each block selects only its +/// two endpoints (selector 0 or 1), whose RGB565 words expand exactly to 0 +/// or 255 per channel. Interpolated palette entries are left out: Apple's +/// hardware decoder rounds them differently from the spec formula. +/// Each block uses selector 1 where `x == 0 || y == 3` within the block. +const BC1_BLOCKS: [[u8; 8]; 4] = [ + // Endpoint 0 red (0xF800), endpoint 1 blue (0x001F). + [0x00, 0xF8, 0x1F, 0x00, 0x01, 0x01, 0x01, 0x55], + // Green (0x07E0), black (0x0000). + [0xE0, 0x07, 0x00, 0x00, 0x01, 0x01, 0x01, 0x55], + // White (0xFFFF), magenta (0xF81F). + [0xFF, 0xFF, 0x1F, 0xF8, 0x01, 0x01, 0x01, 0x55], + // Yellow (0xFFE0), cyan (0x07FF). + [0xE0, 0xFF, 0xFF, 0x07, 0x01, 0x01, 0x01, 0x55], +]; + +/// The BC1 texture decoded by hand, row-major RGBA8. +fn bc1_expected() -> Vec { + let endpoints = [ + [[255, 0, 0, 255], [0, 0, 255, 255]], + [[0, 255, 0, 255], [0, 0, 0, 255]], + [[255, 255, 255, 255], [255, 0, 255, 255]], + [[255, 255, 0, 255], [0, 255, 255, 255]], + ]; + let mut texels = Vec::new(); + for y in 0..8 { + for x in 0..8 { + let block = (y / 4) * 2 + x / 4; + let selector = usize::from(x % 4 == 0 || y % 4 == 3); + texels.extend(endpoints[block][selector]); + } + } + texels +} + +/// A fullscreen triangle: position float4, then texture coordinate float4. +/// Over an N×N viewport the pixel centre `(x + 0.5, y + 0.5)` gets +/// `uv = ((x + 0.5) / N, (y + 0.5) / N)`, so pixel `(x, y)` of an N×N +/// texture samples texel `(x, y)` and the image equals the texture. +const VERTICES: [[f32; 8]; 3] = [ + [-1.0, -1.0, 0.5, 1.0, 0.0, 1.0, 0.0, 1.0], + [3.0, -1.0, 0.5, 1.0, 2.0, 1.0, 0.0, 1.0], + [-1.0, 3.0, 0.5, 1.0, 0.0, -1.0, 0.0, 1.0], +]; + +/// The same triangle with `uv' = 2·uv − 0.6`: pixel centres sample +/// u (and v) = −0.35, 0.15, 0.65, 1.15, off texel centres and outside +/// [0, 1] on both sides. Point sampling with clamping reads texels +/// 0, 0, 2, 3 along each axis; wrapping or linear filtering would not. +const CLAMP_VERTICES: [[f32; 8]; 3] = [ + [-1.0, -1.0, 0.5, 1.0, -0.6, 1.4, 0.0, 1.0], + [3.0, -1.0, 0.5, 1.0, 3.4, 1.4, 0.0, 1.0], + [-1.0, 3.0, 0.5, 1.0, -0.6, -2.6, 0.0, 1.0], +]; +const CLAMPED_TEXEL: [usize; 4] = [0, 0, 2, 3]; + +fn pixel_table(range_type: DescriptorRangeType) -> RootParameter { + RootParameter::DescriptorTable { + ranges: vec![DescriptorRange { + range_type, + num_descriptors: 1, + base_shader_register: 0, + register_space: 0, + offset_in_descriptors_from_table_start: 0, + }], + visibility: ShaderVisibility::Pixel, + } +} + +fn root_signature_desc() -> RootSignatureDesc { + RootSignatureDesc { + parameters: vec![ + pixel_table(DescriptorRangeType::Srv), + pixel_table(DescriptorRangeType::Sampler), + ], + static_sampler_count: 0, + } +} + +fn srv_desc(format: u32) -> ShaderResourceViewDesc { + ShaderResourceViewDesc { + format, + view_dimension: SrvDimension::Texture2D, + most_detailed_mip: 0, + mip_levels: 1, + } +} + +struct Rig { + ctx: GraphicsContext, + memory: GuestMemory, + device: GraphicsHandle, + queue: GraphicsHandle, + alloc: GraphicsHandle, + list: GraphicsHandle, + vb: GraphicsHandle, + srv_heap: GraphicsHandle, + sampler_heap: GraphicsHandle, + root_signature: GraphicsHandle, + /// Sampler table at root parameter 0, SRV table at 1. + swapped_root_signature: GraphicsHandle, +} + +/// SRV heap slots: 0 texture A (4×4), 1 texture B (4×4), 2 the 8×8 BC1 +/// texture, 3 empty. +/// Sampler heap slots: 0 and 2 point/clamp, 1 empty. Every supported +/// sampler has the same state, so slots differ only in being filled. +fn rig() -> Rig { + let mut ctx = GraphicsContext::new(); + let device = ctx.create_device().unwrap(); + let queue = ctx + .create_command_queue(device, CommandListType::Direct) + .unwrap(); + let alloc = ctx + .create_command_allocator(device, CommandListType::Direct) + .unwrap(); + let list = ctx + .create_command_list(device, alloc, CommandListType::Direct) + .unwrap(); + // Records 0–2 are VERTICES and 3–5 CLAMP_VERTICES. + let vertex_bytes: Vec = VERTICES + .as_flattened() + .iter() + .chain(CLAMP_VERTICES.as_flattened()) + .flat_map(|value| value.to_le_bytes()) + .collect(); + let vb = ctx + .create_committed_resource( + device, + ResourceDesc { + dimension: ResourceDimension::Buffer, + width: vertex_bytes.len() as u64, + height: 1, + depth_or_array_size: 1, + mip_levels: 1, + format_rgba8: false, + }, + ResourceStates::VERTEX_AND_CONSTANT_BUFFER, + Some(VB_ADDR), + ) + .unwrap(); + let mut memory = GuestMemory::new(); + memory + .map_region_with_data(VB_ADDR, 0x1000, MemoryPermissions::READ_ONLY, &vertex_bytes) + .unwrap(); + + let textures = [ + (DXGI_FORMAT_R8G8B8A8_UNORM, texture_a()), + (DXGI_FORMAT_R8G8B8A8_UNORM, texture_b()), + (DXGI_FORMAT_BC1_UNORM, BC1_BLOCKS.as_flattened().to_vec()), + ]; + let srv_heap = ctx + .create_descriptor_heap(device, CBV_SRV_UAV, 4, true) + .unwrap(); + let srv_start = ctx.cpu_descriptor_handle_for_heap_start(srv_heap).unwrap(); + for (slot, (format, bytes)) in (0u32..).zip(&textures) { + let addr = TEX_ADDR + u64::from(slot) * 0x1000; + memory + .map_region_with_data(addr, 0x1000, MemoryPermissions::READ_ONLY, bytes) + .unwrap(); + let size = if *format == DXGI_FORMAT_BC1_UNORM { + 8 + } else { + 4 + }; + let texture = ctx + .create_committed_texture2d( + device, + size, + size, + *format, + ResourceStates::COMMON, + Some(addr), + ) + .unwrap(); + ctx.create_shader_resource_view( + texture, + &srv_desc(*format), + srv_start.offset(slot).unwrap(), + ) + .unwrap(); + } + let sampler_heap = ctx + .create_descriptor_heap(device, SAMPLER, 3, true) + .unwrap(); + let sampler_start = ctx + .cpu_descriptor_handle_for_heap_start(sampler_heap) + .unwrap(); + for slot in [0, 2] { + ctx.create_sampler( + &SamplerDesc::point_clamp(), + sampler_start.offset(slot).unwrap(), + ) + .unwrap(); + } + let root_signature = ctx + .create_root_signature(device, &root_signature_desc()) + .unwrap(); + let swapped_root_signature = ctx + .create_root_signature( + device, + &RootSignatureDesc { + parameters: vec![ + pixel_table(DescriptorRangeType::Sampler), + pixel_table(DescriptorRangeType::Srv), + ], + static_sampler_count: 0, + }, + ) + .unwrap(); + Rig { + ctx, + memory, + device, + queue, + alloc, + list, + vb, + srv_heap, + sampler_heap, + root_signature, + swapped_root_signature, + } +} + +/// What one textured draw binds; `None` leaves that table unset. +#[derive(Clone, Copy)] +struct Binding { + srv_slot: Option, + sampler_slot: Option, + heaps_bound: (bool, bool), + stride: usize, + viewport: u32, + first_vertex: u32, + swapped: bool, + /// Vertex count, instance count, start instance. + draw: (u32, u32, u32), +} + +const SLOT_0: Binding = Binding { + srv_slot: Some(0), + sampler_slot: Some(0), + heaps_bound: (true, true), + stride: STRIDE, + viewport: 4, + first_vertex: 0, + swapped: false, + draw: (3, 1, 0), +}; + +/// Slot 2 holds the 8×8 BC1 texture and is drawn into an 8×8 viewport. +fn srv(slot: u32) -> Binding { + Binding { + srv_slot: Some(slot), + viewport: if slot == 2 { 8 } else { 4 }, + ..SLOT_0 + } +} + +/// Record and run: the binding's viewport, heaps, root signature, the two +/// tables (SRV at root parameter 0 and sampler at 1, or swapped) and one draw. +fn run(rig: &mut Rig, binding: Binding) -> Result { + let ctx = &mut rig.ctx; + ctx.reset_command_list(rig.list, rig.alloc)?; + let size = binding.viewport as usize; + ctx.cmd_set_viewport(rig.list, size, size)?; + ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, binding.stride)?; + let mut heaps = Vec::new(); + if binding.heaps_bound.0 { + heaps.push(rig.srv_heap); + } + if binding.heaps_bound.1 { + heaps.push(rig.sampler_heap); + } + ctx.cmd_set_descriptor_heaps(rig.list, &heaps)?; + let (root_signature, srv_parameter, sampler_parameter) = if binding.swapped { + (rig.swapped_root_signature, 1, 0) + } else { + (rig.root_signature, 0, 1) + }; + ctx.cmd_set_graphics_root_signature(rig.list, root_signature)?; + if let Some(slot) = binding.srv_slot { + let base = ctx.gpu_descriptor_handle_for_heap_start(rig.srv_heap)?; + let base = base.offset(slot).unwrap(); + ctx.cmd_set_graphics_root_descriptor_table(rig.list, srv_parameter, base)?; + } + if let Some(slot) = binding.sampler_slot { + let base = ctx.gpu_descriptor_handle_for_heap_start(rig.sampler_heap)?; + let base = base.offset(slot).unwrap(); + ctx.cmd_set_graphics_root_descriptor_table(rig.list, sampler_parameter, base)?; + } + let (vertices, instances, start_instance) = binding.draw; + ctx.cmd_draw_instanced( + rig.list, + vertices, + instances, + binding.first_vertex, + start_instance, + )?; + ctx.close_command_list(rig.list)?; + ctx.execute_command_list(rig.queue, rig.list, &rig.memory) +} + +#[test] +fn software_textured_draw_reproduces_rgba8_texels() { + let mut rig = rig(); + let outcome = run(&mut rig, SLOT_0).expect("textured draw"); + assert_eq!(outcome.backend, GraphicsBackendId::SoftwareReference); + assert_eq!(outcome.draw_count, 1); + assert_eq!((outcome.width, outcome.height), (4, 4)); + assert_eq!(outcome.pixels, texture_a()); +} + +/// The draw reads the descriptor the table names: slot 1 gives texture B, +/// which differs from texture A in every texel. +#[test] +fn descriptor_table_offset_selects_the_texture() { + let mut rig = rig(); + let outcome = run(&mut rig, srv(1)).expect("textured draw"); + assert_eq!(outcome.pixels, texture_b()); + for (a, b) in texture_a().chunks(4).zip(texture_b().chunks(4)) { + assert_ne!(a, b); + } +} + +#[test] +fn software_textured_draw_decodes_bc1() { + let mut rig = rig(); + let outcome = run(&mut rig, srv(2)).expect("BC1 textured draw"); + assert_eq!((outcome.width, outcome.height), (8, 8)); + assert_eq!(outcome.pixels, bc1_expected()); + // The shared BC1 decoder agrees with the hand-decoded blocks. + let expected = bc1_expected(); + for (index, block) in BC1_BLOCKS.into_iter().enumerate() { + let (bx, by) = (index % 2 * 4, index / 2 * 4); + for (i, texel) in xenora_texture::decode_bc1(block).iter().enumerate() { + let at = ((by + i / 4) * 8 + bx + i % 4) * 4; + assert_eq!(texel, &expected[at..at + 4], "block {index} texel {i}"); + } + } +} + +#[test] +fn unsupported_objects_fail_at_creation() { + let mut rig = rig(); + let ctx = &mut rig.ctx; + let device = rig.device; + let unsupported = |result: Result<(), GraphicsError>, case: &str| { + assert!( + matches!(result, Err(GraphicsError::Unsupported(_))), + "{case}: {result:?}" + ); + }; + + // Descriptor heaps: RTV and DSV types, CPU-only heaps, capacity. + for (heap_type, count, visible, case) in [ + (2, 4, true, "RTV heap"), + (3, 4, true, "DSV heap"), + (CBV_SRV_UAV, 4, false, "non-shader-visible heap"), + (CBV_SRV_UAV, 0, true, "empty heap"), + (SAMPLER, 65, true, "heap over capacity"), + ] { + unsupported( + ctx.create_descriptor_heap(device, heap_type, count, visible) + .map(drop), + case, + ); + } + + // Textures: other formats and BC1 sizes that are not whole blocks. + unsupported( + ctx.create_committed_texture2d(device, 4, 4, 2, ResourceStates::COMMON, None) + .map(drop), + "R32G32B32A32_FLOAT texture", + ); + unsupported( + ctx.create_committed_texture2d( + device, + 6, + 6, + DXGI_FORMAT_BC1_UNORM, + ResourceStates::COMMON, + None, + ) + .map(drop), + "6x6 BC1 texture", + ); + unsupported( + ctx.create_committed_texture2d( + device, + 65, + 4, + DXGI_FORMAT_R8G8B8A8_UNORM, + ResourceStates::COMMON, + None, + ) + .map(drop), + "texture over the size limit", + ); + + // Shader resource views. + let texture = ctx + .create_committed_texture2d( + device, + 4, + 4, + DXGI_FORMAT_R8G8B8A8_UNORM, + ResourceStates::COMMON, + None, + ) + .unwrap(); + let dest = ctx + .cpu_descriptor_handle_for_heap_start(rig.srv_heap) + .unwrap(); + let base = srv_desc(DXGI_FORMAT_R8G8B8A8_UNORM); + for (desc, case) in [ + ( + srv_desc(DXGI_FORMAT_BC1_UNORM), + "format differs from resource", + ), + (srv_desc(10), "R16G16B16A16_FLOAT view"), + ( + ShaderResourceViewDesc { + view_dimension: SrvDimension::Texture3D, + ..base + }, + "Texture3D view", + ), + ( + ShaderResourceViewDesc { + mip_levels: 2, + ..base + }, + "two-level view", + ), + ] { + unsupported(ctx.create_shader_resource_view(texture, &desc, dest), case); + } + + // Samplers. + let dest = ctx + .cpu_descriptor_handle_for_heap_start(rig.sampler_heap) + .unwrap(); + let point = SamplerDesc::point_clamp(); + for (desc, case) in [ + ( + SamplerDesc { + filter: 0x15, + ..point + }, + "linear filter", + ), + ( + SamplerDesc { + address_v: 1, + ..point + }, + "wrap addressing", + ), + ( + SamplerDesc { + mip_lod_bias: 0.5, + ..point + }, + "LOD bias", + ), + ] { + unsupported(ctx.create_sampler(&desc, dest), case); + } + assert_eq!(point.address_u, D3D12_TEXTURE_ADDRESS_MODE_CLAMP); + + // Root signatures. + let table = |range_type, visibility| RootParameter::DescriptorTable { + ranges: vec![DescriptorRange { + range_type, + num_descriptors: 1, + base_shader_register: 0, + register_space: 0, + offset_in_descriptors_from_table_start: 0, + }], + visibility, + }; + let srv_table = || pixel_table(DescriptorRangeType::Srv); + let sampler_table = || pixel_table(DescriptorRangeType::Sampler); + let two_ranges = RootParameter::DescriptorTable { + ranges: vec![ + DescriptorRange { + range_type: DescriptorRangeType::Srv, + num_descriptors: 1, + base_shader_register: 0, + register_space: 0, + offset_in_descriptors_from_table_start: 0, + }; + 2 + ], + visibility: ShaderVisibility::Pixel, + }; + let wide_range = RootParameter::DescriptorTable { + ranges: vec![DescriptorRange { + range_type: DescriptorRangeType::Srv, + num_descriptors: 2, + base_shader_register: 0, + register_space: 0, + offset_in_descriptors_from_table_start: 0, + }], + visibility: ShaderVisibility::Pixel, + }; + for (parameters, static_sampler_count, case) in [ + ( + vec![srv_table(), sampler_table(), srv_table()], + 0, + "three tables", + ), + (vec![srv_table(), srv_table()], 0, "two SRV tables"), + ( + vec![ + table(DescriptorRangeType::Uav, ShaderVisibility::Pixel), + sampler_table(), + ], + 0, + "UAV range", + ), + ( + vec![ + table(DescriptorRangeType::Cbv, ShaderVisibility::Pixel), + sampler_table(), + ], + 0, + "CBV range", + ), + ( + vec![ + table(DescriptorRangeType::Srv, ShaderVisibility::Vertex), + sampler_table(), + ], + 0, + "vertex-stage table", + ), + ( + vec![ + srv_table(), + table(DescriptorRangeType::Sampler, ShaderVisibility::All), + ], + 0, + "all-stage table", + ), + ( + vec![ + RootParameter::Constants32Bit { + visibility: ShaderVisibility::Pixel, + }, + sampler_table(), + ], + 0, + "root constants", + ), + ( + vec![two_ranges, sampler_table()], + 0, + "two ranges in a table", + ), + (vec![wide_range, sampler_table()], 0, "two-descriptor range"), + (vec![srv_table(), sampler_table()], 1, "static sampler"), + (vec![srv_table()], 0, "SRV table only"), + ] { + let desc = RootSignatureDesc { + parameters, + static_sampler_count, + }; + unsupported(ctx.create_root_signature(device, &desc).map(drop), case); + } + // The supported shape also works with its tables in the other order. + let swapped = RootSignatureDesc { + parameters: vec![sampler_table(), srv_table()], + static_sampler_count: 0, + }; + ctx.create_root_signature(device, &swapped).unwrap(); +} + +/// Bindings that resolve to nothing, or to the wrong kind of descriptor, +/// fail at execution before the backend is called. +#[test] +fn bad_bindings_fail_and_never_draw() { + let mut rig = rig(); + let calls = Arc::new(AtomicUsize::new(0)); + let counter = calls.clone(); + rig.ctx.set_metal_textured_backend(move |_| { + counter.fetch_add(1, Ordering::SeqCst); + Ok(vec![0; 64]) + }); + for (binding, case) in [ + ( + Binding { + srv_slot: None, + ..SLOT_0 + }, + "SRV table unset", + ), + ( + Binding { + sampler_slot: None, + ..SLOT_0 + }, + "sampler table unset", + ), + (srv(3), "empty SRV slot"), + (srv(4), "SRV slot past the heap"), + ( + Binding { + sampler_slot: Some(1), + ..SLOT_0 + }, + "empty sampler slot", + ), + ( + Binding { + heaps_bound: (true, false), + ..SLOT_0 + }, + "sampler heap not bound", + ), + ( + Binding { + heaps_bound: (false, true), + ..SLOT_0 + }, + "SRV heap not bound", + ), + ( + Binding { + stride: 16, + ..SLOT_0 + }, + "vertex stride without a texture coordinate", + ), + ] { + let result = run(&mut rig, binding); + assert_eq!(result, Err(GraphicsError::InvalidDescriptor), "{case}"); + } + + // A table whose base lies in the other heap, or in the CPU handle space. + let ctx = &mut rig.ctx; + let sampler_base = ctx + .gpu_descriptor_handle_for_heap_start(rig.sampler_heap) + .unwrap(); + let srv_base = ctx + .gpu_descriptor_handle_for_heap_start(rig.srv_heap) + .unwrap(); + let cpu_base = ctx + .cpu_descriptor_handle_for_heap_start(rig.srv_heap) + .unwrap(); + let misaligned = xenora_loader::graphics::GpuDescriptorHandle(srv_base.0 + 4); + for (srv_table, case) in [ + (sampler_base, "SRV table in the sampler heap"), + ( + xenora_loader::graphics::GpuDescriptorHandle(cpu_base.0), + "CPU handle as table base", + ), + (misaligned, "misaligned table base"), + ] { + ctx.reset_command_list(rig.list, rig.alloc).unwrap(); + ctx.cmd_set_viewport(rig.list, 4, 4).unwrap(); + ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, STRIDE) + .unwrap(); + ctx.cmd_set_descriptor_heaps(rig.list, &[rig.srv_heap, rig.sampler_heap]) + .unwrap(); + ctx.cmd_set_graphics_root_signature(rig.list, rig.root_signature) + .unwrap(); + ctx.cmd_set_graphics_root_descriptor_table(rig.list, 0, srv_table) + .unwrap(); + ctx.cmd_set_graphics_root_descriptor_table(rig.list, 1, sampler_base) + .unwrap(); + ctx.cmd_draw_instanced(rig.list, 3, 1, 0, 0).unwrap(); + ctx.close_command_list(rig.list).unwrap(); + let result = ctx.execute_command_list(rig.queue, rig.list, &rig.memory); + assert_eq!(result, Err(GraphicsError::InvalidDescriptor), "{case}"); + } + + // A textured indexed draw is outside the subset. + let ib = ctx + .create_committed_resource( + rig.device, + ResourceDesc { + dimension: ResourceDimension::Buffer, + width: 6, + height: 1, + depth_or_array_size: 1, + mip_levels: 1, + format_rgba8: false, + }, + ResourceStates::COMMON, + None, + ) + .unwrap(); + ctx.reset_command_list(rig.list, rig.alloc).unwrap(); + ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, STRIDE) + .unwrap(); + ctx.cmd_set_index_buffer(rig.list, ib, 0, 57).unwrap(); + ctx.cmd_set_graphics_root_signature(rig.list, rig.root_signature) + .unwrap(); + ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 0, 0, 0) + .unwrap(); + ctx.close_command_list(rig.list).unwrap(); + assert!(matches!( + ctx.execute_command_list(rig.queue, rig.list, &rig.memory), + Err(GraphicsError::Unsupported(_)) + )); + + // Two heaps of one type in one SetDescriptorHeaps call. + ctx.reset_command_list(rig.list, rig.alloc).unwrap(); + assert_eq!( + ctx.cmd_set_descriptor_heaps(rig.list, &[rig.srv_heap, rig.srv_heap]), + Err(GraphicsError::InvalidDescriptor) + ); + + assert_eq!(calls.load(Ordering::SeqCst), 0, "the backend never drew"); + // The same rig draws once its binding is valid. + run(&mut rig, SLOT_0).expect("valid binding draws"); + assert_eq!(calls.load(Ordering::SeqCst), 1); +} + +/// Off-centre and out-of-range coordinates: point sampling with clamping +/// gives pixel `(x, y)` texel `(CLAMPED_TEXEL[x], CLAMPED_TEXEL[y])`. The +/// draw starts at vertex record 3. +#[test] +fn point_clamp_sampling_off_centre_and_outside_unit_range() { + let mut rig = rig(); + let outcome = run( + &mut rig, + Binding { + first_vertex: 3, + ..SLOT_0 + }, + ) + .expect("textured draw"); + let a = texture_a(); + let expected: Vec = (0..16) + .flat_map(|i| { + let at = (CLAMPED_TEXEL[i / 4] * 4 + CLAMPED_TEXEL[i % 4]) * 4; + a[at..at + 4].to_vec() + }) + .collect(); + assert_eq!(outcome.pixels, expected); + assert_ne!(outcome.pixels, a); +} + +/// The root signature's parameter order decides which table is which, and +/// a nonzero sampler slot resolves. +#[test] +fn swapped_root_parameters_and_second_sampler_slot() { + let mut rig = rig(); + let outcome = run( + &mut rig, + Binding { + swapped: true, + sampler_slot: Some(2), + ..srv(1) + }, + ) + .expect("textured draw"); + assert_eq!(outcome.pixels, texture_b()); + // Binding the SRV table at the sampler's parameter fails. + let mut wrong = self::rig(); + let ctx = &mut wrong.ctx; + ctx.reset_command_list(wrong.list, wrong.alloc).unwrap(); + ctx.cmd_set_descriptor_heaps(wrong.list, &[wrong.srv_heap, wrong.sampler_heap]) + .unwrap(); + ctx.cmd_set_graphics_root_signature(wrong.list, wrong.swapped_root_signature) + .unwrap(); + let base = ctx + .gpu_descriptor_handle_for_heap_start(wrong.srv_heap) + .unwrap(); + ctx.cmd_set_graphics_root_descriptor_table(wrong.list, 0, base) + .unwrap(); + ctx.close_command_list(wrong.list).unwrap(); + assert_eq!( + ctx.execute_command_list(wrong.queue, wrong.list, &wrong.memory), + Err(GraphicsError::InvalidDescriptor) + ); +} + +#[derive(Clone)] +enum Step { + Heaps(Vec), + Root(GraphicsHandle), + Tables, + Draw, +} + +fn record(rig: &mut Rig, steps: &[Step]) -> Result { + let ctx = &mut rig.ctx; + ctx.reset_command_list(rig.list, rig.alloc)?; + ctx.cmd_set_viewport(rig.list, 4, 4)?; + ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, STRIDE)?; + for step in steps { + match step { + Step::Heaps(heaps) => ctx.cmd_set_descriptor_heaps(rig.list, heaps)?, + Step::Root(root) => ctx.cmd_set_graphics_root_signature(rig.list, *root)?, + Step::Tables => { + let srv = ctx.gpu_descriptor_handle_for_heap_start(rig.srv_heap)?; + let sampler = ctx.gpu_descriptor_handle_for_heap_start(rig.sampler_heap)?; + ctx.cmd_set_graphics_root_descriptor_table(rig.list, 0, srv)?; + ctx.cmd_set_graphics_root_descriptor_table(rig.list, 1, sampler)?; + } + Step::Draw => ctx.cmd_draw_instanced(rig.list, 3, 1, 0, 0)?, + } + } + ctx.close_command_list(rig.list)?; + ctx.execute_command_list(rig.queue, rig.list, &rig.memory) +} + +/// Changing heaps or the root signature invalidates bound tables; setting +/// the same heaps or the same root signature again keeps them. +#[test] +fn heap_and_root_signature_changes_invalidate_tables() { + let mut rig = rig(); + let other_srv_heap = rig + .ctx + .create_descriptor_heap(rig.device, CBV_SRV_UAV, 4, true) + .unwrap(); + let same_layout = rig + .ctx + .create_root_signature(rig.device, &root_signature_desc()) + .unwrap(); + let heaps = Step::Heaps(vec![rig.srv_heap, rig.sampler_heap]); + let other = Step::Heaps(vec![other_srv_heap, rig.sampler_heap]); + let root = Step::Root(rig.root_signature); + let bound = [heaps.clone(), root.clone(), Step::Tables]; + for (extra, expected, case) in [ + (vec![], Ok(()), "plain"), + (vec![heaps.clone()], Ok(()), "same heaps again"), + (vec![root.clone()], Ok(()), "same root signature again"), + ( + vec![other, heaps.clone()], + Err(GraphicsError::InvalidDescriptor), + "heaps changed and restored", + ), + ( + vec![Step::Root(same_layout)], + Err(GraphicsError::InvalidDescriptor), + "another root signature with the same layout", + ), + ] { + let mut steps = bound.to_vec(); + steps.extend(extra); + steps.push(Step::Draw); + let result = record(&mut rig, &steps); + match expected { + Ok(()) => assert_eq!(result.expect(case).pixels, texture_a(), "{case}"), + Err(error) => assert_eq!(result, Err(error), "{case}"), + } + } +} + +/// Zero vertices or instances draw nothing; any other shape than one +/// instance of three vertices is unsupported. Neither reaches the backend. +#[test] +fn textured_draw_shapes() { + let mut rig = rig(); + let calls = Arc::new(AtomicUsize::new(0)); + let counter = calls.clone(); + rig.ctx.set_metal_textured_backend(move |_| { + counter.fetch_add(1, Ordering::SeqCst); + Ok(vec![0; 64]) + }); + for draw in [(3, 0, 0), (0, 1, 0)] { + let outcome = run(&mut rig, Binding { draw, ..SLOT_0 }).unwrap(); + assert_eq!(outcome.draw_count, 0, "{draw:?}"); + } + for draw in [(6, 1, 0), (3, 2, 0), (3, 1, 1)] { + let result = run(&mut rig, Binding { draw, ..SLOT_0 }); + assert!( + matches!(result, Err(GraphicsError::Unsupported(_))), + "{draw:?}: {result:?}" + ); + } + assert_eq!(calls.load(Ordering::SeqCst), 0); +} + +/// Vertex and texture reads stay inside their resources even when the +/// guest backing maps more bytes. +#[test] +fn reads_stay_inside_resources() { + let mut rig = rig(); + rig.vb = rig + .ctx + .create_committed_resource( + rig.device, + ResourceDesc { + dimension: ResourceDimension::Buffer, + width: 2 * STRIDE as u64, + height: 1, + depth_or_array_size: 1, + mip_levels: 1, + format_rgba8: false, + }, + ResourceStates::VERTEX_AND_CONSTANT_BUFFER, + Some(VB_ADDR), + ) + .unwrap(); + assert_eq!(run(&mut rig, SLOT_0), Err(GraphicsError::IndexOutOfRange)); +} + +/// Array textures cannot be viewed, and a texture in a state that excludes +/// pixel-shader reads cannot be sampled. +#[test] +fn texture_shape_and_state_are_checked() { + let mut rig = rig(); + let ctx = &mut rig.ctx; + let dest = ctx + .cpu_descriptor_handle_for_heap_start(rig.srv_heap) + .unwrap() + .offset(3) + .unwrap(); + let array = ctx + .create_committed_resource( + rig.device, + ResourceDesc { + dimension: ResourceDimension::Texture2D, + width: 4, + height: 4, + depth_or_array_size: 2, + mip_levels: 1, + format_rgba8: true, + }, + ResourceStates::COMMON, + None, + ) + .unwrap(); + assert!(matches!( + ctx.create_shader_resource_view(array, &srv_desc(DXGI_FORMAT_R8G8B8A8_UNORM), dest), + Err(GraphicsError::Unsupported(_)) + )); + for (state, ok) in [ + (ResourceStates::COPY_DEST, false), + ( + ResourceStates(ResourceStates::COPY_DEST.0 | ResourceStates::PIXEL_SHADER_RESOURCE.0), + false, + ), + ( + ResourceStates( + ResourceStates::NON_PIXEL_SHADER_RESOURCE.0 + | ResourceStates::PIXEL_SHADER_RESOURCE.0, + ), + true, + ), + (ResourceStates::RENDER_TARGET, false), + (ResourceStates::PIXEL_SHADER_RESOURCE, true), + ] { + let ctx = &mut rig.ctx; + let texture = ctx + .create_committed_texture2d( + rig.device, + 4, + 4, + DXGI_FORMAT_R8G8B8A8_UNORM, + state, + Some(TEX_ADDR), + ) + .unwrap(); + ctx.create_shader_resource_view(texture, &srv_desc(DXGI_FORMAT_R8G8B8A8_UNORM), dest) + .unwrap(); + let result = run(&mut rig, srv(3)); + if ok { + assert_eq!(result.unwrap().pixels, texture_a(), "{state:?}"); + } else { + assert_eq!( + result, + Err(GraphicsError::ResourceLifetimeViolation), + "{state:?}" + ); + } + } +} + +/// The public software reference rejects viewports it cannot allocate. +#[test] +fn software_reference_rejects_oversized_viewports() { + let texels = texture_a(); + for viewport in [(usize::MAX, 2), (65, 64), (0, 4)] { + let draw = xenora_loader::graphics::TexturedDraw { + positions: VERTICES.map(|v| [v[0], v[1], v[2], v[3]]), + texcoords: VERTICES.map(|v| [v[4], v[5], v[6], v[7]]), + viewport, + clear_color: [0, 0, 0, 255], + texture: xenora_loader::graphics::TextureView { + format: TextureFormat::Rgba8Unorm, + width: 4, + height: 4, + bytes: &texels, + }, + sampler: SamplerDesc::point_clamp(), + }; + assert_eq!( + GraphicsContext::execute_software_reference_textured_draw(&draw), + Err(GraphicsError::InvalidViewport), + "{viewport:?}" + ); + } +} + +/// Handle arithmetic cannot carry into the heap ID. +#[test] +fn descriptor_handle_offsets_stay_in_their_heap() { + let rig = rig(); + let start = rig + .ctx + .cpu_descriptor_handle_for_heap_start(rig.srv_heap) + .unwrap(); + assert_eq!(start.offset(1 << 27), None); + let last = start.offset((1 << 27) - 1).unwrap(); + assert_eq!(last.0 >> 32, start.0 >> 32); + let gpu = rig + .ctx + .gpu_descriptor_handle_for_heap_start(rig.srv_heap) + .unwrap(); + assert_eq!(gpu.offset(1 << 27), None); +} + +#[test] +fn textured_draw_requires_native_backend_when_configured() { + let mut rig = rig(); + rig.ctx.set_require_metal_without_backend(); + assert_eq!( + run(&mut rig, SLOT_0), + Err(GraphicsError::NativeMetalRequired) + ); +} + +/// The backend receives the bound texture's level, the sampler and the +/// guest's per-vertex positions and texture coordinates. +#[test] +fn backend_receives_the_bound_texture_and_vertices() { + let mut rig = rig(); + let seen = Arc::new(std::sync::Mutex::new(None)); + let sink = seen.clone(); + rig.ctx.set_metal_textured_backend(move |draw| { + *sink.lock().unwrap() = Some(( + draw.texture.format, + (draw.texture.width, draw.texture.height), + draw.texture.bytes.to_vec(), + draw.positions, + draw.texcoords, + draw.sampler, + )); + GraphicsContext::execute_software_reference_textured_draw(draw) + }); + let outcome = run(&mut rig, srv(2)).unwrap(); + assert_eq!(outcome.backend, GraphicsBackendId::MetalNative); + let (format, extent, bytes, positions, texcoords, sampler) = + seen.lock().unwrap().take().unwrap(); + assert_eq!(format, TextureFormat::Bc1Unorm); + assert_eq!(extent, (8, 8)); + assert_eq!(bytes, BC1_BLOCKS.as_flattened()); + assert_eq!(positions, VERTICES.map(|v| [v[0], v[1], v[2], v[3]])); + assert_eq!(texcoords, VERTICES.map(|v| [v[4], v[5], v[6], v[7]])); + assert_eq!(sampler, SamplerDesc::point_clamp()); +} + +/// The translated RDNA2 `image_sample_lz` pixel stage samples the bound +/// texture on Metal. Native, software and hand-derived images agree. +#[test] +#[cfg_attr( + not(feature = "gpu-tests"), + ignore = "needs native Metal device; run scripts/test-gpu.sh" +)] +fn native_metal_textured_draw_matches_references() { + use xenora_metal::NativeCompute; + use xenora_metal::sampler::MetalSampler; + use xenora_metal::texture_pipeline::{MetalRgba8Texture, Rgba8MipLevel, Rgba8TextureDesc}; + use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; + use xenora_texture::{Bc1Upload, Bc1UploadDesc}; + + let msl = compile_graphics( + Architecture::Gfx1030, + include_bytes!("../../../fixtures/rdna2/x9-varying-vs.bin"), + &image_sample_lz_ps(), + ) + .expect("compile translated image_sample_lz shader") + .msl; + let gpu = Arc::new(NativeCompute::new().expect("native Metal GPU device")); + let entries = [VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT]; + let backend = gpu.clone(); + let metal_error = |e: xenora_metal::MetalError| GraphicsError::BackendError(format!("{e:?}")); + let mut rig = rig(); + rig.ctx.set_metal_textured_backend(move |draw| { + assert_eq!(draw.sampler, SamplerDesc::point_clamp()); + let sampler = MetalSampler::new( + backend.device(), + xenora_texture::SamplerDesc::nearest_clamp(), + ) + .map_err(metal_error)?; + let (width, height) = (draw.texture.width as usize, draw.texture.height as usize); + let extent = [draw.viewport.0, draw.viewport.1]; + match draw.texture.format { + TextureFormat::Rgba8Unorm => { + let desc = Rgba8TextureDesc::new(width, height, 1).map_err(metal_error)?; + let level = Rgba8MipLevel::new_packed(0, width, height, draw.texture.bytes); + let texture = MetalRgba8Texture::upload(backend.device(), desc, &[level]) + .map_err(metal_error)?; + backend.render_rgba8_sampled( + &msl, + entries, + &draw.positions, + &draw.texcoords, + extent, + draw.clear_color, + Some((&texture, &sampler)), + ) + } + TextureFormat::Bc1Unorm => { + let row_pitch = width.div_ceil(4) * 8; + let desc = Bc1UploadDesc { + width, + height, + mips: 1, + layers: 1, + format: 1, + usage: 1, + row_pitch, + slice_pitch: row_pitch * height.div_ceil(4), + }; + let upload = Bc1Upload::new(draw.texture.bytes, desc) + .map_err(|e| GraphicsError::BackendError(format!("{e:?}")))?; + backend.render_rgba8_sampled_bc1( + &msl, + entries, + &draw.positions, + &draw.texcoords, + extent, + draw.clear_color, + &upload, + &sampler, + ) + } + } + .map_err(metal_error) + }); + + let mut software = self::rig(); + for (slot, expected, name) in [ + (0, texture_a(), "RGBA8 texture A"), + (1, texture_b(), "RGBA8 texture B"), + (2, bc1_expected(), "BC1 texture"), + ] { + let native = run(&mut rig, srv(slot)).expect("native textured draw"); + assert_eq!(native.backend, GraphicsBackendId::MetalNative); + assert_eq!(native.pixels, expected, "{name}: native vs hand-derived"); + let reference = run(&mut software, srv(slot)).expect("software textured draw"); + assert_eq!( + native.pixels, reference.pixels, + "{name}: native vs software" + ); + } + // Off-centre and out-of-range coordinates clamp on Metal as in software. + let clamped = Binding { + first_vertex: 3, + ..SLOT_0 + }; + let native = run(&mut rig, clamped).expect("native clamped draw"); + let reference = run(&mut software, clamped).expect("software clamped draw"); + assert_eq!( + native.pixels, reference.pixels, + "clamped: native vs software" + ); + assert_ne!(native.pixels, texture_a()); + println!( + "device={} guest-bound textures: RGBA8 slots 0 and 1 (16 of 16 pixels) and BC1 slot 2 (64 of 64) match", + gpu.device_name() + ); +} + +/// Translated gfx1030 pixel stage: interpolate parameter 0's `xy`, then +/// `image_sample_lz v[4:7], v[2:3], s[0:7], s[8:11] dmask:0xf dim:2D` and +/// export the sample. Same bytes as the Metal crate's translated-render test. +fn image_sample_lz_ps() -> Vec { + [ + &[0x00, 0x00, 0x08, 0xc8][..], + &[0x01, 0x00, 0x09, 0xc8], + &[0x00, 0x01, 0x0c, 0xc8], + &[0x01, 0x01, 0x0d, 0xc8], + &[0x08, 0x0f, 0x9c, 0xf0, 0x02, 0x04, 0x40, 0x00], + &[0x0f, 0x18, 0x00, 0xf8, 0x04, 0x05, 0x06, 0x07], + &[0x00, 0x00, 0x81, 0xbf], + ] + .concat() +} diff --git a/crates/metal/src/render.rs b/crates/metal/src/render.rs index f407187..91f39ec 100644 --- a/crates/metal/src/render.rs +++ b/crates/metal/src/render.rs @@ -101,7 +101,43 @@ impl NativeCompute { colors, [width, height], clear, - sampled, + sampled.map(|(texture, sampler)| (texture.raw(), sampler)), + ) + .map(|(pixels, _)| pixels) + } + + /// As [`Self::render_rgba8_sampled`], with level 0 of a BC1 upload bound + /// natively as a `BC1_RGBA` texture to fragment texture slot 0 and the + /// sampler to fragment sampler slot 0. + /// + /// # Errors + /// + /// As [`Self::render_rgba8_sampled`], and for an invalid BC1 level. + #[allow(clippy::too_many_arguments)] + pub fn render_rgba8_sampled_bc1( + &self, + source: &str, + entries: [&str; 2], + vertices: &[[f32; 4]; 3], + colors: &[[f32; 4]; 3], + extent: [usize; 2], + clear: [u8; 4], + texture: &Bc1Upload<'_>, + sampler: &crate::sampler::MetalSampler, + ) -> Result, MetalError> { + let level = texture + .subresource(0, 0) + .map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?; + self.validate_bc_extent(level.width, level.height, "BC1")?; + let bc1 = self.new_bc1_texture(&level)?; + self.render_rgba8_internal( + source, + entries, + vertices, + colors, + extent, + clear, + Some((&bc1, sampler)), ) .map(|(pixels, _)| pixels) } @@ -116,7 +152,7 @@ impl NativeCompute { [width, height]: [usize; 2], clear: [u8; 4], sampled: Option<( - &crate::texture_pipeline::MetalRgba8Texture, + &ProtocolObject, &crate::sampler::MetalSampler, )>, ) -> Result<(Vec, Option), MetalError> { @@ -228,7 +264,7 @@ impl NativeCompute { encoder.setVertexBuffer_offset_atIndex(Some(&positions), 0, 0); encoder.setVertexBuffer_offset_atIndex(Some(&colors), 0, 1); if let Some((tex, samp)) = sampled { - encoder.setFragmentTexture_atIndex(Some(tex.raw()), 0); + encoder.setFragmentTexture_atIndex(Some(tex), 0); encoder.setFragmentSamplerState_atIndex(Some(samp.raw()), 0); } encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::Triangle, 0, 3); diff --git a/crates/metal/tests/native/translated_bc1.rs b/crates/metal/tests/native/translated_bc1.rs new file mode 100644 index 0000000..387e4d4 --- /dev/null +++ b/crates/metal/tests/native/translated_bc1.rs @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; +use xenora_texture::{Bc1Upload, Bc1UploadDesc, SamplerDesc, decode_bc1}; + +use super::{context, native}; + +/// The translated `image_sample_lz` pixel stage samples a native BC1 +/// texture bound by `render_rgba8_sampled_bc1`. Each of the 8×8 texture's +/// four blocks selects only its two endpoints, which expand exactly to 0 or +/// 255, so the image is known without a decoder: selector 1 (the second +/// endpoint) where `x == 0 || y == 3` within a block, else selector 0. +#[test] +fn translated_image_sample_lz_reads_bound_bc1_texture() { + let blocks: [[u8; 8]; 4] = [ + [0x00, 0xF8, 0x1F, 0x00, 0x01, 0x01, 0x01, 0x55], // red, blue + [0xE0, 0x07, 0x00, 0x00, 0x01, 0x01, 0x01, 0x55], // green, black + [0xFF, 0xFF, 0x1F, 0xF8, 0x01, 0x01, 0x01, 0x55], // white, magenta + [0xE0, 0xFF, 0xFF, 0x07, 0x01, 0x01, 0x01, 0x55], // yellow, cyan + ]; + let endpoints: [[[u8; 4]; 2]; 4] = [ + [[255, 0, 0, 255], [0, 0, 255, 255]], + [[0, 255, 0, 255], [0, 0, 0, 255]], + [[255, 255, 255, 255], [255, 0, 255, 255]], + [[255, 255, 0, 255], [0, 255, 255, 255]], + ]; + let mut expected = Vec::new(); + for y in 0..8 { + for x in 0..8 { + let selector = usize::from(x % 4 == 0 || y % 4 == 3); + expected.extend(endpoints[(y / 4) * 2 + x / 4][selector]); + } + } + for (index, block) in blocks.into_iter().enumerate() { + let (bx, by) = (index % 2 * 4, index / 2 * 4); + for (i, texel) in decode_bc1(block).iter().enumerate() { + let at = ((by + i / 4) * 8 + bx + i % 4) * 4; + assert_eq!(texel, &expected[at..at + 4], "decoder, block {index}"); + } + } + + let ps: Vec = [ + &[0x00, 0x00, 0x08, 0xc8][..], // v_interp_p1_f32 v2, v0, attr0.x + &[0x01, 0x00, 0x09, 0xc8], // v_interp_p2_f32 v2, v1, attr0.x + &[0x00, 0x01, 0x0c, 0xc8], // v_interp_p1_f32 v3, v0, attr0.y + &[0x01, 0x01, 0x0d, 0xc8], // v_interp_p2_f32 v3, v1, attr0.y + &[0x08, 0x0f, 0x9c, 0xf0, 0x02, 0x04, 0x40, 0x00], // image_sample_lz + &[0x0f, 0x18, 0x00, 0xf8, 0x04, 0x05, 0x06, 0x07], // exp mrt0 + &[0x00, 0x00, 0x81, 0xbf], // s_endpgm + ] + .concat(); + let compiled = compile_graphics( + Architecture::Gfx1030, + include_bytes!("../../../../fixtures/rdna2/x9-varying-vs.bin"), + &ps, + ) + .expect("compile translated image_sample_lz shader"); + let gpu = context(); + let upload = Bc1Upload::new( + blocks.as_flattened(), + Bc1UploadDesc { + width: 8, + height: 8, + mips: 1, + layers: 1, + format: 1, + usage: 1, + row_pitch: 16, + slice_pitch: 32, + }, + ) + .expect("valid BC1 upload"); + let sampler = native(xenora_metal::sampler::MetalSampler::new( + gpu.device(), + SamplerDesc::nearest_clamp(), + )); + // Pixel (x, y) of the 8×8 target samples uv ((x + 0.5) / 8, (y + 0.5) / 8). + let positions = [ + [-1.0, -1.0, 0.5, 1.0], + [3.0, -1.0, 0.5, 1.0], + [-1.0, 3.0, 0.5, 1.0], + ]; + let uvs = [ + [0.0, 1.0, 0.0, 1.0], + [2.0, 1.0, 0.0, 1.0], + [0.0, -1.0, 0.0, 1.0], + ]; + let pixels = native(gpu.render_rgba8_sampled_bc1( + &compiled.msl, + [VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT], + &positions, + &uvs, + [8, 8], + [19, 43, 93, 251], + &upload, + &sampler, + )); + assert_eq!(pixels, expected); +} diff --git a/crates/metal/tests/native_compute.rs b/crates/metal/tests/native_compute.rs index 933cb97..0cdce52 100644 --- a/crates/metal/tests/native_compute.rs +++ b/crates/metal/tests/native_compute.rs @@ -26,6 +26,8 @@ mod texture_bc_alpha; mod texture_bc_channel; #[path = "native/texture_sampling.rs"] mod texture_sampling; +#[path = "native/translated_bc1.rs"] +mod translated_bc1; #[path = "native/translated_render.rs"] mod translated_render; diff --git a/docs/interfaces.md b/docs/interfaces.md index fe6e727..a03ad56 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -498,3 +498,47 @@ compare function. Colour and the stored depth are both read back. These passes are checked on the GPU with Metal validation against expectations derived independently from the public semantics; synthetic fixtures only. + +### Guest texture binding (descriptor tables) + +`GraphicsContext` lets a guest command list sample one texture in the pixel +stage through a D3D12-shaped binding. A draw samples only if a root signature +is bound. Draws without one keep the flat-colour path. The supported subset +is fixed. Anything outside it fails with `GraphicsError::Unsupported` when the +object is created, or with an error at execution. A rejected draw never +reaches the backend. Draws recorded before it in the same list have already +run. + +| Object | Supported | +| --- | --- | +| `create_descriptor_heap` | Shader-visible `CBV_SRV_UAV` (0) or `SAMPLER` (1) heaps of 1–64 descriptors. RTV, DSV and CPU-only heaps are unsupported. | +| `create_committed_texture2d` | One level of `R8G8B8A8_UNORM` (28) or `BC1_UNORM` (71), 1–64 texels per side. BC1 sizes must be multiples of four. Rows are linear: 4 bytes per texel, or 8 bytes per 4×4 block. Xbox tiling is not handled. | +| `create_shader_resource_view` | A `Texture2D` view of mip 0 of a single-level, single-slice 2D texture, in the resource's own format. | +| `create_sampler` | Point filtering (`MIN_MAG_MIP_POINT`), clamp addressing on U, V and W, no LOD bias and a minimum LOD of 0. | +| `create_root_signature` | Exactly two pixel-visibility descriptor tables, in either order: one with a single SRV range for `t0`, and one with a single sampler range for `s0` (one descriptor each, space 0). Root constants, root descriptors, CBV and UAV ranges, extra tables or ranges and static samplers are unsupported. | +| `cmd_set_descriptor_heaps` | At most one heap of each type. | +| `cmd_set_graphics_root_descriptor_table` | The base must be a GPU handle to a slot of the bound heap of the table's type. The slot must hold a descriptor when a draw reads it. Changing the heaps or binding a different root signature clears every table. Setting the same heaps or the same root signature again keeps them. | + +Descriptor handles follow D3D12 pointer arithmetic: the heap start plus +`index × GetDescriptorHandleIncrementSize` (32 here; guests must query the +value). `offset` returns `None` rather than carry into the next heap. CPU and +GPU handles are separate spaces. A textured draw is a `DrawInstanced` of +one instance of three vertices with start instance 0, starting at any vertex. Zero vertices or +instances draw nothing. The sampled texture must be in `COMMON` or a read-only state that includes +`PIXEL_SHADER_RESOURCE`. The software reference draws at most 4096 pixels. Each vertex record holds a float4 position +at byte 0 and a float4 texture coordinate at byte 16, with a stride of at +least 32. Textured indexed draws are unsupported. + +The native backend receives a `TexturedDraw` with the bound level and must +bind it to fragment texture 0 and sampler 0, which are the `tex0` and `samp0` arguments of +the translated `image_sample_lz` pixel stage. `NativeCompute::render_rgba8_sampled_bc1` +binds a BC1 level natively for that purpose. The software reference has no +clipping or depth test. A pixel is covered when its centre lies inside or on +an edge of the triangle. The texture coordinate is interpolated affinely, so +`w = 1` is required, and point sampled with +`min(floor(clamp(u, 0, 1) × width), width − 1)`. It decodes BC1 with the +spec-exact `xenora_texture::decode_bc1`. Apple's hardware rounds BC1's two +interpolated palette entries differently (171/84 against 170/85, measured +on an M5 Pro), so the tests use endpoint colours only. Pipeline +state objects do not exist yet, so the backend, not the guest, chooses the +pixel shader. These entry points are not yet wired to guest imports. diff --git a/scripts/test-gpu.sh b/scripts/test-gpu.sh index 9627db8..d7be36b 100755 --- a/scripts/test-gpu.sh +++ b/scripts/test-gpu.sh @@ -25,6 +25,11 @@ cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 -- \ --nocapture --test-threads=1 +# Guest draws sample textures bound through descriptor tables (#303). +cargo test --locked -p xenora-loader --features gpu-tests --test graphics_textures --no-run +timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_textures -- \ + --nocapture --test-threads=1 + # The native app interface runs the trusted fixture's guest draw on Metal. cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame --no-run timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame -- \ From 0fdb9958922237a8d6ca816f04c08aefa4b86f7b Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:38:44 -0600 Subject: [PATCH 2/2] isa, decoder, shader, ref: VOP3A encodings of eleven VOP2 integer forms and the sixteen integer compares (#215) (#311) * isa, decoder: VOP3 encodings of the eleven registry VOP2 integer forms (#215) Eleven [[encoding_variant]] entries re-encode the VOP2 integer forms as VOP3A (_e64) under operand rule vop3_vgpr2: two VGPR sources, no modifiers, SRC2 the unused inline zero. Opcodes from the pinned XML, checked against llvm-mc. Decoder known words and per-bit rejections. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> * fixtures, decoder, shader: LLVM-assembled fixture and goldens for the eleven VOP3 VOP2 variants (#215) Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> * ref, validation: independent guide-derived oracle for VOP3 integer VOP2 forms and Wave32 VOP3 compares (#215) crates/ref and tests/validation/independent_ref.rs decode and run the eleven VOP3A (_e64) integer VOP2 forms and the sixteen V_CMP_*_{I32,U32}_e64 compares writing a 32-bit lane mask to one SGPR (s0-s105) or vcc_lo, derived from the AMD RDNA 2 guide only. New suites vop3_integer.rs and vop3_compare.rs, with ignored native Metal parts. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> * isa, decoder, shader: add VOP3A encodings for the sixteen integer compares (#215) Sixteen gfx1030 Wave32 integer compares gain their VOP3A (_e64) encoding as registry variants, with an explicit SGPR mask destination (guide 3.9, 13.3.3; pinned XML OPR_SREG), VCCZ branching through vcc_lo and translation errors for reads of runtime-only SGPR results. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> * fixtures, shader, validation: VOP3A compare fixture and native Metal runs (#215) A fixture with all sixteen VOP3A integer compares (vcc_lo destination, runtime s_cbranch_vccz) ties the new variants to fixture coverage, with IR and MSL goldens. The VOP3 integer and compare Metal oracles now run in the GPU gate: the translator they waited for is in this branch. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> * changelog: VOP3A integer and compare encodings (#215) Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> * shader, fixtures, docs: e64 compare names in the IR; status rows for the 27 VOP3A forms (#215) The IR names a VOP3A compare by its _e64 mnemonic and prints its SGPR destination; VOPC output is unchanged. The compare fixture now uses a mid-range second source (so swapped unsigned opcodes change the golden) and one plain SGPR destination. docs/status.toml and the rendered instruction table list the 27 new forms. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> * docs: use a recognized lowering phrase for the VOP3A integer rows (#215) Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> * isa: VOP3A variants exist only for the 32-bit VOPC compares (#215) After main gained the 16-bit compares (#327), the dispatch test expected a VOP3A encoding for every non-64-bit compare. Only the 32-bit ones have one. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --------- Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/decoder/src/lib.rs | 54 +- crates/decoder/tests/gfx1030.rs | 340 ++++++- crates/isa/generate_semantics.py | 83 +- crates/isa/semantics/rdna2.toml | 1 + crates/isa/semantics/rdna2/vop3.toml | 323 +++++++ crates/isa/src/lib.rs | 15 +- crates/isa/src/semantics.rs | 11 +- crates/isa/src/semantics_gen.rs | 844 +++++++++++++++++- crates/isa/tests/semantics.rs | 43 +- crates/ref/src/lib.rs | 86 +- crates/shader/src/lib.rs | 150 +++- crates/shader/tests/compiler.rs | 132 +++ docs/assets/xenora-progress.svg | 8 +- docs/shaders/instruction-coverage.md | 27 + docs/shaders/semantic-coverage.md | 5 +- docs/shaders/semantic-registry.md | 30 +- docs/shaders/vector-compare.md | 42 +- docs/status.toml | 324 +++++++ fixtures/golden/vop3-compare.ir | 59 ++ fixtures/golden/vop3-compare.metal | 188 ++++ fixtures/golden/vop3-integer.ir | 23 + fixtures/golden/vop3-integer.metal | 30 + fixtures/rdna2/vop3-compare.bin | Bin 0 -> 392 bytes fixtures/rdna2/vop3-compare.s | 85 ++ fixtures/rdna2/vop3-integer.bin | Bin 0 -> 156 bytes fixtures/rdna2/vop3-integer.s | 31 + scripts/assemble-fixture.sh | 2 +- .../test_generate_semantics.py | 41 +- tests/validation/independent_ref.rs | 68 +- tests/validation/tests/vop3_compare.rs | 302 +++++++ tests/validation/tests/vop3_integer.rs | 246 +++++ 32 files changed, 3418 insertions(+), 176 deletions(-) create mode 100644 fixtures/golden/vop3-compare.ir create mode 100644 fixtures/golden/vop3-compare.metal create mode 100644 fixtures/golden/vop3-integer.ir create mode 100644 fixtures/golden/vop3-integer.metal create mode 100644 fixtures/rdna2/vop3-compare.bin create mode 100644 fixtures/rdna2/vop3-compare.s create mode 100644 fixtures/rdna2/vop3-integer.bin create mode 100644 fixtures/rdna2/vop3-integer.s create mode 100644 tests/validation/tests/vop3_compare.rs create mode 100644 tests/validation/tests/vop3_integer.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 82a17cc..e686c9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ remains unsupported. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. ### Added +- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215. - Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted. - Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215. - Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending. diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index c273111..2840a01 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -5,8 +5,8 @@ use std::fmt; pub use xenora_isa::{ Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, - SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource, VectorSwapOp, - VectorUnaryOp, + SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op, + VectorSource, VectorSwapOp, VectorUnaryOp, }; use xenora_isa::{ BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_WAITCNT_VSCNT, V_ADD_F32, @@ -330,6 +330,26 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco if let Some(op) = VectorCompareOp::from_word(first) { return vector_compare(op, first, bytes); } + if let Some(op) = VectorCompareVop3Op::from_word(first) { + let second = word(bytes, 8)?; + let sdst = first as u8; + if sdst > VCC_LO { + return Err(unsupported( + op.assembly_name(), + "expected a destination of s0-s105 or vcc_lo", + )); + } + let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?; + return Ok(( + Instruction::VectorCompareVop3 { + op, + sdst, + src0, + src1, + }, + 8, + )); + } if let Some(op) = VectorAluVop3Op::from_word(first) { let second = word(bytes, 8)?; return Ok((vop3_vgpr2(op, first, second)?, 8)); @@ -723,29 +743,37 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi Ok((Instruction::MoveB32 { dst, src }, len)) } -/// Operand rule `vop3_vgpr2`: VDST in bits 0-7 of the first word, SRC0 and SRC1 -/// in bits 0-8 and 9-17 of the second (RDNA 2 ISA section 13.3.4, VOP3A). Both sources -/// are VGPRs, ABS, OP_SEL, CLAMP, OMOD and NEG are clear, and the unused SRC2 is -/// the gfx1030 assembler's inline-zero operand encoding. fn vop3_vgpr2( op: VectorAluVop3Op, first: u32, second: u32, ) -> Result { + let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?; + Ok(Instruction::VectorAluVop3 { + op, + dst: first as u8, + src0, + src1, + }) +} + +/// Common VOP3A source and modifier checks (RDNA 2 ISA section 13.3.4). +/// SRC0 and SRC1 are VGPRs, the unused SRC2 is inline zero, and ABS, OP_SEL, +/// CLAMP, OMOD and NEG are clear. +fn vop3_vgpr2_sources( + mnemonic: &'static str, + first: u32, + second: u32, +) -> Result<(u8, u8), DecodeErrorKind> { let src0 = second & 0x1ff; let src1 = (second >> 9) & 0x1ff; if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 { return Err(unsupported( - op.assembly_name(), + mnemonic, "expected two VGPR sources and no modifiers", )); } - Ok(Instruction::VectorAluVop3 { - op, - dst: first as u8, - src0: src0 as u8, - src1: src1 as u8, - }) + Ok((src0 as u8, src1 as u8)) } fn scalar_form( diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index 4adb463..bdcfc4e 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -5,7 +5,7 @@ use std::process::{Command, Stdio}; use xenora_decoder::{ Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, ScalarAluOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, - VectorSource, VectorUnaryOp, decode, decode_at, + VectorCompareOp, VectorCompareVop3Op, VectorSource, VectorUnaryOp, decode, decode_at, }; use xenora_isa::semantics::Signedness; use xenora_ref::{ @@ -71,6 +71,127 @@ fn decodes_each_fixture_instruction_with_offset_and_length() { assert_eq!(instructions, wanted); } +#[test] +fn decodes_wave32_vop3_compares_from_llvm_words() { + use VectorCompareVop3Op::*; + + // llvm-mc -triple=amdgcn -mcpu=gfx1030 -mattr=+wavefrontsize32 -show-encoding + let cases: [(u32, VectorCompareVop3Op, u8); 19] = [ + // v_cmp_lt_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x81,0xd4,0x01,0x05,0x02,0x02] + (0xd481_0004, CmpLtI32, 4), + // v_cmp_eq_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x82,0xd4,0x01,0x05,0x02,0x02] + (0xd482_0004, CmpEqI32, 4), + // v_cmp_le_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x83,0xd4,0x01,0x05,0x02,0x02] + (0xd483_0004, CmpLeI32, 4), + // v_cmp_gt_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x84,0xd4,0x01,0x05,0x02,0x02] + (0xd484_0004, CmpGtI32, 4), + // v_cmp_ne_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x85,0xd4,0x01,0x05,0x02,0x02] + (0xd485_0004, CmpNeI32, 4), + // v_cmp_ge_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x86,0xd4,0x01,0x05,0x02,0x02] + (0xd486_0004, CmpGeI32, 4), + // v_cmp_lt_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc1,0xd4,0x01,0x05,0x02,0x02] + (0xd4c1_0004, CmpLtU32, 4), + // v_cmp_eq_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02] + (0xd4c2_0004, CmpEqU32, 4), + // v_cmp_le_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc3,0xd4,0x01,0x05,0x02,0x02] + (0xd4c3_0004, CmpLeU32, 4), + // v_cmp_gt_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc4,0xd4,0x01,0x05,0x02,0x02] + (0xd4c4_0004, CmpGtU32, 4), + // v_cmp_ne_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc5,0xd4,0x01,0x05,0x02,0x02] + (0xd4c5_0004, CmpNeU32, 4), + // v_cmp_ge_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc6,0xd4,0x01,0x05,0x02,0x02] + (0xd4c6_0004, CmpGeU32, 4), + // v_cmp_f_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x80,0xd4,0x01,0x05,0x02,0x02] + (0xd480_0004, CmpFI32, 4), + // v_cmp_t_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x87,0xd4,0x01,0x05,0x02,0x02] + (0xd487_0004, CmpTI32, 4), + // v_cmp_f_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc0,0xd4,0x01,0x05,0x02,0x02] + (0xd4c0_0004, CmpFU32, 4), + // v_cmp_t_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc7,0xd4,0x01,0x05,0x02,0x02] + (0xd4c7_0004, CmpTU32, 4), + // v_cmp_eq_u32_e64 s0, v1, v2 ; encoding: [0x00,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02] + (0xd4c2_0000, CmpEqU32, 0), + // v_cmp_eq_u32_e64 s105, v1, v2 ; encoding: [0x69,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02] + (0xd4c2_0069, CmpEqU32, 105), + // v_cmp_eq_u32_e64 vcc_lo, v1, v2 ; encoding: [0x6a,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02] + (0xd4c2_006a, CmpEqU32, 106), + ]; + for (first, op, sdst) in cases { + let code: Vec<_> = [first, 0x0202_0501] + .into_iter() + .flat_map(u32::to_le_bytes) + .collect(); + let decoded = decode(Architecture::Gfx1030, &code).unwrap(); + let dst = if sdst == 106 { + "vcc_lo".to_owned() + } else { + format!("s{sdst}") + }; + assert_eq!( + decoded, + [DecodedInstruction { + offset: 0, + byte_len: 8, + instruction: Instruction::VectorCompareVop3 { + op, + sdst, + src0: 1, + src1: 2 + }, + }], + ); + assert_eq!( + decoded[0].instruction.to_string(), + format!("{} {dst}, v1, v2", op.assembly_name()) + ); + } +} + +#[test] +fn rejects_noncanonical_wave32_vop3_compare_operands() { + // v_cmp_eq_u32_e64 s4, v1, v2 + let first = 0xd4c2_0004; + let second = 0x0202_0501; + let rejects = |first, second| { + let code: Vec<_> = [first, second] + .into_iter() + .flat_map(u32::to_le_bytes) + .collect(); + let error = decode(Architecture::Gfx1030, &code).unwrap_err(); + assert_eq!(error.offset, 0); + assert!( + matches!( + error.kind, + DecodeErrorKind::UnsupportedForm { + mnemonic: "v_cmp_eq_u32_e64", + .. + } + ), + "{first:#010x} {second:#010x}: {error}" + ); + }; + + // Includes vcc_hi (107), TTMPs (108-123), null (124), m0 (125) and EXEC (126-127). + for sdst in 107..=255 { + rejects((first & !0xff) | sdst, second); + } + for bit in 8..=15 { + // ABS, OP_SEL and CLAMP. + rejects(first | (1 << bit), second); + } + for bit in 27..=31 { + // OMOD and NEG. + rejects(first, second | (1 << bit)); + } + rejects(first, second ^ (1 << 18)); // SRC2 = 129 instead of 128. + for shift in [0, 9] { + for selector in [4, 106, 128, 240, 255] { + // SGPR, VCC_LO, inline integer/float, literal. + rejects(first, (second & !(0x1ff << shift)) | (selector << shift)); + } + } +} + #[test] fn every_non_boundary_prefix_reports_the_incomplete_instruction() { let lengths = [8, 4, 8, 8, 8, 4, 4]; @@ -303,6 +424,44 @@ fn reference_scalar(scalar: ScalarSource) -> Source { } } +fn reference_comparison(op: VectorCompareOp) -> Comparison { + Comparison { + offset: match op.relation() { + CompareRelation::Less => 1, + CompareRelation::Equal => 2, + CompareRelation::LessOrEqual => 3, + CompareRelation::Greater => 4, + CompareRelation::NotEqual => 5, + CompareRelation::GreaterOrEqual => 6, + CompareRelation::False => 0, + CompareRelation::True => 7, + }, + signed: op.signed(), + } +} + +fn reference_vector_integer(op: VectorAluOp) -> VectorInteger { + match op { + VectorAluOp::CndmaskB32 => VectorInteger::Select, + VectorAluOp::AddCoCiU32 => VectorInteger::AddCarry, + VectorAluOp::SubCoCiU32 => VectorInteger::SubtractBorrow { reversed: false }, + VectorAluOp::SubrevCoCiU32 => VectorInteger::SubtractBorrow { reversed: true }, + VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true }, + VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true }, + VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false }, + VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false }, + VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true }, + VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true }, + VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false }, + VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false }, + VectorAluOp::XnorB32 => VectorInteger::Xnor, + VectorAluOp::AddNcU32 => VectorInteger::Add, + VectorAluOp::SubNcU32 => VectorInteger::Subtract, + VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse, + _ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"), + } +} + fn reference_op(instruction: Instruction) -> Op { match instruction { Instruction::BufferLoadDword { @@ -391,13 +550,23 @@ fn reference_op(instruction: Instruction) -> Op { reference_scalar(src0), reference_scalar(src1), ), - // The reference's VOP3 add; it is the only VOP3 variant so far. Instruction::VectorAluVop3 { op: VectorAluVop3Op::AddNcU32, dst, src0, src1, } => Op::Add(dst, src0, src1), + Instruction::VectorAluVop3 { + op, + dst, + src0, + src1, + } => Op::VectorInteger( + reference_vector_integer(op.base()), + dst, + CompareSource::Vector(src0), + src1, + ), Instruction::ScalarUnary { op, dst, src } => { let src = reference_scalar(src); let unary = match op { @@ -506,19 +675,7 @@ fn reference_op(instruction: Instruction) -> Op { } Instruction::VectorCompare { op, src0, src1 } => { - let comparison = Comparison { - offset: match op.relation() { - CompareRelation::Less => 1, - CompareRelation::Equal => 2, - CompareRelation::LessOrEqual => 3, - CompareRelation::Greater => 4, - CompareRelation::NotEqual => 5, - CompareRelation::GreaterOrEqual => 6, - CompareRelation::False => 0, - CompareRelation::True => 7, - }, - signed: op.signed(), - }; + let comparison = reference_comparison(op); let src0 = match src0 { VectorSource::Register(reg) => CompareSource::Vector(reg), VectorSource::Scalar(reg) => CompareSource::Scalar(reg), @@ -531,31 +688,24 @@ fn reference_op(instruction: Instruction) -> Op { width => panic!("unexpected VOPC operand width {width}"), } } + Instruction::VectorCompareVop3 { + op, + sdst, + src0, + src1, + } => Op::CompareVop3( + sdst, + reference_comparison(op.base()), + CompareSource::Vector(src0), + src1, + ), Instruction::VectorAlu { op, dst, src0, src1, } => Op::VectorInteger( - match op { - VectorAluOp::CndmaskB32 => VectorInteger::Select, - VectorAluOp::AddCoCiU32 => VectorInteger::AddCarry, - VectorAluOp::SubCoCiU32 => VectorInteger::SubtractBorrow { reversed: false }, - VectorAluOp::SubrevCoCiU32 => VectorInteger::SubtractBorrow { reversed: true }, - VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true }, - VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true }, - VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false }, - VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false }, - VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true }, - VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true }, - VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false }, - VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false }, - VectorAluOp::XnorB32 => VectorInteger::Xnor, - VectorAluOp::AddNcU32 => VectorInteger::Add, - VectorAluOp::SubNcU32 => VectorInteger::Subtract, - VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse, - _ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"), - }, + reference_vector_integer(op), dst, match src0 { VectorSource::Register(reg) => CompareSource::Vector(reg), @@ -596,12 +746,14 @@ fn compares_fixture_instructions_against_llvm() { include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"), include_bytes!("../../../fixtures/rdna2/vector-unary.bin"), include_bytes!("../../../fixtures/rdna2/vector-compare-16.bin"), + include_bytes!("../../../fixtures/rdna2/vop3-integer.bin"), + include_bytes!("../../../fixtures/rdna2/vop3-compare.bin"), high_registers, &matrix, ] { count += compare_against_llvm(fixture, &mut forms); } - assert_eq!(forms.len(), 142, "forms compared: {forms:?}"); + assert_eq!(forms.len(), 169, "forms compared: {forms:?}"); eprintln!( "{count} three-way instruction comparisons across {} forms", forms.len() @@ -829,7 +981,7 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() { let outside_subset: &[&[u32]] = &[ &[0x7e04_026b], // VOP1 VCC_HI source &[0x7da2_0501], // v_cmpx_eq_u32_e32 - &[0xd482_006a, 0x0002_0501], // v_cmp_lt_i32_e64 + &[0xd482_006a, 0x0002_0501], // v_cmp_eq_i32_e64 with SRC2 = 0 &[0x8788_0908], // s_and_b64 &[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources &[0x806c_0908], // SOP2 TTMP destination @@ -1119,6 +1271,122 @@ fn decode_at_resolves_branch_targets_from_the_stream_offset() { ); } +// llvm-mc -triple=amdgcn -mcpu=gfx1030 -show-encoding +const VOP3_INTEGER_ENCODINGS: [(VectorAluVop3Op, u32); 11] = [ + // v_mul_i32_i24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x09,0xd5,0x00,0xff,0x02,0x02] + (VectorAluVop3Op::MulI32I24, 0xd50900ff), + // v_mul_hi_i32_i24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0a,0xd5,0x00,0xff,0x02,0x02] + (VectorAluVop3Op::MulHiI32I24, 0xd50a00ff), + // v_mul_u32_u24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0b,0xd5,0x00,0xff,0x02,0x02] + (VectorAluVop3Op::MulU32U24, 0xd50b00ff), + // v_mul_hi_u32_u24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0c,0xd5,0x00,0xff,0x02,0x02] + (VectorAluVop3Op::MulHiU32U24, 0xd50c00ff), + // v_min_i32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x11,0xd5,0x00,0xff,0x02,0x02] + (VectorAluVop3Op::MinI32, 0xd51100ff), + // v_max_i32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x12,0xd5,0x00,0xff,0x02,0x02] + (VectorAluVop3Op::MaxI32, 0xd51200ff), + // v_min_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x13,0xd5,0x00,0xff,0x02,0x02] + (VectorAluVop3Op::MinU32, 0xd51300ff), + // v_max_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x14,0xd5,0x00,0xff,0x02,0x02] + (VectorAluVop3Op::MaxU32, 0xd51400ff), + // v_xnor_b32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x1e,0xd5,0x00,0xff,0x02,0x02] + (VectorAluVop3Op::XnorB32, 0xd51e00ff), + // v_sub_nc_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x26,0xd5,0x00,0xff,0x02,0x02] + (VectorAluVop3Op::SubNcU32, 0xd52600ff), + // v_subrev_nc_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x27,0xd5,0x00,0xff,0x02,0x02] + (VectorAluVop3Op::SubrevNcU32, 0xd52700ff), +]; +const VOP3_INTEGER_SOURCE_WORD: u32 = 0x0202_ff00; + +#[test] +fn decodes_registry_vop3_integer_encodings() { + for (op, first) in VOP3_INTEGER_ENCODINGS { + let bytes = [first.to_le_bytes(), VOP3_INTEGER_SOURCE_WORD.to_le_bytes()].concat(); + let decoded = decode(Architecture::Gfx1030, &bytes).unwrap(); + assert_eq!(decoded.len(), 1); + assert_eq!(decoded[0].byte_len, 8); + assert_eq!( + decoded[0].instruction, + Instruction::VectorAluVop3 { + op, + dst: 255, + src0: 0, + src1: 127, + } + ); + } +} + +#[test] +fn decodes_vop3_integer_fixture() { + use VectorAluVop3Op::*; + + let code = include_bytes!("../../../fixtures/rdna2/vop3-integer.bin"); + let decoded = decode(Architecture::Gfx1030, code).unwrap(); + let expected = [ + (MulI32I24, 2, 1, 1), + (MulHiI32I24, 3, 2, 1), + (MulU32U24, 4, 2, 1), + (MulHiU32U24, 255, 4, 1), + (MinI32, 6, 1, 2), + (MaxI32, 7, 1, 4), + (MinU32, 8, 3, 1), + (MaxU32, 9, 255, 2), + (XnorB32, 10, 1, 255), + (SubNcU32, 11, 6, 10), + (SubrevNcU32, 1, 1, 9), + ]; + let actual: Vec<_> = decoded + .iter() + .filter_map(|decoded| match decoded.instruction { + Instruction::VectorAluVop3 { + op, + dst, + src0, + src1, + } => Some((decoded.offset, decoded.byte_len, op, dst, src0, src1)), + _ => None, + }) + .collect(); + let expected: Vec<_> = expected + .into_iter() + .enumerate() + .map(|(index, (op, dst, src0, src1))| (12 + 8 * index, 8, op, dst, src0, src1)) + .collect(); + assert_eq!(actual, expected); +} + +#[test] +fn rejects_registry_vop3_integer_modifiers_and_other_sources() { + for (op, first) in VOP3_INTEGER_ENCODINGS { + let second = VOP3_INTEGER_SOURCE_WORD; + let reject = |first: u32, second: u32| { + let bytes = [first.to_le_bytes(), second.to_le_bytes()].concat(); + let error = decode(Architecture::Gfx1030, &bytes) + .expect_err(&format!("{op:?} accepted {first:#010x} {second:#010x}")); + assert_eq!(error.offset, 0); + assert!(matches!( + error.kind, + DecodeErrorKind::UnsupportedForm { mnemonic, .. } + if mnemonic == op.assembly_name() + )); + }; + + // First word: ABS[10:8], OP_SEL[14:11], CLAMP[15]. + for bit in 8..=15 { + reject(first | (1 << bit), second); + } + // Second word: OMOD[28:27], NEG[31:29]. + for bit in 27..=31 { + reject(first, second | (1 << bit)); + } + + reject(first, second & !0x1ff); // SRC0 = s0 + reject(first, (second & !(0x1ff << 9)) | (128 << 9)); // SRC1 = inline zero + reject(first, second | (1 << 18)); // SRC2 = inline one + } +} + #[test] fn decodes_sopk_immediates_and_rejects_non_sgpr_operands() { use xenora_decoder::ScalarImmediateCompareOp; diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 01a459c..7b1794c 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -44,7 +44,7 @@ TOP_KEYS = { # An encoding variant is another encoding of a form already in the registry (for # example the VOP3 `_e64` encoding of a VOP2 form): pure data that names the base # form, the encoding family, its opcode there and the operand rule of that -# encoding. It inherits the base form's operation, signedness and effects. +# encoding. The rule may redirect the base form's mask to an explicit destination. VARIANT_KEYS = {"of", "family", "opcode", "operands", "spec", "verify"} # The assembler suffix LLVM prints for a variant's encoding family. ASSEMBLY_SUFFIX = {"VOP3": "_e64"} @@ -151,8 +151,9 @@ SCC = { "selected_src0": "SelectedSrc0", } # lane_mask: the Wave32 compare or carry result written to VCC_LO. +# sdst_lane_mask: the Wave32 compare result written to explicit VOP3A SDST. # EXEC writes such as v_cmpx have no contract, so exec must stay unchanged. -MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask"} +MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask", "sdst_lane_mask": "SdstLaneMask"} WAVE = {"any": "Any", "wave32": "Wave32"} # The synthetic compute fixture ABI fixes the wave size for these operand-rule # kinds and for the VCC-reading VOP2 rule. Other forms declare "any". @@ -275,7 +276,12 @@ UNSUPPORTED_COMBOS = { # which SOP2 groups under src_vcc and src_special). # VOP3 rules also name source classes and encoding fields they refuse. VOP3_COMBOS = {"src_sgpr", "src_inline", "src_literal", "modifiers", "src2"} -ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"} | VOP3_COMBOS +ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null", "dst_vcc_hi"} | VOP3_COMBOS +VOP3_VGPR2_UNSUPPORTED = { + "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", + "src_float_inline", "src_special", "src_literal", "modifiers", "src2", +} + VECTOR_UNARY_PRIMITIVES = { ("not", "bitwise"): "Not", ("brev", "bitwise"): "ReverseBits", @@ -495,16 +501,34 @@ OPERAND_RULES = { }, # Two VGPR sources only, with ABS, OP_SEL, CLAMP, OMOD and NEG clear and # SRC2 the assembler's unused inline zero; the decoder rejects the rest. - "unsupported": { - "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", - "src_float_inline", "src_special", "src_literal", "modifiers", "src2", - }, + "unsupported": VOP3_VGPR2_UNSUPPORTED, "kind": "vector_vop3", # Only encoding variants of forms whose rule has this kind may use it. "variant_of": "vector", # The generated enum of this rule's variants; base() maps to "enum". "variant_enum": "VectorAluVop3Op", }, + "vop3_cmp_vgpr2": { + "rust": "Vop3CmpVgpr2", + "enum": "VectorCompareOp", + "shape": { + "family": "VOP3", + "dst": {"field": "VDST", "class": "sgpr", "min": 0, "max": 106}, + "src": [ + {"field": "SRC0", "class": "vgpr"}, + {"field": "SRC1", "class": "vgpr"}, + ], + "max_literals": 0, + "variant_only": True, + }, + "unsupported": VOP3_VGPR2_UNSUPPORTED | { + "dst_vcc_hi", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", + }, + "kind": "vector_compare_vop3", + "variant_of": "vector_compare", + "variant_enum": "VectorCompareVop3Op", + "vcc_transition": ("lane_mask", "sdst_lane_mask"), + }, "vop2_vgpr": { "rust": "Vop2Vgpr", "enum": "VectorAluOp", @@ -744,18 +768,18 @@ def _check_xml(form, rule, snapshot, errors): ): mask_inputs += 1 elif field: - operands[field] = (data_format, size, is_input, is_output) + operands[field] = (data_format, kind, size, is_input, is_output) elif kind == "OPR_VCC": - vcc_operands.append((is_input, is_output)) + vcc_operands.append((data_format, size, is_input, is_output)) else: implicit.add(kind) if form["carry_in"] == "vcc": - if vcc_operands.count((True, False)) != 1: + if vcc_operands.count(("FMT_NUM_M64", 64, True, False)) != 1: errors.append(f"{label}: carry_in vcc requires one implicit XML VCC input") - if (True, False) in vcc_operands: - vcc_operands.remove((True, False)) + if ("FMT_NUM_M64", 64, True, False) in vcc_operands: + vcc_operands.remove(("FMT_NUM_M64", 64, True, False)) if form["vcc"] == "lane_mask": - if vcc_operands != [(False, True)]: + if vcc_operands != [("FMT_NUM_M64", 64, False, True)]: errors.append(f"{label}: vcc lane_mask but the XML has no implicit VCC output") elif vcc_operands: implicit.add("OPR_VCC") @@ -780,7 +804,7 @@ def _check_xml(form, rule, snapshot, errors): if field not in operands: errors.append(f"{label}: XML has no operand {field}") continue - data_format, size, is_input, is_output = operands[field] + data_format, kind, size, is_input, is_output = operands[field] if field == "SIMM16" and _rule_kind(form) == "control": expected_kind, expected_format = ( ("OPR_LABEL", "FMT_NUM_I16") if form["operands"] == "sopp_branch" @@ -800,6 +824,11 @@ def _check_xml(form, rule, snapshot, errors): continue bits = form.get(SOURCE_BITS_KEY) if is_source else None expected = bits if type(bits) is int else form["width"] + if not is_source and form["vcc"] == "sdst_lane_mask": + # The XML describes the Wave64 pair. The Wave32 ABI writes one SGPR. + expected = 64 + if (kind, data_format) != ("OPR_SREG", "FMT_NUM_M64"): + errors.append(f"{label}: {field} is not a scalar mask destination in the XML") if size != expected: errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}") # The XML marks both swap operands as outputs. Guide 12.8 also @@ -896,10 +925,11 @@ def validate(registry, snapshot): if form["wave"] in WAVE and form["wave"] != wave: errors.append(f"{label}: wave {form['wave']} is not enforced for this rule (requires {wave})") lane_mask = _rule_kind(form) == "vector_compare" or (reads_vcc and form["operation"] != "cselect") - if form["vcc"] in MASK and (form["vcc"] == "lane_mask") != lane_mask: + vcc = "lane_mask" if lane_mask else "unchanged" + if form["vcc"] in MASK and form["vcc"] != vcc: errors.append( f"{label}: vcc {form['vcc']} contradicts rule {form['operands']} " - f"(requires {'lane_mask' if lane_mask else 'unchanged'})" + f"(requires {vcc})" ) if form["exec"] != "unchanged": errors.append(f"{label}: exec {form['exec']} has no contract (requires unchanged)") @@ -1070,9 +1100,10 @@ def variant_row(registry, variant, base=None): """The base form re-encoded: its declaration with the variant's identity.""" if base is None: base = next(form for form in registry["form"] if form.get("name") == variant["of"]) + _, vcc = OPERAND_RULES[variant["operands"]].get("vcc_transition", ("unchanged", "unchanged")) return dict( base, family=variant["family"], opcode=variant["opcode"], operands=variant["operands"], - spec=variant["spec"], verify=variant["verify"], + vcc=vcc, spec=variant["spec"], verify=variant["verify"], ) @@ -1142,24 +1173,32 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors): if FORM_KEYS - set(base): errors.append(f"{label}: not checked, its form {variant['of']} is incomplete") continue + base_vcc, _ = implemented.get("vcc_transition", ("unchanged", "unchanged")) + if base["vcc"] != base_vcc: + errors.append( + f"{label}: operand rule {variant['operands']} requires a base " + f"destination contract of {base_vcc}, got {base['vcc']}" + ) # The same base row as the completeness check above (with duplicate # declarations, the dict keeps the last one). _check_xml(variant_row(registry, variant, base), rule, snapshot, errors) - # Every explicit operand, destination included, has the base encoding's - # data format, in the same order (VSRC1 of VOP2 is SRC1 of VOP3). + # Explicit destinations and sources keep the base encoding's data format + # in the same role. The implicit-to-explicit mask transition is checked + # above and in _check_xml for each encoding. base_xml = snapshot["variants"].get((base["name"], _family_encoding(base["family"]))) own_xml = snapshot["variants"].get((variant["of"], _family_encoding(variant["family"]))) base_rule = rules.get(base.get("operands")) if base_xml and own_xml and _well_formed(base_rule) and _well_formed(rule): # Operands correspond by role, in rule order: the destination, then # each source (VSRC1 of VOP2 is SRC1 of VOP3). - def roles(rule, record): + def roles(rule, record, explicit_dst): by_field = {row[0]: row[1] for row in record["operands"] if row[0]} - fields = ([rule["dst"]["field"]] if "dst" in rule else []) + fields = [rule["dst"]["field"]] if explicit_dst else [] fields += [src["field"] for src in rule.get("src", [])] return [(field, by_field.get(field)) for field in fields] - pairs = list(zip(roles(base_rule, base_xml), roles(rule, own_xml))) + explicit_dst = "dst" in base_rule and "dst" in rule + pairs = zip(roles(base_rule, base_xml, explicit_dst), roles(rule, own_xml, explicit_dst)) for (base_field, base_format), (field, data_format) in pairs: if base_format != data_format: errors.append( diff --git a/crates/isa/semantics/rdna2.toml b/crates/isa/semantics/rdna2.toml index 13f3828..0f50735 100644 --- a/crates/isa/semantics/rdna2.toml +++ b/crates/isa/semantics/rdna2.toml @@ -49,6 +49,7 @@ file = "amdgpu_isa_rdna2.xml" # width operand and result width in bits # scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0 # vcc, exec unchanged (stated, not implied) | lane_mask (Wave32 VOPC compare or VOP2 carry output) +# VOP3A compare variant rows derive sdst_lane_mask from their operand rule. # wave any | wave32 (wave32 for VOPC compares, VOP1 integer forms and VCC-reading VOP2 forms) # operands a key of [operand_rules] # spec references; at least one guide section with a page diff --git a/crates/isa/semantics/rdna2/vop3.toml b/crates/isa/semantics/rdna2/vop3.toml index cffcc80..f4a948a 100644 --- a/crates/isa/semantics/rdna2/vop3.toml +++ b/crates/isa/semantics/rdna2/vop3.toml @@ -1,6 +1,202 @@ # VOP3 encodings of the gfx1030 semantic registry; included by ../rdna2.toml. # Data only; see the root file for the field meanings. +# ---- Wave32 VOPC compares in VOP3A (#215) ---- + +# VDST encodes the scalar lane-mask destination, including vcc_lo (selector 106). +# The two sources are VGPRs. Modifiers are clear and SRC2 is inline zero. +[operand_rules.vop3_cmp_vgpr2] +family = "VOP3" +dst = { field = "VDST", class = "sgpr", min = 0, max = 106 } +src = [ + { field = "SRC0", class = "vgpr" }, + { field = "SRC1", class = "vgpr" }, +] +max_literals = 0 +variant_only = true +unsupported = [ + "dst_vcc_hi", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", + "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", + "src_float_inline", "src_special", "src_literal", "modifiers", "src2", +] + +# Opcodes come from the pinned XML's default ENC_VOP3 records. +[[encoding_variant]] +of = "V_CMP_LT_I32" +family = "VOP3" +opcode = 129 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_EQ_I32" +family = "VOP3" +opcode = 130 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_LE_I32" +family = "VOP3" +opcode = 131 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_GT_I32" +family = "VOP3" +opcode = 132 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_NE_I32" +family = "VOP3" +opcode = 133 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_GE_I32" +family = "VOP3" +opcode = 134 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_LT_U32" +family = "VOP3" +opcode = 193 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_EQ_U32" +family = "VOP3" +opcode = 194 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_LE_U32" +family = "VOP3" +opcode = 195 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_GT_U32" +family = "VOP3" +opcode = 196 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_NE_U32" +family = "VOP3" +opcode = 197 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_GE_U32" +family = "VOP3" +opcode = 198 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_F_I32" +family = "VOP3" +opcode = 128 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_T_I32" +family = "VOP3" +opcode = 135 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_F_U32" +family = "VOP3" +opcode = 192 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_CMP_T_U32" +family = "VOP3" +opcode = 199 +operands = "vop3_cmp_vgpr2" +spec = [ + { document = "guide", section = "3.9", page = 19 }, + { document = "guide", section = "13.3.4", page = 257 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + # ---- VOP3 encoding variants of registry forms (#215) ---- # An [[encoding_variant]] re-encodes a form declared in another family file: it # names the form (`of`), this family, the XML opcode here and the operand rule @@ -37,3 +233,130 @@ spec = [ { document = "guide", section = "12.7", page = 134 }, ] verify = ["reference", "independent", "metal", "llvm_encoding"] + +# ABS and NEG apply to floating-point inputs (guide 6.2.1) and OMOD +# applies to floating-point results (6.2.2). These integer forms use neither. +# OP_SEL selects 16-bit halves (13.3.4). CLAMP saturates integer results +# (6.5), which these registry forms do not declare. SGPR, inline and literal +# sources remain outside this operand rule. + +[[encoding_variant]] +of = "V_MUL_I32_I24" +family = "VOP3" +opcode = 265 +operands = "vop3_vgpr2" +spec = [ + { document = "guide", section = "12.12", page = 167 }, + { document = "guide", section = "12.7", page = 131 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_MUL_HI_I32_I24" +family = "VOP3" +opcode = 266 +operands = "vop3_vgpr2" +spec = [ + { document = "guide", section = "12.12", page = 167 }, + { document = "guide", section = "12.7", page = 132 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_MUL_U32_U24" +family = "VOP3" +opcode = 267 +operands = "vop3_vgpr2" +spec = [ + { document = "guide", section = "12.12", page = 167 }, + { document = "guide", section = "12.7", page = 132 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_MUL_HI_U32_U24" +family = "VOP3" +opcode = 268 +operands = "vop3_vgpr2" +spec = [ + { document = "guide", section = "12.12", page = 167 }, + { document = "guide", section = "12.7", page = 132 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_MIN_I32" +family = "VOP3" +opcode = 273 +operands = "vop3_vgpr2" +spec = [ + { document = "guide", section = "12.12", page = 167 }, + { document = "guide", section = "12.7", page = 133 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_MAX_I32" +family = "VOP3" +opcode = 274 +operands = "vop3_vgpr2" +spec = [ + { document = "guide", section = "12.12", page = 167 }, + { document = "guide", section = "12.7", page = 133 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_MIN_U32" +family = "VOP3" +opcode = 275 +operands = "vop3_vgpr2" +spec = [ + { document = "guide", section = "12.12", page = 167 }, + { document = "guide", section = "12.7", page = 133 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_MAX_U32" +family = "VOP3" +opcode = 276 +operands = "vop3_vgpr2" +spec = [ + { document = "guide", section = "12.12", page = 167 }, + { document = "guide", section = "12.7", page = 133 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_XNOR_B32" +family = "VOP3" +opcode = 286 +operands = "vop3_vgpr2" +spec = [ + { document = "guide", section = "12.12", page = 167 }, + { document = "guide", section = "12.7", page = 134 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_SUB_NC_U32" +family = "VOP3" +opcode = 294 +operands = "vop3_vgpr2" +spec = [ + { document = "guide", section = "12.12", page = 167 }, + { document = "guide", section = "12.7", page = 134 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[encoding_variant]] +of = "V_SUBREV_NC_U32" +family = "VOP3" +opcode = 295 +operands = "vop3_vgpr2" +spec = [ + { document = "guide", section = "12.12", page = 167 }, + { document = "guide", section = "12.7", page = 134 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index 8bbe4ae..bab45af 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -20,7 +20,8 @@ pub use rdna2::{ }; pub use semantics_gen::{ ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarUnaryOp, - SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSwapOp, VectorUnaryOp, + SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op, + VectorSwapOp, VectorUnaryOp, }; impl VectorAluOp { @@ -227,6 +228,14 @@ pub enum Instruction { src0: VectorSource, src1: u8, }, + /// VOP3A 32-bit integer compare writing a Wave32 mask to s0-s105 or `vcc_lo`. + /// Both sources are VGPR indices. + VectorCompareVop3 { + op: VectorCompareVop3Op, + sdst: u8, + src0: u8, + src1: u8, + }, /// VOP2 32-bit per-lane integer operation from the semantic registry. /// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal; /// `src1` is a VGPR. Inactive lanes keep `dst`. @@ -309,6 +318,7 @@ impl Instruction { Self::ScalarImmediate { op, .. } => op.mnemonic(), Self::ScalarImmediateCompare { op, .. } => op.mnemonic(), Self::VectorCompare { op, .. } => op.assembly_name(), + Self::VectorCompareVop3 { op, .. } => op.assembly_name(), Self::VectorAlu { op, .. } => op.assembly_name(), Self::BranchSccZero { .. } => "s_cbranch_scc0", Self::BranchExecZero { .. } => "s_cbranch_execz", @@ -393,6 +403,9 @@ impl fmt::Display for Instruction { Self::VectorCompare { src0, src1, .. } => { write!(formatter, " vcc_lo, {src0}, v{src1}") } + Self::VectorCompareVop3 { + sdst, src0, src1, .. + } => write!(formatter, " {}, v{src0}, v{src1}", ScalarDestination(sdst)), Self::VectorAlu { op, dst, diff --git a/crates/isa/src/semantics.rs b/crates/isa/src/semantics.rs index d4380b0..5a0304d 100644 --- a/crates/isa/src/semantics.rs +++ b/crates/isa/src/semantics.rs @@ -47,7 +47,7 @@ pub enum Operation { LogicalShiftRight, /// Shift S0 right by the masked count in S1, filling with its sign bit. ArithmeticShiftRight, - /// Compare S0 with S1 under the form's relation; writes only SCC. + /// Compare S0 with S1 under the form's relation, producing SCC or a lane mask. Compare, /// Bitwise complement of S0. Not, @@ -227,7 +227,7 @@ pub enum SccEffect { SelectedSrc0, } -/// What a form writes to VCC or EXEC. +/// Where a form writes its lane mask, if any. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum MaskEffect { /// Not written. @@ -236,6 +236,8 @@ pub enum MaskEffect { /// exists) & test(lane n), fully written; `VCC_HI` has no known value after /// it (docs/shaders/vector-compare.md section 3). LaneMask, + /// Wave32 VOP3A compare mask written to SDST, which may be `vcc_lo`. + SdstLaneMask, } /// Wave-size restriction. @@ -288,6 +290,9 @@ pub enum OperandRule { /// VGPRs, no input or output modifiers, SRC2 unused. Everything else is /// rejected as unsupported. Vop3Vgpr2, + /// VOP3A compare: VDST encodes s0-s105 or `vcc_lo`; SRC0 and SRC1 are + /// VGPRs, SRC2 is unused and all modifiers are clear. + Vop3CmpVgpr2, /// VOP2 vector: VDST is v0-v255; SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline /// integer -16..64 or a literal word; VSRC1 is a VGPR. Everything else is /// rejected as unsupported. @@ -365,7 +370,7 @@ pub struct FormSemantics { pub relation: Option, /// SCC write. pub scc: SccEffect, - /// VCC write. + /// Implicit VCC write or explicit scalar destination for a compare mask. pub vcc: MaskEffect, /// EXEC write. pub exec: MaskEffect, diff --git a/crates/isa/src/semantics_gen.rs b/crates/isa/src/semantics_gen.rs index a6c9527..0778b8a 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -3421,17 +3421,62 @@ impl VectorCompareOp { } } -/// VOP3 encodings of registry forms (operand rule `vop3_vgpr2`). +/// VOP3 encodings of registry forms (operand rule `vop3_cmp_vgpr2`). #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum VectorAluVop3Op { - /// `v_add_nc_u32_e64` (VOP3 opcode 293). - AddNcU32, +pub enum VectorCompareVop3Op { + /// `v_cmp_lt_i32_e64` (VOP3 opcode 129). + CmpLtI32, + /// `v_cmp_eq_i32_e64` (VOP3 opcode 130). + CmpEqI32, + /// `v_cmp_le_i32_e64` (VOP3 opcode 131). + CmpLeI32, + /// `v_cmp_gt_i32_e64` (VOP3 opcode 132). + CmpGtI32, + /// `v_cmp_ne_i32_e64` (VOP3 opcode 133). + CmpNeI32, + /// `v_cmp_ge_i32_e64` (VOP3 opcode 134). + CmpGeI32, + /// `v_cmp_lt_u32_e64` (VOP3 opcode 193). + CmpLtU32, + /// `v_cmp_eq_u32_e64` (VOP3 opcode 194). + CmpEqU32, + /// `v_cmp_le_u32_e64` (VOP3 opcode 195). + CmpLeU32, + /// `v_cmp_gt_u32_e64` (VOP3 opcode 196). + CmpGtU32, + /// `v_cmp_ne_u32_e64` (VOP3 opcode 197). + CmpNeU32, + /// `v_cmp_ge_u32_e64` (VOP3 opcode 198). + CmpGeU32, + /// `v_cmp_f_i32_e64` (VOP3 opcode 128). + CmpFI32, + /// `v_cmp_t_i32_e64` (VOP3 opcode 135). + CmpTI32, + /// `v_cmp_f_u32_e64` (VOP3 opcode 192). + CmpFU32, + /// `v_cmp_t_u32_e64` (VOP3 opcode 199). + CmpTU32, } -impl VectorAluVop3Op { +impl VectorCompareVop3Op { /// Every variant, in registry order. - pub const ALL: [Self; 1] = [ - Self::AddNcU32, + pub const ALL: [Self; 16] = [ + Self::CmpLtI32, + Self::CmpEqI32, + Self::CmpLeI32, + Self::CmpGtI32, + Self::CmpNeI32, + Self::CmpGeI32, + Self::CmpLtU32, + Self::CmpEqU32, + Self::CmpLeU32, + Self::CmpGtU32, + Self::CmpNeU32, + Self::CmpGeU32, + Self::CmpFI32, + Self::CmpTI32, + Self::CmpFU32, + Self::CmpTU32, ]; /// Selects the variant from the first word of its VOP3 encoding: the @@ -3442,7 +3487,159 @@ impl VectorAluVop3Op { return None; } match (word >> 16) & 0x3ff { + 128 => Some(Self::CmpFI32), + 129 => Some(Self::CmpLtI32), + 130 => Some(Self::CmpEqI32), + 131 => Some(Self::CmpLeI32), + 132 => Some(Self::CmpGtI32), + 133 => Some(Self::CmpNeI32), + 134 => Some(Self::CmpGeI32), + 135 => Some(Self::CmpTI32), + 192 => Some(Self::CmpFU32), + 193 => Some(Self::CmpLtU32), + 194 => Some(Self::CmpEqU32), + 195 => Some(Self::CmpLeU32), + 196 => Some(Self::CmpGtU32), + 197 => Some(Self::CmpNeU32), + 198 => Some(Self::CmpGeU32), + 199 => Some(Self::CmpTU32), + _ => None, + } + } + + /// The form this encodes, whose declaration it inherits. + pub const fn base(self) -> VectorCompareOp { + match self { + Self::CmpLtI32 => VectorCompareOp::CmpLtI32, + Self::CmpEqI32 => VectorCompareOp::CmpEqI32, + Self::CmpLeI32 => VectorCompareOp::CmpLeI32, + Self::CmpGtI32 => VectorCompareOp::CmpGtI32, + Self::CmpNeI32 => VectorCompareOp::CmpNeI32, + Self::CmpGeI32 => VectorCompareOp::CmpGeI32, + Self::CmpLtU32 => VectorCompareOp::CmpLtU32, + Self::CmpEqU32 => VectorCompareOp::CmpEqU32, + Self::CmpLeU32 => VectorCompareOp::CmpLeU32, + Self::CmpGtU32 => VectorCompareOp::CmpGtU32, + Self::CmpNeU32 => VectorCompareOp::CmpNeU32, + Self::CmpGeU32 => VectorCompareOp::CmpGeU32, + Self::CmpFI32 => VectorCompareOp::CmpFI32, + Self::CmpTI32 => VectorCompareOp::CmpTI32, + Self::CmpFU32 => VectorCompareOp::CmpFU32, + Self::CmpTU32 => VectorCompareOp::CmpTU32, + } + } + + /// Assembler name of the VOP3 encoding, as LLVM prints it. + pub const fn assembly_name(self) -> &'static str { + match self { + Self::CmpLtI32 => "v_cmp_lt_i32_e64", + Self::CmpEqI32 => "v_cmp_eq_i32_e64", + Self::CmpLeI32 => "v_cmp_le_i32_e64", + Self::CmpGtI32 => "v_cmp_gt_i32_e64", + Self::CmpNeI32 => "v_cmp_ne_i32_e64", + Self::CmpGeI32 => "v_cmp_ge_i32_e64", + Self::CmpLtU32 => "v_cmp_lt_u32_e64", + Self::CmpEqU32 => "v_cmp_eq_u32_e64", + Self::CmpLeU32 => "v_cmp_le_u32_e64", + Self::CmpGtU32 => "v_cmp_gt_u32_e64", + Self::CmpNeU32 => "v_cmp_ne_u32_e64", + Self::CmpGeU32 => "v_cmp_ge_u32_e64", + Self::CmpFI32 => "v_cmp_f_i32_e64", + Self::CmpTI32 => "v_cmp_t_i32_e64", + Self::CmpFU32 => "v_cmp_f_u32_e64", + Self::CmpTU32 => "v_cmp_t_u32_e64", + } + } + + /// The validated registry row of this encoding. + pub fn semantics(self) -> &'static FormSemantics { + &FORMS[match self { + Self::CmpLtI32 => 151, + Self::CmpEqI32 => 152, + Self::CmpLeI32 => 153, + Self::CmpGtI32 => 154, + Self::CmpNeI32 => 155, + Self::CmpGeI32 => 156, + Self::CmpLtU32 => 157, + Self::CmpEqU32 => 158, + Self::CmpLeU32 => 159, + Self::CmpGtU32 => 160, + Self::CmpNeU32 => 161, + Self::CmpGeU32 => 162, + Self::CmpFI32 => 163, + Self::CmpTI32 => 164, + Self::CmpFU32 => 165, + Self::CmpTU32 => 166, + }] + } +} + +/// VOP3 encodings of registry forms (operand rule `vop3_vgpr2`). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum VectorAluVop3Op { + /// `v_add_nc_u32_e64` (VOP3 opcode 293). + AddNcU32, + /// `v_mul_i32_i24_e64` (VOP3 opcode 265). + MulI32I24, + /// `v_mul_hi_i32_i24_e64` (VOP3 opcode 266). + MulHiI32I24, + /// `v_mul_u32_u24_e64` (VOP3 opcode 267). + MulU32U24, + /// `v_mul_hi_u32_u24_e64` (VOP3 opcode 268). + MulHiU32U24, + /// `v_min_i32_e64` (VOP3 opcode 273). + MinI32, + /// `v_max_i32_e64` (VOP3 opcode 274). + MaxI32, + /// `v_min_u32_e64` (VOP3 opcode 275). + MinU32, + /// `v_max_u32_e64` (VOP3 opcode 276). + MaxU32, + /// `v_xnor_b32_e64` (VOP3 opcode 286). + XnorB32, + /// `v_sub_nc_u32_e64` (VOP3 opcode 294). + SubNcU32, + /// `v_subrev_nc_u32_e64` (VOP3 opcode 295). + SubrevNcU32, +} + +impl VectorAluVop3Op { + /// Every variant, in registry order. + pub const ALL: [Self; 12] = [ + Self::AddNcU32, + Self::MulI32I24, + Self::MulHiI32I24, + Self::MulU32U24, + Self::MulHiU32U24, + Self::MinI32, + Self::MaxI32, + Self::MinU32, + Self::MaxU32, + Self::XnorB32, + Self::SubNcU32, + Self::SubrevNcU32, + ]; + + /// Selects the variant from the first word of its VOP3 encoding: the + /// encoding bits (mask 0xfc00_0000) and then the OP field (bits + /// 16-25). `None` for undeclared opcodes. + pub const fn from_word(word: u32) -> Option { + if word & 0xfc00_0000 != 0xd400_0000 { + return None; + } + match (word >> 16) & 0x3ff { + 265 => Some(Self::MulI32I24), + 266 => Some(Self::MulHiI32I24), + 267 => Some(Self::MulU32U24), + 268 => Some(Self::MulHiU32U24), + 273 => Some(Self::MinI32), + 274 => Some(Self::MaxI32), + 275 => Some(Self::MinU32), + 276 => Some(Self::MaxU32), + 286 => Some(Self::XnorB32), 293 => Some(Self::AddNcU32), + 294 => Some(Self::SubNcU32), + 295 => Some(Self::SubrevNcU32), _ => None, } } @@ -3451,6 +3648,17 @@ impl VectorAluVop3Op { pub const fn base(self) -> VectorAluOp { match self { Self::AddNcU32 => VectorAluOp::AddNcU32, + Self::MulI32I24 => VectorAluOp::MulI32I24, + Self::MulHiI32I24 => VectorAluOp::MulHiI32I24, + Self::MulU32U24 => VectorAluOp::MulU32U24, + Self::MulHiU32U24 => VectorAluOp::MulHiU32U24, + Self::MinI32 => VectorAluOp::MinI32, + Self::MaxI32 => VectorAluOp::MaxI32, + Self::MinU32 => VectorAluOp::MinU32, + Self::MaxU32 => VectorAluOp::MaxU32, + Self::XnorB32 => VectorAluOp::XnorB32, + Self::SubNcU32 => VectorAluOp::SubNcU32, + Self::SubrevNcU32 => VectorAluOp::SubrevNcU32, } } @@ -3458,19 +3666,41 @@ impl VectorAluVop3Op { pub const fn assembly_name(self) -> &'static str { match self { Self::AddNcU32 => "v_add_nc_u32_e64", + Self::MulI32I24 => "v_mul_i32_i24_e64", + Self::MulHiI32I24 => "v_mul_hi_i32_i24_e64", + Self::MulU32U24 => "v_mul_u32_u24_e64", + Self::MulHiU32U24 => "v_mul_hi_u32_u24_e64", + Self::MinI32 => "v_min_i32_e64", + Self::MaxI32 => "v_max_i32_e64", + Self::MinU32 => "v_min_u32_e64", + Self::MaxU32 => "v_max_u32_e64", + Self::XnorB32 => "v_xnor_b32_e64", + Self::SubNcU32 => "v_sub_nc_u32_e64", + Self::SubrevNcU32 => "v_subrev_nc_u32_e64", } } /// The validated registry row of this encoding. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { - Self::AddNcU32 => 151, + Self::AddNcU32 => 167, + Self::MulI32I24 => 168, + Self::MulHiI32I24 => 169, + Self::MulU32U24 => 170, + Self::MulHiU32U24 => 171, + Self::MinI32 => 172, + Self::MaxI32 => 173, + Self::MinU32 => 174, + Self::MaxU32 => 175, + Self::XnorB32 => 176, + Self::SubNcU32 => 177, + Self::SubrevNcU32 => 178, }] } } /// Identity of every registry form and encoding variant, in registry order. -pub const FORM_IDS: [(&str, EncodingFamily); 152] = [ +pub const FORM_IDS: [(&str, EncodingFamily); 179] = [ ("S_ADD_U32", EncodingFamily::Sop2), ("S_SUB_U32", EncodingFamily::Sop2), ("S_ADD_I32", EncodingFamily::Sop2), @@ -3622,11 +3852,38 @@ pub const FORM_IDS: [(&str, EncodingFamily); 152] = [ ("S_CBRANCH_VCCZ", EncodingFamily::Sopp), ("S_CBRANCH_EXECZ", EncodingFamily::Sopp), ("S_WAITCNT", EncodingFamily::Sopp), + ("V_CMP_LT_I32", EncodingFamily::Vop3), + ("V_CMP_EQ_I32", EncodingFamily::Vop3), + ("V_CMP_LE_I32", EncodingFamily::Vop3), + ("V_CMP_GT_I32", EncodingFamily::Vop3), + ("V_CMP_NE_I32", EncodingFamily::Vop3), + ("V_CMP_GE_I32", EncodingFamily::Vop3), + ("V_CMP_LT_U32", EncodingFamily::Vop3), + ("V_CMP_EQ_U32", EncodingFamily::Vop3), + ("V_CMP_LE_U32", EncodingFamily::Vop3), + ("V_CMP_GT_U32", EncodingFamily::Vop3), + ("V_CMP_NE_U32", EncodingFamily::Vop3), + ("V_CMP_GE_U32", EncodingFamily::Vop3), + ("V_CMP_F_I32", EncodingFamily::Vop3), + ("V_CMP_T_I32", EncodingFamily::Vop3), + ("V_CMP_F_U32", EncodingFamily::Vop3), + ("V_CMP_T_U32", EncodingFamily::Vop3), ("V_ADD_NC_U32", EncodingFamily::Vop3), + ("V_MUL_I32_I24", EncodingFamily::Vop3), + ("V_MUL_HI_I32_I24", EncodingFamily::Vop3), + ("V_MUL_U32_U24", EncodingFamily::Vop3), + ("V_MUL_HI_U32_U24", EncodingFamily::Vop3), + ("V_MIN_I32", EncodingFamily::Vop3), + ("V_MAX_I32", EncodingFamily::Vop3), + ("V_MIN_U32", EncodingFamily::Vop3), + ("V_MAX_U32", EncodingFamily::Vop3), + ("V_XNOR_B32", EncodingFamily::Vop3), + ("V_SUB_NC_U32", EncodingFamily::Vop3), + ("V_SUBREV_NC_U32", EncodingFamily::Vop3), ]; /// One validated row per registry form, in registry order. -pub static FORMS: [FormSemantics; 152] = [ +pub static FORMS: [FormSemantics; 179] = [ FormSemantics { name: "S_ADD_U32", family: EncodingFamily::Sop2, @@ -6798,6 +7055,342 @@ pub static FORMS: [FormSemantics; 152] = [ spec: &[SpecRef { document: Document::Guide, section: "12.5", page: 125 }, SpecRef { document: Document::Guide, section: "13.1.5", page: 245 }], verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], }, + FormSemantics { + name: "V_CMP_LT_I32", + family: EncodingFamily::Vop3, + opcode: 129, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Less), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_EQ_I32", + family: EncodingFamily::Vop3, + opcode: 130, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Equal), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_LE_I32", + family: EncodingFamily::Vop3, + opcode: 131, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::LessOrEqual), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_GT_I32", + family: EncodingFamily::Vop3, + opcode: 132, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Greater), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_NE_I32", + family: EncodingFamily::Vop3, + opcode: 133, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::NotEqual), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_GE_I32", + family: EncodingFamily::Vop3, + opcode: 134, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::GreaterOrEqual), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_LT_U32", + family: EncodingFamily::Vop3, + opcode: 193, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Less), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_EQ_U32", + family: EncodingFamily::Vop3, + opcode: 194, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Equal), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_LE_U32", + family: EncodingFamily::Vop3, + opcode: 195, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::LessOrEqual), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_GT_U32", + family: EncodingFamily::Vop3, + opcode: 196, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Greater), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_NE_U32", + family: EncodingFamily::Vop3, + opcode: 197, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::NotEqual), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_GE_U32", + family: EncodingFamily::Vop3, + opcode: 198, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::GreaterOrEqual), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_F_I32", + family: EncodingFamily::Vop3, + opcode: 128, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::False), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_T_I32", + family: EncodingFamily::Vop3, + opcode: 135, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::True), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_F_U32", + family: EncodingFamily::Vop3, + opcode: 192, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::False), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_T_U32", + family: EncodingFamily::Vop3, + opcode: 199, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::True), + scc: SccEffect::Unchanged, + vcc: MaskEffect::SdstLaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::Vop3CmpVgpr2, + spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, FormSemantics { name: "V_ADD_NC_U32", family: EncodingFamily::Vop3, @@ -6819,4 +7412,235 @@ pub static FORMS: [FormSemantics; 152] = [ spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 134 }], verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], }, + FormSemantics { + name: "V_MUL_I32_I24", + family: EncodingFamily::Vop3, + opcode: 265, + operation: Operation::Multiply24, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop3Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 131 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_MUL_HI_I32_I24", + family: EncodingFamily::Vop3, + opcode: 266, + operation: Operation::MultiplyHigh24, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop3Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 132 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_MUL_U32_U24", + family: EncodingFamily::Vop3, + opcode: 267, + operation: Operation::Multiply24, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop3Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 132 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_MUL_HI_U32_U24", + family: EncodingFamily::Vop3, + opcode: 268, + operation: Operation::MultiplyHigh24, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop3Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 132 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_MIN_I32", + family: EncodingFamily::Vop3, + opcode: 273, + operation: Operation::Minimum, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop3Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_MAX_I32", + family: EncodingFamily::Vop3, + opcode: 274, + operation: Operation::Maximum, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop3Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_MIN_U32", + family: EncodingFamily::Vop3, + opcode: 275, + operation: Operation::Minimum, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop3Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_MAX_U32", + family: EncodingFamily::Vop3, + opcode: 276, + operation: Operation::Maximum, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop3Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_XNOR_B32", + family: EncodingFamily::Vop3, + opcode: 286, + operation: Operation::Xnor, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop3Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 134 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_SUB_NC_U32", + family: EncodingFamily::Vop3, + opcode: 294, + operation: Operation::Sub, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop3Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 134 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_SUBREV_NC_U32", + family: EncodingFamily::Vop3, + opcode: 295, + operation: Operation::Sub, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: true, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop3Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 134 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, ]; diff --git a/crates/isa/tests/semantics.rs b/crates/isa/tests/semantics.rs index 7db8e65..2f88e0d 100644 --- a/crates/isa/tests/semantics.rs +++ b/crates/isa/tests/semantics.rs @@ -2,11 +2,12 @@ use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS}; use xenora_isa::semantics::{ - CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, SCHEMA, SccEffect, Signedness, Wave, + CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, OperandRule, SCHEMA, SccEffect, + Signedness, Wave, }; use xenora_isa::{ CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, - ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, + ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op, }; #[test] @@ -261,8 +262,38 @@ fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() { assert_eq!(row.swap_sources, base.swap_sources); assert_eq!(op.assembly_name(), format!("{}_e64", op.base().mnemonic())); } + for base_op in VectorCompareOp::ALL { + let base = base_op.semantics(); + let mut variants = VectorCompareVop3Op::ALL + .into_iter() + .filter(|op| op.base() == base_op); + if base.width != 32 { + assert_eq!(variants.next(), None, "{}", base.name); + continue; + } + let op = variants + .next() + .expect("32-bit VOPC form must have a VOP3A encoding"); + assert_eq!(variants.next(), None); + let row = op.semantics(); + assert_eq!((row.name, row.family), (base.name, EncodingFamily::Vop3)); + assert_eq!(row.operation, base.operation); + assert_eq!(row.signedness, base.signedness); + assert_eq!(row.relation, base.relation); + assert_eq!(row.scc, SccEffect::Unchanged); + assert_eq!(row.exec, MaskEffect::Unchanged); + assert_eq!(row.wave, Wave::Wave32); + assert_eq!(row.width, 32); + assert_eq!(row.vcc, MaskEffect::SdstLaneMask); + assert_eq!(row.operands, OperandRule::Vop3CmpVgpr2); + assert_eq!(op.assembly_name(), format!("{}_e64", base_op.mnemonic())); + } dispatch_selects_exactly(EncodingFamily::Vop3, |word| { - VectorAluVop3Op::from_word(word).map(|op| op.semantics().name) + let alu = VectorAluVop3Op::from_word(word); + let compare = VectorCompareVop3Op::from_word(word); + assert!(alu.is_none() || compare.is_none(), "{word:#x}"); + alu.map(|op| op.semantics().name) + .or_else(|| compare.map(|op| op.semantics().name)) }); // No first word of the other 64-bit families (VOP3B shares VOP3's // encoding bits) selects a variant. @@ -276,5 +307,11 @@ fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() { "{}", meta.name ); + assert_eq!( + VectorCompareVop3Op::from_word(meta.bits as u32), + None, + "{}", + meta.name + ); } } diff --git a/crates/ref/src/lib.rs b/crates/ref/src/lib.rs index 56d0769..2636834 100644 --- a/crates/ref/src/lib.rs +++ b/crates/ref/src/lib.rs @@ -57,6 +57,8 @@ pub enum Op { MoveScalar(u8, u8), /// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`. Compare(Comparison, CompareSource, u8), + /// VOP3A integer compare writing a Wave32 mask to SDST. + CompareVop3(u8, Comparison, CompareSource, u8), /// VOPC 16- or 64-bit integer compare writing the Wave32 mask to /// `vcc_lo`. For 64-bit forms a `Vector` or `Scalar` source and VSRC1 name /// the low register of a pair. @@ -187,6 +189,8 @@ pub enum BranchCondition { SccZero, /// Take the branch when the low half of VCC is clear. VccZero, + /// Take the branch when the low half of VCC is nonzero. + VccNonzero, /// Take the branch when the low half of EXEC is clear. ExecZero, } @@ -719,7 +723,13 @@ pub fn decode(code: &[u8]) -> Result, ReferenceError> { left_length.max(right_length), ) } - [lo, hi, opcode @ (0x82 | 0x84 | 0x86 | 0x88), 0xbf, ..] => { + [ + lo, + hi, + opcode @ (0x82 | 0x84 | 0x86 | 0x87 | 0x88), + 0xbf, + .., + ] => { let words = i16::from_le_bytes([*lo, *hi]); let words = usize::try_from(words).map_err(|_| error(offset, "backward branch"))?; ( @@ -728,6 +738,7 @@ pub fn decode(code: &[u8]) -> Result, ReferenceError> { condition: match opcode { 0x84 => BranchCondition::SccZero, 0x86 => BranchCondition::VccZero, + 0x87 => BranchCondition::VccNonzero, 0x88 => BranchCondition::ExecZero, _ => BranchCondition::Always, }, @@ -755,9 +766,50 @@ pub fn decode(code: &[u8]) -> Result, ReferenceError> { let src1 = (second >> 1) | ((third & 1) << 7); (Op::Vector(kind, dst, *first, src1), 4) } - [dst, 0, 0x25, 0xd5, lo, middle, hi @ 2..=3, 0x02, ..] if middle & 1 == 1 => { + // Guide §§12.7.1, 12.9.1, 12.12 and 13.3.4: VOP3A extends + // VOP2 by 0x100 and preserves the VOPC opcode. This subset + // fixes unused SRC2 to inline 0 and excludes FP ABS/NEG/OMOD, + // halfword OP_SEL, and CLAMP (integer saturation or FP compare + // exceptions, §6.5). + [ + dst, + 0, + op, + tag @ (0xd4 | 0xd5), + lo, + middle, + hi @ 2..=3, + 0x02, + .., + ] if middle & 1 != 0 => { + let src0 = CompareSource::Vector(*lo); let src1 = (middle >> 1) | ((hi & 1) << 7); - (Op::Add(*dst, *lo, src1), 8) + match tag { + 0xd4 if matches!(op, 128..=135 | 192..=199) && *dst <= 106 => ( + Op::CompareVop3( + *dst, + Comparison { + offset: op & 7, + signed: *op < 192, + }, + src0, + src1, + ), + 8, + ), + 0xd5 if *op == 37 => (Op::Add(*dst, *lo, src1), 8), + 0xd5 => ( + Op::VectorInteger( + VectorInteger::from_opcode(*op) + .ok_or_else(|| error(offset, "unsupported VOP3 opcode"))?, + *dst, + src0, + src1, + ), + 8, + ), + _ => return Err(error(offset, "unsupported VOP3 opcode or destination")), + } } // VOPC (bits 31-25 = 0b0111110): SRC0 bits 0-8, VSRC1 bits 9-16, OP bits 17-24. [lo, packed, upper, tag @ 0x7c..=0x7d, tail @ ..] @@ -1434,13 +1486,16 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result { - let (comparison, width, src0, src1) = match op { + Op::Compare(..) | Op::WideCompare(..) | Op::CompareVop3(..) => { + let (dst, comparison, width, src0, src1) = match op { Op::Compare(comparison, src0, src1) => { - (comparison, CompareWidth::Word, src0, src1) + (VCC_LO, comparison, CompareWidth::Word, src0, src1) + } + Op::CompareVop3(dst, comparison, src0, src1) => { + (usize::from(dst), comparison, CompareWidth::Word, src0, src1) } Op::WideCompare(comparison, width, src0, src1) => { - (comparison, width, src0, src1) + (VCC_LO, comparison, width, src0, src1) } _ => unreachable!(), }; @@ -1501,18 +1556,24 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result { - if condition == BranchCondition::VccZero && scalars[VCC_LO].is_none() { + let tests_vcc = matches!( + condition, + BranchCondition::VccZero | BranchCondition::VccNonzero + ); + if tests_vcc && scalars[VCC_LO].is_none() { return Err(error(offset, "branch with uninitialized VCC_LO")); } - if condition == BranchCondition::VccZero && lane_derived_vcc { + if tests_vcc && lane_derived_vcc { check_runtime_region( &program[position + 1..], destination, @@ -1529,6 +1590,7 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result scalars[VCC_LO] == Some(0), + BranchCondition::VccNonzero => scalars[VCC_LO] != Some(0), BranchCondition::ExecZero => exec == 0, }; if take_branch { diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 1e24ac6..0d81ca6 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -120,6 +120,10 @@ enum Op { /// The value is wave-uniform; every thread computes it for its own wave. LaneMask { op: VectorCompareOp, + /// Assembly name of the decoded encoding (`_e32` or `_e64`). + name: &'static str, + /// The explicit SGPR destination of the VOP3A encoding (IR text only). + sdst: Option, src0: Value, src1: Value, high: Option<(Value, Value)>, @@ -600,11 +604,18 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result { + let target = match sdst { + None => String::new(), + Some(VCC_LO) => " -> vcc_lo".to_string(), + Some(register) => format!(" -> s{register}"), + }; let (left, right) = if let Some((hi0, hi1)) = high { (format!("{src0}:{hi0}"), format!("{src1}:{hi1}")) } else { @@ -612,8 +623,7 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result Result, CompileError> { let mut operations = Vec::new(); let mut registers = [None::; 256]; @@ -728,12 +745,12 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result = None; // An open runtime `s_cbranch_vccz` region: its end, mask and the VGPRs at the branch. let mut region: Option<(usize, Value, [Option; 256])> = None; @@ -865,11 +882,15 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result Ok(value), - ScalarSource::Register(register) => scalars - .get(usize::from(register)) - .copied() - .flatten() - .ok_or_else(|| error("scalar source has no known value")), + ScalarSource::Register(register) => match scalars.get(usize::from(register)) { + Some(ScalarValue::Known(value)) => Ok(*value), + Some(ScalarValue::RuntimeMask) => Err(error( + "scalar source reads a runtime-only SGPR compare mask", + )), + Some(ScalarValue::Uninitialized) | None => { + Err(error("scalar source has no known value")) + } + }, }; let read_vector = |source, operations: &mut Vec<_>, facts: &mut Vec<_>| { Ok(match source { @@ -877,8 +898,10 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { match (lane_vcc, scalars[VCC_LO]) { (Some(mask), _) => mask, - (None, Some(bits)) => constant(operations, facts, offset, bits), - (None, None) => { + (None, ScalarValue::Known(bits)) => { + constant(operations, facts, offset, bits) + } + (None, _) => { return Err(error("vector ALU reads uninitialized VCC_LO")); } } @@ -896,8 +919,8 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { // Guide 3.9: inactive lanes contribute zero to carry-out. lane_vcc = None; - scalars[VCC_LO] = Some(0); - scalars[VCC_HI] = None; + scalars[VCC_LO] = ScalarValue::Known(0); + scalars[VCC_HI] = ScalarValue::Uninitialized; continue; } Instruction::MoveB32 { .. } @@ -918,6 +941,19 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { @@ -1033,7 +1069,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { @@ -1045,7 +1081,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result Result Result value, + ScalarValue::RuntimeMask => { + return Err(error("SOPK reads a runtime-only SGPR compare mask")); + } + ScalarValue::Uninitialized => { + return Err(error("SOPK reads an uninitialized SGPR")); + } + } } else { 0 }; let (value, flag) = op.evaluate(old, simm16, scc_in); if let Some(value) = value { - *slot = Some(value); + *slot = ScalarValue::Known(value); } if let Some(flag) = flag { scc = Some(flag); @@ -1112,11 +1156,36 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { + // Both encodings share the Wave32 lane mask implementation. + compare @ (Instruction::VectorCompare { .. } + | Instruction::VectorCompareVop3 { .. }) => { + let (op, name, explicit, sdst, src0, src1) = match compare { + Instruction::VectorCompare { op, src0, src1 } => { + (op, op.assembly_name(), false, VCC_LO, src0, src1) + } + Instruction::VectorCompareVop3 { + op, + sdst, + src0, + src1, + } => ( + op.base(), + op.assembly_name(), + true, + usize::from(sdst), + VectorSource::Register(src0), + src1, + ), + _ => unreachable!("only vector compares reach this arm"), + }; if exec == 0 { - scalars[VCC_HI] = None; - scalars[VCC_LO] = Some(0); - lane_vcc = None; + if sdst == VCC_LO { + scalars[VCC_HI] = ScalarValue::Uninitialized; + scalars[VCC_LO] = ScalarValue::Known(0); + lane_vcc = None; + } else { + scalars[sdst] = ScalarValue::RuntimeMask; + } continue; } let constant = @@ -1148,8 +1217,10 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { match (lane_vcc, scalars[VCC_LO]) { (Some(mask), _) => mask, - (None, Some(bits)) => constant(&mut operations, &mut facts, bits), - (None, None) => { + (None, ScalarValue::Known(bits)) => { + constant(&mut operations, &mut facts, bits) + } + (None, _) => { return Err(error("compare reads uninitialized VCC_LO")); } } @@ -1166,6 +1237,8 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result Result Result { - scalars[106].ok_or_else(|| { - error("conditional branch reads uninitialized VCC_LO") - })? == 0 + let ScalarValue::Known(bits) = scalars[VCC_LO] else { + return Err(error( + "conditional branch reads uninitialized VCC_LO", + )); + }; + bits == 0 } SoppControlOp::BranchExecZero => exec == 0, SoppControlOp::WaitLoad | SoppControlOp::EndProgram => { @@ -1259,10 +1339,10 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { let mask = match (lane_vcc, scalars[VCC_LO]) { (Some(mask), _) => mask, - (None, Some(bits)) => { + (None, ScalarValue::Known(bits)) => { constant(&mut operations, &mut facts, offset, bits) } - (None, None) => { + (None, _) => { return Err(error("vector ALU reads uninitialized VCC_LO")); } }; @@ -1282,8 +1362,8 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result = [ + 0x7e02_0281u32, // v_mov_b32_e32 v1, 1 + 0x7e04_0282, // v_mov_b32_e32 v2, 2 + 0xd4c2_006a, // v_cmp_eq_u32_e64 vcc_lo, v1, v2 + 0x0202_0501, + 0xbf86_0001, // s_cbranch_vccz 1 + 0x7e02_0302, // v_mov_b32_e32 v1, v2 + ] + .into_iter() + .flat_map(u32::to_le_bytes) + .chain(FIXTURE[28..].iter().copied()) + .collect(); + let shader = compile(Architecture::Gfx1030, &code).unwrap(); + assert!( + shader + .disassembly + .contains("v_cmp_eq_u32_e64 vcc_lo, v1, v2") + ); + assert!(shader.ir.contains("0008: t2 = wave.mask")); + assert!(shader.ir.contains("0010: branch.vccz t2 -> 0x0018")); + assert!(shader.ir.contains("join.vccz t2")); + assert!(shader.msl.contains("lane_index >= grid")); +} + +#[test] +fn vop3_compare_to_s4_rejects_later_scalar_reads() { + for (setup, offset) in [ + (&[0x7e02_0281u32, 0x7e04_0282][..], 16), // Initialize both VGPRs. + (&[0xbefe_0380][..], 12), // Empty EXEC. The VGPRs need not be initialized. + ] { + let code: Vec<_> = setup + .iter() + .copied() + .chain([ + 0xd4c2_0004, // v_cmp_eq_u32_e64 s4, v1, v2 + 0x0202_0501, + 0xbf06_8004, // s_cmp_eq_u32 s4, 0 + 0xbefe_03c1, // s_mov_b32 exec_lo, -1 + 0x7e02_0281, // v_mov_b32_e32 v1, 1 + ]) + .flat_map(u32::to_le_bytes) + .chain(FIXTURE[28..].iter().copied()) + .collect(); + let error = compile(Architecture::Gfx1030, &code).unwrap_err(); + assert!( + matches!( + error, + CompileError::Verify { + offset: actual, + reason: "scalar source reads a runtime-only SGPR compare mask", + } if actual == offset + ), + "{error}" + ); + } +} + +#[test] +fn vop3_compare_mask_cannot_be_read_as_a_buffer_descriptor() { + let code: Vec<_> = [ + 0x7e02_0281u32, // v_mov_b32_e32 v1, 1 + 0x7e04_0282, // v_mov_b32_e32 v2, 2 + 0xd4c2_0004, // v_cmp_eq_u32_e64 s4, v1, v2 + 0x0202_0501, + ] + .into_iter() + .flat_map(u32::to_le_bytes) + .chain(FIXTURE[28..].iter().copied()) + .collect(); + assert!(matches!( + compile(Architecture::Gfx1030, &code), + Err(CompileError::Verify { + offset: 16, + reason: "resource descriptor reads a runtime-only SGPR compare mask", + }) + )); +} + +#[test] +fn vop3_compare_to_normal_sgpr_preserves_vcc_and_can_be_overwritten() { + let code: Vec<_> = [ + 0x7e02_0281u32, // v_mov_b32_e32 v1, 1 + 0x7e04_0282, // v_mov_b32_e32 v2, 2 + 0xbeea_0381, // s_mov_b32 vcc_lo, 1 + 0xd4c2_0008, // v_cmp_eq_u32_e64 s8, v1, v2 + 0x0202_0501, + 0xbf86_0001, // s_cbranch_vccz 1 + 0xbe88_0381, // s_mov_b32 s8, 1 + 0xbf06_8008, // s_cmp_eq_u32 s8, 0 + ] + .into_iter() + .flat_map(u32::to_le_bytes) + .chain(FIXTURE[28..].iter().copied()) + .collect(); + let shader = compile(Architecture::Gfx1030, &code).unwrap(); + assert!( + shader + .ir + .contains("0014: branch.uniform 0x001c taken=false") + ); +} + #[test] fn load_wait_is_required_before_using_loaded_data() { let mut code = FIXTURE.to_vec(); @@ -364,6 +468,20 @@ fn vector_integer_forms_lower_to_per_lane_templates() { ); } +#[test] +fn vop3_integer_forms_lower_to_per_lane_templates() { + let code = include_bytes!("../../../fixtures/rdna2/vop3-integer.bin"); + let compiled = compile(Architecture::Gfx1030, code).unwrap(); + assert_eq!( + compiled.ir, + include_str!("../../../fixtures/golden/vop3-integer.ir") + ); + assert_eq!( + compiled.msl, + include_str!("../../../fixtures/golden/vop3-integer.metal") + ); +} + #[test] fn vector_f_and_t_compares_lower_to_operand_free_wave_masks() { let code = include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"); @@ -392,6 +510,20 @@ fn vector_compares_lower_to_per_thread_wave_masks_and_selects() { ); } +#[test] +fn vop3_compare_forms_lower_to_wave_masks() { + let code = include_bytes!("../../../fixtures/rdna2/vop3-compare.bin"); + let compiled = compile(Architecture::Gfx1030, code).unwrap(); + assert_eq!( + compiled.ir, + include_str!("../../../fixtures/golden/vop3-compare.ir") + ); + assert_eq!( + compiled.msl, + include_str!("../../../fixtures/golden/vop3-compare.metal") + ); +} + #[test] fn vector_vcc_fixture_matches_ir_and_msl_goldens() { let code = include_bytes!("../../../fixtures/rdna2/vector-vcc.bin"); diff --git a/docs/assets/xenora-progress.svg b/docs/assets/xenora-progress.svg index 0eabd68..81b88cd 100644 --- a/docs/assets/xenora-progress.svg +++ b/docs/assets/xenora-progress.svg @@ -1,17 +1,17 @@ Xenora · recorded progress -Decoded gfx1030 forms: 158 of 158. Accepted Metal forms · Apple M5: 18 of 158. Accepted guest milestones · X1–X4: 4 of 4 +Decoded gfx1030 forms: 185 of 185. Accepted Metal forms · Apple M5: 18 of 185. Accepted guest milestones · X1–X4: 4 of 4 RECORDED FIXTURE PROGRESS Decoded gfx1030 forms -158 / 158 +185 / 185 Accepted Metal forms · Apple M5 -18 / 158 +18 / 185 - + Accepted guest milestones · X1–X4 4 / 4 diff --git a/docs/shaders/instruction-coverage.md b/docs/shaders/instruction-coverage.md index 1af78b2..cc01a14 100644 --- a/docs/shaders/instruction-coverage.md +++ b/docs/shaders/instruction-coverage.md @@ -17,6 +17,33 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin | `s_waitcnt vmcnt(0)` | SOPP, exact immediate `0x3f70`; other counters disabled by their maximum values (semantic registry) | 4 B | yes | yes | three-way passed | verified load wait | implemented | fixture verified | fixture verified | | `v_mov_b32_e32` | VOP1, VGPR destination, VGPR, normal SGPR (wave-uniform, known during translation), vcc_lo (known or a compare mask) or inline integer or literal source, plus the inline bit pattern for +1.0f | 4 or 8 B | yes | yes | three-way passed | constant or register value | implemented | fixture verified | fixture verified | | `v_add_nc_u32_e64` | VOP3, VGPR destination and two VGPR inputs, modifier fields clear, third source field encoded as inline zero | 8 B | yes | yes | three-way passed | MSL unsigned add | implemented | fixture verified | fixture verified | +| `v_mul_i32_i24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_i32_i24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_mul_hi_i32_i24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_hi_i32_i24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_mul_u32_u24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_u32_u24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_mul_hi_u32_u24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_hi_u32_u24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_min_i32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_min_i32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_max_i32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_max_i32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_min_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_min_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_max_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_max_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_xnor_b32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_xnor_b32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_sub_nc_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_sub_nc_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_subrev_nc_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_subrev_nc_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_lt_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_lt_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_eq_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_eq_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_le_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_le_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_gt_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_gt_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_ne_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ne_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_ge_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ge_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_f_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_f_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_t_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_t_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_lt_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_lt_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_eq_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_eq_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_le_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_le_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_gt_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_gt_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_ne_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ne_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_ge_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ge_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_f_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_f_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_t_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_t_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `buffer_store_dword` | MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags | 8 B | yes | yes | three-way passed | MSL store | implemented | fixture verified | fixture verified | | `s_waitcnt_vscnt null, 0` | SOPK, exact null source and zero immediate | 4 B | yes | yes | three-way passed | verified store wait | implemented | fixture verified | fixture verified | | `s_endpgm` | SOPP, zero immediate (semantic registry) | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified | diff --git a/docs/shaders/semantic-coverage.md b/docs/shaders/semantic-coverage.md index e035e06..c883e8c 100644 --- a/docs/shaders/semantic-coverage.md +++ b/docs/shaders/semantic-coverage.md @@ -32,11 +32,11 @@ acceptance remain outside the verified count. All results concern synthetic fixt | VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | | VOP1 | 81 | 7 | 6 | 7 | 7 | 7 | 1 | 1 | 11 | | VOP2 | 47 | 24 | 22 | 24 | 24 | 24 | 7 | 7 | 11 | -| VOP3 | 416 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 12 | +| VOP3 | 416 | 28 | 28 | 28 | 28 | 28 | 1 | 1 | 17 | | VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOPC | 190 | 28 | 44 | 44 | 44 | 44 | 0 | 0 | 9 | -| **Total** | 1465 | 142 | 152 | 162 | 158 | 158 | 18 | 18 | 78 | +| **Total** | 1465 | 169 | 179 | 189 | 185 | 185 | 18 | 18 | 83 | ## Unsupported operand variants @@ -58,6 +58,7 @@ The table counts distinct variant names per family across registry operand rules | VOP2 | `vop2_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` | | VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` | | VOP2 | `vop2_vgpr2` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` | +| VOP3 | `vop3_cmp_vgpr2` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc_hi`, `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` | | VOP3 | `vop3_vgpr2` | `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` | | VOPC | `vopc_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` | | VOPC | `vopc_vcc_half` | `src_exec`, `src_float_inline`, `src_literal`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` | diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index 94eee02..d918adf 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -48,20 +48,19 @@ file of its encoding (`rdna2/vop3.toml`) and has exactly these fields: | `of` | The `name` of the declared base form | | `family` | The encoding family of this variant; must differ from the form's | | `opcode` | The XML opcode in that family | -| `operands` | An operand rule of that family whose kind can encode the base form (today `vop3_vgpr2` for VOP2 vector forms) | +| `operands` | An operand rule of that family that can encode the base form (`vop3_vgpr2` for VOP2 vector forms, `vop3_cmp_vgpr2` for VOPC integer compares) | | `spec`, `verify` | As for a form | -Everything else (operation, signedness, effects, source order) is inherited -from the base form, and the XML check runs on that inherited declaration with -the variant's family, opcode and operand rule, so the VOP3 operand widths and -formats must agree with it. The generator emits one enum per variant rule (`VectorAluVop3Op` for -`vop3_vgpr2`) holding exactly the declared variants, with `from_word` (encoding +The variant inherits the operation, signedness, source order and SCC and EXEC +effects. Its operand rule determines where the result is written. The XML +check uses the variant's family, opcode and operand rule to validate the +inherited declaration. The generator emits one enum per variant rule +(`VectorAluVop3Op` or `VectorCompareVop3Op`) with `from_word` (encoding bits, then an explicit match on the OP field), `base()` (the inherited form), `assembly_name()` and `semantics()`, and one `FORMS` row per variant after the forms. Because the enum has no undeclared members, an instruction cannot name a -VOP3 encoding that does not exist. Every explicit XML operand of the variant, -destination included, must have the data format of the base operand in the same -role (destination, then the sources in rule order). A variant-only rule says so +VOP3 encoding that does not exist. Corresponding explicit XML operands must +have the same data format by role. A variant-only rule says so in the data (`variant_only = true`), so the RDNA2 planner does not count it as a rule that can host new forms. A variant-only rule (one marked `variant_of` in the generator) cannot be used by a @@ -75,7 +74,15 @@ the registry: VGPR destination, two VGPR sources, ABS, OP_SEL, CLAMP, OMOD and NEG clear, and SRC2 the assembler's unused inline zero. `v_add_nc_u32_e64` is its first variant; adding the VOP3 encoding of another VOP2 form under this rule is one `[[encoding_variant]]` entry. Wider VOP3 operand rules (scalar and inline -sources, legal modifiers) come with the VOP3 batch. +sources, legal modifiers) need separate rules. + +`vop3_cmp_vgpr2` uses the same VGPR source and modifier restrictions and +specifies a scalar destination. It requires a base form with a `lane_mask` +write to implicit VCC, and generates an `sdst_lane_mask` effect on the +variant row. The generator checks the base VCC output and the variant's +explicit scalar mask destination against the XML. An SDST of 106 selects +`vcc_lo`. See [the compare contract](vector-compare.md#11-vop3a-encoding-_e64) +for Wave32 lowering and allowed consumers. ## Fields @@ -199,7 +206,8 @@ integer as SRC0 and a VGPR pair as VSRC1. All three declare a `relation`, `scc = "unchanged"`, `vcc = "lane_mask"` and `wave = "wave32"`. The XML's implicit 64-bit VCC output must be present and is accounted for by `lane_mask`. Signedness still matters for `eq` and `lg`, because the MSL lowering casts signed operands. -`v_cmpx_*` (EXEC writes), the VOP3 encoding and Wave64 stay unsupported. +The VOP3A variants redirect the same Wave32 mask to SDST. EXEC-writing +compares (`v_cmpx_*`) and Wave64 stay unsupported. A SOPC compare must use an operand rule of the compare kind (`sopc_scalar`: two sources, no destination), a unary operation one of the unary kind (`sop1_sgpr`: diff --git a/docs/shaders/vector-compare.md b/docs/shaders/vector-compare.md index f988222..35dba87 100644 --- a/docs/shaders/vector-compare.md +++ b/docs/shaders/vector-compare.md @@ -122,7 +122,7 @@ this wave (all 32 except in a final partial wave, see 7). As an unsigned ## 4. Rejected (controlled translation/reference error, never a silent no-op) - V_CMPX_* (writes EXEC: divergent execution; needs its own contract). -- The VOP3 encoding of any compare (arbitrary SGPR destination, modifiers). +- VOP3A compares outside the integer subset in section 11. - SDWA and DPP forms; float compares; v_cmp_class. - 16-bit compares in the decoder and translator (the reference interpreters accept the subset in 2a). @@ -275,12 +275,11 @@ swapped signedness, without the EXEC mask, without the absent-lane bound (shader validation aborts on the out-of-range read) or with an inverted join. The 32-bit readback evidence is local agreement with a specification-derived -reference on Apple M5 Pro. The 16-bit compiler evidence is CPU-only. -There is no RDNA 2 or Xbox hardware evidence. +reference on Apple M5 Pro. There is no RDNA 2 or Xbox hardware evidence. ## 10. Limitations -- Wave32 only. No `v_cmpx`, VOP3, SDWA, DPP or float compares. +- Wave32 only. No `v_cmpx`, SDWA, DPP or float compares. VOP3 encodings cover the 32-bit compares only. - A lane-derived VCC_LO cannot reach EXEC or any scalar instruction, so there is no divergent execution. That needs its own contract. - The skipped region of a runtime `s_cbranch_vccz` holds only integer vector @@ -289,3 +288,38 @@ There is no RDNA 2 or Xbox hardware evidence. - Each thread recomputes up to 32 lanes per compare. The cost grows with the compare's dependency chain. That is fine for fixtures, and no performance is claimed. + +## 11. VOP3A encoding (`_e64`) + +All sixteen 32-bit signed and unsigned compares in section 2 also have a 64-bit +VOP3A encoding. The pinned AMD XML supplies each opcode. Bits 7:0 of the first +word are the scalar destination selector (SDST), in the field named VDST. +Selectors 0–105 name scalar general-purpose registers (SGPRs), and 106 names +`vcc_lo`. All other destinations are rejected. Both SRC0 and SRC1 must name +vector general-purpose registers (VGPRs), and the unused SRC2 must be the +assembler's inline-zero selector (128). ABS, OP_SEL, CLAMP, OMOD and NEG must +be clear. The guide describes CLAMP on compares as enabling floating-point +exception signaling (§6.5, p. 48 and §12.9.1, p. 162). + +The AMD guide's compare-specific text (§3.9, pp. 19–20 and §13.3.3, p. 252) +specifies an SGPR destination for this encoding. The generic VDST label in +§12.9.1 (p. 162) and §13.3.4 Table 82 (pp. 257–258) describes the VOP3A field +as a VGPR destination. The pinned XML identifies VDST for these compares as +`OPR_SREG`, with the Wave64 pair described by `FMT_NUM_M64`. The Wave32 write +occupies one 32-bit SGPR. The guide defines 32 work-items in §2.1 (pp. 7–8), +32-bit SGPRs in §3.1 Table 2 (p. 12) and one compare result bit per lane in +§12.9 (p. 150). Wave64 stays unsupported. + +LLVM 23 `llvm-mc` for gfx1030 with `+wavefrontsize32` assembles +`v_cmp_eq_u32_e64 s4, v1, v2` as bytes `04 00 c2 d4 01 05 02 02`. +Selecting `vcc_lo` changes the first byte to `6a`. The decoder tests cover +the assembler's words for all sixteen forms. This is encoding evidence. + +The compare replaces all 32 bits of SDST with the lane mask from section 3, +including zero bits for inactive and absent lanes. It leaves SCC and EXEC +unchanged. VCC is written only when SDST selects `vcc_lo`, which uses the +same lowering and consumers as the VOPC form, including `s_cbranch_vccz`. +Every other SDST is tracked as a runtime-only SGPR result, including under +empty EXEC. Translation rejects later reads of that result, including reads +through resource descriptors. The runtime branch region rules in section 6 +also apply here. diff --git a/docs/status.toml b/docs/status.toml index 8040ec4..c1c44d8 100644 --- a/docs/status.toml +++ b/docs/status.toml @@ -87,6 +87,330 @@ recognized = true decoded = true llvm = "three-way passed" +[[instruction]] +form = "v_mul_i32_i24_e64" +encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_i32_i24_e32`" +representation = "8 B" +lowering = "per-thread typed integer template of the VOP2 form" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_mul_hi_i32_i24_e64" +encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_hi_i32_i24_e32`" +representation = "8 B" +lowering = "per-thread typed integer template of the VOP2 form" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_mul_u32_u24_e64" +encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_u32_u24_e32`" +representation = "8 B" +lowering = "per-thread typed integer template of the VOP2 form" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_mul_hi_u32_u24_e64" +encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_hi_u32_u24_e32`" +representation = "8 B" +lowering = "per-thread typed integer template of the VOP2 form" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_min_i32_e64" +encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_min_i32_e32`" +representation = "8 B" +lowering = "per-thread typed integer template of the VOP2 form" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_max_i32_e64" +encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_max_i32_e32`" +representation = "8 B" +lowering = "per-thread typed integer template of the VOP2 form" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_min_u32_e64" +encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_min_u32_e32`" +representation = "8 B" +lowering = "per-thread typed integer template of the VOP2 form" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_max_u32_e64" +encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_max_u32_e32`" +representation = "8 B" +lowering = "per-thread typed integer template of the VOP2 form" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_xnor_b32_e64" +encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_xnor_b32_e32`" +representation = "8 B" +lowering = "per-thread typed integer template of the VOP2 form" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_sub_nc_u32_e64" +encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_sub_nc_u32_e32`" +representation = "8 B" +lowering = "per-thread typed integer template of the VOP2 form" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_subrev_nc_u32_e64" +encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_subrev_nc_u32_e32`" +representation = "8 B" +lowering = "per-thread typed integer template of the VOP2 form" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_lt_i32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_lt_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_eq_i32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_eq_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_le_i32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_le_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_gt_i32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_gt_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_ne_i32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ne_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_ge_i32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ge_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_f_i32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_f_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_t_i32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_t_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_lt_u32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_lt_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_eq_u32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_eq_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_le_u32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_le_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_gt_u32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_gt_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_ne_u32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ne_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_ge_u32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ge_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_f_u32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_f_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_t_u32_e64" +encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_t_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error" +representation = "8 B" +lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + [[instruction]] form = "buffer_store_dword" encoding = "MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags" diff --git a/fixtures/golden/vop3-compare.ir b/fixtures/golden/vop3-compare.ir new file mode 100644 index 0000000..e350208 --- /dev/null +++ b/fixtures/golden/vop3-compare.ir @@ -0,0 +1,59 @@ +0000: t0 = load.u32 input[index] +000c: t1 = const.u32 0x00000000 +0010: t2 = const.u32 0x00000001 +0014: t3 = const.u32 0x40000001 +001c: t4 = const.u32 0x00000001 +0020: t5 = wave.mask v_cmp_f_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff +002c: t6 = lshl.b32 t1, t2 +0030: t7 = xor.b32 t6, t5 +0034: t8 = wave.mask v_cmp_lt_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff +0040: t9 = lshl.b32 t7, t2 +0044: t10 = xor.b32 t9, t8 +0048: t11 = wave.mask v_cmp_eq_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff +0054: t12 = lshl.b32 t10, t2 +0058: t13 = xor.b32 t12, t11 +005c: t14 = wave.mask v_cmp_le_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff +0068: t15 = lshl.b32 t13, t2 +006c: t16 = xor.b32 t15, t14 +0070: t17 = wave.mask v_cmp_gt_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff +007c: t18 = lshl.b32 t16, t2 +0080: t19 = xor.b32 t18, t17 +0084: t20 = wave.mask v_cmp_ne_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff +0090: t21 = lshl.b32 t19, t2 +0094: t22 = xor.b32 t21, t20 +0098: t23 = wave.mask v_cmp_ge_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff +00a4: t24 = lshl.b32 t22, t2 +00a8: t25 = xor.b32 t24, t23 +00ac: t26 = wave.mask v_cmp_t_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff +00b8: t27 = lshl.b32 t25, t2 +00bc: t28 = xor.b32 t27, t26 +00c0: t29 = wave.mask v_cmp_f_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff +00cc: t30 = lshl.b32 t28, t2 +00d0: t31 = xor.b32 t30, t29 +00d4: t32 = wave.mask v_cmp_lt_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff +00e0: t33 = lshl.b32 t31, t2 +00e4: t34 = xor.b32 t33, t32 +00e8: t35 = wave.mask v_cmp_eq_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff +00f4: t36 = lshl.b32 t34, t2 +00f8: t37 = xor.b32 t36, t35 +00fc: t38 = wave.mask v_cmp_le_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff +0108: t39 = lshl.b32 t37, t2 +010c: t40 = xor.b32 t39, t38 +0110: t41 = wave.mask v_cmp_gt_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff +011c: t42 = lshl.b32 t40, t2 +0120: t43 = xor.b32 t42, t41 +0124: t44 = wave.mask v_cmp_ne_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff +0130: t45 = lshl.b32 t43, t2 +0134: t46 = xor.b32 t45, t44 +0138: t47 = wave.mask v_cmp_ge_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff +0144: t48 = lshl.b32 t46, t2 +0148: t49 = xor.b32 t48, t47 +014c: t50 = wave.mask v_cmp_t_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff +0158: t51 = lshl.b32 t49, t2 +015c: t52 = xor.b32 t51, t50 +0160: t53 = wave.mask v_cmp_eq_u32_e64 t0, t3 -> s8 exec=0xffffffff +0168: t54 = wave.mask v_cmp_gt_u32_e64 t3, t0 -> vcc_lo exec=0xffffffff +0170: branch.vccz t54 -> 0x0178 +0174: t56 = xor.b32 t4, t52 +0178: t57 = join.vccz t54, t56, t52 +0178: store.u32 output[index], t57 diff --git a/fixtures/golden/vop3-compare.metal b/fixtures/golden/vop3-compare.metal new file mode 100644 index 0000000..07596d1 --- /dev/null +++ b/fixtures/golden/vop3-compare.metal @@ -0,0 +1,188 @@ +#include +using namespace metal; +kernel void xenora_compute( + device const uint* input [[buffer(0)]], + device uint* output [[buffer(1)]], + uint index [[thread_position_in_grid]], + uint grid [[threads_per_grid]]) { + uint t0 = input[index]; + uint t1 = 0x00000000u; + uint t2 = 0x00000001u; + uint t3 = 0x40000001u; + uint t4 = 0x00000001u; + uint t5 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (false) ? 1u : 0u; + t5 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t6 = t1 << (t2 & 31u); + uint t7 = t6 ^ t5; + uint t8 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint l0 = input[lane_index]; + uint pass = (as_type(l0) < as_type(t3)) ? 1u : 0u; + t8 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t9 = t7 << (t2 & 31u); + uint t10 = t9 ^ t8; + uint t11 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint l0 = input[lane_index]; + uint pass = (as_type(l0) == as_type(t3)) ? 1u : 0u; + t11 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t12 = t10 << (t2 & 31u); + uint t13 = t12 ^ t11; + uint t14 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint l0 = input[lane_index]; + uint pass = (as_type(l0) <= as_type(t3)) ? 1u : 0u; + t14 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t15 = t13 << (t2 & 31u); + uint t16 = t15 ^ t14; + uint t17 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint l0 = input[lane_index]; + uint pass = (as_type(l0) > as_type(t3)) ? 1u : 0u; + t17 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t18 = t16 << (t2 & 31u); + uint t19 = t18 ^ t17; + uint t20 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint l0 = input[lane_index]; + uint pass = (as_type(l0) != as_type(t3)) ? 1u : 0u; + t20 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t21 = t19 << (t2 & 31u); + uint t22 = t21 ^ t20; + uint t23 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint l0 = input[lane_index]; + uint pass = (as_type(l0) >= as_type(t3)) ? 1u : 0u; + t23 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t24 = t22 << (t2 & 31u); + uint t25 = t24 ^ t23; + uint t26 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (true) ? 1u : 0u; + t26 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t27 = t25 << (t2 & 31u); + uint t28 = t27 ^ t26; + uint t29 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (false) ? 1u : 0u; + t29 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t30 = t28 << (t2 & 31u); + uint t31 = t30 ^ t29; + uint t32 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint l0 = input[lane_index]; + uint pass = (l0 < t3) ? 1u : 0u; + t32 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t33 = t31 << (t2 & 31u); + uint t34 = t33 ^ t32; + uint t35 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint l0 = input[lane_index]; + uint pass = (l0 == t3) ? 1u : 0u; + t35 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t36 = t34 << (t2 & 31u); + uint t37 = t36 ^ t35; + uint t38 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint l0 = input[lane_index]; + uint pass = (l0 <= t3) ? 1u : 0u; + t38 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t39 = t37 << (t2 & 31u); + uint t40 = t39 ^ t38; + uint t41 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint l0 = input[lane_index]; + uint pass = (l0 > t3) ? 1u : 0u; + t41 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t42 = t40 << (t2 & 31u); + uint t43 = t42 ^ t41; + uint t44 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint l0 = input[lane_index]; + uint pass = (l0 != t3) ? 1u : 0u; + t44 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t45 = t43 << (t2 & 31u); + uint t46 = t45 ^ t44; + uint t47 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint l0 = input[lane_index]; + uint pass = (l0 >= t3) ? 1u : 0u; + t47 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t48 = t46 << (t2 & 31u); + uint t49 = t48 ^ t47; + uint t50 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (true) ? 1u : 0u; + t50 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t51 = t49 << (t2 & 31u); + uint t52 = t51 ^ t50; + uint t53 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint l0 = input[lane_index]; + uint pass = (l0 == t3) ? 1u : 0u; + t53 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t54 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint l0 = input[lane_index]; + uint pass = (t3 > l0) ? 1u : 0u; + t54 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t56 = t4 ^ t52; + uint t57 = t54 != 0u ? t56 : t52; + output[index] = t57; +} diff --git a/fixtures/golden/vop3-integer.ir b/fixtures/golden/vop3-integer.ir new file mode 100644 index 0000000..c1111c6 --- /dev/null +++ b/fixtures/golden/vop3-integer.ir @@ -0,0 +1,23 @@ +0000: t0 = load.u32 input[index] +000c: t1 = mul24.i32 t0, t0 +0014: t2 = mulhi24.i32 t1, t0 +001c: t3 = mul24.u32 t1, t0 +0024: t4 = mulhi24.u32 t3, t0 +002c: t5 = min.i32 t0, t1 +0034: t6 = max.i32 t0, t3 +003c: t7 = min.u32 t2, t0 +0044: t8 = max.u32 t4, t1 +004c: t9 = xnor.b32 t0, t4 +0054: t10 = sub.u32 t5, t9 +005c: t11 = sub.u32 t8, t0 +0064: t12 = xor.b32 t1, t2 +0068: t13 = xor.b32 t3, t12 +006c: t14 = xor.b32 t4, t13 +0070: t15 = xor.b32 t5, t14 +0074: t16 = xor.b32 t6, t15 +0078: t17 = xor.b32 t7, t16 +007c: t18 = xor.b32 t8, t17 +0080: t19 = xor.b32 t9, t18 +0084: t20 = xor.b32 t10, t19 +0088: t21 = xor.b32 t11, t20 +008c: store.u32 output[index], t21 diff --git a/fixtures/golden/vop3-integer.metal b/fixtures/golden/vop3-integer.metal new file mode 100644 index 0000000..5311339 --- /dev/null +++ b/fixtures/golden/vop3-integer.metal @@ -0,0 +1,30 @@ +#include +using namespace metal; +kernel void xenora_compute( + device const uint* input [[buffer(0)]], + device uint* output [[buffer(1)]], + uint index [[thread_position_in_grid]]) { + uint t0 = input[index]; + uint t1 = as_type((as_type(t0 << 8u) >> 8)) * as_type((as_type(t0 << 8u) >> 8)); + uint t2 = as_type(mulhi((as_type(t1 << 8u) >> 8), (as_type(t0 << 8u) >> 8))); + uint t3 = (t1 & 0x00ffffffu) * (t0 & 0x00ffffffu); + uint t4 = mulhi((t3 & 0x00ffffffu), (t0 & 0x00ffffffu)); + uint t5 = as_type(min(as_type(t0), as_type(t1))); + uint t6 = as_type(max(as_type(t0), as_type(t3))); + uint t7 = min(t2, t0); + uint t8 = max(t4, t1); + uint t9 = ~(t0 ^ t4); + uint t10 = t5 - t9; + uint t11 = t8 - t0; + uint t12 = t1 ^ t2; + uint t13 = t3 ^ t12; + uint t14 = t4 ^ t13; + uint t15 = t5 ^ t14; + uint t16 = t6 ^ t15; + uint t17 = t7 ^ t16; + uint t18 = t8 ^ t17; + uint t19 = t9 ^ t18; + uint t20 = t10 ^ t19; + uint t21 = t11 ^ t20; + output[index] = t21; +} diff --git a/fixtures/rdna2/vop3-compare.bin b/fixtures/rdna2/vop3-compare.bin new file mode 100644 index 0000000000000000000000000000000000000000..c45cd9185670ec62789a17f39beae0f13bffaa54 GIT binary patch literal 392 zcmZwAyA^^k00q#OM}p{a2u855qS1L$F+on^2OBrC2rB9V48S5DZR~vQZ7%B71cTUa z&Nu${2Iu!FFpuuj-XSTF1<>?Z6kY!LPk e_7wK|vkJc#!&nrgL6=Ks8`SLtnh3lvK+0bzV@YNJ literal 0 HcmV?d00001 diff --git a/fixtures/rdna2/vop3-compare.s b/fixtures/rdna2/vop3-compare.s new file mode 100644 index 0000000..10ec31c --- /dev/null +++ b/fixtures/rdna2/vop3-compare.s @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Original Wave32 VOP3A vectors for the sixteen integer compare encoding variants. +// Each compare writes vcc_lo through the explicit 64-bit destination field +// (one writes s8), and each wave folds the masks into v2 as +// v2 = (v2 << 1) ^ mask. Sources are VGPRs. This fixture is checked through +// its IR and MSL goldens; the per-lane expected values for these forms are in +// tests/validation/tests/vop3_compare.rs. +.text +buffer_load_dword v1, v0, s[0:3], 0 idxen // Load the lane's input word. +s_waitcnt vmcnt(0) // Wait for the load. +v_mov_b32_e32 v2, 0 // Clear the accumulator. +v_mov_b32_e32 v5, 1 // Shift count for the fold. +v_mov_b32_e32 v3, 0x40000001 // Second source: inputs fall below, on and above it. +v_mov_b32_e32 v6, 1 // Low bit for the branch fold. +v_cmp_f_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_lt_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_eq_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_le_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_gt_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_ne_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_ge_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_t_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_f_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_lt_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_eq_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_le_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_gt_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_ne_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_ge_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_t_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001. +v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR. +v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator. +v_xor_b32_e32 v2, v2, v4 // Fold the mask. +v_cmp_eq_u32_e64 s8, v1, v3 // A mask into a plain SGPR, never read. +v_cmp_gt_u32_e64 vcc_lo, v3, v1 // Unsigned 0x40000001 > input. +s_cbranch_vccz 1 // Skip the next fold when no lane passed. +v_xor_b32_e32 v2, v6, v2 // Flip the low bit when some lane passed. +buffer_store_dword v2, v0, s[4:7], 0 idxen // Store the folded word. +s_waitcnt_vscnt null, 0 // Wait for the store. +s_endpgm // End the program. diff --git a/fixtures/rdna2/vop3-integer.bin b/fixtures/rdna2/vop3-integer.bin new file mode 100644 index 0000000000000000000000000000000000000000..a2c4c8c84c90f06d281e8b4a2ac0f03530cff114 GIT binary patch literal 156 zcmW;DF%E)26a>)uv$(LV7K%2Q7%FY8X}l6gz@8gfaEjk^5wlJ#UM4fiV0dmY%+qUG ziR2c@fYzz3kpEe*_ewqD=(ZzkoZJ%Gp!1+T;p|0wi!bk literal 0 HcmV?d00001 diff --git a/fixtures/rdna2/vop3-integer.s b/fixtures/rdna2/vop3-integer.s new file mode 100644 index 0000000..55c16a0 --- /dev/null +++ b/fixtures/rdna2/vop3-integer.s @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Original VOP3A vectors for the eleven per-lane integer encoding variants. +// All arithmetic operands are vector general-purpose registers (VGPRs) and every result +// depends on the lane's own input word. XOR folds the results into one word. +.text +buffer_load_dword v1, v0, s[0:3], 0 idxen // Load the lane's input word. +s_waitcnt vmcnt(0) // Wait for the load. +v_mul_i32_i24_e64 v2, v1, v1 // Multiply signed 24-bit inputs and keep the low word. +v_mul_hi_i32_i24_e64 v3, v2, v1 // Multiply signed 24-bit inputs and keep the high word. +v_mul_u32_u24_e64 v4, v2, v1 // Multiply unsigned 24-bit inputs and keep the low word. +v_mul_hi_u32_u24_e64 v255, v4, v1 // Multiply unsigned 24-bit inputs and keep the high word. +v_min_i32_e64 v6, v1, v2 // Select the signed minimum. +v_max_i32_e64 v7, v1, v4 // Select the signed maximum. +v_min_u32_e64 v8, v3, v1 // Select the unsigned minimum. +v_max_u32_e64 v9, v255, v2 // Select the unsigned maximum. +v_xnor_b32_e64 v10, v1, v255 // Complement the XOR. +v_sub_nc_u32_e64 v11, v6, v10 // Subtract the second source from the first. +v_subrev_nc_u32_e64 v1, v1, v9 // Subtract the first source from the second, overwriting the first. +v_xor_b32_e32 v13, v2, v3 // Start the XOR fold. +v_xor_b32_e32 v13, v4, v13 // Fold the unsigned product low word. +v_xor_b32_e32 v13, v255, v13 // Fold the unsigned product high word. +v_xor_b32_e32 v13, v6, v13 // Fold the signed minimum. +v_xor_b32_e32 v13, v7, v13 // Fold the signed maximum. +v_xor_b32_e32 v13, v8, v13 // Fold the unsigned minimum. +v_xor_b32_e32 v13, v9, v13 // Fold the unsigned maximum. +v_xor_b32_e32 v13, v10, v13 // Fold the XNOR result. +v_xor_b32_e32 v13, v11, v13 // Fold the subtraction result. +v_xor_b32_e32 v13, v1, v13 // Fold the reverse subtraction result. +buffer_store_dword v13, v0, s[4:7], 0 idxen // Store the folded word. +s_waitcnt_vscnt null, 0 // Wait for the store. +s_endpgm // End the program. diff --git a/scripts/assemble-fixture.sh b/scripts/assemble-fixture.sh index e6c001d..02d516d 100755 --- a/scripts/assemble-fixture.sh +++ b/scripts/assemble-fixture.sh @@ -12,7 +12,7 @@ case "${1:-}" in esac for name in add bitwise-branch float-exact or shifts ashr \ - x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft vector-vcc vector-unary vector-compare-64 vector-compare-16; do + x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft vector-vcc vop3-integer vop3-compare vector-unary vector-compare-64 vector-compare-16; do "$llvm_bin/llvm-mc" -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \ -filetype=obj "fixtures/rdna2/$name.s" -o "$scratch/$name.o" "$llvm_bin/llvm-objcopy" -O binary --only-section=.text "$scratch/$name.o" "$scratch/$name.bin" diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index 848ac86..f3a2b60 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -177,7 +177,7 @@ def snapshot(): ["SRC2", [[50, 9]]], ["OMOD", [[59, 2]]], ["NEG", [[61, 3]]], ], "identifier_mask": 0xFFFF0000, - "identifiers": [0xD4000000 | (op << 16) for op in (265, 273, 295)], + "identifiers": [0xD4000000 | (op << 16) for op in (129, 265, 273, 295)], } # Values copied from the AMD XML snapshot: VOP3 encodings of VOP2 forms. for name, opcode, data_format in ( @@ -191,6 +191,14 @@ def snapshot(): ["SRC1", data_format, "OPR_SRC_NOLDS", 32, True, False, False, True], ], } + variants[("V_CMP_LT_I32", "ENC_VOP3")] = { + "instruction": "V_CMP_LT_I32", "encoding": "ENC_VOP3", "opcode": 129, + "operands": [ + ["VDST", "FMT_NUM_M64", "OPR_SREG", 64, False, True, False, True], + ["SRC0", I32, "OPR_SRC", 32, True, False, False, True], + ["SRC1", I32, "OPR_SRC_NOLDS", 32, True, False, False, True], + ], + } return { "source": {"sha256": SHA}, "encodings": { @@ -309,6 +317,18 @@ def _variant(of, opcode): } +def compare_variants(): + reg = vector_compares() + rule = gen.OPERAND_RULES["vop3_cmp_vgpr2"] + reg["operand_rules"]["vop3_cmp_vgpr2"] = dict( + copy.deepcopy(rule["shape"]), unsupported=sorted(rule["unsupported"]) + ) + reg["encoding_variant"] = [ + dict(_variant("V_CMP_LT_I32", 129), operands="vop3_cmp_vgpr2") + ] + return reg + + def compares(): reg = registry() reg["form"] += [ @@ -860,6 +880,25 @@ class Validate(unittest.TestCase): def test_accepts_encoding_variants(self): self.assertEqual(self.errors(variants()), []) + def test_compare_variant_routes_mask_to_sdst(self): + reg = compare_variants() + self.assertEqual(self.errors(reg), []) + row = gen.variant_row(reg, reg["encoding_variant"][0]) + self.assertEqual((row["vcc"], row["width"], row["wave"]), ("sdst_lane_mask", 32, "wave32")) + + def test_rejects_mismatched_compare_variant_destination(self): + reg = compare_variants() + form(reg, "V_CMP_LT_I32")["vcc"] = "unchanged" + self.rejects(reg, "requires a base destination contract of lane_mask, got unchanged") + + reg = compare_variants() + reg["operand_rules"]["vop3_cmp_vgpr2"]["dst"]["class"] = "vgpr" + self.rejects(reg, "operand rule vop3_cmp_vgpr2: declaration differs") + + snap = snapshot() + snap["variants"][("V_CMP_LT_I32", "ENC_VOP3")]["operands"][0][2] = "OPR_VGPR" + self.rejects(compare_variants(), "VDST is not a scalar mask destination in the XML", snap) + def test_rejects_a_variant_of_an_undeclared_form(self): reg = variants() reg["encoding_variant"].append(_variant("V_MUL_HI_I32_I24", 266)) diff --git a/tests/validation/independent_ref.rs b/tests/validation/independent_ref.rs index af5061c..161f7e5 100644 --- a/tests/validation/independent_ref.rs +++ b/tests/validation/independent_ref.rs @@ -22,7 +22,7 @@ //! MUL_I32_I24, MUL_HI_I32_I24, MUL_U32_U24, MUL_HI_U32_U24, MIN/MAX (I32, //! U32), XNOR and ADD/SUB/SUBREV_NC_U32 (any SRC0 a VOPC compare takes; a //! shift-and-add multiplier and floor division for the high half, the ripple -//! adder for add and subtract), VOP3 add-no-carry, MUBUF +//! adder for add and subtract), VOP3A integer arithmetic and compares, MUBUF //! load/store and the two waits plus `s_endpgm`. Anything else is a controlled //! error. The arithmetic shift is evaluated as a floor division by a power of //! two rather than with a host signed shift, so the oracle does not share the @@ -72,18 +72,20 @@ enum Insn { /// SOPK opcode 0 or 2-16 on SGPR `SDST` (s0-s105) with the raw SIMM16. SImm(u32, u8, u16), BranchScc0(usize), - BranchMaskZero { + BranchMask { target: usize, register: usize, + nonzero: bool, }, Branch(usize), VMov(u8, Src), VMovFromSgpr(u8, u8), /// `v_mov_b32_e32 vD, vcc_lo`. VMovFromVcc(u8), - /// VOPC compare into VCC_LO: relation 0 f, 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge, 7 t. + /// Integer vector compare into `dst`: relation 0 f, 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge, 7 t. /// `bits` is 16, 32 or 64; 64-bit register operands name the low register of a pair. VCmp { + dst: u8, relation: u8, signed: bool, bits: u32, @@ -207,6 +209,7 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result, String> return Ok(lanes.iter().map(|lane| lane.written.unwrap()).collect()); } Insn::VCmp { + dst, relation, signed, bits, @@ -226,10 +229,12 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result, String> offset, ) .map(|mask| { - sgpr[106] = Some(mask); - // VCC_HI has no known value after a compare (contract 3). - sgpr[107] = None; - vcc_lane_derived = execution_mask != 0; + sgpr[usize::from(dst)] = Some(mask); + if dst == 106 { + // VCC_HI has no known value after a VCC compare (contract 3). + sgpr[107] = None; + vcc_lane_derived = execution_mask != 0; + } None }) } @@ -301,12 +306,17 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result, String> index_of(program, target, offset).map(Some) } }), - Insn::BranchMaskZero { target, register } => { + Insn::BranchMask { + target, + register, + nonzero, + } => { + let takes = |mask| (mask != 0) == nonzero; if register == 106 && vcc_lane_derived { let live = lanes.iter().find(|lane| lane.error.is_none()).unwrap(); check_runtime_region(program, pc, target, live, &sgpr, execution_mask, offset) .and_then(|()| { - if sgpr[106] == Some(0) { + if takes(sgpr[106].unwrap()) { index_of(program, target, offset).map(Some) } else { Ok(None) @@ -316,7 +326,7 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result, String> sgpr[register] .ok_or_else(|| format!("{offset:#x}: uninitialized mask")) .and_then(|mask| { - if mask == 0 { + if takes(mask) { index_of(program, target, offset).map(Some) } else { Ok(None) @@ -690,7 +700,7 @@ fn read_vgpr(lane: &Lane, reg: u8, offset: usize) -> Result { lane.vgpr[reg as usize].ok_or_else(|| format!("{offset:#x}: uninitialized v{reg}")) } -/// Evaluate one VOPC compare for the whole wave and return the new VCC_LO. +/// Evaluate one integer vector compare for the whole wave and return its mask. fn compare( lanes: &[Lane], sgpr: &[Option; 128], @@ -1214,7 +1224,7 @@ fn decode(code: &[u8]) -> Result, String> { offset += len; } for &(at, insn) in &program { - if let Insn::Branch(target) | Insn::BranchScc0(target) | Insn::BranchMaskZero { target, .. } = + if let Insn::Branch(target) | Insn::BranchScc0(target) | Insn::BranchMask { target, .. } = insn && !program.iter().any(|(boundary, _)| *boundary == target) { @@ -1315,6 +1325,7 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> { return Err(fail("unsupported VOPC operand")); } let insn = Insn::VCmp { + dst: 106, relation: relation as u8, signed, bits, @@ -1337,14 +1348,34 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> { let insn = Insn::VInt(vop2_op, (first >> 17) as u8, src0, (first >> 9) as u8); return Ok((insn, len)); } - if first & 0xffff_0000 == 0xd525_0000 { - let second = word(code, offset + 4)?; + if first >> 26 == 0b110101 { + let dst = first as u8; + let opcode = (first >> 16) & 0x3ff; + let second = word(code, offset + 4).map_err(|_| fail("truncated VOP3A"))?; let src0 = second & 0x1ff; let src1 = (second >> 9) & 0x1ff; if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 { - return Err(fail("bad VOP3 add form")); + return Err(fail("unsupported VOP3A modifiers or sources")); } - return Ok((Insn::VAddNc(first as u8, src0 as u8, src1 as u8), 8)); + // Guide §§3.9, 12.7.1 and 12.9.1: re-encoded VOP2 writes a VGPR, + // while VOPC uses the destination field for the scalar mask. + let (src0, src1) = (src0 as u8, src1 as u8); + let insn = match opcode { + 128..=135 | 192..=199 if dst <= 106 => Insn::VCmp { + dst, + relation: (opcode % 8) as u8, + signed: opcode < 192, + bits: 32, + src0: CmpSrc::Vgpr(src0), + src1, + }, + 293 => Insn::VAddNc(dst, src0, src1), + 265..=268 | 273..=276 | 286 | 294..=295 => { + Insn::VInt(opcode - 256, dst, CmpSrc::Vgpr(src0), src1) + } + _ => return Err(fail("unsupported VOP3A opcode or destination")), + }; + return Ok((insn, 8)); } // SOP1: ENCODING 0b10_1111101 in bits 23-31, SDST 16-22, OP 8-15. let sop1_op = (first >> 8) & 0xff; @@ -1429,15 +1460,16 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> { return Ok((Insn::BranchScc0(branch_target(first, offset)?), 4)); } let tested_register = match first >> 16 { - 0xbf86 => Some(106), + 0xbf86 | 0xbf87 => Some(106), 0xbf88 => Some(126), _ => None, }; if let Some(register) = tested_register { return Ok(( - Insn::BranchMaskZero { + Insn::BranchMask { target: branch_target(first, offset)?, register, + nonzero: first >> 16 == 0xbf87, }, 4, )); diff --git a/tests/validation/tests/vop3_compare.rs b/tests/validation/tests/vop3_compare.rs new file mode 100644 index 0000000..39c38b9 --- /dev/null +++ b/tests/validation/tests/vop3_compare.rs @@ -0,0 +1,302 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Wave32 VOP3A integer compares. Guide §3.9 permits an SGPR destination in +//! the 64-bit encoding and describes the fully rewritten per-lane mask. +//! A Wave32 mask has 32 bits (§2.1), so SDST consumes one 32-bit SGPR (§5.2). +//! The opcode relations are in §12.9, the re-encoding in §12.9.1, and the +//! VOP3A fields in §13.3.4. These are spec-derived expectations. + +#[path = "operand_domains/harness.rs"] +#[allow(dead_code)] +mod harness; +#[path = "../independent_ref.rs"] +mod independent_ref; + +use harness::{Case, words}; + +const FORMS: [(u32, &str); 16] = [ + (128, "v_cmp_f_i32"), + (129, "v_cmp_lt_i32"), + (130, "v_cmp_eq_i32"), + (131, "v_cmp_le_i32"), + (132, "v_cmp_gt_i32"), + (133, "v_cmp_ne_i32"), + (134, "v_cmp_ge_i32"), + (135, "v_cmp_t_i32"), + (192, "v_cmp_f_u32"), + (193, "v_cmp_lt_u32"), + (194, "v_cmp_eq_u32"), + (195, "v_cmp_le_u32"), + (196, "v_cmp_gt_u32"), + (197, "v_cmp_ne_u32"), + (198, "v_cmp_ge_u32"), + (199, "v_cmp_t_u32"), +]; +const VALUES: [u32; 10] = [ + 0, + 1, + 0x7fff_ffff, + 0x8000_0000, + u32::MAX, + 0x00ff_ffff, + 0x0080_0000, + 0xff80_0000, + 0x0100_0001, + 0xff00_0003, +]; +const MASKS: [u32; 4] = [u32::MAX, 0x5555_5555, 0x8000_0001, 0]; + +fn passes(op: u32, a: u32, b: u32) -> bool { + let operand = |value: u32| { + if op < 192 { + i64::from(value as i32) + } else { + i64::from(value) + } + }; + let (a, b) = (operand(a), operand(b)); + match op & 7 { + // D[threadId] = 0. + 0 => false, + // D[threadId] = (S0 < S1). + 1 => a < b, + // D[threadId] = (S0 == S1). + 2 => a == b, + // D[threadId] = (S0 <= S1). + 3 => a <= b, + // D[threadId] = (S0 > S1). + 4 => a > b, + // D[threadId] = (S0 <> S1). + 5 => a != b, + // D[threadId] = (S0 >= S1). + 6 => a >= b, + // D[threadId] = 1. + _ => true, + } +} + +fn expected_mask(op: u32, exec: u32, wave: &[u32], bound: u32, reverse: bool) -> u32 { + // §3.9: VCC[n] = EXEC[n] & (test passed for thread[n]). + // §3.9 uses the same result for the alternate scalar destination. + wave.iter().enumerate().fold(0, |mask, (n, &x)| { + let (a, b) = if reverse { (bound, x) } else { (x, bound) }; + mask | (exec & (u32::from(passes(op, a, b)) << n)) + }) +} + +fn vop3(op: u32, dst: u32, reverse: bool) -> [u32; 2] { + let (a, b) = if reverse { (511, 257) } else { (257, 511) }; + [0xd400_0000 | op << 16 | dst, a | b << 9 | 128 << 18] +} + +fn smov(dst: u32, value: u32) -> [u32; 2] { + [0xbe80_03ff | dst << 16, value] +} + +fn setup(bound: u32, exec: u32) -> Vec { + let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70]; // load v1 + code.extend([0x7ffe_02ff, bound]); // v255 = literal + code.extend(smov(126, exec)); + code +} + +fn store(mut code: Vec) -> Vec { + code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]); + words(&code) +} + +fn mask_cases() -> Vec { + let mut cases = Vec::new(); + for (op, name) in FORMS { + for bound in VALUES { + for reverse in [false, true] { + for exec in MASKS { + for (lanes, dst) in [(7, 106), (32, 106), (45, 106), (45, 0), (45, 105)] { + let mut code = setup(bound, exec); + // Give the old VCC bits on both sides of EXEC. + code.extend(smov(106, 0xa5a5_5a5a)); + code.extend(vop3(op, dst, reverse)); + code.extend([0xbefe_03c1, 0x7e04_0200 | dst]); + let input: Vec<_> = VALUES.into_iter().cycle().take(lanes).collect(); + let expected = input + .chunks(32) + .flat_map(|wave| { + let mask = expected_mask(op, exec, wave, bound, reverse); + std::iter::repeat_n(mask, wave.len()) + }) + .collect(); + cases.push(Case { + form: name, + family: if dst == 106 { "vcc_lo" } else { "sgpr" }, + label: format!("{name} s{dst}, bound={bound:#x}, reverse={reverse}, EXEC={exec:#x}, {lanes} lanes"), + code: store(code), + input, + expected, + }); + } + } + } + } + } + cases +} + +fn branch_cases() -> Vec { + let mut cases = Vec::new(); + for (op, name) in FORMS { + for dst in [0, 105, 106] { + for exec in MASKS { + for old_vcc in [0, 0xa5a5_5a5a] { + for nonzero in [false, true] { + let scc = old_vcc != 0; + let mut code = setup(0, u32::MAX); + // Seed s1 to detect an accidental second SGPR write to s0:s1. + code.extend(vop3(199, 1, false)); + code.extend(smov(106, old_vcc)); + code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 }); + code.extend([0x7e04_0280, 0x7e08_0280, 0x7e0c_0284]); // v2 = v4 = 0, v6 = 4 + code.extend(smov(126, exec)); + code.extend(vop3(op, dst, false)); + code.extend([ + 0x7e08_0281, // v4 = 1 only where EXEC was set + 0xbefe_03c1, + // Independent bits for the VCC edge, SCC, and EXEC. + if nonzero { 0xbf87_0001 } else { 0xbf86_0001 }, + 0x7e04_0282, // v2 = 2 on fallthrough + 0xbf84_0001, + 0x3a04_0d02, // v2 ^= 4 if SCC = 1 + 0x3a04_0902, // v2 ^= v4 + 0x7e06_0201, + 0x3a04_0702, // v2 ^= s1 + 0x7e06_026a, + 0x3a04_0702, // v2 ^= VCC_LO + ]); + // The two waves give opposite results for several relations. + let input: Vec<_> = std::iter::repeat_n(1, 32) + .chain(std::iter::repeat_n(u32::MAX, 13)) + .collect(); + let mut expected = Vec::new(); + for wave in input.chunks(32) { + let mask = expected_mask(op, exec, wave, 0, false); + let vcc = if dst == 106 { mask } else { old_vcc }; + // §12.5: if (VCC == 0) / if (VCC != 0), PC = PC + signext(SIMM16 * 4) + 4. + let taken = (vcc != 0) == nonzero; + let s1 = u32::MAX >> (32 - wave.len()); + let marker = (u32::from(scc) << 2) | (u32::from(!taken) << 1); + expected.extend( + wave.iter() + .enumerate() + .map(|(n, _)| marker ^ ((exec >> n) & 1) ^ s1 ^ vcc), + ); + } + cases.push(Case { + form: name, + family: "vcc branch and flags", + label: format!( + "{name} s{dst}, EXEC={exec:#x}, VCC={old_vcc:#x}, NZ={nonzero}" + ), + code: store(code), + input, + expected, + }); + } + } + } + } + } + cases +} + +#[test] +fn vop3_compare_matches_the_guide() { + let masks = mask_cases(); + let branches = branch_cases(); + assert_eq!(masks.len(), 16 * 10 * 2 * 4 * 5); + assert_eq!(branches.len(), 16 * 3 * 4 * 2 * 2); + for case in masks.iter().chain(&branches) { + assert_eq!( + xenora_ref::execute(&case.code, &case.input).unwrap(), + case.expected, + "reference: {}", + case.label + ); + assert_eq!( + independent_ref::execute(&case.code, &case.input).unwrap(), + case.expected, + "independent: {}", + case.label + ); + } + eprintln!( + "vop3_compare: {} mask and {} branch/flag cases per CPU interpreter", + masks.len(), + branches.len() + ); +} + +#[test] +fn vop3_compare_rejects_excluded_operands_and_modifiers() { + let mut count = 0; + for (op, name) in FORMS { + let setup = setup(7, u32::MAX); + let offset = setup.len() * 4; + let [head, tail] = vop3(op, 106, false); + let mut check = |alu: &[u32]| { + let mut code = setup.clone(); + code.extend(alu); + let code = if alu.len() == 1 { + words(&code) + } else { + // A successful decode would read its mask here and complete. + code.push(0x7e04_026a); + store(code) + }; + let input = [1, 2]; + let err = xenora_ref::execute(&code, &input).expect_err(name); + assert_eq!(err.offset, offset, "{name}: {alu:08x?} {err:?}"); + let err = independent_ref::execute(&code, &input).expect_err(name); + assert!( + err.starts_with(&format!("{offset:#x}:")), + "{name}: {alu:08x?} {err}" + ); + count += 1; + }; + // ABS, OP_SEL and CLAMP in word 0. OMOD and NEG in word 1. + for bit in 8..16 { + check(&[head | 1 << bit, tail]); + } + for bit in 27..32 { + check(&[head, tail | 1 << bit]); + } + for selector in 0..256 { + check(&[head, (tail & !511) | selector]); + check(&[head, (tail & !(511 << 9)) | selector << 9]); + } + for selector in (0..512).filter(|&s| s != 128) { + check(&[head, (tail & !(511 << 18)) | selector << 18]); + } + for dst in 107..=255 { + check(&[(head & !255) | dst, tail]); + } + check(&[head]); + } + assert_eq!(count, 16 * (13 + 512 + 511 + 149 + 1)); + eprintln!("vop3_compare: {count} rejections per CPU interpreter"); +} + +#[test] +#[ignore = "requires a native Metal device with API and shader validation"] +fn vop3_vcc_compare_matches_the_guide_on_native_metal() { + assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1")); + assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1")); + let cases: Vec<_> = mask_cases() + .into_iter() + .filter(|case| case.family == "vcc_lo") + .collect(); + let (failures, programs) = harness::check_metal(&cases); + failures.assert_none("native Metal disagrees with the guide"); + eprintln!( + "vop3_compare: {} Metal cases in {programs} programs", + cases.len() + ); +} diff --git a/tests/validation/tests/vop3_integer.rs b/tests/validation/tests/vop3_integer.rs new file mode 100644 index 0000000..cc50e85 --- /dev/null +++ b/tests/validation/tests/vop3_integer.rs @@ -0,0 +1,246 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Wave32 VOP3A integer ALU forms. AMD RDNA 2 ISA guide §§12.7, 12.7.1, +//! 12.12 and 13.3.4. The expectations use the guide's arithmetic per lane. + +#[path = "operand_domains/harness.rs"] +#[allow(dead_code)] +mod harness; +#[path = "../independent_ref.rs"] +mod independent_ref; + +use harness::{Case, words}; + +const FORMS: [(u32, &str); 11] = [ + (265, "v_mul_i32_i24"), + (266, "v_mul_hi_i32_i24"), + (267, "v_mul_u32_u24"), + (268, "v_mul_hi_u32_u24"), + (273, "v_min_i32"), + (274, "v_max_i32"), + (275, "v_min_u32"), + (276, "v_max_u32"), + (286, "v_xnor_b32"), + (294, "v_sub_nc_u32"), + (295, "v_subrev_nc_u32"), +]; +const VALUES: [u32; 12] = [ + 0, + 1, + 2, + 0x007f_ffff, + 0x0080_0000, + 0x0080_0001, + 0x00ff_ffff, + 0xff80_0000, + 0xff00_0003, + 0x7fff_ffff, + 0x8000_0000, + u32::MAX, +]; +const MASKS: [u32; 4] = [u32::MAX, 0x5555_5555, 0x8000_0001, 0]; + +fn expected(op: u32, a: u32, b: u32) -> u32 { + // S.i24 is bits 23:0 sign-extended from bit 23; S.u24 is zero-extended. + let i24 = |x: u32| (i64::from(x & 0x7f_ffff)) - i64::from(x & 0x80_0000); + let u24 = |x: u32| i64::from(x & 0xff_ffff); + match op { + // D.i32 = S0.i24 * S1.i24. + 265 => (i24(a) * i24(b)) as u32, + // D.i32 = (S0.i24 * S1.i24)>>32. + 266 => (i24(a) * i24(b)).div_euclid(1 << 32) as u32, + // D.u32 = S0.u24 * S1.u24. + 267 => (u24(a) * u24(b)) as u32, + // D.u32 = (S0.u24 * S1.u24)>>32. + 268 => (u24(a) * u24(b)).div_euclid(1 << 32) as u32, + // D.i32 = (S0.i32 < S1.i32 ? S0.i32 : S1.i32). + 273 => (a as i32).min(b as i32) as u32, + // D.i32 = (S0.i32 >= S1.i32 ? S0.i32 : S1.i32). + 274 => (a as i32).max(b as i32) as u32, + // D.u32 = (S0.u32 < S1.u32 ? S0.u32 : S1.u32). + 275 => a.min(b), + // D.u32 = (S0.u32 >= S1.u32 ? S0.u32 : S1.u32). + 276 => a.max(b), + // D.u32 = ~(S0.u32 ^ S1.u32). + 286 => !(a ^ b), + // D.u32 = S0.u32 - S1.u32. + 294 => (i64::from(a) - i64::from(b)) as u32, + // D.u32 = S1.u32 - S0.u32. + 295 => (i64::from(b) - i64::from(a)) as u32, + _ => unreachable!("test only uses the listed forms"), + } +} + +/// VOP3A: OP 25:16, VDST 7:0, three 9-bit sources, inline zero at SRC2. +fn vop3(op: u32, dst: u32, a: u32, b: u32) -> [u32; 2] { + [ + 0xd400_0000 | op << 16 | dst, + (256 + a) | (256 + b) << 9 | 128 << 18, + ] +} + +fn vmov(dst: u32, value: u32) -> [u32; 2] { + [0x7e00_02ff | dst << 17, value] +} + +fn smov(dst: u32, value: u32) -> [u32; 2] { + [0xbe80_03ff | dst << 16, value] +} + +fn setup(b: u32, exec: u32, scc: bool) -> Vec { + let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70]; // load v1 + code.extend(vmov(255, b)); + code.extend(vmov(2, 0xabad_1dea)); + code.extend(smov(106, 0x1357_9bdf)); + code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 }); + code.extend(smov(126, exec)); + code +} + +fn finish(mut code: Vec, dst: u32) -> Vec { + // Restore EXEC, read D and VCC_LO, and XOR in v1 when SCC is set. + code.extend([ + 0xbefe_03c1, + 0x7e04_0300 | dst, + 0x7e0c_026a, + 0x3a04_0506, + 0xbf84_0001, + 0x3a04_0501, + 0xe070_2000, + 0x8001_0200, + 0xbbfd_0000, + 0xbf81_0000, + ]); + words(&code) +} + +fn cases() -> Vec { + let mut cases = Vec::new(); + for (op, name) in FORMS { + for b in VALUES { + for (dst, src0, src1) in [ + (2, 1, 255), + (2, 255, 1), + (1, 1, 255), + (255, 1, 255), + (255, 255, 255), + ] { + for exec in MASKS { + for lanes in [7, 32, 45] { + let scc = dst == 255; + let mut code = setup(b, exec, scc); + code.extend(vop3(op, dst, src0, src1)); + let input: Vec<_> = VALUES.into_iter().cycle().take(lanes).collect(); + let expected = input + .iter() + .enumerate() + .map(|(lane, &x)| { + let read = |reg| if reg == 1 { x } else { b }; + // Guide §3.3: a disabled lane retains its previous VGPR. + let d = if exec & (1 << (lane % 32)) != 0 { + expected(op, read(src0), read(src1)) + } else { + match dst { + 1 => x, + 255 => b, + _ => 0xabad_1dea, + } + }; + d ^ 0x1357_9bdf ^ if scc { x } else { 0 } + }) + .collect(); + cases.push(Case { + form: name, + family: "vop3 integer", + label: format!("{name} v{dst}, v{src0}, v{src1} ({b:#x}), EXEC={exec:#x}, {lanes} lanes"), + code: finish(code, dst), + input, + expected, + }); + } + } + } + } + } + cases +} + +#[test] +fn vop3_integer_matches_the_guide() { + let cases = cases(); + assert_eq!(cases.len(), 11 * 12 * 5 * 4 * 3); + for case in &cases { + assert_eq!( + xenora_ref::execute(&case.code, &case.input).unwrap(), + case.expected, + "reference: {}", + case.label + ); + assert_eq!( + independent_ref::execute(&case.code, &case.input).unwrap(), + case.expected, + "independent: {}", + case.label + ); + } + eprintln!("vop3_integer: {} cases per CPU interpreter", cases.len()); +} + +#[test] +fn vop3_integer_rejects_excluded_operands_and_modifiers() { + let mut count = 0; + for (op, name) in FORMS { + let setup = setup(7, u32::MAX, false); + let offset = setup.len() * 4; + let [head, tail] = vop3(op, 2, 1, 255); + let mut check = |alu: &[u32]| { + let mut code = setup.clone(); + code.extend(alu); + let code = if alu.len() == 1 { + words(&code) + } else { + finish(code, 2) + }; + let input = [1, 2]; + let err = xenora_ref::execute(&code, &input).expect_err(name); + assert_eq!(err.offset, offset, "{name}: {alu:08x?} {err:?}"); + let err = independent_ref::execute(&code, &input).expect_err(name); + assert!( + err.starts_with(&format!("{offset:#x}:")), + "{name}: {alu:08x?} {err}" + ); + count += 1; + }; + // ABS, OP_SEL and CLAMP in word 0. OMOD and NEG in word 1. + for bit in 8..16 { + check(&[head | 1 << bit, tail]); + } + for bit in 27..32 { + check(&[head, tail | 1 << bit]); + } + for selector in 0..256 { + check(&[head, (tail & !511) | selector]); + check(&[head, (tail & !(511 << 9)) | selector << 9]); + } + for selector in (0..512).filter(|&s| s != 128) { + check(&[head, (tail & !(511 << 18)) | selector << 18]); + } + check(&[head]); + } + assert_eq!(count, 11 * (13 + 512 + 511 + 1)); + eprintln!("vop3_integer: {count} rejections per CPU interpreter"); +} + +#[test] +#[ignore = "requires a native Metal device with API and shader validation"] +fn vop3_integer_matches_the_guide_on_native_metal() { + assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1")); + assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1")); + let cases = cases(); + let (failures, programs) = harness::check_metal(&cases); + failures.assert_none("native Metal disagrees with the guide"); + eprintln!( + "vop3_integer: {} Metal cases in {programs} programs", + cases.len() + ); +}