From e6e5f5288cf4dc5b4a8a1447bce420f455ad3261 Mon Sep 17 00:00:00 2001 From: atlv Date: Thu, 9 Apr 2026 15:36:02 -0700 Subject: [PATCH] Bring immediate in line with webgpu spec (#9280) --- CHANGELOG.md | 1 + examples/features/src/ray_shadows/mod.rs | 4 +- examples/features/src/ray_shadows/shader.wgsl | 1 - naga/src/valid/analyzer.rs | 36 +- naga/src/valid/immediates.rs | 230 +++++++++++ naga/src/valid/mod.rs | 2 + naga/tests/out/analysis/spv-shadow.info.ron | 3 + naga/tests/out/analysis/wgsl-access.info.ron | 19 + naga/tests/out/analysis/wgsl-collatz.info.ron | 2 + .../out/analysis/wgsl-overrides.info.ron | 1 + .../analysis/wgsl-storage-textures.info.ron | 2 + tests/tests/wgpu-validation/api/immediates.rs | 360 ++++++++++++++++++ tests/tests/wgpu-validation/api/mod.rs | 1 + wgpu-core/src/command/bundle.rs | 40 +- wgpu-core/src/command/compute.rs | 22 ++ wgpu-core/src/command/draw.rs | 4 + wgpu-core/src/command/render.rs | 19 + wgpu-core/src/device/resource.rs | 52 ++- wgpu-core/src/pipeline.rs | 2 + wgpu-core/src/validation.rs | 16 + wgpu-hal/src/auxil/mod.rs | 2 + 21 files changed, 784 insertions(+), 35 deletions(-) create mode 100644 naga/src/valid/immediates.rs create mode 100644 tests/tests/wgpu-validation/api/immediates.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index b3f9e0d80..2926c6b48 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,6 +88,7 @@ Bottom level categories: #### Validation - Add clip distances validation for `maxInterStageShaderVariables`. By @ErichDonGubler in [#8762](https://github.com/gfx-rs/wgpu/pull/8762). This may break some existing programs, but it compiles with the WebGPU spec. +- Bring immediates in line with webgpu spec. By @atlv24 in [#9280](https://github.com/gfx-rs/wgpu/pull/9280). #### DX12 diff --git a/examples/features/src/ray_shadows/mod.rs b/examples/features/src/ray_shadows/mod.rs index 1c04751a7..53201de94 100644 --- a/examples/features/src/ray_shadows/mod.rs +++ b/examples/features/src/ray_shadows/mod.rs @@ -94,7 +94,7 @@ impl crate::framework::Example for Example { fn required_limits() -> wgpu::Limits { wgpu::Limits { - max_immediate_size: 16, + max_immediate_size: 12, ..wgpu::Limits::default() } .using_minimum_supported_acceleration_structure_values() @@ -186,7 +186,7 @@ impl crate::framework::Example for Example { let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&bind_group_layout)], - immediate_size: 16, + immediate_size: 12, }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { diff --git a/examples/features/src/ray_shadows/shader.wgsl b/examples/features/src/ray_shadows/shader.wgsl index 0bb430b75..7cb8faa44 100644 --- a/examples/features/src/ray_shadows/shader.wgsl +++ b/examples/features/src/ray_shadows/shader.wgsl @@ -37,7 +37,6 @@ var acc_struct: acceleration_structure; struct ImmediateData { light: vec3, - padding: f32, } var pc: ImmediateData; diff --git a/naga/src/valid/analyzer.rs b/naga/src/valid/analyzer.rs index 30ab11aef..ab834bdfe 100644 --- a/naga/src/valid/analyzer.rs +++ b/naga/src/valid/analyzer.rs @@ -8,7 +8,9 @@ use alloc::{boxed::Box, vec}; use core::ops; -use super::{ExpressionError, FunctionError, ModuleInfo, ShaderStages, ValidationFlags}; +use super::{ + ExpressionError, FunctionError, ImmediateSlots, ModuleInfo, ShaderStages, ValidationFlags, +}; use crate::diagnostic_filter::{DiagnosticFilterNode, StandardFilterableTriggeringRule}; use crate::span::{AddSpan as _, WithSpan}; use crate::{ @@ -302,6 +304,10 @@ pub struct FunctionInfo { /// See [`DiagnosticFilterNode`] for details on how the tree is represented and used in /// validation. diagnostic_filter_leaf: Option>, + + /// A bitmask, tracking which 4-byte slots this function (possibly transitively) reads. + /// Used to determine the minimum set of slots that must be written via `set_immediates`. + pub immediate_slots_used: ImmediateSlots, } impl FunctionInfo { @@ -493,10 +499,11 @@ impl FunctionInfo { } } - // Inherit global use from our callees. + // Inherit global use and immediate slot tracking from our callees. for (mine, other) in self.global_uses.iter_mut().zip(callee.global_uses.iter()) { *mine |= *other; } + self.immediate_slots_used |= callee.immediate_slots_used; Ok(FunctionUniformity { result: callee.uniformity.clone(), @@ -672,10 +679,25 @@ impl FunctionInfo { non_uniform_result: Some(handle), requirements: UniformityRequirements::empty(), }, - E::Load { pointer } => Uniformity { - non_uniform_result: self.add_ref(pointer), - requirements: UniformityRequirements::empty(), - }, + E::Load { pointer } => { + let non_uniform_result = self.add_ref(pointer); + // Track which immediate slots this load touches. + if let Some(global) = self.expressions[pointer.index()].assignable_global { + if resolve_context.global_vars[global].space == crate::AddressSpace::Immediate { + self.immediate_slots_used |= ImmediateSlots::for_pointer( + pointer, + global, + expression_arena, + resolve_context.global_vars, + resolve_context.types, + ); + } + } + Uniformity { + non_uniform_result, + requirements: UniformityRequirements::empty(), + } + } E::ImageSample { image, sampler, @@ -1246,6 +1268,7 @@ impl ModuleInfo { sampling: crate::FastHashSet::default(), dual_source_blending: false, diagnostic_filter_leaf: fun.diagnostic_filter_leaf, + immediate_slots_used: ImmediateSlots::default(), }; let resolve_context = ResolveContext::with_locals(module, &fun.local_variables, &fun.arguments); @@ -1381,6 +1404,7 @@ fn uniform_control_flow() { sampling: crate::FastHashSet::default(), dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: ImmediateSlots::default(), }; let resolve_context = ResolveContext { constants: &Arena::new(), diff --git a/naga/src/valid/immediates.rs b/naga/src/valid/immediates.rs new file mode 100644 index 000000000..bd089fec5 --- /dev/null +++ b/naga/src/valid/immediates.rs @@ -0,0 +1,230 @@ +use core::{fmt, ops}; + +/// A bitmask, tracking which 4-byte slots have been written via `set_immediates`. +/// Bit N corresponds to bytes [N*4 .. N*4+4). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize))] +#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))] +pub struct ImmediateSlots(u64); + +impl ImmediateSlots { + pub const fn from_raw(raw: u64) -> Self { + Self(raw) + } + + /// Compute the bitmask for a byte range [offset .. offset + size_bytes). + pub const fn from_range(offset: u32, size_bytes: u32) -> Self { + if size_bytes == 0 { + return Self(0); + } + let lo = offset / 4; + let hi = (offset + size_bytes).div_ceil(4); + Self(u64::MAX << lo & u64::MAX >> (64 - hi)) + } + + /// Compute the slots occupied by a type at a given byte offset, + /// excluding padding between struct members. + pub fn from_type( + ty: &crate::TypeInner, + offset: u32, + types: &crate::UniqueArena, + gctx: crate::proc::GlobalCtx, + ) -> Self { + match *ty { + crate::TypeInner::Struct { ref members, .. } => { + let mut slots = Self::default(); + for member in members { + let member_ty = &types[member.ty].inner; + slots |= Self::from_type(member_ty, offset + member.offset, types, gctx); + } + slots + } + _ => Self::from_range(offset, ty.size(gctx)), + } + } + + /// Returns true if `self` contains all bits in `other`. + pub const fn contains(self, other: Self) -> bool { + other.0 & !self.0 == 0 + } + + /// Returns the bits in `self` that are not set in `other`. + pub const fn difference(self, other: Self) -> Self { + Self(self.0 & !other.0) + } + + /// Returns the byte size of the `var` type in a module. + /// Zero if the module has no `var`. + pub fn size_for_module(module: &crate::Module) -> u32 { + module + .global_variables + .iter() + .find(|&(_, var)| var.space == crate::AddressSpace::Immediate) + .map(|(_, var)| module.types[var.ty].inner.size(module.to_ctx())) + .unwrap_or(0) + } + + /// Compute the immediate slot bitmask for a pointer expression that + /// refers to (part of) an immediate global variable. + /// + /// `global` is the handle of the immediate global variable that this + /// pointer derives from (obtained from `assignable_global`). + pub(crate) fn for_pointer( + pointer: crate::arena::Handle, + global: crate::arena::Handle, + expression_arena: &crate::Arena, + global_vars: &crate::Arena, + types: &crate::UniqueArena, + ) -> Self { + use crate::Expression as E; + use crate::TypeInner; + + let gctx = crate::proc::GlobalCtx { + types, + constants: &crate::Arena::new(), + overrides: &crate::Arena::new(), + global_expressions: &crate::Arena::new(), + }; + + let global_ty = &types[global_vars[global].ty].inner; + + match expression_arena[pointer] { + E::GlobalVariable(_) => Self::from_type(global_ty, 0, types, gctx), + E::AccessIndex { base, index } => { + if let E::GlobalVariable(_) = expression_arena[base] { + if let TypeInner::Struct { ref members, .. } = *global_ty { + let member = &members[index as usize]; + let member_ty = &types[member.ty].inner; + return Self::from_type(member_ty, member.offset, types, gctx); + } + } + Self::from_type(global_ty, 0, types, gctx) + } + _ => Self::from_type(global_ty, 0, types, gctx), + } + } +} + +impl ops::BitOrAssign for ImmediateSlots { + fn bitor_assign(&mut self, rhs: Self) { + self.0 |= rhs.0; + } +} + +impl ops::BitOr for ImmediateSlots { + type Output = Self; + fn bitor(self, rhs: Self) -> Self { + Self(self.0 | rhs.0) + } +} + +impl fmt::Display for ImmediateSlots { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.0 == 0 { + return write!(f, "(none)"); + } + let mut first = true; + let mut bit = 0u32; + while bit < 64 { + if self.0 & (1u64 << bit) != 0 { + let start = bit * 4; + while bit < 64 && self.0 & (1u64 << bit) != 0 { + bit += 1; + } + let end = bit * 4; + if !first { + write!(f, ", ")?; + } + write!(f, "{start}..{end}")?; + first = false; + } else { + bit += 1; + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::ImmediateSlots; + + #[test] + fn range_single() { + assert_eq!( + ImmediateSlots::from_range(0, 4), + ImmediateSlots::from_raw(0b1) + ); + assert_eq!( + ImmediateSlots::from_range(4, 4), + ImmediateSlots::from_raw(0b10) + ); + assert_eq!( + ImmediateSlots::from_range(8, 4), + ImmediateSlots::from_raw(0b100) + ); + } + + #[test] + fn range_vec4() { + assert_eq!( + ImmediateSlots::from_range(0, 16), + ImmediateSlots::from_raw(0b1111) + ); + assert_eq!( + ImmediateSlots::from_range(16, 16), + ImmediateSlots::from_raw(0b1111_0000) + ); + } + + #[test] + fn range_full_256() { + assert_eq!( + ImmediateSlots::from_range(0, 256), + ImmediateSlots::from_raw(u64::MAX) + ); + } + + #[test] + fn from_type_excludes_struct_padding() { + let module = crate::front::wgsl::parse_str("struct S { a: f32, b: vec4 }").unwrap(); + let struct_ty = (module.types.iter().map(|ty| ty.1)) + .find(|ty| ty.name.as_deref() == Some("S")) + .unwrap(); + let slots = ImmediateSlots::from_type(&struct_ty.inner, 0, &module.types, module.to_ctx()); + assert_eq!(slots, ImmediateSlots::from_raw(0b1111_0001)); + } + + #[test] + fn range_unaligned() { + assert_eq!( + ImmediateSlots::from_range(0, 3), + ImmediateSlots::from_raw(0b1) + ); + assert_eq!( + ImmediateSlots::from_range(0, 5), + ImmediateSlots::from_raw(0b11) + ); + } + + #[test] + fn contains() { + let required = ImmediateSlots::from_raw(0b1111_0001); + let mut set = ImmediateSlots::default(); + assert!(!set.contains(required)); + set |= ImmediateSlots::from_range(0, 4); + assert!(!set.contains(required)); + set |= ImmediateSlots::from_range(16, 16); + assert!(set.contains(required)); + } + + #[test] + fn difference() { + let required = ImmediateSlots::from_raw(0b1111_0001); + let set = ImmediateSlots::from_range(0, 4); + assert_eq!( + required.difference(set), + ImmediateSlots::from_raw(0b1111_0000) + ); + } +} diff --git a/naga/src/valid/mod.rs b/naga/src/valid/mod.rs index 87e0ef531..cbc10ced1 100644 --- a/naga/src/valid/mod.rs +++ b/naga/src/valid/mod.rs @@ -7,6 +7,7 @@ mod compose; mod expression; mod function; mod handles; +pub(crate) mod immediates; mod interface; mod r#type; @@ -30,6 +31,7 @@ pub use compose::ComposeError; pub use expression::{check_literal_value, LiteralError}; pub use expression::{ConstExpressionError, ExpressionError}; pub use function::{CallError, FunctionError, LocalVariableError, SubgroupError}; +pub use immediates::ImmediateSlots; pub use interface::{EntryPointError, GlobalVariableError, VaryingError}; pub use r#type::{Disalignment, ImmediateError, TypeError, TypeFlags, WidthError}; diff --git a/naga/tests/out/analysis/spv-shadow.info.ron b/naga/tests/out/analysis/spv-shadow.info.ron index 015a3d365..e629371c9 100644 --- a/naga/tests/out/analysis/spv-shadow.info.ron +++ b/naga/tests/out/analysis/spv-shadow.info.ron @@ -413,6 +413,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -1591,6 +1592,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ], entry_points: [ @@ -1685,6 +1687,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ], const_expression_types: [ diff --git a/naga/tests/out/analysis/wgsl-access.info.ron b/naga/tests/out/analysis/wgsl-access.info.ron index 04705b66c..6d1ed96d6 100644 --- a/naga/tests/out/analysis/wgsl-access.info.ron +++ b/naga/tests/out/analysis/wgsl-access.info.ron @@ -1197,6 +1197,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -2523,6 +2524,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -2563,6 +2565,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -2612,6 +2615,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -2655,6 +2659,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -2749,6 +2754,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -2870,6 +2876,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -2922,6 +2929,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -2977,6 +2985,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -3029,6 +3038,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -3084,6 +3094,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -3148,6 +3159,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -3221,6 +3233,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -3297,6 +3310,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -3397,6 +3411,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -3593,6 +3608,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ], entry_points: [ @@ -4290,6 +4306,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -4742,6 +4759,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -4812,6 +4830,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ], const_expression_types: [ diff --git a/naga/tests/out/analysis/wgsl-collatz.info.ron b/naga/tests/out/analysis/wgsl-collatz.info.ron index 9647887a0..a9a69bbbb 100644 --- a/naga/tests/out/analysis/wgsl-collatz.info.ron +++ b/naga/tests/out/analysis/wgsl-collatz.info.ron @@ -275,6 +275,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ], entry_points: [ @@ -430,6 +431,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ], const_expression_types: [], diff --git a/naga/tests/out/analysis/wgsl-overrides.info.ron b/naga/tests/out/analysis/wgsl-overrides.info.ron index d6fcee4aa..9d0db8d53 100644 --- a/naga/tests/out/analysis/wgsl-overrides.info.ron +++ b/naga/tests/out/analysis/wgsl-overrides.info.ron @@ -201,6 +201,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ], const_expression_types: [ diff --git a/naga/tests/out/analysis/wgsl-storage-textures.info.ron b/naga/tests/out/analysis/wgsl-storage-textures.info.ron index 95b9484bd..c0287855d 100644 --- a/naga/tests/out/analysis/wgsl-storage-textures.info.ron +++ b/naga/tests/out/analysis/wgsl-storage-textures.info.ron @@ -184,6 +184,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ( flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"), @@ -396,6 +397,7 @@ sampling: [], dual_source_blending: false, diagnostic_filter_leaf: None, + immediate_slots_used: (0), ), ], const_expression_types: [], diff --git a/tests/tests/wgpu-validation/api/immediates.rs b/tests/tests/wgpu-validation/api/immediates.rs new file mode 100644 index 000000000..6a92f665e --- /dev/null +++ b/tests/tests/wgpu-validation/api/immediates.rs @@ -0,0 +1,360 @@ +//! Validation tests for `var` + +use wgpu_test::fail; + +const COMPUTE_SHADER: &str = " + var im: vec4; + + @group(0) @binding(0) + var output: vec4; + + @compute @workgroup_size(1) + fn main() { + output = im; + } +"; + +fn setup_compute() -> ( + wgpu::Device, + wgpu::Queue, + wgpu::ComputePipeline, + wgpu::BindGroup, +) { + let (device, queue) = wgpu::Device::noop(&wgpu::DeviceDescriptor { + required_features: wgpu::Features::IMMEDIATES, + required_limits: wgpu::Limits { + max_immediate_size: 64, + ..Default::default() + }, + ..Default::default() + }); + + let sm = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(COMPUTE_SHADER.into()), + }); + + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: false }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }], + }); + + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&bgl)], + immediate_size: 16, + }); + + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &sm, + entry_point: Some("main"), + compilation_options: Default::default(), + cache: None, + }); + + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 16, + usage: wgpu::BufferUsages::STORAGE, + mapped_at_creation: false, + }); + + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &bgl, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: buffer.as_entire_binding(), + }], + }); + + (device, queue, pipeline, bind_group) +} + +#[test] +fn dispatch_without_setting_immediates_fails() { + let (device, _queue, pipeline, bind_group) = setup_compute(); + + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + fail(&device, || encoder.finish(), Some("immediate data")); +} + +#[test] +fn dispatch_with_partial_immediates_fails() { + let (device, _queue, pipeline, bind_group) = setup_compute(); + + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.set_immediates(0, &[0u8; 8]); + pass.dispatch_workgroups(1, 1, 1); + } + fail(&device, || encoder.finish(), Some("immediate data")); +} + +#[test] +fn dispatch_with_all_immediates_set_succeeds() { + let (device, _queue, pipeline, bind_group) = setup_compute(); + + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.set_immediates(0, &[0u8; 16]); + pass.dispatch_workgroups(1, 1, 1); + } + wgpu_test::valid(&device, || encoder.finish()); +} + +#[test] +fn dispatch_with_incremental_immediates_succeeds() { + let (device, _queue, pipeline, bind_group) = setup_compute(); + + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.set_immediates(0, &[0u8; 8]); + pass.set_immediates(8, &[0u8; 8]); + pass.dispatch_workgroups(1, 1, 1); + } + wgpu_test::valid(&device, || encoder.finish()); +} + +const STRUCT_SHADER: &str = " + struct S { + a: f32, + // 12 bytes padding + b: vec4, + } + var im: S; + + @group(0) @binding(0) + var output: vec4; + + @compute @workgroup_size(1) + fn main() { + output = im.b; + } +"; + +#[test] +fn struct_padding_slots_not_required() { + let (device, _q) = wgpu::Device::noop(&wgpu::DeviceDescriptor { + required_features: wgpu::Features::IMMEDIATES, + required_limits: wgpu::Limits { + max_immediate_size: 64, + ..Default::default() + }, + ..Default::default() + }); + + let sm = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(STRUCT_SHADER.into()), + }); + + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: false }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }], + }); + + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&bgl)], + immediate_size: 32, + }); + + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &sm, + entry_point: Some("main"), + compilation_options: Default::default(), + cache: None, + }); + + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 16, + usage: wgpu::BufferUsages::STORAGE, + mapped_at_creation: false, + }); + + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &bgl, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: buffer.as_entire_binding(), + }], + }); + + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + // skip padding at bytes 4..16 + pass.set_immediates(0, &[0u8; 4]); + pass.set_immediates(16, &[0u8; 16]); + pass.dispatch_workgroups(1, 1, 1); + } + wgpu_test::valid(&device, || encoder.finish()); +} + +const NO_IMMEDIATES_SHADER: &str = " + @group(0) @binding(0) + var output: u32; + + @compute @workgroup_size(1) + fn main() { + output = 42u; + } +"; + +#[test] +fn pipeline_without_immediates_needs_none() { + let (device, _queue) = wgpu::Device::noop(&wgpu::DeviceDescriptor::default()); + + let sm = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(NO_IMMEDIATES_SHADER.into()), + }); + + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: false }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }], + }); + + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &sm, + entry_point: Some("main"), + compilation_options: Default::default(), + cache: None, + }); + + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 4, + usage: wgpu::BufferUsages::STORAGE, + mapped_at_creation: false, + }); + + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &bgl, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: buffer.as_entire_binding(), + }], + }); + + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + wgpu_test::valid(&device, || encoder.finish()); +} + +#[test] +fn auto_layout_infers_immediate_size() { + let (device, _q) = wgpu::Device::noop(&wgpu::DeviceDescriptor { + required_features: wgpu::Features::IMMEDIATES, + required_limits: wgpu::Limits { + max_immediate_size: 64, + ..Default::default() + }, + ..Default::default() + }); + + let sm = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(COMPUTE_SHADER.into()), + }); + + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: None, + module: &sm, + entry_point: Some("main"), + compilation_options: Default::default(), + cache: None, + }); + + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 16, + usage: wgpu::BufferUsages::STORAGE, + mapped_at_creation: false, + }); + + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &pipeline.get_bind_group_layout(0), + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: buffer.as_entire_binding(), + }], + }); + + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.set_immediates(0, &[0u8; 16]); + pass.dispatch_workgroups(1, 1, 1); + } + wgpu_test::valid(&device, || encoder.finish()); +} diff --git a/tests/tests/wgpu-validation/api/mod.rs b/tests/tests/wgpu-validation/api/mod.rs index ebb050a8c..b7919d8d1 100644 --- a/tests/tests/wgpu-validation/api/mod.rs +++ b/tests/tests/wgpu-validation/api/mod.rs @@ -8,6 +8,7 @@ mod encoding; mod error_scopes; mod experimental; mod external_texture; +mod immediates; mod instance; mod render_pipeline; mod texture; diff --git a/wgpu-core/src/command/bundle.rs b/wgpu-core/src/command/bundle.rs index 1193c287f..bcefab860 100644 --- a/wgpu-core/src/command/bundle.rs +++ b/wgpu-core/src/command/bundle.rs @@ -346,6 +346,7 @@ impl RenderBundleEncoder { texture_memory_init_actions: Vec::new(), next_dynamic_offset: 0, binder: Binder::new(), + immediate_slots_set: Default::default(), }; let indices = &state.device.tracker_indices; @@ -656,11 +657,6 @@ fn set_pipeline( .commands .push(ArcRenderCommand::SetPipeline(pipeline.clone())); - // If this pipeline uses immediates, zero out their values. - if let Some(cmd) = pipeline_state.zero_immediates() { - state.commands.push(cmd); - } - state.pipeline = Some(pipeline_state); state @@ -772,6 +768,7 @@ fn set_immediates( size_bytes, values_offset, }); + state.immediate_slots_set |= naga::valid::ImmediateSlots::from_range(offset, size_bytes); Ok(()) } @@ -1367,9 +1364,6 @@ struct PipelineState { /// How this pipeline's vertex shader traverses each vertex buffer, indexed /// by vertex buffer slot number. steps: Vec, - - /// Size of the immediate data ranges this pipeline uses. Copied from the pipeline layout. - immediate_size: u32, } impl PipelineState { @@ -1377,23 +1371,8 @@ impl PipelineState { Self { pipeline: pipeline.clone(), steps: pipeline.vertex_steps.to_vec(), - immediate_size: pipeline.layout.immediate_size, } } - - /// Return a sequence of commands to zero the immediate data ranges this - /// pipeline uses. If no initialization is necessary, return `None`. - fn zero_immediates(&self) -> Option { - if self.immediate_size == 0 { - return None; - } - - Some(ArcRenderCommand::SetImmediate { - offset: 0, - size_bytes: self.immediate_size, - values_offset: None, - }) - } } /// State for analyzing and cleaning up bundle command streams. @@ -1434,6 +1413,9 @@ struct State { texture_memory_init_actions: Vec, next_dynamic_offset: usize, binder: Binder, + /// A bitmask, tracking which 4-byte slots have been written via `set_immediates`. + /// Checked against the pipeline's required slots before each draw call. + immediate_slots_set: naga::valid::ImmediateSlots, } impl State { @@ -1512,6 +1494,18 @@ impl State { } } + if !self + .immediate_slots_set + .contains(pipeline.pipeline.immediate_slots_required) + { + return Err(DrawError::MissingImmediateData { + missing: pipeline + .pipeline + .immediate_slots_required + .difference(self.immediate_slots_set), + }); + } + Ok(()) } else { Err(DrawError::MissingPipeline(pass::MissingPipeline)) diff --git a/wgpu-core/src/command/compute.rs b/wgpu-core/src/command/compute.rs index d8f203362..d39df7e03 100644 --- a/wgpu-core/src/command/compute.rs +++ b/wgpu-core/src/command/compute.rs @@ -129,6 +129,10 @@ pub enum DispatchError { InvalidGroupSize { current: [u32; 3], limit: u32 }, #[error(transparent)] BindingSizeTooSmall(#[from] LateMinBufferBindingSizeMismatch), + #[error("Not all immediate data required by the pipeline has been set via set_immediates (missing byte ranges: {missing})")] + MissingImmediateData { + missing: naga::valid::ImmediateSlots, + }, } impl WebGpuError for DispatchError { @@ -265,6 +269,10 @@ struct State<'scope, 'snatch_guard, 'cmd_enc> { immediates: Vec, + /// A bitmask, tracking which 4-byte slots have been written via `set_immediates`. + /// Checked against the pipeline's required slots before each dispatch. + immediate_slots_set: naga::valid::ImmediateSlots, + intermediate_trackers: Tracker, } @@ -273,6 +281,16 @@ impl<'scope, 'snatch_guard, 'cmd_enc> State<'scope, 'snatch_guard, 'cmd_enc> { if let Some(pipeline) = self.pipeline.as_ref() { self.pass.binder.check_compatibility(pipeline.as_ref())?; self.pass.binder.check_late_buffer_bindings()?; + if !self + .immediate_slots_set + .contains(pipeline.immediate_slots_required) + { + return Err(DispatchError::MissingImmediateData { + missing: pipeline + .immediate_slots_required + .difference(self.immediate_slots_set), + }); + } Ok(()) } else { Err(DispatchError::MissingPipeline(pass::MissingPipeline)) @@ -625,6 +643,8 @@ pub(super) fn encode_compute_pass( immediates: Vec::new(), + immediate_slots_set: Default::default(), + intermediate_trackers: Tracker::new( device.ordered_buffer_usages, device.ordered_texture_usages, @@ -741,6 +761,8 @@ pub(super) fn encode_compute_pass( }, ) .map_pass_err(scope)?; + state.immediate_slots_set |= + naga::valid::ImmediateSlots::from_range(offset, size_bytes); } ArcComputeCommand::Dispatch(groups) => { let scope = PassErrorScope::Dispatch { indirect: false }; diff --git a/wgpu-core/src/command/draw.rs b/wgpu-core/src/command/draw.rs index 3690f7d90..5b27c0740 100644 --- a/wgpu-core/src/command/draw.rs +++ b/wgpu-core/src/command/draw.rs @@ -70,6 +70,10 @@ pub enum DrawError { highest_view_index: u32, max_multiviews: u32, }, + #[error("Not all immediate data required by the pipeline has been set via set_immediates (missing byte ranges: {missing})")] + MissingImmediateData { + missing: naga::valid::ImmediateSlots, + }, } impl WebGpuError for DrawError { diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index ebc6a5a29..68608c11d 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -529,6 +529,10 @@ struct State<'scope, 'snatch_guard, 'cmd_enc> { pass: pass::PassState<'scope, 'snatch_guard, 'cmd_enc>, + /// A bitmask, tracking which 4-byte slots have been written via `set_immediates`. + /// Checked against the pipeline's required slots before each draw call. + immediate_slots_set: naga::valid::ImmediateSlots, + active_occlusion_query: Option<(Arc, u32)>, active_pipeline_statistics_query: Option<(Arc, u32)>, } @@ -581,6 +585,16 @@ impl<'scope, 'snatch_guard, 'cmd_enc> State<'scope, 'snatch_guard, 'cmd_enc> { wanted_mesh_pipeline: !pipeline.is_mesh, }); } + if !self + .immediate_slots_set + .contains(pipeline.immediate_slots_required) + { + return Err(DrawError::MissingImmediateData { + missing: pipeline + .immediate_slots_required + .difference(self.immediate_slots_set), + }); + } Ok(()) } else { Err(DrawError::MissingPipeline(pass::MissingPipeline)) @@ -602,6 +616,7 @@ impl<'scope, 'snatch_guard, 'cmd_enc> State<'scope, 'snatch_guard, 'cmd_enc> { self.pipeline = None; self.index.reset(); self.vertex = Default::default(); + self.immediate_slots_set = Default::default(); } } @@ -1966,6 +1981,8 @@ pub(super) fn encode_render_pass( string_offset: 0, }, + immediate_slots_set: Default::default(), + active_occlusion_query: None, active_pipeline_statistics_query: None, }; @@ -2042,6 +2059,8 @@ pub(super) fn encode_render_pass( |_| {}, ) .map_pass_err(scope)?; + state.immediate_slots_set |= + naga::valid::ImmediateSlots::from_range(offset, size_bytes); } ArcRenderCommand::SetScissor(rect) => { let scope = PassErrorScope::SetScissorRect; diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index 3c7777cad..eb6141122 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -3809,6 +3809,7 @@ impl Device { fn create_derived_pipeline_layout( self: &Arc, mut derived_group_layouts: Box>, + immediate_size: u32, ) -> Result, pipeline::ImplicitLayoutError> { while derived_group_layouts .last() @@ -3849,7 +3850,7 @@ impl Device { let layout_desc = binding_model::ResolvedPipelineLayoutDescriptor { label: None, bind_group_layouts: Cow::Owned(bind_group_layouts), - immediate_size: 0, //TODO? + immediate_size, }; let layout = self.create_pipeline_layout_impl(&layout_desc, true)?; @@ -3911,7 +3912,11 @@ impl Device { let pipeline_layout = match binding_layout_source { validation::BindingLayoutSource::Provided(pipeline_layout) => pipeline_layout, validation::BindingLayoutSource::Derived(entries) => { - self.create_derived_pipeline_layout(entries)? + let immediate_size = shader_module + .interface + .interface() + .map_or(0, |i| i.immediate_size); + self.create_derived_pipeline_layout(entries, immediate_size)? } }; @@ -3958,12 +3963,24 @@ impl Device { }, )?; + let immediate_slots_required = + shader_module + .interface + .interface() + .map_or(Default::default(), |iface| { + iface.immediate_slots_required( + naga::ShaderStage::Compute, + &final_entry_point_name, + ) + }); + let pipeline = pipeline::ComputePipeline { raw: ManuallyDrop::new(raw), layout: pipeline_layout, device: self.clone(), _shader_module: shader_module, late_sized_buffer_groups, + immediate_slots_required, label: desc.label.to_string(), tracking_data: TrackingData::new(self.tracker_indices.compute_pipelines.clone()), }; @@ -4401,6 +4418,7 @@ impl Device { let mut _vertex_entry_point_name = String::new(); let mut _task_entry_point_name = String::new(); let mut _mesh_entry_point_name = String::new(); + let mut immediate_slots_required = naga::valid::ImmediateSlots::default(); match desc.vertex { pipeline::RenderPipelineVertexProcessor::Vertex(ref vertex) => { vertex_stage = { @@ -4427,6 +4445,8 @@ impl Device { .map_err(stage_err)?; if let Some(interface) = vertex_shader_module.interface.interface() { + immediate_slots_required |= interface + .immediate_slots_required(stage.to_naga(), &_vertex_entry_point_name); io = interface .check_stage( &mut binding_layout_source, @@ -4471,6 +4491,8 @@ impl Device { .map_err(stage_err)?; if let Some(interface) = task_shader_module.interface.interface() { + immediate_slots_required |= interface + .immediate_slots_required(stage.to_naga(), &_task_entry_point_name); io = interface .check_stage( &mut binding_layout_source, @@ -4513,6 +4535,8 @@ impl Device { .map_err(stage_err)?; if let Some(interface) = mesh_shader_module.interface.interface() { + immediate_slots_required |= interface + .immediate_slots_required(stage.to_naga(), &_mesh_entry_point_name); io = interface .check_stage( &mut binding_layout_source, @@ -4565,6 +4589,8 @@ impl Device { .map_err(stage_err)?; if let Some(interface) = shader_module.interface.interface() { + immediate_slots_required |= interface + .immediate_slots_required(stage.to_naga(), &fragment_entry_point_name); io = interface .check_stage( &mut binding_layout_source, @@ -4629,7 +4655,26 @@ impl Device { let pipeline_layout = match binding_layout_source { validation::BindingLayoutSource::Provided(pipeline_layout) => pipeline_layout, validation::BindingLayoutSource::Derived(entries) => { - self.create_derived_pipeline_layout(entries)? + let immediate_size = { + let immediate_size_of = |sm: &pipeline::ShaderModule| { + sm.interface.interface().map(|i| i.immediate_size) + }; + let vertex = match desc.vertex { + pipeline::RenderPipelineVertexProcessor::Vertex(ref v) => { + immediate_size_of(&v.stage.module) + } + pipeline::RenderPipelineVertexProcessor::Mesh(ref task, ref mesh) => task + .as_ref() + .and_then(|t| immediate_size_of(&t.stage.module)) + .max(immediate_size_of(&mesh.stage.module)), + }; + let fragment = desc + .fragment + .as_ref() + .and_then(|f| immediate_size_of(&f.stage.module)); + vertex.max(fragment).unwrap_or(0) + }; + self.create_derived_pipeline_layout(entries, immediate_size)? } }; @@ -4773,6 +4818,7 @@ impl Device { strip_index_format: desc.primitive.strip_index_format, vertex_steps, late_sized_buffer_groups, + immediate_slots_required, label: desc.label.to_string(), tracking_data: TrackingData::new(self.tracker_indices.render_pipelines.clone()), is_mesh, diff --git a/wgpu-core/src/pipeline.rs b/wgpu-core/src/pipeline.rs index b8b669083..4b79f873c 100644 --- a/wgpu-core/src/pipeline.rs +++ b/wgpu-core/src/pipeline.rs @@ -304,6 +304,7 @@ pub struct ComputePipeline { pub(crate) device: Arc, pub(crate) _shader_module: Arc, pub(crate) late_sized_buffer_groups: ArrayVec, + pub(crate) immediate_slots_required: naga::valid::ImmediateSlots, /// The `label` from the descriptor used to create the resource. pub(crate) label: String, pub(crate) tracking_data: TrackingData, @@ -841,6 +842,7 @@ pub struct RenderPipeline { pub(crate) strip_index_format: Option, pub(crate) vertex_steps: Vec, pub(crate) late_sized_buffer_groups: ArrayVec, + pub(crate) immediate_slots_required: naga::valid::ImmediateSlots, /// The `label` from the descriptor used to create the resource. pub(crate) label: String, pub(crate) tracking_data: TrackingData, diff --git a/wgpu-core/src/validation.rs b/wgpu-core/src/validation.rs index 19e856d94..44d8b0fec 100644 --- a/wgpu-core/src/validation.rs +++ b/wgpu-core/src/validation.rs @@ -293,6 +293,7 @@ struct EntryPoint { dual_source_blending: bool, task_payload_size: Option, mesh_info: Option, + immediate_slots_required: naga::valid::ImmediateSlots, } #[derive(Debug)] @@ -300,6 +301,7 @@ pub struct Interface { limits: wgt::Limits, resources: naga::Arena, entry_points: FastHashMap<(naga::ShaderStage, String), EntryPoint>, + pub(crate) immediate_size: u32, } #[derive(Debug)] @@ -1254,6 +1256,8 @@ impl Interface { resource_mapping.insert(var_handle, handle); } + let immediate_size = naga::valid::ImmediateSlots::size_for_module(module); + let mut entry_points = FastHashMap::default(); entry_points.reserve(module.entry_points.len()); for (index, entry_point) in module.entry_points.iter().enumerate() { @@ -1284,6 +1288,7 @@ impl Interface { } ep.dual_source_blending = info.dual_source_blending; ep.workgroup_size = entry_point.workgroup_size; + ep.immediate_slots_required = info.immediate_slots_used; if let Some(task_payload) = entry_point.task_payload { ep.task_payload_size = Some( @@ -1323,9 +1328,20 @@ impl Interface { limits, resources, entry_points, + immediate_size, } } + pub fn immediate_slots_required( + &self, + stage: naga::ShaderStage, + entry_point_name: &str, + ) -> naga::valid::ImmediateSlots { + self.entry_points + .get(&(stage, entry_point_name.to_string())) + .map_or(Default::default(), |ep| ep.immediate_slots_required) + } + pub fn finalize_entry_point_name( &self, stage: naga::ShaderStage, diff --git a/wgpu-hal/src/auxil/mod.rs b/wgpu-hal/src/auxil/mod.rs index 18c356735..9d3d3d06c 100644 --- a/wgpu-hal/src/auxil/mod.rs +++ b/wgpu-hal/src/auxil/mod.rs @@ -187,6 +187,8 @@ pub(crate) fn adjust_raw_limits(mut limits: wgt::Limits) -> wgt::Limits { limits.max_compute_workgroup_size_z = z.min(m); limits.max_compute_invocations_per_workgroup = m.min(x.saturating_mul(y).saturating_mul(z)); + limits.max_immediate_size = limits.max_immediate_size.min(256); + limits }