naga/ir/mod.rs
1/*!
2The Intermediate Representation shared by all frontends and backends.
3
4The central structure of the IR, and the crate, is [`Module`]. A `Module` contains:
5
6- [`Function`]s, which have arguments, a return type, local variables, and a body,
7
8- [`EntryPoint`]s, which are specialized functions that can serve as the entry
9 point for pipeline stages like vertex shading or fragment shading,
10
11- [`Constant`]s and [`GlobalVariable`]s used by `EntryPoint`s and `Function`s, and
12
13- [`Type`]s used by the above.
14
15The body of an `EntryPoint` or `Function` is represented using two types:
16
17- An [`Expression`] produces a value, but has no side effects or control flow.
18 `Expressions` include variable references, unary and binary operators, and so
19 on.
20
21- A [`Statement`] can have side effects and structured control flow.
22 `Statement`s do not produce a value, other than by storing one in some
23 designated place. `Statements` include blocks, conditionals, and loops, but also
24 operations that have side effects, like stores and function calls.
25
26`Statement`s form a tree, with pointers into the DAG of `Expression`s.
27
28Restricting side effects to statements simplifies analysis and code generation.
29A Naga backend can generate code to evaluate an `Expression` however and
30whenever it pleases, as long as it is certain to observe the side effects of all
31previously executed `Statement`s.
32
33Many `Statement` variants use the [`Block`] type, which is `Vec<Statement>`,
34with optional span info, representing a series of statements executed in order. The body of an
35`EntryPoint`s or `Function` is a `Block`, and `Statement` has a
36[`Block`][Statement::Block] variant.
37
38## Function Calls
39
40Naga's representation of function calls is unusual. Most languages treat
41function calls as expressions, but because calls may have side effects, Naga
42represents them as a kind of statement, [`Statement::Call`]. If the function
43returns a value, a call statement designates a particular [`Expression::CallResult`]
44expression to represent its return value, for use by subsequent statements and
45expressions.
46
47## `Expression` evaluation time
48
49It is essential to know when an [`Expression`] should be evaluated, because its
50value may depend on previous [`Statement`]s' effects. But whereas the order of
51execution for a tree of `Statement`s is apparent from its structure, it is not
52so clear for `Expressions`, since an expression may be referred to by any number
53of `Statement`s and other `Expression`s.
54
55Naga's rules for when `Expression`s are evaluated are as follows:
56
57- [`Literal`], [`Constant`], and [`ZeroValue`] expressions are
58 considered to be implicitly evaluated before execution begins.
59
60- [`FunctionArgument`] and [`LocalVariable`] expressions are considered
61 implicitly evaluated upon entry to the function to which they belong.
62 Function arguments cannot be assigned to, and `LocalVariable` expressions
63 produce a *pointer to* the variable's value (for use with [`Load`] and
64 [`Store`]). Neither varies while the function executes, so it suffices to
65 consider these expressions evaluated once on entry.
66
67- Similarly, [`GlobalVariable`] expressions are considered implicitly
68 evaluated before execution begins, since their value does not change while
69 code executes, for one of two reasons:
70
71 - Most `GlobalVariable` expressions produce a pointer to the variable's
72 value, for use with [`Load`] and [`Store`], as `LocalVariable`
73 expressions do. Although the variable's value may change, its address
74 does not.
75
76 - A `GlobalVariable` expression referring to a global in the
77 [`AddressSpace::Handle`] address space produces the value directly, not
78 a pointer. Such global variables hold opaque types like shaders or
79 images, and cannot be assigned to.
80
81- A [`CallResult`] expression that is the `result` of a [`Statement::Call`],
82 representing the call's return value, is evaluated when the `Call` statement
83 is executed.
84
85- Similarly, an [`AtomicResult`] expression that is the `result` of an
86 [`Atomic`] statement, representing the result of the atomic operation, is
87 evaluated when the `Atomic` statement is executed.
88
89- A [`RayQueryProceedResult`] expression, which is a boolean
90 indicating if the ray query is finished, is evaluated when the
91 [`RayQuery`] statement whose [`Proceed::result`] points to it is
92 executed.
93
94- A [`SubgroupBallotResult`] expression is evaluated when the
95 [`SubgroupBallot`] statement whose [`result`][Statement::SubgroupBallot::result]
96 field points to it is executed.
97
98- A [`SubgroupOperationResult`] expression is evaluated when the
99 [`SubgroupCollectiveOperation`] statement whose
100 [`result`][Statement::SubgroupCollectiveOperation::result]
101 field points to it is executed.
102
103- All other expressions are evaluated when the (unique) [`Statement::Emit`]
104 statement that covers them is executed.
105
106Now, strictly speaking, not all `Expression` variants actually care when they're
107evaluated. For example, you can evaluate a [`BinaryOperator::Add`] expression
108any time you like, as long as you give it the right operands. It's really only a
109very small set of expressions that are affected by timing:
110
111- [`Load`], [`ImageSample`], and [`ImageLoad`] expressions are influenced by
112 stores to the variables or images they access, and must execute at the
113 proper time relative to them.
114
115- [`Derivative`] expressions are sensitive to control flow uniformity: they
116 must not be moved out of an area of uniform control flow into a non-uniform
117 area.
118
119- More generally, any expression that's used by more than one other expression
120 or statement should probably be evaluated only once, and then stored in a
121 variable to be cited at each point of use.
122
123Naga tries to help back ends handle all these cases correctly in a somewhat
124circuitous way. The [`ModuleInfo`] structure returned by [`Validator::validate`]
125provides a reference count for each expression in each function in the module.
126Naturally, any expression with a reference count of two or more deserves to be
127evaluated and stored in a temporary variable at the point that the `Emit`
128statement covering it is executed. But if we selectively lower the reference
129count threshold to _one_ for the sensitive expression types listed above, so
130that we _always_ generate a temporary variable and save their value, then the
131same code that manages multiply referenced expressions will take care of
132introducing temporaries for time-sensitive expressions as well. The
133`Expression::bake_ref_count` method (private to the back ends) is meant to help
134with this.
135
136## `Expression` scope
137
138Each `Expression` has a *scope*, which is the region of the function within
139which it can be used by `Statement`s and other `Expression`s. It is a validation
140error to use an `Expression` outside its scope.
141
142An expression's scope is defined as follows:
143
144- The scope of a [`Constant`], [`GlobalVariable`], [`FunctionArgument`] or
145 [`LocalVariable`] expression covers the entire `Function` in which it
146 occurs.
147
148- The scope of an expression evaluated by an [`Emit`] statement covers the
149 subsequent expressions in that `Emit`, the subsequent statements in the `Block`
150 to which that `Emit` belongs (if any) and their sub-statements (if any).
151
152- The `result` expression of a [`Call`] or [`Atomic`] statement has a scope
153 covering the subsequent statements in the `Block` in which the statement
154 occurs (if any) and their sub-statements (if any).
155
156For example, this implies that an expression evaluated by some statement in a
157nested `Block` is not available in the `Block`'s parents. Such a value would
158need to be stored in a local variable to be carried upwards in the statement
159tree.
160
161## Constant expressions
162
163A Naga *constant expression* is one of the following [`Expression`]
164variants, whose operands (if any) are also constant expressions:
165- [`Literal`]
166- [`Constant`], for [`Constant`]s
167- [`ZeroValue`], for fixed-size types
168- [`Compose`]
169- [`Access`]
170- [`AccessIndex`]
171- [`Splat`]
172- [`Swizzle`]
173- [`Unary`]
174- [`Binary`]
175- [`Select`]
176- [`Relational`]
177- [`Math`]
178- [`As`]
179- [`Bitcast`]
180
181A constant expression can be evaluated at module translation time.
182
183## Override expressions
184
185A Naga *override expression* is the same as a [constant expression],
186except that it is also allowed to reference other [`Override`]s.
187
188An override expression can be evaluated at pipeline creation time.
189
190[`AtomicResult`]: Expression::AtomicResult
191[`RayQueryProceedResult`]: Expression::RayQueryProceedResult
192[`SubgroupBallotResult`]: Expression::SubgroupBallotResult
193[`SubgroupOperationResult`]: Expression::SubgroupOperationResult
194[`CallResult`]: Expression::CallResult
195[`Constant`]: Expression::Constant
196[`ZeroValue`]: Expression::ZeroValue
197[`Literal`]: Expression::Literal
198[`Derivative`]: Expression::Derivative
199[`FunctionArgument`]: Expression::FunctionArgument
200[`GlobalVariable`]: Expression::GlobalVariable
201[`ImageLoad`]: Expression::ImageLoad
202[`ImageSample`]: Expression::ImageSample
203[`Load`]: Expression::Load
204[`LocalVariable`]: Expression::LocalVariable
205
206[`Atomic`]: Statement::Atomic
207[`Call`]: Statement::Call
208[`Emit`]: Statement::Emit
209[`Store`]: Statement::Store
210[`RayQuery`]: Statement::RayQuery
211[`SubgroupBallot`]: Statement::SubgroupBallot
212[`SubgroupCollectiveOperation`]: Statement::SubgroupCollectiveOperation
213
214[`Proceed::result`]: RayQueryFunction::Proceed::result
215
216[`Validator::validate`]: crate::valid::Validator::validate
217[`ModuleInfo`]: crate::valid::ModuleInfo
218
219[`Literal`]: Expression::Literal
220[`ZeroValue`]: Expression::ZeroValue
221[`Compose`]: Expression::Compose
222[`Access`]: Expression::Access
223[`AccessIndex`]: Expression::AccessIndex
224[`Splat`]: Expression::Splat
225[`Swizzle`]: Expression::Swizzle
226[`Unary`]: Expression::Unary
227[`Binary`]: Expression::Binary
228[`Select`]: Expression::Select
229[`Relational`]: Expression::Relational
230[`Math`]: Expression::Math
231[`As`]: Expression::As
232[`Bitcast`]: Expression::Bitcast
233
234[constant expression]: #constant-expressions
235*/
236
237mod block;
238
239use alloc::{boxed::Box, string::String, vec::Vec};
240
241#[cfg(feature = "arbitrary")]
242use arbitrary::Arbitrary;
243use half::f16;
244#[cfg(feature = "deserialize")]
245use serde::Deserialize;
246#[cfg(feature = "serialize")]
247use serde::Serialize;
248
249use crate::arena::{Arena, Handle, Range, UniqueArena};
250use crate::diagnostic_filter::DiagnosticFilterNode;
251use crate::{FastIndexMap, NamedExpressions};
252
253pub use block::Block;
254pub use naga_types::{ResourceBinding, ShaderStage};
255
256/// Explicitly allows early depth/stencil tests.
257///
258/// Normally, depth/stencil tests are performed after fragment shading. However, as an optimization,
259/// most drivers will move the depth/stencil tests before fragment shading if this does not
260/// have any observable consequences. This optimization is disabled under the following
261/// circumstances:
262/// - `discard` is called in the fragment shader.
263/// - The fragment shader writes to the depth buffer.
264/// - The fragment shader writes to any storage bindings.
265///
266/// When `EarlyDepthTest` is set, it is allowed to perform an early depth/stencil test even if the
267/// above conditions are not met. When [`EarlyDepthTest::Force`] is used, depth/stencil tests
268/// **must** be performed before fragment shading.
269///
270/// To force early depth/stencil tests in a shader:
271/// - GLSL: `layout(early_fragment_tests) in;`
272/// - HLSL: `Attribute earlydepthstencil`
273/// - SPIR-V: `ExecutionMode EarlyFragmentTests`
274/// - WGSL: `@early_depth_test(force)`
275///
276/// This may also be enabled in a shader by specifying a [`ConservativeDepth`].
277///
278/// For more, see:
279/// - <https://www.khronos.org/opengl/wiki/Early_Fragment_Test#Explicit_specification>
280/// - <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-earlydepthstencil>
281/// - <https://www.khronos.org/registry/SPIR-V/specs/unified1/SPIRV.html#Execution_Mode>
282#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
283#[cfg_attr(feature = "serialize", derive(Serialize))]
284#[cfg_attr(feature = "deserialize", derive(Deserialize))]
285#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
286pub enum EarlyDepthTest {
287 /// Requires depth/stencil tests to be performed before fragment shading.
288 ///
289 /// This will disable depth/stencil tests after fragment shading, so discarding the fragment
290 /// or overwriting the fragment depth will have no effect.
291 Force,
292
293 /// Allows an additional depth/stencil test to be performed before fragment shading.
294 ///
295 /// It is up to the driver to decide whether early tests are performed. Unlike `Force`, this
296 /// does not disable depth/stencil tests after fragment shading.
297 Allow {
298 /// Specifies restrictions on how the depth value can be modified within the fragment
299 /// shader.
300 ///
301 /// This may be taken into account when deciding whether to perform early tests.
302 conservative: ConservativeDepth,
303 },
304}
305
306/// Enables adjusting depth without disabling early Z.
307///
308/// To use in a shader:
309/// - GLSL: `layout (depth_<greater/less/unchanged/any>) out float gl_FragDepth;`
310/// - `depth_any` option behaves as if the layout qualifier was not present.
311/// - HLSL: `SV_DepthGreaterEqual`/`SV_DepthLessEqual`/`SV_Depth`
312/// - SPIR-V: `ExecutionMode Depth<Greater/Less/Unchanged>`
313/// - WGSL: `@early_depth_test(greater_equal/less_equal/unchanged)`
314///
315/// For more, see:
316/// - <https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_conservative_depth.txt>
317/// - <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-semantics#system-value-semantics>
318/// - <https://www.khronos.org/registry/SPIR-V/specs/unified1/SPIRV.html#Execution_Mode>
319#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
320#[cfg_attr(feature = "serialize", derive(Serialize))]
321#[cfg_attr(feature = "deserialize", derive(Deserialize))]
322#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
323pub enum ConservativeDepth {
324 /// Shader may rewrite depth only with a value greater than calculated.
325 GreaterEqual,
326
327 /// Shader may rewrite depth smaller than one that would have been written without the modification.
328 LessEqual,
329
330 /// Shader may not rewrite depth value.
331 Unchanged,
332}
333
334/// Addressing space of variables.
335#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
336#[cfg_attr(feature = "serialize", derive(Serialize))]
337#[cfg_attr(feature = "deserialize", derive(Deserialize))]
338#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
339pub enum AddressSpace {
340 /// Function locals.
341 Function,
342 /// Private data, per invocation, mutable.
343 Private,
344 /// Workgroup shared data, mutable.
345 WorkGroup,
346 /// Uniform buffer data.
347 Uniform,
348 /// Storage buffer data, potentially mutable.
349 Storage { access: StorageAccess },
350 /// Opaque handles, such as samplers and images.
351 Handle,
352
353 /// Immediate data.
354 ///
355 /// A [`Module`] may contain at most one [`GlobalVariable`] in
356 /// this address space. Its contents are provided not by a buffer
357 /// but by `SetImmediates` pass commands, allowing the CPU to
358 /// establish different values for each draw/dispatch.
359 ///
360 /// `Immediate` variables may not contain `f16` values, even if
361 /// the [`SHADER_FLOAT16`] capability is enabled.
362 ///
363 /// Backends generally place tight limits on the size of
364 /// `Immediate` variables.
365 ///
366 /// [`SHADER_FLOAT16`]: crate::valid::Capabilities::SHADER_FLOAT16
367 Immediate,
368 /// Task shader to mesh shader payload
369 TaskPayload,
370
371 /// Ray tracing payload, for inputting in TraceRays
372 RayPayload,
373 /// Ray tracing payload, for entrypoints invoked by a TraceRays call
374 ///
375 /// Each entrypoint may reference only one variable in this scope, as
376 /// only one may be passed as a payload.
377 IncomingRayPayload,
378}
379
380/// Built-in inputs and outputs.
381#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
382#[cfg_attr(feature = "serialize", derive(Serialize))]
383#[cfg_attr(feature = "deserialize", derive(Deserialize))]
384#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
385pub enum BuiltIn {
386 // This must be at the top so that it gets sorted to the top. PrimitiveIndex is considered a non SV
387 // by FXC so it must appear before any other SVs.
388 /// Read in fragment shaders, written in mesh shaders, read in any and closest hit shaders.
389 PrimitiveIndex,
390
391 /// Written in vertex/mesh shaders, read in fragment shaders
392 Position { invariant: bool },
393 /// Read in task, mesh, vertex, and fragment shaders
394 ViewIndex,
395
396 /// Read in vertex shaders
397 BaseInstance,
398 /// Read in vertex shaders
399 BaseVertex,
400 /// Written in vertex & mesh shaders
401 ClipDistances,
402 /// Written in vertex & mesh shaders
403 CullDistance,
404 /// Read in vertex, any- and closest-hit shaders
405 InstanceIndex,
406 /// Written in vertex & mesh shaders
407 PointSize,
408 /// Read in vertex shaders
409 VertexIndex,
410 /// Read in vertex & task shaders, or mesh shaders in pipelines without task shaders
411 DrawIndex,
412
413 /// Written in fragment shaders
414 FragDepth,
415 /// Read in fragment shaders
416 PointCoord,
417 /// Read in fragment shaders
418 FrontFacing,
419 /// Read in fragment shaders
420 Barycentric { perspective: bool },
421 /// Read in fragment shaders
422 SampleIndex,
423 /// Read or written in fragment shaders
424 SampleMask,
425
426 /// Read in compute, task, and mesh shaders
427 GlobalInvocationId,
428 /// Read in compute, task, and mesh shaders
429 LocalInvocationId,
430 /// Read in compute, task, and mesh shaders
431 LocalInvocationIndex,
432 /// Read in compute, task, and mesh shaders
433 WorkGroupId,
434 /// Read in compute, task, and mesh shaders
435 WorkGroupSize,
436 /// Read in compute, task, and mesh shaders
437 NumWorkGroups,
438
439 /// Read in compute, task, and mesh shaders
440 NumSubgroups,
441 /// Read in compute, task, and mesh shaders
442 SubgroupId,
443 /// Read in compute, fragment, task, and mesh shaders
444 SubgroupSize,
445 /// Read in compute, fragment, task, and mesh shaders
446 SubgroupInvocationId,
447
448 /// Written in task shaders
449 MeshTaskSize,
450 /// Written in mesh shaders
451 CullPrimitive,
452 /// Written in mesh shaders
453 PointIndex,
454 /// Written in mesh shaders
455 LineIndices,
456 /// Written in mesh shaders
457 TriangleIndices,
458
459 /// Written to a workgroup variable in mesh shaders
460 VertexCount,
461 /// Written to a workgroup variable in mesh shaders
462 Vertices,
463 /// Written to a workgroup variable in mesh shaders
464 PrimitiveCount,
465 /// Written to a workgroup variable in mesh shaders
466 Primitives,
467
468 /// Read in all ray tracing pipeline shaders, the id within the number of
469 /// rays that this current ray is.
470 RayInvocationId,
471 /// Read in all ray tracing pipeline shaders, the number of rays created.
472 NumRayInvocations,
473 /// Read in closest hit and any hit shaders, the custom data in the tlas
474 /// instance
475 InstanceCustomData,
476 /// Read in closest hit and any hit shaders, the index of the geometry in
477 /// the blas.
478 GeometryIndex,
479 /// Read in closest hit, any hit, and miss shaders, the origin of the ray.
480 WorldRayOrigin,
481 /// Read in closest hit, any hit, and miss shaders, the direction of the
482 /// ray.
483 WorldRayDirection,
484 /// Read in closest hit and any hit shaders, the direction of the ray in
485 /// object space.
486 ObjectRayOrigin,
487 /// Read in closest hit and any hit shaders, the direction of the ray in
488 /// object space.
489 ObjectRayDirection,
490 /// Read in closest hit, any hit, and miss shaders, the t min provided by
491 /// in the ray desc.
492 RayTmin,
493 /// Read in closest hit, any hit, and miss shaders, the final bounds at which
494 /// a hit is accepted (the closest committed hit if there is one otherwise, t
495 /// max provided in the ray desc).
496 RayTCurrentMax,
497 /// Read in closest hit and any hit shaders, the matrix for converting from
498 /// object space to world space
499 ObjectToWorld,
500 /// Read in closest hit and any hit shaders, the matrix for converting from
501 /// world space to object space
502 WorldToObject,
503 /// Read in closest hit and any hit shaders, the type of hit as provided by
504 /// the intersection function if any, otherwise this is 254 (0xFE) for a
505 /// front facing triangle and 255 (0xFF) for a back facing triangle
506 HitKind,
507 /// Read in closest hit and any hit shaders, the second and third barycentric
508 /// coordinates of the hit point on the triangle. The first can be computed as
509 /// `1.0 - x - y`. Only meaningful if the hit was a triangle.
510 HitBarycentrics,
511}
512
513/// Number of bytes per scalar.
514pub type Bytes = u8;
515
516/// Number of components in a vector.
517#[repr(u8)]
518#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
519#[cfg_attr(feature = "serialize", derive(Serialize))]
520#[cfg_attr(feature = "deserialize", derive(Deserialize))]
521#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
522pub enum VectorSize {
523 /// 2D vector
524 Bi = 2,
525 /// 3D vector
526 Tri = 3,
527 /// 4D vector
528 Quad = 4,
529}
530
531impl VectorSize {
532 pub const MAX: usize = Self::Quad as usize;
533}
534
535impl From<VectorSize> for u8 {
536 fn from(size: VectorSize) -> u8 {
537 size as u8
538 }
539}
540
541impl From<VectorSize> for u32 {
542 fn from(size: VectorSize) -> u32 {
543 size as u32
544 }
545}
546
547/// Number of components in a cooperative vector.
548#[repr(u8)]
549#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
550#[cfg_attr(feature = "serialize", derive(Serialize))]
551#[cfg_attr(feature = "deserialize", derive(Deserialize))]
552#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
553pub enum CooperativeSize {
554 Eight = 8,
555 Sixteen = 16,
556}
557
558/// Primitive type for a scalar.
559#[repr(u8)]
560#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
561#[cfg_attr(feature = "serialize", derive(Serialize))]
562#[cfg_attr(feature = "deserialize", derive(Deserialize))]
563#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
564pub enum ScalarKind {
565 /// Signed integer type.
566 Sint,
567 /// Unsigned integer type.
568 Uint,
569 /// Floating point type.
570 Float,
571 /// Boolean type.
572 Bool,
573
574 /// WGSL abstract integer type.
575 ///
576 /// These are forbidden by validation, and should never reach backends.
577 AbstractInt,
578
579 /// Abstract floating-point type.
580 ///
581 /// These are forbidden by validation, and should never reach backends.
582 AbstractFloat,
583}
584
585/// Role of a cooperative variable in the equation "A * B + C"
586#[repr(u8)]
587#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
588#[cfg_attr(feature = "serialize", derive(Serialize))]
589#[cfg_attr(feature = "deserialize", derive(Deserialize))]
590#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
591pub enum CooperativeRole {
592 A,
593 B,
594 C,
595}
596
597/// Characteristics of a scalar type.
598#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
599#[cfg_attr(feature = "serialize", derive(Serialize))]
600#[cfg_attr(feature = "deserialize", derive(Deserialize))]
601#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
602pub struct Scalar {
603 /// How the value's bits are to be interpreted.
604 pub kind: ScalarKind,
605
606 /// This size of the value in bytes.
607 pub width: Bytes,
608}
609
610/// Size of an array.
611#[repr(u8)]
612#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
613#[cfg_attr(feature = "serialize", derive(Serialize))]
614#[cfg_attr(feature = "deserialize", derive(Deserialize))]
615#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
616pub enum ArraySize {
617 /// The array size is constant.
618 Constant(core::num::NonZeroU32),
619 /// The array size is an override-expression.
620 Pending(Handle<Override>),
621 /// The array size can change at runtime.
622 Dynamic,
623}
624
625/// The interpolation qualifier of a binding or struct field.
626#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
627#[cfg_attr(feature = "serialize", derive(Serialize))]
628#[cfg_attr(feature = "deserialize", derive(Deserialize))]
629#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
630pub enum Interpolation {
631 /// The value will be interpolated in a perspective-correct fashion.
632 /// Also known as "smooth" in glsl.
633 Perspective,
634 /// Indicates that linear, non-perspective, correct
635 /// interpolation must be used.
636 /// Also known as "no_perspective" in glsl.
637 Linear,
638 /// Indicates that no interpolation will be performed.
639 Flat,
640 /// Indicates the fragment input binding holds an array of per-vertex values.
641 /// This is typically used with barycentrics.
642 PerVertex,
643}
644
645/// The sampling qualifiers of a binding or struct field.
646#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
647#[cfg_attr(feature = "serialize", derive(Serialize))]
648#[cfg_attr(feature = "deserialize", derive(Deserialize))]
649#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
650pub enum Sampling {
651 /// Interpolate the value at the center of the pixel.
652 Center,
653
654 /// Interpolate the value at a point that lies within all samples covered by
655 /// the fragment within the current primitive. In multisampling, use a
656 /// single value for all samples in the primitive.
657 Centroid,
658
659 /// Interpolate the value at each sample location. In multisampling, invoke
660 /// the fragment shader once per sample.
661 Sample,
662
663 /// Use the value provided by the first vertex of the current primitive.
664 First,
665
666 /// Use the value provided by the first or last vertex of the current primitive. The exact
667 /// choice is implementation-dependent.
668 Either,
669}
670
671/// Member of a user-defined structure.
672// Clone is used only for error reporting and is not intended for end users
673#[derive(Clone, Debug, Eq, Hash, PartialEq)]
674#[cfg_attr(feature = "serialize", derive(Serialize))]
675#[cfg_attr(feature = "deserialize", derive(Deserialize))]
676#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
677pub struct StructMember {
678 pub name: Option<String>,
679 /// Type of the field.
680 pub ty: Handle<Type>,
681 /// For I/O structs, defines the binding.
682 pub binding: Option<Binding>,
683 /// Offset from the beginning from the struct.
684 pub offset: u32,
685}
686
687/// The number of dimensions an image has.
688#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
689#[cfg_attr(feature = "serialize", derive(Serialize))]
690#[cfg_attr(feature = "deserialize", derive(Deserialize))]
691#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
692pub enum ImageDimension {
693 /// 1D image
694 D1,
695 /// 2D image
696 D2,
697 /// 3D image
698 D3,
699 /// Cube map
700 Cube,
701}
702
703bitflags::bitflags! {
704 /// Flags describing an image.
705 #[cfg_attr(feature = "serialize", derive(Serialize))]
706 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
707 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
708 #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
709 pub struct StorageAccess: u32 {
710 /// Storage can be used as a source for load ops.
711 const LOAD = 0x1;
712 /// Storage can be used as a target for store ops.
713 const STORE = 0x2;
714 /// Storage can be used as a target for atomic ops.
715 const ATOMIC = 0x4;
716 }
717}
718
719bitflags::bitflags! {
720 /// Memory decorations for global variables.
721 #[cfg_attr(feature = "serialize", derive(Serialize))]
722 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
723 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
724 #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
725 pub struct MemoryDecorations: u8 {
726 /// Reads and writes are automatically visible to other invocations
727 /// without explicit barriers.
728 const COHERENT = 0x1;
729 /// The variable may be modified by something external to the shader,
730 /// preventing certain compiler optimizations.
731 const VOLATILE = 0x2;
732 }
733}
734
735/// Image storage format.
736#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
737#[cfg_attr(feature = "serialize", derive(Serialize))]
738#[cfg_attr(feature = "deserialize", derive(Deserialize))]
739#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
740pub enum StorageFormat {
741 // 8-bit formats
742 R8Unorm,
743 R8Snorm,
744 R8Uint,
745 R8Sint,
746
747 // 16-bit formats
748 R16Uint,
749 R16Sint,
750 R16Float,
751 Rg8Unorm,
752 Rg8Snorm,
753 Rg8Uint,
754 Rg8Sint,
755
756 // 32-bit formats
757 R32Uint,
758 R32Sint,
759 R32Float,
760 Rg16Uint,
761 Rg16Sint,
762 Rg16Float,
763 Rgba8Unorm,
764 Rgba8Snorm,
765 Rgba8Uint,
766 Rgba8Sint,
767 Bgra8Unorm,
768
769 // Packed 32-bit formats
770 Rgb10a2Uint,
771 Rgb10a2Unorm,
772 Rg11b10Ufloat,
773
774 // 64-bit formats
775 R64Uint,
776 Rg32Uint,
777 Rg32Sint,
778 Rg32Float,
779 Rgba16Uint,
780 Rgba16Sint,
781 Rgba16Float,
782
783 // 128-bit formats
784 Rgba32Uint,
785 Rgba32Sint,
786 Rgba32Float,
787
788 // Normalized 16-bit per channel formats
789 R16Unorm,
790 R16Snorm,
791 Rg16Unorm,
792 Rg16Snorm,
793 Rgba16Unorm,
794 Rgba16Snorm,
795}
796
797/// Sub-class of the image type.
798#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
799#[cfg_attr(feature = "serialize", derive(Serialize))]
800#[cfg_attr(feature = "deserialize", derive(Deserialize))]
801#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
802pub enum ImageClass {
803 /// Regular sampled image.
804 Sampled {
805 /// Kind of values to sample.
806 kind: ScalarKind,
807 /// Multi-sampled image.
808 ///
809 /// A multi-sampled image holds several samples per texel. Multi-sampled
810 /// images cannot have mipmaps.
811 multi: bool,
812 },
813 /// Depth comparison image.
814 Depth {
815 /// Multi-sampled depth image.
816 multi: bool,
817 },
818 /// External texture.
819 External,
820 /// Storage image.
821 Storage {
822 format: StorageFormat,
823 access: StorageAccess,
824 },
825}
826
827/// A data type declared in the module.
828#[derive(Clone, Debug, Eq, Hash, PartialEq)]
829#[cfg_attr(feature = "serialize", derive(Serialize))]
830#[cfg_attr(feature = "deserialize", derive(Deserialize))]
831#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
832pub struct Type {
833 /// The name of the type, if any.
834 pub name: Option<String>,
835 /// Inner structure that depends on the kind of the type.
836 pub inner: TypeInner,
837}
838
839/// Enum with additional information, depending on the kind of type.
840///
841/// Comparison using `==` is not reliable in the case of [`Pointer`],
842/// [`ValuePointer`], or [`Struct`] variants. For these variants,
843/// use [`TypeInner::non_struct_equivalent`] or [`compare_types`].
844///
845/// [`compare_types`]: crate::proc::compare_types
846/// [`ValuePointer`]: TypeInner::ValuePointer
847/// [`Pointer`]: TypeInner::Pointer
848/// [`Struct`]: TypeInner::Struct
849#[derive(Clone, Debug, Eq, Hash, PartialEq)]
850#[cfg_attr(feature = "serialize", derive(Serialize))]
851#[cfg_attr(feature = "deserialize", derive(Deserialize))]
852#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
853pub enum TypeInner {
854 /// Number of integral or floating-point kind.
855 Scalar(Scalar),
856 /// Vector of numbers.
857 Vector { size: VectorSize, scalar: Scalar },
858 /// Matrix of numbers.
859 Matrix {
860 columns: VectorSize,
861 rows: VectorSize,
862 scalar: Scalar,
863 },
864 /// Matrix that is cooperatively processed by all the threads
865 /// in an opaque mapping.
866 CooperativeMatrix {
867 columns: CooperativeSize,
868 rows: CooperativeSize,
869 scalar: Scalar,
870 role: CooperativeRole,
871 },
872 /// Atomic scalar.
873 Atomic(Scalar),
874 /// Pointer to another type.
875 ///
876 /// Pointers to scalars and vectors should be treated as equivalent to
877 /// [`ValuePointer`] types. Use either [`TypeInner::non_struct_equivalent`]
878 /// or [`compare_types`] to compare types in a way that treats pointers
879 /// correctly.
880 ///
881 /// ## Pointers to non-`SIZED` types
882 ///
883 /// The `base` type of a pointer may be a non-[`SIZED`] type like a
884 /// dynamically-sized [`Array`], or a [`Struct`] whose last member is a
885 /// dynamically sized array. Such pointers occur as the types of
886 /// [`GlobalVariable`] or [`AccessIndex`] expressions referring to
887 /// dynamically-sized arrays.
888 ///
889 /// However, among pointers to non-`SIZED` types, only pointers to `Struct`s
890 /// are [`DATA`]. Pointers to dynamically sized `Array`s cannot be passed as
891 /// arguments, stored in variables, or held in arrays or structures. Their
892 /// only use is as the types of `AccessIndex` expressions.
893 ///
894 /// [`SIZED`]: crate::valid::TypeFlags::SIZED
895 /// [`DATA`]: crate::valid::TypeFlags::DATA
896 /// [`Array`]: TypeInner::Array
897 /// [`Struct`]: TypeInner::Struct
898 /// [`ValuePointer`]: TypeInner::ValuePointer
899 /// [`GlobalVariable`]: Expression::GlobalVariable
900 /// [`AccessIndex`]: Expression::AccessIndex
901 /// [`compare_types`]: crate::proc::compare_types
902 Pointer {
903 base: Handle<Type>,
904 space: AddressSpace,
905 },
906
907 /// Pointer to a scalar or vector.
908 ///
909 /// A `ValuePointer` type is equivalent to a `Pointer` whose `base` is a
910 /// `Scalar` or `Vector` type. This is for use in [`TypeResolution::Value`]
911 /// variants; see the documentation for [`TypeResolution`] for details.
912 ///
913 /// Use [`TypeInner::non_struct_equivalent`] or [`compare_types`] to compare
914 /// types that could be pointers, to ensure that `Pointer` and
915 /// `ValuePointer` types are recognized as equivalent.
916 ///
917 /// [`TypeResolution`]: crate::proc::TypeResolution
918 /// [`TypeResolution::Value`]: crate::proc::TypeResolution::Value
919 /// [`compare_types`]: crate::proc::compare_types
920 ValuePointer {
921 size: Option<VectorSize>,
922 scalar: Scalar,
923 space: AddressSpace,
924 },
925
926 /// Homogeneous list of elements.
927 ///
928 /// The `base` type must be a [`SIZED`], [`DATA`] type.
929 ///
930 /// ## Dynamically sized arrays
931 ///
932 /// An `Array` is [`SIZED`] unless its `size` is [`Dynamic`].
933 /// Dynamically-sized arrays may only appear in a few situations:
934 ///
935 /// - They may appear as the type of a [`GlobalVariable`], or as the last
936 /// member of a [`Struct`].
937 ///
938 /// - They may appear as the base type of a [`Pointer`]. An
939 /// [`AccessIndex`] expression referring to a struct's final
940 /// unsized array member would have such a pointer type. However, such
941 /// pointer types may only appear as the types of such intermediate
942 /// expressions. They are not [`DATA`], and cannot be stored in
943 /// variables, held in arrays or structs, or passed as parameters.
944 ///
945 /// [`SIZED`]: crate::valid::TypeFlags::SIZED
946 /// [`DATA`]: crate::valid::TypeFlags::DATA
947 /// [`Dynamic`]: ArraySize::Dynamic
948 /// [`Struct`]: TypeInner::Struct
949 /// [`Pointer`]: TypeInner::Pointer
950 /// [`AccessIndex`]: Expression::AccessIndex
951 Array {
952 base: Handle<Type>,
953 size: ArraySize,
954 stride: u32,
955 },
956
957 /// User-defined structure.
958 ///
959 /// There must always be at least one member.
960 ///
961 /// A `Struct` type is [`DATA`], and the types of its members must be
962 /// `DATA` as well.
963 ///
964 /// Member types must be [`SIZED`], except for the final member of a
965 /// struct, which may be a dynamically sized [`Array`]. The
966 /// `Struct` type itself is `SIZED` when all its members are `SIZED`.
967 ///
968 /// Two structure types with different names are not equivalent. Because
969 /// this variant does not contain the name, it is not possible to use it
970 /// to compare struct types. Use [`compare_types`] to compare two types
971 /// that may be structs.
972 ///
973 /// [`DATA`]: crate::valid::TypeFlags::DATA
974 /// [`SIZED`]: crate::∅TypeFlags::SIZED
975 /// [`Array`]: TypeInner::Array
976 /// [`compare_types`]: crate::proc::compare_types
977 Struct {
978 members: Vec<StructMember>,
979 //TODO: should this be unaligned?
980 span: u32,
981 },
982 /// Possibly multidimensional array of texels.
983 Image {
984 dim: ImageDimension,
985 arrayed: bool,
986 //TODO: consider moving `multisampled: bool` out
987 class: ImageClass,
988 },
989 /// Can be used to sample values from images.
990 Sampler { comparison: bool },
991
992 /// Opaque object representing an acceleration structure of geometry.
993 AccelerationStructure { vertex_return: bool },
994
995 /// Locally used handle for ray queries.
996 RayQuery { vertex_return: bool },
997
998 /// Opaque handle to ray traversal state (hit / miss / empty) used by ray
999 /// tracing invocation reordering.
1000 ///
1001 /// Like [`RayQuery`], values of this type may only live in local variables
1002 /// in the [`Function`] address space, and may only be manipulated through
1003 /// [`Statement::HitObject`] and [`Expression::HitObjectQuery`]. Such
1004 /// variables are only valid in functions reachable from the
1005 /// [`RayGeneration`], [`ClosestHit`] and [`Miss`] stages.
1006 ///
1007 /// A hit object local variable is empty (as if by
1008 /// [`HitObjectFunction::RecordEmpty`]) when its function starts executing.
1009 /// A declaration inside a loop is not reset automatically on each
1010 /// iteration; front ends that want that behavior should emit a
1011 /// [`RecordEmpty`] where the declaration appears in the loop body, as the
1012 /// WGSL front end does.
1013 ///
1014 /// [`RayQuery`]: TypeInner::RayQuery
1015 /// [`Function`]: AddressSpace::Function
1016 /// [`RayGeneration`]: ShaderStage::RayGeneration
1017 /// [`ClosestHit`]: ShaderStage::ClosestHit
1018 /// [`Miss`]: ShaderStage::Miss
1019 /// [`RecordEmpty`]: HitObjectFunction::RecordEmpty
1020 HitObject,
1021
1022 /// Array of bindings.
1023 ///
1024 /// A `BindingArray` represents an array where each element draws its value
1025 /// from a separate bound resource. The array's element type `base` may be
1026 /// [`Image`], [`Sampler`], or any type that would be permitted for a global
1027 /// in the [`Uniform`] or [`Storage`] address spaces. Only global variables
1028 /// may be binding arrays; on the host side, their values are provided by
1029 /// [`TextureViewArray`], [`SamplerArray`], or [`BufferArray`]
1030 /// bindings.
1031 ///
1032 /// Since each element comes from a distinct resource, a binding array of
1033 /// images could have images of varying sizes (but not varying dimensions;
1034 /// they must all have the same `Image` type). Or, a binding array of
1035 /// buffers could have elements that are dynamically sized arrays, each with
1036 /// a different length.
1037 ///
1038 /// Binding arrays are in the same address spaces as their underlying type.
1039 /// As such, referring to an array of images produces an [`Image`] value
1040 /// directly (as opposed to a pointer). The only operation permitted on
1041 /// `BindingArray` values is indexing, which works transparently: indexing
1042 /// a binding array of samplers yields a [`Sampler`], indexing a pointer to the
1043 /// binding array of storage buffers produces a pointer to the storage struct.
1044 ///
1045 /// Unlike textures and samplers, binding arrays are not [`ARGUMENT`], so
1046 /// they cannot be passed as arguments to functions.
1047 ///
1048 /// Naga's WGSL front end supports binding arrays with the type syntax
1049 /// `binding_array<T, N>`.
1050 ///
1051 /// [`Image`]: TypeInner::Image
1052 /// [`Sampler`]: TypeInner::Sampler
1053 /// [`Uniform`]: AddressSpace::Uniform
1054 /// [`Storage`]: AddressSpace::Storage
1055 /// [`TextureViewArray`]: https://docs.rs/wgpu/latest/wgpu/enum.BindingResource.html#variant.TextureViewArray
1056 /// [`SamplerArray`]: https://docs.rs/wgpu/latest/wgpu/enum.BindingResource.html#variant.SamplerArray
1057 /// [`BufferArray`]: https://docs.rs/wgpu/latest/wgpu/enum.BindingResource.html#variant.BufferArray
1058 /// [`DATA`]: crate::valid::TypeFlags::DATA
1059 /// [`ARGUMENT`]: crate::valid::TypeFlags::ARGUMENT
1060 /// [naga#1864]: https://github.com/gfx-rs/naga/issues/1864
1061 BindingArray { base: Handle<Type>, size: ArraySize },
1062}
1063
1064#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
1065#[cfg_attr(feature = "serialize", derive(Serialize))]
1066#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1067#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1068pub enum Literal {
1069 /// May not be NaN or infinity.
1070 F64(f64),
1071 /// May not be NaN or infinity.
1072 F32(f32),
1073 /// May not be NaN or infinity.
1074 F16(f16),
1075 U16(u16),
1076 I16(i16),
1077 U32(u32),
1078 I32(i32),
1079 U64(u64),
1080 I64(i64),
1081 Bool(bool),
1082 AbstractInt(i64),
1083 AbstractFloat(f64),
1084}
1085
1086/// Pipeline-overridable constant.
1087#[derive(Clone, Debug, PartialEq)]
1088#[cfg_attr(feature = "serialize", derive(Serialize))]
1089#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1090#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1091pub struct Override {
1092 pub name: Option<String>,
1093 /// Pipeline Constant ID.
1094 pub id: Option<u16>,
1095 pub ty: Handle<Type>,
1096
1097 /// The default value of the pipeline-overridable constant.
1098 ///
1099 /// This [`Handle`] refers to [`Module::global_expressions`], not
1100 /// any [`Function::expressions`] arena.
1101 pub init: Option<Handle<Expression>>,
1102}
1103
1104/// Constant value.
1105#[derive(Clone, Debug, PartialEq)]
1106#[cfg_attr(feature = "serialize", derive(Serialize))]
1107#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1108#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1109pub struct Constant {
1110 pub name: Option<String>,
1111 pub ty: Handle<Type>,
1112
1113 /// The value of the constant.
1114 ///
1115 /// This [`Handle`] refers to [`Module::global_expressions`], not
1116 /// any [`Function::expressions`] arena.
1117 pub init: Handle<Expression>,
1118}
1119
1120/// Describes how an input/output variable is to be bound.
1121#[derive(Clone, Debug, Eq, PartialEq, Hash)]
1122#[cfg_attr(feature = "serialize", derive(Serialize))]
1123#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1124#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1125pub enum Binding {
1126 /// Built-in shader variable.
1127 BuiltIn(BuiltIn),
1128
1129 /// Indexed location.
1130 ///
1131 /// This is a value passed to a [`Fragment`] shader from a [`Vertex`] or
1132 /// [`Mesh`] shader.
1133 ///
1134 /// Values passed from the [`Vertex`] stage to the [`Fragment`] stage must
1135 /// have their `interpolation` defaulted (i.e. not `None`) by the front end
1136 /// as appropriate for that language.
1137 ///
1138 /// For other stages, we permit interpolations even though they're ignored.
1139 /// When a front end is parsing a struct type, it usually doesn't know what
1140 /// stages will be using it for IO, so it's easiest if it can apply the
1141 /// defaults to anything with a `Location` binding, just in case.
1142 ///
1143 /// For anything other than floating-point scalars and vectors, the
1144 /// interpolation must be `Flat`.
1145 ///
1146 /// [`Vertex`]: crate::ShaderStage::Vertex
1147 /// [`Mesh`]: crate::ShaderStage::Mesh
1148 /// [`Fragment`]: crate::ShaderStage::Fragment
1149 Location {
1150 location: u32,
1151 interpolation: Option<Interpolation>,
1152 sampling: Option<Sampling>,
1153
1154 /// Optional `blend_src` index used for dual source blending.
1155 /// See <https://www.w3.org/TR/WGSL/#attribute-blend_src>
1156 blend_src: Option<u32>,
1157
1158 /// Whether the binding is a per-primitive binding for use with mesh shaders.
1159 ///
1160 /// This must be `true` if this binding is a mesh shader primitive output, or such
1161 /// an output's corresponding fragment shader input. It must be `false` otherwise.
1162 ///
1163 /// A stage's outputs must all have unique `location` numbers, regardless of
1164 /// whether they are per-primitive; a mesh shader's per-vertex and per-primitive
1165 /// outputs share the same location numbering space.
1166 ///
1167 /// Per-primitive values are not interpolated at all and are not dependent on the
1168 /// vertices or pixel location. For example, it may be used to store a
1169 /// non-interpolated normal vector.
1170 per_primitive: bool,
1171 },
1172}
1173
1174/// Variable defined at module level.
1175#[derive(Clone, Debug, PartialEq)]
1176#[cfg_attr(feature = "serialize", derive(Serialize))]
1177#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1178#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1179pub struct GlobalVariable {
1180 /// Name of the variable, if any.
1181 pub name: Option<String>,
1182 /// How this variable is to be stored.
1183 pub space: AddressSpace,
1184 /// For resources, defines the binding point.
1185 pub binding: Option<ResourceBinding>,
1186 /// The type of this variable.
1187 pub ty: Handle<Type>,
1188 /// Initial value for this variable.
1189 ///
1190 /// This refers to an [`Expression`] in [`Module::global_expressions`].
1191 pub init: Option<Handle<Expression>>,
1192 /// Memory decorations for this variable.
1193 ///
1194 /// These are meaningful for storage address space variables in SPIR-V,
1195 /// where they map to SPIR-V memory decorations on the variable.
1196 ///
1197 /// In WGSL, these can be set with attributes like `@coherent` or `@volatile`.
1198 pub memory_decorations: MemoryDecorations,
1199}
1200
1201/// Variable defined at function level.
1202#[derive(Clone, Debug)]
1203#[cfg_attr(feature = "serialize", derive(Serialize))]
1204#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1205#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1206pub struct LocalVariable {
1207 /// Name of the variable, if any.
1208 pub name: Option<String>,
1209 /// The type of this variable.
1210 pub ty: Handle<Type>,
1211 /// Initial value for this variable.
1212 ///
1213 /// This handle refers to an expression in this `LocalVariable`'s function's
1214 /// [`expressions`] arena, but it is required to be an evaluated override
1215 /// expression.
1216 ///
1217 /// [`expressions`]: Function::expressions
1218 pub init: Option<Handle<Expression>>,
1219}
1220
1221/// Operation that can be applied on a single value.
1222#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1223#[cfg_attr(feature = "serialize", derive(Serialize))]
1224#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1225#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1226pub enum UnaryOperator {
1227 Negate,
1228 LogicalNot,
1229 BitwiseNot,
1230}
1231
1232/// Operation that can be applied on two values.
1233///
1234/// ## Arithmetic type rules
1235///
1236/// The arithmetic operations `Add`, `Subtract`, `Multiply`, `Divide`, and
1237/// `Modulo` can all be applied to [`Scalar`] types other than [`Bool`], or
1238/// [`Vector`]s thereof. Both operands must have the same type.
1239///
1240/// `Add` and `Subtract` can also be applied to [`Matrix`] values. Both operands
1241/// must have the same type.
1242///
1243/// `Multiply` supports additional cases:
1244///
1245/// - A [`Matrix`] or [`Vector`] can be multiplied by a scalar [`Float`],
1246/// either on the left or the right.
1247///
1248/// - A [`Matrix`] on the left can be multiplied by a [`Vector`] on the right
1249/// if the matrix has as many columns as the vector has components
1250/// (`matCxR * VecC`).
1251///
1252/// - A [`Vector`] on the left can be multiplied by a [`Matrix`] on the right
1253/// if the matrix has as many rows as the vector has components
1254/// (`VecR * matCxR`).
1255///
1256/// - Two matrices can be multiplied if the left operand has as many columns
1257/// as the right operand has rows (`matNxR * matCxN`).
1258///
1259/// In all the above `Multiply` cases, the byte widths of the underlying scalar
1260/// types of both operands must be the same.
1261///
1262/// Note that `Multiply` supports mixed vector and scalar operations directly,
1263/// whereas the other arithmetic operations require an explicit [`Splat`] for
1264/// mixed-type use.
1265///
1266/// [`Scalar`]: TypeInner::Scalar
1267/// [`Vector`]: TypeInner::Vector
1268/// [`Matrix`]: TypeInner::Matrix
1269/// [`Float`]: ScalarKind::Float
1270/// [`Bool`]: ScalarKind::Bool
1271/// [`Splat`]: Expression::Splat
1272#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1273#[cfg_attr(feature = "serialize", derive(Serialize))]
1274#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1275#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1276pub enum BinaryOperator {
1277 Add,
1278 Subtract,
1279 Multiply,
1280 Divide,
1281 /// Equivalent of the WGSL's `%` operator or SPIR-V's `OpFRem`
1282 Modulo,
1283 Equal,
1284 NotEqual,
1285 Less,
1286 LessEqual,
1287 Greater,
1288 GreaterEqual,
1289 And,
1290 ExclusiveOr,
1291 InclusiveOr,
1292 LogicalAnd,
1293 LogicalOr,
1294 ShiftLeft,
1295 /// Right shift carries the sign of signed integers only.
1296 ShiftRight,
1297}
1298
1299/// Function on an atomic value.
1300///
1301/// Note: these do not include load/store, which use the existing
1302/// [`Expression::Load`] and [`Statement::Store`].
1303///
1304/// All `Handle<Expression>` values here refer to an expression in
1305/// [`Function::expressions`].
1306#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1307#[cfg_attr(feature = "serialize", derive(Serialize))]
1308#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1309#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1310pub enum AtomicFunction {
1311 Add,
1312 Subtract,
1313 And,
1314 ExclusiveOr,
1315 InclusiveOr,
1316 Min,
1317 Max,
1318 Exchange { compare: Option<Handle<Expression>> },
1319}
1320
1321/// Hint at which precision to compute a derivative.
1322#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1323#[cfg_attr(feature = "serialize", derive(Serialize))]
1324#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1325#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1326pub enum DerivativeControl {
1327 Coarse,
1328 Fine,
1329 None,
1330}
1331
1332/// Axis on which to compute a derivative.
1333#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1334#[cfg_attr(feature = "serialize", derive(Serialize))]
1335#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1336#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1337pub enum DerivativeAxis {
1338 X,
1339 Y,
1340 Width,
1341}
1342
1343/// Built-in shader function for testing relation between values.
1344#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1345#[cfg_attr(feature = "serialize", derive(Serialize))]
1346#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1347#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1348pub enum RelationalFunction {
1349 All,
1350 Any,
1351 IsNan,
1352 IsInf,
1353}
1354
1355/// Built-in shader function for math.
1356#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1357#[cfg_attr(feature = "serialize", derive(Serialize))]
1358#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1359#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1360pub enum MathFunction {
1361 // comparison
1362 Abs,
1363 Min,
1364 Max,
1365 Clamp,
1366 Saturate,
1367 // trigonometry
1368 Cos,
1369 Cosh,
1370 Sin,
1371 Sinh,
1372 Tan,
1373 Tanh,
1374 Acos,
1375 Asin,
1376 Atan,
1377 Atan2,
1378 Asinh,
1379 Acosh,
1380 Atanh,
1381 Radians,
1382 Degrees,
1383 // decomposition
1384 Ceil,
1385 Floor,
1386 Round,
1387 Fract,
1388 Trunc,
1389 Modf,
1390 Frexp,
1391 Ldexp,
1392 // exponent
1393 Exp,
1394 Exp2,
1395 Log,
1396 Log2,
1397 Pow,
1398 // geometry
1399 Dot,
1400 Dot4I8Packed,
1401 Dot4U8Packed,
1402 Outer,
1403 Cross,
1404 Distance,
1405 Length,
1406 Normalize,
1407 FaceForward,
1408 Reflect,
1409 Refract,
1410 // computational
1411 Sign,
1412 Fma,
1413 Mix,
1414 Step,
1415 SmoothStep,
1416 Sqrt,
1417 InverseSqrt,
1418 Inverse,
1419 Transpose,
1420 Determinant,
1421 QuantizeToF16,
1422 // bits
1423 CountTrailingZeros,
1424 CountLeadingZeros,
1425 CountOneBits,
1426 ReverseBits,
1427 ExtractBits,
1428 InsertBits,
1429 FirstTrailingBit,
1430 FirstLeadingBit,
1431 // data packing
1432 Pack4x8snorm,
1433 Pack4x8unorm,
1434 Pack2x16snorm,
1435 Pack2x16unorm,
1436 Pack2x16float,
1437 Pack4xI8,
1438 Pack4xU8,
1439 Pack4xI8Clamp,
1440 Pack4xU8Clamp,
1441 // data unpacking
1442 Unpack4x8snorm,
1443 Unpack4x8unorm,
1444 Unpack2x16snorm,
1445 Unpack2x16unorm,
1446 Unpack2x16float,
1447 Unpack4xI8,
1448 Unpack4xU8,
1449}
1450
1451/// Sampling modifier to control the level of detail.
1452///
1453/// All `Handle<Expression>` values here refer to an expression in
1454/// [`Function::expressions`].
1455#[derive(Clone, Copy, Debug, PartialEq)]
1456#[cfg_attr(feature = "serialize", derive(Serialize))]
1457#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1458#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1459pub enum SampleLevel {
1460 Auto,
1461 Zero,
1462 Exact(Handle<Expression>),
1463 Bias(Handle<Expression>),
1464 Gradient {
1465 x: Handle<Expression>,
1466 y: Handle<Expression>,
1467 },
1468}
1469
1470/// Type of an image query.
1471///
1472/// All `Handle<Expression>` values here refer to an expression in
1473/// [`Function::expressions`].
1474#[derive(Clone, Copy, Debug, PartialEq)]
1475#[cfg_attr(feature = "serialize", derive(Serialize))]
1476#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1477#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1478pub enum ImageQuery {
1479 /// Get the size at the specified level.
1480 ///
1481 /// The return value is a `u32` for 1D images, and a `vecN<u32>`
1482 /// for an image with dimensions N > 2.
1483 Size {
1484 /// If `None`, the base level is considered.
1485 level: Option<Handle<Expression>>,
1486 },
1487 /// Get the number of mipmap levels, a `u32`.
1488 NumLevels,
1489 /// Get the number of array layers, a `u32`.
1490 NumLayers,
1491 /// Get the number of samples, a `u32`.
1492 NumSamples,
1493}
1494
1495/// Component selection for a vector swizzle.
1496#[repr(u8)]
1497#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
1498#[cfg_attr(feature = "serialize", derive(Serialize))]
1499#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1500#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1501pub enum SwizzleComponent {
1502 X = 0,
1503 Y = 1,
1504 Z = 2,
1505 W = 3,
1506}
1507
1508/// The specific behavior of a [`SubgroupGather`] statement.
1509///
1510/// All `Handle<Expression>` values here refer to an expression in
1511/// [`Function::expressions`].
1512///
1513/// [`SubgroupGather`]: Statement::SubgroupGather
1514#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1515#[cfg_attr(feature = "serialize", derive(Serialize))]
1516#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1517#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1518pub enum GatherMode {
1519 /// All gather from the active lane with the smallest index
1520 BroadcastFirst,
1521 /// All gather from the same lane at the index given by the expression
1522 Broadcast(Handle<Expression>),
1523 /// Each gathers from a different lane at the index given by the expression
1524 Shuffle(Handle<Expression>),
1525 /// Each gathers from their lane plus the shift given by the expression
1526 ShuffleDown(Handle<Expression>),
1527 /// Each gathers from their lane minus the shift given by the expression
1528 ShuffleUp(Handle<Expression>),
1529 /// Each gathers from their lane xored with the given by the expression
1530 ShuffleXor(Handle<Expression>),
1531 /// All gather from the same quad lane at the index given by the expression
1532 QuadBroadcast(Handle<Expression>),
1533 /// Each gathers from the opposite quad lane along the given direction
1534 QuadSwap(Direction),
1535}
1536
1537#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1538#[cfg_attr(feature = "serialize", derive(Serialize))]
1539#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1540#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1541pub enum Direction {
1542 X = 0,
1543 Y = 1,
1544 Diagonal = 2,
1545}
1546
1547#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1548#[cfg_attr(feature = "serialize", derive(Serialize))]
1549#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1550#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1551pub enum SubgroupOperation {
1552 All = 0,
1553 Any = 1,
1554 Add = 2,
1555 Mul = 3,
1556 Min = 4,
1557 Max = 5,
1558 And = 6,
1559 Or = 7,
1560 Xor = 8,
1561}
1562
1563#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1564#[cfg_attr(feature = "serialize", derive(Serialize))]
1565#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1566#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1567pub enum CollectiveOperation {
1568 Reduce = 0,
1569 InclusiveScan = 1,
1570 ExclusiveScan = 2,
1571}
1572
1573/// The specific bit a [`SubgroupBallotFindBit`] statement is looking for.
1574///
1575/// [`SubgroupBallotFindBit`]: Statement::SubgroupBallotFindBit
1576#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1577#[cfg_attr(feature = "serialize", derive(Serialize))]
1578#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1579#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1580pub enum BallotFindBitOrder {
1581 /// Find the least significant set bit (the lowest invocation index).
1582 Lsb = 0,
1583 /// Find the most significant set bit (the highest invocation index).
1584 Msb = 1,
1585}
1586
1587bitflags::bitflags! {
1588 /// Memory barrier flags.
1589 #[cfg_attr(feature = "serialize", derive(Serialize))]
1590 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
1591 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1592 #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1593 pub struct Barrier: u32 {
1594 /// Barrier affects all [`AddressSpace::Storage`] accesses.
1595 const STORAGE = 1 << 0;
1596 /// Barrier affects all [`AddressSpace::WorkGroup`] and [`AddressSpace::TaskPayload`] accesses.
1597 const WORK_GROUP = 1 << 1;
1598 /// Barrier synchronizes execution across all invocations within a subgroup that execute this instruction.
1599 const SUB_GROUP = 1 << 2;
1600 /// Barrier synchronizes texture memory accesses in a workgroup.
1601 const TEXTURE = 1 << 3;
1602 }
1603}
1604
1605#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
1606#[cfg_attr(feature = "serialize", derive(Serialize))]
1607#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1608#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1609pub struct CooperativeData {
1610 pub pointer: Handle<Expression>,
1611 pub stride: Handle<Expression>,
1612 pub row_major: bool,
1613}
1614
1615/// An expression that can be evaluated to obtain a value.
1616///
1617/// This is a Single Static Assignment (SSA) scheme similar to SPIR-V.
1618///
1619/// When an `Expression` variant holds `Handle<Expression>` fields, they refer
1620/// to another expression in the same arena, unless explicitly noted otherwise.
1621/// One `Arena<Expression>` may only refer to a different arena indirectly, via
1622/// [`Constant`] or [`Override`] expressions, which hold handles for their
1623/// respective types.
1624///
1625/// [`Constant`]: Expression::Constant
1626/// [`Override`]: Expression::Override
1627#[derive(Clone, Debug, PartialEq)]
1628#[cfg_attr(feature = "serialize", derive(Serialize))]
1629#[cfg_attr(feature = "deserialize", derive(Deserialize))]
1630#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1631pub enum Expression {
1632 /// Literal.
1633 Literal(Literal),
1634 /// Constant value.
1635 Constant(Handle<Constant>),
1636 /// Pipeline-overridable constant.
1637 Override(Handle<Override>),
1638 /// Zero value of a type.
1639 ZeroValue(Handle<Type>),
1640 /// Composite expression.
1641 Compose {
1642 ty: Handle<Type>,
1643 components: Vec<Handle<Expression>>,
1644 },
1645
1646 /// Array access with a computed index.
1647 ///
1648 /// ## Typing rules
1649 ///
1650 /// The `base` operand must be some composite type: [`Vector`], [`Matrix`],
1651 /// [`Array`], a [`Pointer`] to one of those, or a [`ValuePointer`] with a
1652 /// `size`.
1653 ///
1654 /// The `index` operand must be an integer, signed or unsigned.
1655 ///
1656 /// Indexing a [`Vector`] or [`Array`] produces a value of its element type.
1657 /// Indexing a [`Matrix`] produces a [`Vector`].
1658 ///
1659 /// Indexing a [`Pointer`] to any of the above produces a pointer to the
1660 /// element/component type, in the same [`space`]. In the case of [`Array`],
1661 /// the result is an actual [`Pointer`], but for vectors and matrices, there
1662 /// may not be any type in the arena representing the component's type, so
1663 /// those produce [`ValuePointer`] types equivalent to the appropriate
1664 /// [`Pointer`].
1665 ///
1666 /// ## Dynamic indexing restrictions
1667 ///
1668 /// To accommodate restrictions in some of the shader languages that Naga
1669 /// targets, it is not permitted to subscript a matrix with a dynamically
1670 /// computed index unless that matrix appears behind a pointer. In other
1671 /// words, if the inner type of `base` is [`Matrix`], then `index` must be a
1672 /// constant. But if the type of `base` is a [`Pointer`] to an matrix, then
1673 /// the index may be any expression of integer type.
1674 ///
1675 /// You can use the [`Expression::is_dynamic_index`] method to determine
1676 /// whether a given index expression requires matrix base operands to be
1677 /// behind a pointer.
1678 ///
1679 /// (It would be simpler to always require the use of `AccessIndex` when
1680 /// subscripting matrices that are not behind pointers, but to accommodate
1681 /// existing front ends, Naga also permits `Access`, with a restricted
1682 /// `index`.)
1683 ///
1684 /// [`Vector`]: TypeInner::Vector
1685 /// [`Matrix`]: TypeInner::Matrix
1686 /// [`Array`]: TypeInner::Array
1687 /// [`Pointer`]: TypeInner::Pointer
1688 /// [`space`]: TypeInner::Pointer::space
1689 /// [`ValuePointer`]: TypeInner::ValuePointer
1690 /// [`Float`]: ScalarKind::Float
1691 Access {
1692 base: Handle<Expression>,
1693 index: Handle<Expression>,
1694 },
1695 /// Access the same types as [`Access`], plus [`Struct`] with a known index.
1696 ///
1697 /// [`Access`]: Expression::Access
1698 /// [`Struct`]: TypeInner::Struct
1699 AccessIndex {
1700 base: Handle<Expression>,
1701 index: u32,
1702 },
1703 /// Splat scalar into a vector.
1704 Splat {
1705 size: VectorSize,
1706 value: Handle<Expression>,
1707 },
1708 /// Vector swizzle.
1709 Swizzle {
1710 size: VectorSize,
1711 vector: Handle<Expression>,
1712 pattern: [SwizzleComponent; 4],
1713 },
1714
1715 /// Reference a function parameter, by its index.
1716 ///
1717 /// A `FunctionArgument` expression evaluates to the argument's value.
1718 FunctionArgument(u32),
1719
1720 /// Reference a global variable.
1721 ///
1722 /// If the given `GlobalVariable`'s [`space`] is [`AddressSpace::Handle`],
1723 /// then the variable stores some opaque type like a sampler or an image,
1724 /// and a `GlobalVariable` expression referring to it produces the
1725 /// variable's value directly.
1726 ///
1727 /// For any other address space, a `GlobalVariable` expression produces a
1728 /// pointer to the variable's value. You must use a [`Load`] expression to
1729 /// retrieve its value, or a [`Store`] statement to assign it a new value.
1730 ///
1731 /// [`space`]: GlobalVariable::space
1732 /// [`Load`]: Expression::Load
1733 /// [`Store`]: Statement::Store
1734 GlobalVariable(Handle<GlobalVariable>),
1735
1736 /// Reference a local variable.
1737 ///
1738 /// A `LocalVariable` expression evaluates to a pointer to the variable's value.
1739 /// You must use a [`Load`](Expression::Load) expression to retrieve its value,
1740 /// or a [`Store`](Statement::Store) statement to assign it a new value.
1741 LocalVariable(Handle<LocalVariable>),
1742
1743 /// Load a value indirectly.
1744 ///
1745 /// For [`TypeInner::Atomic`] the result is a corresponding scalar.
1746 /// For other types behind the `pointer<T>`, the result is `T`.
1747 Load { pointer: Handle<Expression> },
1748 /// Sample a point from a sampled or a depth image.
1749 ImageSample {
1750 image: Handle<Expression>,
1751 sampler: Handle<Expression>,
1752 /// If Some(), this operation is a gather operation
1753 /// on the selected component.
1754 gather: Option<SwizzleComponent>,
1755 coordinate: Handle<Expression>,
1756 array_index: Option<Handle<Expression>>,
1757 /// This must be a const-expression.
1758 offset: Option<Handle<Expression>>,
1759 level: SampleLevel,
1760 depth_ref: Option<Handle<Expression>>,
1761 /// Whether the sampling operation should clamp each component of
1762 /// `coordinate` to the range `[half_texel, 1 - half_texel]`, regardless
1763 /// of `sampler`.
1764 clamp_to_edge: bool,
1765 },
1766
1767 /// Load a texel from an image.
1768 ///
1769 /// For most images, this returns a four-element vector of the same
1770 /// [`ScalarKind`] as the image. If the format of the image does not have
1771 /// four components, default values are provided: the first three components
1772 /// (typically R, G, and B) default to zero, and the final component
1773 /// (typically alpha) defaults to one.
1774 ///
1775 /// However, if the image's [`class`] is [`Depth`], then this returns a
1776 /// [`Float`] scalar value.
1777 ///
1778 /// [`ScalarKind`]: ScalarKind
1779 /// [`class`]: TypeInner::Image::class
1780 /// [`Depth`]: ImageClass::Depth
1781 /// [`Float`]: ScalarKind::Float
1782 ImageLoad {
1783 /// The image to load a texel from. This must have type [`Image`]. (This
1784 /// will necessarily be a [`GlobalVariable`] or [`FunctionArgument`]
1785 /// expression, since no other expressions are allowed to have that
1786 /// type.)
1787 ///
1788 /// [`Image`]: TypeInner::Image
1789 /// [`GlobalVariable`]: Expression::GlobalVariable
1790 /// [`FunctionArgument`]: Expression::FunctionArgument
1791 image: Handle<Expression>,
1792
1793 /// The coordinate of the texel we wish to load. This must be a scalar
1794 /// for [`D1`] images, a [`Bi`] vector for [`D2`] images, and a [`Tri`]
1795 /// vector for [`D3`] images. (Array indices, sample indices, and
1796 /// explicit level-of-detail values are supplied separately.) Its
1797 /// component type must be [`Sint`].
1798 ///
1799 /// [`D1`]: ImageDimension::D1
1800 /// [`D2`]: ImageDimension::D2
1801 /// [`D3`]: ImageDimension::D3
1802 /// [`Bi`]: VectorSize::Bi
1803 /// [`Tri`]: VectorSize::Tri
1804 /// [`Sint`]: ScalarKind::Sint
1805 coordinate: Handle<Expression>,
1806
1807 /// The index into an arrayed image. If the [`arrayed`] flag in
1808 /// `image`'s type is `true`, then this must be `Some(expr)`, where
1809 /// `expr` is a [`Sint`] scalar. Otherwise, it must be `None`.
1810 ///
1811 /// [`arrayed`]: TypeInner::Image::arrayed
1812 /// [`Sint`]: ScalarKind::Sint
1813 array_index: Option<Handle<Expression>>,
1814
1815 /// A sample index, for multisampled [`Sampled`] and [`Depth`] images.
1816 ///
1817 /// [`Sampled`]: ImageClass::Sampled
1818 /// [`Depth`]: ImageClass::Depth
1819 sample: Option<Handle<Expression>>,
1820
1821 /// A level of detail, for mipmapped images.
1822 ///
1823 /// This must be present when accessing non-multisampled
1824 /// [`Sampled`] and [`Depth`] images, even if only the
1825 /// full-resolution level is present (in which case the only
1826 /// valid level is zero).
1827 ///
1828 /// [`Sampled`]: ImageClass::Sampled
1829 /// [`Depth`]: ImageClass::Depth
1830 level: Option<Handle<Expression>>,
1831 },
1832
1833 /// Query information from an image.
1834 ImageQuery {
1835 image: Handle<Expression>,
1836 query: ImageQuery,
1837 },
1838 /// Apply an unary operator.
1839 Unary {
1840 op: UnaryOperator,
1841 expr: Handle<Expression>,
1842 },
1843 /// Apply a binary operator.
1844 Binary {
1845 op: BinaryOperator,
1846 left: Handle<Expression>,
1847 right: Handle<Expression>,
1848 },
1849 /// Select between two values based on a condition.
1850 ///
1851 /// Note that, because expressions have no side effects, it is unobservable
1852 /// whether the non-selected branch is evaluated.
1853 Select {
1854 /// Boolean expression
1855 condition: Handle<Expression>,
1856 accept: Handle<Expression>,
1857 reject: Handle<Expression>,
1858 },
1859 /// Compute the derivative on an axis.
1860 Derivative {
1861 axis: DerivativeAxis,
1862 ctrl: DerivativeControl,
1863 expr: Handle<Expression>,
1864 },
1865 /// Call a relational function.
1866 Relational {
1867 fun: RelationalFunction,
1868 argument: Handle<Expression>,
1869 },
1870 /// Call a math function
1871 Math {
1872 fun: MathFunction,
1873 arg: Handle<Expression>,
1874 arg1: Option<Handle<Expression>>,
1875 arg2: Option<Handle<Expression>>,
1876 arg3: Option<Handle<Expression>>,
1877 },
1878 /// Convert the components of a scalar, vector or matrix to another scalar type.
1879 ///
1880 /// The result has the same shape as `expr`, with its scalar type replaced
1881 /// by `target`. To reinterpret bits instead, see [`Bitcast`].
1882 ///
1883 /// [`Bitcast`]: Expression::Bitcast
1884 As {
1885 /// Source expression, which can only be a scalar, a vector or a matrix.
1886 expr: Handle<Expression>,
1887 /// Scalar type of the result's components.
1888 target: Scalar,
1889 },
1890 /// Reinterpret the bits of a scalar or vector as another scalar or vector type.
1891 ///
1892 /// `ty` and the type of `expr` must both be numeric scalars or vectors with
1893 /// the same size in bytes. Components are laid out as in memory, so a
1894 /// `vec2<f16>` can be bitcast to a `u32`, whose low bits are the first
1895 /// component.
1896 Bitcast {
1897 /// Source expression, which can only be a scalar or a vector.
1898 expr: Handle<Expression>,
1899 /// Type of the result.
1900 ty: Handle<Type>,
1901 },
1902 /// Result of calling another function.
1903 CallResult(Handle<Function>),
1904
1905 /// Result of an atomic operation.
1906 ///
1907 /// This expression must be referred to by the [`result`] field of exactly one
1908 /// [`Atomic`][stmt] statement somewhere in the same function. Let `T` be the
1909 /// scalar type contained by the [`Atomic`][type] value that the statement
1910 /// operates on.
1911 ///
1912 /// If `comparison` is `false`, then `ty` must be the scalar type `T`.
1913 ///
1914 /// If `comparison` is `true`, then `ty` must be a [`Struct`] with two members:
1915 ///
1916 /// - A member named `old_value`, whose type is `T`, and
1917 ///
1918 /// - A member named `exchanged`, of type [`BOOL`].
1919 ///
1920 /// [`result`]: Statement::Atomic::result
1921 /// [stmt]: Statement::Atomic
1922 /// [type]: TypeInner::Atomic
1923 /// [`Struct`]: TypeInner::Struct
1924 /// [`BOOL`]: Scalar::BOOL
1925 AtomicResult { ty: Handle<Type>, comparison: bool },
1926
1927 /// Result of a [`WorkGroupUniformLoad`] statement.
1928 ///
1929 /// [`WorkGroupUniformLoad`]: Statement::WorkGroupUniformLoad
1930 WorkGroupUniformLoadResult {
1931 /// The type of the result
1932 ty: Handle<Type>,
1933 },
1934 /// Get the length of an array.
1935 /// The expression must resolve to a pointer to an array with a dynamic size.
1936 ///
1937 /// This doesn't match the semantics of spirv's `OpArrayLength`, which must be passed
1938 /// a pointer to a structure containing a runtime array in its' last field.
1939 ArrayLength(Handle<Expression>),
1940
1941 /// Get the Positions of the triangle hit by the [`RayQuery`]
1942 ///
1943 /// [`RayQuery`]: Statement::RayQuery
1944 RayQueryVertexPositions {
1945 query: Handle<Expression>,
1946 committed: bool,
1947 },
1948
1949 /// Result of a [`Proceed`] [`RayQuery`] statement.
1950 ///
1951 /// [`Proceed`]: RayQueryFunction::Proceed
1952 /// [`RayQuery`]: Statement::RayQuery
1953 RayQueryProceedResult,
1954
1955 /// Return an intersection found by `query`.
1956 ///
1957 /// If `committed` is true, return the committed result available when
1958 RayQueryGetIntersection {
1959 query: Handle<Expression>,
1960 committed: bool,
1961 },
1962
1963 /// Query the state recorded in a [`HitObject`].
1964 ///
1965 /// The `hit_object` operand must be a pointer in the [`Function`] address
1966 /// space to a [`TypeInner::HitObject`]. Unlike the operand of a
1967 /// [`Statement::HitObject`] statement, it can be a function argument.
1968 ///
1969 /// Like [`RayQueryGetIntersection`], this is an ordinary expression that is
1970 /// evaluated by the [`Emit`] statement that covers it.
1971 ///
1972 /// [`HitObject`]: TypeInner::HitObject
1973 /// [`Function`]: AddressSpace::Function
1974 /// [`RayQueryGetIntersection`]: Expression::RayQueryGetIntersection
1975 /// [`Emit`]: Statement::Emit
1976 HitObjectQuery {
1977 /// The hit object to inspect.
1978 hit_object: Handle<Expression>,
1979
1980 /// The property of `hit_object` to retrieve.
1981 query: HitObjectQuery,
1982 },
1983
1984 /// Result of a [`SubgroupBallot`] statement.
1985 ///
1986 /// [`SubgroupBallot`]: Statement::SubgroupBallot
1987 SubgroupBallotResult,
1988
1989 /// Result of a [`SubgroupCollectiveOperation`] or [`SubgroupGather`] statement.
1990 ///
1991 /// [`SubgroupCollectiveOperation`]: Statement::SubgroupCollectiveOperation
1992 /// [`SubgroupGather`]: Statement::SubgroupGather
1993 SubgroupOperationResult { ty: Handle<Type> },
1994
1995 /// Load a cooperative primitive from memory.
1996 CooperativeLoad {
1997 columns: CooperativeSize,
1998 rows: CooperativeSize,
1999 role: CooperativeRole,
2000 data: CooperativeData,
2001 },
2002 /// Compute `a * b + c`
2003 CooperativeMultiplyAdd {
2004 a: Handle<Expression>,
2005 b: Handle<Expression>,
2006 c: Handle<Expression>,
2007 },
2008}
2009
2010/// The value of the switch case.
2011#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
2012#[cfg_attr(feature = "serialize", derive(Serialize))]
2013#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2014#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2015pub enum SwitchValue {
2016 I32(i32),
2017 U32(u32),
2018 Default,
2019}
2020
2021/// A case for a switch statement.
2022// Clone is used only for error reporting and is not intended for end users
2023#[derive(Clone, Debug)]
2024#[cfg_attr(feature = "serialize", derive(Serialize))]
2025#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2026#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2027pub struct SwitchCase {
2028 /// Value, upon which the case is considered true.
2029 pub value: SwitchValue,
2030 /// Body of the case.
2031 pub body: Block,
2032 /// If true, the control flow continues to the next case in the list,
2033 /// or default.
2034 pub fall_through: bool,
2035}
2036
2037/// An operation that a [`RayQuery` statement] applies to its [`query`] operand.
2038///
2039/// [`RayQuery` statement]: Statement::RayQuery
2040/// [`query`]: Statement::RayQuery::query
2041#[derive(Clone, Debug)]
2042#[cfg_attr(feature = "serialize", derive(Serialize))]
2043#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2044#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2045pub enum RayQueryFunction {
2046 /// Initialize the `RayQuery` object.
2047 Initialize {
2048 /// The acceleration structure within which this query should search for hits.
2049 ///
2050 /// The expression must be an [`AccelerationStructure`].
2051 ///
2052 /// [`AccelerationStructure`]: TypeInner::AccelerationStructure
2053 acceleration_structure: Handle<Expression>,
2054
2055 #[allow(rustdoc::private_intra_doc_links)]
2056 /// A struct of detailed parameters for the ray query.
2057 ///
2058 /// This expression should have the struct type given in
2059 /// [`SpecialTypes::ray_desc`]. This is available in the WGSL
2060 /// front end as the `RayDesc` type.
2061 descriptor: Handle<Expression>,
2062 },
2063
2064 /// Start or continue the query given by the statement's [`query`] operand.
2065 ///
2066 /// After executing this statement, the `result` expression is a
2067 /// [`Bool`] scalar indicating whether there are more intersection
2068 /// candidates to consider.
2069 ///
2070 /// [`query`]: Statement::RayQuery::query
2071 /// [`Bool`]: ScalarKind::Bool
2072 Proceed {
2073 result: Handle<Expression>,
2074 },
2075
2076 /// Add a candidate generated intersection to be included
2077 /// in the determination of the closest hit for a ray query.
2078 GenerateIntersection {
2079 hit_t: Handle<Expression>,
2080 },
2081
2082 /// Confirm a triangle intersection to be included in the determination of
2083 /// the closest hit for a ray query.
2084 ConfirmIntersection,
2085
2086 Terminate,
2087
2088 /// Resets a variable's to appear as though it was previously unused.
2089 ///
2090 /// For most types in variables which don't have initialisers, a zero store
2091 /// is fine when resetting a variable in a loop (as functions always have
2092 /// their variables outside all blocks while wgsl and others can have blocks
2093 /// in loops) but ray queries cannot be stored to nor can be zero initialized.
2094 Begin,
2095}
2096
2097//TODO: consider removing `Clone`. It's not valid to clone `Statement::Emit` anyway.
2098/// Instructions which make up an executable block.
2099///
2100/// `Handle<Expression>` and `Range<Expression>` values in `Statement` variants
2101/// refer to expressions in [`Function::expressions`], unless otherwise noted.
2102// Clone is used only for error reporting and is not intended for end users
2103#[derive(Clone, Debug)]
2104#[cfg_attr(feature = "serialize", derive(Serialize))]
2105#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2106#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2107pub enum Statement {
2108 /// Emit a range of expressions, visible to all statements that follow in this block.
2109 ///
2110 /// See the [module-level documentation][emit] for details.
2111 ///
2112 /// [emit]: index.html#expression-evaluation-time
2113 Emit(Range<Expression>),
2114 /// A block containing more statements, to be executed sequentially.
2115 Block(Block),
2116 /// Conditionally executes one of two blocks, based on the value of the condition.
2117 ///
2118 /// Naga IR does not have "phi" instructions. If you need to use
2119 /// values computed in an `accept` or `reject` block after the `If`,
2120 /// store them in a [`LocalVariable`].
2121 If {
2122 condition: Handle<Expression>, //bool
2123 accept: Block,
2124 reject: Block,
2125 },
2126 /// Conditionally executes one of multiple blocks, based on the value of the selector.
2127 ///
2128 /// Each case must have a distinct [`value`], exactly one of which must be
2129 /// [`Default`]. The `Default` may appear at any position, and covers all
2130 /// values not explicitly appearing in other cases. A `Default` appearing in
2131 /// the midst of the list of cases does not shadow the cases that follow.
2132 ///
2133 /// Some backend languages don't support fallthrough (HLSL due to FXC,
2134 /// WGSL), and may translate fallthrough cases in the IR by duplicating
2135 /// code. However, all backend languages do support cases selected by
2136 /// multiple values, like `case 1: case 2: case 3: { ... }`. This is
2137 /// represented in the IR as a series of fallthrough cases with empty
2138 /// bodies, except for the last.
2139 ///
2140 /// Naga IR does not have "phi" instructions. If you need to use
2141 /// values computed in a [`SwitchCase::body`] block after the `Switch`,
2142 /// store them in a [`LocalVariable`].
2143 ///
2144 /// [`value`]: SwitchCase::value
2145 /// [`body`]: SwitchCase::body
2146 /// [`Default`]: SwitchValue::Default
2147 Switch {
2148 selector: Handle<Expression>,
2149 cases: Vec<SwitchCase>,
2150 },
2151
2152 /// Executes a block repeatedly.
2153 ///
2154 /// Each iteration of the loop executes the `body` block, followed by the
2155 /// `continuing` block.
2156 ///
2157 /// Executing a [`Break`], [`Return`] or [`Kill`] statement exits the loop.
2158 ///
2159 /// A [`Continue`] statement in `body` jumps to the `continuing` block. The
2160 /// `continuing` block is meant to be used to represent structures like the
2161 /// third expression of a C-style `for` loop head, to which `continue`
2162 /// statements in the loop's body jump.
2163 ///
2164 /// The `continuing` block and its substatements must not contain `Return`
2165 /// or `Kill` statements, or any `Break` or `Continue` statements targeting
2166 /// this loop. (It may have `Break` and `Continue` statements targeting
2167 /// loops or switches nested within the `continuing` block.) Expressions
2168 /// emitted in `body` are in scope in `continuing`.
2169 ///
2170 /// If present, `break_if` is an expression which is evaluated after the
2171 /// continuing block. Expressions emitted in `body` or `continuing` are
2172 /// considered to be in scope. If the expression's value is true, control
2173 /// continues after the `Loop` statement, rather than branching back to the
2174 /// top of body as usual. The `break_if` expression corresponds to a "break
2175 /// if" statement in WGSL, or a loop whose back edge is an
2176 /// `OpBranchConditional` instruction in SPIR-V.
2177 ///
2178 /// Naga IR does not have "phi" instructions. If you need to use
2179 /// values computed in a `body` or `continuing` block after the
2180 /// `Loop`, store them in a [`LocalVariable`].
2181 ///
2182 /// [`Break`]: Statement::Break
2183 /// [`Continue`]: Statement::Continue
2184 /// [`Kill`]: Statement::Kill
2185 /// [`Return`]: Statement::Return
2186 /// [`break if`]: Self::Loop::break_if
2187 Loop {
2188 body: Block,
2189 continuing: Block,
2190 break_if: Option<Handle<Expression>>,
2191 },
2192
2193 /// Exits the innermost enclosing [`Loop`] or [`Switch`].
2194 ///
2195 /// A `Break` statement may only appear within a [`Loop`] or [`Switch`]
2196 /// statement. It may not break out of a [`Loop`] from within the loop's
2197 /// `continuing` block.
2198 ///
2199 /// [`Loop`]: Statement::Loop
2200 /// [`Switch`]: Statement::Switch
2201 Break,
2202
2203 /// Skips to the `continuing` block of the innermost enclosing [`Loop`].
2204 ///
2205 /// A `Continue` statement may only appear within the `body` block of the
2206 /// innermost enclosing [`Loop`] statement. It must not appear within that
2207 /// loop's `continuing` block.
2208 ///
2209 /// [`Loop`]: Statement::Loop
2210 Continue,
2211
2212 /// Returns from the function (possibly with a value).
2213 ///
2214 /// `Return` statements are forbidden within the `continuing` block of a
2215 /// [`Loop`] statement.
2216 ///
2217 /// [`Loop`]: Statement::Loop
2218 Return { value: Option<Handle<Expression>> },
2219
2220 /// Aborts the current shader execution.
2221 ///
2222 /// `Kill` statements are forbidden within the `continuing` block of a
2223 /// [`Loop`] statement.
2224 ///
2225 /// [`Loop`]: Statement::Loop
2226 Kill,
2227
2228 /// Synchronize invocations within the work group.
2229 /// The `Barrier` flags control which memory accesses should be synchronized.
2230 /// If empty, this becomes purely an execution barrier.
2231 ControlBarrier(Barrier),
2232
2233 /// Synchronize invocations within the work group.
2234 /// The `Barrier` flags control which memory accesses should be synchronized.
2235 MemoryBarrier(Barrier),
2236
2237 /// Stores a value at an address.
2238 ///
2239 /// For [`TypeInner::Atomic`] type behind the pointer, the value
2240 /// has to be a corresponding scalar.
2241 /// For other types behind the `pointer<T>`, the value is `T`.
2242 ///
2243 /// This statement is a barrier for any operations on the
2244 /// `Expression::LocalVariable` or `Expression::GlobalVariable`
2245 /// that is the destination of an access chain, started
2246 /// from the `pointer`.
2247 Store {
2248 pointer: Handle<Expression>,
2249 value: Handle<Expression>,
2250 },
2251 /// Stores a texel value to an image.
2252 ///
2253 /// The `image`, `coordinate`, and `array_index` fields have the same
2254 /// meanings as the corresponding operands of an [`ImageLoad`] expression;
2255 /// see that documentation for details. Storing into multisampled images or
2256 /// images with mipmaps is not supported, so there are no `level` or
2257 /// `sample` operands.
2258 ///
2259 /// This statement is a barrier for any operations on the corresponding
2260 /// [`Expression::GlobalVariable`] for this image.
2261 ///
2262 /// [`ImageLoad`]: Expression::ImageLoad
2263 ImageStore {
2264 image: Handle<Expression>,
2265 coordinate: Handle<Expression>,
2266 array_index: Option<Handle<Expression>>,
2267 value: Handle<Expression>,
2268 },
2269 /// Atomic function.
2270 Atomic {
2271 /// Pointer to an atomic value.
2272 ///
2273 /// This must be a [`Pointer`] to an [`Atomic`] value. The atomic's
2274 /// scalar type may be [`I32`] or [`U32`].
2275 ///
2276 /// If [`SHADER_INT64_ATOMIC_MIN_MAX`] or [`SHADER_INT64_ATOMIC_ALL_OPS`] are
2277 /// enabled, this may also be [`I64`] or [`U64`].
2278 ///
2279 /// If [`SHADER_FLOAT32_ATOMIC`] is enabled, this may be [`F32`].
2280 ///
2281 /// [`Pointer`]: TypeInner::Pointer
2282 /// [`Atomic`]: TypeInner::Atomic
2283 /// [`I32`]: Scalar::I32
2284 /// [`U32`]: Scalar::U32
2285 /// [`SHADER_INT64_ATOMIC_MIN_MAX`]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_MIN_MAX
2286 /// [`SHADER_INT64_ATOMIC_ALL_OPS`]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_ALL_OPS
2287 /// [`SHADER_FLOAT32_ATOMIC`]: crate::valid::Capabilities::SHADER_FLOAT32_ATOMIC
2288 /// [`I64`]: Scalar::I64
2289 /// [`U64`]: Scalar::U64
2290 /// [`F32`]: Scalar::F32
2291 pointer: Handle<Expression>,
2292
2293 /// Function to run on the atomic value.
2294 ///
2295 /// If [`pointer`] refers to a 64-bit atomic value, then:
2296 ///
2297 /// - The [`SHADER_INT64_ATOMIC_ALL_OPS`] capability allows any [`AtomicFunction`]
2298 /// value here.
2299 ///
2300 /// - The [`SHADER_INT64_ATOMIC_MIN_MAX`] capability allows
2301 /// [`AtomicFunction::Min`] and [`AtomicFunction::Max`]
2302 /// in the [`Storage`] address space here.
2303 ///
2304 /// - If neither of those capabilities are present, then 64-bit scalar
2305 /// atomics are not allowed.
2306 ///
2307 /// If [`pointer`] refers to a 32-bit floating-point atomic value, then:
2308 ///
2309 /// - The [`SHADER_FLOAT32_ATOMIC`] capability allows [`AtomicFunction::Add`],
2310 /// [`AtomicFunction::Subtract`], and [`AtomicFunction::Exchange { compare: None }`]
2311 /// in the [`Storage`] address space here.
2312 ///
2313 /// [`AtomicFunction::Exchange { compare: None }`]: AtomicFunction::Exchange
2314 /// [`pointer`]: Statement::Atomic::pointer
2315 /// [`Storage`]: AddressSpace::Storage
2316 /// [`SHADER_INT64_ATOMIC_MIN_MAX`]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_MIN_MAX
2317 /// [`SHADER_INT64_ATOMIC_ALL_OPS`]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_ALL_OPS
2318 /// [`SHADER_FLOAT32_ATOMIC`]: crate::valid::Capabilities::SHADER_FLOAT32_ATOMIC
2319 fun: AtomicFunction,
2320
2321 /// Value to use in the function.
2322 ///
2323 /// This must be a scalar of the same type as [`pointer`]'s atomic's scalar type.
2324 ///
2325 /// [`pointer`]: Statement::Atomic::pointer
2326 value: Handle<Expression>,
2327
2328 /// [`AtomicResult`] expression representing this function's result.
2329 ///
2330 /// If [`fun`] is [`Exchange { compare: None }`], this must be `Some`,
2331 /// as otherwise that operation would be equivalent to a simple [`Store`]
2332 /// to the atomic.
2333 ///
2334 /// Otherwise, this may be `None` if the return value of the operation is not needed.
2335 ///
2336 /// If `pointer` refers to a 64-bit atomic value, [`SHADER_INT64_ATOMIC_MIN_MAX`]
2337 /// is enabled, and [`SHADER_INT64_ATOMIC_ALL_OPS`] is not, this must be `None`.
2338 ///
2339 /// [`AtomicResult`]: crate::Expression::AtomicResult
2340 /// [`fun`]: Statement::Atomic::fun
2341 /// [`Store`]: Statement::Store
2342 /// [`Exchange { compare: None }`]: AtomicFunction::Exchange
2343 /// [`SHADER_INT64_ATOMIC_MIN_MAX`]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_MIN_MAX
2344 /// [`SHADER_INT64_ATOMIC_ALL_OPS`]: crate::valid::Capabilities::SHADER_INT64_ATOMIC_ALL_OPS
2345 result: Option<Handle<Expression>>,
2346 },
2347 /// Performs an atomic operation on a texel value of an image.
2348 ///
2349 /// Doing atomics on images with mipmaps is not supported, so there is no
2350 /// `level` operand.
2351 ImageAtomic {
2352 /// The image to perform an atomic operation on. This must have type
2353 /// [`Image`]. (This will necessarily be a [`GlobalVariable`] or
2354 /// [`FunctionArgument`] expression, since no other expressions are
2355 /// allowed to have that type.)
2356 ///
2357 /// [`Image`]: TypeInner::Image
2358 /// [`GlobalVariable`]: Expression::GlobalVariable
2359 /// [`FunctionArgument`]: Expression::FunctionArgument
2360 image: Handle<Expression>,
2361
2362 /// The coordinate of the texel we wish to load. This must be a scalar
2363 /// for [`D1`] images, a [`Bi`] vector for [`D2`] images, and a [`Tri`]
2364 /// vector for [`D3`] images. (Array indices, sample indices, and
2365 /// explicit level-of-detail values are supplied separately.) Its
2366 /// component type must be [`Sint`].
2367 ///
2368 /// [`D1`]: ImageDimension::D1
2369 /// [`D2`]: ImageDimension::D2
2370 /// [`D3`]: ImageDimension::D3
2371 /// [`Bi`]: VectorSize::Bi
2372 /// [`Tri`]: VectorSize::Tri
2373 /// [`Sint`]: ScalarKind::Sint
2374 coordinate: Handle<Expression>,
2375
2376 /// The index into an arrayed image. If the [`arrayed`] flag in
2377 /// `image`'s type is `true`, then this must be `Some(expr)`, where
2378 /// `expr` is a [`Sint`] scalar. Otherwise, it must be `None`.
2379 ///
2380 /// [`arrayed`]: TypeInner::Image::arrayed
2381 /// [`Sint`]: ScalarKind::Sint
2382 array_index: Option<Handle<Expression>>,
2383
2384 /// The kind of atomic operation to perform on the texel.
2385 fun: AtomicFunction,
2386
2387 /// The value with which to perform the atomic operation.
2388 value: Handle<Expression>,
2389 },
2390 /// Load uniformly from a uniform pointer in the workgroup address space.
2391 ///
2392 /// Corresponds to the [`workgroupUniformLoad`](https://www.w3.org/TR/WGSL/#workgroupUniformLoad-builtin)
2393 /// built-in function of wgsl, and has the same barrier semantics
2394 WorkGroupUniformLoad {
2395 /// This must be of type [`Pointer`] in the [`WorkGroup`] address space
2396 ///
2397 /// [`Pointer`]: TypeInner::Pointer
2398 /// [`WorkGroup`]: AddressSpace::WorkGroup
2399 pointer: Handle<Expression>,
2400 /// The [`WorkGroupUniformLoadResult`] expression representing this load's result.
2401 ///
2402 /// [`WorkGroupUniformLoadResult`]: Expression::WorkGroupUniformLoadResult
2403 result: Handle<Expression>,
2404 },
2405 /// Calls a function.
2406 ///
2407 /// If the `result` is `Some`, the corresponding expression has to be
2408 /// `Expression::CallResult`, and this statement serves as a barrier for any
2409 /// operations on that expression.
2410 Call {
2411 function: Handle<Function>,
2412 arguments: Vec<Handle<Expression>>,
2413 result: Option<Handle<Expression>>,
2414 },
2415 RayQuery {
2416 /// The [`RayQuery`] object this statement operates on.
2417 ///
2418 /// [`RayQuery`]: TypeInner::RayQuery
2419 query: Handle<Expression>,
2420
2421 /// The specific operation we're performing on `query`.
2422 fun: RayQueryFunction,
2423 },
2424 /// A ray tracing pipeline shader intrinsic.
2425 RayPipelineFunction(RayPipelineFunction),
2426 /// An operation on a hit object.
2427 HitObject {
2428 /// The [`HitObject`] this statement operates on.
2429 ///
2430 /// This must be a [`LocalVariable`] expression whose type is
2431 /// [`TypeInner::HitObject`].
2432 ///
2433 /// [`HitObject`]: TypeInner::HitObject
2434 /// [`LocalVariable`]: Expression::LocalVariable
2435 hit_object: Handle<Expression>,
2436
2437 /// The specific operation we're performing on `hit_object`.
2438 fun: HitObjectFunction,
2439 },
2440 /// Calculate a bitmask using a boolean from each active thread in the subgroup
2441 SubgroupBallot {
2442 /// The [`SubgroupBallotResult`] expression representing this load's result.
2443 ///
2444 /// [`SubgroupBallotResult`]: Expression::SubgroupBallotResult
2445 result: Handle<Expression>,
2446 /// The value from this thread to store in the ballot
2447 predicate: Option<Handle<Expression>>,
2448 },
2449 /// Gather a value from another active thread in the subgroup
2450 SubgroupGather {
2451 /// Specifies which thread to gather from
2452 mode: GatherMode,
2453 /// The value to broadcast over
2454 argument: Handle<Expression>,
2455 /// The [`SubgroupOperationResult`] expression representing this load's result.
2456 ///
2457 /// [`SubgroupOperationResult`]: Expression::SubgroupOperationResult
2458 result: Handle<Expression>,
2459 },
2460 /// Compute a collective operation across all active threads in the subgroup
2461 SubgroupCollectiveOperation {
2462 /// What operation to compute
2463 op: SubgroupOperation,
2464 /// How to combine the results
2465 collective_op: CollectiveOperation,
2466 /// The value to compute over
2467 argument: Handle<Expression>,
2468 /// The [`SubgroupOperationResult`] expression representing this load's result.
2469 ///
2470 /// [`SubgroupOperationResult`]: Expression::SubgroupOperationResult
2471 result: Handle<Expression>,
2472 },
2473 /// Find the invocation index of a set bit in a subgroup ballot.
2474 SubgroupBallotFindBit {
2475 /// Which set bit to find.
2476 order: BallotFindBitOrder,
2477 /// The ballot to search, a `vec4<u32>`, usually a [`SubgroupBallotResult`] expression.
2478 ///
2479 /// [`SubgroupBallotResult`]: Expression::SubgroupBallotResult
2480 argument: Handle<Expression>,
2481 /// The [`SubgroupOperationResult`] expression representing this load's result.
2482 ///
2483 /// [`SubgroupOperationResult`]: Expression::SubgroupOperationResult
2484 result: Handle<Expression>,
2485 },
2486 /// Store a cooperative primitive into memory.
2487 CooperativeStore {
2488 target: Handle<Expression>,
2489 data: CooperativeData,
2490 },
2491 /// This corresponds to `debugPrintf` in WGSL when the `wgpu_debug_printf` extension is enabled.
2492 DebugPrintf {
2493 format: String,
2494 arguments: Vec<Handle<Expression>>,
2495 },
2496}
2497
2498/// A function argument.
2499#[derive(Clone, Debug)]
2500#[cfg_attr(feature = "serialize", derive(Serialize))]
2501#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2502#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2503pub struct FunctionArgument {
2504 /// Name of the argument, if any.
2505 pub name: Option<String>,
2506 /// Type of the argument.
2507 pub ty: Handle<Type>,
2508 /// For entry points, an argument has to have a binding
2509 /// unless it's a structure.
2510 pub binding: Option<Binding>,
2511}
2512
2513/// A function result.
2514#[derive(Clone, Debug)]
2515#[cfg_attr(feature = "serialize", derive(Serialize))]
2516#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2517#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2518pub struct FunctionResult {
2519 /// Type of the result.
2520 pub ty: Handle<Type>,
2521 /// For entry points, the result has to have a binding
2522 /// unless it's a structure.
2523 pub binding: Option<Binding>,
2524}
2525
2526/// A function defined in the module.
2527#[derive(Debug, Default, Clone)]
2528#[cfg_attr(feature = "serialize", derive(Serialize))]
2529#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2530#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2531pub struct Function {
2532 /// Name of the function, if any.
2533 ///
2534 /// Unlike WGSL, Naga IR allows a module to have multiple functions with the
2535 /// same name. Since functions are generally identified by handle, the name
2536 /// is mostly needed for diagnostics and as a hint to [`Namer`].
2537 ///
2538 /// [`Namer`]: crate::proc::Namer
2539 pub name: Option<String>,
2540 /// Information about function argument.
2541 pub arguments: Vec<FunctionArgument>,
2542 /// The result of this function, if any.
2543 pub result: Option<FunctionResult>,
2544 /// Local variables defined and used in the function.
2545 pub local_variables: Arena<LocalVariable>,
2546 /// Expressions used inside this function.
2547 ///
2548 /// Unless explicitly stated otherwise, if an [`Expression`] is in this
2549 /// arena, then its subexpressions are in this arena too. In other words,
2550 /// every `Handle<Expression>` in this arena refers to an [`Expression`] in
2551 /// this arena too.
2552 ///
2553 /// The main ways this arena refers to [`Module::global_expressions`] are:
2554 ///
2555 /// - [`Constant`], [`Override`], and [`GlobalVariable`] expressions hold
2556 /// handles for their respective types, whose initializer expressions are
2557 /// in [`Module::global_expressions`].
2558 ///
2559 /// - Various expressions hold [`Type`] handles, and [`Type`]s may refer to
2560 /// global expressions, for things like array lengths.
2561 ///
2562 /// An [`Expression`] must occur before all other [`Expression`]s that use
2563 /// its value.
2564 ///
2565 /// [`Constant`]: Expression::Constant
2566 /// [`Override`]: Expression::Override
2567 /// [`GlobalVariable`]: Expression::GlobalVariable
2568 pub expressions: Arena<Expression>,
2569 /// Map of expressions that have associated variable names
2570 pub named_expressions: NamedExpressions,
2571 /// Block of instructions comprising the body of the function.
2572 pub body: Block,
2573 /// The leaf of all diagnostic filter rules tree (stored in [`Module::diagnostic_filters`])
2574 /// parsed on this function.
2575 ///
2576 /// In WGSL, this corresponds to `@diagnostic(…)` attributes.
2577 ///
2578 /// See [`DiagnosticFilterNode`] for details on how the tree is represented and used in
2579 /// validation.
2580 pub diagnostic_filter_leaf: Option<Handle<DiagnosticFilterNode>>,
2581}
2582
2583/// The main function for a pipeline stage.
2584///
2585/// An [`EntryPoint`] is a [`Function`] that serves as the main function for a
2586/// graphics or compute pipeline stage. For example, an `EntryPoint` whose
2587/// [`stage`] is [`ShaderStage::Vertex`] can serve as a graphics pipeline's
2588/// vertex shader.
2589///
2590/// Since an entry point is called directly by the graphics or compute pipeline,
2591/// not by other WGSL functions, you must specify what the pipeline should pass
2592/// as the entry point's arguments, and what values it will return. For example,
2593/// a vertex shader needs a vertex's attributes as its arguments, but if it's
2594/// used for instanced draw calls, it will also want to know the instance id.
2595/// The vertex shader's return value will usually include an output vertex
2596/// position, and possibly other attributes to be interpolated and passed along
2597/// to a fragment shader.
2598///
2599/// To specify this, the arguments and result of an `EntryPoint`'s [`function`]
2600/// must each have a [`Binding`], or be structs whose members all have
2601/// `Binding`s. This associates every value passed to or returned from the entry
2602/// point with either a [`BuiltIn`] or a [`Location`]:
2603///
2604/// - A [`BuiltIn`] has special semantics, usually specific to its pipeline
2605/// stage. For example, the result of a vertex shader can include a
2606/// [`BuiltIn::Position`] value, which determines the position of a vertex
2607/// of a rendered primitive. Or, a compute shader might take an argument
2608/// whose binding is [`BuiltIn::WorkGroupSize`], through which the compute
2609/// pipeline would pass the number of invocations in your workgroup.
2610///
2611/// - A [`Location`] indicates user-defined IO to be passed from one pipeline
2612/// stage to the next. For example, a vertex shader might also produce a
2613/// `uv` texture location as a user-defined IO value.
2614///
2615/// In other words, the pipeline stage's input and output interface are
2616/// determined by the bindings of the arguments and result of the `EntryPoint`'s
2617/// [`function`].
2618///
2619/// [`Function`]: crate::Function
2620/// [`Location`]: Binding::Location
2621/// [`function`]: EntryPoint::function
2622/// [`stage`]: EntryPoint::stage
2623#[derive(Debug, Clone)]
2624#[cfg_attr(feature = "serialize", derive(Serialize))]
2625#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2626#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2627pub struct EntryPoint {
2628 /// Name of this entry point, visible externally.
2629 ///
2630 /// Unlike WGSL, Naga IR allows a module to have multiple entry points with
2631 /// the same name, as long as they are for different shader stages. That is,
2632 /// `(name, stage)` pairs must be distinct within a module.
2633 pub name: String,
2634 /// Shader stage.
2635 pub stage: ShaderStage,
2636 /// Early depth test for fragment stages.
2637 pub early_depth_test: Option<EarlyDepthTest>,
2638 /// Workgroup size for compute stages
2639 pub workgroup_size: [u32; 3],
2640 /// Override expressions for workgroup size in the global_expressions arena
2641 pub workgroup_size_overrides: Option<[Option<Handle<Expression>>; 3]>,
2642 /// The entrance function.
2643 pub function: Function,
2644 /// Information for [`Mesh`] shaders.
2645 ///
2646 /// [`Mesh`]: ShaderStage::Mesh
2647 pub mesh_info: Option<MeshStageInfo>,
2648 /// The unique global variable used as a task payload from task shader to mesh shader
2649 pub task_payload: Option<Handle<GlobalVariable>>,
2650 /// The unique global variable used as an incoming ray payload going into any hit, closest hit and miss shaders.
2651 /// Unlike the outgoing ray payload, an incoming ray payload must be unique
2652 pub incoming_ray_payload: Option<Handle<GlobalVariable>>,
2653}
2654
2655/// Return types predeclared for the frexp, modf, and atomicCompareExchangeWeak built-in functions.
2656///
2657/// These cannot be spelled in WGSL source.
2658///
2659/// Stored in [`SpecialTypes::predeclared_types`] and created by [`Module::generate_predeclared_type`].
2660#[derive(Debug, PartialEq, Eq, Hash, Clone)]
2661#[cfg_attr(feature = "serialize", derive(Serialize))]
2662#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2663#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2664pub enum PredeclaredType {
2665 AtomicCompareExchangeWeakResult(Scalar),
2666 ModfResult {
2667 size: Option<VectorSize>,
2668 scalar: Scalar,
2669 },
2670 FrexpResult {
2671 size: Option<VectorSize>,
2672 scalar: Scalar,
2673 },
2674}
2675
2676/// Set of special types that can be optionally generated by the frontends.
2677#[derive(Debug, Default, Clone)]
2678#[cfg_attr(feature = "serialize", derive(Serialize))]
2679#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2680#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2681pub struct SpecialTypes {
2682 /// Type for `RayDesc`.
2683 ///
2684 /// Call [`Module::generate_ray_desc_type`] to populate this if
2685 /// needed and return the handle.
2686 pub ray_desc: Option<Handle<Type>>,
2687
2688 /// Type for `RayIntersection`.
2689 ///
2690 /// Call [`Module::generate_ray_intersection_type`] to populate
2691 /// this if needed and return the handle.
2692 pub ray_intersection: Option<Handle<Type>>,
2693
2694 /// Type for `RayVertexReturn`.
2695 ///
2696 /// Call [`Module::generate_vertex_return_type`]
2697 pub ray_vertex_return: Option<Handle<Type>>,
2698
2699 /// Struct containing parameters required by some backends to emit code for
2700 /// [`ImageClass::External`] textures.
2701 ///
2702 /// See `wgpu_core::device::resource::ExternalTextureParams` for the
2703 /// documentation of each field.
2704 ///
2705 /// In WGSL, this type would be:
2706 ///
2707 /// ```ignore
2708 /// struct NagaExternalTextureParams { // align size offset
2709 /// yuv_conversion_matrix: mat4x4<f32>, // 16 64 0
2710 /// gamut_conversion_matrix: mat3x3<f32>, // 16 48 64
2711 /// src_tf: NagaExternalTextureTransferFn, // 4 16 112
2712 /// dst_tf: NagaExternalTextureTransferFn, // 4 16 128
2713 /// sample_transform: mat3x2<f32>, // 8 24 144
2714 /// load_transform: mat3x2<f32>, // 8 24 168
2715 /// size: vec2<u32>, // 8 8 192
2716 /// num_planes: u32, // 4 4 200
2717 /// } // whole struct: 16 208
2718 /// ```
2719 ///
2720 /// Call [`Module::generate_external_texture_types`] to populate this if
2721 /// needed.
2722 pub external_texture_params: Option<Handle<Type>>,
2723
2724 /// Struct describing a gamma encoding transfer function. Member of
2725 /// `NagaExternalTextureParams`, describing how the backend should perform
2726 /// color space conversion when sampling from [`ImageClass::External`]
2727 /// textures.
2728 ///
2729 /// In WGSL, this type would be:
2730 ///
2731 /// ```ignore
2732 /// struct NagaExternalTextureTransferFn { // align size offset
2733 /// a: f32, // 4 4 0
2734 /// b: f32, // 4 4 4
2735 /// g: f32, // 4 4 8
2736 /// k: f32, // 4 4 12
2737 /// } // whole struct: 4 16
2738 /// ```
2739 ///
2740 /// Call [`Module::generate_external_texture_types`] to populate this if
2741 /// needed.
2742 pub external_texture_transfer_function: Option<Handle<Type>>,
2743
2744 /// Types for predeclared wgsl types instantiated on demand.
2745 ///
2746 /// Call [`Module::generate_predeclared_type`] to populate this if
2747 /// needed and return the handle.
2748 pub predeclared_types: FastIndexMap<PredeclaredType, Handle<Type>>,
2749}
2750
2751bitflags::bitflags! {
2752 /// Ray flags used when casting rays.
2753 /// Matching vulkan constants can be found in
2754 /// https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/KHR/ray_common/ray_flags_section.txt
2755 #[cfg_attr(feature = "serialize", derive(Serialize))]
2756 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
2757 #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2758 #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
2759 pub struct RayFlag: u32 {
2760 /// Force all intersections to be treated as opaque.
2761 const FORCE_OPAQUE = 0x1;
2762 /// Force all intersections to be treated as non-opaque.
2763 const FORCE_NO_OPAQUE = 0x2;
2764 /// Stop traversal after the first hit.
2765 const TERMINATE_ON_FIRST_HIT = 0x4;
2766 /// Don't execute the closest hit shader.
2767 const SKIP_CLOSEST_HIT_SHADER = 0x8;
2768 /// Cull back facing geometry.
2769 const CULL_BACK_FACING = 0x10;
2770 /// Cull front facing geometry.
2771 const CULL_FRONT_FACING = 0x20;
2772 /// Cull opaque geometry.
2773 const CULL_OPAQUE = 0x40;
2774 /// Cull non-opaque geometry.
2775 const CULL_NO_OPAQUE = 0x80;
2776 /// Skip triangular geometry.
2777 const SKIP_TRIANGLES = 0x100;
2778 /// Skip axis-aligned bounding boxes.
2779 const SKIP_AABBS = 0x200;
2780 }
2781}
2782
2783/// Type of a ray query intersection.
2784/// Matching vulkan constants can be found in
2785/// <https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/KHR/SPV_KHR_ray_query.asciidoc>
2786/// but the actual values are different for candidate intersections.
2787#[cfg_attr(feature = "serialize", derive(Serialize))]
2788#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2789#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2790#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
2791pub enum RayQueryIntersection {
2792 /// No intersection found.
2793 /// Matches `RayQueryCommittedIntersectionNoneKHR`.
2794 #[default]
2795 None = 0,
2796 /// Intersecting with triangles.
2797 /// Matches `RayQueryCommittedIntersectionTriangleKHR` and `RayQueryCandidateIntersectionTriangleKHR`.
2798 Triangle = 1,
2799 /// Intersecting with generated primitives.
2800 /// Matches `RayQueryCommittedIntersectionGeneratedKHR`.
2801 Generated = 2,
2802 /// Intersecting with Axis Aligned Bounding Boxes.
2803 /// Matches `RayQueryCandidateIntersectionAABBKHR`.
2804 Aabb = 3,
2805}
2806
2807/// Doc comments preceding items.
2808///
2809/// These can be used to generate automated documentation,
2810/// IDE hover information or translate shaders with their context comments.
2811#[derive(Debug, Default, Clone)]
2812#[cfg_attr(feature = "serialize", derive(Serialize))]
2813#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2814#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2815pub struct DocComments {
2816 pub types: FastIndexMap<Handle<Type>, Vec<String>>,
2817 // The key is:
2818 // - key.0: the handle to the Struct
2819 // - key.1: the index of the `StructMember`.
2820 pub struct_members: FastIndexMap<(Handle<Type>, usize), Vec<String>>,
2821 pub entry_points: FastIndexMap<usize, Vec<String>>,
2822 pub functions: FastIndexMap<Handle<Function>, Vec<String>>,
2823 pub constants: FastIndexMap<Handle<Constant>, Vec<String>>,
2824 pub global_variables: FastIndexMap<Handle<GlobalVariable>, Vec<String>>,
2825 // Top level comments, appearing before any space.
2826 pub module: Vec<String>,
2827}
2828
2829/// The output topology for a mesh shader. Note that mesh shaders don't allow things like triangle-strips.
2830#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2831#[cfg_attr(feature = "serialize", derive(Serialize))]
2832#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2833#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2834pub enum MeshOutputTopology {
2835 /// Outputs individual vertices to be rendered as points.
2836 Points,
2837 /// Outputs groups of 2 vertices to be renderedas lines .
2838 Lines,
2839 /// Outputs groups of 3 vertices to be rendered as triangles.
2840 Triangles,
2841}
2842
2843/// Information specific to mesh shader entry points.
2844#[derive(Debug, Clone, PartialEq, Eq)]
2845#[cfg_attr(feature = "serialize", derive(Serialize))]
2846#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2847#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2848#[allow(dead_code)]
2849pub struct MeshStageInfo {
2850 /// The type of primitive outputted.
2851 pub topology: MeshOutputTopology,
2852 /// The maximum number of vertices a mesh shader may output.
2853 pub max_vertices: u32,
2854 /// If pipeline constants are used, the expressions that override `max_vertices`
2855 pub max_vertices_override: Option<Handle<Expression>>,
2856 /// The maximum number of primitives a mesh shader may output.
2857 pub max_primitives: u32,
2858 /// If pipeline constants are used, the expressions that override `max_primitives`
2859 pub max_primitives_override: Option<Handle<Expression>>,
2860 /// The type used by vertex outputs, i.e. what is passed to `setVertex`.
2861 pub vertex_output_type: Handle<Type>,
2862 /// The type used by primitive outputs, i.e. what is passed to `setPrimitive`.
2863 pub primitive_output_type: Handle<Type>,
2864 /// The global variable holding the outputted vertices, primitives, and counts
2865 pub output_variable: Handle<GlobalVariable>,
2866}
2867
2868/// Ray tracing pipeline intrinsics
2869#[derive(Debug, Clone, Copy)]
2870#[cfg_attr(feature = "serialize", derive(Serialize))]
2871#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2872#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2873pub enum RayPipelineFunction {
2874 /// Traces a ray through the given acceleration structure
2875 TraceRay {
2876 /// The acceleration structure within which this ray should search for hits.
2877 ///
2878 /// The expression must be an [`AccelerationStructure`].
2879 ///
2880 /// [`AccelerationStructure`]: TypeInner::AccelerationStructure
2881 acceleration_structure: Handle<Expression>,
2882
2883 #[allow(rustdoc::private_intra_doc_links)]
2884 /// A struct of detailed parameters for the ray query.
2885 ///
2886 /// This expression should have the struct type given in
2887 /// [`SpecialTypes::ray_desc`]. This is available in the WGSL
2888 /// front end as the `RayDesc` type.
2889 descriptor: Handle<Expression>,
2890
2891 /// A pointer in the ray_payload or incoming_ray_payload address spaces
2892 payload: Handle<Expression>,
2893 // Do we want miss index? What about sbt offset and sbt stride (could be hard to validate)?
2894 // https://github.com/gfx-rs/wgpu/issues/8894
2895 },
2896
2897 /// Reorder the invocations in the ray generation shader according to a
2898 /// user-supplied hint.
2899 ///
2900 /// Only valid in the [`RayGeneration`] stage.
2901 ///
2902 /// [`RayGeneration`]: ShaderStage::RayGeneration
2903 ReorderThread {
2904 /// The value to reorder by. Must be a [`U32`] scalar.
2905 ///
2906 /// [`U32`]: Scalar::U32
2907 hint: Handle<Expression>,
2908
2909 /// How many of the low bits of `hint` are significant. Must be a
2910 /// [`U32`] scalar. Values greater than 32 are undefined behavior.
2911 ///
2912 /// [`U32`]: Scalar::U32
2913 bits: Handle<Expression>,
2914 },
2915}
2916
2917/// An operation that a [`HitObject` statement] applies to its [`hit_object`] operand.
2918///
2919/// [`HitObject` statement]: Statement::HitObject
2920/// [`hit_object`]: Statement::HitObject::hit_object
2921#[derive(Clone, Copy, Debug)]
2922#[cfg_attr(feature = "serialize", derive(Serialize))]
2923#[cfg_attr(feature = "deserialize", derive(Deserialize))]
2924#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
2925pub enum HitObjectFunction {
2926 /// Trace a ray, recording the result in the hit object without executing
2927 /// any closest hit or miss shaders.
2928 TraceRay {
2929 /// The acceleration structure within which this ray should search for hits.
2930 ///
2931 /// The expression must be an [`AccelerationStructure`].
2932 ///
2933 /// [`AccelerationStructure`]: TypeInner::AccelerationStructure
2934 acceleration_structure: Handle<Expression>,
2935
2936 #[allow(rustdoc::private_intra_doc_links)]
2937 /// A struct of detailed parameters for the ray.
2938 ///
2939 /// This expression should have the struct type given in
2940 /// [`SpecialTypes::ray_desc`]. This is available in the WGSL
2941 /// front end as the `RayDesc` type.
2942 descriptor: Handle<Expression>,
2943
2944 /// A pointer in the `ray_payload` or `incoming_ray_payload` address spaces.
2945 payload: Handle<Expression>,
2946 },
2947
2948 /// Record a miss in the hit object, without tracing a ray.
2949 ///
2950 /// The `cull_mask` of the descriptor is ignored, and the miss index is
2951 /// always zero.
2952 RecordMiss {
2953 #[allow(rustdoc::private_intra_doc_links)]
2954 /// A struct of detailed parameters describing the recorded ray.
2955 ///
2956 /// This expression should have the struct type given in
2957 /// [`SpecialTypes::ray_desc`]. This is available in the WGSL
2958 /// front end as the `RayDesc` type.
2959 descriptor: Handle<Expression>,
2960 },
2961
2962 /// Record the committed intersection of a ray query in the hit object.
2963 ///
2964 /// If the ray query's committed intersection is a hit, the hit object
2965 /// records that hit. The shader binding table record used for a hit is
2966 /// chosen exactly as a [`TraceRay`] would choose it: the shader binding
2967 /// table offset and stride are zero, so the hit group is the intersected
2968 /// instance's shader binding table record offset. For a triangle hit, the
2969 /// hit kind and barycentric attributes come from the ray query. Ray queries
2970 /// carry no hit kind or attributes for procedural (AABB) hits, so those are
2971 /// recorded with zeroed attributes and an unspecified hit kind. As a
2972 /// result, a [`HitObjectQuery::Intersection`] of such a hit can report it
2973 /// as a triangle hit, with an incorrect `front_face` and barycentrics.
2974 ///
2975 /// If the ray query has no committed intersection, the hit object records
2976 /// a miss along the ray the query was initialized with, with a miss index
2977 /// of zero, exactly as a [`TraceRay`] that missed would have.
2978 ///
2979 /// If the ray query has not finished traversal, the hit object is recorded
2980 /// as empty instead. A [`RayQueryFunction::Terminate`] does not finish
2981 /// traversal.
2982 ///
2983 /// [`TraceRay`]: HitObjectFunction::TraceRay
2984 RecordFromQuery {
2985 /// The ray query whose committed intersection should be recorded.
2986 ///
2987 /// Like [`Statement::RayQuery::query`], this must be a
2988 /// [`LocalVariable`] expression whose type is [`TypeInner::RayQuery`].
2989 ///
2990 /// [`LocalVariable`]: Expression::LocalVariable
2991 query: Handle<Expression>,
2992 },
2993
2994 /// Record that the hit object is empty: neither a hit nor a miss.
2995 ///
2996 /// An empty hit object does not run any shader when passed to
2997 /// [`ExecuteShader`].
2998 ///
2999 /// [`ExecuteShader`]: HitObjectFunction::ExecuteShader
3000 RecordEmpty,
3001
3002 /// Execute the closest hit or miss shader recorded in the hit object.
3003 ExecuteShader {
3004 /// A pointer in the `ray_payload` or `incoming_ray_payload` address spaces.
3005 payload: Handle<Expression>,
3006 },
3007
3008 /// Reorder invocations by the contents of the hit object, optionally
3009 /// combined with a user-supplied hint.
3010 ///
3011 /// Only valid in the [`RayGeneration`] stage.
3012 ///
3013 /// [`RayGeneration`]: ShaderStage::RayGeneration
3014 Reorder {
3015 /// An extra user hint to reorder by, in addition to the hit object.
3016 hint: Option<ReorderHint>,
3017 },
3018}
3019
3020/// A user-supplied hint for [`HitObjectFunction::Reorder`].
3021#[derive(Clone, Copy, Debug)]
3022#[cfg_attr(feature = "serialize", derive(Serialize))]
3023#[cfg_attr(feature = "deserialize", derive(Deserialize))]
3024#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
3025pub struct ReorderHint {
3026 /// The value to reorder by. Must be a [`U32`] scalar.
3027 ///
3028 /// [`U32`]: Scalar::U32
3029 pub hint: Handle<Expression>,
3030
3031 /// How many of the low bits of `hint` are significant. Must be a [`U32`]
3032 /// scalar. Values greater than 32 are undefined behavior.
3033 ///
3034 /// [`U32`]: Scalar::U32
3035 pub bits: Handle<Expression>,
3036}
3037
3038/// A property of a [`HitObject`] retrieved by an [`Expression::HitObjectQuery`].
3039///
3040/// [`HitObject`]: TypeInner::HitObject
3041#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
3042#[cfg_attr(feature = "serialize", derive(Serialize))]
3043#[cfg_attr(feature = "deserialize", derive(Deserialize))]
3044#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
3045pub enum HitObjectQuery {
3046 /// Whether the hit object is empty. Returns a [`Bool`] scalar.
3047 ///
3048 /// [`Bool`]: ScalarKind::Bool
3049 IsEmpty,
3050
3051 /// Whether the hit object represents a hit. Returns a [`Bool`] scalar.
3052 ///
3053 /// [`Bool`]: ScalarKind::Bool
3054 IsHit,
3055
3056 /// Whether the hit object represents a miss. Returns a [`Bool`] scalar.
3057 ///
3058 /// [`Bool`]: ScalarKind::Bool
3059 IsMiss,
3060
3061 #[allow(rustdoc::private_intra_doc_links)]
3062 /// The intersection recorded in the hit object.
3063 ///
3064 /// Returns a [`SpecialTypes::ray_intersection`] struct. For a miss or an
3065 /// empty hit object, all members are zero, so `kind` is
3066 /// [`RayQueryIntersection::None`].
3067 Intersection,
3068}
3069
3070/// Shader module.
3071///
3072/// A module is a set of constants, global variables and functions, as well as
3073/// the types required to define them.
3074///
3075/// Some functions are marked as entry points, to be used in a certain shader stage.
3076///
3077/// To create a new module, use the `Default` implementation.
3078/// Alternatively, you can load an existing shader using one of the [available front ends].
3079///
3080/// When finished, you can export modules using one of the [available backends].
3081///
3082/// ## Module arenas
3083///
3084/// Most module contents are stored in [`Arena`]s. In a valid module, arena
3085/// elements only refer to prior arena elements. That is, whenever an element in
3086/// some `Arena<T>` contains a `Handle<T>` referring to another element the same
3087/// arena, the handle's referent always precedes the element containing the
3088/// handle.
3089///
3090/// The elements of [`Module::types`] may refer to [`Expression`]s in
3091/// [`Module::global_expressions`], and those expressions may in turn refer back
3092/// to [`Type`]s in [`Module::types`]. In a valid module, there exists an order
3093/// in which all types and global expressions can be visited such that:
3094///
3095/// - types and expressions are visited in the order in which they appear in
3096/// their arenas, and
3097///
3098/// - every element refers only to previously visited elements.
3099///
3100/// This implies that the graph of types and global expressions is acyclic.
3101/// (However, it is a stronger condition: there are cycle-free arrangements of
3102/// types and expressions for which an order like the one described above does
3103/// not exist. Modules arranged in such a way are not valid.)
3104///
3105/// [available front ends]: crate::front
3106/// [available backends]: crate::back
3107#[derive(Debug, Default, Clone)]
3108#[cfg_attr(feature = "serialize", derive(Serialize))]
3109#[cfg_attr(feature = "deserialize", derive(Deserialize))]
3110#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
3111pub struct Module {
3112 /// Arena for the types defined in this module.
3113 ///
3114 /// See the [`Module`] docs for more details about this field.
3115 pub types: UniqueArena<Type>,
3116 /// Dictionary of special type handles.
3117 pub special_types: SpecialTypes,
3118 /// Arena for the constants defined in this module.
3119 pub constants: Arena<Constant>,
3120 /// Arena for the pipeline-overridable constants defined in this module.
3121 pub overrides: Arena<Override>,
3122 /// Arena for the global variables defined in this module.
3123 pub global_variables: Arena<GlobalVariable>,
3124 /// [Constant expressions] and [override expressions] used by this module.
3125 ///
3126 /// If an expression is in this arena, then its subexpressions are in this
3127 /// arena too. In other words, every `Handle<Expression>` in this arena
3128 /// refers to an [`Expression`] in this arena too.
3129 ///
3130 /// See the [`Module`] docs for more details about this field.
3131 ///
3132 /// [Constant expressions]: index.html#constant-expressions
3133 /// [override expressions]: index.html#override-expressions
3134 pub global_expressions: Arena<Expression>,
3135 /// Arena for the functions defined in this module.
3136 ///
3137 /// Each function must appear in this arena strictly before all its callers.
3138 /// Recursion is not supported.
3139 pub functions: Arena<Function>,
3140 /// Entry points.
3141 pub entry_points: Vec<EntryPoint>,
3142 /// Arena for all diagnostic filter rules parsed in this module, including those in functions
3143 /// and statements.
3144 ///
3145 /// This arena contains elements of a _tree_ of diagnostic filter rules. When nodes are built
3146 /// by a front-end, they refer to a parent scope
3147 pub diagnostic_filters: Arena<DiagnosticFilterNode>,
3148 /// The leaf of all diagnostic filter rules tree parsed from directives in this module.
3149 ///
3150 /// In WGSL, this corresponds to `diagnostic(…);` directives.
3151 ///
3152 /// See [`DiagnosticFilterNode`] for details on how the tree is represented and used in
3153 /// validation.
3154 pub diagnostic_filter_leaf: Option<Handle<DiagnosticFilterNode>>,
3155 /// Doc comments.
3156 pub doc_comments: Option<Box<DocComments>>,
3157}