naga/proc/
index.rs

1/*!
2Definitions for index bounds checking.
3*/
4
5use crate::arena::{Handle, HandleSet, UniqueArena};
6use crate::valid;
7
8/// How should code generated by Naga do bounds checks?
9///
10/// When a vector, matrix, or array index is out of bounds—either negative, or
11/// greater than or equal to the number of elements in the type—WGSL requires
12/// that some other index of the implementation's choice that is in bounds is
13/// used instead. (There are no types with zero elements.)
14///
15/// Similarly, when out-of-bounds coordinates, array indices, or sample indices
16/// are presented to the WGSL `textureLoad` and `textureStore` operations, the
17/// operation is redirected to do something safe.
18///
19/// Different users of Naga will prefer different defaults:
20///
21/// -   When used as part of a WebGPU implementation, the WGSL specification
22///     requires the `Restrict` behavior for array, vector, and matrix accesses,
23///     and either the `Restrict` or `ReadZeroSkipWrite` behaviors for texture
24///     accesses.
25///
26/// -   When used by the `wgpu` crate for native development, `wgpu` selects
27///     `ReadZeroSkipWrite` as its default.
28///
29/// -   Naga's own default is `Unchecked`, so that shader translations
30///     are as faithful to the original as possible.
31///
32/// Sometimes the underlying hardware and drivers can perform bounds checks
33/// themselves, in a way that performs better than the checks Naga would inject.
34/// If you're using native checks like this, then having Naga inject its own
35/// checks as well would be redundant, and the `Unchecked` policy is
36/// appropriate.
37#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
38#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
39#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
40pub enum BoundsCheckPolicy {
41    /// Replace out-of-bounds indexes with some arbitrary in-bounds index.
42    ///
43    /// (This does not necessarily mean clamping. For example, interpreting the
44    /// index as unsigned and taking the minimum with the largest valid index
45    /// would also be a valid implementation. That would map negative indices to
46    /// the last element, not the first.)
47    Restrict,
48
49    /// Out-of-bounds reads return zero, and writes have no effect.
50    ///
51    /// When applied to a chain of accesses, like `a[i][j].b[k]`, all index
52    /// expressions are evaluated, regardless of whether prior or later index
53    /// expressions were in bounds. But all the accesses per se are skipped
54    /// if any index is out of bounds.
55    ReadZeroSkipWrite,
56
57    /// Naga adds no checks to indexing operations. Generate the fastest code
58    /// possible. This is the default for Naga, as a translator, but consumers
59    /// should consider defaulting to a safer behavior.
60    Unchecked,
61}
62
63/// Policies for injecting bounds checks during code generation.
64#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
65#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
66#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
67#[cfg_attr(feature = "deserialize", serde(default))]
68pub struct BoundsCheckPolicies {
69    /// How should the generated code handle array, vector, or matrix indices
70    /// that are out of range?
71    pub index: BoundsCheckPolicy,
72
73    /// How should the generated code handle array, vector, or matrix indices
74    /// that are out of range, when those values live in a [`GlobalVariable`] in
75    /// the [`Storage`] or [`Uniform`] address spaces?
76    ///
77    /// Some graphics hardware provides "robust buffer access", a feature that
78    /// ensures that using a pointer cannot access memory outside the 'buffer'
79    /// that it was derived from. In Naga terms, this means that the hardware
80    /// ensures that pointers computed by applying [`Access`] and
81    /// [`AccessIndex`] expressions to a [`GlobalVariable`] whose [`space`] is
82    /// [`Storage`] or [`Uniform`] will never read or write memory outside that
83    /// global variable.
84    ///
85    /// When hardware offers such a feature, it is probably undesirable to have
86    /// Naga inject bounds checking code for such accesses, since the hardware
87    /// can probably provide the same protection more efficiently. However,
88    /// bounds checks are still needed on accesses to indexable values that do
89    /// not live in buffers, like local variables.
90    ///
91    /// So, this option provides a separate policy that applies only to accesses
92    /// to storage and uniform globals. When depending on hardware bounds
93    /// checking, this policy can be `Unchecked` to avoid unnecessary overhead.
94    ///
95    /// When special hardware support is not available, this should probably be
96    /// the same as `index_bounds_check_policy`.
97    ///
98    /// [`GlobalVariable`]: crate::GlobalVariable
99    /// [`space`]: crate::GlobalVariable::space
100    /// [`Restrict`]: crate::back::BoundsCheckPolicy::Restrict
101    /// [`ReadZeroSkipWrite`]: crate::back::BoundsCheckPolicy::ReadZeroSkipWrite
102    /// [`Access`]: crate::Expression::Access
103    /// [`AccessIndex`]: crate::Expression::AccessIndex
104    /// [`Storage`]: crate::AddressSpace::Storage
105    /// [`Uniform`]: crate::AddressSpace::Uniform
106    pub buffer: BoundsCheckPolicy,
107
108    /// How should the generated code handle image texel loads that are out
109    /// of range?
110    ///
111    /// This controls the behavior of [`ImageLoad`] expressions when a coordinate,
112    /// texture array index, level of detail, or multisampled sample number is out of range.
113    ///
114    /// There is no corresponding policy for [`ImageStore`] statements. All the
115    /// platforms we support already discard out-of-bounds image stores,
116    /// effectively implementing the "skip write" part of [`ReadZeroSkipWrite`].
117    ///
118    /// [`ImageLoad`]: crate::Expression::ImageLoad
119    /// [`ImageStore`]: crate::Statement::ImageStore
120    /// [`ReadZeroSkipWrite`]: BoundsCheckPolicy::ReadZeroSkipWrite
121    pub image_load: BoundsCheckPolicy,
122
123    /// How should the generated code handle binding array indexes that are out of bounds.
124    pub binding_array: BoundsCheckPolicy,
125}
126
127/// The default `BoundsCheckPolicy` is `Unchecked`.
128impl Default for BoundsCheckPolicy {
129    fn default() -> Self {
130        BoundsCheckPolicy::Unchecked
131    }
132}
133
134impl BoundsCheckPolicies {
135    /// Determine which policy applies to `base`.
136    ///
137    /// `base` is the "base" expression (the expression being indexed) of a `Access`
138    /// and `AccessIndex` expression. This is either a pointer, a value, being directly
139    /// indexed, or a binding array.
140    ///
141    /// See the documentation for [`BoundsCheckPolicy`] for details about
142    /// when each policy applies.
143    pub fn choose_policy(
144        &self,
145        base: Handle<crate::Expression>,
146        types: &UniqueArena<crate::Type>,
147        info: &valid::FunctionInfo,
148    ) -> BoundsCheckPolicy {
149        let ty = info[base].ty.inner_with(types);
150
151        if let crate::TypeInner::BindingArray { .. } = *ty {
152            return self.binding_array;
153        }
154
155        match ty.pointer_space() {
156            Some(crate::AddressSpace::Storage { access: _ } | crate::AddressSpace::Uniform) => {
157                self.buffer
158            }
159            // This covers other address spaces, but also accessing vectors and
160            // matrices by value, where no pointer is involved.
161            _ => self.index,
162        }
163    }
164
165    /// Return `true` if any of `self`'s policies are `policy`.
166    pub fn contains(&self, policy: BoundsCheckPolicy) -> bool {
167        self.index == policy || self.buffer == policy || self.image_load == policy
168    }
169}
170
171/// An index that may be statically known, or may need to be computed at runtime.
172///
173/// This enum lets us handle both [`Access`] and [`AccessIndex`] expressions
174/// with the same code.
175///
176/// [`Access`]: crate::Expression::Access
177/// [`AccessIndex`]: crate::Expression::AccessIndex
178#[derive(Clone, Copy, Debug)]
179pub enum GuardedIndex {
180    Known(u32),
181    Expression(Handle<crate::Expression>),
182}
183
184/// Build a set of expressions used as indices, to cache in temporary variables when
185/// emitted.
186///
187/// Given the bounds-check policies `policies`, construct a `HandleSet` containing the handle
188/// indices of all the expressions in `function` that are ever used as guarded indices
189/// under the [`ReadZeroSkipWrite`] policy. The `module` argument must be the module to
190/// which `function` belongs, and `info` should be that function's analysis results.
191///
192/// Such index expressions will be used twice in the generated code: first for the
193/// comparison to see if the index is in bounds, and then for the access itself, should
194/// the comparison succeed. To avoid computing the expressions twice, the generated code
195/// should cache them in temporary variables.
196///
197/// Why do we need to build such a set in advance, instead of just processing access
198/// expressions as we encounter them? Whether an expression needs to be cached depends on
199/// whether it appears as something like the [`index`] operand of an [`Access`] expression
200/// or the [`level`] operand of an [`ImageLoad`] expression, and on the index bounds check
201/// policies that apply to those accesses. But [`Emit`] statements just identify a range
202/// of expressions by index; there's no good way to tell what an expression is used
203/// for. The only way to do it is to just iterate over all the expressions looking for
204/// relevant `Access` expressions --- which is what this function does.
205///
206/// Simple expressions like variable loads and constants don't make sense to cache: it's
207/// no better than just re-evaluating them. But constants are not covered by `Emit`
208/// statements, and `Load`s are always cached to ensure they occur at the right time, so
209/// we don't bother filtering them out from this set.
210///
211/// Fortunately, we don't need to deal with [`ImageStore`] statements here. When we emit
212/// code for a statement, the writer isn't in the middle of an expression, so we can just
213/// emit declarations for temporaries, initialized appropriately.
214///
215/// None of these concerns apply for SPIR-V output, since it's easy to just reuse an
216/// instruction ID in two places; that has the same semantics as a temporary variable, and
217/// it's inherent in the design of SPIR-V. This function is more useful for text-based
218/// back ends.
219///
220/// [`ReadZeroSkipWrite`]: BoundsCheckPolicy::ReadZeroSkipWrite
221/// [`index`]: crate::Expression::Access::index
222/// [`Access`]: crate::Expression::Access
223/// [`level`]: crate::Expression::ImageLoad::level
224/// [`ImageLoad`]: crate::Expression::ImageLoad
225/// [`Emit`]: crate::Statement::Emit
226/// [`ImageStore`]: crate::Statement::ImageStore
227pub fn find_checked_indexes(
228    module: &crate::Module,
229    function: &crate::Function,
230    info: &valid::FunctionInfo,
231    policies: BoundsCheckPolicies,
232) -> HandleSet<crate::Expression> {
233    use crate::Expression as Ex;
234
235    let mut guarded_indices = HandleSet::for_arena(&function.expressions);
236
237    // Don't bother scanning if we never need `ReadZeroSkipWrite`.
238    if policies.contains(BoundsCheckPolicy::ReadZeroSkipWrite) {
239        for (_handle, expr) in function.expressions.iter() {
240            // There's no need to handle `AccessIndex` expressions, as their
241            // indices never need to be cached.
242            match *expr {
243                Ex::Access { base, index } => {
244                    if policies.choose_policy(base, &module.types, info)
245                        == BoundsCheckPolicy::ReadZeroSkipWrite
246                        && access_needs_check(
247                            base,
248                            GuardedIndex::Expression(index),
249                            module,
250                            &function.expressions,
251                            info,
252                        )
253                        .is_some()
254                    {
255                        guarded_indices.insert(index);
256                    }
257                }
258                Ex::ImageLoad {
259                    coordinate,
260                    array_index,
261                    sample,
262                    level,
263                    ..
264                } => {
265                    if policies.image_load == BoundsCheckPolicy::ReadZeroSkipWrite {
266                        guarded_indices.insert(coordinate);
267                        if let Some(array_index) = array_index {
268                            guarded_indices.insert(array_index);
269                        }
270                        if let Some(sample) = sample {
271                            guarded_indices.insert(sample);
272                        }
273                        if let Some(level) = level {
274                            guarded_indices.insert(level);
275                        }
276                    }
277                }
278                _ => {}
279            }
280        }
281    }
282
283    guarded_indices
284}
285
286/// Determine whether `index` is statically known to be in bounds for `base`.
287///
288/// If we can't be sure that the index is in bounds, return the limit within
289/// which valid indices must fall.
290///
291/// The return value is one of the following:
292///
293/// - `Some(Known(n))` indicates that `n` is the largest valid index.
294///
295/// - `Some(Computed(global))` indicates that the largest valid index is one
296///   less than the length of the array that is the last member of the
297///   struct held in `global`.
298///
299/// - `None` indicates that the index need not be checked, either because it
300///   is statically known to be in bounds, or because the applicable policy
301///   is `Unchecked`.
302///
303/// This function only handles subscriptable types: arrays, vectors, and
304/// matrices. It does not handle struct member indices; those never require
305/// run-time checks, so it's best to deal with them further up the call
306/// chain.
307pub fn access_needs_check(
308    base: Handle<crate::Expression>,
309    mut index: GuardedIndex,
310    module: &crate::Module,
311    expressions: &crate::Arena<crate::Expression>,
312    info: &valid::FunctionInfo,
313) -> Option<IndexableLength> {
314    let base_inner = info[base].ty.inner_with(&module.types);
315    // Unwrap safety: `Err` here indicates unindexable base types and invalid
316    // length constants, but `access_needs_check` is only used by back ends, so
317    // validation should have caught those problems.
318    let length = base_inner.indexable_length(module).unwrap();
319    index.try_resolve_to_constant(expressions, module);
320    if let (&GuardedIndex::Known(index), &IndexableLength::Known(length)) = (&index, &length) {
321        if index < length {
322            // Index is statically known to be in bounds, no check needed.
323            return None;
324        }
325    };
326
327    Some(length)
328}
329
330impl GuardedIndex {
331    /// Make a `GuardedIndex::Known` from a `GuardedIndex::Expression` if possible.
332    ///
333    /// Return values that are already `Known` unchanged.
334    pub(crate) fn try_resolve_to_constant(
335        &mut self,
336        expressions: &crate::Arena<crate::Expression>,
337        module: &crate::Module,
338    ) {
339        if let GuardedIndex::Expression(expr) = *self {
340            *self = GuardedIndex::from_expression(expr, expressions, module);
341        }
342    }
343
344    pub(crate) fn from_expression(
345        expr: Handle<crate::Expression>,
346        expressions: &crate::Arena<crate::Expression>,
347        module: &crate::Module,
348    ) -> Self {
349        match module.to_ctx().eval_expr_to_u32_from(expr, expressions) {
350            Ok(value) => Self::Known(value),
351            Err(_) => Self::Expression(expr),
352        }
353    }
354}
355
356#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq)]
357pub enum IndexableLengthError {
358    #[error("Type is not indexable, and has no length (validation error)")]
359    TypeNotIndexable,
360    #[error("Array length constant {0:?} is invalid")]
361    InvalidArrayLength(Handle<crate::Expression>),
362}
363
364impl crate::TypeInner {
365    /// Return the length of a subscriptable type.
366    ///
367    /// The `self` parameter should be a handle to a vector, matrix, or array
368    /// type, a pointer to one of those, or a value pointer. Arrays may be
369    /// fixed-size, dynamically sized, or sized by a specializable constant.
370    /// This function does not handle struct member references, as with
371    /// `AccessIndex`.
372    ///
373    /// The value returned is appropriate for bounds checks on subscripting.
374    ///
375    /// Return an error if `self` does not describe a subscriptable type at all.
376    pub fn indexable_length(
377        &self,
378        module: &crate::Module,
379    ) -> Result<IndexableLength, IndexableLengthError> {
380        use crate::TypeInner as Ti;
381        let known_length = match *self {
382            Ti::Vector { size, .. } => size as _,
383            Ti::Matrix { columns, .. } => columns as _,
384            Ti::Array { size, .. } | Ti::BindingArray { size, .. } => {
385                return size.to_indexable_length(module);
386            }
387            Ti::ValuePointer {
388                size: Some(size), ..
389            } => size as _,
390            Ti::Pointer { base, .. } => {
391                // When assigning types to expressions, ResolveContext::Resolve
392                // does a separate sub-match here instead of a full recursion,
393                // so we'll do the same.
394                let base_inner = &module.types[base].inner;
395                match *base_inner {
396                    Ti::Vector { size, .. } => size as _,
397                    Ti::Matrix { columns, .. } => columns as _,
398                    Ti::Array { size, .. } | Ti::BindingArray { size, .. } => {
399                        return size.to_indexable_length(module)
400                    }
401                    _ => return Err(IndexableLengthError::TypeNotIndexable),
402                }
403            }
404            _ => return Err(IndexableLengthError::TypeNotIndexable),
405        };
406        Ok(IndexableLength::Known(known_length))
407    }
408}
409
410/// The number of elements in an indexable type.
411///
412/// This summarizes the length of vectors, matrices, and arrays in a way that is
413/// convenient for indexing and bounds-checking code.
414#[derive(Debug)]
415pub enum IndexableLength {
416    /// Values of this type always have the given number of elements.
417    Known(u32),
418
419    Pending,
420
421    /// The number of elements is determined at runtime.
422    Dynamic,
423}
424
425impl crate::ArraySize {
426    pub const fn to_indexable_length(
427        self,
428        _module: &crate::Module,
429    ) -> Result<IndexableLength, IndexableLengthError> {
430        Ok(match self {
431            Self::Constant(length) => IndexableLength::Known(length.get()),
432            Self::Pending(_) => IndexableLength::Pending,
433            Self::Dynamic => IndexableLength::Dynamic,
434        })
435    }
436}