Skip to main content

naga/valid/
mod.rs

1/*!
2Shader validator.
3*/
4
5mod analyzer;
6mod compose;
7mod expression;
8mod function;
9mod handles;
10pub(crate) mod immediates;
11mod interface;
12mod r#type;
13
14use alloc::{boxed::Box, string::String, vec, vec::Vec};
15use core::ops;
16
17use bit_set::BitSet;
18
19use crate::{
20    arena::{Handle, HandleSet},
21    proc::{ExpressionKindTracker, LayoutError, Layouter, TypeResolution},
22    FastHashSet,
23};
24
25//TODO: analyze the model at the same time as we validate it,
26// merge the corresponding matches over expressions and statements.
27
28use crate::span::{AddSpan as _, WithSpan};
29pub use analyzer::{ExpressionInfo, FunctionInfo, GlobalUse, Uniformity, UniformityRequirements};
30pub use compose::ComposeError;
31pub use expression::{check_literal_value, LiteralError};
32pub use expression::{ConstExpressionError, ExpressionError};
33pub use function::{CallError, FunctionError, LocalVariableError, SubgroupError};
34pub use immediates::{ImmediateSlots, ImmediateSlotsOverflowError, ImmediateUsage};
35pub use interface::{EntryPointError, GlobalVariableError, VaryingError};
36pub use r#type::{Disalignment, ImmediateError, TypeError, TypeFlags, WidthError};
37
38use self::handles::InvalidHandleError;
39
40/// Maximum size of a type, in bytes.
41pub const MAX_TYPE_SIZE: u32 = i32::MAX as u32;
42
43bitflags::bitflags! {
44    /// Validation flags.
45    ///
46    /// If you are working with trusted shaders, then you may be able
47    /// to save some time by skipping validation.
48    ///
49    /// If you do not perform full validation, invalid shaders may
50    /// cause Naga to panic. If you do perform full validation and
51    /// [`Validator::validate`] returns `Ok`, then Naga promises that
52    /// code generation will either succeed or return an error; it
53    /// should never panic.
54    ///
55    /// The default value for `ValidationFlags` is
56    /// `ValidationFlags::all()`.
57    #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
58    #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
59    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
60    pub struct ValidationFlags: u8 {
61        /// Expressions.
62        const EXPRESSIONS = 0x1;
63        /// Statements and blocks of them.
64        const BLOCKS = 0x2;
65        /// Uniformity of control flow for operations that require it.
66        const CONTROL_FLOW_UNIFORMITY = 0x4;
67        /// Host-shareable structure layouts.
68        const STRUCT_LAYOUTS = 0x8;
69        /// Constants.
70        const CONSTANTS = 0x10;
71        /// Group, binding, and location attributes.
72        const BINDINGS = 0x20;
73    }
74}
75
76impl Default for ValidationFlags {
77    fn default() -> Self {
78        Self::all()
79    }
80}
81
82bitflags::bitflags! {
83    /// Allowed IR capabilities.
84    #[must_use]
85    #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
86    #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
87    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
88    pub struct Capabilities: u64 {
89        /// Support for [`AddressSpace::Immediate`][1].
90        ///
91        /// [1]: crate::AddressSpace::Immediate
92        const IMMEDIATES = 1 << 0;
93        /// Float values with width = 8.
94        const FLOAT64 = 1 << 1;
95        /// Support for [`BuiltIn::PrimitiveIndex`][1].
96        ///
97        /// [1]: crate::BuiltIn::PrimitiveIndex
98        const PRIMITIVE_INDEX = 1 << 2;
99        /// Support for binding arrays of sampled textures and samplers.
100        const TEXTURE_AND_SAMPLER_BINDING_ARRAY = 1 << 3;
101        /// Support for binding arrays of uniform buffers.
102        const BUFFER_BINDING_ARRAY = 1 << 4;
103        /// Support for binding arrays of storage textures.
104        const STORAGE_TEXTURE_BINDING_ARRAY = 1 << 5;
105        /// Support for binding arrays of storage buffers.
106        const STORAGE_BUFFER_BINDING_ARRAY = 1 << 6;
107        /// Support for [`BuiltIn::ClipDistances`].
108        ///
109        /// [`BuiltIn::ClipDistances`]: crate::BuiltIn::ClipDistances
110        const CLIP_DISTANCES = 1 << 7;
111        /// Support for [`BuiltIn::CullDistance`].
112        ///
113        /// [`BuiltIn::CullDistance`]: crate::BuiltIn::CullDistance
114        const CULL_DISTANCE = 1 << 8;
115        /// Support for 16-bit normalized storage texture formats.
116        const STORAGE_TEXTURE_16BIT_NORM_FORMATS = 1 << 9;
117        /// Support for [`BuiltIn::ViewIndex`].
118        ///
119        /// [`BuiltIn::ViewIndex`]: crate::BuiltIn::ViewIndex
120        const MULTIVIEW = 1 << 10;
121        /// Support for `early_depth_test`.
122        const EARLY_DEPTH_TEST = 1 << 11;
123        /// Support for [`BuiltIn::SampleIndex`] and [`Sampling::Sample`].
124        ///
125        /// [`BuiltIn::SampleIndex`]: crate::BuiltIn::SampleIndex
126        /// [`Sampling::Sample`]: crate::Sampling::Sample
127        const MULTISAMPLED_SHADING = 1 << 12;
128        /// Support for ray queries and acceleration structures.
129        const RAY_QUERY = 1 << 13;
130        /// Support for generating two sources for blending from fragment shaders.
131        const DUAL_SOURCE_BLENDING = 1 << 14;
132        /// Support for arrayed cube textures.
133        const CUBE_ARRAY_TEXTURES = 1 << 15;
134        /// Support for 64-bit signed and unsigned integers.
135        const SHADER_INT64 = 1 << 16;
136        /// Support for subgroup operations (except barriers) in fragment and compute shaders.
137        ///
138        /// Subgroup operations in the vertex stage require
139        /// [`Capabilities::SUBGROUP_VERTEX_STAGE`] in addition to `Capabilities::SUBGROUP`.
140        /// (But note that `create_validator` automatically sets
141        /// `Capabilities::SUBGROUP` whenever `Features::SUBGROUP_VERTEX` is
142        /// available.)
143        ///
144        /// Subgroup barriers require [`Capabilities::SUBGROUP_BARRIER`] in addition to
145        /// `Capabilities::SUBGROUP`.
146        const SUBGROUP = 1 << 17;
147        /// Support for subgroup barriers in compute shaders.
148        ///
149        /// Requires [`Capabilities::SUBGROUP`]. Without it, enables nothing.
150        const SUBGROUP_BARRIER = 1 << 18;
151        /// Support for subgroup operations (not including barriers) in the vertex stage.
152        ///
153        /// Without [`Capabilities::SUBGROUP`], enables nothing. (But note that
154        /// `create_validator` automatically sets `Capabilities::SUBGROUP`
155        /// whenever `Features::SUBGROUP_VERTEX` is available.)
156        const SUBGROUP_VERTEX_STAGE = 1 << 19;
157        /// Support for [`AtomicFunction::Min`] and [`AtomicFunction::Max`] on
158        /// 64-bit integers in the [`Storage`] address space, when the return
159        /// value is not used.
160        ///
161        /// This is the only 64-bit atomic functionality available on Metal 3.1.
162        ///
163        /// [`AtomicFunction::Min`]: crate::AtomicFunction::Min
164        /// [`AtomicFunction::Max`]: crate::AtomicFunction::Max
165        /// [`Storage`]: crate::AddressSpace::Storage
166        const SHADER_INT64_ATOMIC_MIN_MAX = 1 << 20;
167        /// Support for all atomic operations on 64-bit integers.
168        const SHADER_INT64_ATOMIC_ALL_OPS = 1 << 21;
169        /// Support for [`AtomicFunction::Add`], [`AtomicFunction::Sub`],
170        /// and [`AtomicFunction::Exchange { compare: None }`] on 32-bit floating-point numbers
171        /// in the [`Storage`] address space.
172        ///
173        /// [`AtomicFunction::Add`]: crate::AtomicFunction::Add
174        /// [`AtomicFunction::Sub`]: crate::AtomicFunction::Sub
175        /// [`AtomicFunction::Exchange { compare: None }`]: crate::AtomicFunction::Exchange
176        /// [`Storage`]: crate::AddressSpace::Storage
177        const SHADER_FLOAT32_ATOMIC = 1 << 22;
178        /// Support for atomic operations on images.
179        const TEXTURE_ATOMIC = 1 << 23;
180        /// Support for atomic operations on 64-bit images.
181        const TEXTURE_INT64_ATOMIC = 1 << 24;
182        /// Support for ray queries returning vertex position
183        const RAY_HIT_VERTEX_POSITION = 1 << 25;
184        /// Support for 16-bit floating-point types.
185        const SHADER_FLOAT16 = 1 << 26;
186        /// Support for [`ImageClass::External`]
187        const TEXTURE_EXTERNAL = 1 << 27;
188        /// Support for fragment shader barycentric coordinates.
189        const SHADER_BARYCENTRICS = 1 << 29;
190        /// Support for task shaders, mesh shaders, and per-primitive fragment inputs
191        const MESH_SHADER = 1 << 30;
192        /// Support for mesh shaders which output points.
193        const MESH_SHADER_POINT_TOPOLOGY = 1 << 31;
194        /// Support for non-uniform indexing of binding arrays of sampled textures and samplers.
195        const TEXTURE_AND_SAMPLER_BINDING_ARRAY_NON_UNIFORM_INDEXING = 1 << 32;
196        /// Support for non-uniform indexing of binding arrays of uniform buffers.
197        const BUFFER_BINDING_ARRAY_NON_UNIFORM_INDEXING = 1 << 33;
198        /// Support for non-uniform indexing of binding arrays of storage textures.
199        const STORAGE_TEXTURE_BINDING_ARRAY_NON_UNIFORM_INDEXING = 1 << 34;
200        /// Support for non-uniform indexing of binding arrays of storage buffers.
201        const STORAGE_BUFFER_BINDING_ARRAY_NON_UNIFORM_INDEXING = 1 << 35;
202        /// Support for cooperative matrix types and operations
203        const COOPERATIVE_MATRIX = 1 << 36;
204        /// Support for per-vertex fragment input.
205        const PER_VERTEX = 1 << 37;
206        /// Support for ray generation, any hit, closest hit, and miss shaders.
207        const RAY_TRACING_PIPELINE = 1 << 38;
208        /// Support for draw index builtin
209        const DRAW_INDEX = 1 << 39;
210        /// Support for binding arrays of acceleration structures.
211        const ACCELERATION_STRUCTURE_BINDING_ARRAY = 1 << 40;
212        /// Support for the `@coherent` memory decoration on storage buffers.
213        const MEMORY_DECORATION_COHERENT = 1 << 41;
214        /// Support for the `@volatile` memory decoration on storage buffers.
215        const MEMORY_DECORATION_VOLATILE = 1 << 42;
216        /// Support for 16-bit integer types.
217        const SHADER_INT16 = 1 << 43;
218        /// Support for [`Interpolation::Linear`] (`@interpolate(linear)` in WGSL).
219        ///
220        /// This is core WebGPU, but GLSL ES (and thus WebGL) has no `noperspective` qualifier (unless enabled by extensions).
221        ///
222        /// [`Interpolation::Linear`]: crate::Interpolation::Linear
223        const LINEAR_INTERPOLATION = 1 << 44;
224        /// Support for `debugPrintf`.
225        const DEBUG_PRINTF = 1 << 45;
226        /// Support for ray tracing invocation reordering: the `hit_object` type,
227        /// the `hitObject*` built-in functions, and `reorderThread`.
228        ///
229        /// Only useful together with [`Capabilities::RAY_TRACING_PIPELINE`], since
230        /// hit objects exist only in ray tracing pipeline stages.
231        const RAY_TRACING_INVOCATION_REORDER = 1 << 46;
232
233        // Free flag slot at 1 << 28
234    }
235}
236
237impl Capabilities {
238    /// Returns the extension corresponding to this capability, if there is one.
239    ///
240    /// This is used by integration tests.
241    #[cfg(feature = "wgsl-in")]
242    #[doc(hidden)]
243    pub const fn extension(&self) -> Option<crate::front::wgsl::ImplementedEnableExtension> {
244        use crate::front::wgsl::ImplementedEnableExtension as Ext;
245        match *self {
246            Self::DUAL_SOURCE_BLENDING => Some(Ext::DualSourceBlending),
247            // NOTE: `SHADER_FLOAT16_IN_FLOAT32` _does not_ require the `f16` extension
248            Self::SHADER_FLOAT16 => Some(Ext::F16),
249            Self::FLOAT64 => Some(Ext::WgpuF64),
250            Self::SHADER_INT16 => Some(Ext::WgpuInt16),
251            Self::CLIP_DISTANCES => Some(Ext::ClipDistances),
252            Self::MESH_SHADER => Some(Ext::WgpuMeshShader),
253            Self::RAY_QUERY => Some(Ext::WgpuRayQuery),
254            Self::RAY_HIT_VERTEX_POSITION => Some(Ext::WgpuRayQueryVertexReturn),
255            Self::COOPERATIVE_MATRIX => Some(Ext::WgpuCooperativeMatrix),
256            Self::RAY_TRACING_PIPELINE => Some(Ext::WgpuRayTracingPipeline),
257            Self::RAY_TRACING_INVOCATION_REORDER => Some(Ext::WgpuRayTracingInvocationReorder),
258            Self::PER_VERTEX => Some(Ext::WgpuPerVertex),
259            Self::BUFFER_BINDING_ARRAY
260            | Self::BUFFER_BINDING_ARRAY_NON_UNIFORM_INDEXING
261            | Self::STORAGE_BUFFER_BINDING_ARRAY
262            | Self::STORAGE_BUFFER_BINDING_ARRAY_NON_UNIFORM_INDEXING
263            | Self::STORAGE_TEXTURE_BINDING_ARRAY
264            | Self::STORAGE_TEXTURE_BINDING_ARRAY_NON_UNIFORM_INDEXING
265            | Self::TEXTURE_AND_SAMPLER_BINDING_ARRAY
266            | Self::TEXTURE_AND_SAMPLER_BINDING_ARRAY_NON_UNIFORM_INDEXING => {
267                Some(Ext::WgpuBindingArray)
268            }
269            Self::DEBUG_PRINTF => Some(Ext::WgpuDebugPrintf),
270            _ => None,
271        }
272    }
273}
274
275impl Default for Capabilities {
276    fn default() -> Self {
277        Self::MULTISAMPLED_SHADING | Self::CUBE_ARRAY_TEXTURES
278    }
279}
280
281bitflags::bitflags! {
282    /// Supported subgroup operations
283    #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
284    #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
285    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
286    pub struct SubgroupOperationSet: u8 {
287        /// Barriers
288        // Possibly elections, when that is supported.
289        // https://github.com/gfx-rs/wgpu/issues/6042#issuecomment-3272603431
290        // Contrary to what the name "basic" suggests, HLSL/DX12 support the
291        // other subgroup operations, but do not support subgroup barriers.
292        const BASIC = 1 << 0;
293        /// Any, All
294        const VOTE = 1 << 1;
295        /// reductions, scans
296        const ARITHMETIC = 1 << 2;
297        /// ballot, broadcast
298        const BALLOT = 1 << 3;
299        /// shuffle, shuffle xor
300        const SHUFFLE = 1 << 4;
301        /// shuffle up, down
302        const SHUFFLE_RELATIVE = 1 << 5;
303        // We don't support these operations yet
304        // /// Clustered
305        // const CLUSTERED = 1 << 6;
306        /// Quad supported
307        const QUAD_FRAGMENT_COMPUTE = 1 << 7;
308        // /// Quad supported in all stages
309        // const QUAD_ALL_STAGES = 1 << 8;
310    }
311}
312
313impl super::SubgroupOperation {
314    const fn required_operations(&self) -> SubgroupOperationSet {
315        use SubgroupOperationSet as S;
316        match *self {
317            Self::All | Self::Any => S::VOTE,
318            Self::Add | Self::Mul | Self::Min | Self::Max | Self::And | Self::Or | Self::Xor => {
319                S::ARITHMETIC
320            }
321        }
322    }
323}
324
325impl super::GatherMode {
326    const fn required_operations(&self) -> SubgroupOperationSet {
327        use SubgroupOperationSet as S;
328        match *self {
329            Self::BroadcastFirst | Self::Broadcast(_) => S::BALLOT,
330            Self::Shuffle(_) | Self::ShuffleXor(_) => S::SHUFFLE,
331            Self::ShuffleUp(_) | Self::ShuffleDown(_) => S::SHUFFLE_RELATIVE,
332            Self::QuadBroadcast(_) | Self::QuadSwap(_) => S::QUAD_FRAGMENT_COMPUTE,
333        }
334    }
335}
336
337bitflags::bitflags! {
338    /// Validation flags.
339    #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
340    #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
341    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
342    pub struct ShaderStages: u16 {
343        const VERTEX = 0x1;
344        const FRAGMENT = 0x2;
345        const COMPUTE = 0x4;
346        const MESH = 0x8;
347        const TASK = 0x10;
348        const RAY_GENERATION = 0x20;
349        const ANY_HIT = 0x40;
350        const CLOSEST_HIT = 0x80;
351        const MISS = 0x100;
352        const COMPUTE_LIKE = Self::COMPUTE.bits() | Self::TASK.bits() | Self::MESH.bits();
353    }
354}
355
356#[derive(Debug, Clone, Default)]
357#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
358#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
359pub struct ModuleInfo {
360    type_flags: Vec<TypeFlags>,
361    functions: Vec<FunctionInfo>,
362    entry_points: Vec<FunctionInfo>,
363    const_expression_types: Box<[TypeResolution]>,
364}
365
366impl ops::Index<Handle<crate::Type>> for ModuleInfo {
367    type Output = TypeFlags;
368    fn index(&self, handle: Handle<crate::Type>) -> &Self::Output {
369        &self.type_flags[handle.index()]
370    }
371}
372
373impl ops::Index<Handle<crate::Function>> for ModuleInfo {
374    type Output = FunctionInfo;
375    fn index(&self, handle: Handle<crate::Function>) -> &Self::Output {
376        &self.functions[handle.index()]
377    }
378}
379
380impl ops::Index<Handle<crate::Expression>> for ModuleInfo {
381    type Output = TypeResolution;
382    fn index(&self, handle: Handle<crate::Expression>) -> &Self::Output {
383        &self.const_expression_types[handle.index()]
384    }
385}
386
387#[derive(Debug)]
388pub struct Validator {
389    flags: ValidationFlags,
390    capabilities: Capabilities,
391    subgroup_stages: ShaderStages,
392    subgroup_operations: SubgroupOperationSet,
393    types: Vec<r#type::TypeInfo>,
394    layouter: Layouter,
395    location_mask: BitSet,
396    ep_resource_bindings: FastHashSet<crate::ResourceBinding>,
397    switch_values: FastHashSet<crate::SwitchValue>,
398    valid_expression_list: Vec<Handle<crate::Expression>>,
399    valid_expression_set: HandleSet<crate::Expression>,
400    override_ids: FastHashSet<u16>,
401
402    /// Treat overrides whose initializers are not fully-evaluated
403    /// constant expressions as errors.
404    overrides_resolved: bool,
405
406    /// A checklist of expressions that must be visited by a specific kind of
407    /// statement.
408    ///
409    /// For example:
410    ///
411    /// - [`CallResult`] expressions must be visited by a [`Call`] statement.
412    /// - [`AtomicResult`] expressions must be visited by an [`Atomic`] statement.
413    ///
414    /// Be sure not to remove any [`Expression`] handle from this set unless
415    /// you've explicitly checked that it is the right kind of expression for
416    /// the visiting [`Statement`].
417    ///
418    /// [`CallResult`]: crate::Expression::CallResult
419    /// [`Call`]: crate::Statement::Call
420    /// [`AtomicResult`]: crate::Expression::AtomicResult
421    /// [`Atomic`]: crate::Statement::Atomic
422    /// [`Expression`]: crate::Expression
423    /// [`Statement`]: crate::Statement
424    needs_visit: HandleSet<crate::Expression>,
425
426    /// Whether any trace rays call is called, and whether all have vertex return.
427    /// If one call doesn't use vertex ruturn, builtins for triangle vertex positions
428    /// (not yet implemented) are not allowed.
429    trace_rays_vertex_return: TraceRayVertexReturnState,
430
431    /// The type of the ray payload, this must always be the same type in a particular
432    /// entrypoint
433    trace_rays_payload_type: Option<Handle<crate::Type>>,
434}
435
436#[derive(Debug)]
437enum TraceRayVertexReturnState {
438    /// No trace ray calls yet have been found.
439    NoTraceRays,
440    /// Trace ray calls have been found, at least
441    /// one uses an acceleration structure that
442    /// does not have the flag enabling vertex return.
443    #[expect(
444        unused,
445        reason = "Don't yet have vertex return builtins to return this error for."
446    )]
447    NoVertexReturn(crate::Span),
448    /// Trace ray calls have been found, all
449    /// acceleration structures have the flag enabling
450    /// vertex return.
451    VertexReturn,
452}
453
454#[derive(Clone, Debug, thiserror::Error)]
455#[cfg_attr(test, derive(PartialEq))]
456pub enum ConstantError {
457    #[error("Initializer must be a const-expression")]
458    InitializerExprType,
459    #[error("The type doesn't match the constant")]
460    InvalidType,
461    #[error("The type is not constructible")]
462    NonConstructibleType,
463}
464
465#[derive(Clone, Debug, thiserror::Error)]
466#[cfg_attr(test, derive(PartialEq))]
467pub enum OverrideError {
468    #[error("Override name and ID are missing")]
469    MissingNameAndID,
470    #[error("Override ID must be unique")]
471    DuplicateID,
472    #[error("Initializer must be a const-expression or override-expression")]
473    InitializerExprType,
474    #[error("The type doesn't match the override")]
475    InvalidType,
476    #[error("The type is not constructible")]
477    NonConstructibleType,
478    #[error("The type is not a scalar")]
479    TypeNotScalar,
480    #[error("Override declarations are not allowed")]
481    NotAllowed,
482    #[error("Override is uninitialized")]
483    UninitializedOverride,
484    #[error("Constant expression {handle:?} is invalid")]
485    ConstExpression {
486        handle: Handle<crate::Expression>,
487        source: ConstExpressionError,
488    },
489}
490
491#[derive(Clone, Debug, thiserror::Error)]
492#[cfg_attr(test, derive(PartialEq))]
493pub enum ValidationError {
494    #[error(transparent)]
495    InvalidHandle(#[from] InvalidHandleError),
496    #[error(transparent)]
497    Layouter(#[from] LayoutError),
498    #[error("Type {handle:?} '{name}' is invalid")]
499    Type {
500        handle: Handle<crate::Type>,
501        name: String,
502        source: TypeError,
503    },
504    #[error("Constant expression {handle:?} is invalid")]
505    ConstExpression {
506        handle: Handle<crate::Expression>,
507        source: ConstExpressionError,
508    },
509    #[error("Array size expression {handle:?} is not strictly positive")]
510    ArraySizeError { handle: Handle<crate::Expression> },
511    #[error("Constant {handle:?} '{name}' is invalid")]
512    Constant {
513        handle: Handle<crate::Constant>,
514        name: String,
515        source: ConstantError,
516    },
517    #[error("Override {handle:?} '{name}' is invalid")]
518    Override {
519        handle: Handle<crate::Override>,
520        name: String,
521        source: OverrideError,
522    },
523    #[error("Global variable {handle:?} '{name}' is invalid")]
524    GlobalVariable {
525        handle: Handle<crate::GlobalVariable>,
526        name: String,
527        source: GlobalVariableError,
528    },
529    #[error("Function {handle:?} '{name}' is invalid")]
530    Function {
531        handle: Handle<crate::Function>,
532        name: String,
533        source: FunctionError,
534    },
535    #[error("Entry point {name} at {stage:?} is invalid")]
536    EntryPoint {
537        stage: crate::ShaderStage,
538        name: String,
539        source: EntryPointError,
540    },
541    #[error("Module is corrupted")]
542    Corrupted,
543}
544
545impl crate::TypeInner {
546    const fn is_sized(&self) -> bool {
547        match *self {
548            Self::Scalar { .. }
549            | Self::Vector { .. }
550            | Self::Matrix { .. }
551            | Self::CooperativeMatrix { .. }
552            | Self::Array {
553                size: crate::ArraySize::Constant(_),
554                ..
555            }
556            | Self::Atomic { .. }
557            | Self::Pointer { .. }
558            | Self::ValuePointer { .. }
559            | Self::Struct { .. } => true,
560            Self::Array { .. }
561            | Self::Image { .. }
562            | Self::Sampler { .. }
563            | Self::AccelerationStructure { .. }
564            | Self::RayQuery { .. }
565            | Self::HitObject
566            | Self::BindingArray { .. } => false,
567        }
568    }
569
570    /// Return the `ImageDimension` for which `self` is an appropriate coordinate.
571    const fn image_storage_coordinates(&self) -> Option<crate::ImageDimension> {
572        match *self {
573            Self::Scalar(crate::Scalar {
574                kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
575                ..
576            }) => Some(crate::ImageDimension::D1),
577            Self::Vector {
578                size: crate::VectorSize::Bi,
579                scalar:
580                    crate::Scalar {
581                        kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
582                        ..
583                    },
584            } => Some(crate::ImageDimension::D2),
585            Self::Vector {
586                size: crate::VectorSize::Tri,
587                scalar:
588                    crate::Scalar {
589                        kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
590                        ..
591                    },
592            } => Some(crate::ImageDimension::D3),
593            _ => None,
594        }
595    }
596}
597
598impl Validator {
599    /// Create a validator for Naga [`Module`]s.
600    ///
601    /// The `flags` argument indicates which stages of validation the
602    /// returned `Validator` should perform. Skipping stages can make
603    /// validation somewhat faster, but the validator may not reject some
604    /// invalid modules. Regardless of `flags`, validation always returns
605    /// a usable [`ModuleInfo`] value on success.
606    ///
607    /// If `flags` contains everything in `ValidationFlags::default()`,
608    /// then the returned Naga [`Validator`] will reject any [`Module`]
609    /// that would use capabilities not included in `capabilities`.
610    ///
611    /// [`Module`]: crate::Module
612    pub fn new(flags: ValidationFlags, capabilities: Capabilities) -> Self {
613        let subgroup_operations = if capabilities.contains(Capabilities::SUBGROUP) {
614            use SubgroupOperationSet as S;
615            S::BASIC
616                | S::VOTE
617                | S::ARITHMETIC
618                | S::BALLOT
619                | S::SHUFFLE
620                | S::SHUFFLE_RELATIVE
621                | S::QUAD_FRAGMENT_COMPUTE
622        } else {
623            SubgroupOperationSet::empty()
624        };
625        let subgroup_stages = {
626            let mut stages = ShaderStages::empty();
627            if capabilities.contains(Capabilities::SUBGROUP_VERTEX_STAGE) {
628                stages |= ShaderStages::VERTEX;
629            }
630            if capabilities.contains(Capabilities::SUBGROUP) {
631                stages |= ShaderStages::FRAGMENT | ShaderStages::COMPUTE_LIKE;
632            }
633            stages
634        };
635
636        Validator {
637            flags,
638            capabilities,
639            subgroup_stages,
640            subgroup_operations,
641            types: Vec::new(),
642            layouter: Layouter::default(),
643            location_mask: BitSet::new(),
644            ep_resource_bindings: FastHashSet::default(),
645            switch_values: FastHashSet::default(),
646            valid_expression_list: Vec::new(),
647            valid_expression_set: HandleSet::new(),
648            override_ids: FastHashSet::default(),
649            overrides_resolved: false,
650            needs_visit: HandleSet::new(),
651            trace_rays_vertex_return: TraceRayVertexReturnState::NoTraceRays,
652            trace_rays_payload_type: None,
653        }
654    }
655
656    // TODO(https://github.com/gfx-rs/wgpu/issues/8207): Consider removing this
657    pub const fn subgroup_stages(&mut self, stages: ShaderStages) -> &mut Self {
658        self.subgroup_stages = stages;
659        self
660    }
661
662    // TODO(https://github.com/gfx-rs/wgpu/issues/8207): Consider removing this
663    pub const fn subgroup_operations(&mut self, operations: SubgroupOperationSet) -> &mut Self {
664        self.subgroup_operations = operations;
665        self
666    }
667
668    /// Reset the validator internals
669    pub fn reset(&mut self) {
670        self.types.clear();
671        self.layouter.clear();
672        self.location_mask.make_empty();
673        self.ep_resource_bindings.clear();
674        self.switch_values.clear();
675        self.valid_expression_list.clear();
676        self.valid_expression_set.clear();
677        self.override_ids.clear();
678        self.trace_rays_vertex_return = TraceRayVertexReturnState::NoTraceRays;
679        self.trace_rays_payload_type = None;
680    }
681
682    fn validate_constant(
683        &self,
684        handle: Handle<crate::Constant>,
685        gctx: crate::proc::GlobalCtx,
686        mod_info: &ModuleInfo,
687        global_expr_kind: &ExpressionKindTracker,
688    ) -> Result<(), ConstantError> {
689        let con = &gctx.constants[handle];
690
691        let type_info = &self.types[con.ty.index()];
692        if !type_info.flags.contains(TypeFlags::CONSTRUCTIBLE) {
693            return Err(ConstantError::NonConstructibleType);
694        }
695
696        if !global_expr_kind.is_const(con.init) {
697            return Err(ConstantError::InitializerExprType);
698        }
699
700        if !gctx.compare_types(&TypeResolution::Handle(con.ty), &mod_info[con.init]) {
701            return Err(ConstantError::InvalidType);
702        }
703
704        Ok(())
705    }
706
707    fn validate_override(
708        &mut self,
709        handle: Handle<crate::Override>,
710        gctx: crate::proc::GlobalCtx,
711        mod_info: &ModuleInfo,
712    ) -> Result<(), OverrideError> {
713        let o = &gctx.overrides[handle];
714
715        if let Some(id) = o.id {
716            if !self.override_ids.insert(id) {
717                return Err(OverrideError::DuplicateID);
718            }
719        }
720
721        let type_info = &self.types[o.ty.index()];
722        if !type_info.flags.contains(TypeFlags::CONSTRUCTIBLE) {
723            return Err(OverrideError::NonConstructibleType);
724        }
725
726        match gctx.types[o.ty].inner {
727            crate::TypeInner::Scalar(
728                crate::Scalar::BOOL
729                | crate::Scalar::I16
730                | crate::Scalar::U16
731                | crate::Scalar::I32
732                | crate::Scalar::U32
733                | crate::Scalar::F16
734                | crate::Scalar::F32
735                | crate::Scalar::F64,
736            ) => {}
737            _ => return Err(OverrideError::TypeNotScalar),
738        }
739
740        if let Some(init) = o.init {
741            if !gctx.compare_types(&TypeResolution::Handle(o.ty), &mod_info[init]) {
742                return Err(OverrideError::InvalidType);
743            }
744        } else if self.overrides_resolved {
745            return Err(OverrideError::UninitializedOverride);
746        }
747
748        Ok(())
749    }
750
751    /// Check the given module to be valid.
752    pub fn validate(
753        &mut self,
754        module: &crate::Module,
755    ) -> Result<ModuleInfo, Box<WithSpan<ValidationError>>> {
756        self.overrides_resolved = false;
757        self.validate_impl(module)
758    }
759
760    /// Check the given module to be valid, requiring overrides to be resolved.
761    ///
762    /// This is the same as [`validate`], except that any override
763    /// whose value is not a fully-evaluated constant expression is
764    /// treated as an error.
765    ///
766    /// [`validate`]: Validator::validate
767    pub fn validate_resolved_overrides(
768        &mut self,
769        module: &crate::Module,
770    ) -> Result<ModuleInfo, Box<WithSpan<ValidationError>>> {
771        self.overrides_resolved = true;
772        self.validate_impl(module)
773    }
774
775    fn validate_impl(
776        &mut self,
777        module: &crate::Module,
778    ) -> Result<ModuleInfo, Box<WithSpan<ValidationError>>> {
779        self.reset();
780        self.reset_types(module.types.len());
781
782        Self::validate_module_handles(module).map_err(|e| Box::new((*e).with_span()))?;
783
784        self.layouter.update(module.to_ctx()).map_err(|e| {
785            let handle = e.ty;
786            ValidationError::from(e).with_span_handle(handle, &module.types)
787        })?;
788
789        // These should all get overwritten.
790        let placeholder = TypeResolution::Value(crate::TypeInner::Scalar(crate::Scalar {
791            kind: crate::ScalarKind::Bool,
792            width: 0,
793        }));
794
795        let mut mod_info = ModuleInfo {
796            type_flags: Vec::with_capacity(module.types.len()),
797            functions: Vec::with_capacity(module.functions.len()),
798            entry_points: Vec::with_capacity(module.entry_points.len()),
799            const_expression_types: vec![placeholder; module.global_expressions.len()]
800                .into_boxed_slice(),
801        };
802
803        for (handle, ty) in module.types.iter() {
804            let ty_info = self
805                .validate_type(handle, module.to_ctx())
806                .map_err(|source| {
807                    ValidationError::Type {
808                        handle,
809                        name: ty.name.clone().unwrap_or_default(),
810                        source,
811                    }
812                    .with_span_handle(handle, &module.types)
813                })?;
814            debug_assert!(
815                ty_info.flags.contains(TypeFlags::CONSTRUCTIBLE)
816                    == module.types[handle].inner.is_constructible(&module.types)
817            );
818            mod_info.type_flags.push(ty_info.flags);
819            self.types[handle.index()] = ty_info;
820        }
821
822        {
823            let t = crate::Arena::new();
824            let resolve_context = crate::proc::ResolveContext::with_locals(module, &t, &[]);
825            for (handle, _) in module.global_expressions.iter() {
826                mod_info
827                    .process_const_expression(handle, &resolve_context, module.to_ctx())
828                    .map_err(|source| {
829                        ValidationError::ConstExpression { handle, source }
830                            .with_span_handle(handle, &module.global_expressions)
831                    })?
832            }
833        }
834
835        let global_expr_kind = ExpressionKindTracker::from_arena(&module.global_expressions);
836
837        if self.flags.contains(ValidationFlags::CONSTANTS) {
838            for (handle, _) in module.global_expressions.iter() {
839                self.validate_const_expression(
840                    handle,
841                    module.to_ctx(),
842                    &mod_info,
843                    &global_expr_kind,
844                )
845                .map_err(|source| {
846                    ValidationError::ConstExpression { handle, source }
847                        .with_span_handle(handle, &module.global_expressions)
848                })?
849            }
850
851            for (handle, constant) in module.constants.iter() {
852                self.validate_constant(handle, module.to_ctx(), &mod_info, &global_expr_kind)
853                    .map_err(|source| {
854                        ValidationError::Constant {
855                            handle,
856                            name: constant.name.clone().unwrap_or_default(),
857                            source,
858                        }
859                        .with_span_handle(handle, &module.constants)
860                    })?
861            }
862
863            for (handle, r#override) in module.overrides.iter() {
864                self.validate_override(handle, module.to_ctx(), &mod_info)
865                    .map_err(|source| {
866                        ValidationError::Override {
867                            handle,
868                            name: r#override.name.clone().unwrap_or_default(),
869                            source,
870                        }
871                        .with_span_handle(handle, &module.overrides)
872                    })?;
873            }
874        }
875
876        for (var_handle, var) in module.global_variables.iter() {
877            self.validate_global_var(var, module.to_ctx(), &mod_info, &global_expr_kind)
878                .map_err(|source| {
879                    ValidationError::GlobalVariable {
880                        handle: var_handle,
881                        name: var.name.clone().unwrap_or_default(),
882                        source,
883                    }
884                    .with_span_handle(var_handle, &module.global_variables)
885                })?;
886        }
887
888        for (handle, fun) in module.functions.iter() {
889            match self.validate_function(fun, module, &mod_info, false) {
890                Ok(info) => mod_info.functions.push(info),
891                Err(error) => {
892                    return Err(Box::new(error.and_then(|source| {
893                        ValidationError::Function {
894                            handle,
895                            name: fun.name.clone().unwrap_or_default(),
896                            source,
897                        }
898                        .with_span_handle(handle, &module.functions)
899                    })))
900                }
901            }
902        }
903
904        let mut ep_map = FastHashSet::default();
905        for ep in module.entry_points.iter() {
906            if !ep_map.insert((ep.stage, &ep.name)) {
907                return Err(Box::new(
908                    ValidationError::EntryPoint {
909                        stage: ep.stage,
910                        name: ep.name.clone(),
911                        source: EntryPointError::Conflict,
912                    }
913                    .with_span(),
914                )); // TODO: keep some EP span information?
915            }
916
917            match self.validate_entry_point(ep, module, &mod_info) {
918                Ok(info) => {
919                    mod_info.entry_points.push(info);
920                }
921                Err(error) => {
922                    return Err(Box::new(error.and_then(|source| {
923                        ValidationError::EntryPoint {
924                            stage: ep.stage,
925                            name: ep.name.clone(),
926                            source,
927                        }
928                        .with_span()
929                    })));
930                }
931            }
932        }
933
934        Ok(mod_info)
935    }
936}
937
938fn validate_atomic_compare_exchange_struct(
939    types: &crate::UniqueArena<crate::Type>,
940    members: &[crate::StructMember],
941    scalar_predicate: impl FnOnce(&crate::TypeInner) -> bool,
942) -> bool {
943    members.len() == 2
944        && members[0].name.as_deref() == Some("old_value")
945        && scalar_predicate(&types[members[0].ty].inner)
946        && members[1].name.as_deref() == Some("exchanged")
947        && types[members[1].ty].inner == crate::TypeInner::Scalar(crate::Scalar::BOOL)
948}