Debian Codegraph @

third_party/rust/naga/src/valid/analyzer.rs

raw
1 //! Module analyzer.
2 //!
3 //! Figures out the following properties:
4 //! - control flow uniformity
5 //! - texture/sampler pairs
6 //! - expression reference counts
7
8 use alloc::{boxed::Box, vec};
9 use core::ops;
10
11 use super::{ExpressionError, FunctionError, ModuleInfo, ShaderStages, ValidationFlags};
12 use crate::diagnostic_filter::{DiagnosticFilterNode, StandardFilterableTriggeringRule};
13 use crate::span::{AddSpan as _, WithSpan};
14 use crate::{
15 arena::{Arena, Handle},
16 proc::{ResolveContext, TypeResolution},
17 };
18
19 pub type NonUniformResult = Option<Handle<crate::Expression>>;
20
21 const DISABLE_UNIFORMITY_REQ_FOR_FRAGMENT_STAGE: bool = true;
22
23 bitflags::bitflags! {
24 /// Kinds of expressions that require uniform control flow.
25 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
26 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
27 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
28 pub struct UniformityRequirements: u8 {
29 const WORK_GROUP_BARRIER = 0x1;
30 const DERIVATIVE = if DISABLE_UNIFORMITY_REQ_FOR_FRAGMENT_STAGE { 0 } else { 0x2 };
31 const IMPLICIT_LEVEL = if DISABLE_UNIFORMITY_REQ_FOR_FRAGMENT_STAGE { 0 } else { 0x4 };
32 }
33 }
34
35 /// Uniform control flow characteristics.
36 #[derive(Clone, Debug)]
37 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
38 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
39 #[cfg_attr(test, derive(PartialEq))]
40 pub struct Uniformity {
41 /// A child expression with non-uniform result.
42 ///
43 /// This means, when the relevant invocations are scheduled on a compute unit,
44 /// they have to use vector registers to store an individual value
45 /// per invocation.
46 ///
47 /// Whenever the control flow is conditioned on such value,
48 /// the hardware needs to keep track of the mask of invocations,
49 /// and process all branches of the control flow.
50 ///
51 /// Any operations that depend on non-uniform results also produce non-uniform.
52 pub non_uniform_result: NonUniformResult,
53 /// If this expression requires uniform control flow, store the reason here.
54 pub requirements: UniformityRequirements,
55 }
56
57 impl Uniformity {
58 const fn new() -> Self {
59 Uniformity {
60 non_uniform_result: None,
61 requirements: UniformityRequirements::empty(),
62 }
63 }
64 }
65
66 bitflags::bitflags! {
67 #[derive(Clone, Copy, Debug, PartialEq)]
68 struct ExitFlags: u8 {
69 /// Control flow may return from the function, which makes all the
70 /// subsequent statements within the current function (only!)
71 /// to be executed in a non-uniform control flow.
72 const MAY_RETURN = 0x1;
73 /// Control flow may be killed. Anything after [`Statement::Kill`] is
74 /// considered inside non-uniform context.
75 ///
76 /// [`Statement::Kill`]: crate::Statement::Kill
77 const MAY_KILL = 0x2;
78 }
79 }
80
81 /// Uniformity characteristics of a function.
82 #[cfg_attr(test, derive(Debug, PartialEq))]
83 struct FunctionUniformity {
84 result: Uniformity,
85 exit: ExitFlags,
86 }
87
88 impl ops::BitOr for FunctionUniformity {
89 type Output = Self;
90 fn bitor(self, other: Self) -> Self {
91 FunctionUniformity {
92 result: Uniformity {
93 non_uniform_result: self
94 .result
95 .non_uniform_result
96 .or(other.result.non_uniform_result),
97 requirements: self.result.requirements | other.result.requirements,
98 },
99 exit: self.exit | other.exit,
100 }
101 }
102 }
103
104 impl FunctionUniformity {
105 const fn new() -> Self {
106 FunctionUniformity {
107 result: Uniformity::new(),
108 exit: ExitFlags::empty(),
109 }
110 }
111
112 /// Returns a disruptor based on the stored exit flags, if any.
113 const fn exit_disruptor(&self) -> Option<UniformityDisruptor> {
114 if self.exit.contains(ExitFlags::MAY_RETURN) {
115 Some(UniformityDisruptor::Return)
116 } else if self.exit.contains(ExitFlags::MAY_KILL) {
117 Some(UniformityDisruptor::Discard)
118 } else {
119 None
120 }
121 }
122 }
123
124 bitflags::bitflags! {
125 /// Indicates how a global variable is used.
126 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
127 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
128 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
129 pub struct GlobalUse: u8 {
130 /// Data will be read from the variable.
131 const READ = 0x1;
132 /// Data will be written to the variable.
133 const WRITE = 0x2;
134 /// The information about the data is queried.
135 const QUERY = 0x4;
136 /// Atomic operations will be performed on the variable.
137 const ATOMIC = 0x8;
138 }
139 }
140
141 #[derive(Clone, Debug, Eq, Hash, PartialEq)]
142 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
143 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
144 pub struct SamplingKey {
145 pub image: Handle<crate::GlobalVariable>,
146 pub sampler: Handle<crate::GlobalVariable>,
147 }
148
149 #[derive(Clone, Debug)]
150 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
151 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
152 /// Information about an expression in a function body.
153 pub struct ExpressionInfo {
154 /// Whether this expression is uniform, and why.
155 ///
156 /// If this expression's value is not uniform, this is the handle
157 /// of the expression from which this one's non-uniformity
158 /// originates. Otherwise, this is `None`.
159 pub uniformity: Uniformity,
160
161 /// The number of direct references to this expression in statements and
162 /// other expressions.
163 ///
164 /// This is a _local_ reference count only, it may be non-zero for
165 /// expressions that are ultimately unused.
166 pub ref_count: usize,
167
168 /// The global variable into which this expression produces a pointer.
169 ///
170 /// This is `None` unless this expression is either a
171 /// [`GlobalVariable`], or an [`Access`] or [`AccessIndex`] that
172 /// ultimately refers to some part of a global.
173 ///
174 /// [`Load`] expressions applied to pointer-typed arguments could
175 /// refer to globals, but we leave this as `None` for them.
176 ///
177 /// [`GlobalVariable`]: crate::Expression::GlobalVariable
178 /// [`Access`]: crate::Expression::Access
179 /// [`AccessIndex`]: crate::Expression::AccessIndex
180 /// [`Load`]: crate::Expression::Load
181 assignable_global: Option<Handle<crate::GlobalVariable>>,
182
183 /// The type of this expression.
184 pub ty: TypeResolution,
185 }
186
187 impl ExpressionInfo {
188 const fn new() -> Self {
189 ExpressionInfo {
190 uniformity: Uniformity::new(),
191 ref_count: 0,
192 assignable_global: None,
193 // this doesn't matter at this point, will be overwritten
194 ty: TypeResolution::Value(crate::TypeInner::Scalar(crate::Scalar {
195 kind: crate::ScalarKind::Bool,
196 width: 0,
197 })),
198 }
199 }
200 }
201
202 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
203 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
204 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
205 enum GlobalOrArgument {
206 Global(Handle<crate::GlobalVariable>),
207 Argument(u32),
208 }
209
210 impl GlobalOrArgument {
211 fn from_expression(
212 expression_arena: &Arena<crate::Expression>,
213 expression: Handle<crate::Expression>,
214 ) -> Result<GlobalOrArgument, ExpressionError> {
215 Ok(match expression_arena[expression] {
216 crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var),
217 crate::Expression::FunctionArgument(i) => GlobalOrArgument::Argument(i),
218 crate::Expression::Access { base, .. }
219 | crate::Expression::AccessIndex { base, .. } => match expression_arena[base] {
220 crate::Expression::GlobalVariable(var) => GlobalOrArgument::Global(var),
221 _ => return Err(ExpressionError::ExpectedGlobalOrArgument),
222 },
223 _ => return Err(ExpressionError::ExpectedGlobalOrArgument),
224 })
225 }
226 }
227
228 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
229 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
230 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
231 struct Sampling {
232 image: GlobalOrArgument,
233 sampler: GlobalOrArgument,
234 }
235
236 #[derive(Debug, Clone)]
237 #[cfg_attr(feature = "serialize", derive(serde::Serialize))]
238 #[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
239 pub struct FunctionInfo {
240 /// Validation flags.
241 #[allow(dead_code)]
242 flags: ValidationFlags,
243 /// Set of shader stages where calling this function is valid.
244 pub available_stages: ShaderStages,
245 /// Uniformity characteristics.
246 pub uniformity: Uniformity,
247 /// Function may kill the invocation.
248 pub may_kill: bool,
249
250 /// All pairs of (texture, sampler) globals that may be used together in
251 /// sampling operations by this function and its callees. This includes
252 /// pairings that arise when this function passes textures and samplers as
253 /// arguments to its callees.
254 ///
255 /// This table does not include uses of textures and samplers passed as
256 /// arguments to this function itself, since we do not know which globals
257 /// those will be. However, this table *is* exhaustive when computed for an
258 /// entry point function: entry points never receive textures or samplers as
259 /// arguments, so all an entry point's sampling can be reported in terms of
260 /// globals.
261 ///
262 /// The GLSL back end uses this table to construct reflection info that
263 /// clients need to construct texture-combined sampler values.
264 pub sampling_set: crate::FastHashSet<SamplingKey>,
265
266 /// How this function and its callees use this module's globals.
267 ///
268 /// This is indexed by `Handle<GlobalVariable>` indices. However,
269 /// `FunctionInfo` implements `core::ops::Index<Handle<GlobalVariable>>`,
270 /// so you can simply index this struct with a global handle to retrieve
271 /// its usage information.
272 global_uses: Box<[GlobalUse]>,
273
274 /// Information about each expression in this function's body.
275 ///
276 /// This is indexed by `Handle<Expression>` indices. However, `FunctionInfo`
277 /// implements `core::ops::Index<Handle<Expression>>`, so you can simply
278 /// index this struct with an expression handle to retrieve its
279 /// `ExpressionInfo`.
280 expressions: Box<[ExpressionInfo]>,
281
282 /// All (texture, sampler) pairs that may be used together in sampling
283 /// operations by this function and its callees, whether they are accessed
284 /// as globals or passed as arguments.
285 ///
286 /// Participants are represented by [`GlobalVariable`] handles whenever
287 /// possible, and otherwise by indices of this function's arguments.
288 ///
289 /// When analyzing a function call, we combine this data about the callee
290 /// with the actual arguments being passed to produce the callers' own
291 /// `sampling_set` and `sampling` tables.
292 ///
293 /// [`GlobalVariable`]: crate::GlobalVariable
294 sampling: crate::FastHashSet<Sampling>,
295
296 /// Indicates that the function is using dual source blending.
297 pub dual_source_blending: bool,
298
299 /// The leaf of all module-wide diagnostic filter rules tree parsed from directives in this
300 /// module.
301 ///
302 /// See [`DiagnosticFilterNode`] for details on how the tree is represented and used in
303 /// validation.
304 diagnostic_filter_leaf: Option<Handle<DiagnosticFilterNode>>,
305 }
306
307 impl FunctionInfo {
308 pub const fn global_variable_count(&self) -> usize {
309 self.global_uses.len()
310 }
311 pub const fn expression_count(&self) -> usize {
312 self.expressions.len()
313 }
314 pub fn dominates_global_use(&self, other: &Self) -> bool {
315 for (self_global_uses, other_global_uses) in
316 self.global_uses.iter().zip(other.global_uses.iter())
317 {
318 if !self_global_uses.contains(*other_global_uses) {
319 return false;
320 }
321 }
322 true
323 }
324 }
325
326 impl ops::Index<Handle<crate::GlobalVariable>> for FunctionInfo {
327 type Output = GlobalUse;
328 fn index(&self, handle: Handle<crate::GlobalVariable>) -> &GlobalUse {
329 &self.global_uses[handle.index()]
330 }
331 }
332
333 impl ops::Index<Handle<crate::Expression>> for FunctionInfo {
334 type Output = ExpressionInfo;
335 fn index(&self, handle: Handle<crate::Expression>) -> &ExpressionInfo {
336 &self.expressions[handle.index()]
337 }
338 }
339
340 /// Disruptor of the uniform control flow.
341 #[derive(Clone, Copy, Debug, thiserror::Error)]
342 #[cfg_attr(test, derive(PartialEq))]
343 pub enum UniformityDisruptor {
344 #[error("Expression {0:?} produced non-uniform result, and control flow depends on it")]
345 Expression(Handle<crate::Expression>),
346 #[error("There is a Return earlier in the control flow of the function")]
347 Return,
348 #[error("There is a Discard earlier in the entry point across all called functions")]
349 Discard,
350 }
351
352 impl FunctionInfo {
353 /// Record a use of `expr` of the sort given by `global_use`.
354 ///
355 /// Bump `expr`'s reference count, and return its uniformity.
356 ///
357 /// If `expr` is a pointer to a global variable, or some part of
358 /// a global variable, add `global_use` to that global's set of
359 /// uses.
360 #[must_use]
361 fn add_ref_impl(
362 &mut self,
363 expr: Handle<crate::Expression>,
364 global_use: GlobalUse,
365 ) -> NonUniformResult {
366 let info = &mut self.expressions[expr.index()];
367 info.ref_count += 1;
368 // Record usage if this expression may access a global
369 if let Some(global) = info.assignable_global {
370 self.global_uses[global.index()] |= global_use;
371 }
372 info.uniformity.non_uniform_result
373 }
374
375 /// Record a use of `expr` for its value.
376 ///
377 /// This is used for almost all expression references. Anything
378 /// that writes to the value `expr` points to, or otherwise wants
379 /// contribute flags other than `GlobalUse::READ`, should use
380 /// `add_ref_impl` directly.
381 #[must_use]
382 fn add_ref(&mut self, expr: Handle<crate::Expression>) -> NonUniformResult {
383 self.add_ref_impl(expr, GlobalUse::READ)
384 }
385
386 /// Record a use of `expr`, and indicate which global variable it
387 /// refers to, if any.
388 ///
389 /// Bump `expr`'s reference count, and return its uniformity.
390 ///
391 /// If `expr` is a pointer to a global variable, or some part
392 /// thereof, store that global in `*assignable_global`. Leave the
393 /// global's uses unchanged.
394 ///
395 /// This is used to determine the [`assignable_global`] for
396 /// [`Access`] and [`AccessIndex`] expressions that ultimately
397 /// refer to a global variable. Those expressions don't contribute
398 /// any usage to the global themselves; that depends on how other
399 /// expressions use them.
400 ///
401 /// [`assignable_global`]: ExpressionInfo::assignable_global
402 /// [`Access`]: crate::Expression::Access
403 /// [`AccessIndex`]: crate::Expression::AccessIndex
404 #[must_use]
405 fn add_assignable_ref(
406 &mut self,
407 expr: Handle<crate::Expression>,
408 assignable_global: &mut Option<Handle<crate::GlobalVariable>>,
409 ) -> NonUniformResult {
410 let info = &mut self.expressions[expr.index()];
411 info.ref_count += 1;
412 // propagate the assignable global up the chain, till it either hits
413 // a value-type expression, or the assignment statement.
414 if let Some(global) = info.assignable_global {
415 if let Some(_old) = assignable_global.replace(global) {
416 unreachable!()
417 }
418 }
419 info.uniformity.non_uniform_result
420 }
421
422 /// Inherit information from a called function.
423 fn process_call(
424 &mut self,
425 callee: &Self,
426 arguments: &[Handle<crate::Expression>],
427 expression_arena: &Arena<crate::Expression>,
428 ) -> Result<FunctionUniformity, WithSpan<FunctionError>> {
429 self.sampling_set
430 .extend(callee.sampling_set.iter().cloned());
431 for sampling in callee.sampling.iter() {
432 // If the callee was passed the texture or sampler as an argument,
433 // we may now be able to determine which globals those referred to.
434 let image_storage = match sampling.image {
435 GlobalOrArgument::Global(var) => GlobalOrArgument::Global(var),
436 GlobalOrArgument::Argument(i) => {
437 let Some(handle) = arguments.get(i as usize).cloned() else {
438 // Argument count mismatch, will be reported later by validate_call
439 break;
440 };
441 GlobalOrArgument::from_expression(expression_arena, handle).map_err(
442 |source| {
443 FunctionError::Expression { handle, source }
444 .with_span_handle(handle, expression_arena)
445 },
446 )?
447 }
448 };
449
450 let sampler_storage = match sampling.sampler {
451 GlobalOrArgument::Global(var) => GlobalOrArgument::Global(var),
452 GlobalOrArgument::Argument(i) => {
453 let Some(handle) = arguments.get(i as usize).cloned() else {
454 // Argument count mismatch, will be reported later by validate_call
455 break;
456 };
457 GlobalOrArgument::from_expression(expression_arena, handle).map_err(
458 |source| {
459 FunctionError::Expression { handle, source }
460 .with_span_handle(handle, expression_arena)
461 },
462 )?
463 }
464 };
465
466 // If we've managed to pin both the image and sampler down to
467 // specific globals, record that in our `sampling_set`. Otherwise,
468 // record as much as we do know in our own `sampling` table, for our
469 // callers to sort out.
470 match (image_storage, sampler_storage) {
471 (GlobalOrArgument::Global(image), GlobalOrArgument::Global(sampler)) => {
472 self.sampling_set.insert(SamplingKey { image, sampler });
473 }
474 (image, sampler) => {
475 self.sampling.insert(Sampling { image, sampler });
476 }
477 }
478 }
479
480 // Inherit global use from our callees.
481 for (mine, other) in self.global_uses.iter_mut().zip(callee.global_uses.iter()) {
482 *mine |= *other;
483 }
484
485 Ok(FunctionUniformity {
486 result: callee.uniformity.clone(),
487 exit: if callee.may_kill {
488 ExitFlags::MAY_KILL
489 } else {
490 ExitFlags::empty()
491 },
492 })
493 }
494
495 /// Compute the [`ExpressionInfo`] for `handle`.
496 ///
497 /// Replace the dummy entry in [`self.expressions`] for `handle`
498 /// with a real `ExpressionInfo` value describing that expression.
499 ///
500 /// This function is called as part of a forward sweep through the
501 /// arena, so we can assume that all earlier expressions in the
502 /// arena already have valid info. Since expressions only depend
503 /// on earlier expressions, this includes all our subexpressions.
504 ///
505 /// Adjust the reference counts on all expressions we use.
506 ///
507 /// Also populate the [`sampling_set`], [`sampling`] and
508 /// [`global_uses`] fields of `self`.
509 ///
510 /// [`self.expressions`]: FunctionInfo::expressions
511 /// [`sampling_set`]: FunctionInfo::sampling_set
512 /// [`sampling`]: FunctionInfo::sampling
513 /// [`global_uses`]: FunctionInfo::global_uses
514 #[allow(clippy::or_fun_call)]
515 fn process_expression(
516 &mut self,
517 handle: Handle<crate::Expression>,
518 expression_arena: &Arena<crate::Expression>,
519 other_functions: &[FunctionInfo],
520 resolve_context: &ResolveContext,
521 capabilities: super::Capabilities,
522 ) -> Result<(), ExpressionError> {
523 use crate::{Expression as E, SampleLevel as Sl};
524
525 let expression = &expression_arena[handle];
526 let mut assignable_global = None;
527 let uniformity = match *expression {
528 E::Access { base, index } => {
529 let base_ty = self[base].ty.inner_with(resolve_context.types);
530
531 // build up the caps needed if this is indexed non-uniformly
532 let mut needed_caps = super::Capabilities::empty();
533 let is_binding_array = match *base_ty {
534 crate::TypeInner::BindingArray {
535 base: array_element_ty_handle,
536 ..
537 } => {
538 // these are nasty aliases, but these idents are too long and break rustfmt
539 let sto = super::Capabilities::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING;
540 let uni = super::Capabilities::UNIFORM_BUFFER_ARRAY_NON_UNIFORM_INDEXING;
541 let st_sb = super::Capabilities::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING;
542 let sampler = super::Capabilities::SAMPLER_NON_UNIFORM_INDEXING;
543
544 // We're a binding array, so lets use the type of _what_ we are array of to determine if we can non-uniformly index it.
545 let array_element_ty =
546 &resolve_context.types[array_element_ty_handle].inner;
547
548 needed_caps |= match *array_element_ty {
549 // If we're an image, use the appropriate limit.
550 crate::TypeInner::Image { class, .. } => match class {
551 crate::ImageClass::Storage { .. } => sto,
552 _ => st_sb,
553 },
554 crate::TypeInner::Sampler { .. } => sampler,
555 // If we're anything but an image, assume we're a buffer and use the address space.
556 _ => {
557 if let E::GlobalVariable(global_handle) = expression_arena[base] {
558 let global = &resolve_context.global_vars[global_handle];
559 match global.space {
560 crate::AddressSpace::Uniform => uni,
561 crate::AddressSpace::Storage { .. } => st_sb,
562 _ => unreachable!(),
563 }
564 } else {
565 unreachable!()
566 }
567 }
568 };
569
570 true
571 }
572 _ => false,
573 };
574
575 if self[index].uniformity.non_uniform_result.is_some()
576 && !capabilities.contains(needed_caps)
577 && is_binding_array
578 {
579 return Err(ExpressionError::MissingCapabilities(needed_caps));
580 }
581
582 Uniformity {
583 non_uniform_result: self
584 .add_assignable_ref(base, &mut assignable_global)
585 .or(self.add_ref(index)),
586 requirements: UniformityRequirements::empty(),
587 }
588 }
589 E::AccessIndex { base, .. } => Uniformity {
590 non_uniform_result: self.add_assignable_ref(base, &mut assignable_global),
591 requirements: UniformityRequirements::empty(),
592 },
593 // always uniform
594 E::Splat { size: _, value } => Uniformity {
595 non_uniform_result: self.add_ref(value),
596 requirements: UniformityRequirements::empty(),
597 },
598 E::Swizzle { vector, .. } => Uniformity {
599 non_uniform_result: self.add_ref(vector),
600 requirements: UniformityRequirements::empty(),
601 },
602 E::Literal(_) | E::Constant(_) | E::Override(_) | E::ZeroValue(_) => Uniformity::new(),
603 E::Compose { ref components, .. } => {
604 let non_uniform_result = components
605 .iter()
606 .fold(None, |nur, &comp| nur.or(self.add_ref(comp)));
607 Uniformity {
608 non_uniform_result,
609 requirements: UniformityRequirements::empty(),
610 }
611 }
612 // depends on the builtin
613 E::FunctionArgument(index) => {
614 let arg = &resolve_context.arguments[index as usize];
615 let uniform = match arg.binding {
616 Some(crate::Binding::BuiltIn(
617 // per-work-group built-ins are uniform
618 crate::BuiltIn::WorkGroupId
619 | crate::BuiltIn::WorkGroupSize
620 | crate::BuiltIn::NumWorkGroups,
621 )) => true,
622 _ => false,
623 };
624 Uniformity {
625 non_uniform_result: if uniform { None } else { Some(handle) },
626 requirements: UniformityRequirements::empty(),
627 }
628 }
629 // depends on the address space
630 E::GlobalVariable(gh) => {
631 use crate::AddressSpace as As;
632 assignable_global = Some(gh);
633 let var = &resolve_context.global_vars[gh];
634 let uniform = match var.space {
635 // local data is non-uniform
636 As::Function | As::Private => false,
637 // workgroup memory is exclusively accessed by the group
638 As::WorkGroup => true,
639 // uniform data
640 As::Uniform | As::PushConstant => true,
641 // storage data is only uniform when read-only
642 As::Storage { access } => !access.contains(crate::StorageAccess::STORE),
643 As::Handle => false,
644 };
645 Uniformity {
646 non_uniform_result: if uniform { None } else { Some(handle) },
647 requirements: UniformityRequirements::empty(),
648 }
649 }
650 E::LocalVariable(_) => Uniformity {
651 non_uniform_result: Some(handle),
652 requirements: UniformityRequirements::empty(),
653 },
654 E::Load { pointer } => Uniformity {
655 non_uniform_result: self.add_ref(pointer),
656 requirements: UniformityRequirements::empty(),
657 },
658 E::ImageSample {
659 image,
660 sampler,
661 gather: _,
662 coordinate,
663 array_index,
664 offset,
665 level,
666 depth_ref,
667 } => {
668 let image_storage = GlobalOrArgument::from_expression(expression_arena, image)?;
669 let sampler_storage = GlobalOrArgument::from_expression(expression_arena, sampler)?;
670
671 match (image_storage, sampler_storage) {
672 (GlobalOrArgument::Global(image), GlobalOrArgument::Global(sampler)) => {
673 self.sampling_set.insert(SamplingKey { image, sampler });
674 }
675 _ => {
676 self.sampling.insert(Sampling {
677 image: image_storage,
678 sampler: sampler_storage,
679 });
680 }
681 }
682
683 // "nur" == "Non-Uniform Result"
684 let array_nur = array_index.and_then(|h| self.add_ref(h));
685 let level_nur = match level {
686 Sl::Auto | Sl::Zero => None,
687 Sl::Exact(h) | Sl::Bias(h) => self.add_ref(h),
688 Sl::Gradient { x, y } => self.add_ref(x).or(self.add_ref(y)),
689 };
690 let dref_nur = depth_ref.and_then(|h| self.add_ref(h));
691 let offset_nur = offset.and_then(|h| self.add_ref(h));
692 Uniformity {
693 non_uniform_result: self
694 .add_ref(image)
695 .or(self.add_ref(sampler))
696 .or(self.add_ref(coordinate))
697 .or(array_nur)
698 .or(level_nur)
699 .or(dref_nur)
700 .or(offset_nur),
701 requirements: if level.implicit_derivatives() {
702 UniformityRequirements::IMPLICIT_LEVEL
703 } else {
704 UniformityRequirements::empty()
705 },
706 }
707 }
708 E::ImageLoad {
709 image,
710 coordinate,
711 array_index,
712 sample,
713 level,
714 } => {
715 let array_nur = array_index.and_then(|h| self.add_ref(h));
716 let sample_nur = sample.and_then(|h| self.add_ref(h));
717 let level_nur = level.and_then(|h| self.add_ref(h));
718 Uniformity {
719 non_uniform_result: self
720 .add_ref(image)
721 .or(self.add_ref(coordinate))
722 .or(array_nur)
723 .or(sample_nur)
724 .or(level_nur),
725 requirements: UniformityRequirements::empty(),
726 }
727 }
728 E::ImageQuery { image, query } => {
729 let query_nur = match query {
730 crate::ImageQuery::Size { level: Some(h) } => self.add_ref(h),
731 _ => None,
732 };
733 Uniformity {
734 non_uniform_result: self.add_ref_impl(image, GlobalUse::QUERY).or(query_nur),
735 requirements: UniformityRequirements::empty(),
736 }
737 }
738 E::Unary { expr, .. } => Uniformity {
739 non_uniform_result: self.add_ref(expr),
740 requirements: UniformityRequirements::empty(),
741 },
742 E::Binary { left, right, .. } => Uniformity {
743 non_uniform_result: self.add_ref(left).or(self.add_ref(right)),
744 requirements: UniformityRequirements::empty(),
745 },
746 E::Select {
747 condition,
748 accept,
749 reject,
750 } => Uniformity {
751 non_uniform_result: self
752 .add_ref(condition)
753 .or(self.add_ref(accept))
754 .or(self.add_ref(reject)),
755 requirements: UniformityRequirements::empty(),
756 },
757 // explicit derivatives require uniform
758 E::Derivative { expr, .. } => Uniformity {
759 //Note: taking a derivative of a uniform doesn't make it non-uniform
760 non_uniform_result: self.add_ref(expr),
761 requirements: UniformityRequirements::DERIVATIVE,
762 },
763 E::Relational { argument, .. } => Uniformity {
764 non_uniform_result: self.add_ref(argument),
765 requirements: UniformityRequirements::empty(),
766 },
767 E::Math {
768 fun: _,
769 arg,
770 arg1,
771 arg2,
772 arg3,
773 } => {
774 let arg1_nur = arg1.and_then(|h| self.add_ref(h));
775 let arg2_nur = arg2.and_then(|h| self.add_ref(h));
776 let arg3_nur = arg3.and_then(|h| self.add_ref(h));
777 Uniformity {
778 non_uniform_result: self.add_ref(arg).or(arg1_nur).or(arg2_nur).or(arg3_nur),
779 requirements: UniformityRequirements::empty(),
780 }
781 }
782 E::As { expr, .. } => Uniformity {
783 non_uniform_result: self.add_ref(expr),
784 requirements: UniformityRequirements::empty(),
785 },
786 E::CallResult(function) => other_functions[function.index()].uniformity.clone(),
787 E::AtomicResult { .. } | E::RayQueryProceedResult => Uniformity {
788 non_uniform_result: Some(handle),
789 requirements: UniformityRequirements::empty(),
790 },
791 E::WorkGroupUniformLoadResult { .. } => Uniformity {
792 // The result of WorkGroupUniformLoad is always uniform by definition
793 non_uniform_result: None,
794 // The call is what cares about uniformity, not the expression
795 // This expression is never emitted, so this requirement should never be used anyway?
796 requirements: UniformityRequirements::empty(),
797 },
798 E::ArrayLength(expr) => Uniformity {
799 non_uniform_result: self.add_ref_impl(expr, GlobalUse::QUERY),
800 requirements: UniformityRequirements::empty(),
801 },
802 E::RayQueryGetIntersection {
803 query,
804 committed: _,
805 } => Uniformity {
806 non_uniform_result: self.add_ref(query),
807 requirements: UniformityRequirements::empty(),
808 },
809 E::SubgroupBallotResult => Uniformity {
810 non_uniform_result: Some(handle),
811 requirements: UniformityRequirements::empty(),
812 },
813 E::SubgroupOperationResult { .. } => Uniformity {
814 non_uniform_result: Some(handle),
815 requirements: UniformityRequirements::empty(),
816 },
817 E::RayQueryVertexPositions {
818 query,
819 committed: _,
820 } => Uniformity {
821 non_uniform_result: self.add_ref(query),
822 requirements: UniformityRequirements::empty(),
823 },
824 };
825
826 let ty = resolve_context.resolve(expression, |h| Ok(&self[h].ty))?;
827 self.expressions[handle.index()] = ExpressionInfo {
828 uniformity,
829 ref_count: 0,
830 assignable_global,
831 ty,
832 };
833 Ok(())
834 }
835
836 /// Analyzes the uniformity requirements of a block (as a sequence of statements).
837 /// Returns the uniformity characteristics at the *function* level, i.e.
838 /// whether or not the function requires to be called in uniform control flow,
839 /// and whether the produced result is not disrupting the control flow.
840 ///
841 /// The parent control flow is uniform if `disruptor.is_none()`.
842 ///
843 /// Returns a `NonUniformControlFlow` error if any of the expressions in the block
844 /// require uniformity, but the current flow is non-uniform.
845 #[allow(clippy::or_fun_call)]
846 fn process_block(
847 &mut self,
848 statements: &crate::Block,
849 other_functions: &[FunctionInfo],
850 mut disruptor: Option<UniformityDisruptor>,
851 expression_arena: &Arena<crate::Expression>,
852 diagnostic_filter_arena: &Arena<DiagnosticFilterNode>,
853 ) -> Result<FunctionUniformity, WithSpan<FunctionError>> {
854 use crate::Statement as S;
855
856 let mut combined_uniformity = FunctionUniformity::new();
857 for statement in statements {
858 let uniformity = match *statement {
859 S::Emit(ref range) => {
860 let mut requirements = UniformityRequirements::empty();
861 for expr in range.clone() {
862 let req = self.expressions[expr.index()].uniformity.requirements;
863 if self
864 .flags
865 .contains(ValidationFlags::CONTROL_FLOW_UNIFORMITY)
866 && !req.is_empty()
867 {
868 if let Some(cause) = disruptor {
869 let severity = DiagnosticFilterNode::search(
870 self.diagnostic_filter_leaf,
871 diagnostic_filter_arena,
872 StandardFilterableTriggeringRule::DerivativeUniformity,
873 );
874 severity.report_diag(
875 FunctionError::NonUniformControlFlow(req, expr, cause)
876 .with_span_handle(expr, expression_arena),
877 // TODO: Yes, this isn't contextualized with source, because
878 // the user is supposed to render what would normally be an
879 // error here. Once we actually support warning-level
880 // diagnostic items, then we won't need this non-compliant hack:
881 // <https://github.com/gfx-rs/wgpu/issues/6458>
882 |e, level| log::log!(level, "{e}"),
883 )?;
884 }
885 }
886 requirements |= req;
887 }
888 FunctionUniformity {
889 result: Uniformity {
890 non_uniform_result: None,
891 requirements,
892 },
893 exit: ExitFlags::empty(),
894 }
895 }
896 S::Break | S::Continue => FunctionUniformity::new(),
897 S::Kill => FunctionUniformity {
898 result: Uniformity::new(),
899 exit: if disruptor.is_some() {
900 ExitFlags::MAY_KILL
901 } else {
902 ExitFlags::empty()
903 },
904 },
905 S::Barrier(_) => FunctionUniformity {
906 result: Uniformity {
907 non_uniform_result: None,
908 requirements: UniformityRequirements::WORK_GROUP_BARRIER,
909 },
910 exit: ExitFlags::empty(),
911 },
912 S::WorkGroupUniformLoad { pointer, .. } => {
913 let _condition_nur = self.add_ref(pointer);
914
915 // Don't check that this call occurs in uniform control flow until Naga implements WGSL's standard
916 // uniformity analysis (https://github.com/gfx-rs/naga/issues/1744).
917 // The uniformity analysis Naga uses now is less accurate than the one in the WGSL standard,
918 // causing Naga to reject correct uses of `workgroupUniformLoad` in some interesting programs.
919
920 /*
921 if self
922 .flags
923 .contains(super::ValidationFlags::CONTROL_FLOW_UNIFORMITY)
924 {
925 let condition_nur = self.add_ref(pointer);
926 let this_disruptor =
927 disruptor.or(condition_nur.map(UniformityDisruptor::Expression));
928 if let Some(cause) = this_disruptor {
929 return Err(FunctionError::NonUniformWorkgroupUniformLoad(cause)
930 .with_span_static(*span, "WorkGroupUniformLoad"));
931 }
932 } */
933 FunctionUniformity {
934 result: Uniformity {
935 non_uniform_result: None,
936 requirements: UniformityRequirements::WORK_GROUP_BARRIER,
937 },
938 exit: ExitFlags::empty(),
939 }
940 }
941 S::Block(ref b) => self.process_block(
942 b,
943 other_functions,
944 disruptor,
945 expression_arena,
946 diagnostic_filter_arena,
947 )?,
948 S::If {
949 condition,
950 ref accept,
951 ref reject,
952 } => {
953 let condition_nur = self.add_ref(condition);
954 let branch_disruptor =
955 disruptor.or(condition_nur.map(UniformityDisruptor::Expression));
956 let accept_uniformity = self.process_block(
957 accept,
958 other_functions,
959 branch_disruptor,
960 expression_arena,
961 diagnostic_filter_arena,
962 )?;
963 let reject_uniformity = self.process_block(
964 reject,
965 other_functions,
966 branch_disruptor,
967 expression_arena,
968 diagnostic_filter_arena,
969 )?;
970 accept_uniformity | reject_uniformity
971 }
972 S::Switch {
973 selector,
974 ref cases,
975 } => {
976 let selector_nur = self.add_ref(selector);
977 let branch_disruptor =
978 disruptor.or(selector_nur.map(UniformityDisruptor::Expression));
979 let mut uniformity = FunctionUniformity::new();
980 let mut case_disruptor = branch_disruptor;
981 for case in cases.iter() {
982 let case_uniformity = self.process_block(
983 &case.body,
984 other_functions,
985 case_disruptor,
986 expression_arena,
987 diagnostic_filter_arena,
988 )?;
989 case_disruptor = if case.fall_through {
990 case_disruptor.or(case_uniformity.exit_disruptor())
991 } else {
992 branch_disruptor
993 };
994 uniformity = uniformity | case_uniformity;
995 }
996 uniformity
997 }
998 S::Loop {
999 ref body,
1000 ref continuing,
1001 break_if,
1002 } => {
1003 let body_uniformity = self.process_block(
1004 body,
1005 other_functions,
1006 disruptor,
1007 expression_arena,
1008 diagnostic_filter_arena,
1009 )?;
1010 let continuing_disruptor = disruptor.or(body_uniformity.exit_disruptor());
1011 let continuing_uniformity = self.process_block(
1012 continuing,
1013 other_functions,
1014 continuing_disruptor,
1015 expression_arena,
1016 diagnostic_filter_arena,
1017 )?;
1018 if let Some(expr) = break_if {
1019 let _ = self.add_ref(expr);
1020 }
1021 body_uniformity | continuing_uniformity
1022 }
1023 S::Return { value } => FunctionUniformity {
1024 result: Uniformity {
1025 non_uniform_result: value.and_then(|expr| self.add_ref(expr)),
1026 requirements: UniformityRequirements::empty(),
1027 },
1028 exit: if disruptor.is_some() {
1029 ExitFlags::MAY_RETURN
1030 } else {
1031 ExitFlags::empty()
1032 },
1033 },
1034 // Here and below, the used expressions are already emitted,
1035 // and their results do not affect the function return value,
1036 // so we can ignore their non-uniformity.
1037 S::Store { pointer, value } => {
1038 let _ = self.add_ref_impl(pointer, GlobalUse::WRITE);
1039 let _ = self.add_ref(value);
1040 FunctionUniformity::new()
1041 }
1042 S::ImageStore {
1043 image,
1044 coordinate,
1045 array_index,
1046 value,
1047 } => {
1048 let _ = self.add_ref_impl(image, GlobalUse::WRITE);
1049 if let Some(expr) = array_index {
1050 let _ = self.add_ref(expr);
1051 }
1052 let _ = self.add_ref(coordinate);
1053 let _ = self.add_ref(value);
1054 FunctionUniformity::new()
1055 }
1056 S::Call {
1057 function,
1058 ref arguments,
1059 result: _,
1060 } => {
1061 for &argument in arguments {
1062 let _ = self.add_ref(argument);
1063 }
1064 let info = &other_functions[function.index()];
1065 //Note: the result is validated by the Validator, not here
1066 self.process_call(info, arguments, expression_arena)?
1067 }
1068 S::Atomic {
1069 pointer,
1070 ref fun,
1071 value,
1072 result: _,
1073 } => {
1074 let _ = self.add_ref_impl(pointer, GlobalUse::READ | GlobalUse::WRITE);
1075 let _ = self.add_ref(value);
1076 if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun {
1077 let _ = self.add_ref(cmp);
1078 }
1079 FunctionUniformity::new()
1080 }
1081 S::ImageAtomic {
1082 image,
1083 coordinate,
1084 array_index,
1085 fun: _,
1086 value,
1087 } => {
1088 let _ = self.add_ref_impl(image, GlobalUse::ATOMIC);
1089 let _ = self.add_ref(coordinate);
1090 if let Some(expr) = array_index {
1091 let _ = self.add_ref(expr);
1092 }
1093 let _ = self.add_ref(value);
1094 FunctionUniformity::new()
1095 }
1096 S::RayQuery { query, ref fun } => {
1097 let _ = self.add_ref(query);
1098 match *fun {
1099 crate::RayQueryFunction::Initialize {
1100 acceleration_structure,
1101 descriptor,
1102 } => {
1103 let _ = self.add_ref(acceleration_structure);
1104 let _ = self.add_ref(descriptor);
1105 }
1106 crate::RayQueryFunction::Proceed { result: _ } => {}
1107 crate::RayQueryFunction::GenerateIntersection { hit_t } => {
1108 let _ = self.add_ref(hit_t);
1109 }
1110 crate::RayQueryFunction::ConfirmIntersection => {}
1111 crate::RayQueryFunction::Terminate => {}
1112 }
1113 FunctionUniformity::new()
1114 }
1115 S::SubgroupBallot {
1116 result: _,
1117 predicate,
1118 } => {
1119 if let Some(predicate) = predicate {
1120 let _ = self.add_ref(predicate);
1121 }
1122 FunctionUniformity::new()
1123 }
1124 S::SubgroupCollectiveOperation {
1125 op: _,
1126 collective_op: _,
1127 argument,
1128 result: _,
1129 } => {
1130 let _ = self.add_ref(argument);
1131 FunctionUniformity::new()
1132 }
1133 S::SubgroupGather {
1134 mode,
1135 argument,
1136 result: _,
1137 } => {
1138 let _ = self.add_ref(argument);
1139 match mode {
1140 crate::GatherMode::BroadcastFirst => {}
1141 crate::GatherMode::Broadcast(index)
1142 | crate::GatherMode::Shuffle(index)
1143 | crate::GatherMode::ShuffleDown(index)
1144 | crate::GatherMode::ShuffleUp(index)
1145 | crate::GatherMode::ShuffleXor(index) => {
1146 let _ = self.add_ref(index);
1147 }
1148 }
1149 FunctionUniformity::new()
1150 }
1151 };
1152
1153 disruptor = disruptor.or(uniformity.exit_disruptor());
1154 combined_uniformity = combined_uniformity | uniformity;
1155 }
1156 Ok(combined_uniformity)
1157 }
1158 }
1159
1160 impl ModuleInfo {
1161 /// Populates `self.const_expression_types`
1162 pub(super) fn process_const_expression(
1163 &mut self,
1164 handle: Handle<crate::Expression>,
1165 resolve_context: &ResolveContext,
1166 gctx: crate::proc::GlobalCtx,
1167 ) -> Result<(), super::ConstExpressionError> {
1168 self.const_expression_types[handle.index()] =
1169 resolve_context.resolve(&gctx.global_expressions[handle], |h| Ok(&self[h]))?;
1170 Ok(())
1171 }
1172
1173 /// Builds the `FunctionInfo` based on the function, and validates the
1174 /// uniform control flow if required by the expressions of this function.
1175 pub(super) fn process_function(
1176 &self,
1177 fun: &crate::Function,
1178 module: &crate::Module,
1179 flags: ValidationFlags,
1180 capabilities: super::Capabilities,
1181 ) -> Result<FunctionInfo, WithSpan<FunctionError>> {
1182 let mut info = FunctionInfo {
1183 flags,
1184 available_stages: ShaderStages::all(),
1185 uniformity: Uniformity::new(),
1186 may_kill: false,
1187 sampling_set: crate::FastHashSet::default(),
1188 global_uses: vec![GlobalUse::empty(); module.global_variables.len()].into_boxed_slice(),
1189 expressions: vec![ExpressionInfo::new(); fun.expressions.len()].into_boxed_slice(),
1190 sampling: crate::FastHashSet::default(),
1191 dual_source_blending: false,
1192 diagnostic_filter_leaf: fun.diagnostic_filter_leaf,
1193 };
1194 let resolve_context =
1195 ResolveContext::with_locals(module, &fun.local_variables, &fun.arguments);
1196
1197 for (handle, _) in fun.expressions.iter() {
1198 if let Err(source) = info.process_expression(
1199 handle,
1200 &fun.expressions,
1201 &self.functions,
1202 &resolve_context,
1203 capabilities,
1204 ) {
1205 return Err(FunctionError::Expression { handle, source }
1206 .with_span_handle(handle, &fun.expressions));
1207 }
1208 }
1209
1210 for (_, expr) in fun.local_variables.iter() {
1211 if let Some(init) = expr.init {
1212 let _ = info.add_ref(init);
1213 }
1214 }
1215
1216 let uniformity = info.process_block(
1217 &fun.body,
1218 &self.functions,
1219 None,
1220 &fun.expressions,
1221 &module.diagnostic_filters,
1222 )?;
1223 info.uniformity = uniformity.result;
1224 info.may_kill = uniformity.exit.contains(ExitFlags::MAY_KILL);
1225
1226 // If there are any globals referenced directly by a named expression,
1227 // ensure they are marked as used even if they are not referenced
1228 // anywhere else. An important case where this matters is phony
1229 // assignments used to include a global in the shader's resource
1230 // interface. https://www.w3.org/TR/WGSL/#phony-assignment-section
1231 for &handle in fun.named_expressions.keys() {
1232 if let Some(global) = info[handle].assignable_global {
1233 if info.global_uses[global.index()].is_empty() {
1234 info.global_uses[global.index()] = GlobalUse::QUERY;
1235 }
1236 }
1237 }
1238
1239 Ok(info)
1240 }
1241
1242 pub fn get_entry_point(&self, index: usize) -> &FunctionInfo {
1243 &self.entry_points[index]
1244 }
1245 }
1246
1247 #[test]
1248 fn uniform_control_flow() {
1249 use crate::{Expression as E, Statement as S};
1250
1251 let mut type_arena = crate::UniqueArena::new();
1252 let ty = type_arena.insert(
1253 crate::Type {
1254 name: None,
1255 inner: crate::TypeInner::Vector {
1256 size: crate::VectorSize::Bi,
1257 scalar: crate::Scalar::F32,
1258 },
1259 },
1260 Default::default(),
1261 );
1262 let mut global_var_arena = Arena::new();
1263 let non_uniform_global = global_var_arena.append(
1264 crate::GlobalVariable {
1265 name: None,
1266 init: None,
1267 ty,
1268 space: crate::AddressSpace::Handle,
1269 binding: None,
1270 },
1271 Default::default(),
1272 );
1273 let uniform_global = global_var_arena.append(
1274 crate::GlobalVariable {
1275 name: None,
1276 init: None,
1277 ty,
1278 binding: None,
1279 space: crate::AddressSpace::Uniform,
1280 },
1281 Default::default(),
1282 );
1283
1284 let mut expressions = Arena::new();
1285 // checks the uniform control flow
1286 let constant_expr = expressions.append(E::Literal(crate::Literal::U32(0)), Default::default());
1287 // checks the non-uniform control flow
1288 let derivative_expr = expressions.append(
1289 E::Derivative {
1290 axis: crate::DerivativeAxis::X,
1291 ctrl: crate::DerivativeControl::None,
1292 expr: constant_expr,
1293 },
1294 Default::default(),
1295 );
1296 let emit_range_constant_derivative = expressions.range_from(0);
1297 let non_uniform_global_expr =
1298 expressions.append(E::GlobalVariable(non_uniform_global), Default::default());
1299 let uniform_global_expr =
1300 expressions.append(E::GlobalVariable(uniform_global), Default::default());
1301 let emit_range_globals = expressions.range_from(2);
1302
1303 // checks the QUERY flag
1304 let query_expr = expressions.append(E::ArrayLength(uniform_global_expr), Default::default());
1305 // checks the transitive WRITE flag
1306 let access_expr = expressions.append(
1307 E::AccessIndex {
1308 base: non_uniform_global_expr,
1309 index: 1,
1310 },
1311 Default::default(),
1312 );
1313 let emit_range_query_access_globals = expressions.range_from(2);
1314
1315 let mut info = FunctionInfo {
1316 flags: ValidationFlags::all(),
1317 available_stages: ShaderStages::all(),
1318 uniformity: Uniformity::new(),
1319 may_kill: false,
1320 sampling_set: crate::FastHashSet::default(),
1321 global_uses: vec![GlobalUse::empty(); global_var_arena.len()].into_boxed_slice(),
1322 expressions: vec![ExpressionInfo::new(); expressions.len()].into_boxed_slice(),
1323 sampling: crate::FastHashSet::default(),
1324 dual_source_blending: false,
1325 diagnostic_filter_leaf: None,
1326 };
1327 let resolve_context = ResolveContext {
1328 constants: &Arena::new(),
1329 overrides: &Arena::new(),
1330 types: &type_arena,
1331 special_types: &crate::SpecialTypes::default(),
1332 global_vars: &global_var_arena,
1333 local_vars: &Arena::new(),
1334 functions: &Arena::new(),
1335 arguments: &[],
1336 };
1337 for (handle, _) in expressions.iter() {
1338 info.process_expression(
1339 handle,
1340 &expressions,
1341 &[],
1342 &resolve_context,
1343 super::Capabilities::empty(),
1344 )
1345 .unwrap();
1346 }
1347 assert_eq!(info[non_uniform_global_expr].ref_count, 1);
1348 assert_eq!(info[uniform_global_expr].ref_count, 1);
1349 assert_eq!(info[query_expr].ref_count, 0);
1350 assert_eq!(info[access_expr].ref_count, 0);
1351 assert_eq!(info[non_uniform_global], GlobalUse::empty());
1352 assert_eq!(info[uniform_global], GlobalUse::QUERY);
1353
1354 let stmt_emit1 = S::Emit(emit_range_globals.clone());
1355 let stmt_if_uniform = S::If {
1356 condition: uniform_global_expr,
1357 accept: crate::Block::new(),
1358 reject: vec![
1359 S::Emit(emit_range_constant_derivative.clone()),
1360 S::Store {
1361 pointer: constant_expr,
1362 value: derivative_expr,
1363 },
1364 ]
1365 .into(),
1366 };
1367 assert_eq!(
1368 info.process_block(
1369 &vec![stmt_emit1, stmt_if_uniform].into(),
1370 &[],
1371 None,
1372 &expressions,
1373 &Arena::new(),
1374 ),
1375 Ok(FunctionUniformity {
1376 result: Uniformity {
1377 non_uniform_result: None,
1378 requirements: UniformityRequirements::DERIVATIVE,
1379 },
1380 exit: ExitFlags::empty(),
1381 }),
1382 );
1383 assert_eq!(info[constant_expr].ref_count, 2);
1384 assert_eq!(info[uniform_global], GlobalUse::READ | GlobalUse::QUERY);
1385
1386 let stmt_emit2 = S::Emit(emit_range_globals.clone());
1387 let stmt_if_non_uniform = S::If {
1388 condition: non_uniform_global_expr,
1389 accept: vec![
1390 S::Emit(emit_range_constant_derivative),
1391 S::Store {
1392 pointer: constant_expr,
1393 value: derivative_expr,
1394 },
1395 ]
1396 .into(),
1397 reject: crate::Block::new(),
1398 };
1399 {
1400 let block_info = info.process_block(
1401 &vec![stmt_emit2.clone(), stmt_if_non_uniform.clone()].into(),
1402 &[],
1403 None,
1404 &expressions,
1405 &Arena::new(),
1406 );
1407 if DISABLE_UNIFORMITY_REQ_FOR_FRAGMENT_STAGE {
1408 assert_eq!(info[derivative_expr].ref_count, 2);
1409 } else {
1410 assert_eq!(
1411 block_info,
1412 Err(FunctionError::NonUniformControlFlow(
1413 UniformityRequirements::DERIVATIVE,
1414 derivative_expr,
1415 UniformityDisruptor::Expression(non_uniform_global_expr)
1416 )
1417 .with_span()),
1418 );
1419 assert_eq!(info[derivative_expr].ref_count, 1);
1420
1421 // Test that the same thing passes when we disable the `derivative_uniformity`
1422 let mut diagnostic_filters = Arena::new();
1423 let diagnostic_filter_leaf = diagnostic_filters.append(
1424 DiagnosticFilterNode {
1425 inner: crate::diagnostic_filter::DiagnosticFilter {
1426 new_severity: crate::diagnostic_filter::Severity::Off,
1427 triggering_rule:
1428 crate::diagnostic_filter::FilterableTriggeringRule::Standard(
1429 StandardFilterableTriggeringRule::DerivativeUniformity,
1430 ),
1431 },
1432 parent: None,
1433 },
1434 crate::Span::default(),
1435 );
1436 let mut info = FunctionInfo {
1437 diagnostic_filter_leaf: Some(diagnostic_filter_leaf),
1438 ..info.clone()
1439 };
1440
1441 let block_info = info.process_block(
1442 &vec![stmt_emit2, stmt_if_non_uniform].into(),
1443 &[],
1444 None,
1445 &expressions,
1446 &diagnostic_filters,
1447 );
1448 assert_eq!(
1449 block_info,
1450 Ok(FunctionUniformity {
1451 result: Uniformity {
1452 non_uniform_result: None,
1453 requirements: UniformityRequirements::DERIVATIVE,
1454 },
1455 exit: ExitFlags::empty()
1456 }),
1457 );
1458 assert_eq!(info[derivative_expr].ref_count, 2);
1459 }
1460 }
1461 assert_eq!(info[non_uniform_global], GlobalUse::READ);
1462
1463 let stmt_emit3 = S::Emit(emit_range_globals);
1464 let stmt_return_non_uniform = S::Return {
1465 value: Some(non_uniform_global_expr),
1466 };
1467 assert_eq!(
1468 info.process_block(
1469 &vec![stmt_emit3, stmt_return_non_uniform].into(),
1470 &[],
1471 Some(UniformityDisruptor::Return),
1472 &expressions,
1473 &Arena::new(),
1474 ),
1475 Ok(FunctionUniformity {
1476 result: Uniformity {
1477 non_uniform_result: Some(non_uniform_global_expr),
1478 requirements: UniformityRequirements::empty(),
1479 },
1480 exit: ExitFlags::MAY_RETURN,
1481 }),
1482 );
1483 assert_eq!(info[non_uniform_global_expr].ref_count, 3);
1484
1485 // Check that uniformity requirements reach through a pointer
1486 let stmt_emit4 = S::Emit(emit_range_query_access_globals);
1487 let stmt_assign = S::Store {
1488 pointer: access_expr,
1489 value: query_expr,
1490 };
1491 let stmt_return_pointer = S::Return {
1492 value: Some(access_expr),
1493 };
1494 let stmt_kill = S::Kill;
1495 assert_eq!(
1496 info.process_block(
1497 &vec![stmt_emit4, stmt_assign, stmt_kill, stmt_return_pointer].into(),
1498 &[],
1499 Some(UniformityDisruptor::Discard),
1500 &expressions,
1501 &Arena::new(),
1502 ),
1503 Ok(FunctionUniformity {
1504 result: Uniformity {
1505 non_uniform_result: Some(non_uniform_global_expr),
1506 requirements: UniformityRequirements::empty(),
1507 },
1508 exit: ExitFlags::all(),
1509 }),
1510 );
1511 assert_eq!(info[non_uniform_global], GlobalUse::READ | GlobalUse::WRITE);
1512 }