From e4a2030ab99103cbab6fd2ba852464ef58390a40 Mon Sep 17 00:00:00 2001 From: Lachlan Sneff Date: Thu, 29 Apr 2021 19:45:49 -0400 Subject: [PATCH] Add several additional ops to the spirv frontend. (#803) * Add support for int8, int16, and int64 as well as null constant structs * Add support for OpArrayLength to the spirv frontend * Add hacky OpCopyMemory support to spirv frontend * Add OpInBoundsAccessChain to spirv frontend * Add OpLogical(Not)Equal to spirv frontend * Fix several of the issues raised in the pr * Fix the Op::ArrayLength match * Validate accessing structs through pointers * Remove extraneous type check --- src/front/spv/convert.rs | 8 ++- src/front/spv/mod.rs | 142 ++++++++++++++++++++++++++++++++------- src/lib.rs | 4 ++ src/valid/expression.rs | 48 ++++++++----- 4 files changed, 156 insertions(+), 46 deletions(-) diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 76c234e6f..c0f6f3917 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -14,8 +14,12 @@ pub(super) fn map_binary_operator(word: spirv::Op) -> Result Ok(BinaryOperator::Divide), Op::UMod | Op::SMod | Op::FMod => Ok(BinaryOperator::Modulo), // Relational and Logical Instructions - Op::IEqual | Op::FOrdEqual | Op::FUnordEqual => Ok(BinaryOperator::Equal), - Op::INotEqual | Op::FOrdNotEqual | Op::FUnordNotEqual => Ok(BinaryOperator::NotEqual), + Op::IEqual | Op::FOrdEqual | Op::FUnordEqual | Op::LogicalEqual => { + Ok(BinaryOperator::Equal) + } + Op::INotEqual | Op::FOrdNotEqual | Op::FUnordNotEqual | Op::LogicalNotEqual => { + Ok(BinaryOperator::NotEqual) + } Op::ULessThan | Op::SLessThan | Op::FOrdLessThan | Op::FUnordLessThan => { Ok(BinaryOperator::Less) } diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index ccea724d5..33113e055 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -64,6 +64,9 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[ spirv::Capability::StorageImageExtendedFormats, spirv::Capability::Sampled1D, spirv::Capability::SampledCubeArray, + spirv::Capability::Int8, + spirv::Capability::Int16, + spirv::Capability::Int64, // tricky ones spirv::Capability::UniformBufferArrayDynamicIndexing, spirv::Capability::StorageBufferArrayDynamicIndexing, @@ -882,7 +885,7 @@ impl> Parser { }, ); } - Op::AccessChain => { + Op::AccessChain | Op::InBoundsAccessChain => { struct AccessExpression { base_handle: Handle, type_id: spirv::Word, @@ -1617,7 +1620,9 @@ impl> Parser { | Op::ConvertSToF | Op::ConvertUToF | Op::ConvertFToU - | Op::ConvertFToS => { + | Op::ConvertFToS + | Op::UConvert + | Op::SConvert => { inst.expect_at_least(4)?; let result_type_id = self.next()?; let result_id = self.next()?; @@ -1808,7 +1813,8 @@ impl> Parser { | Op::FOrdLessThanEqual | Op::FUnordLessThanEqual | Op::FOrdGreaterThanEqual - | Op::FUnordGreaterThanEqual => { + | Op::FUnordGreaterThanEqual + | Op::LogicalNotEqual => { inst.expect(5)?; let operator = map_binary_operator(inst.op)?; self.parse_expr_binary_op(expressions, operator)?; @@ -1947,6 +1953,62 @@ impl> Parser { Op::Fwidth | Op::FwidthFine | Op::FwidthCoarse => { self.parse_expr_derivative(expressions, crate::DerivativeAxis::Width)?; } + Op::ArrayLength => { + inst.expect(5)?; + let result_type_id = self.next()?; + let result_id = self.next()?; + let structure_id = self.next()?; + let member_index = self.next()?; + + // We're assuming that the validation pass, if it's run, will catch if the + // wrong types or parameters are supplied here. + + let structure_ptr = self.lookup_expression.lookup(structure_id)?; + + let member_ptr = expressions.append(crate::Expression::AccessIndex { + base: structure_ptr.handle, + index: member_index, + }); + + let length = expressions.append(crate::Expression::ArrayLength(member_ptr)); + + self.lookup_expression.insert( + result_id, + LookupExpression { + handle: length, + type_id: result_type_id, + }, + ); + } + Op::CopyMemory => { + inst.expect_at_least(3)?; + let target_id = self.next()?; + let source_id = self.next()?; + let _memory_access = if inst.wc != 3 { + inst.expect(4)?; + spirv::MemoryAccess::from_bits(self.next()?) + .ok_or(Error::InvalidParameter(Op::CopyMemory))? + } else { + spirv::MemoryAccess::NONE + }; + + // TODO: check if the source and target types are the same? + let target = self.lookup_expression.lookup(target_id)?; + let source = self.lookup_expression.lookup(source_id)?; + + // This operation is practically the same as loading and then storing, I think. + let value_expr = expressions.append(crate::Expression::Load { + pointer: source.handle, + }); + + block.extend(emitter.finish(expressions)); + block.push(crate::Statement::Store { + pointer: target.handle, + value: value_expr, + }); + + emitter.start(expressions); + } _ => return Err(Error::UnsupportedInstruction(self.state, inst.op)), } }; @@ -2956,15 +3018,12 @@ impl> Parser { kind: crate::ScalarKind::Sint, width, } => { - use std::cmp::Ordering; let low = self.next()?; - let high = match width.cmp(&4) { - Ordering::Less => return Err(Error::InvalidTypeWidth(u32::from(width))), - Ordering::Greater => { - inst.expect(4)?; - self.next()? - } - Ordering::Equal => 0, + let high = if width > 4 { + inst.expect(4)?; + self.next()? + } else { + 0 }; crate::ConstantInner::Scalar { width, @@ -3044,18 +3103,13 @@ impl> Parser { Ok(()) } - fn parse_null_constant( + fn generate_null_constant( &mut self, - inst: Instruction, - module: &mut crate::Module, - ) -> Result<(), Error> { - self.switch(ModuleState::Type, inst.op)?; - inst.expect(3)?; - let type_id = self.next()?; - let id = self.next()?; - let type_lookup = self.lookup_type.lookup(type_id)?; - let ty = type_lookup.handle; - + constants: &mut Arena, + types: &Arena, + ty: Handle, + inner: &crate::TypeInner, + ) -> Result { fn make_scalar_inner(kind: crate::ScalarKind, width: crate::Bytes) -> crate::ConstantInner { crate::ConstantInner::Scalar { width, @@ -3068,12 +3122,12 @@ impl> Parser { } } - let inner = match module.types[ty].inner { + let inner = match *inner { crate::TypeInner::Scalar { kind, width } => make_scalar_inner(kind, width), crate::TypeInner::Vector { size, kind, width } => { let mut components = Vec::with_capacity(size as usize); for _ in 0..size as usize { - components.push(module.constants.fetch_or_append(crate::Constant { + components.push(constants.fetch_or_append(crate::Constant { name: None, specialization: None, inner: make_scalar_inner(kind, width), @@ -3081,12 +3135,48 @@ impl> Parser { } crate::ConstantInner::Composite { ty, components } } - //TODO: handle matrices, arrays, and structures + crate::TypeInner::Struct { ref members, .. } => { + let mut components = Vec::with_capacity(members.len()); + for field in members { + let ty_inner = &types[field.ty].inner; + let inner = + self.generate_null_constant(constants, types, field.ty, ty_inner)?; + components.push(constants.fetch_or_append(crate::Constant { + name: None, + specialization: None, + inner, + })); + } + + crate::ConstantInner::Composite { ty, components } + } + //TODO: handle matrices, arrays ref other => { log::warn!("null constant type {:?}", other); - return Err(Error::UnsupportedType(type_lookup.handle)); + return Err(Error::UnsupportedType(ty)); } }; + Ok(inner) + } + + fn parse_null_constant( + &mut self, + inst: Instruction, + module: &mut crate::Module, + ) -> Result<(), Error> { + self.switch(ModuleState::Type, inst.op)?; + inst.expect(3)?; + let type_id = self.next()?; + let id = self.next()?; + let type_lookup = self.lookup_type.lookup(type_id)?; + let ty = type_lookup.handle; + + let inner = self.generate_null_constant( + &mut module.constants, + &module.types, + ty, + &module.types[ty].inner, + )?; self.lookup_constant.insert( id, diff --git a/src/lib.rs b/src/lib.rs index 270fbf974..d51828e5b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -813,6 +813,10 @@ pub enum Expression { /// Result of calling another function. Call(Handle), /// Get the length of an array. + /// The expression must resolve to a pointer to an array with a dynamic size. + /// + /// This doesn't match the semantics of spirv's `OpArrayLength`, which must be passed + /// a pointer to a structure containing a runtime array in its' last field. ArrayLength(Handle), } diff --git a/src/valid/expression.rs b/src/valid/expression.rs index 46d2099c6..df79a3dff 100644 --- a/src/valid/expression.rs +++ b/src/valid/expression.rs @@ -171,24 +171,36 @@ impl super::Validator { ShaderStages::all() } E::AccessIndex { base, index } => { - let limit = match *resolver.resolve(base)? { - Ti::Vector { size, .. } - | Ti::ValuePointer { - size: Some(size), .. - } => size as u32, - Ti::Matrix { columns, .. } => columns as u32, - Ti::Array { - size: crate::ArraySize::Constant(handle), - .. - } => module.constants[handle].to_array_length().unwrap(), - Ti::Array { .. } => !0, // can't statically know, but need run-time checks - Ti::Pointer { .. } => !0, //TODO - Ti::Struct { ref members, .. } => members.len() as u32, - ref other => { - log::error!("Indexing of {:?}", other); - return Err(ExpressionError::InvalidBaseType(base)); - } - }; + fn resolve_index_limit( + module: &crate::Module, + top: Handle, + ty: &crate::TypeInner, + top_level: bool, + ) -> Result { + let limit = match *ty { + Ti::Vector { size, .. } + | Ti::ValuePointer { + size: Some(size), .. + } => size as u32, + Ti::Matrix { columns, .. } => columns as u32, + Ti::Array { + size: crate::ArraySize::Constant(handle), + .. + } => module.constants[handle].to_array_length().unwrap(), + Ti::Array { .. } => !0, // can't statically know, but need run-time checks + Ti::Pointer { base, .. } if top_level => { + resolve_index_limit(module, top, &module.types[base].inner, false)? + } + Ti::Struct { ref members, .. } => members.len() as u32, + ref other => { + log::error!("Indexing of {:?}", other); + return Err(ExpressionError::InvalidBaseType(top)); + } + }; + Ok(limit) + } + + let limit = resolve_index_limit(module, base, resolver.resolve(base)?, true)?; if index >= limit { return Err(ExpressionError::IndexOutOfBounds(base, index)); }