Debian Codegraph @

third_party/rust/naga/src/back/msl/writer.rs

raw
1 use alloc::{
2 format,
3 string::{String, ToString},
4 vec,
5 vec::Vec,
6 };
7 use core::{
8 cmp::Ordering,
9 fmt::{Display, Error as FmtError, Formatter, Write},
10 iter,
11 };
12 use num_traits::real::Real as _;
13
14 use half::f16;
15
16 use super::{sampler as sm, Error, LocationMode, Options, PipelineOptions, TranslationInfo};
17 use crate::{
18 arena::{Handle, HandleSet},
19 back::{self, get_entry_points, Baked},
20 common,
21 proc::{
22 self,
23 index::{self, BoundsCheck},
24 NameKey, TypeResolution,
25 },
26 valid, FastHashMap, FastHashSet,
27 };
28
29 #[cfg(test)]
30 use core::ptr;
31
32 /// Shorthand result used internally by the backend
33 type BackendResult = Result<(), Error>;
34
35 const NAMESPACE: &str = "metal";
36 // The name of the array member of the Metal struct types we generate to
37 // represent Naga `Array` types. See the comments in `Writer::write_type_defs`
38 // for details.
39 const WRAPPED_ARRAY_FIELD: &str = "inner";
40 // This is a hack: we need to pass a pointer to an atomic,
41 // but generally the backend isn't putting "&" in front of every pointer.
42 // Some more general handling of pointers is needed to be implemented here.
43 const ATOMIC_REFERENCE: &str = "&";
44
45 const RT_NAMESPACE: &str = "metal::raytracing";
46 const RAY_QUERY_TYPE: &str = "_RayQuery";
47 const RAY_QUERY_FIELD_INTERSECTOR: &str = "intersector";
48 const RAY_QUERY_FIELD_INTERSECTION: &str = "intersection";
49 const RAY_QUERY_MODERN_SUPPORT: bool = false; //TODO
50 const RAY_QUERY_FIELD_READY: &str = "ready";
51 const RAY_QUERY_FUN_MAP_INTERSECTION: &str = "_map_intersection_type";
52
53 pub(crate) const ATOMIC_COMP_EXCH_FUNCTION: &str = "naga_atomic_compare_exchange_weak_explicit";
54 pub(crate) const MODF_FUNCTION: &str = "naga_modf";
55 pub(crate) const FREXP_FUNCTION: &str = "naga_frexp";
56 pub(crate) const ABS_FUNCTION: &str = "naga_abs";
57 pub(crate) const DIV_FUNCTION: &str = "naga_div";
58 pub(crate) const MOD_FUNCTION: &str = "naga_mod";
59 pub(crate) const NEG_FUNCTION: &str = "naga_neg";
60 pub(crate) const F2I32_FUNCTION: &str = "naga_f2i32";
61 pub(crate) const F2U32_FUNCTION: &str = "naga_f2u32";
62 pub(crate) const F2I64_FUNCTION: &str = "naga_f2i64";
63 pub(crate) const F2U64_FUNCTION: &str = "naga_f2u64";
64 /// For some reason, Metal does not let you have `metal::texture<..>*` as a buffer argument.
65 /// However, if you put that texture inside a struct, everything is totally fine. This
66 /// baffles me to no end.
67 ///
68 /// As such, we wrap all argument buffers in a struct that has a single generic `<T>` field.
69 /// This allows `NagaArgumentBufferWrapper<metal::texture<..>>*` to work. The astute among
70 /// you have noticed that this should be exactly the same to the compiler, and you're correct.
71 pub(crate) const ARGUMENT_BUFFER_WRAPPER_STRUCT: &str = "NagaArgumentBufferWrapper";
72
73 /// Write the Metal name for a Naga numeric type: scalar, vector, or matrix.
74 ///
75 /// The `sizes` slice determines whether this function writes a
76 /// scalar, vector, or matrix type:
77 ///
78 /// - An empty slice produces a scalar type.
79 /// - A one-element slice produces a vector type.
80 /// - A two element slice `[ROWS COLUMNS]` produces a matrix of the given size.
81 fn put_numeric_type(
82 out: &mut impl Write,
83 scalar: crate::Scalar,
84 sizes: &[crate::VectorSize],
85 ) -> Result<(), FmtError> {
86 match (scalar, sizes) {
87 (scalar, &[]) => {
88 write!(out, "{}", scalar.to_msl_name())
89 }
90 (scalar, &[rows]) => {
91 write!(
92 out,
93 "{}::{}{}",
94 NAMESPACE,
95 scalar.to_msl_name(),
96 common::vector_size_str(rows)
97 )
98 }
99 (scalar, &[rows, columns]) => {
100 write!(
101 out,
102 "{}::{}{}x{}",
103 NAMESPACE,
104 scalar.to_msl_name(),
105 common::vector_size_str(columns),
106 common::vector_size_str(rows)
107 )
108 }
109 (_, _) => Ok(()), // not meaningful
110 }
111 }
112
113 const fn scalar_is_int(scalar: crate::Scalar) -> bool {
114 use crate::ScalarKind::*;
115 match scalar.kind {
116 Sint | Uint | AbstractInt | Bool => true,
117 Float | AbstractFloat => false,
118 }
119 }
120
121 /// Prefix for cached clamped level-of-detail values for `ImageLoad` expressions.
122 const CLAMPED_LOD_LOAD_PREFIX: &str = "clamped_lod_e";
123
124 /// Wrapper for identifier names for clamped level-of-detail values
125 ///
126 /// Values of this type implement [`core::fmt::Display`], formatting as
127 /// the name of the variable used to hold the cached clamped
128 /// level-of-detail value for an `ImageLoad` expression.
129 struct ClampedLod(Handle<crate::Expression>);
130
131 impl Display for ClampedLod {
132 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
133 self.0.write_prefixed(f, CLAMPED_LOD_LOAD_PREFIX)
134 }
135 }
136
137 /// Wrapper for generating `struct _mslBufferSizes` member names for
138 /// runtime-sized array lengths.
139 ///
140 /// On Metal, `wgpu_hal` passes the element counts for all runtime-sized arrays
141 /// as an argument to the entry point. This argument's type in the MSL is
142 /// `struct _mslBufferSizes`, a Naga-synthesized struct with a `uint` member for
143 /// each global variable containing a runtime-sized array.
144 ///
145 /// If `global` is a [`Handle`] for a [`GlobalVariable`] that contains a
146 /// runtime-sized array, then the value `ArraySize(global)` implements
147 /// [`core::fmt::Display`], formatting as the name of the struct member carrying
148 /// the number of elements in that runtime-sized array.
149 ///
150 /// [`GlobalVariable`]: crate::GlobalVariable
151 struct ArraySizeMember(Handle<crate::GlobalVariable>);
152
153 impl Display for ArraySizeMember {
154 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
155 self.0.write_prefixed(f, "size")
156 }
157 }
158
159 struct TypeContext<'a> {
160 handle: Handle<crate::Type>,
161 gctx: proc::GlobalCtx<'a>,
162 names: &'a FastHashMap<NameKey, String>,
163 access: crate::StorageAccess,
164 first_time: bool,
165 }
166
167 impl TypeContext<'_> {
168 fn scalar(&self) -> Option<crate::Scalar> {
169 let ty = &self.gctx.types[self.handle];
170 ty.inner.scalar()
171 }
172
173 fn vertex_input_dimension(&self) -> u32 {
174 let ty = &self.gctx.types[self.handle];
175 match ty.inner {
176 crate::TypeInner::Scalar(_) => 1,
177 crate::TypeInner::Vector { size, .. } => size as u32,
178 _ => unreachable!(),
179 }
180 }
181 }
182
183 impl Display for TypeContext<'_> {
184 fn fmt(&self, out: &mut Formatter<'_>) -> Result<(), FmtError> {
185 let ty = &self.gctx.types[self.handle];
186 if ty.needs_alias() && !self.first_time {
187 let name = &self.names[&NameKey::Type(self.handle)];
188 return write!(out, "{name}");
189 }
190
191 match ty.inner {
192 crate::TypeInner::Scalar(scalar) => put_numeric_type(out, scalar, &[]),
193 crate::TypeInner::Atomic(scalar) => {
194 write!(out, "{}::atomic_{}", NAMESPACE, scalar.to_msl_name())
195 }
196 crate::TypeInner::Vector { size, scalar } => put_numeric_type(out, scalar, &[size]),
197 crate::TypeInner::Matrix {
198 columns,
199 rows,
200 scalar,
201 } => put_numeric_type(out, scalar, &[rows, columns]),
202 crate::TypeInner::Pointer { base, space } => {
203 let sub = Self {
204 handle: base,
205 first_time: false,
206 ..*self
207 };
208 let space_name = match space.to_msl_name() {
209 Some(name) => name,
210 None => return Ok(()),
211 };
212 write!(out, "{space_name} {sub}&")
213 }
214 crate::TypeInner::ValuePointer {
215 size,
216 scalar,
217 space,
218 } => {
219 match space.to_msl_name() {
220 Some(name) => write!(out, "{name} ")?,
221 None => return Ok(()),
222 };
223 match size {
224 Some(rows) => put_numeric_type(out, scalar, &[rows])?,
225 None => put_numeric_type(out, scalar, &[])?,
226 };
227
228 write!(out, "&")
229 }
230 crate::TypeInner::Array { base, .. } => {
231 let sub = Self {
232 handle: base,
233 first_time: false,
234 ..*self
235 };
236 // Array lengths go at the end of the type definition,
237 // so just print the element type here.
238 write!(out, "{sub}")
239 }
240 crate::TypeInner::Struct { .. } => unreachable!(),
241 crate::TypeInner::Image {
242 dim,
243 arrayed,
244 class,
245 } => {
246 let dim_str = match dim {
247 crate::ImageDimension::D1 => "1d",
248 crate::ImageDimension::D2 => "2d",
249 crate::ImageDimension::D3 => "3d",
250 crate::ImageDimension::Cube => "cube",
251 };
252 let (texture_str, msaa_str, scalar, access) = match class {
253 crate::ImageClass::Sampled { kind, multi } => {
254 let (msaa_str, access) = if multi {
255 ("_ms", "read")
256 } else {
257 ("", "sample")
258 };
259 let scalar = crate::Scalar { kind, width: 4 };
260 ("texture", msaa_str, scalar, access)
261 }
262 crate::ImageClass::Depth { multi } => {
263 let (msaa_str, access) = if multi {
264 ("_ms", "read")
265 } else {
266 ("", "sample")
267 };
268 let scalar = crate::Scalar {
269 kind: crate::ScalarKind::Float,
270 width: 4,
271 };
272 ("depth", msaa_str, scalar, access)
273 }
274 crate::ImageClass::Storage { format, .. } => {
275 let access = if self
276 .access
277 .contains(crate::StorageAccess::LOAD | crate::StorageAccess::STORE)
278 {
279 "read_write"
280 } else if self.access.contains(crate::StorageAccess::STORE) {
281 "write"
282 } else if self.access.contains(crate::StorageAccess::LOAD) {
283 "read"
284 } else {
285 log::warn!(
286 "Storage access for {:?} (name '{}'): {:?}",
287 self.handle,
288 ty.name.as_deref().unwrap_or_default(),
289 self.access
290 );
291 unreachable!("module is not valid");
292 };
293 ("texture", "", format.into(), access)
294 }
295 };
296 let base_name = scalar.to_msl_name();
297 let array_str = if arrayed { "_array" } else { "" };
298 write!(
299 out,
300 "{NAMESPACE}::{texture_str}{dim_str}{msaa_str}{array_str}<{base_name}, {NAMESPACE}::access::{access}>",
301 )
302 }
303 crate::TypeInner::Sampler { comparison: _ } => {
304 write!(out, "{NAMESPACE}::sampler")
305 }
306 crate::TypeInner::AccelerationStructure { vertex_return } => {
307 if vertex_return {
308 unimplemented!("metal does not support vertex ray hit return")
309 }
310 write!(out, "{RT_NAMESPACE}::instance_acceleration_structure")
311 }
312 crate::TypeInner::RayQuery { vertex_return } => {
313 if vertex_return {
314 unimplemented!("metal does not support vertex ray hit return")
315 }
316 write!(out, "{RAY_QUERY_TYPE}")
317 }
318 crate::TypeInner::BindingArray { base, .. } => {
319 let base_tyname = Self {
320 handle: base,
321 first_time: false,
322 ..*self
323 };
324
325 write!(
326 out,
327 "constant {ARGUMENT_BUFFER_WRAPPER_STRUCT}<{base_tyname}>*"
328 )
329 }
330 }
331 }
332 }
333
334 struct TypedGlobalVariable<'a> {
335 module: &'a crate::Module,
336 names: &'a FastHashMap<NameKey, String>,
337 handle: Handle<crate::GlobalVariable>,
338 usage: valid::GlobalUse,
339 reference: bool,
340 }
341
342 impl TypedGlobalVariable<'_> {
343 fn try_fmt<W: Write>(&self, out: &mut W) -> BackendResult {
344 let var = &self.module.global_variables[self.handle];
345 let name = &self.names[&NameKey::GlobalVariable(self.handle)];
346
347 let storage_access = match var.space {
348 crate::AddressSpace::Storage { access } => access,
349 _ => match self.module.types[var.ty].inner {
350 crate::TypeInner::Image {
351 class: crate::ImageClass::Storage { access, .. },
352 ..
353 } => access,
354 crate::TypeInner::BindingArray { base, .. } => {
355 match self.module.types[base].inner {
356 crate::TypeInner::Image {
357 class: crate::ImageClass::Storage { access, .. },
358 ..
359 } => access,
360 _ => crate::StorageAccess::default(),
361 }
362 }
363 _ => crate::StorageAccess::default(),
364 },
365 };
366 let ty_name = TypeContext {
367 handle: var.ty,
368 gctx: self.module.to_ctx(),
369 names: self.names,
370 access: storage_access,
371 first_time: false,
372 };
373
374 let (space, access, reference) = match var.space.to_msl_name() {
375 Some(space) if self.reference => {
376 let access = if var.space.needs_access_qualifier()
377 && !self.usage.intersects(valid::GlobalUse::WRITE)
378 {
379 "const"
380 } else {
381 ""
382 };
383 (space, access, "&")
384 }
385 _ => ("", "", ""),
386 };
387
388 Ok(write!(
389 out,
390 "{}{}{}{}{}{} {}",
391 space,
392 if space.is_empty() { "" } else { " " },
393 ty_name,
394 if access.is_empty() { "" } else { " " },
395 access,
396 reference,
397 name,
398 )?)
399 }
400 }
401
402 #[derive(Eq, PartialEq, Hash)]
403 enum WrappedFunction {
404 UnaryOp {
405 op: crate::UnaryOperator,
406 ty: (Option<crate::VectorSize>, crate::Scalar),
407 },
408 BinaryOp {
409 op: crate::BinaryOperator,
410 left_ty: (Option<crate::VectorSize>, crate::Scalar),
411 right_ty: (Option<crate::VectorSize>, crate::Scalar),
412 },
413 Math {
414 fun: crate::MathFunction,
415 arg_ty: (Option<crate::VectorSize>, crate::Scalar),
416 },
417 Cast {
418 src_scalar: crate::Scalar,
419 vector_size: Option<crate::VectorSize>,
420 dst_scalar: crate::Scalar,
421 },
422 }
423
424 pub struct Writer<W> {
425 out: W,
426 names: FastHashMap<NameKey, String>,
427 named_expressions: crate::NamedExpressions,
428 /// Set of expressions that need to be baked to avoid unnecessary repetition in output
429 need_bake_expressions: back::NeedBakeExpressions,
430 namer: proc::Namer,
431 wrapped_functions: FastHashSet<WrappedFunction>,
432 #[cfg(test)]
433 put_expression_stack_pointers: FastHashSet<*const ()>,
434 #[cfg(test)]
435 put_block_stack_pointers: FastHashSet<*const ()>,
436 /// Set of (struct type, struct field index) denoting which fields require
437 /// padding inserted **before** them (i.e. between fields at index - 1 and index)
438 struct_member_pads: FastHashSet<(Handle<crate::Type>, u32)>,
439 }
440
441 impl crate::Scalar {
442 fn to_msl_name(self) -> &'static str {
443 use crate::ScalarKind as Sk;
444 match self {
445 Self {
446 kind: Sk::Float,
447 width: 4,
448 } => "float",
449 Self {
450 kind: Sk::Float,
451 width: 2,
452 } => "half",
453 Self {
454 kind: Sk::Sint,
455 width: 4,
456 } => "int",
457 Self {
458 kind: Sk::Uint,
459 width: 4,
460 } => "uint",
461 Self {
462 kind: Sk::Sint,
463 width: 8,
464 } => "long",
465 Self {
466 kind: Sk::Uint,
467 width: 8,
468 } => "ulong",
469 Self {
470 kind: Sk::Bool,
471 width: _,
472 } => "bool",
473 Self {
474 kind: Sk::AbstractInt | Sk::AbstractFloat,
475 width: _,
476 } => unreachable!("Found Abstract scalar kind"),
477 _ => unreachable!("Unsupported scalar kind: {:?}", self),
478 }
479 }
480 }
481
482 const fn separate(need_separator: bool) -> &'static str {
483 if need_separator {
484 ","
485 } else {
486 ""
487 }
488 }
489
490 fn should_pack_struct_member(
491 members: &[crate::StructMember],
492 span: u32,
493 index: usize,
494 module: &crate::Module,
495 ) -> Option<crate::Scalar> {
496 let member = &members[index];
497
498 let ty_inner = &module.types[member.ty].inner;
499 let last_offset = member.offset + ty_inner.size(module.to_ctx());
500 let next_offset = match members.get(index + 1) {
501 Some(next) => next.offset,
502 None => span,
503 };
504 let is_tight = next_offset == last_offset;
505
506 match *ty_inner {
507 crate::TypeInner::Vector {
508 size: crate::VectorSize::Tri,
509 scalar: scalar @ crate::Scalar { width: 4 | 2, .. },
510 } if is_tight => Some(scalar),
511 _ => None,
512 }
513 }
514
515 fn needs_array_length(ty: Handle<crate::Type>, arena: &crate::UniqueArena<crate::Type>) -> bool {
516 match arena[ty].inner {
517 crate::TypeInner::Struct { ref members, .. } => {
518 if let Some(member) = members.last() {
519 if let crate::TypeInner::Array {
520 size: crate::ArraySize::Dynamic,
521 ..
522 } = arena[member.ty].inner
523 {
524 return true;
525 }
526 }
527 false
528 }
529 crate::TypeInner::Array {
530 size: crate::ArraySize::Dynamic,
531 ..
532 } => true,
533 _ => false,
534 }
535 }
536
537 impl crate::AddressSpace {
538 /// Returns true if global variables in this address space are
539 /// passed in function arguments. These arguments need to be
540 /// passed through any functions called from the entry point.
541 const fn needs_pass_through(&self) -> bool {
542 match *self {
543 Self::Uniform
544 | Self::Storage { .. }
545 | Self::Private
546 | Self::WorkGroup
547 | Self::PushConstant
548 | Self::Handle => true,
549 Self::Function => false,
550 }
551 }
552
553 /// Returns true if the address space may need a "const" qualifier.
554 const fn needs_access_qualifier(&self) -> bool {
555 match *self {
556 //Note: we are ignoring the storage access here, and instead
557 // rely on the actual use of a global by functions. This means we
558 // may end up with "const" even if the binding is read-write,
559 // and that should be OK.
560 Self::Storage { .. } => true,
561 // These should always be read-write.
562 Self::Private | Self::WorkGroup => false,
563 // These translate to `constant` address space, no need for qualifiers.
564 Self::Uniform | Self::PushConstant => false,
565 // Not applicable.
566 Self::Handle | Self::Function => false,
567 }
568 }
569
570 const fn to_msl_name(self) -> Option<&'static str> {
571 match self {
572 Self::Handle => None,
573 Self::Uniform | Self::PushConstant => Some("constant"),
574 Self::Storage { .. } => Some("device"),
575 Self::Private | Self::Function => Some("thread"),
576 Self::WorkGroup => Some("threadgroup"),
577 }
578 }
579 }
580
581 impl crate::Type {
582 // Returns `true` if we need to emit an alias for this type.
583 const fn needs_alias(&self) -> bool {
584 use crate::TypeInner as Ti;
585
586 match self.inner {
587 // value types are concise enough, we only alias them if they are named
588 Ti::Scalar(_)
589 | Ti::Vector { .. }
590 | Ti::Matrix { .. }
591 | Ti::Atomic(_)
592 | Ti::Pointer { .. }
593 | Ti::ValuePointer { .. } => self.name.is_some(),
594 // composite types are better to be aliased, regardless of the name
595 Ti::Struct { .. } | Ti::Array { .. } => true,
596 // handle types may be different, depending on the global var access, so we always inline them
597 Ti::Image { .. }
598 | Ti::Sampler { .. }
599 | Ti::AccelerationStructure { .. }
600 | Ti::RayQuery { .. }
601 | Ti::BindingArray { .. } => false,
602 }
603 }
604 }
605
606 #[derive(Clone, Copy)]
607 enum FunctionOrigin {
608 Handle(Handle<crate::Function>),
609 EntryPoint(proc::EntryPointIndex),
610 }
611
612 trait NameKeyExt {
613 fn local(origin: FunctionOrigin, local_handle: Handle<crate::LocalVariable>) -> NameKey {
614 match origin {
615 FunctionOrigin::Handle(handle) => NameKey::FunctionLocal(handle, local_handle),
616 FunctionOrigin::EntryPoint(idx) => NameKey::EntryPointLocal(idx, local_handle),
617 }
618 }
619
620 /// Return the name key for a local variable used by ReadZeroSkipWrite bounds-check
621 /// policy when it needs to produce a pointer-typed result for an OOB access. These
622 /// are unique per accessed type, so the second argument is a type handle. See docs
623 /// for [`crate::back::msl`].
624 fn oob_local_for_type(origin: FunctionOrigin, ty: Handle<crate::Type>) -> NameKey {
625 match origin {
626 FunctionOrigin::Handle(handle) => NameKey::FunctionOobLocal(handle, ty),
627 FunctionOrigin::EntryPoint(idx) => NameKey::EntryPointOobLocal(idx, ty),
628 }
629 }
630 }
631
632 impl NameKeyExt for NameKey {}
633
634 /// A level of detail argument.
635 ///
636 /// When [`BoundsCheckPolicy::Restrict`] applies to an [`ImageLoad`] access, we
637 /// save the clamped level of detail in a temporary variable whose name is based
638 /// on the handle of the `ImageLoad` expression. But for other policies, we just
639 /// use the expression directly.
640 ///
641 /// [`BoundsCheckPolicy::Restrict`]: index::BoundsCheckPolicy::Restrict
642 /// [`ImageLoad`]: crate::Expression::ImageLoad
643 #[derive(Clone, Copy)]
644 enum LevelOfDetail {
645 Direct(Handle<crate::Expression>),
646 Restricted(Handle<crate::Expression>),
647 }
648
649 /// Values needed to select a particular texel for [`ImageLoad`] and [`ImageStore`].
650 ///
651 /// When this is used in code paths unconcerned with the `Restrict` bounds check
652 /// policy, the `LevelOfDetail` enum introduces an unneeded match, since `level`
653 /// will always be either `None` or `Some(Direct(_))`. But this turns out not to
654 /// be too awkward. If that changes, we can revisit.
655 ///
656 /// [`ImageLoad`]: crate::Expression::ImageLoad
657 /// [`ImageStore`]: crate::Statement::ImageStore
658 struct TexelAddress {
659 coordinate: Handle<crate::Expression>,
660 array_index: Option<Handle<crate::Expression>>,
661 sample: Option<Handle<crate::Expression>>,
662 level: Option<LevelOfDetail>,
663 }
664
665 struct ExpressionContext<'a> {
666 function: &'a crate::Function,
667 origin: FunctionOrigin,
668 info: &'a valid::FunctionInfo,
669 module: &'a crate::Module,
670 mod_info: &'a valid::ModuleInfo,
671 pipeline_options: &'a PipelineOptions,
672 lang_version: (u8, u8),
673 policies: index::BoundsCheckPolicies,
674
675 /// The set of expressions used as indices in `ReadZeroSkipWrite`-policy
676 /// accesses. These may need to be cached in temporary variables. See
677 /// `index::find_checked_indexes` for details.
678 guarded_indices: HandleSet<crate::Expression>,
679 /// See [`Writer::gen_force_bounded_loop_statements`] for details.
680 force_loop_bounding: bool,
681 }
682
683 impl<'a> ExpressionContext<'a> {
684 fn resolve_type(&self, handle: Handle<crate::Expression>) -> &'a crate::TypeInner {
685 self.info[handle].ty.inner_with(&self.module.types)
686 }
687
688 /// Return true if calls to `image`'s `read` and `write` methods should supply a level of detail.
689 ///
690 /// Only mipmapped images need to specify a level of detail. Since 1D
691 /// textures cannot have mipmaps, MSL requires that the level argument to
692 /// texture1d queries and accesses must be a constexpr 0. It's easiest
693 /// just to omit the level entirely for 1D textures.
694 fn image_needs_lod(&self, image: Handle<crate::Expression>) -> bool {
695 let image_ty = self.resolve_type(image);
696 if let crate::TypeInner::Image { dim, class, .. } = *image_ty {
697 class.is_mipmapped() && dim != crate::ImageDimension::D1
698 } else {
699 false
700 }
701 }
702
703 fn choose_bounds_check_policy(
704 &self,
705 pointer: Handle<crate::Expression>,
706 ) -> index::BoundsCheckPolicy {
707 self.policies
708 .choose_policy(pointer, &self.module.types, self.info)
709 }
710
711 /// See docs for [`proc::index::access_needs_check`].
712 fn access_needs_check(
713 &self,
714 base: Handle<crate::Expression>,
715 index: index::GuardedIndex,
716 ) -> Option<index::IndexableLength> {
717 index::access_needs_check(
718 base,
719 index,
720 self.module,
721 &self.function.expressions,
722 self.info,
723 )
724 }
725
726 /// See docs for [`proc::index::bounds_check_iter`].
727 fn bounds_check_iter(
728 &self,
729 chain: Handle<crate::Expression>,
730 ) -> impl Iterator<Item = BoundsCheck> + '_ {
731 index::bounds_check_iter(chain, self.module, self.function, self.info)
732 }
733
734 /// See docs for [`proc::index::oob_local_types`].
735 fn oob_local_types(&self) -> FastHashSet<Handle<crate::Type>> {
736 index::oob_local_types(self.module, self.function, self.info, self.policies)
737 }
738
739 fn get_packed_vec_kind(&self, expr_handle: Handle<crate::Expression>) -> Option<crate::Scalar> {
740 match self.function.expressions[expr_handle] {
741 crate::Expression::AccessIndex { base, index } => {
742 let ty = match *self.resolve_type(base) {
743 crate::TypeInner::Pointer { base, .. } => &self.module.types[base].inner,
744 ref ty => ty,
745 };
746 match *ty {
747 crate::TypeInner::Struct {
748 ref members, span, ..
749 } => should_pack_struct_member(members, span, index as usize, self.module),
750 _ => None,
751 }
752 }
753 _ => None,
754 }
755 }
756 }
757
758 struct StatementContext<'a> {
759 expression: ExpressionContext<'a>,
760 result_struct: Option<&'a str>,
761 }
762
763 impl<W: Write> Writer<W> {
764 /// Creates a new `Writer` instance.
765 pub fn new(out: W) -> Self {
766 Writer {
767 out,
768 names: FastHashMap::default(),
769 named_expressions: Default::default(),
770 need_bake_expressions: Default::default(),
771 namer: proc::Namer::default(),
772 wrapped_functions: FastHashSet::default(),
773 #[cfg(test)]
774 put_expression_stack_pointers: Default::default(),
775 #[cfg(test)]
776 put_block_stack_pointers: Default::default(),
777 struct_member_pads: FastHashSet::default(),
778 }
779 }
780
781 /// Finishes writing and returns the output.
782 // See https://github.com/rust-lang/rust-clippy/issues/4979.
783 #[allow(clippy::missing_const_for_fn)]
784 pub fn finish(self) -> W {
785 self.out
786 }
787
788 /// Generates statements to be inserted immediately before and at the very
789 /// start of the body of each loop, to defeat MSL infinite loop reasoning.
790 /// The 0th item of the returned tuple should be inserted immediately prior
791 /// to the loop and the 1st item should be inserted at the very start of
792 /// the loop body.
793 ///
794 /// # What is this trying to solve?
795 ///
796 /// In Metal Shading Language, an infinite loop has undefined behavior.
797 /// (This rule is inherited from C++14.) This means that, if the MSL
798 /// compiler determines that a given loop will never exit, it may assume
799 /// that it is never reached. It may thus assume that any conditions
800 /// sufficient to cause the loop to be reached must be false. Like many
801 /// optimizing compilers, MSL uses this kind of analysis to establish limits
802 /// on the range of values variables involved in those conditions might
803 /// hold.
804 ///
805 /// For example, suppose the MSL compiler sees the code:
806 ///
807 /// ```ignore
808 /// if (i >= 10) {
809 /// while (true) { }
810 /// }
811 /// ```
812 ///
813 /// It will recognize that the `while` loop will never terminate, conclude
814 /// that it must be unreachable, and thus infer that, if this code is
815 /// reached, then `i < 10` at that point.
816 ///
817 /// Now suppose that, at some point where `i` has the same value as above,
818 /// the compiler sees the code:
819 ///
820 /// ```ignore
821 /// if (i < 10) {
822 /// a[i] = 1;
823 /// }
824 /// ```
825 ///
826 /// Because the compiler is confident that `i < 10`, it will make the
827 /// assignment to `a[i]` unconditional, rewriting this code as, simply:
828 ///
829 /// ```ignore
830 /// a[i] = 1;
831 /// ```
832 ///
833 /// If that `if` condition was injected by Naga to implement a bounds check,
834 /// the MSL compiler's optimizations could allow out-of-bounds array
835 /// accesses to occur.
836 ///
837 /// Naga cannot feasibly anticipate whether the MSL compiler will determine
838 /// that a loop is infinite, so an attacker could craft a Naga module
839 /// containing an infinite loop protected by conditions that cause the Metal
840 /// compiler to remove bounds checks that Naga injected elsewhere in the
841 /// function.
842 ///
843 /// This rewrite could occur even if the conditional assignment appears
844 /// *before* the `while` loop, as long as `i < 10` by the time the loop is
845 /// reached. This would allow the attacker to save the results of
846 /// unauthorized reads somewhere accessible before entering the infinite
847 /// loop. But even worse, the MSL compiler has been observed to simply
848 /// delete the infinite loop entirely, so that even code dominated by the
849 /// loop becomes reachable. This would make the attack even more flexible,
850 /// since shaders that would appear to never terminate would actually exit
851 /// nicely, after having stolen data from elsewhere in the GPU address
852 /// space.
853 ///
854 /// To avoid UB, Naga must persuade the MSL compiler that no loop Naga
855 /// generates is infinite. One approach would be to add inline assembly to
856 /// each loop that is annotated as potentially branching out of the loop,
857 /// but which in fact generates no instructions. Unfortunately, inline
858 /// assembly is not handled correctly by some Metal device drivers.
859 ///
860 /// A previously used approach was to add the following code to the bottom
861 /// of every loop:
862 ///
863 /// ```ignore
864 /// if (volatile bool unpredictable = false; unpredictable)
865 /// break;
866 /// ```
867 ///
868 /// Although the `if` condition will always be false in any real execution,
869 /// the `volatile` qualifier prevents the compiler from assuming this. Thus,
870 /// it must assume that the `break` might be reached, and hence that the
871 /// loop is not unbounded. This prevents the range analysis impact described
872 /// above. Unfortunately this prevented the compiler from making important,
873 /// and safe, optimizations such as loop unrolling and was observed to
874 /// significantly hurt performance.
875 ///
876 /// Our current approach declares a counter before every loop and
877 /// increments it every iteration, breaking after 2^64 iterations:
878 ///
879 /// ```ignore
880 /// uint2 loop_bound = uint2(0);
881 /// while (true) {
882 /// if (metal::all(loop_bound == uint2(4294967295))) { break; }
883 /// loop_bound += uint2(loop_bound.y == 4294967295, 1);
884 /// }
885 /// ```
886 ///
887 /// This convinces the compiler that the loop is finite and therefore may
888 /// execute, whilst at the same time allowing optimizations such as loop
889 /// unrolling. Furthermore the 64-bit counter is large enough it seems
890 /// implausible that it would affect the execution of any shader.
891 ///
892 /// This approach is also used by Chromium WebGPU's Dawn shader compiler:
893 /// <https://dawn.googlesource.com/dawn/+/d9e2d1f718678ebee0728b999830576c410cce0a/src/tint/lang/core/ir/transform/prevent_infinite_loops.cc>
894 fn gen_force_bounded_loop_statements(
895 &mut self,
896 level: back::Level,
897 context: &StatementContext,
898 ) -> Option<(String, String)> {
899 if !context.expression.force_loop_bounding {
900 return None;
901 }
902
903 let loop_bound_name = self.namer.call("loop_bound");
904 // Count down from u32::MAX rather than up from 0 to avoid hang on
905 // certain Intel drivers. See <https://github.com/gfx-rs/wgpu/issues/7319>.
906 let decl = format!("{level}uint2 {loop_bound_name} = uint2({}u);", u32::MAX);
907 let level = level.next();
908 let break_and_inc = format!(
909 "{level}if ({NAMESPACE}::all({loop_bound_name} == uint2(0u))) {{ break; }}
910 {level}{loop_bound_name} -= uint2({loop_bound_name}.y == 0u, 1u);"
911 );
912
913 Some((decl, break_and_inc))
914 }
915
916 fn put_call_parameters(
917 &mut self,
918 parameters: impl Iterator<Item = Handle<crate::Expression>>,
919 context: &ExpressionContext,
920 ) -> BackendResult {
921 self.put_call_parameters_impl(parameters, context, |writer, context, expr| {
922 writer.put_expression(expr, context, true)
923 })
924 }
925
926 fn put_call_parameters_impl<C, E>(
927 &mut self,
928 parameters: impl Iterator<Item = Handle<crate::Expression>>,
929 ctx: &C,
930 put_expression: E,
931 ) -> BackendResult
932 where
933 E: Fn(&mut Self, &C, Handle<crate::Expression>) -> BackendResult,
934 {
935 write!(self.out, "(")?;
936 for (i, handle) in parameters.enumerate() {
937 if i != 0 {
938 write!(self.out, ", ")?;
939 }
940 put_expression(self, ctx, handle)?;
941 }
942 write!(self.out, ")")?;
943 Ok(())
944 }
945
946 /// Writes the local variables of the given function, as well as any extra
947 /// out-of-bounds locals that are needed.
948 ///
949 /// The names of the OOB locals are also added to `self.names` at the same
950 /// time.
951 fn put_locals(&mut self, context: &ExpressionContext) -> BackendResult {
952 let oob_local_types = context.oob_local_types();
953 for &ty in oob_local_types.iter() {
954 let name_key = NameKey::oob_local_for_type(context.origin, ty);
955 self.names.insert(name_key, self.namer.call("oob"));
956 }
957
958 for (name_key, ty, init) in context
959 .function
960 .local_variables
961 .iter()
962 .map(|(local_handle, local)| {
963 let name_key = NameKey::local(context.origin, local_handle);
964 (name_key, local.ty, local.init)
965 })
966 .chain(oob_local_types.iter().map(|&ty| {
967 let name_key = NameKey::oob_local_for_type(context.origin, ty);
968 (name_key, ty, None)
969 }))
970 {
971 let ty_name = TypeContext {
972 handle: ty,
973 gctx: context.module.to_ctx(),
974 names: &self.names,
975 access: crate::StorageAccess::empty(),
976 first_time: false,
977 };
978 write!(
979 self.out,
980 "{}{} {}",
981 back::INDENT,
982 ty_name,
983 self.names[&name_key]
984 )?;
985 match init {
986 Some(value) => {
987 write!(self.out, " = ")?;
988 self.put_expression(value, context, true)?;
989 }
990 None => {
991 write!(self.out, " = {{}}")?;
992 }
993 };
994 writeln!(self.out, ";")?;
995 }
996 Ok(())
997 }
998
999 fn put_level_of_detail(
1000 &mut self,
1001 level: LevelOfDetail,
1002 context: &ExpressionContext,
1003 ) -> BackendResult {
1004 match level {
1005 LevelOfDetail::Direct(expr) => self.put_expression(expr, context, true)?,
1006 LevelOfDetail::Restricted(load) => write!(self.out, "{}", ClampedLod(load))?,
1007 }
1008 Ok(())
1009 }
1010
1011 fn put_image_query(
1012 &mut self,
1013 image: Handle<crate::Expression>,
1014 query: &str,
1015 level: Option<LevelOfDetail>,
1016 context: &ExpressionContext,
1017 ) -> BackendResult {
1018 self.put_expression(image, context, false)?;
1019 write!(self.out, ".get_{query}(")?;
1020 if let Some(level) = level {
1021 self.put_level_of_detail(level, context)?;
1022 }
1023 write!(self.out, ")")?;
1024 Ok(())
1025 }
1026
1027 fn put_image_size_query(
1028 &mut self,
1029 image: Handle<crate::Expression>,
1030 level: Option<LevelOfDetail>,
1031 kind: crate::ScalarKind,
1032 context: &ExpressionContext,
1033 ) -> BackendResult {
1034 //Note: MSL only has separate width/height/depth queries,
1035 // so compose the result of them.
1036 let dim = match *context.resolve_type(image) {
1037 crate::TypeInner::Image { dim, .. } => dim,
1038 ref other => unreachable!("Unexpected type {:?}", other),
1039 };
1040 let scalar = crate::Scalar { kind, width: 4 };
1041 let coordinate_type = scalar.to_msl_name();
1042 match dim {
1043 crate::ImageDimension::D1 => {
1044 // Since 1D textures never have mipmaps, MSL requires that the
1045 // `level` argument be a constexpr 0. It's simplest for us just
1046 // to pass `None` and omit the level entirely.
1047 if kind == crate::ScalarKind::Uint {
1048 // No need to construct a vector. No cast needed.
1049 self.put_image_query(image, "width", None, context)?;
1050 } else {
1051 // There's no definition for `int` in the `metal` namespace.
1052 write!(self.out, "int(")?;
1053 self.put_image_query(image, "width", None, context)?;
1054 write!(self.out, ")")?;
1055 }
1056 }
1057 crate::ImageDimension::D2 => {
1058 write!(self.out, "{NAMESPACE}::{coordinate_type}2(")?;
1059 self.put_image_query(image, "width", level, context)?;
1060 write!(self.out, ", ")?;
1061 self.put_image_query(image, "height", level, context)?;
1062 write!(self.out, ")")?;
1063 }
1064 crate::ImageDimension::D3 => {
1065 write!(self.out, "{NAMESPACE}::{coordinate_type}3(")?;
1066 self.put_image_query(image, "width", level, context)?;
1067 write!(self.out, ", ")?;
1068 self.put_image_query(image, "height", level, context)?;
1069 write!(self.out, ", ")?;
1070 self.put_image_query(image, "depth", level, context)?;
1071 write!(self.out, ")")?;
1072 }
1073 crate::ImageDimension::Cube => {
1074 write!(self.out, "{NAMESPACE}::{coordinate_type}2(")?;
1075 self.put_image_query(image, "width", level, context)?;
1076 write!(self.out, ")")?;
1077 }
1078 }
1079 Ok(())
1080 }
1081
1082 fn put_cast_to_uint_scalar_or_vector(
1083 &mut self,
1084 expr: Handle<crate::Expression>,
1085 context: &ExpressionContext,
1086 ) -> BackendResult {
1087 // coordinates in IR are int, but Metal expects uint
1088 match *context.resolve_type(expr) {
1089 crate::TypeInner::Scalar(_) => {
1090 put_numeric_type(&mut self.out, crate::Scalar::U32, &[])?
1091 }
1092 crate::TypeInner::Vector { size, .. } => {
1093 put_numeric_type(&mut self.out, crate::Scalar::U32, &[size])?
1094 }
1095 _ => {
1096 return Err(Error::GenericValidation(
1097 "Invalid type for image coordinate".into(),
1098 ))
1099 }
1100 };
1101
1102 write!(self.out, "(")?;
1103 self.put_expression(expr, context, true)?;
1104 write!(self.out, ")")?;
1105 Ok(())
1106 }
1107
1108 fn put_image_sample_level(
1109 &mut self,
1110 image: Handle<crate::Expression>,
1111 level: crate::SampleLevel,
1112 context: &ExpressionContext,
1113 ) -> BackendResult {
1114 let has_levels = context.image_needs_lod(image);
1115 match level {
1116 crate::SampleLevel::Auto => {}
1117 crate::SampleLevel::Zero => {
1118 //TODO: do we support Zero on `Sampled` image classes?
1119 }
1120 _ if !has_levels => {
1121 log::warn!("1D image can't be sampled with level {:?}", level);
1122 }
1123 crate::SampleLevel::Exact(h) => {
1124 write!(self.out, ", {NAMESPACE}::level(")?;
1125 self.put_expression(h, context, true)?;
1126 write!(self.out, ")")?;
1127 }
1128 crate::SampleLevel::Bias(h) => {
1129 write!(self.out, ", {NAMESPACE}::bias(")?;
1130 self.put_expression(h, context, true)?;
1131 write!(self.out, ")")?;
1132 }
1133 crate::SampleLevel::Gradient { x, y } => {
1134 write!(self.out, ", {NAMESPACE}::gradient2d(")?;
1135 self.put_expression(x, context, true)?;
1136 write!(self.out, ", ")?;
1137 self.put_expression(y, context, true)?;
1138 write!(self.out, ")")?;
1139 }
1140 }
1141 Ok(())
1142 }
1143
1144 fn put_image_coordinate_limits(
1145 &mut self,
1146 image: Handle<crate::Expression>,
1147 level: Option<LevelOfDetail>,
1148 context: &ExpressionContext,
1149 ) -> BackendResult {
1150 self.put_image_size_query(image, level, crate::ScalarKind::Uint, context)?;
1151 write!(self.out, " - 1")?;
1152 Ok(())
1153 }
1154
1155 /// General function for writing restricted image indexes.
1156 ///
1157 /// This is used to produce restricted mip levels, array indices, and sample
1158 /// indices for [`ImageLoad`] and [`ImageStore`] accesses under the
1159 /// [`Restrict`] bounds check policy.
1160 ///
1161 /// This function writes an expression of the form:
1162 ///
1163 /// ```ignore
1164 ///
1165 /// metal::min(uint(INDEX), IMAGE.LIMIT_METHOD() - 1)
1166 ///
1167 /// ```
1168 ///
1169 /// [`ImageLoad`]: crate::Expression::ImageLoad
1170 /// [`ImageStore`]: crate::Statement::ImageStore
1171 /// [`Restrict`]: index::BoundsCheckPolicy::Restrict
1172 fn put_restricted_scalar_image_index(
1173 &mut self,
1174 image: Handle<crate::Expression>,
1175 index: Handle<crate::Expression>,
1176 limit_method: &str,
1177 context: &ExpressionContext,
1178 ) -> BackendResult {
1179 write!(self.out, "{NAMESPACE}::min(uint(")?;
1180 self.put_expression(index, context, true)?;
1181 write!(self.out, "), ")?;
1182 self.put_expression(image, context, false)?;
1183 write!(self.out, ".{limit_method}() - 1)")?;
1184 Ok(())
1185 }
1186
1187 fn put_restricted_texel_address(
1188 &mut self,
1189 image: Handle<crate::Expression>,
1190 address: &TexelAddress,
1191 context: &ExpressionContext,
1192 ) -> BackendResult {
1193 // Write the coordinate.
1194 write!(self.out, "{NAMESPACE}::min(")?;
1195 self.put_cast_to_uint_scalar_or_vector(address.coordinate, context)?;
1196 write!(self.out, ", ")?;
1197 self.put_image_coordinate_limits(image, address.level, context)?;
1198 write!(self.out, ")")?;
1199
1200 // Write the array index, if present.
1201 if let Some(array_index) = address.array_index {
1202 write!(self.out, ", ")?;
1203 self.put_restricted_scalar_image_index(image, array_index, "get_array_size", context)?;
1204 }
1205
1206 // Write the sample index, if present.
1207 if let Some(sample) = address.sample {
1208 write!(self.out, ", ")?;
1209 self.put_restricted_scalar_image_index(image, sample, "get_num_samples", context)?;
1210 }
1211
1212 // The level of detail should be clamped and cached by
1213 // `put_cache_restricted_level`, so we don't need to clamp it here.
1214 if let Some(level) = address.level {
1215 write!(self.out, ", ")?;
1216 self.put_level_of_detail(level, context)?;
1217 }
1218
1219 Ok(())
1220 }
1221
1222 /// Write an expression that is true if the given image access is in bounds.
1223 fn put_image_access_bounds_check(
1224 &mut self,
1225 image: Handle<crate::Expression>,
1226 address: &TexelAddress,
1227 context: &ExpressionContext,
1228 ) -> BackendResult {
1229 let mut conjunction = "";
1230
1231 // First, check the level of detail. Only if that is in bounds can we
1232 // use it to find the appropriate bounds for the coordinates.
1233 let level = if let Some(level) = address.level {
1234 write!(self.out, "uint(")?;
1235 self.put_level_of_detail(level, context)?;
1236 write!(self.out, ") < ")?;
1237 self.put_expression(image, context, true)?;
1238 write!(self.out, ".get_num_mip_levels()")?;
1239 conjunction = " && ";
1240 Some(level)
1241 } else {
1242 None
1243 };
1244
1245 // Check sample index, if present.
1246 if let Some(sample) = address.sample {
1247 write!(self.out, "uint(")?;
1248 self.put_expression(sample, context, true)?;
1249 write!(self.out, ") < ")?;
1250 self.put_expression(image, context, true)?;
1251 write!(self.out, ".get_num_samples()")?;
1252 conjunction = " && ";
1253 }
1254
1255 // Check array index, if present.
1256 if let Some(array_index) = address.array_index {
1257 write!(self.out, "{conjunction}uint(")?;
1258 self.put_expression(array_index, context, true)?;
1259 write!(self.out, ") < ")?;
1260 self.put_expression(image, context, true)?;
1261 write!(self.out, ".get_array_size()")?;
1262 conjunction = " && ";
1263 }
1264
1265 // Finally, check if the coordinates are within bounds.
1266 let coord_is_vector = match *context.resolve_type(address.coordinate) {
1267 crate::TypeInner::Vector { .. } => true,
1268 _ => false,
1269 };
1270 write!(self.out, "{conjunction}")?;
1271 if coord_is_vector {
1272 write!(self.out, "{NAMESPACE}::all(")?;
1273 }
1274 self.put_cast_to_uint_scalar_or_vector(address.coordinate, context)?;
1275 write!(self.out, " < ")?;
1276 self.put_image_size_query(image, level, crate::ScalarKind::Uint, context)?;
1277 if coord_is_vector {
1278 write!(self.out, ")")?;
1279 }
1280
1281 Ok(())
1282 }
1283
1284 fn put_image_load(
1285 &mut self,
1286 load: Handle<crate::Expression>,
1287 image: Handle<crate::Expression>,
1288 mut address: TexelAddress,
1289 context: &ExpressionContext,
1290 ) -> BackendResult {
1291 match context.policies.image_load {
1292 proc::BoundsCheckPolicy::Restrict => {
1293 // Use the cached restricted level of detail, if any. Omit the
1294 // level altogether for 1D textures.
1295 if address.level.is_some() {
1296 address.level = if context.image_needs_lod(image) {
1297 Some(LevelOfDetail::Restricted(load))
1298 } else {
1299 None
1300 }
1301 }
1302
1303 self.put_expression(image, context, false)?;
1304 write!(self.out, ".read(")?;
1305 self.put_restricted_texel_address(image, &address, context)?;
1306 write!(self.out, ")")?;
1307 }
1308 proc::BoundsCheckPolicy::ReadZeroSkipWrite => {
1309 write!(self.out, "(")?;
1310 self.put_image_access_bounds_check(image, &address, context)?;
1311 write!(self.out, " ? ")?;
1312 self.put_unchecked_image_load(image, &address, context)?;
1313 write!(self.out, ": DefaultConstructible())")?;
1314 }
1315 proc::BoundsCheckPolicy::Unchecked => {
1316 self.put_unchecked_image_load(image, &address, context)?;
1317 }
1318 }
1319
1320 Ok(())
1321 }
1322
1323 fn put_unchecked_image_load(
1324 &mut self,
1325 image: Handle<crate::Expression>,
1326 address: &TexelAddress,
1327 context: &ExpressionContext,
1328 ) -> BackendResult {
1329 self.put_expression(image, context, false)?;
1330 write!(self.out, ".read(")?;
1331 // coordinates in IR are int, but Metal expects uint
1332 self.put_cast_to_uint_scalar_or_vector(address.coordinate, context)?;
1333 if let Some(expr) = address.array_index {
1334 write!(self.out, ", ")?;
1335 self.put_expression(expr, context, true)?;
1336 }
1337 if let Some(sample) = address.sample {
1338 write!(self.out, ", ")?;
1339 self.put_expression(sample, context, true)?;
1340 }
1341 if let Some(level) = address.level {
1342 if context.image_needs_lod(image) {
1343 write!(self.out, ", ")?;
1344 self.put_level_of_detail(level, context)?;
1345 }
1346 }
1347 write!(self.out, ")")?;
1348
1349 Ok(())
1350 }
1351
1352 fn put_image_atomic(
1353 &mut self,
1354 level: back::Level,
1355 image: Handle<crate::Expression>,
1356 address: &TexelAddress,
1357 fun: crate::AtomicFunction,
1358 value: Handle<crate::Expression>,
1359 context: &StatementContext,
1360 ) -> BackendResult {
1361 write!(self.out, "{level}")?;
1362 self.put_expression(image, &context.expression, false)?;
1363 let op = if context.expression.resolve_type(value).scalar_width() == Some(8) {
1364 fun.to_msl_64_bit()?
1365 } else {
1366 fun.to_msl()
1367 };
1368 write!(self.out, ".atomic_{}(", op)?;
1369 // coordinates in IR are int, but Metal expects uint
1370 self.put_cast_to_uint_scalar_or_vector(address.coordinate, &context.expression)?;
1371 write!(self.out, ", ")?;
1372 self.put_expression(value, &context.expression, true)?;
1373 writeln!(self.out, ");")?;
1374
1375 Ok(())
1376 }
1377
1378 fn put_image_store(
1379 &mut self,
1380 level: back::Level,
1381 image: Handle<crate::Expression>,
1382 address: &TexelAddress,
1383 value: Handle<crate::Expression>,
1384 context: &StatementContext,
1385 ) -> BackendResult {
1386 write!(self.out, "{level}")?;
1387 self.put_expression(image, &context.expression, false)?;
1388 write!(self.out, ".write(")?;
1389 self.put_expression(value, &context.expression, true)?;
1390 write!(self.out, ", ")?;
1391 // coordinates in IR are int, but Metal expects uint
1392 self.put_cast_to_uint_scalar_or_vector(address.coordinate, &context.expression)?;
1393 if let Some(expr) = address.array_index {
1394 write!(self.out, ", ")?;
1395 self.put_expression(expr, &context.expression, true)?;
1396 }
1397 writeln!(self.out, ");")?;
1398
1399 Ok(())
1400 }
1401
1402 /// Write the maximum valid index of the dynamically sized array at the end of `handle`.
1403 ///
1404 /// The 'maximum valid index' is simply one less than the array's length.
1405 ///
1406 /// This emits an expression of the form `a / b`, so the caller must
1407 /// parenthesize its output if it will be applying operators of higher
1408 /// precedence.
1409 ///
1410 /// `handle` must be the handle of a global variable whose final member is a
1411 /// dynamically sized array.
1412 fn put_dynamic_array_max_index(
1413 &mut self,
1414 handle: Handle<crate::GlobalVariable>,
1415 context: &ExpressionContext,
1416 ) -> BackendResult {
1417 let global = &context.module.global_variables[handle];
1418 let (offset, array_ty) = match context.module.types[global.ty].inner {
1419 crate::TypeInner::Struct { ref members, .. } => match members.last() {
1420 Some(&crate::StructMember { offset, ty, .. }) => (offset, ty),
1421 None => return Err(Error::GenericValidation("Struct has no members".into())),
1422 },
1423 crate::TypeInner::Array {
1424 size: crate::ArraySize::Dynamic,
1425 ..
1426 } => (0, global.ty),
1427 ref ty => {
1428 return Err(Error::GenericValidation(format!(
1429 "Expected type with dynamic array, got {ty:?}"
1430 )))
1431 }
1432 };
1433
1434 let (size, stride) = match context.module.types[array_ty].inner {
1435 crate::TypeInner::Array { base, stride, .. } => (
1436 context.module.types[base]
1437 .inner
1438 .size(context.module.to_ctx()),
1439 stride,
1440 ),
1441 ref ty => {
1442 return Err(Error::GenericValidation(format!(
1443 "Expected array type, got {ty:?}"
1444 )))
1445 }
1446 };
1447
1448 // When the stride length is larger than the size, the final element's stride of
1449 // bytes would have padding following the value. But the buffer size in
1450 // `buffer_sizes.sizeN` may not include this padding - it only needs to be large
1451 // enough to hold the actual values' bytes.
1452 //
1453 // So subtract off the size to get a byte size that falls at the start or within
1454 // the final element. Then divide by the stride size, to get one less than the
1455 // length, and then add one. This works even if the buffer size does include the
1456 // stride padding, since division rounds towards zero (MSL 2.4 §6.1). It will fail
1457 // if there are zero elements in the array, but the WebGPU `validating shader binding`
1458 // rules, together with draw-time validation when `minBindingSize` is zero,
1459 // prevent that.
1460 write!(
1461 self.out,
1462 "(_buffer_sizes.{member} - {offset} - {size}) / {stride}",
1463 member = ArraySizeMember(handle),
1464 offset = offset,
1465 size = size,
1466 stride = stride,
1467 )?;
1468 Ok(())
1469 }
1470
1471 /// Emit code for the arithmetic expression of the dot product.
1472 ///
1473 /// The argument `extractor` is a function that accepts a `Writer`, a handle to a vector,
1474 /// and an index. writes out the expression for the component at that index.
1475 fn put_dot_product(
1476 &mut self,
1477 arg: Handle<crate::Expression>,
1478 arg1: Handle<crate::Expression>,
1479 size: usize,
1480 extractor: impl Fn(&mut Self, Handle<crate::Expression>, usize) -> BackendResult,
1481 ) -> BackendResult {
1482 // Write parentheses around the dot product expression to prevent operators
1483 // with different precedences from applying earlier.
1484 write!(self.out, "(")?;
1485
1486 // Cycle through all the components of the vector
1487 for index in 0..size {
1488 // Write the addition to the previous product
1489 // This will print an extra '+' at the beginning but that is fine in msl
1490 write!(self.out, " + ")?;
1491 extractor(self, arg, index)?;
1492 write!(self.out, " * ")?;
1493 extractor(self, arg1, index)?;
1494 }
1495
1496 write!(self.out, ")")?;
1497 Ok(())
1498 }
1499
1500 /// Emit code for the isign expression.
1501 ///
1502 fn put_isign(
1503 &mut self,
1504 arg: Handle<crate::Expression>,
1505 context: &ExpressionContext,
1506 ) -> BackendResult {
1507 write!(self.out, "{NAMESPACE}::select({NAMESPACE}::select(")?;
1508 let scalar = context
1509 .resolve_type(arg)
1510 .scalar()
1511 .expect("put_isign should only be called for args which have an integer scalar type")
1512 .to_msl_name();
1513 match context.resolve_type(arg) {
1514 &crate::TypeInner::Vector { size, .. } => {
1515 let size = common::vector_size_str(size);
1516 write!(self.out, "{scalar}{size}(-1), {scalar}{size}(1)")?;
1517 }
1518 _ => {
1519 write!(self.out, "{scalar}(-1), {scalar}(1)")?;
1520 }
1521 }
1522 write!(self.out, ", (")?;
1523 self.put_expression(arg, context, true)?;
1524 write!(self.out, " > 0)), {scalar}(0), (")?;
1525 self.put_expression(arg, context, true)?;
1526 write!(self.out, " == 0))")?;
1527 Ok(())
1528 }
1529
1530 fn put_const_expression(
1531 &mut self,
1532 expr_handle: Handle<crate::Expression>,
1533 module: &crate::Module,
1534 mod_info: &valid::ModuleInfo,
1535 arena: &crate::Arena<crate::Expression>,
1536 ) -> BackendResult {
1537 self.put_possibly_const_expression(
1538 expr_handle,
1539 arena,
1540 module,
1541 mod_info,
1542 &(module, mod_info),
1543 |&(_, mod_info), expr| &mod_info[expr],
1544 |writer, &(module, _), expr| writer.put_const_expression(expr, module, mod_info, arena),
1545 )
1546 }
1547
1548 fn put_literal(&mut self, literal: crate::Literal) -> BackendResult {
1549 match literal {
1550 crate::Literal::F64(_) => {
1551 return Err(Error::CapabilityNotSupported(valid::Capabilities::FLOAT64))
1552 }
1553 crate::Literal::F16(value) => {
1554 if value.is_infinite() {
1555 let sign = if value.is_sign_negative() { "-" } else { "" };
1556 write!(self.out, "{sign}INFINITY")?;
1557 } else if value.is_nan() {
1558 write!(self.out, "NAN")?;
1559 } else {
1560 let suffix = if value.fract() == f16::from_f32(0.0) {
1561 ".0h"
1562 } else {
1563 "h"
1564 };
1565 write!(self.out, "{value}{suffix}")?;
1566 }
1567 }
1568 crate::Literal::F32(value) => {
1569 if value.is_infinite() {
1570 let sign = if value.is_sign_negative() { "-" } else { "" };
1571 write!(self.out, "{sign}INFINITY")?;
1572 } else if value.is_nan() {
1573 write!(self.out, "NAN")?;
1574 } else {
1575 let suffix = if value.fract() == 0.0 { ".0" } else { "" };
1576 write!(self.out, "{value}{suffix}")?;
1577 }
1578 }
1579 crate::Literal::U32(value) => {
1580 write!(self.out, "{value}u")?;
1581 }
1582 crate::Literal::I32(value) => {
1583 // `-2147483648` is parsed as unary negation of positive 2147483648.
1584 // 2147483648 is too large for int32_t meaning the expression gets
1585 // promoted to a int64_t which is not our intention. Avoid this by instead
1586 // using `-2147483647 - 1`.
1587 if value == i32::MIN {
1588 write!(self.out, "({} - 1)", value + 1)?;
1589 } else {
1590 write!(self.out, "{value}")?;
1591 }
1592 }
1593 crate::Literal::U64(value) => {
1594 write!(self.out, "{value}uL")?;
1595 }
1596 crate::Literal::I64(value) => {
1597 // `-9223372036854775808` is parsed as unary negation of positive
1598 // 9223372036854775808. 9223372036854775808 is too large for int64_t
1599 // causing Metal to emit a `-Wconstant-conversion` warning, and change the
1600 // value to `-9223372036854775808`. Which would then be negated, possibly
1601 // causing undefined behaviour. Avoid this by instead using
1602 // `-9223372036854775808L - 1L`.
1603 if value == i64::MIN {
1604 write!(self.out, "({}L - 1L)", value + 1)?;
1605 } else {
1606 write!(self.out, "{value}L")?;
1607 }
1608 }
1609 crate::Literal::Bool(value) => {
1610 write!(self.out, "{value}")?;
1611 }
1612 crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => {
1613 return Err(Error::GenericValidation(
1614 "Unsupported abstract literal".into(),
1615 ));
1616 }
1617 }
1618 Ok(())
1619 }
1620
1621 #[allow(clippy::too_many_arguments)]
1622 fn put_possibly_const_expression<C, I, E>(
1623 &mut self,
1624 expr_handle: Handle<crate::Expression>,
1625 expressions: &crate::Arena<crate::Expression>,
1626 module: &crate::Module,
1627 mod_info: &valid::ModuleInfo,
1628 ctx: &C,
1629 get_expr_ty: I,
1630 put_expression: E,
1631 ) -> BackendResult
1632 where
1633 I: Fn(&C, Handle<crate::Expression>) -> &TypeResolution,
1634 E: Fn(&mut Self, &C, Handle<crate::Expression>) -> BackendResult,
1635 {
1636 match expressions[expr_handle] {
1637 crate::Expression::Literal(literal) => {
1638 self.put_literal(literal)?;
1639 }
1640 crate::Expression::Constant(handle) => {
1641 let constant = &module.constants[handle];
1642 if constant.name.is_some() {
1643 write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?;
1644 } else {
1645 self.put_const_expression(
1646 constant.init,
1647 module,
1648 mod_info,
1649 &module.global_expressions,
1650 )?;
1651 }
1652 }
1653 crate::Expression::ZeroValue(ty) => {
1654 let ty_name = TypeContext {
1655 handle: ty,
1656 gctx: module.to_ctx(),
1657 names: &self.names,
1658 access: crate::StorageAccess::empty(),
1659 first_time: false,
1660 };
1661 write!(self.out, "{ty_name} {{}}")?;
1662 }
1663 crate::Expression::Compose { ty, ref components } => {
1664 let ty_name = TypeContext {
1665 handle: ty,
1666 gctx: module.to_ctx(),
1667 names: &self.names,
1668 access: crate::StorageAccess::empty(),
1669 first_time: false,
1670 };
1671 write!(self.out, "{ty_name}")?;
1672 match module.types[ty].inner {
1673 crate::TypeInner::Scalar(_)
1674 | crate::TypeInner::Vector { .. }
1675 | crate::TypeInner::Matrix { .. } => {
1676 self.put_call_parameters_impl(
1677 components.iter().copied(),
1678 ctx,
1679 put_expression,
1680 )?;
1681 }
1682 crate::TypeInner::Array { .. } | crate::TypeInner::Struct { .. } => {
1683 write!(self.out, " {{")?;
1684 for (index, &component) in components.iter().enumerate() {
1685 if index != 0 {
1686 write!(self.out, ", ")?;
1687 }
1688 // insert padding initialization, if needed
1689 if self.struct_member_pads.contains(&(ty, index as u32)) {
1690 write!(self.out, "{{}}, ")?;
1691 }
1692 put_expression(self, ctx, component)?;
1693 }
1694 write!(self.out, "}}")?;
1695 }
1696 _ => return Err(Error::UnsupportedCompose(ty)),
1697 }
1698 }
1699 crate::Expression::Splat { size, value } => {
1700 let scalar = match *get_expr_ty(ctx, value).inner_with(&module.types) {
1701 crate::TypeInner::Scalar(scalar) => scalar,
1702 ref ty => {
1703 return Err(Error::GenericValidation(format!(
1704 "Expected splat value type must be a scalar, got {ty:?}",
1705 )))
1706 }
1707 };
1708 put_numeric_type(&mut self.out, scalar, &[size])?;
1709 write!(self.out, "(")?;
1710 put_expression(self, ctx, value)?;
1711 write!(self.out, ")")?;
1712 }
1713 _ => {
1714 return Err(Error::Override);
1715 }
1716 }
1717
1718 Ok(())
1719 }
1720
1721 /// Emit code for the expression `expr_handle`.
1722 ///
1723 /// The `is_scoped` argument is true if the surrounding operators have the
1724 /// precedence of the comma operator, or lower. So, for example:
1725 ///
1726 /// - Pass `true` for `is_scoped` when writing function arguments, an
1727 /// expression statement, an initializer expression, or anything already
1728 /// wrapped in parenthesis.
1729 ///
1730 /// - Pass `false` if it is an operand of a `?:` operator, a `[]`, or really
1731 /// almost anything else.
1732 fn put_expression(
1733 &mut self,
1734 expr_handle: Handle<crate::Expression>,
1735 context: &ExpressionContext,
1736 is_scoped: bool,
1737 ) -> BackendResult {
1738 // Add to the set in order to track the stack size.
1739 #[cfg(test)]
1740 self.put_expression_stack_pointers
1741 .insert(ptr::from_ref(&expr_handle).cast());
1742
1743 if let Some(name) = self.named_expressions.get(&expr_handle) {
1744 write!(self.out, "{name}")?;
1745 return Ok(());
1746 }
1747
1748 let expression = &context.function.expressions[expr_handle];
1749 match *expression {
1750 crate::Expression::Literal(_)
1751 | crate::Expression::Constant(_)
1752 | crate::Expression::ZeroValue(_)
1753 | crate::Expression::Compose { .. }
1754 | crate::Expression::Splat { .. } => {
1755 self.put_possibly_const_expression(
1756 expr_handle,
1757 &context.function.expressions,
1758 context.module,
1759 context.mod_info,
1760 context,
1761 |context, expr: Handle<crate::Expression>| &context.info[expr].ty,
1762 |writer, context, expr| writer.put_expression(expr, context, true),
1763 )?;
1764 }
1765 crate::Expression::Override(_) => return Err(Error::Override),
1766 crate::Expression::Access { base, .. }
1767 | crate::Expression::AccessIndex { base, .. } => {
1768 // This is an acceptable place to generate a `ReadZeroSkipWrite` check.
1769 // Since `put_bounds_checks` and `put_access_chain` handle an entire
1770 // access chain at a time, recursing back through `put_expression` only
1771 // for index expressions and the base object, we will never see intermediate
1772 // `Access` or `AccessIndex` expressions here.
1773 let policy = context.choose_bounds_check_policy(base);
1774 if policy == index::BoundsCheckPolicy::ReadZeroSkipWrite
1775 && self.put_bounds_checks(
1776 expr_handle,
1777 context,
1778 back::Level(0),
1779 if is_scoped { "" } else { "(" },
1780 )?
1781 {
1782 write!(self.out, " ? ")?;
1783 self.put_access_chain(expr_handle, policy, context)?;
1784 write!(self.out, " : ")?;
1785
1786 if context.resolve_type(base).pointer_space().is_some() {
1787 // We can't just use `DefaultConstructible` if this is a pointer.
1788 // Instead, we create a dummy local variable to serve as pointer
1789 // target if the access is out of bounds.
1790 let result_ty = context.info[expr_handle]
1791 .ty
1792 .inner_with(&context.module.types)
1793 .pointer_base_type();
1794 let result_ty_handle = match result_ty {
1795 Some(TypeResolution::Handle(handle)) => handle,
1796 Some(TypeResolution::Value(_)) => {
1797 // As long as the result of a pointer access expression is
1798 // passed to a function or stored in a let binding, the
1799 // type will be in the arena. If additional uses of
1800 // pointers become valid, this assumption might no longer
1801 // hold. Note that the LHS of a load or store doesn't
1802 // take this path -- there is dedicated code in `put_load`
1803 // and `put_store`.
1804 unreachable!(
1805 "Expected type {result_ty:?} of access through pointer type {base:?} to be in the arena",
1806 );
1807 }
1808 None => {
1809 unreachable!(
1810 "Expected access through pointer type {base:?} to return a pointer, but got {result_ty:?}",
1811 )
1812 }
1813 };
1814 let name_key =
1815 NameKey::oob_local_for_type(context.origin, result_ty_handle);
1816 self.out.write_str(&self.names[&name_key])?;
1817 } else {
1818 write!(self.out, "DefaultConstructible()")?;
1819 }
1820
1821 if !is_scoped {
1822 write!(self.out, ")")?;
1823 }
1824 } else {
1825 self.put_access_chain(expr_handle, policy, context)?;
1826 }
1827 }
1828 crate::Expression::Swizzle {
1829 size,
1830 vector,
1831 pattern,
1832 } => {
1833 self.put_wrapped_expression_for_packed_vec3_access(
1834 vector,
1835 context,
1836 false,
1837 &Self::put_expression,
1838 )?;
1839 write!(self.out, ".")?;
1840 for &sc in pattern[..size as usize].iter() {
1841 write!(self.out, "{}", back::COMPONENTS[sc as usize])?;
1842 }
1843 }
1844 crate::Expression::FunctionArgument(index) => {
1845 let name_key = match context.origin {
1846 FunctionOrigin::Handle(handle) => NameKey::FunctionArgument(handle, index),
1847 FunctionOrigin::EntryPoint(ep_index) => {
1848 NameKey::EntryPointArgument(ep_index, index)
1849 }
1850 };
1851 let name = &self.names[&name_key];
1852 write!(self.out, "{name}")?;
1853 }
1854 crate::Expression::GlobalVariable(handle) => {
1855 let name = &self.names[&NameKey::GlobalVariable(handle)];
1856 write!(self.out, "{name}")?;
1857 }
1858 crate::Expression::LocalVariable(handle) => {
1859 let name_key = NameKey::local(context.origin, handle);
1860 let name = &self.names[&name_key];
1861 write!(self.out, "{name}")?;
1862 }
1863 crate::Expression::Load { pointer } => self.put_load(pointer, context, is_scoped)?,
1864 crate::Expression::ImageSample {
1865 image,
1866 sampler,
1867 gather,
1868 coordinate,
1869 array_index,
1870 offset,
1871 level,
1872 depth_ref,
1873 } => {
1874 let main_op = match gather {
1875 Some(_) => "gather",
1876 None => "sample",
1877 };
1878 let comparison_op = match depth_ref {
1879 Some(_) => "_compare",
1880 None => "",
1881 };
1882 self.put_expression(image, context, false)?;
1883 write!(self.out, ".{main_op}{comparison_op}(")?;
1884 self.put_expression(sampler, context, true)?;
1885 write!(self.out, ", ")?;
1886 self.put_expression(coordinate, context, true)?;
1887 if let Some(expr) = array_index {
1888 write!(self.out, ", ")?;
1889 self.put_expression(expr, context, true)?;
1890 }
1891 if let Some(dref) = depth_ref {
1892 write!(self.out, ", ")?;
1893 self.put_expression(dref, context, true)?;
1894 }
1895
1896 self.put_image_sample_level(image, level, context)?;
1897
1898 if let Some(offset) = offset {
1899 write!(self.out, ", ")?;
1900 self.put_expression(offset, context, true)?;
1901 }
1902
1903 match gather {
1904 None | Some(crate::SwizzleComponent::X) => {}
1905 Some(component) => {
1906 let is_cube_map = match *context.resolve_type(image) {
1907 crate::TypeInner::Image {
1908 dim: crate::ImageDimension::Cube,
1909 ..
1910 } => true,
1911 _ => false,
1912 };
1913 // Offset always comes before the gather, except
1914 // in cube maps where it's not applicable
1915 if offset.is_none() && !is_cube_map {
1916 write!(self.out, ", {NAMESPACE}::int2(0)")?;
1917 }
1918 let letter = back::COMPONENTS[component as usize];
1919 write!(self.out, ", {NAMESPACE}::component::{letter}")?;
1920 }
1921 }
1922 write!(self.out, ")")?;
1923 }
1924 crate::Expression::ImageLoad {
1925 image,
1926 coordinate,
1927 array_index,
1928 sample,
1929 level,
1930 } => {
1931 let address = TexelAddress {
1932 coordinate,
1933 array_index,
1934 sample,
1935 level: level.map(LevelOfDetail::Direct),
1936 };
1937 self.put_image_load(expr_handle, image, address, context)?;
1938 }
1939 //Note: for all the queries, the signed integers are expected,
1940 // so a conversion is needed.
1941 crate::Expression::ImageQuery { image, query } => match query {
1942 crate::ImageQuery::Size { level } => {
1943 self.put_image_size_query(
1944 image,
1945 level.map(LevelOfDetail::Direct),
1946 crate::ScalarKind::Uint,
1947 context,
1948 )?;
1949 }
1950 crate::ImageQuery::NumLevels => {
1951 self.put_expression(image, context, false)?;
1952 write!(self.out, ".get_num_mip_levels()")?;
1953 }
1954 crate::ImageQuery::NumLayers => {
1955 self.put_expression(image, context, false)?;
1956 write!(self.out, ".get_array_size()")?;
1957 }
1958 crate::ImageQuery::NumSamples => {
1959 self.put_expression(image, context, false)?;
1960 write!(self.out, ".get_num_samples()")?;
1961 }
1962 },
1963 crate::Expression::Unary { op, expr } => {
1964 let op_str = match op {
1965 crate::UnaryOperator::Negate => {
1966 match context.resolve_type(expr).scalar_kind() {
1967 Some(crate::ScalarKind::Sint) => NEG_FUNCTION,
1968 _ => "-",
1969 }
1970 }
1971 crate::UnaryOperator::LogicalNot => "!",
1972 crate::UnaryOperator::BitwiseNot => "~",
1973 };
1974 write!(self.out, "{op_str}(")?;
1975 self.put_expression(expr, context, false)?;
1976 write!(self.out, ")")?;
1977 }
1978 crate::Expression::Binary { op, left, right } => {
1979 let kind = context
1980 .resolve_type(left)
1981 .scalar_kind()
1982 .ok_or(Error::UnsupportedBinaryOp(op))?;
1983
1984 if op == crate::BinaryOperator::Divide
1985 && (kind == crate::ScalarKind::Sint || kind == crate::ScalarKind::Uint)
1986 {
1987 write!(self.out, "{DIV_FUNCTION}(")?;
1988 self.put_expression(left, context, true)?;
1989 write!(self.out, ", ")?;
1990 self.put_expression(right, context, true)?;
1991 write!(self.out, ")")?;
1992 } else if op == crate::BinaryOperator::Modulo
1993 && (kind == crate::ScalarKind::Sint || kind == crate::ScalarKind::Uint)
1994 {
1995 write!(self.out, "{MOD_FUNCTION}(")?;
1996 self.put_expression(left, context, true)?;
1997 write!(self.out, ", ")?;
1998 self.put_expression(right, context, true)?;
1999 write!(self.out, ")")?;
2000 } else if op == crate::BinaryOperator::Modulo && kind == crate::ScalarKind::Float {
2001 // TODO: handle undefined behavior of BinaryOperator::Modulo
2002 //
2003 // float:
2004 // if right == 0 return ? see https://github.com/gpuweb/gpuweb/issues/2798
2005 write!(self.out, "{NAMESPACE}::fmod(")?;
2006 self.put_expression(left, context, true)?;
2007 write!(self.out, ", ")?;
2008 self.put_expression(right, context, true)?;
2009 write!(self.out, ")")?;
2010 } else if (op == crate::BinaryOperator::Add
2011 || op == crate::BinaryOperator::Subtract
2012 || op == crate::BinaryOperator::Multiply)
2013 && kind == crate::ScalarKind::Sint
2014 {
2015 let to_unsigned = |ty: &crate::TypeInner| match *ty {
2016 crate::TypeInner::Scalar(scalar) => {
2017 Ok(crate::TypeInner::Scalar(crate::Scalar {
2018 kind: crate::ScalarKind::Uint,
2019 ..scalar
2020 }))
2021 }
2022 crate::TypeInner::Vector { size, scalar } => Ok(crate::TypeInner::Vector {
2023 size,
2024 scalar: crate::Scalar {
2025 kind: crate::ScalarKind::Uint,
2026 ..scalar
2027 },
2028 }),
2029 _ => Err(Error::UnsupportedBitCast(ty.clone())),
2030 };
2031
2032 // Avoid undefined behaviour due to overflowing signed
2033 // integer arithmetic. Cast the operands to unsigned prior
2034 // to performing the operation, then cast the result back
2035 // to signed.
2036 self.put_bitcasted_expression(
2037 context.resolve_type(expr_handle),
2038 context,
2039 &|writer, context, is_scoped| {
2040 writer.put_binop(
2041 op,
2042 left,
2043 right,
2044 context,
2045 is_scoped,
2046 &|writer, expr, context, _is_scoped| {
2047 writer.put_bitcasted_expression(
2048 &to_unsigned(context.resolve_type(expr))?,
2049 context,
2050 &|writer, context, is_scoped| {
2051 writer.put_expression(expr, context, is_scoped)
2052 },
2053 )
2054 },
2055 )
2056 },
2057 )?;
2058 } else {
2059 self.put_binop(op, left, right, context, is_scoped, &Self::put_expression)?;
2060 }
2061 }
2062 crate::Expression::Select {
2063 condition,
2064 accept,
2065 reject,
2066 } => match *context.resolve_type(condition) {
2067 crate::TypeInner::Scalar(crate::Scalar {
2068 kind: crate::ScalarKind::Bool,
2069 ..
2070 }) => {
2071 if !is_scoped {
2072 write!(self.out, "(")?;
2073 }
2074 self.put_expression(condition, context, false)?;
2075 write!(self.out, " ? ")?;
2076 self.put_expression(accept, context, false)?;
2077 write!(self.out, " : ")?;
2078 self.put_expression(reject, context, false)?;
2079 if !is_scoped {
2080 write!(self.out, ")")?;
2081 }
2082 }
2083 crate::TypeInner::Vector {
2084 scalar:
2085 crate::Scalar {
2086 kind: crate::ScalarKind::Bool,
2087 ..
2088 },
2089 ..
2090 } => {
2091 write!(self.out, "{NAMESPACE}::select(")?;
2092 self.put_expression(reject, context, true)?;
2093 write!(self.out, ", ")?;
2094 self.put_expression(accept, context, true)?;
2095 write!(self.out, ", ")?;
2096 self.put_expression(condition, context, true)?;
2097 write!(self.out, ")")?;
2098 }
2099 ref ty => {
2100 return Err(Error::GenericValidation(format!(
2101 "Expected select condition to be a non-bool type, got {ty:?}",
2102 )))
2103 }
2104 },
2105 crate::Expression::Derivative { axis, expr, .. } => {
2106 use crate::DerivativeAxis as Axis;
2107 let op = match axis {
2108 Axis::X => "dfdx",
2109 Axis::Y => "dfdy",
2110 Axis::Width => "fwidth",
2111 };
2112 write!(self.out, "{NAMESPACE}::{op}")?;
2113 self.put_call_parameters(iter::once(expr), context)?;
2114 }
2115 crate::Expression::Relational { fun, argument } => {
2116 let op = match fun {
2117 crate::RelationalFunction::Any => "any",
2118 crate::RelationalFunction::All => "all",
2119 crate::RelationalFunction::IsNan => "isnan",
2120 crate::RelationalFunction::IsInf => "isinf",
2121 };
2122 write!(self.out, "{NAMESPACE}::{op}")?;
2123 self.put_call_parameters(iter::once(argument), context)?;
2124 }
2125 crate::Expression::Math {
2126 fun,
2127 arg,
2128 arg1,
2129 arg2,
2130 arg3,
2131 } => {
2132 use crate::MathFunction as Mf;
2133
2134 let arg_type = context.resolve_type(arg);
2135 let scalar_argument = match arg_type {
2136 &crate::TypeInner::Scalar(_) => true,
2137 _ => false,
2138 };
2139
2140 let fun_name = match fun {
2141 // comparison
2142 Mf::Abs => "abs",
2143 Mf::Min => "min",
2144 Mf::Max => "max",
2145 Mf::Clamp => "clamp",
2146 Mf::Saturate => "saturate",
2147 // trigonometry
2148 Mf::Cos => "cos",
2149 Mf::Cosh => "cosh",
2150 Mf::Sin => "sin",
2151 Mf::Sinh => "sinh",
2152 Mf::Tan => "tan",
2153 Mf::Tanh => "tanh",
2154 Mf::Acos => "acos",
2155 Mf::Asin => "asin",
2156 Mf::Atan => "atan",
2157 Mf::Atan2 => "atan2",
2158 Mf::Asinh => "asinh",
2159 Mf::Acosh => "acosh",
2160 Mf::Atanh => "atanh",
2161 Mf::Radians => "",
2162 Mf::Degrees => "",
2163 // decomposition
2164 Mf::Ceil => "ceil",
2165 Mf::Floor => "floor",
2166 Mf::Round => "rint",
2167 Mf::Fract => "fract",
2168 Mf::Trunc => "trunc",
2169 Mf::Modf => MODF_FUNCTION,
2170 Mf::Frexp => FREXP_FUNCTION,
2171 Mf::Ldexp => "ldexp",
2172 // exponent
2173 Mf::Exp => "exp",
2174 Mf::Exp2 => "exp2",
2175 Mf::Log => "log",
2176 Mf::Log2 => "log2",
2177 Mf::Pow => "pow",
2178 // geometry
2179 Mf::Dot => match *context.resolve_type(arg) {
2180 crate::TypeInner::Vector {
2181 scalar:
2182 crate::Scalar {
2183 kind: crate::ScalarKind::Float,
2184 ..
2185 },
2186 ..
2187 } => "dot",
2188 crate::TypeInner::Vector { size, .. } => {
2189 return self.put_dot_product(
2190 arg,
2191 arg1.unwrap(),
2192 size as usize,
2193 |writer, arg, index| {
2194 // Write the vector expression; this expression is marked to be
2195 // cached so unless it can't be cached (for example, it's a Constant)
2196 // it shouldn't produce large expressions.
2197 writer.put_expression(arg, context, true)?;
2198 // Access the current component on the vector.
2199 write!(writer.out, ".{}", back::COMPONENTS[index])?;
2200 Ok(())
2201 },
2202 );
2203 }
2204 _ => unreachable!(
2205 "Correct TypeInner for dot product should be already validated"
2206 ),
2207 },
2208 fun @ (Mf::Dot4I8Packed | Mf::Dot4U8Packed) => {
2209 let conversion = match fun {
2210 Mf::Dot4I8Packed => "int",
2211 Mf::Dot4U8Packed => "",
2212 _ => unreachable!(),
2213 };
2214
2215 return self.put_dot_product(
2216 arg,
2217 arg1.unwrap(),
2218 4,
2219 |writer, arg, index| {
2220 write!(writer.out, "({}(", conversion)?;
2221 writer.put_expression(arg, context, true)?;
2222 if index == 3 {
2223 write!(writer.out, ") >> 24)")?;
2224 } else {
2225 write!(writer.out, ") << {} >> 24)", (3 - index) * 8)?;
2226 }
2227 Ok(())
2228 },
2229 );
2230 }
2231 Mf::Outer => return Err(Error::UnsupportedCall(format!("{fun:?}"))),
2232 Mf::Cross => "cross",
2233 Mf::Distance => "distance",
2234 Mf::Length if scalar_argument => "abs",
2235 Mf::Length => "length",
2236 Mf::Normalize => "normalize",
2237 Mf::FaceForward => "faceforward",
2238 Mf::Reflect => "reflect",
2239 Mf::Refract => "refract",
2240 // computational
2241 Mf::Sign => match arg_type.scalar_kind() {
2242 Some(crate::ScalarKind::Sint) => {
2243 return self.put_isign(arg, context);
2244 }
2245 _ => "sign",
2246 },
2247 Mf::Fma => "fma",
2248 Mf::Mix => "mix",
2249 Mf::Step => "step",
2250 Mf::SmoothStep => "smoothstep",
2251 Mf::Sqrt => "sqrt",
2252 Mf::InverseSqrt => "rsqrt",
2253 Mf::Inverse => return Err(Error::UnsupportedCall(format!("{fun:?}"))),
2254 Mf::Transpose => "transpose",
2255 Mf::Determinant => "determinant",
2256 Mf::QuantizeToF16 => "",
2257 // bits
2258 Mf::CountTrailingZeros => "ctz",
2259 Mf::CountLeadingZeros => "clz",
2260 Mf::CountOneBits => "popcount",
2261 Mf::ReverseBits => "reverse_bits",
2262 Mf::ExtractBits => "",
2263 Mf::InsertBits => "",
2264 Mf::FirstTrailingBit => "",
2265 Mf::FirstLeadingBit => "",
2266 // data packing
2267 Mf::Pack4x8snorm => "pack_float_to_snorm4x8",
2268 Mf::Pack4x8unorm => "pack_float_to_unorm4x8",
2269 Mf::Pack2x16snorm => "pack_float_to_snorm2x16",
2270 Mf::Pack2x16unorm => "pack_float_to_unorm2x16",
2271 Mf::Pack2x16float => "",
2272 Mf::Pack4xI8 => "",
2273 Mf::Pack4xU8 => "",
2274 Mf::Pack4xI8Clamp => "",
2275 Mf::Pack4xU8Clamp => "",
2276 // data unpacking
2277 Mf::Unpack4x8snorm => "unpack_snorm4x8_to_float",
2278 Mf::Unpack4x8unorm => "unpack_unorm4x8_to_float",
2279 Mf::Unpack2x16snorm => "unpack_snorm2x16_to_float",
2280 Mf::Unpack2x16unorm => "unpack_unorm2x16_to_float",
2281 Mf::Unpack2x16float => "",
2282 Mf::Unpack4xI8 => "",
2283 Mf::Unpack4xU8 => "",
2284 };
2285
2286 match fun {
2287 Mf::ReverseBits | Mf::ExtractBits | Mf::InsertBits => {
2288 // reverse_bits is listed as requiring MSL 2.1 but that
2289 // is a copy/paste error. Looking at previous snapshots
2290 // on web.archive.org it's present in MSL 1.2.
2291 //
2292 // https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/WhatsNewiniOS10tvOS10andOSX1012/WhatsNewiniOS10tvOS10andOSX1012.html
2293 // also talks about MSL 1.2 adding "New integer
2294 // functions to extract, insert, and reverse bits, as
2295 // described in Integer Functions."
2296 if context.lang_version < (1, 2) {
2297 return Err(Error::UnsupportedFunction(fun_name.to_string()));
2298 }
2299 }
2300 _ => {}
2301 }
2302
2303 match fun {
2304 Mf::Abs if arg_type.scalar_kind() == Some(crate::ScalarKind::Sint) => {
2305 write!(self.out, "{ABS_FUNCTION}(")?;
2306 self.put_expression(arg, context, true)?;
2307 write!(self.out, ")")?;
2308 }
2309 Mf::Distance if scalar_argument => {
2310 write!(self.out, "{NAMESPACE}::abs(")?;
2311 self.put_expression(arg, context, false)?;
2312 write!(self.out, " - ")?;
2313 self.put_expression(arg1.unwrap(), context, false)?;
2314 write!(self.out, ")")?;
2315 }
2316 Mf::FirstTrailingBit => {
2317 let scalar = context.resolve_type(arg).scalar().unwrap();
2318 let constant = scalar.width * 8 + 1;
2319
2320 write!(self.out, "((({NAMESPACE}::ctz(")?;
2321 self.put_expression(arg, context, true)?;
2322 write!(self.out, ") + 1) % {constant}) - 1)")?;
2323 }
2324 Mf::FirstLeadingBit => {
2325 let inner = context.resolve_type(arg);
2326 let scalar = inner.scalar().unwrap();
2327 let constant = scalar.width * 8 - 1;
2328
2329 write!(
2330 self.out,
2331 "{NAMESPACE}::select({constant} - {NAMESPACE}::clz("
2332 )?;
2333
2334 if scalar.kind == crate::ScalarKind::Sint {
2335 write!(self.out, "{NAMESPACE}::select(")?;
2336 self.put_expression(arg, context, true)?;
2337 write!(self.out, ", ~")?;
2338 self.put_expression(arg, context, true)?;
2339 write!(self.out, ", ")?;
2340 self.put_expression(arg, context, true)?;
2341 write!(self.out, " < 0)")?;
2342 } else {
2343 self.put_expression(arg, context, true)?;
2344 }
2345
2346 write!(self.out, "), ")?;
2347
2348 // or metal will complain that select is ambiguous
2349 match *inner {
2350 crate::TypeInner::Vector { size, scalar } => {
2351 let size = common::vector_size_str(size);
2352 let name = scalar.to_msl_name();
2353 write!(self.out, "{name}{size}")?;
2354 }
2355 crate::TypeInner::Scalar(scalar) => {
2356 let name = scalar.to_msl_name();
2357 write!(self.out, "{name}")?;
2358 }
2359 _ => (),
2360 }
2361
2362 write!(self.out, "(-1), ")?;
2363 self.put_expression(arg, context, true)?;
2364 write!(self.out, " == 0 || ")?;
2365 self.put_expression(arg, context, true)?;
2366 write!(self.out, " == -1)")?;
2367 }
2368 Mf::Unpack2x16float => {
2369 write!(self.out, "float2(as_type<half2>(")?;
2370 self.put_expression(arg, context, false)?;
2371 write!(self.out, "))")?;
2372 }
2373 Mf::Pack2x16float => {
2374 write!(self.out, "as_type<uint>(half2(")?;
2375 self.put_expression(arg, context, false)?;
2376 write!(self.out, "))")?;
2377 }
2378 Mf::ExtractBits => {
2379 // The behavior of ExtractBits is undefined when offset + count > bit_width. We need
2380 // to first sanitize the offset and count first. If we don't do this, Apple chips
2381 // will return out-of-spec values if the extracted range is not within the bit width.
2382 //
2383 // This encodes the exact formula specified by the wgsl spec, without temporary values:
2384 // https://gpuweb.github.io/gpuweb/wgsl/#extractBits-unsigned-builtin
2385 //
2386 // w = sizeof(x) * 8
2387 // o = min(offset, w)
2388 // tmp = w - o
2389 // c = min(count, tmp)
2390 //
2391 // bitfieldExtract(x, o, c)
2392 //
2393 // extract_bits(e, min(offset, w), min(count, w - min(offset, w))))
2394
2395 let scalar_bits = context.resolve_type(arg).scalar_width().unwrap() * 8;
2396
2397 write!(self.out, "{NAMESPACE}::extract_bits(")?;
2398 self.put_expression(arg, context, true)?;
2399 write!(self.out, ", {NAMESPACE}::min(")?;
2400 self.put_expression(arg1.unwrap(), context, true)?;
2401 write!(self.out, ", {scalar_bits}u), {NAMESPACE}::min(")?;
2402 self.put_expression(arg2.unwrap(), context, true)?;
2403 write!(self.out, ", {scalar_bits}u - {NAMESPACE}::min(")?;
2404 self.put_expression(arg1.unwrap(), context, true)?;
2405 write!(self.out, ", {scalar_bits}u)))")?;
2406 }
2407 Mf::InsertBits => {
2408 // The behavior of InsertBits has the same issue as ExtractBits.
2409 //
2410 // insertBits(e, newBits, min(offset, w), min(count, w - min(offset, w))))
2411
2412 let scalar_bits = context.resolve_type(arg).scalar_width().unwrap() * 8;
2413
2414 write!(self.out, "{NAMESPACE}::insert_bits(")?;
2415 self.put_expression(arg, context, true)?;
2416 write!(self.out, ", ")?;
2417 self.put_expression(arg1.unwrap(), context, true)?;
2418 write!(self.out, ", {NAMESPACE}::min(")?;
2419 self.put_expression(arg2.unwrap(), context, true)?;
2420 write!(self.out, ", {scalar_bits}u), {NAMESPACE}::min(")?;
2421 self.put_expression(arg3.unwrap(), context, true)?;
2422 write!(self.out, ", {scalar_bits}u - {NAMESPACE}::min(")?;
2423 self.put_expression(arg2.unwrap(), context, true)?;
2424 write!(self.out, ", {scalar_bits}u)))")?;
2425 }
2426 Mf::Radians => {
2427 write!(self.out, "((")?;
2428 self.put_expression(arg, context, false)?;
2429 write!(self.out, ") * 0.017453292519943295474)")?;
2430 }
2431 Mf::Degrees => {
2432 write!(self.out, "((")?;
2433 self.put_expression(arg, context, false)?;
2434 write!(self.out, ") * 57.295779513082322865)")?;
2435 }
2436 Mf::Modf | Mf::Frexp => {
2437 write!(self.out, "{fun_name}")?;
2438 self.put_call_parameters(iter::once(arg), context)?;
2439 }
2440 fun @ (Mf::Pack4xI8 | Mf::Pack4xU8 | Mf::Pack4xI8Clamp | Mf::Pack4xU8Clamp) => {
2441 let was_signed = matches!(fun, Mf::Pack4xI8 | Mf::Pack4xI8Clamp);
2442 let clamp_bounds = match fun {
2443 Mf::Pack4xI8Clamp => Some(("-128", "127")),
2444 Mf::Pack4xU8Clamp => Some(("0", "255")),
2445 _ => None,
2446 };
2447 if was_signed {
2448 write!(self.out, "uint(")?;
2449 }
2450 let write_arg = |this: &mut Self| -> BackendResult {
2451 if let Some((min, max)) = clamp_bounds {
2452 write!(this.out, "{NAMESPACE}::clamp(")?;
2453 this.put_expression(arg, context, true)?;
2454 write!(this.out, ", {min}, {max})")?;
2455 } else {
2456 this.put_expression(arg, context, true)?;
2457 }
2458 Ok(())
2459 };
2460 write!(self.out, "(")?;
2461 write_arg(self)?;
2462 write!(self.out, "[0] & 0xFF) | ((")?;
2463 write_arg(self)?;
2464 write!(self.out, "[1] & 0xFF) << 8) | ((")?;
2465 write_arg(self)?;
2466 write!(self.out, "[2] & 0xFF) << 16) | ((")?;
2467 write_arg(self)?;
2468 write!(self.out, "[3] & 0xFF) << 24)")?;
2469 if was_signed {
2470 write!(self.out, ")")?;
2471 }
2472 }
2473 fun @ (Mf::Unpack4xI8 | Mf::Unpack4xU8) => {
2474 write!(self.out, "(")?;
2475 if matches!(fun, Mf::Unpack4xU8) {
2476 write!(self.out, "u")?;
2477 }
2478 write!(self.out, "int4(")?;
2479 self.put_expression(arg, context, true)?;
2480 write!(self.out, ", ")?;
2481 self.put_expression(arg, context, true)?;
2482 write!(self.out, " >> 8, ")?;
2483 self.put_expression(arg, context, true)?;
2484 write!(self.out, " >> 16, ")?;
2485 self.put_expression(arg, context, true)?;
2486 write!(self.out, " >> 24) << 24 >> 24)")?;
2487 }
2488 Mf::QuantizeToF16 => {
2489 match *context.resolve_type(arg) {
2490 crate::TypeInner::Scalar { .. } => write!(self.out, "float(half(")?,
2491 crate::TypeInner::Vector { size, .. } => write!(
2492 self.out,
2493 "{NAMESPACE}::float{size}({NAMESPACE}::half{size}(",
2494 size = common::vector_size_str(size),
2495 )?,
2496 _ => unreachable!(
2497 "Correct TypeInner for QuantizeToF16 should be already validated"
2498 ),
2499 };
2500
2501 self.put_expression(arg, context, true)?;
2502 write!(self.out, "))")?;
2503 }
2504 _ => {
2505 write!(self.out, "{NAMESPACE}::{fun_name}")?;
2506 self.put_call_parameters(
2507 iter::once(arg).chain(arg1).chain(arg2).chain(arg3),
2508 context,
2509 )?;
2510 }
2511 }
2512 }
2513 crate::Expression::As {
2514 expr,
2515 kind,
2516 convert,
2517 } => match *context.resolve_type(expr) {
2518 crate::TypeInner::Scalar(src) | crate::TypeInner::Vector { scalar: src, .. } => {
2519 if src.kind == crate::ScalarKind::Float
2520 && (kind == crate::ScalarKind::Sint || kind == crate::ScalarKind::Uint)
2521 && convert.is_some()
2522 {
2523 // Use helper functions for float to int casts in order to avoid
2524 // undefined behaviour when value is out of range for the target
2525 // type.
2526 let fun_name = match (kind, convert) {
2527 (crate::ScalarKind::Sint, Some(4)) => F2I32_FUNCTION,
2528 (crate::ScalarKind::Uint, Some(4)) => F2U32_FUNCTION,
2529 (crate::ScalarKind::Sint, Some(8)) => F2I64_FUNCTION,
2530 (crate::ScalarKind::Uint, Some(8)) => F2U64_FUNCTION,
2531 _ => unreachable!(),
2532 };
2533 write!(self.out, "{fun_name}(")?;
2534 self.put_expression(expr, context, true)?;
2535 write!(self.out, ")")?;
2536 } else {
2537 let target_scalar = crate::Scalar {
2538 kind,
2539 width: convert.unwrap_or(src.width),
2540 };
2541 let op = match convert {
2542 Some(_) => "static_cast",
2543 None => "as_type",
2544 };
2545 write!(self.out, "{op}<")?;
2546 match *context.resolve_type(expr) {
2547 crate::TypeInner::Vector { size, .. } => {
2548 put_numeric_type(&mut self.out, target_scalar, &[size])?
2549 }
2550 _ => put_numeric_type(&mut self.out, target_scalar, &[])?,
2551 };
2552 write!(self.out, ">(")?;
2553 self.put_expression(expr, context, true)?;
2554 write!(self.out, ")")?;
2555 }
2556 }
2557 crate::TypeInner::Matrix {
2558 columns,
2559 rows,
2560 scalar,
2561 } => {
2562 let target_scalar = crate::Scalar {
2563 kind,
2564 width: convert.unwrap_or(scalar.width),
2565 };
2566 put_numeric_type(&mut self.out, target_scalar, &[rows, columns])?;
2567 write!(self.out, "(")?;
2568 self.put_expression(expr, context, true)?;
2569 write!(self.out, ")")?;
2570 }
2571 ref ty => {
2572 return Err(Error::GenericValidation(format!(
2573 "Unsupported type for As: {ty:?}"
2574 )))
2575 }
2576 },
2577 // has to be a named expression
2578 crate::Expression::CallResult(_)
2579 | crate::Expression::AtomicResult { .. }
2580 | crate::Expression::WorkGroupUniformLoadResult { .. }
2581 | crate::Expression::SubgroupBallotResult
2582 | crate::Expression::SubgroupOperationResult { .. }
2583 | crate::Expression::RayQueryProceedResult => {
2584 unreachable!()
2585 }
2586 crate::Expression::ArrayLength(expr) => {
2587 // Find the global to which the array belongs.
2588 let global = match context.function.expressions[expr] {
2589 crate::Expression::AccessIndex { base, .. } => {
2590 match context.function.expressions[base] {
2591 crate::Expression::GlobalVariable(handle) => handle,
2592 ref ex => {
2593 return Err(Error::GenericValidation(format!(
2594 "Expected global variable in AccessIndex, got {ex:?}"
2595 )))
2596 }
2597 }
2598 }
2599 crate::Expression::GlobalVariable(handle) => handle,
2600 ref ex => {
2601 return Err(Error::GenericValidation(format!(
2602 "Unexpected expression in ArrayLength, got {ex:?}"
2603 )))
2604 }
2605 };
2606
2607 if !is_scoped {
2608 write!(self.out, "(")?;
2609 }
2610 write!(self.out, "1 + ")?;
2611 self.put_dynamic_array_max_index(global, context)?;
2612 if !is_scoped {
2613 write!(self.out, ")")?;
2614 }
2615 }
2616 crate::Expression::RayQueryVertexPositions { .. } => {
2617 unimplemented!()
2618 }
2619 crate::Expression::RayQueryGetIntersection {
2620 query,
2621 committed: _,
2622 } => {
2623 if context.lang_version < (2, 4) {
2624 return Err(Error::UnsupportedRayTracing);
2625 }
2626
2627 let ty = context.module.special_types.ray_intersection.unwrap();
2628 let type_name = &self.names[&NameKey::Type(ty)];
2629 write!(self.out, "{type_name} {{{RAY_QUERY_FUN_MAP_INTERSECTION}(")?;
2630 self.put_expression(query, context, true)?;
2631 write!(self.out, ".{RAY_QUERY_FIELD_INTERSECTION}.type)")?;
2632 let fields = [
2633 "distance",
2634 "user_instance_id", // req Metal 2.4
2635 "instance_id",
2636 "", // SBT offset
2637 "geometry_id",
2638 "primitive_id",
2639 "triangle_barycentric_coord",
2640 "triangle_front_facing",
2641 "", // padding
2642 "object_to_world_transform", // req Metal 2.4
2643 "world_to_object_transform", // req Metal 2.4
2644 ];
2645 for field in fields {
2646 write!(self.out, ", ")?;
2647 if field.is_empty() {
2648 write!(self.out, "{{}}")?;
2649 } else {
2650 self.put_expression(query, context, true)?;
2651 write!(self.out, ".{RAY_QUERY_FIELD_INTERSECTION}.{field}")?;
2652 }
2653 }
2654 write!(self.out, "}}")?;
2655 }
2656 }
2657 Ok(())
2658 }
2659
2660 /// Emits code for a binary operation, using the provided callback to emit
2661 /// the left and right operands.
2662 fn put_binop<F>(
2663 &mut self,
2664 op: crate::BinaryOperator,
2665 left: Handle<crate::Expression>,
2666 right: Handle<crate::Expression>,
2667 context: &ExpressionContext,
2668 is_scoped: bool,
2669 put_expression: &F,
2670 ) -> BackendResult
2671 where
2672 F: Fn(&mut Self, Handle<crate::Expression>, &ExpressionContext, bool) -> BackendResult,
2673 {
2674 let op_str = back::binary_operation_str(op);
2675
2676 if !is_scoped {
2677 write!(self.out, "(")?;
2678 }
2679
2680 // Cast packed vector if necessary
2681 // Packed vector - matrix multiplications are not supported in MSL
2682 if op == crate::BinaryOperator::Multiply
2683 && matches!(
2684 context.resolve_type(right),
2685 &crate::TypeInner::Matrix { .. }
2686 )
2687 {
2688 self.put_wrapped_expression_for_packed_vec3_access(
2689 left,
2690 context,
2691 false,
2692 put_expression,
2693 )?;
2694 } else {
2695 put_expression(self, left, context, false)?;
2696 }
2697
2698 write!(self.out, " {op_str} ")?;
2699
2700 // See comment above
2701 if op == crate::BinaryOperator::Multiply
2702 && matches!(context.resolve_type(left), &crate::TypeInner::Matrix { .. })
2703 {
2704 self.put_wrapped_expression_for_packed_vec3_access(
2705 right,
2706 context,
2707 false,
2708 put_expression,
2709 )?;
2710 } else {
2711 put_expression(self, right, context, false)?;
2712 }
2713
2714 if !is_scoped {
2715 write!(self.out, ")")?;
2716 }
2717
2718 Ok(())
2719 }
2720
2721 /// Used by expressions like Swizzle and Binary since they need packed_vec3's to be casted to a vec3
2722 fn put_wrapped_expression_for_packed_vec3_access<F>(
2723 &mut self,
2724 expr_handle: Handle<crate::Expression>,
2725 context: &ExpressionContext,
2726 is_scoped: bool,
2727 put_expression: &F,
2728 ) -> BackendResult
2729 where
2730 F: Fn(&mut Self, Handle<crate::Expression>, &ExpressionContext, bool) -> BackendResult,
2731 {
2732 if let Some(scalar) = context.get_packed_vec_kind(expr_handle) {
2733 write!(self.out, "{}::{}3(", NAMESPACE, scalar.to_msl_name())?;
2734 put_expression(self, expr_handle, context, is_scoped)?;
2735 write!(self.out, ")")?;
2736 } else {
2737 put_expression(self, expr_handle, context, is_scoped)?;
2738 }
2739 Ok(())
2740 }
2741
2742 /// Emits code for an expression using the provided callback, wrapping the
2743 /// result in a bitcast to the type `cast_to`.
2744 fn put_bitcasted_expression<F>(
2745 &mut self,
2746 cast_to: &crate::TypeInner,
2747 context: &ExpressionContext,
2748 put_expression: &F,
2749 ) -> BackendResult
2750 where
2751 F: Fn(&mut Self, &ExpressionContext, bool) -> BackendResult,
2752 {
2753 write!(self.out, "as_type<")?;
2754 match *cast_to {
2755 crate::TypeInner::Scalar(scalar) => put_numeric_type(&mut self.out, scalar, &[])?,
2756 crate::TypeInner::Vector { size, scalar } => {
2757 put_numeric_type(&mut self.out, scalar, &[size])?
2758 }
2759 _ => return Err(Error::UnsupportedBitCast(cast_to.clone())),
2760 };
2761 write!(self.out, ">(")?;
2762 put_expression(self, context, true)?;
2763 write!(self.out, ")")?;
2764
2765 Ok(())
2766 }
2767
2768 /// Write a `GuardedIndex` as a Metal expression.
2769 fn put_index(
2770 &mut self,
2771 index: index::GuardedIndex,
2772 context: &ExpressionContext,
2773 is_scoped: bool,
2774 ) -> BackendResult {
2775 match index {
2776 index::GuardedIndex::Expression(expr) => {
2777 self.put_expression(expr, context, is_scoped)?
2778 }
2779 index::GuardedIndex::Known(value) => write!(self.out, "{value}")?,
2780 }
2781 Ok(())
2782 }
2783
2784 /// Emit an index bounds check condition for `chain`, if required.
2785 ///
2786 /// `chain` is a subtree of `Access` and `AccessIndex` expressions,
2787 /// operating either on a pointer to a value, or on a value directly. If we cannot
2788 /// statically determine that all indexing operations in `chain` are within
2789 /// bounds, then write a conditional expression to check them dynamically,
2790 /// and return true. All accesses in the chain are checked by the generated
2791 /// expression.
2792 ///
2793 /// This assumes that the [`BoundsCheckPolicy`] for `chain` is [`ReadZeroSkipWrite`].
2794 ///
2795 /// The text written is of the form:
2796 ///
2797 /// ```ignore
2798 /// {level}{prefix}uint(i) < 4 && uint(j) < 10
2799 /// ```
2800 ///
2801 /// where `{level}` and `{prefix}` are the arguments to this function. For [`Store`]
2802 /// statements, presumably these arguments start an indented `if` statement; for
2803 /// [`Load`] expressions, the caller is probably building up a ternary `?:`
2804 /// expression. In either case, what is written is not a complete syntactic structure
2805 /// in its own right, and the caller will have to finish it off if we return `true`.
2806 ///
2807 /// If no expression is written, return false.
2808 ///
2809 /// [`BoundsCheckPolicy`]: index::BoundsCheckPolicy
2810 /// [`ReadZeroSkipWrite`]: index::BoundsCheckPolicy::ReadZeroSkipWrite
2811 /// [`Store`]: crate::Statement::Store
2812 /// [`Load`]: crate::Expression::Load
2813 #[allow(unused_variables)]
2814 fn put_bounds_checks(
2815 &mut self,
2816 chain: Handle<crate::Expression>,
2817 context: &ExpressionContext,
2818 level: back::Level,
2819 prefix: &'static str,
2820 ) -> Result<bool, Error> {
2821 let mut check_written = false;
2822
2823 // Iterate over the access chain, handling each required bounds check.
2824 for item in context.bounds_check_iter(chain) {
2825 let BoundsCheck {
2826 base,
2827 index,
2828 length,
2829 } = item;
2830
2831 if check_written {
2832 write!(self.out, " && ")?;
2833 } else {
2834 write!(self.out, "{level}{prefix}")?;
2835 check_written = true;
2836 }
2837
2838 // Check that the index falls within bounds. Do this with a single
2839 // comparison, by casting the index to `uint` first, so that negative
2840 // indices become large positive values.
2841 write!(self.out, "uint(")?;
2842 self.put_index(index, context, true)?;
2843 self.out.write_str(") < ")?;
2844 match length {
2845 index::IndexableLength::Known(value) => write!(self.out, "{value}")?,
2846 index::IndexableLength::Dynamic => {
2847 let global = context.function.originating_global(base).ok_or_else(|| {
2848 Error::GenericValidation("Could not find originating global".into())
2849 })?;
2850 write!(self.out, "1 + ")?;
2851 self.put_dynamic_array_max_index(global, context)?
2852 }
2853 }
2854 }
2855
2856 Ok(check_written)
2857 }
2858
2859 /// Write the access chain `chain`.
2860 ///
2861 /// `chain` is a subtree of [`Access`] and [`AccessIndex`] expressions,
2862 /// operating either on a pointer to a value, or on a value directly.
2863 ///
2864 /// Generate bounds checks code only if `policy` is [`Restrict`]. The
2865 /// [`ReadZeroSkipWrite`] policy requires checks before any accesses take place, so
2866 /// that must be handled in the caller.
2867 ///
2868 /// Handle the entire chain, recursing back into `put_expression` only for index
2869 /// expressions and the base expression that originates the pointer or composite value
2870 /// being accessed. This allows `put_expression` to assume that any `Access` or
2871 /// `AccessIndex` expressions it sees are the top of a chain, so it can emit
2872 /// `ReadZeroSkipWrite` checks.
2873 ///
2874 /// [`Access`]: crate::Expression::Access
2875 /// [`AccessIndex`]: crate::Expression::AccessIndex
2876 /// [`Restrict`]: crate::proc::index::BoundsCheckPolicy::Restrict
2877 /// [`ReadZeroSkipWrite`]: crate::proc::index::BoundsCheckPolicy::ReadZeroSkipWrite
2878 fn put_access_chain(
2879 &mut self,
2880 chain: Handle<crate::Expression>,
2881 policy: index::BoundsCheckPolicy,
2882 context: &ExpressionContext,
2883 ) -> BackendResult {
2884 match context.function.expressions[chain] {
2885 crate::Expression::Access { base, index } => {
2886 let mut base_ty = context.resolve_type(base);
2887
2888 // Look through any pointers to see what we're really indexing.
2889 if let crate::TypeInner::Pointer { base, space: _ } = *base_ty {
2890 base_ty = &context.module.types[base].inner;
2891 }
2892
2893 self.put_subscripted_access_chain(
2894 base,
2895 base_ty,
2896 index::GuardedIndex::Expression(index),
2897 policy,
2898 context,
2899 )?;
2900 }
2901 crate::Expression::AccessIndex { base, index } => {
2902 let base_resolution = &context.info[base].ty;
2903 let mut base_ty = base_resolution.inner_with(&context.module.types);
2904 let mut base_ty_handle = base_resolution.handle();
2905
2906 // Look through any pointers to see what we're really indexing.
2907 if let crate::TypeInner::Pointer { base, space: _ } = *base_ty {
2908 base_ty = &context.module.types[base].inner;
2909 base_ty_handle = Some(base);
2910 }
2911
2912 // Handle structs and anything else that can use `.x` syntax here, so
2913 // `put_subscripted_access_chain` won't have to handle the absurd case of
2914 // indexing a struct with an expression.
2915 match *base_ty {
2916 crate::TypeInner::Struct { .. } => {
2917 let base_ty = base_ty_handle.unwrap();
2918 self.put_access_chain(base, policy, context)?;
2919 let name = &self.names[&NameKey::StructMember(base_ty, index)];
2920 write!(self.out, ".{name}")?;
2921 }
2922 crate::TypeInner::ValuePointer { .. } | crate::TypeInner::Vector { .. } => {
2923 self.put_access_chain(base, policy, context)?;
2924 // Prior to Metal v2.1 component access for packed vectors wasn't available
2925 // however array indexing is
2926 if context.get_packed_vec_kind(base).is_some() {
2927 write!(self.out, "[{index}]")?;
2928 } else {
2929 write!(self.out, ".{}", back::COMPONENTS[index as usize])?;
2930 }
2931 }
2932 _ => {
2933 self.put_subscripted_access_chain(
2934 base,
2935 base_ty,
2936 index::GuardedIndex::Known(index),
2937 policy,
2938 context,
2939 )?;
2940 }
2941 }
2942 }
2943 _ => self.put_expression(chain, context, false)?,
2944 }
2945
2946 Ok(())
2947 }
2948
2949 /// Write a `[]`-style access of `base` by `index`.
2950 ///
2951 /// If `policy` is [`Restrict`], then generate code as needed to force all index
2952 /// values within bounds.
2953 ///
2954 /// The `base_ty` argument must be the type we are actually indexing, like [`Array`] or
2955 /// [`Vector`]. In other words, it's `base`'s type with any surrounding [`Pointer`]
2956 /// removed. Our callers often already have this handy.
2957 ///
2958 /// This only emits `[]` expressions; it doesn't handle struct member accesses or
2959 /// referencing vector components by name.
2960 ///
2961 /// [`Restrict`]: crate::proc::index::BoundsCheckPolicy::Restrict
2962 /// [`Array`]: crate::TypeInner::Array
2963 /// [`Vector`]: crate::TypeInner::Vector
2964 /// [`Pointer`]: crate::TypeInner::Pointer
2965 fn put_subscripted_access_chain(
2966 &mut self,
2967 base: Handle<crate::Expression>,
2968 base_ty: &crate::TypeInner,
2969 index: index::GuardedIndex,
2970 policy: index::BoundsCheckPolicy,
2971 context: &ExpressionContext,
2972 ) -> BackendResult {
2973 let accessing_wrapped_array = match *base_ty {
2974 crate::TypeInner::Array {
2975 size: crate::ArraySize::Constant(_) | crate::ArraySize::Pending(_),
2976 ..
2977 } => true,
2978 _ => false,
2979 };
2980 let accessing_wrapped_binding_array =
2981 matches!(*base_ty, crate::TypeInner::BindingArray { .. });
2982
2983 self.put_access_chain(base, policy, context)?;
2984 if accessing_wrapped_array {
2985 write!(self.out, ".{WRAPPED_ARRAY_FIELD}")?;
2986 }
2987 write!(self.out, "[")?;
2988
2989 // Decide whether this index needs to be clamped to fall within range.
2990 let restriction_needed = if policy == index::BoundsCheckPolicy::Restrict {
2991 context.access_needs_check(base, index)
2992 } else {
2993 None
2994 };
2995 if let Some(limit) = restriction_needed {
2996 write!(self.out, "{NAMESPACE}::min(unsigned(")?;
2997 self.put_index(index, context, true)?;
2998 write!(self.out, "), ")?;
2999 match limit {
3000 index::IndexableLength::Known(limit) => {
3001 write!(self.out, "{}u", limit - 1)?;
3002 }
3003 index::IndexableLength::Dynamic => {
3004 let global = context.function.originating_global(base).ok_or_else(|| {
3005 Error::GenericValidation("Could not find originating global".into())
3006 })?;
3007 self.put_dynamic_array_max_index(global, context)?;
3008 }
3009 }
3010 write!(self.out, ")")?;
3011 } else {
3012 self.put_index(index, context, true)?;
3013 }
3014
3015 write!(self.out, "]")?;
3016
3017 if accessing_wrapped_binding_array {
3018 write!(self.out, ".{WRAPPED_ARRAY_FIELD}")?;
3019 }
3020
3021 Ok(())
3022 }
3023
3024 fn put_load(
3025 &mut self,
3026 pointer: Handle<crate::Expression>,
3027 context: &ExpressionContext,
3028 is_scoped: bool,
3029 ) -> BackendResult {
3030 // Since access chains never cross between address spaces, we can just
3031 // check the index bounds check policy once at the top.
3032 let policy = context.choose_bounds_check_policy(pointer);
3033 if policy == index::BoundsCheckPolicy::ReadZeroSkipWrite
3034 && self.put_bounds_checks(
3035 pointer,
3036 context,
3037 back::Level(0),
3038 if is_scoped { "" } else { "(" },
3039 )?
3040 {
3041 write!(self.out, " ? ")?;
3042 self.put_unchecked_load(pointer, policy, context)?;
3043 write!(self.out, " : DefaultConstructible()")?;
3044
3045 if !is_scoped {
3046 write!(self.out, ")")?;
3047 }
3048 } else {
3049 self.put_unchecked_load(pointer, policy, context)?;
3050 }
3051
3052 Ok(())
3053 }
3054
3055 fn put_unchecked_load(
3056 &mut self,
3057 pointer: Handle<crate::Expression>,
3058 policy: index::BoundsCheckPolicy,
3059 context: &ExpressionContext,
3060 ) -> BackendResult {
3061 let is_atomic_pointer = context
3062 .resolve_type(pointer)
3063 .is_atomic_pointer(&context.module.types);
3064
3065 if is_atomic_pointer {
3066 write!(
3067 self.out,
3068 "{NAMESPACE}::atomic_load_explicit({ATOMIC_REFERENCE}"
3069 )?;
3070 self.put_access_chain(pointer, policy, context)?;
3071 write!(self.out, ", {NAMESPACE}::memory_order_relaxed)")?;
3072 } else {
3073 // We don't do any dereferencing with `*` here as pointer arguments to functions
3074 // are done by `&` references and not `*` pointers. These do not need to be
3075 // dereferenced.
3076 self.put_access_chain(pointer, policy, context)?;
3077 }
3078
3079 Ok(())
3080 }
3081
3082 fn put_return_value(
3083 &mut self,
3084 level: back::Level,
3085 expr_handle: Handle<crate::Expression>,
3086 result_struct: Option<&str>,
3087 context: &ExpressionContext,
3088 ) -> BackendResult {
3089 match result_struct {
3090 Some(struct_name) => {
3091 let mut has_point_size = false;
3092 let result_ty = context.function.result.as_ref().unwrap().ty;
3093 match context.module.types[result_ty].inner {
3094 crate::TypeInner::Struct { ref members, .. } => {
3095 let tmp = "_tmp";
3096 write!(self.out, "{level}const auto {tmp} = ")?;
3097 self.put_expression(expr_handle, context, true)?;
3098 writeln!(self.out, ";")?;
3099 write!(self.out, "{level}return {struct_name} {{")?;
3100
3101 let mut is_first = true;
3102
3103 for (index, member) in members.iter().enumerate() {
3104 if let Some(crate::Binding::BuiltIn(crate::BuiltIn::PointSize)) =
3105 member.binding
3106 {
3107 has_point_size = true;
3108 if !context.pipeline_options.allow_and_force_point_size {
3109 continue;
3110 }
3111 }
3112
3113 let comma = if is_first { "" } else { "," };
3114 is_first = false;
3115 let name = &self.names[&NameKey::StructMember(result_ty, index as u32)];
3116 // HACK: we are forcefully deduplicating the expression here
3117 // to convert from a wrapped struct to a raw array, e.g.
3118 // `float gl_ClipDistance1 [[clip_distance]] [1];`.
3119 if let crate::TypeInner::Array {
3120 size: crate::ArraySize::Constant(size),
3121 ..
3122 } = context.module.types[member.ty].inner
3123 {
3124 write!(self.out, "{comma} {{")?;
3125 for j in 0..size.get() {
3126 if j != 0 {
3127 write!(self.out, ",")?;
3128 }
3129 write!(self.out, "{tmp}.{name}.{WRAPPED_ARRAY_FIELD}[{j}]")?;
3130 }
3131 write!(self.out, "}}")?;
3132 } else {
3133 write!(self.out, "{comma} {tmp}.{name}")?;
3134 }
3135 }
3136 }
3137 _ => {
3138 write!(self.out, "{level}return {struct_name} {{ ")?;
3139 self.put_expression(expr_handle, context, true)?;
3140 }
3141 }
3142
3143 if let FunctionOrigin::EntryPoint(ep_index) = context.origin {
3144 let stage = context.module.entry_points[ep_index as usize].stage;
3145 if context.pipeline_options.allow_and_force_point_size
3146 && stage == crate::ShaderStage::Vertex
3147 && !has_point_size
3148 {
3149 // point size was injected and comes last
3150 write!(self.out, ", 1.0")?;
3151 }
3152 }
3153 write!(self.out, " }}")?;
3154 }
3155 None => {
3156 write!(self.out, "{level}return ")?;
3157 self.put_expression(expr_handle, context, true)?;
3158 }
3159 }
3160 writeln!(self.out, ";")?;
3161 Ok(())
3162 }
3163
3164 /// Helper method used to find which expressions of a given function require baking
3165 ///
3166 /// # Notes
3167 /// This function overwrites the contents of `self.need_bake_expressions`
3168 fn update_expressions_to_bake(
3169 &mut self,
3170 func: &crate::Function,
3171 info: &valid::FunctionInfo,
3172 context: &ExpressionContext,
3173 ) {
3174 use crate::Expression;
3175 self.need_bake_expressions.clear();
3176
3177 for (expr_handle, expr) in func.expressions.iter() {
3178 // Expressions whose reference count is above the
3179 // threshold should always be stored in temporaries.
3180 let expr_info = &info[expr_handle];
3181 let min_ref_count = func.expressions[expr_handle].bake_ref_count();
3182 if min_ref_count <= expr_info.ref_count {
3183 self.need_bake_expressions.insert(expr_handle);
3184 } else {
3185 match expr_info.ty {
3186 // force ray desc to be baked: it's used multiple times internally
3187 TypeResolution::Handle(h)
3188 if Some(h) == context.module.special_types.ray_desc =>
3189 {
3190 self.need_bake_expressions.insert(expr_handle);
3191 }
3192 _ => {}
3193 }
3194 }
3195
3196 if let Expression::Math {
3197 fun,
3198 arg,
3199 arg1,
3200 arg2,
3201 ..
3202 } = *expr
3203 {
3204 match fun {
3205 crate::MathFunction::Dot => {
3206 // WGSL's `dot` function works on any `vecN` type, but Metal's only
3207 // works on floating-point vectors, so we emit inline code for
3208 // integer vector `dot` calls. But that code uses each argument `N`
3209 // times, once for each component (see `put_dot_product`), so to
3210 // avoid duplicated evaluation, we must bake integer operands.
3211
3212 // check what kind of product this is depending
3213 // on the resolve type of the Dot function itself
3214 let inner = context.resolve_type(expr_handle);
3215 if let crate::TypeInner::Scalar(scalar) = *inner {
3216 match scalar.kind {
3217 crate::ScalarKind::Sint | crate::ScalarKind::Uint => {
3218 self.need_bake_expressions.insert(arg);
3219 self.need_bake_expressions.insert(arg1.unwrap());
3220 }
3221 _ => {}
3222 }
3223 }
3224 }
3225 crate::MathFunction::Dot4U8Packed | crate::MathFunction::Dot4I8Packed => {
3226 self.need_bake_expressions.insert(arg);
3227 self.need_bake_expressions.insert(arg1.unwrap());
3228 }
3229 crate::MathFunction::FirstLeadingBit
3230 | crate::MathFunction::Pack4xI8
3231 | crate::MathFunction::Pack4xU8
3232 | crate::MathFunction::Pack4xI8Clamp
3233 | crate::MathFunction::Pack4xU8Clamp
3234 | crate::MathFunction::Unpack4xI8
3235 | crate::MathFunction::Unpack4xU8 => {
3236 self.need_bake_expressions.insert(arg);
3237 }
3238 crate::MathFunction::ExtractBits => {
3239 // Only argument 1 is re-used.
3240 self.need_bake_expressions.insert(arg1.unwrap());
3241 }
3242 crate::MathFunction::InsertBits => {
3243 // Only argument 2 is re-used.
3244 self.need_bake_expressions.insert(arg2.unwrap());
3245 }
3246 crate::MathFunction::Sign => {
3247 // WGSL's `sign` function works also on signed ints, but Metal's only
3248 // works on floating points, so we emit inline code for integer `sign`
3249 // calls. But that code uses each argument 2 times (see `put_isign`),
3250 // so to avoid duplicated evaluation, we must bake the argument.
3251 let inner = context.resolve_type(expr_handle);
3252 if inner.scalar_kind() == Some(crate::ScalarKind::Sint) {
3253 self.need_bake_expressions.insert(arg);
3254 }
3255 }
3256 _ => {}
3257 }
3258 }
3259 }
3260 }
3261
3262 fn start_baking_expression(
3263 &mut self,
3264 handle: Handle<crate::Expression>,
3265 context: &ExpressionContext,
3266 name: &str,
3267 ) -> BackendResult {
3268 match context.info[handle].ty {
3269 TypeResolution::Handle(ty_handle) => {
3270 let ty_name = TypeContext {
3271 handle: ty_handle,
3272 gctx: context.module.to_ctx(),
3273 names: &self.names,
3274 access: crate::StorageAccess::empty(),
3275 first_time: false,
3276 };
3277 write!(self.out, "{ty_name}")?;
3278 }
3279 TypeResolution::Value(crate::TypeInner::Scalar(scalar)) => {
3280 put_numeric_type(&mut self.out, scalar, &[])?;
3281 }
3282 TypeResolution::Value(crate::TypeInner::Vector { size, scalar }) => {
3283 put_numeric_type(&mut self.out, scalar, &[size])?;
3284 }
3285 TypeResolution::Value(crate::TypeInner::Matrix {
3286 columns,
3287 rows,
3288 scalar,
3289 }) => {
3290 put_numeric_type(&mut self.out, scalar, &[rows, columns])?;
3291 }
3292 TypeResolution::Value(ref other) => {
3293 log::warn!("Type {:?} isn't a known local", other); //TEMP!
3294 return Err(Error::FeatureNotImplemented("weird local type".to_string()));
3295 }
3296 }
3297
3298 //TODO: figure out the naming scheme that wouldn't collide with user names.
3299 write!(self.out, " {name} = ")?;
3300
3301 Ok(())
3302 }
3303
3304 /// Cache a clamped level of detail value, if necessary.
3305 ///
3306 /// [`ImageLoad`] accesses covered by [`BoundsCheckPolicy::Restrict`] use a
3307 /// properly clamped level of detail value both in the access itself, and
3308 /// for fetching the size of the requested MIP level, needed to clamp the
3309 /// coordinates. To avoid recomputing this clamped level of detail, we cache
3310 /// it in a temporary variable, as part of the [`Emit`] statement covering
3311 /// the [`ImageLoad`] expression.
3312 ///
3313 /// [`ImageLoad`]: crate::Expression::ImageLoad
3314 /// [`BoundsCheckPolicy::Restrict`]: index::BoundsCheckPolicy::Restrict
3315 /// [`Emit`]: crate::Statement::Emit
3316 fn put_cache_restricted_level(
3317 &mut self,
3318 load: Handle<crate::Expression>,
3319 image: Handle<crate::Expression>,
3320 mip_level: Option<Handle<crate::Expression>>,
3321 indent: back::Level,
3322 context: &StatementContext,
3323 ) -> BackendResult {
3324 // Does this image access actually require (or even permit) a
3325 // level-of-detail, and does the policy require us to restrict it?
3326 let level_of_detail = match mip_level {
3327 Some(level) => level,
3328 None => return Ok(()),
3329 };
3330
3331 if context.expression.policies.image_load != index::BoundsCheckPolicy::Restrict
3332 || !context.expression.image_needs_lod(image)
3333 {
3334 return Ok(());
3335 }
3336
3337 write!(self.out, "{}uint {} = ", indent, ClampedLod(load),)?;
3338 self.put_restricted_scalar_image_index(
3339 image,
3340 level_of_detail,
3341 "get_num_mip_levels",
3342 &context.expression,
3343 )?;
3344 writeln!(self.out, ";")?;
3345
3346 Ok(())
3347 }
3348
3349 fn put_block(
3350 &mut self,
3351 level: back::Level,
3352 statements: &[crate::Statement],
3353 context: &StatementContext,
3354 ) -> BackendResult {
3355 // Add to the set in order to track the stack size.
3356 #[cfg(test)]
3357 self.put_block_stack_pointers
3358 .insert(ptr::from_ref(&level).cast());
3359
3360 for statement in statements {
3361 log::trace!("statement[{}] {:?}", level.0, statement);
3362 match *statement {
3363 crate::Statement::Emit(ref range) => {
3364 for handle in range.clone() {
3365 // `ImageLoad` expressions covered by the `Restrict` bounds check policy
3366 // may need to cache a clamped version of their level-of-detail argument.
3367 if let crate::Expression::ImageLoad {
3368 image,
3369 level: mip_level,
3370 ..
3371 } = context.expression.function.expressions[handle]
3372 {
3373 self.put_cache_restricted_level(
3374 handle, image, mip_level, level, context,
3375 )?;
3376 }
3377
3378 let ptr_class = context.expression.resolve_type(handle).pointer_space();
3379 let expr_name = if ptr_class.is_some() {
3380 None // don't bake pointer expressions (just yet)
3381 } else if let Some(name) =
3382 context.expression.function.named_expressions.get(&handle)
3383 {
3384 // The `crate::Function::named_expressions` table holds
3385 // expressions that should be saved in temporaries once they
3386 // are `Emit`ted. We only add them to `self.named_expressions`
3387 // when we reach the `Emit` that covers them, so that we don't
3388 // try to use their names before we've actually initialized
3389 // the temporary that holds them.
3390 //
3391 // Don't assume the names in `named_expressions` are unique,
3392 // or even valid. Use the `Namer`.
3393 Some(self.namer.call(name))
3394 } else {
3395 // If this expression is an index that we're going to first compare
3396 // against a limit, and then actually use as an index, then we may
3397 // want to cache it in a temporary, to avoid evaluating it twice.
3398 let bake = if context.expression.guarded_indices.contains(handle) {
3399 true
3400 } else {
3401 self.need_bake_expressions.contains(&handle)
3402 };
3403
3404 if bake {
3405 Some(Baked(handle).to_string())
3406 } else {
3407 None
3408 }
3409 };
3410
3411 if let Some(name) = expr_name {
3412 write!(self.out, "{level}")?;
3413 self.start_baking_expression(handle, &context.expression, &name)?;
3414 self.put_expression(handle, &context.expression, true)?;
3415 self.named_expressions.insert(handle, name);
3416 writeln!(self.out, ";")?;
3417 }
3418 }
3419 }
3420 crate::Statement::Block(ref block) => {
3421 if !block.is_empty() {
3422 writeln!(self.out, "{level}{{")?;
3423 self.put_block(level.next(), block, context)?;
3424 writeln!(self.out, "{level}}}")?;
3425 }
3426 }
3427 crate::Statement::If {
3428 condition,
3429 ref accept,
3430 ref reject,
3431 } => {
3432 write!(self.out, "{level}if (")?;
3433 self.put_expression(condition, &context.expression, true)?;
3434 writeln!(self.out, ") {{")?;
3435 self.put_block(level.next(), accept, context)?;
3436 if !reject.is_empty() {
3437 writeln!(self.out, "{level}}} else {{")?;
3438 self.put_block(level.next(), reject, context)?;
3439 }
3440 writeln!(self.out, "{level}}}")?;
3441 }
3442 crate::Statement::Switch {
3443 selector,
3444 ref cases,
3445 } => {
3446 write!(self.out, "{level}switch(")?;
3447 self.put_expression(selector, &context.expression, true)?;
3448 writeln!(self.out, ") {{")?;
3449 let lcase = level.next();
3450 for case in cases.iter() {
3451 match case.value {
3452 crate::SwitchValue::I32(value) => {
3453 write!(self.out, "{lcase}case {value}:")?;
3454 }
3455 crate::SwitchValue::U32(value) => {
3456 write!(self.out, "{lcase}case {value}u:")?;
3457 }
3458 crate::SwitchValue::Default => {
3459 write!(self.out, "{lcase}default:")?;
3460 }
3461 }
3462
3463 let write_block_braces = !(case.fall_through && case.body.is_empty());
3464 if write_block_braces {
3465 writeln!(self.out, " {{")?;
3466 } else {
3467 writeln!(self.out)?;
3468 }
3469
3470 self.put_block(lcase.next(), &case.body, context)?;
3471 if !case.fall_through && case.body.last().is_none_or(|s| !s.is_terminator())
3472 {
3473 writeln!(self.out, "{}break;", lcase.next())?;
3474 }
3475
3476 if write_block_braces {
3477 writeln!(self.out, "{lcase}}}")?;
3478 }
3479 }
3480 writeln!(self.out, "{level}}}")?;
3481 }
3482 crate::Statement::Loop {
3483 ref body,
3484 ref continuing,
3485 break_if,
3486 } => {
3487 let force_loop_bound_statements =
3488 self.gen_force_bounded_loop_statements(level, context);
3489 let gate_name = (!continuing.is_empty() || break_if.is_some())
3490 .then(|| self.namer.call("loop_init"));
3491
3492 if let Some((ref decl, _)) = force_loop_bound_statements {
3493 writeln!(self.out, "{decl}")?;
3494 }
3495 if let Some(ref gate_name) = gate_name {
3496 writeln!(self.out, "{level}bool {gate_name} = true;")?;
3497 }
3498
3499 writeln!(self.out, "{level}while(true) {{",)?;
3500 if let Some((_, ref break_and_inc)) = force_loop_bound_statements {
3501 writeln!(self.out, "{break_and_inc}")?;
3502 }
3503 if let Some(ref gate_name) = gate_name {
3504 let lif = level.next();
3505 let lcontinuing = lif.next();
3506 writeln!(self.out, "{lif}if (!{gate_name}) {{")?;
3507 self.put_block(lcontinuing, continuing, context)?;
3508 if let Some(condition) = break_if {
3509 write!(self.out, "{lcontinuing}if (")?;
3510 self.put_expression(condition, &context.expression, true)?;
3511 writeln!(self.out, ") {{")?;
3512 writeln!(self.out, "{}break;", lcontinuing.next())?;
3513 writeln!(self.out, "{lcontinuing}}}")?;
3514 }
3515 writeln!(self.out, "{lif}}}")?;
3516 writeln!(self.out, "{lif}{gate_name} = false;")?;
3517 }
3518 self.put_block(level.next(), body, context)?;
3519
3520 writeln!(self.out, "{level}}}")?;
3521 }
3522 crate::Statement::Break => {
3523 writeln!(self.out, "{level}break;")?;
3524 }
3525 crate::Statement::Continue => {
3526 writeln!(self.out, "{level}continue;")?;
3527 }
3528 crate::Statement::Return {
3529 value: Some(expr_handle),
3530 } => {
3531 self.put_return_value(
3532 level,
3533 expr_handle,
3534 context.result_struct,
3535 &context.expression,
3536 )?;
3537 }
3538 crate::Statement::Return { value: None } => {
3539 writeln!(self.out, "{level}return;")?;
3540 }
3541 crate::Statement::Kill => {
3542 writeln!(self.out, "{level}{NAMESPACE}::discard_fragment();")?;
3543 }
3544 crate::Statement::Barrier(flags) => {
3545 self.write_barrier(flags, level)?;
3546 }
3547 crate::Statement::Store { pointer, value } => {
3548 self.put_store(pointer, value, level, context)?
3549 }
3550 crate::Statement::ImageStore {
3551 image,
3552 coordinate,
3553 array_index,
3554 value,
3555 } => {
3556 let address = TexelAddress {
3557 coordinate,
3558 array_index,
3559 sample: None,
3560 level: None,
3561 };
3562 self.put_image_store(level, image, &address, value, context)?
3563 }
3564 crate::Statement::Call {
3565 function,
3566 ref arguments,
3567 result,
3568 } => {
3569 write!(self.out, "{level}")?;
3570 if let Some(expr) = result {
3571 let name = Baked(expr).to_string();
3572 self.start_baking_expression(expr, &context.expression, &name)?;
3573 self.named_expressions.insert(expr, name);
3574 }
3575 let fun_name = &self.names[&NameKey::Function(function)];
3576 write!(self.out, "{fun_name}(")?;
3577 // first, write down the actual arguments
3578 for (i, &handle) in arguments.iter().enumerate() {
3579 if i != 0 {
3580 write!(self.out, ", ")?;
3581 }
3582 self.put_expression(handle, &context.expression, true)?;
3583 }
3584 // follow-up with any global resources used
3585 let mut separate = !arguments.is_empty();
3586 let fun_info = &context.expression.mod_info[function];
3587 let mut needs_buffer_sizes = false;
3588 for (handle, var) in context.expression.module.global_variables.iter() {
3589 if fun_info[handle].is_empty() {
3590 continue;
3591 }
3592 if var.space.needs_pass_through() {
3593 let name = &self.names[&NameKey::GlobalVariable(handle)];
3594 if separate {
3595 write!(self.out, ", ")?;
3596 } else {
3597 separate = true;
3598 }
3599 write!(self.out, "{name}")?;
3600 }
3601 needs_buffer_sizes |=
3602 needs_array_length(var.ty, &context.expression.module.types);
3603 }
3604 if needs_buffer_sizes {
3605 if separate {
3606 write!(self.out, ", ")?;
3607 }
3608 write!(self.out, "_buffer_sizes")?;
3609 }
3610
3611 // done
3612 writeln!(self.out, ");")?;
3613 }
3614 crate::Statement::Atomic {
3615 pointer,
3616 ref fun,
3617 value,
3618 result,
3619 } => {
3620 let context = &context.expression;
3621
3622 // This backend supports `SHADER_INT64_ATOMIC_MIN_MAX` but not
3623 // `SHADER_INT64_ATOMIC_ALL_OPS`, so we can assume that if `result` is
3624 // `Some`, we are not operating on a 64-bit value, and that if we are
3625 // operating on a 64-bit value, `result` is `None`.
3626 write!(self.out, "{level}")?;
3627 let fun_key = if let Some(result) = result {
3628 let res_name = Baked(result).to_string();
3629 self.start_baking_expression(result, context, &res_name)?;
3630 self.named_expressions.insert(result, res_name);
3631 fun.to_msl()
3632 } else if context.resolve_type(value).scalar_width() == Some(8) {
3633 fun.to_msl_64_bit()?
3634 } else {
3635 fun.to_msl()
3636 };
3637
3638 // If the pointer we're passing to the atomic operation needs to be conditional
3639 // for `ReadZeroSkipWrite`, the condition needs to *surround* the atomic op, and
3640 // the pointer operand should be unchecked.
3641 let policy = context.choose_bounds_check_policy(pointer);
3642 let checked = policy == index::BoundsCheckPolicy::ReadZeroSkipWrite
3643 && self.put_bounds_checks(pointer, context, back::Level(0), "")?;
3644
3645 // If requested and successfully put bounds checks, continue the ternary expression.
3646 if checked {
3647 write!(self.out, " ? ")?;
3648 }
3649
3650 // Put the atomic function invocation.
3651 match *fun {
3652 crate::AtomicFunction::Exchange { compare: Some(cmp) } => {
3653 write!(self.out, "{ATOMIC_COMP_EXCH_FUNCTION}({ATOMIC_REFERENCE}")?;
3654 self.put_access_chain(pointer, policy, context)?;
3655 write!(self.out, ", ")?;
3656 self.put_expression(cmp, context, true)?;
3657 write!(self.out, ", ")?;
3658 self.put_expression(value, context, true)?;
3659 write!(self.out, ")")?;
3660 }
3661 _ => {
3662 write!(
3663 self.out,
3664 "{NAMESPACE}::atomic_{fun_key}_explicit({ATOMIC_REFERENCE}"
3665 )?;
3666 self.put_access_chain(pointer, policy, context)?;
3667 write!(self.out, ", ")?;
3668 self.put_expression(value, context, true)?;
3669 write!(self.out, ", {NAMESPACE}::memory_order_relaxed)")?;
3670 }
3671 }
3672
3673 // Finish the ternary expression.
3674 if checked {
3675 write!(self.out, " : DefaultConstructible()")?;
3676 }
3677
3678 // Done
3679 writeln!(self.out, ";")?;
3680 }
3681 crate::Statement::ImageAtomic {
3682 image,
3683 coordinate,
3684 array_index,
3685 fun,
3686 value,
3687 } => {
3688 let address = TexelAddress {
3689 coordinate,
3690 array_index,
3691 sample: None,
3692 level: None,
3693 };
3694 self.put_image_atomic(level, image, &address, fun, value, context)?
3695 }
3696 crate::Statement::WorkGroupUniformLoad { pointer, result } => {
3697 self.write_barrier(crate::Barrier::WORK_GROUP, level)?;
3698
3699 write!(self.out, "{level}")?;
3700 let name = self.namer.call("");
3701 self.start_baking_expression(result, &context.expression, &name)?;
3702 self.put_load(pointer, &context.expression, true)?;
3703 self.named_expressions.insert(result, name);
3704
3705 writeln!(self.out, ";")?;
3706 self.write_barrier(crate::Barrier::WORK_GROUP, level)?;
3707 }
3708 crate::Statement::RayQuery { query, ref fun } => {
3709 if context.expression.lang_version < (2, 4) {
3710 return Err(Error::UnsupportedRayTracing);
3711 }
3712
3713 match *fun {
3714 crate::RayQueryFunction::Initialize {
3715 acceleration_structure,
3716 descriptor,
3717 } => {
3718 //TODO: how to deal with winding?
3719 write!(self.out, "{level}")?;
3720 self.put_expression(query, &context.expression, true)?;
3721 writeln!(self.out, ".{RAY_QUERY_FIELD_INTERSECTOR}.assume_geometry_type({RT_NAMESPACE}::geometry_type::triangle);")?;
3722 {
3723 let f_opaque = back::RayFlag::CULL_OPAQUE.bits();
3724 let f_no_opaque = back::RayFlag::CULL_NO_OPAQUE.bits();
3725 write!(self.out, "{level}")?;
3726 self.put_expression(query, &context.expression, true)?;
3727 write!(
3728 self.out,
3729 ".{RAY_QUERY_FIELD_INTERSECTOR}.set_opacity_cull_mode(("
3730 )?;
3731 self.put_expression(descriptor, &context.expression, true)?;
3732 write!(self.out, ".flags & {f_opaque}) != 0 ? {RT_NAMESPACE}::opacity_cull_mode::opaque : (")?;
3733 self.put_expression(descriptor, &context.expression, true)?;
3734 write!(self.out, ".flags & {f_no_opaque}) != 0 ? {RT_NAMESPACE}::opacity_cull_mode::non_opaque : ")?;
3735 writeln!(self.out, "{RT_NAMESPACE}::opacity_cull_mode::none);")?;
3736 }
3737 {
3738 let f_opaque = back::RayFlag::OPAQUE.bits();
3739 let f_no_opaque = back::RayFlag::NO_OPAQUE.bits();
3740 write!(self.out, "{level}")?;
3741 self.put_expression(query, &context.expression, true)?;
3742 write!(self.out, ".{RAY_QUERY_FIELD_INTERSECTOR}.force_opacity((")?;
3743 self.put_expression(descriptor, &context.expression, true)?;
3744 write!(self.out, ".flags & {f_opaque}) != 0 ? {RT_NAMESPACE}::forced_opacity::opaque : (")?;
3745 self.put_expression(descriptor, &context.expression, true)?;
3746 write!(self.out, ".flags & {f_no_opaque}) != 0 ? {RT_NAMESPACE}::forced_opacity::non_opaque : ")?;
3747 writeln!(self.out, "{RT_NAMESPACE}::forced_opacity::none);")?;
3748 }
3749 {
3750 let flag = back::RayFlag::TERMINATE_ON_FIRST_HIT.bits();
3751 write!(self.out, "{level}")?;
3752 self.put_expression(query, &context.expression, true)?;
3753 write!(
3754 self.out,
3755 ".{RAY_QUERY_FIELD_INTERSECTOR}.accept_any_intersection(("
3756 )?;
3757 self.put_expression(descriptor, &context.expression, true)?;
3758 writeln!(self.out, ".flags & {flag}) != 0);")?;
3759 }
3760
3761 write!(self.out, "{level}")?;
3762 self.put_expression(query, &context.expression, true)?;
3763 write!(self.out, ".{RAY_QUERY_FIELD_INTERSECTION} = ")?;
3764 self.put_expression(query, &context.expression, true)?;
3765 write!(
3766 self.out,
3767 ".{RAY_QUERY_FIELD_INTERSECTOR}.intersect({RT_NAMESPACE}::ray("
3768 )?;
3769 self.put_expression(descriptor, &context.expression, true)?;
3770 write!(self.out, ".origin, ")?;
3771 self.put_expression(descriptor, &context.expression, true)?;
3772 write!(self.out, ".dir, ")?;
3773 self.put_expression(descriptor, &context.expression, true)?;
3774 write!(self.out, ".tmin, ")?;
3775 self.put_expression(descriptor, &context.expression, true)?;
3776 write!(self.out, ".tmax), ")?;
3777 self.put_expression(acceleration_structure, &context.expression, true)?;
3778 write!(self.out, ", ")?;
3779 self.put_expression(descriptor, &context.expression, true)?;
3780 write!(self.out, ".cull_mask);")?;
3781
3782 write!(self.out, "{level}")?;
3783 self.put_expression(query, &context.expression, true)?;
3784 writeln!(self.out, ".{RAY_QUERY_FIELD_READY} = true;")?;
3785 }
3786 crate::RayQueryFunction::Proceed { result } => {
3787 write!(self.out, "{level}")?;
3788 let name = Baked(result).to_string();
3789 self.start_baking_expression(result, &context.expression, &name)?;
3790 self.named_expressions.insert(result, name);
3791 self.put_expression(query, &context.expression, true)?;
3792 writeln!(self.out, ".{RAY_QUERY_FIELD_READY};")?;
3793 if RAY_QUERY_MODERN_SUPPORT {
3794 write!(self.out, "{level}")?;
3795 self.put_expression(query, &context.expression, true)?;
3796 writeln!(self.out, ".?.next();")?;
3797 }
3798 }
3799 crate::RayQueryFunction::GenerateIntersection { hit_t } => {
3800 if RAY_QUERY_MODERN_SUPPORT {
3801 write!(self.out, "{level}")?;
3802 self.put_expression(query, &context.expression, true)?;
3803 write!(self.out, ".?.commit_bounding_box_intersection(")?;
3804 self.put_expression(hit_t, &context.expression, true)?;
3805 writeln!(self.out, ");")?;
3806 } else {
3807 log::warn!("Ray Query GenerateIntersection is not yet supported");
3808 }
3809 }
3810 crate::RayQueryFunction::ConfirmIntersection => {
3811 if RAY_QUERY_MODERN_SUPPORT {
3812 write!(self.out, "{level}")?;
3813 self.put_expression(query, &context.expression, true)?;
3814 writeln!(self.out, ".?.commit_triangle_intersection();")?;
3815 } else {
3816 log::warn!("Ray Query ConfirmIntersection is not yet supported");
3817 }
3818 }
3819 crate::RayQueryFunction::Terminate => {
3820 if RAY_QUERY_MODERN_SUPPORT {
3821 write!(self.out, "{level}")?;
3822 self.put_expression(query, &context.expression, true)?;
3823 writeln!(self.out, ".?.abort();")?;
3824 }
3825 write!(self.out, "{level}")?;
3826 self.put_expression(query, &context.expression, true)?;
3827 writeln!(self.out, ".{RAY_QUERY_FIELD_READY} = false;")?;
3828 }
3829 }
3830 }
3831 crate::Statement::SubgroupBallot { result, predicate } => {
3832 write!(self.out, "{level}")?;
3833 let name = self.namer.call("");
3834 self.start_baking_expression(result, &context.expression, &name)?;
3835 self.named_expressions.insert(result, name);
3836 write!(
3837 self.out,
3838 "{NAMESPACE}::uint4((uint64_t){NAMESPACE}::simd_ballot("
3839 )?;
3840 if let Some(predicate) = predicate {
3841 self.put_expression(predicate, &context.expression, true)?;
3842 } else {
3843 write!(self.out, "true")?;
3844 }
3845 writeln!(self.out, "), 0, 0, 0);")?;
3846 }
3847 crate::Statement::SubgroupCollectiveOperation {
3848 op,
3849 collective_op,
3850 argument,
3851 result,
3852 } => {
3853 write!(self.out, "{level}")?;
3854 let name = self.namer.call("");
3855 self.start_baking_expression(result, &context.expression, &name)?;
3856 self.named_expressions.insert(result, name);
3857 match (collective_op, op) {
3858 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::All) => {
3859 write!(self.out, "{NAMESPACE}::simd_all(")?
3860 }
3861 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Any) => {
3862 write!(self.out, "{NAMESPACE}::simd_any(")?
3863 }
3864 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Add) => {
3865 write!(self.out, "{NAMESPACE}::simd_sum(")?
3866 }
3867 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Mul) => {
3868 write!(self.out, "{NAMESPACE}::simd_product(")?
3869 }
3870 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Max) => {
3871 write!(self.out, "{NAMESPACE}::simd_max(")?
3872 }
3873 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Min) => {
3874 write!(self.out, "{NAMESPACE}::simd_min(")?
3875 }
3876 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::And) => {
3877 write!(self.out, "{NAMESPACE}::simd_and(")?
3878 }
3879 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Or) => {
3880 write!(self.out, "{NAMESPACE}::simd_or(")?
3881 }
3882 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Xor) => {
3883 write!(self.out, "{NAMESPACE}::simd_xor(")?
3884 }
3885 (
3886 crate::CollectiveOperation::ExclusiveScan,
3887 crate::SubgroupOperation::Add,
3888 ) => write!(self.out, "{NAMESPACE}::simd_prefix_exclusive_sum(")?,
3889 (
3890 crate::CollectiveOperation::ExclusiveScan,
3891 crate::SubgroupOperation::Mul,
3892 ) => write!(self.out, "{NAMESPACE}::simd_prefix_exclusive_product(")?,
3893 (
3894 crate::CollectiveOperation::InclusiveScan,
3895 crate::SubgroupOperation::Add,
3896 ) => write!(self.out, "{NAMESPACE}::simd_prefix_inclusive_sum(")?,
3897 (
3898 crate::CollectiveOperation::InclusiveScan,
3899 crate::SubgroupOperation::Mul,
3900 ) => write!(self.out, "{NAMESPACE}::simd_prefix_inclusive_product(")?,
3901 _ => unimplemented!(),
3902 }
3903 self.put_expression(argument, &context.expression, true)?;
3904 writeln!(self.out, ");")?;
3905 }
3906 crate::Statement::SubgroupGather {
3907 mode,
3908 argument,
3909 result,
3910 } => {
3911 write!(self.out, "{level}")?;
3912 let name = self.namer.call("");
3913 self.start_baking_expression(result, &context.expression, &name)?;
3914 self.named_expressions.insert(result, name);
3915 match mode {
3916 crate::GatherMode::BroadcastFirst => {
3917 write!(self.out, "{NAMESPACE}::simd_broadcast_first(")?;
3918 }
3919 crate::GatherMode::Broadcast(_) => {
3920 write!(self.out, "{NAMESPACE}::simd_broadcast(")?;
3921 }
3922 crate::GatherMode::Shuffle(_) => {
3923 write!(self.out, "{NAMESPACE}::simd_shuffle(")?;
3924 }
3925 crate::GatherMode::ShuffleDown(_) => {
3926 write!(self.out, "{NAMESPACE}::simd_shuffle_down(")?;
3927 }
3928 crate::GatherMode::ShuffleUp(_) => {
3929 write!(self.out, "{NAMESPACE}::simd_shuffle_up(")?;
3930 }
3931 crate::GatherMode::ShuffleXor(_) => {
3932 write!(self.out, "{NAMESPACE}::simd_shuffle_xor(")?;
3933 }
3934 }
3935 self.put_expression(argument, &context.expression, true)?;
3936 match mode {
3937 crate::GatherMode::BroadcastFirst => {}
3938 crate::GatherMode::Broadcast(index)
3939 | crate::GatherMode::Shuffle(index)
3940 | crate::GatherMode::ShuffleDown(index)
3941 | crate::GatherMode::ShuffleUp(index)
3942 | crate::GatherMode::ShuffleXor(index) => {
3943 write!(self.out, ", ")?;
3944 self.put_expression(index, &context.expression, true)?;
3945 }
3946 }
3947 writeln!(self.out, ");")?;
3948 }
3949 }
3950 }
3951
3952 // un-emit expressions
3953 //TODO: take care of loop/continuing?
3954 for statement in statements {
3955 if let crate::Statement::Emit(ref range) = *statement {
3956 for handle in range.clone() {
3957 self.named_expressions.shift_remove(&handle);
3958 }
3959 }
3960 }
3961 Ok(())
3962 }
3963
3964 fn put_store(
3965 &mut self,
3966 pointer: Handle<crate::Expression>,
3967 value: Handle<crate::Expression>,
3968 level: back::Level,
3969 context: &StatementContext,
3970 ) -> BackendResult {
3971 let policy = context.expression.choose_bounds_check_policy(pointer);
3972 if policy == index::BoundsCheckPolicy::ReadZeroSkipWrite
3973 && self.put_bounds_checks(pointer, &context.expression, level, "if (")?
3974 {
3975 writeln!(self.out, ") {{")?;
3976 self.put_unchecked_store(pointer, value, policy, level.next(), context)?;
3977 writeln!(self.out, "{level}}}")?;
3978 } else {
3979 self.put_unchecked_store(pointer, value, policy, level, context)?;
3980 }
3981
3982 Ok(())
3983 }
3984
3985 fn put_unchecked_store(
3986 &mut self,
3987 pointer: Handle<crate::Expression>,
3988 value: Handle<crate::Expression>,
3989 policy: index::BoundsCheckPolicy,
3990 level: back::Level,
3991 context: &StatementContext,
3992 ) -> BackendResult {
3993 let is_atomic_pointer = context
3994 .expression
3995 .resolve_type(pointer)
3996 .is_atomic_pointer(&context.expression.module.types);
3997
3998 if is_atomic_pointer {
3999 write!(
4000 self.out,
4001 "{level}{NAMESPACE}::atomic_store_explicit({ATOMIC_REFERENCE}"
4002 )?;
4003 self.put_access_chain(pointer, policy, &context.expression)?;
4004 write!(self.out, ", ")?;
4005 self.put_expression(value, &context.expression, true)?;
4006 writeln!(self.out, ", {NAMESPACE}::memory_order_relaxed);")?;
4007 } else {
4008 write!(self.out, "{level}")?;
4009 self.put_access_chain(pointer, policy, &context.expression)?;
4010 write!(self.out, " = ")?;
4011 self.put_expression(value, &context.expression, true)?;
4012 writeln!(self.out, ";")?;
4013 }
4014
4015 Ok(())
4016 }
4017
4018 pub fn write(
4019 &mut self,
4020 module: &crate::Module,
4021 info: &valid::ModuleInfo,
4022 options: &Options,
4023 pipeline_options: &PipelineOptions,
4024 ) -> Result<TranslationInfo, Error> {
4025 self.names.clear();
4026 self.namer.reset(
4027 module,
4028 &super::keywords::RESERVED_SET,
4029 &[],
4030 &[CLAMPED_LOD_LOAD_PREFIX],
4031 &mut self.names,
4032 );
4033 self.wrapped_functions.clear();
4034 self.struct_member_pads.clear();
4035
4036 writeln!(
4037 self.out,
4038 "// language: metal{}.{}",
4039 options.lang_version.0, options.lang_version.1
4040 )?;
4041 writeln!(self.out, "#include <metal_stdlib>")?;
4042 writeln!(self.out, "#include <simd/simd.h>")?;
4043 writeln!(self.out)?;
4044 // Work around Metal bug where `uint` is not available by default
4045 writeln!(self.out, "using {NAMESPACE}::uint;")?;
4046
4047 let mut uses_ray_query = false;
4048 for (_, ty) in module.types.iter() {
4049 match ty.inner {
4050 crate::TypeInner::AccelerationStructure { .. } => {
4051 if options.lang_version < (2, 4) {
4052 return Err(Error::UnsupportedRayTracing);
4053 }
4054 }
4055 crate::TypeInner::RayQuery { .. } => {
4056 if options.lang_version < (2, 4) {
4057 return Err(Error::UnsupportedRayTracing);
4058 }
4059 uses_ray_query = true;
4060 }
4061 _ => (),
4062 }
4063 }
4064
4065 if module.special_types.ray_desc.is_some()
4066 || module.special_types.ray_intersection.is_some()
4067 {
4068 if options.lang_version < (2, 4) {
4069 return Err(Error::UnsupportedRayTracing);
4070 }
4071 }
4072
4073 if uses_ray_query {
4074 self.put_ray_query_type()?;
4075 }
4076
4077 if options
4078 .bounds_check_policies
4079 .contains(index::BoundsCheckPolicy::ReadZeroSkipWrite)
4080 {
4081 self.put_default_constructible()?;
4082 }
4083 writeln!(self.out)?;
4084
4085 {
4086 // Make a `Vec` of all the `GlobalVariable`s that contain
4087 // runtime-sized arrays.
4088 let globals: Vec<Handle<crate::GlobalVariable>> = module
4089 .global_variables
4090 .iter()
4091 .filter(|&(_, var)| needs_array_length(var.ty, &module.types))
4092 .map(|(handle, _)| handle)
4093 .collect();
4094
4095 let mut buffer_indices = vec![];
4096 for vbm in &pipeline_options.vertex_buffer_mappings {
4097 buffer_indices.push(vbm.id);
4098 }
4099
4100 if !globals.is_empty() || !buffer_indices.is_empty() {
4101 writeln!(self.out, "struct _mslBufferSizes {{")?;
4102
4103 for global in globals {
4104 writeln!(
4105 self.out,
4106 "{}uint {};",
4107 back::INDENT,
4108 ArraySizeMember(global)
4109 )?;
4110 }
4111
4112 for idx in buffer_indices {
4113 writeln!(self.out, "{}uint buffer_size{};", back::INDENT, idx)?;
4114 }
4115
4116 writeln!(self.out, "}};")?;
4117 writeln!(self.out)?;
4118 }
4119 };
4120
4121 self.write_type_defs(module)?;
4122 self.write_global_constants(module, info)?;
4123 self.write_functions(module, info, options, pipeline_options)
4124 }
4125
4126 /// Write the definition for the `DefaultConstructible` class.
4127 ///
4128 /// The [`ReadZeroSkipWrite`] bounds check policy requires us to be able to
4129 /// produce 'zero' values for any type, including structs, arrays, and so
4130 /// on. We could do this by emitting default constructor applications, but
4131 /// that would entail printing the name of the type, which is more trouble
4132 /// than you'd think. Instead, we just construct this magic C++14 class that
4133 /// can be converted to any type that can be default constructed, using
4134 /// template parameter inference to detect which type is needed, so we don't
4135 /// have to figure out the name.
4136 ///
4137 /// [`ReadZeroSkipWrite`]: index::BoundsCheckPolicy::ReadZeroSkipWrite
4138 fn put_default_constructible(&mut self) -> BackendResult {
4139 let tab = back::INDENT;
4140 writeln!(self.out, "struct DefaultConstructible {{")?;
4141 writeln!(self.out, "{tab}template<typename T>")?;
4142 writeln!(self.out, "{tab}operator T() && {{")?;
4143 writeln!(self.out, "{tab}{tab}return T {{}};")?;
4144 writeln!(self.out, "{tab}}}")?;
4145 writeln!(self.out, "}};")?;
4146 Ok(())
4147 }
4148
4149 fn put_ray_query_type(&mut self) -> BackendResult {
4150 let tab = back::INDENT;
4151 writeln!(self.out, "struct {RAY_QUERY_TYPE} {{")?;
4152 let full_type = format!("{RT_NAMESPACE}::intersector<{RT_NAMESPACE}::instancing, {RT_NAMESPACE}::triangle_data, {RT_NAMESPACE}::world_space_data>");
4153 writeln!(self.out, "{tab}{full_type} {RAY_QUERY_FIELD_INTERSECTOR};")?;
4154 writeln!(
4155 self.out,
4156 "{tab}{full_type}::result_type {RAY_QUERY_FIELD_INTERSECTION};"
4157 )?;
4158 writeln!(self.out, "{tab}bool {RAY_QUERY_FIELD_READY} = false;")?;
4159 writeln!(self.out, "}};")?;
4160 writeln!(self.out, "constexpr {NAMESPACE}::uint {RAY_QUERY_FUN_MAP_INTERSECTION}(const {RT_NAMESPACE}::intersection_type ty) {{")?;
4161 let v_triangle = back::RayIntersectionType::Triangle as u32;
4162 let v_bbox = back::RayIntersectionType::BoundingBox as u32;
4163 writeln!(
4164 self.out,
4165 "{tab}return ty=={RT_NAMESPACE}::intersection_type::triangle ? {v_triangle} : "
4166 )?;
4167 writeln!(
4168 self.out,
4169 "{tab}{tab}ty=={RT_NAMESPACE}::intersection_type::bounding_box ? {v_bbox} : 0;"
4170 )?;
4171 writeln!(self.out, "}}")?;
4172 Ok(())
4173 }
4174
4175 fn write_type_defs(&mut self, module: &crate::Module) -> BackendResult {
4176 let mut generated_argument_buffer_wrapper = false;
4177 for (handle, ty) in module.types.iter() {
4178 if let crate::TypeInner::BindingArray { .. } = ty.inner {
4179 if !generated_argument_buffer_wrapper {
4180 writeln!(self.out, "template <typename T>")?;
4181 writeln!(self.out, "struct {ARGUMENT_BUFFER_WRAPPER_STRUCT} {{")?;
4182 writeln!(self.out, "{}T {WRAPPED_ARRAY_FIELD};", back::INDENT)?;
4183 writeln!(self.out, "}};")?;
4184 generated_argument_buffer_wrapper = true;
4185 }
4186 }
4187
4188 if !ty.needs_alias() {
4189 continue;
4190 }
4191 let name = &self.names[&NameKey::Type(handle)];
4192 match ty.inner {
4193 // Naga IR can pass around arrays by value, but Metal, following
4194 // C++, performs an array-to-pointer conversion (C++ [conv.array])
4195 // on expressions of array type, so assigning the array by value
4196 // isn't possible. However, Metal *does* assign structs by
4197 // value. So in our Metal output, we wrap all array types in
4198 // synthetic struct types:
4199 //
4200 // struct type1 {
4201 // float inner[10]
4202 // };
4203 //
4204 // Then we carefully include `.inner` (`WRAPPED_ARRAY_FIELD`) in
4205 // any expression that actually wants access to the array.
4206 crate::TypeInner::Array {
4207 base,
4208 size,
4209 stride: _,
4210 } => {
4211 let base_name = TypeContext {
4212 handle: base,
4213 gctx: module.to_ctx(),
4214 names: &self.names,
4215 access: crate::StorageAccess::empty(),
4216 first_time: false,
4217 };
4218
4219 match size.resolve(module.to_ctx())? {
4220 proc::IndexableLength::Known(size) => {
4221 writeln!(self.out, "struct {name} {{")?;
4222 writeln!(
4223 self.out,
4224 "{}{} {}[{}];",
4225 back::INDENT,
4226 base_name,
4227 WRAPPED_ARRAY_FIELD,
4228 size
4229 )?;
4230 writeln!(self.out, "}};")?;
4231 }
4232 proc::IndexableLength::Dynamic => {
4233 writeln!(self.out, "typedef {base_name} {name}[1];")?;
4234 }
4235 }
4236 }
4237 crate::TypeInner::Struct {
4238 ref members, span, ..
4239 } => {
4240 writeln!(self.out, "struct {name} {{")?;
4241 let mut last_offset = 0;
4242 for (index, member) in members.iter().enumerate() {
4243 if member.offset > last_offset {
4244 self.struct_member_pads.insert((handle, index as u32));
4245 let pad = member.offset - last_offset;
4246 writeln!(self.out, "{}char _pad{}[{}];", back::INDENT, index, pad)?;
4247 }
4248 let ty_inner = &module.types[member.ty].inner;
4249 last_offset = member.offset + ty_inner.size(module.to_ctx());
4250
4251 let member_name = &self.names[&NameKey::StructMember(handle, index as u32)];
4252
4253 // If the member should be packed (as is the case for a misaligned vec3) issue a packed vector
4254 match should_pack_struct_member(members, span, index, module) {
4255 Some(scalar) => {
4256 writeln!(
4257 self.out,
4258 "{}{}::packed_{}3 {};",
4259 back::INDENT,
4260 NAMESPACE,
4261 scalar.to_msl_name(),
4262 member_name
4263 )?;
4264 }
4265 None => {
4266 let base_name = TypeContext {
4267 handle: member.ty,
4268 gctx: module.to_ctx(),
4269 names: &self.names,
4270 access: crate::StorageAccess::empty(),
4271 first_time: false,
4272 };
4273 writeln!(
4274 self.out,
4275 "{}{} {};",
4276 back::INDENT,
4277 base_name,
4278 member_name
4279 )?;
4280
4281 // for 3-component vectors, add one component
4282 if let crate::TypeInner::Vector {
4283 size: crate::VectorSize::Tri,
4284 scalar,
4285 } = *ty_inner
4286 {
4287 last_offset += scalar.width as u32;
4288 }
4289 }
4290 }
4291 }
4292 writeln!(self.out, "}};")?;
4293 }
4294 _ => {
4295 let ty_name = TypeContext {
4296 handle,
4297 gctx: module.to_ctx(),
4298 names: &self.names,
4299 access: crate::StorageAccess::empty(),
4300 first_time: true,
4301 };
4302 writeln!(self.out, "typedef {ty_name} {name};")?;
4303 }
4304 }
4305 }
4306
4307 // Write functions to create special types.
4308 for (type_key, struct_ty) in module.special_types.predeclared_types.iter() {
4309 match type_key {
4310 &crate::PredeclaredType::ModfResult { size, scalar }
4311 | &crate::PredeclaredType::FrexpResult { size, scalar } => {
4312 let arg_type_name_owner;
4313 let arg_type_name = if let Some(size) = size {
4314 arg_type_name_owner = format!(
4315 "{NAMESPACE}::{}{}",
4316 if scalar.width == 8 { "double" } else { "float" },
4317 size as u8
4318 );
4319 &arg_type_name_owner
4320 } else if scalar.width == 8 {
4321 "double"
4322 } else {
4323 "float"
4324 };
4325
4326 let other_type_name_owner;
4327 let (defined_func_name, called_func_name, other_type_name) =
4328 if matches!(type_key, &crate::PredeclaredType::ModfResult { .. }) {
4329 (MODF_FUNCTION, "modf", arg_type_name)
4330 } else {
4331 let other_type_name = if let Some(size) = size {
4332 other_type_name_owner = format!("int{}", size as u8);
4333 &other_type_name_owner
4334 } else {
4335 "int"
4336 };
4337 (FREXP_FUNCTION, "frexp", other_type_name)
4338 };
4339
4340 let struct_name = &self.names[&NameKey::Type(*struct_ty)];
4341
4342 writeln!(self.out)?;
4343 writeln!(
4344 self.out,
4345 "{struct_name} {defined_func_name}({arg_type_name} arg) {{
4346 {other_type_name} other;
4347 {arg_type_name} fract = {NAMESPACE}::{called_func_name}(arg, other);
4348 return {struct_name}{{ fract, other }};
4349 }}"
4350 )?;
4351 }
4352 &crate::PredeclaredType::AtomicCompareExchangeWeakResult(scalar) => {
4353 let arg_type_name = scalar.to_msl_name();
4354 let called_func_name = "atomic_compare_exchange_weak_explicit";
4355 let defined_func_name = ATOMIC_COMP_EXCH_FUNCTION;
4356 let struct_name = &self.names[&NameKey::Type(*struct_ty)];
4357
4358 writeln!(self.out)?;
4359
4360 for address_space_name in ["device", "threadgroup"] {
4361 writeln!(
4362 self.out,
4363 "\
4364 template <typename A>
4365 {struct_name} {defined_func_name}(
4366 {address_space_name} A *atomic_ptr,
4367 {arg_type_name} cmp,
4368 {arg_type_name} v
4369 ) {{
4370 bool swapped = {NAMESPACE}::{called_func_name}(
4371 atomic_ptr, &cmp, v,
4372 metal::memory_order_relaxed, metal::memory_order_relaxed
4373 );
4374 return {struct_name}{{cmp, swapped}};
4375 }}"
4376 )?;
4377 }
4378 }
4379 }
4380 }
4381
4382 Ok(())
4383 }
4384
4385 /// Writes all named constants
4386 fn write_global_constants(
4387 &mut self,
4388 module: &crate::Module,
4389 mod_info: &valid::ModuleInfo,
4390 ) -> BackendResult {
4391 let constants = module.constants.iter().filter(|&(_, c)| c.name.is_some());
4392
4393 for (handle, constant) in constants {
4394 let ty_name = TypeContext {
4395 handle: constant.ty,
4396 gctx: module.to_ctx(),
4397 names: &self.names,
4398 access: crate::StorageAccess::empty(),
4399 first_time: false,
4400 };
4401 let name = &self.names[&NameKey::Constant(handle)];
4402 write!(self.out, "constant {ty_name} {name} = ")?;
4403 self.put_const_expression(constant.init, module, mod_info, &module.global_expressions)?;
4404 writeln!(self.out, ";")?;
4405 }
4406
4407 Ok(())
4408 }
4409
4410 fn put_inline_sampler_properties(
4411 &mut self,
4412 level: back::Level,
4413 sampler: &sm::InlineSampler,
4414 ) -> BackendResult {
4415 for (&letter, address) in ['s', 't', 'r'].iter().zip(sampler.address.iter()) {
4416 writeln!(
4417 self.out,
4418 "{}{}::{}_address::{},",
4419 level,
4420 NAMESPACE,
4421 letter,
4422 address.as_str(),
4423 )?;
4424 }
4425 writeln!(
4426 self.out,
4427 "{}{}::mag_filter::{},",
4428 level,
4429 NAMESPACE,
4430 sampler.mag_filter.as_str(),
4431 )?;
4432 writeln!(
4433 self.out,
4434 "{}{}::min_filter::{},",
4435 level,
4436 NAMESPACE,
4437 sampler.min_filter.as_str(),
4438 )?;
4439 if let Some(filter) = sampler.mip_filter {
4440 writeln!(
4441 self.out,
4442 "{}{}::mip_filter::{},",
4443 level,
4444 NAMESPACE,
4445 filter.as_str(),
4446 )?;
4447 }
4448 // avoid setting it on platforms that don't support it
4449 if sampler.border_color != sm::BorderColor::TransparentBlack {
4450 writeln!(
4451 self.out,
4452 "{}{}::border_color::{},",
4453 level,
4454 NAMESPACE,
4455 sampler.border_color.as_str(),
4456 )?;
4457 }
4458 //TODO: I'm not able to feed this in a way that MSL likes:
4459 //>error: use of undeclared identifier 'lod_clamp'
4460 //>error: no member named 'max_anisotropy' in namespace 'metal'
4461 if false {
4462 if let Some(ref lod) = sampler.lod_clamp {
4463 writeln!(self.out, "{}lod_clamp({},{}),", level, lod.start, lod.end,)?;
4464 }
4465 if let Some(aniso) = sampler.max_anisotropy {
4466 writeln!(self.out, "{}max_anisotropy({}),", level, aniso.get(),)?;
4467 }
4468 }
4469 if sampler.compare_func != sm::CompareFunc::Never {
4470 writeln!(
4471 self.out,
4472 "{}{}::compare_func::{},",
4473 level,
4474 NAMESPACE,
4475 sampler.compare_func.as_str(),
4476 )?;
4477 }
4478 writeln!(
4479 self.out,
4480 "{}{}::coord::{}",
4481 level,
4482 NAMESPACE,
4483 sampler.coord.as_str()
4484 )?;
4485 Ok(())
4486 }
4487
4488 fn write_unpacking_function(
4489 &mut self,
4490 format: back::msl::VertexFormat,
4491 ) -> Result<(String, u32, u32), Error> {
4492 use back::msl::VertexFormat::*;
4493 match format {
4494 Uint8 => {
4495 let name = self.namer.call("unpackUint8");
4496 writeln!(self.out, "uint {name}(metal::uchar b0) {{")?;
4497 writeln!(self.out, "{}return uint(b0);", back::INDENT)?;
4498 writeln!(self.out, "}}")?;
4499 Ok((name, 1, 1))
4500 }
4501 Uint8x2 => {
4502 let name = self.namer.call("unpackUint8x2");
4503 writeln!(
4504 self.out,
4505 "metal::uint2 {name}(metal::uchar b0, \
4506 metal::uchar b1) {{"
4507 )?;
4508 writeln!(self.out, "{}return metal::uint2(b0, b1);", back::INDENT)?;
4509 writeln!(self.out, "}}")?;
4510 Ok((name, 2, 2))
4511 }
4512 Uint8x4 => {
4513 let name = self.namer.call("unpackUint8x4");
4514 writeln!(
4515 self.out,
4516 "metal::uint4 {name}(metal::uchar b0, \
4517 metal::uchar b1, \
4518 metal::uchar b2, \
4519 metal::uchar b3) {{"
4520 )?;
4521 writeln!(
4522 self.out,
4523 "{}return metal::uint4(b0, b1, b2, b3);",
4524 back::INDENT
4525 )?;
4526 writeln!(self.out, "}}")?;
4527 Ok((name, 4, 4))
4528 }
4529 Sint8 => {
4530 let name = self.namer.call("unpackSint8");
4531 writeln!(self.out, "int {name}(metal::uchar b0) {{")?;
4532 writeln!(self.out, "{}return int(as_type<char>(b0));", back::INDENT)?;
4533 writeln!(self.out, "}}")?;
4534 Ok((name, 1, 1))
4535 }
4536 Sint8x2 => {
4537 let name = self.namer.call("unpackSint8x2");
4538 writeln!(
4539 self.out,
4540 "metal::int2 {name}(metal::uchar b0, \
4541 metal::uchar b1) {{"
4542 )?;
4543 writeln!(
4544 self.out,
4545 "{}return metal::int2(as_type<char>(b0), \
4546 as_type<char>(b1));",
4547 back::INDENT
4548 )?;
4549 writeln!(self.out, "}}")?;
4550 Ok((name, 2, 2))
4551 }
4552 Sint8x4 => {
4553 let name = self.namer.call("unpackSint8x4");
4554 writeln!(
4555 self.out,
4556 "metal::int4 {name}(metal::uchar b0, \
4557 metal::uchar b1, \
4558 metal::uchar b2, \
4559 metal::uchar b3) {{"
4560 )?;
4561 writeln!(
4562 self.out,
4563 "{}return metal::int4(as_type<char>(b0), \
4564 as_type<char>(b1), \
4565 as_type<char>(b2), \
4566 as_type<char>(b3));",
4567 back::INDENT
4568 )?;
4569 writeln!(self.out, "}}")?;
4570 Ok((name, 4, 4))
4571 }
4572 Unorm8 => {
4573 let name = self.namer.call("unpackUnorm8");
4574 writeln!(self.out, "float {name}(metal::uchar b0) {{")?;
4575 writeln!(
4576 self.out,
4577 "{}return float(float(b0) / 255.0f);",
4578 back::INDENT
4579 )?;
4580 writeln!(self.out, "}}")?;
4581 Ok((name, 1, 1))
4582 }
4583 Unorm8x2 => {
4584 let name = self.namer.call("unpackUnorm8x2");
4585 writeln!(
4586 self.out,
4587 "metal::float2 {name}(metal::uchar b0, \
4588 metal::uchar b1) {{"
4589 )?;
4590 writeln!(
4591 self.out,
4592 "{}return metal::float2(float(b0) / 255.0f, \
4593 float(b1) / 255.0f);",
4594 back::INDENT
4595 )?;
4596 writeln!(self.out, "}}")?;
4597 Ok((name, 2, 2))
4598 }
4599 Unorm8x4 => {
4600 let name = self.namer.call("unpackUnorm8x4");
4601 writeln!(
4602 self.out,
4603 "metal::float4 {name}(metal::uchar b0, \
4604 metal::uchar b1, \
4605 metal::uchar b2, \
4606 metal::uchar b3) {{"
4607 )?;
4608 writeln!(
4609 self.out,
4610 "{}return metal::float4(float(b0) / 255.0f, \
4611 float(b1) / 255.0f, \
4612 float(b2) / 255.0f, \
4613 float(b3) / 255.0f);",
4614 back::INDENT
4615 )?;
4616 writeln!(self.out, "}}")?;
4617 Ok((name, 4, 4))
4618 }
4619 Snorm8 => {
4620 let name = self.namer.call("unpackSnorm8");
4621 writeln!(self.out, "float {name}(metal::uchar b0) {{")?;
4622 writeln!(
4623 self.out,
4624 "{}return float(metal::max(-1.0f, as_type<char>(b0) / 127.0f));",
4625 back::INDENT
4626 )?;
4627 writeln!(self.out, "}}")?;
4628 Ok((name, 1, 1))
4629 }
4630 Snorm8x2 => {
4631 let name = self.namer.call("unpackSnorm8x2");
4632 writeln!(
4633 self.out,
4634 "metal::float2 {name}(metal::uchar b0, \
4635 metal::uchar b1) {{"
4636 )?;
4637 writeln!(
4638 self.out,
4639 "{}return metal::float2(metal::max(-1.0f, as_type<char>(b0) / 127.0f), \
4640 metal::max(-1.0f, as_type<char>(b1) / 127.0f));",
4641 back::INDENT
4642 )?;
4643 writeln!(self.out, "}}")?;
4644 Ok((name, 2, 2))
4645 }
4646 Snorm8x4 => {
4647 let name = self.namer.call("unpackSnorm8x4");
4648 writeln!(
4649 self.out,
4650 "metal::float4 {name}(metal::uchar b0, \
4651 metal::uchar b1, \
4652 metal::uchar b2, \
4653 metal::uchar b3) {{"
4654 )?;
4655 writeln!(
4656 self.out,
4657 "{}return metal::float4(metal::max(-1.0f, as_type<char>(b0) / 127.0f), \
4658 metal::max(-1.0f, as_type<char>(b1) / 127.0f), \
4659 metal::max(-1.0f, as_type<char>(b2) / 127.0f), \
4660 metal::max(-1.0f, as_type<char>(b3) / 127.0f));",
4661 back::INDENT
4662 )?;
4663 writeln!(self.out, "}}")?;
4664 Ok((name, 4, 4))
4665 }
4666 Uint16 => {
4667 let name = self.namer.call("unpackUint16");
4668 writeln!(
4669 self.out,
4670 "metal::uint {name}(metal::uint b0, \
4671 metal::uint b1) {{"
4672 )?;
4673 writeln!(
4674 self.out,
4675 "{}return metal::uint(b1 << 8 | b0);",
4676 back::INDENT
4677 )?;
4678 writeln!(self.out, "}}")?;
4679 Ok((name, 2, 1))
4680 }
4681 Uint16x2 => {
4682 let name = self.namer.call("unpackUint16x2");
4683 writeln!(
4684 self.out,
4685 "metal::uint2 {name}(metal::uint b0, \
4686 metal::uint b1, \
4687 metal::uint b2, \
4688 metal::uint b3) {{"
4689 )?;
4690 writeln!(
4691 self.out,
4692 "{}return metal::uint2(b1 << 8 | b0, \
4693 b3 << 8 | b2);",
4694 back::INDENT
4695 )?;
4696 writeln!(self.out, "}}")?;
4697 Ok((name, 4, 2))
4698 }
4699 Uint16x4 => {
4700 let name = self.namer.call("unpackUint16x4");
4701 writeln!(
4702 self.out,
4703 "metal::uint4 {name}(metal::uint b0, \
4704 metal::uint b1, \
4705 metal::uint b2, \
4706 metal::uint b3, \
4707 metal::uint b4, \
4708 metal::uint b5, \
4709 metal::uint b6, \
4710 metal::uint b7) {{"
4711 )?;
4712 writeln!(
4713 self.out,
4714 "{}return metal::uint4(b1 << 8 | b0, \
4715 b3 << 8 | b2, \
4716 b5 << 8 | b4, \
4717 b7 << 8 | b6);",
4718 back::INDENT
4719 )?;
4720 writeln!(self.out, "}}")?;
4721 Ok((name, 8, 4))
4722 }
4723 Sint16 => {
4724 let name = self.namer.call("unpackSint16");
4725 writeln!(
4726 self.out,
4727 "int {name}(metal::ushort b0, \
4728 metal::ushort b1) {{"
4729 )?;
4730 writeln!(
4731 self.out,
4732 "{}return int(as_type<short>(metal::ushort(b1 << 8 | b0)));",
4733 back::INDENT
4734 )?;
4735 writeln!(self.out, "}}")?;
4736 Ok((name, 2, 1))
4737 }
4738 Sint16x2 => {
4739 let name = self.namer.call("unpackSint16x2");
4740 writeln!(
4741 self.out,
4742 "metal::int2 {name}(metal::ushort b0, \
4743 metal::ushort b1, \
4744 metal::ushort b2, \
4745 metal::ushort b3) {{"
4746 )?;
4747 writeln!(
4748 self.out,
4749 "{}return metal::int2(as_type<short>(metal::ushort(b1 << 8 | b0)), \
4750 as_type<short>(metal::ushort(b3 << 8 | b2)));",
4751 back::INDENT
4752 )?;
4753 writeln!(self.out, "}}")?;
4754 Ok((name, 4, 2))
4755 }
4756 Sint16x4 => {
4757 let name = self.namer.call("unpackSint16x4");
4758 writeln!(
4759 self.out,
4760 "metal::int4 {name}(metal::ushort b0, \
4761 metal::ushort b1, \
4762 metal::ushort b2, \
4763 metal::ushort b3, \
4764 metal::ushort b4, \
4765 metal::ushort b5, \
4766 metal::ushort b6, \
4767 metal::ushort b7) {{"
4768 )?;
4769 writeln!(
4770 self.out,
4771 "{}return metal::int4(as_type<short>(metal::ushort(b1 << 8 | b0)), \
4772 as_type<short>(metal::ushort(b3 << 8 | b2)), \
4773 as_type<short>(metal::ushort(b5 << 8 | b4)), \
4774 as_type<short>(metal::ushort(b7 << 8 | b6)));",
4775 back::INDENT
4776 )?;
4777 writeln!(self.out, "}}")?;
4778 Ok((name, 8, 4))
4779 }
4780 Unorm16 => {
4781 let name = self.namer.call("unpackUnorm16");
4782 writeln!(
4783 self.out,
4784 "float {name}(metal::ushort b0, \
4785 metal::ushort b1) {{"
4786 )?;
4787 writeln!(
4788 self.out,
4789 "{}return float(float(b1 << 8 | b0) / 65535.0f);",
4790 back::INDENT
4791 )?;
4792 writeln!(self.out, "}}")?;
4793 Ok((name, 2, 1))
4794 }
4795 Unorm16x2 => {
4796 let name = self.namer.call("unpackUnorm16x2");
4797 writeln!(
4798 self.out,
4799 "metal::float2 {name}(metal::ushort b0, \
4800 metal::ushort b1, \
4801 metal::ushort b2, \
4802 metal::ushort b3) {{"
4803 )?;
4804 writeln!(
4805 self.out,
4806 "{}return metal::float2(float(b1 << 8 | b0) / 65535.0f, \
4807 float(b3 << 8 | b2) / 65535.0f);",
4808 back::INDENT
4809 )?;
4810 writeln!(self.out, "}}")?;
4811 Ok((name, 4, 2))
4812 }
4813 Unorm16x4 => {
4814 let name = self.namer.call("unpackUnorm16x4");
4815 writeln!(
4816 self.out,
4817 "metal::float4 {name}(metal::ushort b0, \
4818 metal::ushort b1, \
4819 metal::ushort b2, \
4820 metal::ushort b3, \
4821 metal::ushort b4, \
4822 metal::ushort b5, \
4823 metal::ushort b6, \
4824 metal::ushort b7) {{"
4825 )?;
4826 writeln!(
4827 self.out,
4828 "{}return metal::float4(float(b1 << 8 | b0) / 65535.0f, \
4829 float(b3 << 8 | b2) / 65535.0f, \
4830 float(b5 << 8 | b4) / 65535.0f, \
4831 float(b7 << 8 | b6) / 65535.0f);",
4832 back::INDENT
4833 )?;
4834 writeln!(self.out, "}}")?;
4835 Ok((name, 8, 4))
4836 }
4837 Snorm16 => {
4838 let name = self.namer.call("unpackSnorm16");
4839 writeln!(
4840 self.out,
4841 "float {name}(metal::ushort b0, \
4842 metal::ushort b1) {{"
4843 )?;
4844 writeln!(
4845 self.out,
4846 "{}return metal::unpack_snorm2x16_to_float(b1 << 8 | b0).x;",
4847 back::INDENT
4848 )?;
4849 writeln!(self.out, "}}")?;
4850 Ok((name, 2, 1))
4851 }
4852 Snorm16x2 => {
4853 let name = self.namer.call("unpackSnorm16x2");
4854 writeln!(
4855 self.out,
4856 "metal::float2 {name}(metal::ushort b0, \
4857 metal::ushort b1, \
4858 metal::ushort b2, \
4859 metal::ushort b3) {{"
4860 )?;
4861 writeln!(
4862 self.out,
4863 "{}return metal::unpack_snorm2x16_to_float(b1 << 24 | b0 << 16 | b3 << 8 | b2);",
4864 back::INDENT
4865 )?;
4866 writeln!(self.out, "}}")?;
4867 Ok((name, 4, 2))
4868 }
4869 Snorm16x4 => {
4870 let name = self.namer.call("unpackSnorm16x4");
4871 writeln!(
4872 self.out,
4873 "metal::float4 {name}(metal::ushort b0, \
4874 metal::ushort b1, \
4875 metal::ushort b2, \
4876 metal::ushort b3, \
4877 metal::ushort b4, \
4878 metal::ushort b5, \
4879 metal::ushort b6, \
4880 metal::ushort b7) {{"
4881 )?;
4882 writeln!(
4883 self.out,
4884 "{}return metal::float4(metal::unpack_snorm2x16_to_float(b1 << 24 | b0 << 16 | b3 << 8 | b2), \
4885 metal::unpack_snorm2x16_to_float(b5 << 24 | b4 << 16 | b7 << 8 | b6));",
4886 back::INDENT
4887 )?;
4888 writeln!(self.out, "}}")?;
4889 Ok((name, 8, 4))
4890 }
4891 Float16 => {
4892 let name = self.namer.call("unpackFloat16");
4893 writeln!(
4894 self.out,
4895 "float {name}(metal::ushort b0, \
4896 metal::ushort b1) {{"
4897 )?;
4898 writeln!(
4899 self.out,
4900 "{}return float(as_type<half>(metal::ushort(b1 << 8 | b0)));",
4901 back::INDENT
4902 )?;
4903 writeln!(self.out, "}}")?;
4904 Ok((name, 2, 1))
4905 }
4906 Float16x2 => {
4907 let name = self.namer.call("unpackFloat16x2");
4908 writeln!(
4909 self.out,
4910 "metal::float2 {name}(metal::ushort b0, \
4911 metal::ushort b1, \
4912 metal::ushort b2, \
4913 metal::ushort b3) {{"
4914 )?;
4915 writeln!(
4916 self.out,
4917 "{}return metal::float2(as_type<half>(metal::ushort(b1 << 8 | b0)), \
4918 as_type<half>(metal::ushort(b3 << 8 | b2)));",
4919 back::INDENT
4920 )?;
4921 writeln!(self.out, "}}")?;
4922 Ok((name, 4, 2))
4923 }
4924 Float16x4 => {
4925 let name = self.namer.call("unpackFloat16x4");
4926 writeln!(
4927 self.out,
4928 "metal::float4 {name}(metal::ushort b0, \
4929 metal::ushort b1, \
4930 metal::ushort b2, \
4931 metal::ushort b3, \
4932 metal::ushort b4, \
4933 metal::ushort b5, \
4934 metal::ushort b6, \
4935 metal::ushort b7) {{"
4936 )?;
4937 writeln!(
4938 self.out,
4939 "{}return metal::float4(as_type<half>(metal::ushort(b1 << 8 | b0)), \
4940 as_type<half>(metal::ushort(b3 << 8 | b2)), \
4941 as_type<half>(metal::ushort(b5 << 8 | b4)), \
4942 as_type<half>(metal::ushort(b7 << 8 | b6)));",
4943 back::INDENT
4944 )?;
4945 writeln!(self.out, "}}")?;
4946 Ok((name, 8, 4))
4947 }
4948 Float32 => {
4949 let name = self.namer.call("unpackFloat32");
4950 writeln!(
4951 self.out,
4952 "float {name}(uint b0, \
4953 uint b1, \
4954 uint b2, \
4955 uint b3) {{"
4956 )?;
4957 writeln!(
4958 self.out,
4959 "{}return as_type<float>(b3 << 24 | b2 << 16 | b1 << 8 | b0);",
4960 back::INDENT
4961 )?;
4962 writeln!(self.out, "}}")?;
4963 Ok((name, 4, 1))
4964 }
4965 Float32x2 => {
4966 let name = self.namer.call("unpackFloat32x2");
4967 writeln!(
4968 self.out,
4969 "metal::float2 {name}(uint b0, \
4970 uint b1, \
4971 uint b2, \
4972 uint b3, \
4973 uint b4, \
4974 uint b5, \
4975 uint b6, \
4976 uint b7) {{"
4977 )?;
4978 writeln!(
4979 self.out,
4980 "{}return metal::float2(as_type<float>(b3 << 24 | b2 << 16 | b1 << 8 | b0), \
4981 as_type<float>(b7 << 24 | b6 << 16 | b5 << 8 | b4));",
4982 back::INDENT
4983 )?;
4984 writeln!(self.out, "}}")?;
4985 Ok((name, 8, 2))
4986 }
4987 Float32x3 => {
4988 let name = self.namer.call("unpackFloat32x3");
4989 writeln!(
4990 self.out,
4991 "metal::float3 {name}(uint b0, \
4992 uint b1, \
4993 uint b2, \
4994 uint b3, \
4995 uint b4, \
4996 uint b5, \
4997 uint b6, \
4998 uint b7, \
4999 uint b8, \
5000 uint b9, \
5001 uint b10, \
5002 uint b11) {{"
5003 )?;
5004 writeln!(
5005 self.out,
5006 "{}return metal::float3(as_type<float>(b3 << 24 | b2 << 16 | b1 << 8 | b0), \
5007 as_type<float>(b7 << 24 | b6 << 16 | b5 << 8 | b4), \
5008 as_type<float>(b11 << 24 | b10 << 16 | b9 << 8 | b8));",
5009 back::INDENT
5010 )?;
5011 writeln!(self.out, "}}")?;
5012 Ok((name, 12, 3))
5013 }
5014 Float32x4 => {
5015 let name = self.namer.call("unpackFloat32x4");
5016 writeln!(
5017 self.out,
5018 "metal::float4 {name}(uint b0, \
5019 uint b1, \
5020 uint b2, \
5021 uint b3, \
5022 uint b4, \
5023 uint b5, \
5024 uint b6, \
5025 uint b7, \
5026 uint b8, \
5027 uint b9, \
5028 uint b10, \
5029 uint b11, \
5030 uint b12, \
5031 uint b13, \
5032 uint b14, \
5033 uint b15) {{"
5034 )?;
5035 writeln!(
5036 self.out,
5037 "{}return metal::float4(as_type<float>(b3 << 24 | b2 << 16 | b1 << 8 | b0), \
5038 as_type<float>(b7 << 24 | b6 << 16 | b5 << 8 | b4), \
5039 as_type<float>(b11 << 24 | b10 << 16 | b9 << 8 | b8), \
5040 as_type<float>(b15 << 24 | b14 << 16 | b13 << 8 | b12));",
5041 back::INDENT
5042 )?;
5043 writeln!(self.out, "}}")?;
5044 Ok((name, 16, 4))
5045 }
5046 Uint32 => {
5047 let name = self.namer.call("unpackUint32");
5048 writeln!(
5049 self.out,
5050 "uint {name}(uint b0, \
5051 uint b1, \
5052 uint b2, \
5053 uint b3) {{"
5054 )?;
5055 writeln!(
5056 self.out,
5057 "{}return (b3 << 24 | b2 << 16 | b1 << 8 | b0);",
5058 back::INDENT
5059 )?;
5060 writeln!(self.out, "}}")?;
5061 Ok((name, 4, 1))
5062 }
5063 Uint32x2 => {
5064 let name = self.namer.call("unpackUint32x2");
5065 writeln!(
5066 self.out,
5067 "uint2 {name}(uint b0, \
5068 uint b1, \
5069 uint b2, \
5070 uint b3, \
5071 uint b4, \
5072 uint b5, \
5073 uint b6, \
5074 uint b7) {{"
5075 )?;
5076 writeln!(
5077 self.out,
5078 "{}return uint2((b3 << 24 | b2 << 16 | b1 << 8 | b0), \
5079 (b7 << 24 | b6 << 16 | b5 << 8 | b4));",
5080 back::INDENT
5081 )?;
5082 writeln!(self.out, "}}")?;
5083 Ok((name, 8, 2))
5084 }
5085 Uint32x3 => {
5086 let name = self.namer.call("unpackUint32x3");
5087 writeln!(
5088 self.out,
5089 "uint3 {name}(uint b0, \
5090 uint b1, \
5091 uint b2, \
5092 uint b3, \
5093 uint b4, \
5094 uint b5, \
5095 uint b6, \
5096 uint b7, \
5097 uint b8, \
5098 uint b9, \
5099 uint b10, \
5100 uint b11) {{"
5101 )?;
5102 writeln!(
5103 self.out,
5104 "{}return uint3((b3 << 24 | b2 << 16 | b1 << 8 | b0), \
5105 (b7 << 24 | b6 << 16 | b5 << 8 | b4), \
5106 (b11 << 24 | b10 << 16 | b9 << 8 | b8));",
5107 back::INDENT
5108 )?;
5109 writeln!(self.out, "}}")?;
5110 Ok((name, 12, 3))
5111 }
5112 Uint32x4 => {
5113 let name = self.namer.call("unpackUint32x4");
5114 writeln!(
5115 self.out,
5116 "{NAMESPACE}::uint4 {name}(uint b0, \
5117 uint b1, \
5118 uint b2, \
5119 uint b3, \
5120 uint b4, \
5121 uint b5, \
5122 uint b6, \
5123 uint b7, \
5124 uint b8, \
5125 uint b9, \
5126 uint b10, \
5127 uint b11, \
5128 uint b12, \
5129 uint b13, \
5130 uint b14, \
5131 uint b15) {{"
5132 )?;
5133 writeln!(
5134 self.out,
5135 "{}return {NAMESPACE}::uint4((b3 << 24 | b2 << 16 | b1 << 8 | b0), \
5136 (b7 << 24 | b6 << 16 | b5 << 8 | b4), \
5137 (b11 << 24 | b10 << 16 | b9 << 8 | b8), \
5138 (b15 << 24 | b14 << 16 | b13 << 8 | b12));",
5139 back::INDENT
5140 )?;
5141 writeln!(self.out, "}}")?;
5142 Ok((name, 16, 4))
5143 }
5144 Sint32 => {
5145 let name = self.namer.call("unpackSint32");
5146 writeln!(
5147 self.out,
5148 "int {name}(uint b0, \
5149 uint b1, \
5150 uint b2, \
5151 uint b3) {{"
5152 )?;
5153 writeln!(
5154 self.out,
5155 "{}return as_type<int>(b3 << 24 | b2 << 16 | b1 << 8 | b0);",
5156 back::INDENT
5157 )?;
5158 writeln!(self.out, "}}")?;
5159 Ok((name, 4, 1))
5160 }
5161 Sint32x2 => {
5162 let name = self.namer.call("unpackSint32x2");
5163 writeln!(
5164 self.out,
5165 "metal::int2 {name}(uint b0, \
5166 uint b1, \
5167 uint b2, \
5168 uint b3, \
5169 uint b4, \
5170 uint b5, \
5171 uint b6, \
5172 uint b7) {{"
5173 )?;
5174 writeln!(
5175 self.out,
5176 "{}return metal::int2(as_type<int>(b3 << 24 | b2 << 16 | b1 << 8 | b0), \
5177 as_type<int>(b7 << 24 | b6 << 16 | b5 << 8 | b4));",
5178 back::INDENT
5179 )?;
5180 writeln!(self.out, "}}")?;
5181 Ok((name, 8, 2))
5182 }
5183 Sint32x3 => {
5184 let name = self.namer.call("unpackSint32x3");
5185 writeln!(
5186 self.out,
5187 "metal::int3 {name}(uint b0, \
5188 uint b1, \
5189 uint b2, \
5190 uint b3, \
5191 uint b4, \
5192 uint b5, \
5193 uint b6, \
5194 uint b7, \
5195 uint b8, \
5196 uint b9, \
5197 uint b10, \
5198 uint b11) {{"
5199 )?;
5200 writeln!(
5201 self.out,
5202 "{}return metal::int3(as_type<int>(b3 << 24 | b2 << 16 | b1 << 8 | b0), \
5203 as_type<int>(b7 << 24 | b6 << 16 | b5 << 8 | b4), \
5204 as_type<int>(b11 << 24 | b10 << 16 | b9 << 8 | b8));",
5205 back::INDENT
5206 )?;
5207 writeln!(self.out, "}}")?;
5208 Ok((name, 12, 3))
5209 }
5210 Sint32x4 => {
5211 let name = self.namer.call("unpackSint32x4");
5212 writeln!(
5213 self.out,
5214 "metal::int4 {name}(uint b0, \
5215 uint b1, \
5216 uint b2, \
5217 uint b3, \
5218 uint b4, \
5219 uint b5, \
5220 uint b6, \
5221 uint b7, \
5222 uint b8, \
5223 uint b9, \
5224 uint b10, \
5225 uint b11, \
5226 uint b12, \
5227 uint b13, \
5228 uint b14, \
5229 uint b15) {{"
5230 )?;
5231 writeln!(
5232 self.out,
5233 "{}return metal::int4(as_type<int>(b3 << 24 | b2 << 16 | b1 << 8 | b0), \
5234 as_type<int>(b7 << 24 | b6 << 16 | b5 << 8 | b4), \
5235 as_type<int>(b11 << 24 | b10 << 16 | b9 << 8 | b8), \
5236 as_type<int>(b15 << 24 | b14 << 16 | b13 << 8 | b12));",
5237 back::INDENT
5238 )?;
5239 writeln!(self.out, "}}")?;
5240 Ok((name, 16, 4))
5241 }
5242 Unorm10_10_10_2 => {
5243 let name = self.namer.call("unpackUnorm10_10_10_2");
5244 writeln!(
5245 self.out,
5246 "metal::float4 {name}(uint b0, \
5247 uint b1, \
5248 uint b2, \
5249 uint b3) {{"
5250 )?;
5251 writeln!(
5252 self.out,
5253 // The following is correct for RGBA packing, but our format seems to
5254 // match ABGR, which can be fed into the Metal builtin function
5255 // unpack_unorm10a2_to_float.
5256 /*
5257 "{}uint v = (b3 << 24 | b2 << 16 | b1 << 8 | b0); \
5258 uint r = (v & 0xFFC00000) >> 22; \
5259 uint g = (v & 0x003FF000) >> 12; \
5260 uint b = (v & 0x00000FFC) >> 2; \
5261 uint a = (v & 0x00000003); \
5262 return metal::float4(float(r) / 1023.0f, float(g) / 1023.0f, float(b) / 1023.0f, float(a) / 3.0f);",
5263 */
5264 "{}return metal::unpack_unorm10a2_to_float(b3 << 24 | b2 << 16 | b1 << 8 | b0);",
5265 back::INDENT
5266 )?;
5267 writeln!(self.out, "}}")?;
5268 Ok((name, 4, 4))
5269 }
5270 Unorm8x4Bgra => {
5271 let name = self.namer.call("unpackUnorm8x4Bgra");
5272 writeln!(
5273 self.out,
5274 "metal::float4 {name}(metal::uchar b0, \
5275 metal::uchar b1, \
5276 metal::uchar b2, \
5277 metal::uchar b3) {{"
5278 )?;
5279 writeln!(
5280 self.out,
5281 "{}return metal::float4(float(b2) / 255.0f, \
5282 float(b1) / 255.0f, \
5283 float(b0) / 255.0f, \
5284 float(b3) / 255.0f);",
5285 back::INDENT
5286 )?;
5287 writeln!(self.out, "}}")?;
5288 Ok((name, 4, 4))
5289 }
5290 }
5291 }
5292
5293 pub(super) fn write_wrapped_functions(
5294 &mut self,
5295 module: &crate::Module,
5296 func_ctx: &back::FunctionCtx,
5297 ) -> BackendResult {
5298 for (expr_handle, expr) in func_ctx.expressions.iter() {
5299 match *expr {
5300 crate::Expression::Unary { op, expr: operand } => {
5301 let operand_ty = func_ctx.resolve_type(operand, &module.types);
5302 match op {
5303 // Negating the TYPE_MIN of a two's complement signed integer
5304 // type causes overflow, which is undefined behaviour in MSL. To
5305 // avoid this we bitcast the value to unsigned and negate it,
5306 // then bitcast back to signed.
5307 // This adheres to the WGSL spec in that the negative of the
5308 // type's minimum value should equal to the minimum value.
5309 crate::UnaryOperator::Negate
5310 if operand_ty.scalar_kind() == Some(crate::ScalarKind::Sint) =>
5311 {
5312 let Some((vector_size, scalar)) = operand_ty.vector_size_and_scalar()
5313 else {
5314 continue;
5315 };
5316 let wrapped = WrappedFunction::UnaryOp {
5317 op,
5318 ty: (vector_size, scalar),
5319 };
5320 if !self.wrapped_functions.insert(wrapped) {
5321 continue;
5322 }
5323
5324 let unsigned_scalar = crate::Scalar {
5325 kind: crate::ScalarKind::Uint,
5326 ..scalar
5327 };
5328 let mut type_name = String::new();
5329 let mut unsigned_type_name = String::new();
5330 match vector_size {
5331 None => {
5332 put_numeric_type(&mut type_name, scalar, &[])?;
5333 put_numeric_type(&mut unsigned_type_name, unsigned_scalar, &[])?
5334 }
5335 Some(size) => {
5336 put_numeric_type(&mut type_name, scalar, &[size])?;
5337 put_numeric_type(
5338 &mut unsigned_type_name,
5339 unsigned_scalar,
5340 &[size],
5341 )?;
5342 }
5343 };
5344
5345 writeln!(self.out, "{type_name} {NEG_FUNCTION}({type_name} val) {{")?;
5346 let level = back::Level(1);
5347 writeln!(self.out, "{level}return as_type<{type_name}>(-as_type<{unsigned_type_name}>(val));")?;
5348 writeln!(self.out, "}}")?;
5349 writeln!(self.out)?;
5350 }
5351 _ => {}
5352 }
5353 }
5354 crate::Expression::Binary { op, left, right } => {
5355 let expr_ty = func_ctx.resolve_type(expr_handle, &module.types);
5356 let left_ty = func_ctx.resolve_type(left, &module.types);
5357 let right_ty = func_ctx.resolve_type(right, &module.types);
5358 match (op, expr_ty.scalar_kind()) {
5359 // Signed integer division of TYPE_MIN / -1, or signed or
5360 // unsigned division by zero, gives an unspecified value in MSL.
5361 // We override the divisor to 1 in these cases.
5362 // This adheres to the WGSL spec in that:
5363 // * TYPE_MIN / -1 == TYPE_MIN
5364 // * x / 0 == x
5365 (
5366 crate::BinaryOperator::Divide,
5367 Some(crate::ScalarKind::Sint | crate::ScalarKind::Uint),
5368 ) => {
5369 let Some(left_wrapped_ty) = left_ty.vector_size_and_scalar() else {
5370 continue;
5371 };
5372 let Some(right_wrapped_ty) = right_ty.vector_size_and_scalar() else {
5373 continue;
5374 };
5375 let wrapped = WrappedFunction::BinaryOp {
5376 op,
5377 left_ty: left_wrapped_ty,
5378 right_ty: right_wrapped_ty,
5379 };
5380 if !self.wrapped_functions.insert(wrapped) {
5381 continue;
5382 }
5383
5384 let Some((vector_size, scalar)) = expr_ty.vector_size_and_scalar()
5385 else {
5386 continue;
5387 };
5388 let mut type_name = String::new();
5389 match vector_size {
5390 None => put_numeric_type(&mut type_name, scalar, &[])?,
5391 Some(size) => put_numeric_type(&mut type_name, scalar, &[size])?,
5392 };
5393 writeln!(
5394 self.out,
5395 "{type_name} {DIV_FUNCTION}({type_name} lhs, {type_name} rhs) {{"
5396 )?;
5397 let level = back::Level(1);
5398 match scalar.kind {
5399 crate::ScalarKind::Sint => {
5400 let min_val = match scalar.width {
5401 4 => crate::Literal::I32(i32::MIN),
5402 8 => crate::Literal::I64(i64::MIN),
5403 _ => {
5404 return Err(Error::GenericValidation(format!(
5405 "Unexpected width for scalar {scalar:?}"
5406 )));
5407 }
5408 };
5409 write!(
5410 self.out,
5411 "{level}return lhs / metal::select(rhs, 1, (lhs == "
5412 )?;
5413 self.put_literal(min_val)?;
5414 writeln!(self.out, " & rhs == -1) | (rhs == 0));")?
5415 }
5416 crate::ScalarKind::Uint => writeln!(
5417 self.out,
5418 "{level}return lhs / metal::select(rhs, 1u, rhs == 0u);"
5419 )?,
5420 _ => unreachable!(),
5421 }
5422 writeln!(self.out, "}}")?;
5423 writeln!(self.out)?;
5424 }
5425 // Integer modulo where one or both operands are negative, or the
5426 // divisor is zero, is undefined behaviour in MSL. To avoid this
5427 // we use the following equation:
5428 //
5429 // dividend - (dividend / divisor) * divisor
5430 //
5431 // overriding the divisor to 1 if either it is 0, or it is -1
5432 // and the dividend is TYPE_MIN.
5433 //
5434 // This adheres to the WGSL spec in that:
5435 // * TYPE_MIN % -1 == 0
5436 // * x % 0 == 0
5437 (
5438 crate::BinaryOperator::Modulo,
5439 Some(crate::ScalarKind::Sint | crate::ScalarKind::Uint),
5440 ) => {
5441 let Some(left_wrapped_ty) = left_ty.vector_size_and_scalar() else {
5442 continue;
5443 };
5444 let Some((right_vector_size, right_scalar)) =
5445 right_ty.vector_size_and_scalar()
5446 else {
5447 continue;
5448 };
5449 let wrapped = WrappedFunction::BinaryOp {
5450 op,
5451 left_ty: left_wrapped_ty,
5452 right_ty: (right_vector_size, right_scalar),
5453 };
5454 if !self.wrapped_functions.insert(wrapped) {
5455 continue;
5456 }
5457
5458 let Some((vector_size, scalar)) = expr_ty.vector_size_and_scalar()
5459 else {
5460 continue;
5461 };
5462 let mut type_name = String::new();
5463 match vector_size {
5464 None => put_numeric_type(&mut type_name, scalar, &[])?,
5465 Some(size) => put_numeric_type(&mut type_name, scalar, &[size])?,
5466 };
5467 let mut rhs_type_name = String::new();
5468 match right_vector_size {
5469 None => put_numeric_type(&mut rhs_type_name, right_scalar, &[])?,
5470 Some(size) => {
5471 put_numeric_type(&mut rhs_type_name, right_scalar, &[size])?
5472 }
5473 };
5474
5475 writeln!(
5476 self.out,
5477 "{type_name} {MOD_FUNCTION}({type_name} lhs, {type_name} rhs) {{"
5478 )?;
5479 let level = back::Level(1);
5480 match scalar.kind {
5481 crate::ScalarKind::Sint => {
5482 let min_val = match scalar.width {
5483 4 => crate::Literal::I32(i32::MIN),
5484 8 => crate::Literal::I64(i64::MIN),
5485 _ => {
5486 return Err(Error::GenericValidation(format!(
5487 "Unexpected width for scalar {scalar:?}"
5488 )));
5489 }
5490 };
5491 write!(self.out, "{level}{rhs_type_name} divisor = metal::select(rhs, 1, (lhs == ")?;
5492 self.put_literal(min_val)?;
5493 writeln!(self.out, " & rhs == -1) | (rhs == 0));")?;
5494 writeln!(
5495 self.out,
5496 "{level}return lhs - (lhs / divisor) * divisor;"
5497 )?
5498 }
5499 crate::ScalarKind::Uint => writeln!(
5500 self.out,
5501 "{level}return lhs % metal::select(rhs, 1u, rhs == 0u);"
5502 )?,
5503 _ => unreachable!(),
5504 }
5505 writeln!(self.out, "}}")?;
5506 writeln!(self.out)?;
5507 }
5508 _ => {}
5509 }
5510 }
5511 crate::Expression::Math {
5512 fun,
5513 arg,
5514 arg1: _,
5515 arg2: _,
5516 arg3: _,
5517 } => {
5518 let arg_ty = func_ctx.resolve_type(arg, &module.types);
5519 match fun {
5520 // Taking the absolute value of the TYPE_MIN of a two's
5521 // complement signed integer type causes overflow, which is
5522 // undefined behaviour in MSL. To avoid this, when the value is
5523 // negative we bitcast the value to unsigned and negate it, then
5524 // bitcast back to signed.
5525 // This adheres to the WGSL spec in that the absolute of the
5526 // type's minimum value should equal to the minimum value.
5527 crate::MathFunction::Abs
5528 if arg_ty.scalar_kind() == Some(crate::ScalarKind::Sint) =>
5529 {
5530 let Some((vector_size, scalar)) = arg_ty.vector_size_and_scalar()
5531 else {
5532 continue;
5533 };
5534 let wrapped = WrappedFunction::Math {
5535 fun,
5536 arg_ty: (vector_size, scalar),
5537 };
5538 if !self.wrapped_functions.insert(wrapped) {
5539 continue;
5540 }
5541
5542 let unsigned_scalar = crate::Scalar {
5543 kind: crate::ScalarKind::Uint,
5544 ..scalar
5545 };
5546 let mut type_name = String::new();
5547 let mut unsigned_type_name = String::new();
5548 match vector_size {
5549 None => {
5550 put_numeric_type(&mut type_name, scalar, &[])?;
5551 put_numeric_type(&mut unsigned_type_name, unsigned_scalar, &[])?
5552 }
5553 Some(size) => {
5554 put_numeric_type(&mut type_name, scalar, &[size])?;
5555 put_numeric_type(
5556 &mut unsigned_type_name,
5557 unsigned_scalar,
5558 &[size],
5559 )?;
5560 }
5561 };
5562
5563 writeln!(self.out, "{type_name} {ABS_FUNCTION}({type_name} val) {{")?;
5564 let level = back::Level(1);
5565 writeln!(self.out, "{level}return metal::select(as_type<{type_name}>(-as_type<{unsigned_type_name}>(val)), val, val >= 0);")?;
5566 writeln!(self.out, "}}")?;
5567 writeln!(self.out)?;
5568 }
5569 _ => {}
5570 }
5571 }
5572 crate::Expression::As {
5573 expr,
5574 kind,
5575 convert: Some(width),
5576 } => {
5577 // Avoid undefined behaviour when casting from a float to integer
5578 // when the value is out of range for the target type. Additionally
5579 // ensure we clamp to the correct value as per the WGSL spec.
5580 //
5581 // https://www.w3.org/TR/WGSL/#floating-point-conversion:
5582 // * If X is exactly representable in the target type T, then the
5583 // result is that value.
5584 // * Otherwise, the result is the value in T closest to
5585 // truncate(X) and also exactly representable in the original
5586 // floating point type.
5587 let src_ty = func_ctx.resolve_type(expr, &module.types);
5588 let Some((vector_size, src_scalar)) = src_ty.vector_size_and_scalar() else {
5589 continue;
5590 };
5591 let dst_scalar = crate::Scalar { kind, width };
5592 if src_scalar.kind != crate::ScalarKind::Float
5593 || (dst_scalar.kind != crate::ScalarKind::Sint
5594 && dst_scalar.kind != crate::ScalarKind::Uint)
5595 {
5596 continue;
5597 }
5598 let wrapped = WrappedFunction::Cast {
5599 src_scalar,
5600 vector_size,
5601 dst_scalar,
5602 };
5603 if !self.wrapped_functions.insert(wrapped) {
5604 continue;
5605 }
5606 let (min, max) = proc::min_max_float_representable_by(src_scalar, dst_scalar);
5607
5608 let mut src_type_name = String::new();
5609 match vector_size {
5610 None => put_numeric_type(&mut src_type_name, src_scalar, &[])?,
5611 Some(size) => put_numeric_type(&mut src_type_name, src_scalar, &[size])?,
5612 };
5613 let mut dst_type_name = String::new();
5614 match vector_size {
5615 None => put_numeric_type(&mut dst_type_name, dst_scalar, &[])?,
5616 Some(size) => put_numeric_type(&mut dst_type_name, dst_scalar, &[size])?,
5617 };
5618 let fun_name = match dst_scalar {
5619 crate::Scalar::I32 => F2I32_FUNCTION,
5620 crate::Scalar::U32 => F2U32_FUNCTION,
5621 crate::Scalar::I64 => F2I64_FUNCTION,
5622 crate::Scalar::U64 => F2U64_FUNCTION,
5623 _ => unreachable!(),
5624 };
5625
5626 writeln!(
5627 self.out,
5628 "{dst_type_name} {fun_name}({src_type_name} value) {{"
5629 )?;
5630 let level = back::Level(1);
5631 write!(
5632 self.out,
5633 "{level}return static_cast<{dst_type_name}>({NAMESPACE}::clamp(value, "
5634 )?;
5635 self.put_literal(min)?;
5636 write!(self.out, ", ")?;
5637 self.put_literal(max)?;
5638 writeln!(self.out, "));")?;
5639 writeln!(self.out, "}}")?;
5640 writeln!(self.out)?;
5641 }
5642 _ => {}
5643 }
5644 }
5645
5646 Ok(())
5647 }
5648
5649 // Returns the array of mapped entry point names.
5650 fn write_functions(
5651 &mut self,
5652 module: &crate::Module,
5653 mod_info: &valid::ModuleInfo,
5654 options: &Options,
5655 pipeline_options: &PipelineOptions,
5656 ) -> Result<TranslationInfo, Error> {
5657 use back::msl::VertexFormat;
5658
5659 // Define structs to hold resolved/generated data for vertex buffers and
5660 // their attributes.
5661 struct AttributeMappingResolved {
5662 ty_name: String,
5663 dimension: u32,
5664 ty_is_int: bool,
5665 name: String,
5666 }
5667 let mut am_resolved = FastHashMap::<u32, AttributeMappingResolved>::default();
5668
5669 struct VertexBufferMappingResolved<'a> {
5670 id: u32,
5671 stride: u32,
5672 indexed_by_vertex: bool,
5673 ty_name: String,
5674 param_name: String,
5675 elem_name: String,
5676 attributes: &'a Vec<back::msl::AttributeMapping>,
5677 }
5678 let mut vbm_resolved = Vec::<VertexBufferMappingResolved>::new();
5679
5680 // Define a struct to hold a named reference to a byte-unpacking function.
5681 struct UnpackingFunction {
5682 name: String,
5683 byte_count: u32,
5684 dimension: u32,
5685 }
5686 let mut unpacking_functions = FastHashMap::<VertexFormat, UnpackingFunction>::default();
5687
5688 // Check if we are attempting vertex pulling. If we are, generate some
5689 // names we'll need, and iterate the vertex buffer mappings to output
5690 // all the conversion functions we'll need to unpack the attribute data.
5691 // We can re-use these names for all entry points that need them, since
5692 // those entry points also use self.namer.
5693 let mut needs_vertex_id = false;
5694 let v_id = self.namer.call("v_id");
5695
5696 let mut needs_instance_id = false;
5697 let i_id = self.namer.call("i_id");
5698 if pipeline_options.vertex_pulling_transform {
5699 for vbm in &pipeline_options.vertex_buffer_mappings {
5700 let buffer_id = vbm.id;
5701 let buffer_stride = vbm.stride;
5702
5703 assert!(
5704 buffer_stride > 0,
5705 "Vertex pulling requires a non-zero buffer stride."
5706 );
5707
5708 if vbm.indexed_by_vertex {
5709 needs_vertex_id = true;
5710 } else {
5711 needs_instance_id = true;
5712 }
5713
5714 let buffer_ty = self.namer.call(format!("vb_{buffer_id}_type").as_str());
5715 let buffer_param = self.namer.call(format!("vb_{buffer_id}_in").as_str());
5716 let buffer_elem = self.namer.call(format!("vb_{buffer_id}_elem").as_str());
5717
5718 vbm_resolved.push(VertexBufferMappingResolved {
5719 id: buffer_id,
5720 stride: buffer_stride,
5721 indexed_by_vertex: vbm.indexed_by_vertex,
5722 ty_name: buffer_ty,
5723 param_name: buffer_param,
5724 elem_name: buffer_elem,
5725 attributes: &vbm.attributes,
5726 });
5727
5728 // Iterate the attributes and generate needed unpacking functions.
5729 for attribute in &vbm.attributes {
5730 if unpacking_functions.contains_key(&attribute.format) {
5731 continue;
5732 }
5733 let (name, byte_count, dimension) =
5734 match self.write_unpacking_function(attribute.format) {
5735 Ok((name, byte_count, dimension)) => (name, byte_count, dimension),
5736 _ => {
5737 continue;
5738 }
5739 };
5740 unpacking_functions.insert(
5741 attribute.format,
5742 UnpackingFunction {
5743 name,
5744 byte_count,
5745 dimension,
5746 },
5747 );
5748 }
5749 }
5750 }
5751
5752 let mut pass_through_globals = Vec::new();
5753 for (fun_handle, fun) in module.functions.iter() {
5754 log::trace!(
5755 "function {:?}, handle {:?}",
5756 fun.name.as_deref().unwrap_or("(anonymous)"),
5757 fun_handle
5758 );
5759
5760 let ctx = back::FunctionCtx {
5761 ty: back::FunctionType::Function(fun_handle),
5762 info: &mod_info[fun_handle],
5763 expressions: &fun.expressions,
5764 named_expressions: &fun.named_expressions,
5765 };
5766
5767 writeln!(self.out)?;
5768 self.write_wrapped_functions(module, &ctx)?;
5769
5770 let fun_info = &mod_info[fun_handle];
5771 pass_through_globals.clear();
5772 let mut needs_buffer_sizes = false;
5773 for (handle, var) in module.global_variables.iter() {
5774 if !fun_info[handle].is_empty() {
5775 if var.space.needs_pass_through() {
5776 pass_through_globals.push(handle);
5777 }
5778 needs_buffer_sizes |= needs_array_length(var.ty, &module.types);
5779 }
5780 }
5781
5782 let fun_name = &self.names[&NameKey::Function(fun_handle)];
5783 match fun.result {
5784 Some(ref result) => {
5785 let ty_name = TypeContext {
5786 handle: result.ty,
5787 gctx: module.to_ctx(),
5788 names: &self.names,
5789 access: crate::StorageAccess::empty(),
5790 first_time: false,
5791 };
5792 write!(self.out, "{ty_name}")?;
5793 }
5794 None => {
5795 write!(self.out, "void")?;
5796 }
5797 }
5798 writeln!(self.out, " {fun_name}(")?;
5799
5800 for (index, arg) in fun.arguments.iter().enumerate() {
5801 let name = &self.names[&NameKey::FunctionArgument(fun_handle, index as u32)];
5802 let param_type_name = TypeContext {
5803 handle: arg.ty,
5804 gctx: module.to_ctx(),
5805 names: &self.names,
5806 access: crate::StorageAccess::empty(),
5807 first_time: false,
5808 };
5809 let separator = separate(
5810 !pass_through_globals.is_empty()
5811 || index + 1 != fun.arguments.len()
5812 || needs_buffer_sizes,
5813 );
5814 writeln!(
5815 self.out,
5816 "{}{} {}{}",
5817 back::INDENT,
5818 param_type_name,
5819 name,
5820 separator
5821 )?;
5822 }
5823 for (index, &handle) in pass_through_globals.iter().enumerate() {
5824 let tyvar = TypedGlobalVariable {
5825 module,
5826 names: &self.names,
5827 handle,
5828 usage: fun_info[handle],
5829
5830 reference: true,
5831 };
5832 let separator =
5833 separate(index + 1 != pass_through_globals.len() || needs_buffer_sizes);
5834 write!(self.out, "{}", back::INDENT)?;
5835 tyvar.try_fmt(&mut self.out)?;
5836 writeln!(self.out, "{separator}")?;
5837 }
5838
5839 if needs_buffer_sizes {
5840 writeln!(
5841 self.out,
5842 "{}constant _mslBufferSizes& _buffer_sizes",
5843 back::INDENT
5844 )?;
5845 }
5846
5847 writeln!(self.out, ") {{")?;
5848
5849 let guarded_indices =
5850 index::find_checked_indexes(module, fun, fun_info, options.bounds_check_policies);
5851
5852 let context = StatementContext {
5853 expression: ExpressionContext {
5854 function: fun,
5855 origin: FunctionOrigin::Handle(fun_handle),
5856 info: fun_info,
5857 lang_version: options.lang_version,
5858 policies: options.bounds_check_policies,
5859 guarded_indices,
5860 module,
5861 mod_info,
5862 pipeline_options,
5863 force_loop_bounding: options.force_loop_bounding,
5864 },
5865 result_struct: None,
5866 };
5867
5868 self.put_locals(&context.expression)?;
5869 self.update_expressions_to_bake(fun, fun_info, &context.expression);
5870 self.put_block(back::Level(1), &fun.body, &context)?;
5871 writeln!(self.out, "}}")?;
5872 self.named_expressions.clear();
5873 }
5874
5875 let ep_range = get_entry_points(module, pipeline_options.entry_point.as_ref())
5876 .map_err(|(stage, name)| Error::EntryPointNotFound(stage, name))?;
5877
5878 let mut info = TranslationInfo {
5879 entry_point_names: Vec::with_capacity(ep_range.len()),
5880 };
5881
5882 for ep_index in ep_range {
5883 let ep = &module.entry_points[ep_index];
5884 let fun = &ep.function;
5885 let fun_info = mod_info.get_entry_point(ep_index);
5886 let mut ep_error = None;
5887
5888 // For vertex_id and instance_id arguments, presume that we'll
5889 // use our generated names, but switch to the name of an
5890 // existing @builtin param, if we find one.
5891 let mut v_existing_id = None;
5892 let mut i_existing_id = None;
5893
5894 log::trace!(
5895 "entry point {:?}, index {:?}",
5896 fun.name.as_deref().unwrap_or("(anonymous)"),
5897 ep_index
5898 );
5899
5900 let ctx = back::FunctionCtx {
5901 ty: back::FunctionType::EntryPoint(ep_index as u16),
5902 info: fun_info,
5903 expressions: &fun.expressions,
5904 named_expressions: &fun.named_expressions,
5905 };
5906
5907 self.write_wrapped_functions(module, &ctx)?;
5908
5909 let (em_str, in_mode, out_mode, can_vertex_pull) = match ep.stage {
5910 crate::ShaderStage::Vertex => (
5911 "vertex",
5912 LocationMode::VertexInput,
5913 LocationMode::VertexOutput,
5914 true,
5915 ),
5916 crate::ShaderStage::Fragment => (
5917 "fragment",
5918 LocationMode::FragmentInput,
5919 LocationMode::FragmentOutput,
5920 false,
5921 ),
5922 crate::ShaderStage::Compute => (
5923 "kernel",
5924 LocationMode::Uniform,
5925 LocationMode::Uniform,
5926 false,
5927 ),
5928 crate::ShaderStage::Task | crate::ShaderStage::Mesh => unreachable!(),
5929 };
5930
5931 // Should this entry point be modified to do vertex pulling?
5932 let do_vertex_pulling = can_vertex_pull
5933 && pipeline_options.vertex_pulling_transform
5934 && !pipeline_options.vertex_buffer_mappings.is_empty();
5935
5936 // Is any global variable used by this entry point dynamically sized?
5937 let needs_buffer_sizes = do_vertex_pulling
5938 || module
5939 .global_variables
5940 .iter()
5941 .filter(|&(handle, _)| !fun_info[handle].is_empty())
5942 .any(|(_, var)| needs_array_length(var.ty, &module.types));
5943
5944 // skip this entry point if any global bindings are missing,
5945 // or their types are incompatible.
5946 if !options.fake_missing_bindings {
5947 for (var_handle, var) in module.global_variables.iter() {
5948 if fun_info[var_handle].is_empty() {
5949 continue;
5950 }
5951 match var.space {
5952 crate::AddressSpace::Uniform
5953 | crate::AddressSpace::Storage { .. }
5954 | crate::AddressSpace::Handle => {
5955 let br = match var.binding {
5956 Some(ref br) => br,
5957 None => {
5958 let var_name = var.name.clone().unwrap_or_default();
5959 ep_error =
5960 Some(super::EntryPointError::MissingBinding(var_name));
5961 break;
5962 }
5963 };
5964 let target = options.get_resource_binding_target(ep, br);
5965 let good = match target {
5966 Some(target) => {
5967 // We intentionally don't dereference binding_arrays here,
5968 // so that binding arrays fall to the buffer location.
5969
5970 match module.types[var.ty].inner {
5971 crate::TypeInner::Image { .. } => target.texture.is_some(),
5972 crate::TypeInner::Sampler { .. } => {
5973 target.sampler.is_some()
5974 }
5975 _ => target.buffer.is_some(),
5976 }
5977 }
5978 None => false,
5979 };
5980 if !good {
5981 ep_error = Some(super::EntryPointError::MissingBindTarget(*br));
5982 break;
5983 }
5984 }
5985 crate::AddressSpace::PushConstant => {
5986 if let Err(e) = options.resolve_push_constants(ep) {
5987 ep_error = Some(e);
5988 break;
5989 }
5990 }
5991 crate::AddressSpace::Function
5992 | crate::AddressSpace::Private
5993 | crate::AddressSpace::WorkGroup => {}
5994 }
5995 }
5996 if needs_buffer_sizes {
5997 if let Err(err) = options.resolve_sizes_buffer(ep) {
5998 ep_error = Some(err);
5999 }
6000 }
6001 }
6002
6003 if let Some(err) = ep_error {
6004 info.entry_point_names.push(Err(err));
6005 continue;
6006 }
6007 let fun_name = &self.names[&NameKey::EntryPoint(ep_index as _)];
6008 info.entry_point_names.push(Ok(fun_name.clone()));
6009
6010 writeln!(self.out)?;
6011
6012 // Since `Namer.reset` wasn't expecting struct members to be
6013 // suddenly injected into another namespace like this,
6014 // `self.names` doesn't keep them distinct from other variables.
6015 // Generate fresh names for these arguments, and remember the
6016 // mapping.
6017 let mut flattened_member_names = FastHashMap::default();
6018 // Varyings' members get their own namespace
6019 let mut varyings_namer = proc::Namer::default();
6020
6021 // List all the Naga `EntryPoint`'s `Function`'s arguments,
6022 // flattening structs into their members. In Metal, we will pass
6023 // each of these values to the entry point as a separate argument—
6024 // except for the varyings, handled next.
6025 let mut flattened_arguments = Vec::new();
6026 for (arg_index, arg) in fun.arguments.iter().enumerate() {
6027 match module.types[arg.ty].inner {
6028 crate::TypeInner::Struct { ref members, .. } => {
6029 for (member_index, member) in members.iter().enumerate() {
6030 let member_index = member_index as u32;
6031 flattened_arguments.push((
6032 NameKey::StructMember(arg.ty, member_index),
6033 member.ty,
6034 member.binding.as_ref(),
6035 ));
6036 let name_key = NameKey::StructMember(arg.ty, member_index);
6037 let name = match member.binding {
6038 Some(crate::Binding::Location { .. }) => {
6039 if do_vertex_pulling {
6040 self.namer.call(&self.names[&name_key])
6041 } else {
6042 varyings_namer.call(&self.names[&name_key])
6043 }
6044 }
6045 _ => self.namer.call(&self.names[&name_key]),
6046 };
6047 flattened_member_names.insert(name_key, name);
6048 }
6049 }
6050 _ => flattened_arguments.push((
6051 NameKey::EntryPointArgument(ep_index as _, arg_index as u32),
6052 arg.ty,
6053 arg.binding.as_ref(),
6054 )),
6055 }
6056 }
6057
6058 // Identify the varyings among the argument values, and maybe emit
6059 // a struct type named `<fun>Input` to hold them. If we are doing
6060 // vertex pulling, we instead update our attribute mapping to
6061 // note the types, names, and zero values of the attributes.
6062 let stage_in_name = self.namer.call(&format!("{fun_name}Input"));
6063 let varyings_member_name = self.namer.call("varyings");
6064 let mut has_varyings = false;
6065 if !flattened_arguments.is_empty() {
6066 if !do_vertex_pulling {
6067 writeln!(self.out, "struct {stage_in_name} {{")?;
6068 }
6069 for &(ref name_key, ty, binding) in flattened_arguments.iter() {
6070 let (binding, location) = match binding {
6071 Some(ref binding @ &crate::Binding::Location { location, .. }) => {
6072 (binding, location)
6073 }
6074 _ => continue,
6075 };
6076 let name = match *name_key {
6077 NameKey::StructMember(..) => &flattened_member_names[name_key],
6078 _ => &self.names[name_key],
6079 };
6080 let ty_name = TypeContext {
6081 handle: ty,
6082 gctx: module.to_ctx(),
6083 names: &self.names,
6084 access: crate::StorageAccess::empty(),
6085 first_time: false,
6086 };
6087 let resolved = options.resolve_local_binding(binding, in_mode)?;
6088 if do_vertex_pulling {
6089 // Update our attribute mapping.
6090 am_resolved.insert(
6091 location,
6092 AttributeMappingResolved {
6093 ty_name: ty_name.to_string(),
6094 dimension: ty_name.vertex_input_dimension(),
6095 ty_is_int: ty_name.scalar().is_some_and(scalar_is_int),
6096 name: name.to_string(),
6097 },
6098 );
6099 } else {
6100 has_varyings = true;
6101 write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?;
6102 resolved.try_fmt(&mut self.out)?;
6103 writeln!(self.out, ";")?;
6104 }
6105 }
6106 if !do_vertex_pulling {
6107 writeln!(self.out, "}};")?;
6108 }
6109 }
6110
6111 // Define a struct type named for the return value, if any, named
6112 // `<fun>Output`.
6113 let stage_out_name = self.namer.call(&format!("{fun_name}Output"));
6114 let result_member_name = self.namer.call("member");
6115 let result_type_name = match fun.result {
6116 Some(ref result) => {
6117 let mut result_members = Vec::new();
6118 if let crate::TypeInner::Struct { ref members, .. } =
6119 module.types[result.ty].inner
6120 {
6121 for (member_index, member) in members.iter().enumerate() {
6122 result_members.push((
6123 &self.names[&NameKey::StructMember(result.ty, member_index as u32)],
6124 member.ty,
6125 member.binding.as_ref(),
6126 ));
6127 }
6128 } else {
6129 result_members.push((
6130 &result_member_name,
6131 result.ty,
6132 result.binding.as_ref(),
6133 ));
6134 }
6135
6136 writeln!(self.out, "struct {stage_out_name} {{")?;
6137 let mut has_point_size = false;
6138 for (name, ty, binding) in result_members {
6139 let ty_name = TypeContext {
6140 handle: ty,
6141 gctx: module.to_ctx(),
6142 names: &self.names,
6143 access: crate::StorageAccess::empty(),
6144 first_time: true,
6145 };
6146 let binding = binding.ok_or_else(|| {
6147 Error::GenericValidation("Expected binding, got None".into())
6148 })?;
6149
6150 if let crate::Binding::BuiltIn(crate::BuiltIn::PointSize) = *binding {
6151 has_point_size = true;
6152 if !pipeline_options.allow_and_force_point_size {
6153 continue;
6154 }
6155 }
6156
6157 let array_len = match module.types[ty].inner {
6158 crate::TypeInner::Array {
6159 size: crate::ArraySize::Constant(size),
6160 ..
6161 } => Some(size),
6162 _ => None,
6163 };
6164 let resolved = options.resolve_local_binding(binding, out_mode)?;
6165 write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?;
6166 if let Some(array_len) = array_len {
6167 write!(self.out, " [{array_len}]")?;
6168 }
6169 resolved.try_fmt(&mut self.out)?;
6170 writeln!(self.out, ";")?;
6171 }
6172
6173 if pipeline_options.allow_and_force_point_size
6174 && ep.stage == crate::ShaderStage::Vertex
6175 && !has_point_size
6176 {
6177 // inject the point size output last
6178 writeln!(
6179 self.out,
6180 "{}float _point_size [[point_size]];",
6181 back::INDENT
6182 )?;
6183 }
6184 writeln!(self.out, "}};")?;
6185 &stage_out_name
6186 }
6187 None => "void",
6188 };
6189
6190 // If we're doing a vertex pulling transform, define the buffer
6191 // structure types.
6192 if do_vertex_pulling {
6193 for vbm in &vbm_resolved {
6194 let buffer_stride = vbm.stride;
6195 let buffer_ty = &vbm.ty_name;
6196
6197 // Define a structure of bytes of the appropriate size.
6198 // When we access the attributes, we'll be unpacking these
6199 // bytes at some offset.
6200 writeln!(
6201 self.out,
6202 "struct {buffer_ty} {{ metal::uchar data[{buffer_stride}]; }};"
6203 )?;
6204 }
6205 }
6206
6207 // Write the entry point function's name, and begin its argument list.
6208 writeln!(self.out, "{em_str} {result_type_name} {fun_name}(")?;
6209 let mut is_first_argument = true;
6210
6211 // If we have produced a struct holding the `EntryPoint`'s
6212 // `Function`'s arguments' varyings, pass that struct first.
6213 if has_varyings {
6214 writeln!(
6215 self.out,
6216 " {stage_in_name} {varyings_member_name} [[stage_in]]"
6217 )?;
6218 is_first_argument = false;
6219 }
6220
6221 let mut local_invocation_id = None;
6222
6223 // Then pass the remaining arguments not included in the varyings
6224 // struct.
6225 for &(ref name_key, ty, binding) in flattened_arguments.iter() {
6226 let binding = match binding {
6227 Some(binding @ &crate::Binding::BuiltIn { .. }) => binding,
6228 _ => continue,
6229 };
6230 let name = match *name_key {
6231 NameKey::StructMember(..) => &flattened_member_names[name_key],
6232 _ => &self.names[name_key],
6233 };
6234
6235 if binding == &crate::Binding::BuiltIn(crate::BuiltIn::LocalInvocationId) {
6236 local_invocation_id = Some(name_key);
6237 }
6238
6239 let ty_name = TypeContext {
6240 handle: ty,
6241 gctx: module.to_ctx(),
6242 names: &self.names,
6243 access: crate::StorageAccess::empty(),
6244 first_time: false,
6245 };
6246
6247 match *binding {
6248 crate::Binding::BuiltIn(crate::BuiltIn::VertexIndex) => {
6249 v_existing_id = Some(name.clone());
6250 }
6251 crate::Binding::BuiltIn(crate::BuiltIn::InstanceIndex) => {
6252 i_existing_id = Some(name.clone());
6253 }
6254 _ => {}
6255 };
6256
6257 let resolved = options.resolve_local_binding(binding, in_mode)?;
6258 let separator = if is_first_argument {
6259 is_first_argument = false;
6260 ' '
6261 } else {
6262 ','
6263 };
6264 write!(self.out, "{separator} {ty_name} {name}")?;
6265 resolved.try_fmt(&mut self.out)?;
6266 writeln!(self.out)?;
6267 }
6268
6269 let need_workgroup_variables_initialization =
6270 self.need_workgroup_variables_initialization(options, ep, module, fun_info);
6271
6272 if need_workgroup_variables_initialization && local_invocation_id.is_none() {
6273 let separator = if is_first_argument {
6274 is_first_argument = false;
6275 ' '
6276 } else {
6277 ','
6278 };
6279 writeln!(
6280 self.out,
6281 "{separator} {NAMESPACE}::uint3 __local_invocation_id [[thread_position_in_threadgroup]]"
6282 )?;
6283 }
6284
6285 // Those global variables used by this entry point and its callees
6286 // get passed as arguments. `Private` globals are an exception, they
6287 // don't outlive this invocation, so we declare them below as locals
6288 // within the entry point.
6289 for (handle, var) in module.global_variables.iter() {
6290 let usage = fun_info[handle];
6291 if usage.is_empty() || var.space == crate::AddressSpace::Private {
6292 continue;
6293 }
6294
6295 if options.lang_version < (1, 2) {
6296 match var.space {
6297 // This restriction is not documented in the MSL spec
6298 // but validation will fail if it is not upheld.
6299 //
6300 // We infer the required version from the "Function
6301 // Buffer Read-Writes" section of [what's new], where
6302 // the feature sets listed correspond with the ones
6303 // supporting MSL 1.2.
6304 //
6305 // [what's new]: https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/WhatsNewiniOS10tvOS10andOSX1012/WhatsNewiniOS10tvOS10andOSX1012.html
6306 crate::AddressSpace::Storage { access }
6307 if access.contains(crate::StorageAccess::STORE)
6308 && ep.stage == crate::ShaderStage::Fragment =>
6309 {
6310 return Err(Error::UnsupportedWriteableStorageBuffer)
6311 }
6312 crate::AddressSpace::Handle => {
6313 match module.types[var.ty].inner {
6314 crate::TypeInner::Image {
6315 class: crate::ImageClass::Storage { access, .. },
6316 ..
6317 } => {
6318 // This restriction is not documented in the MSL spec
6319 // but validation will fail if it is not upheld.
6320 //
6321 // We infer the required version from the "Function
6322 // Texture Read-Writes" section of [what's new], where
6323 // the feature sets listed correspond with the ones
6324 // supporting MSL 1.2.
6325 //
6326 // [what's new]: https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/WhatsNewiniOS10tvOS10andOSX1012/WhatsNewiniOS10tvOS10andOSX1012.html
6327 if access.contains(crate::StorageAccess::STORE)
6328 && (ep.stage == crate::ShaderStage::Vertex
6329 || ep.stage == crate::ShaderStage::Fragment)
6330 {
6331 return Err(Error::UnsupportedWriteableStorageTexture(
6332 ep.stage,
6333 ));
6334 }
6335
6336 if access.contains(
6337 crate::StorageAccess::LOAD | crate::StorageAccess::STORE,
6338 ) {
6339 return Err(Error::UnsupportedRWStorageTexture);
6340 }
6341 }
6342 _ => {}
6343 }
6344 }
6345 _ => {}
6346 }
6347 }
6348
6349 // Check min MSL version for binding arrays
6350 match var.space {
6351 crate::AddressSpace::Handle => match module.types[var.ty].inner {
6352 crate::TypeInner::BindingArray { base, .. } => {
6353 match module.types[base].inner {
6354 crate::TypeInner::Sampler { .. } => {
6355 if options.lang_version < (2, 0) {
6356 return Err(Error::UnsupportedArrayOf(
6357 "samplers".to_string(),
6358 ));
6359 }
6360 }
6361 crate::TypeInner::Image { class, .. } => match class {
6362 crate::ImageClass::Sampled { .. }
6363 | crate::ImageClass::Depth { .. }
6364 | crate::ImageClass::Storage {
6365 access: crate::StorageAccess::LOAD,
6366 ..
6367 } => {
6368 // Array of textures since:
6369 // - iOS: Metal 1.2 (check depends on https://github.com/gfx-rs/naga/issues/2164)
6370 // - macOS: Metal 2
6371
6372 if options.lang_version < (2, 0) {
6373 return Err(Error::UnsupportedArrayOf(
6374 "textures".to_string(),
6375 ));
6376 }
6377 }
6378 crate::ImageClass::Storage {
6379 access: crate::StorageAccess::STORE,
6380 ..
6381 } => {
6382 // Array of write-only textures since:
6383 // - iOS: Metal 2.2 (check depends on https://github.com/gfx-rs/naga/issues/2164)
6384 // - macOS: Metal 2
6385
6386 if options.lang_version < (2, 0) {
6387 return Err(Error::UnsupportedArrayOf(
6388 "write-only textures".to_string(),
6389 ));
6390 }
6391 }
6392 crate::ImageClass::Storage { .. } => {
6393 return Err(Error::UnsupportedArrayOf(
6394 "read-write textures".to_string(),
6395 ));
6396 }
6397 },
6398 _ => {
6399 return Err(Error::UnsupportedArrayOfType(base));
6400 }
6401 }
6402 }
6403 _ => {}
6404 },
6405 _ => {}
6406 }
6407
6408 // the resolves have already been checked for `!fake_missing_bindings` case
6409 let resolved = match var.space {
6410 crate::AddressSpace::PushConstant => options.resolve_push_constants(ep).ok(),
6411 crate::AddressSpace::WorkGroup => None,
6412 _ => options
6413 .resolve_resource_binding(ep, var.binding.as_ref().unwrap())
6414 .ok(),
6415 };
6416 if let Some(ref resolved) = resolved {
6417 // Inline samplers are be defined in the EP body
6418 if resolved.as_inline_sampler(options).is_some() {
6419 continue;
6420 }
6421 }
6422
6423 let tyvar = TypedGlobalVariable {
6424 module,
6425 names: &self.names,
6426 handle,
6427 usage,
6428 reference: true,
6429 };
6430 let separator = if is_first_argument {
6431 is_first_argument = false;
6432 ' '
6433 } else {
6434 ','
6435 };
6436 write!(self.out, "{separator} ")?;
6437 tyvar.try_fmt(&mut self.out)?;
6438 if let Some(resolved) = resolved {
6439 resolved.try_fmt(&mut self.out)?;
6440 }
6441 if let Some(value) = var.init {
6442 write!(self.out, " = ")?;
6443 self.put_const_expression(value, module, mod_info, &module.global_expressions)?;
6444 }
6445 writeln!(self.out)?;
6446 }
6447
6448 if do_vertex_pulling {
6449 assert!(needs_vertex_id || needs_instance_id);
6450
6451 let mut separator = if is_first_argument {
6452 is_first_argument = false;
6453 ' '
6454 } else {
6455 ','
6456 };
6457
6458 if needs_vertex_id && v_existing_id.is_none() {
6459 // Write the [[vertex_id]] argument.
6460 writeln!(self.out, "{separator} uint {v_id} [[vertex_id]]")?;
6461 separator = ',';
6462 }
6463
6464 if needs_instance_id && i_existing_id.is_none() {
6465 writeln!(self.out, "{separator} uint {i_id} [[instance_id]]")?;
6466 }
6467
6468 // Iterate vbm_resolved, output one argument for every vertex buffer,
6469 // using the names we generated earlier.
6470 for vbm in &vbm_resolved {
6471 let id = &vbm.id;
6472 let ty_name = &vbm.ty_name;
6473 let param_name = &vbm.param_name;
6474 writeln!(
6475 self.out,
6476 ", const device {ty_name}* {param_name} [[buffer({id})]]"
6477 )?;
6478 }
6479 }
6480
6481 // If this entry uses any variable-length arrays, their sizes are
6482 // passed as a final struct-typed argument.
6483 if needs_buffer_sizes {
6484 // this is checked earlier
6485 let resolved = options.resolve_sizes_buffer(ep).unwrap();
6486 let separator = if is_first_argument { ' ' } else { ',' };
6487 write!(
6488 self.out,
6489 "{separator} constant _mslBufferSizes& _buffer_sizes",
6490 )?;
6491 resolved.try_fmt(&mut self.out)?;
6492 writeln!(self.out)?;
6493 }
6494
6495 // end of the entry point argument list
6496 writeln!(self.out, ") {{")?;
6497
6498 // Starting the function body.
6499 if do_vertex_pulling {
6500 // Provide zero values for all the attributes, which we will overwrite with
6501 // real data from the vertex attribute buffers, if the indices are in-bounds.
6502 for vbm in &vbm_resolved {
6503 for attribute in vbm.attributes {
6504 let location = attribute.shader_location;
6505 let am_option = am_resolved.get(&location);
6506 if am_option.is_none() {
6507 // This bound attribute isn't used in this entry point, so
6508 // don't bother zero-initializing it.
6509 continue;
6510 }
6511 let am = am_option.unwrap();
6512 let attribute_ty_name = &am.ty_name;
6513 let attribute_name = &am.name;
6514
6515 writeln!(
6516 self.out,
6517 "{}{attribute_ty_name} {attribute_name} = {{}};",
6518 back::Level(1)
6519 )?;
6520 }
6521
6522 // Output a bounds check block that will set real values for the
6523 // attributes, if the bounds are satisfied.
6524 write!(self.out, "{}if (", back::Level(1))?;
6525
6526 let idx = &vbm.id;
6527 let stride = &vbm.stride;
6528 let index_name = if vbm.indexed_by_vertex {
6529 if let Some(ref name) = v_existing_id {
6530 name
6531 } else {
6532 &v_id
6533 }
6534 } else if let Some(ref name) = i_existing_id {
6535 name
6536 } else {
6537 &i_id
6538 };
6539 write!(
6540 self.out,
6541 "{index_name} < (_buffer_sizes.buffer_size{idx} / {stride})"
6542 )?;
6543
6544 writeln!(self.out, ") {{")?;
6545
6546 // Pull the bytes out of the vertex buffer.
6547 let ty_name = &vbm.ty_name;
6548 let elem_name = &vbm.elem_name;
6549 let param_name = &vbm.param_name;
6550
6551 writeln!(
6552 self.out,
6553 "{}const {ty_name} {elem_name} = {param_name}[{index_name}];",
6554 back::Level(2),
6555 )?;
6556
6557 // Now set real values for each of the attributes, by unpacking the data
6558 // from the buffer elements.
6559 for attribute in vbm.attributes {
6560 let location = attribute.shader_location;
6561 let Some(am) = am_resolved.get(&location) else {
6562 // This bound attribute isn't used in this entry point, so
6563 // don't bother extracting the data. Too bad we emitted the
6564 // unpacking function earlier -- it might not get used.
6565 continue;
6566 };
6567 let attribute_name = &am.name;
6568 let attribute_ty_name = &am.ty_name;
6569
6570 let offset = attribute.offset;
6571 let func = unpacking_functions
6572 .get(&attribute.format)
6573 .expect("Should have generated this unpacking function earlier.");
6574 let func_name = &func.name;
6575
6576 // Check dimensionality of the attribute compared to the unpacking
6577 // function. If attribute dimension > unpack dimension, we have to
6578 // pad out the unpack value from a vec4(0, 0, 0, 1) of matching
6579 // scalar type. Otherwise, if attribute dimension is < unpack
6580 // dimension, then we need to explicitly truncate the result.
6581
6582 let needs_padding_or_truncation = am.dimension.cmp(&func.dimension);
6583
6584 if needs_padding_or_truncation != Ordering::Equal {
6585 // Emit a comment flagging that a conversion is happening,
6586 // since the actual logic can be at the end of a long line.
6587 writeln!(
6588 self.out,
6589 "{}// {attribute_ty_name} <- {:?}",
6590 back::Level(2),
6591 attribute.format
6592 )?;
6593 }
6594
6595 write!(self.out, "{}{attribute_name} = ", back::Level(2),)?;
6596
6597 if needs_padding_or_truncation == Ordering::Greater {
6598 // Needs padding: emit constructor call for wider type
6599 write!(self.out, "{attribute_ty_name}(")?;
6600 }
6601
6602 // Emit call to unpacking function
6603 write!(self.out, "{func_name}({elem_name}.data[{offset}]",)?;
6604 for i in (offset + 1)..(offset + func.byte_count) {
6605 write!(self.out, ", {elem_name}.data[{i}]")?;
6606 }
6607 write!(self.out, ")")?;
6608
6609 match needs_padding_or_truncation {
6610 Ordering::Greater => {
6611 // Padding
6612 let zero_value = if am.ty_is_int { "0" } else { "0.0" };
6613 let one_value = if am.ty_is_int { "1" } else { "1.0" };
6614 for i in func.dimension..am.dimension {
6615 write!(
6616 self.out,
6617 ", {}",
6618 if i == 3 { one_value } else { zero_value }
6619 )?;
6620 }
6621 write!(self.out, ")")?;
6622 }
6623 Ordering::Less => {
6624 // Truncate to the first `am.dimension` components
6625 write!(
6626 self.out,
6627 ".{}",
6628 &"xyzw"[0..usize::try_from(am.dimension).unwrap()]
6629 )?;
6630 }
6631 Ordering::Equal => {}
6632 }
6633
6634 writeln!(self.out, ";")?;
6635 }
6636
6637 // End the bounds check / attribute setting block.
6638 writeln!(self.out, "{}}}", back::Level(1))?;
6639 }
6640 }
6641
6642 if need_workgroup_variables_initialization {
6643 self.write_workgroup_variables_initialization(
6644 module,
6645 mod_info,
6646 fun_info,
6647 local_invocation_id,
6648 )?;
6649 }
6650
6651 // Metal doesn't support private mutable variables outside of functions,
6652 // so we put them here, just like the locals.
6653 for (handle, var) in module.global_variables.iter() {
6654 let usage = fun_info[handle];
6655 if usage.is_empty() {
6656 continue;
6657 }
6658 if var.space == crate::AddressSpace::Private {
6659 let tyvar = TypedGlobalVariable {
6660 module,
6661 names: &self.names,
6662 handle,
6663 usage,
6664
6665 reference: false,
6666 };
6667 write!(self.out, "{}", back::INDENT)?;
6668 tyvar.try_fmt(&mut self.out)?;
6669 match var.init {
6670 Some(value) => {
6671 write!(self.out, " = ")?;
6672 self.put_const_expression(
6673 value,
6674 module,
6675 mod_info,
6676 &module.global_expressions,
6677 )?;
6678 writeln!(self.out, ";")?;
6679 }
6680 None => {
6681 writeln!(self.out, " = {{}};")?;
6682 }
6683 };
6684 } else if let Some(ref binding) = var.binding {
6685 // write an inline sampler
6686 let resolved = options.resolve_resource_binding(ep, binding).unwrap();
6687 if let Some(sampler) = resolved.as_inline_sampler(options) {
6688 let name = &self.names[&NameKey::GlobalVariable(handle)];
6689 writeln!(
6690 self.out,
6691 "{}constexpr {}::sampler {}(",
6692 back::INDENT,
6693 NAMESPACE,
6694 name
6695 )?;
6696 self.put_inline_sampler_properties(back::Level(2), sampler)?;
6697 writeln!(self.out, "{});", back::INDENT)?;
6698 }
6699 }
6700 }
6701
6702 // Now take the arguments that we gathered into structs, and the
6703 // structs that we flattened into arguments, and emit local
6704 // variables with initializers that put everything back the way the
6705 // body code expects.
6706 //
6707 // If we had to generate fresh names for struct members passed as
6708 // arguments, be sure to use those names when rebuilding the struct.
6709 //
6710 // "Each day, I change some zeros to ones, and some ones to zeros.
6711 // The rest, I leave alone."
6712 for (arg_index, arg) in fun.arguments.iter().enumerate() {
6713 let arg_name =
6714 &self.names[&NameKey::EntryPointArgument(ep_index as _, arg_index as u32)];
6715 match module.types[arg.ty].inner {
6716 crate::TypeInner::Struct { ref members, .. } => {
6717 let struct_name = &self.names[&NameKey::Type(arg.ty)];
6718 write!(
6719 self.out,
6720 "{}const {} {} = {{ ",
6721 back::INDENT,
6722 struct_name,
6723 arg_name
6724 )?;
6725 for (member_index, member) in members.iter().enumerate() {
6726 let key = NameKey::StructMember(arg.ty, member_index as u32);
6727 let name = &flattened_member_names[&key];
6728 if member_index != 0 {
6729 write!(self.out, ", ")?;
6730 }
6731 // insert padding initialization, if needed
6732 if self
6733 .struct_member_pads
6734 .contains(&(arg.ty, member_index as u32))
6735 {
6736 write!(self.out, "{{}}, ")?;
6737 }
6738 if let Some(crate::Binding::Location { .. }) = member.binding {
6739 if has_varyings {
6740 write!(self.out, "{varyings_member_name}.")?;
6741 }
6742 }
6743 write!(self.out, "{name}")?;
6744 }
6745 writeln!(self.out, " }};")?;
6746 }
6747 _ => {
6748 if let Some(crate::Binding::Location { .. }) = arg.binding {
6749 if has_varyings {
6750 writeln!(
6751 self.out,
6752 "{}const auto {} = {}.{};",
6753 back::INDENT,
6754 arg_name,
6755 varyings_member_name,
6756 arg_name
6757 )?;
6758 }
6759 }
6760 }
6761 }
6762 }
6763
6764 let guarded_indices =
6765 index::find_checked_indexes(module, fun, fun_info, options.bounds_check_policies);
6766
6767 let context = StatementContext {
6768 expression: ExpressionContext {
6769 function: fun,
6770 origin: FunctionOrigin::EntryPoint(ep_index as _),
6771 info: fun_info,
6772 lang_version: options.lang_version,
6773 policies: options.bounds_check_policies,
6774 guarded_indices,
6775 module,
6776 mod_info,
6777 pipeline_options,
6778 force_loop_bounding: options.force_loop_bounding,
6779 },
6780 result_struct: Some(&stage_out_name),
6781 };
6782
6783 // Finally, declare all the local variables that we need
6784 //TODO: we can postpone this till the relevant expressions are emitted
6785 self.put_locals(&context.expression)?;
6786 self.update_expressions_to_bake(fun, fun_info, &context.expression);
6787 self.put_block(back::Level(1), &fun.body, &context)?;
6788 writeln!(self.out, "}}")?;
6789 if ep_index + 1 != module.entry_points.len() {
6790 writeln!(self.out)?;
6791 }
6792 self.named_expressions.clear();
6793 }
6794
6795 Ok(info)
6796 }
6797
6798 fn write_barrier(&mut self, flags: crate::Barrier, level: back::Level) -> BackendResult {
6799 // Note: OR-ring bitflags requires `__HAVE_MEMFLAG_OPERATORS__`,
6800 // so we try to avoid it here.
6801 if flags.is_empty() {
6802 writeln!(
6803 self.out,
6804 "{level}{NAMESPACE}::threadgroup_barrier({NAMESPACE}::mem_flags::mem_none);",
6805 )?;
6806 }
6807 if flags.contains(crate::Barrier::STORAGE) {
6808 writeln!(
6809 self.out,
6810 "{level}{NAMESPACE}::threadgroup_barrier({NAMESPACE}::mem_flags::mem_device);",
6811 )?;
6812 }
6813 if flags.contains(crate::Barrier::WORK_GROUP) {
6814 writeln!(
6815 self.out,
6816 "{level}{NAMESPACE}::threadgroup_barrier({NAMESPACE}::mem_flags::mem_threadgroup);",
6817 )?;
6818 }
6819 if flags.contains(crate::Barrier::SUB_GROUP) {
6820 writeln!(
6821 self.out,
6822 "{level}{NAMESPACE}::simdgroup_barrier({NAMESPACE}::mem_flags::mem_threadgroup);",
6823 )?;
6824 }
6825 if flags.contains(crate::Barrier::TEXTURE) {
6826 writeln!(
6827 self.out,
6828 "{level}{NAMESPACE}::threadgroup_barrier({NAMESPACE}::mem_flags::mem_texture);",
6829 )?;
6830 }
6831 Ok(())
6832 }
6833 }
6834
6835 /// Initializing workgroup variables is more tricky for Metal because we have to deal
6836 /// with atomics at the type-level (which don't have a copy constructor).
6837 mod workgroup_mem_init {
6838 use crate::EntryPoint;
6839
6840 use super::*;
6841
6842 enum Access {
6843 GlobalVariable(Handle<crate::GlobalVariable>),
6844 StructMember(Handle<crate::Type>, u32),
6845 Array(usize),
6846 }
6847
6848 impl Access {
6849 fn write<W: Write>(
6850 &self,
6851 writer: &mut W,
6852 names: &FastHashMap<NameKey, String>,
6853 ) -> Result<(), core::fmt::Error> {
6854 match *self {
6855 Access::GlobalVariable(handle) => {
6856 write!(writer, "{}", &names[&NameKey::GlobalVariable(handle)])
6857 }
6858 Access::StructMember(handle, index) => {
6859 write!(writer, ".{}", &names[&NameKey::StructMember(handle, index)])
6860 }
6861 Access::Array(depth) => write!(writer, ".{WRAPPED_ARRAY_FIELD}[__i{depth}]"),
6862 }
6863 }
6864 }
6865
6866 struct AccessStack {
6867 stack: Vec<Access>,
6868 array_depth: usize,
6869 }
6870
6871 impl AccessStack {
6872 const fn new() -> Self {
6873 Self {
6874 stack: Vec::new(),
6875 array_depth: 0,
6876 }
6877 }
6878
6879 fn enter_array<R>(&mut self, cb: impl FnOnce(&mut Self, usize) -> R) -> R {
6880 let array_depth = self.array_depth;
6881 self.stack.push(Access::Array(array_depth));
6882 self.array_depth += 1;
6883 let res = cb(self, array_depth);
6884 self.stack.pop();
6885 self.array_depth -= 1;
6886 res
6887 }
6888
6889 fn enter<R>(&mut self, new: Access, cb: impl FnOnce(&mut Self) -> R) -> R {
6890 self.stack.push(new);
6891 let res = cb(self);
6892 self.stack.pop();
6893 res
6894 }
6895
6896 fn write<W: Write>(
6897 &self,
6898 writer: &mut W,
6899 names: &FastHashMap<NameKey, String>,
6900 ) -> Result<(), core::fmt::Error> {
6901 for next in self.stack.iter() {
6902 next.write(writer, names)?;
6903 }
6904 Ok(())
6905 }
6906 }
6907
6908 impl<W: Write> Writer<W> {
6909 pub(super) fn need_workgroup_variables_initialization(
6910 &mut self,
6911 options: &Options,
6912 ep: &EntryPoint,
6913 module: &crate::Module,
6914 fun_info: &valid::FunctionInfo,
6915 ) -> bool {
6916 options.zero_initialize_workgroup_memory
6917 && ep.stage == crate::ShaderStage::Compute
6918 && module.global_variables.iter().any(|(handle, var)| {
6919 !fun_info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup
6920 })
6921 }
6922
6923 pub(super) fn write_workgroup_variables_initialization(
6924 &mut self,
6925 module: &crate::Module,
6926 module_info: &valid::ModuleInfo,
6927 fun_info: &valid::FunctionInfo,
6928 local_invocation_id: Option<&NameKey>,
6929 ) -> BackendResult {
6930 let level = back::Level(1);
6931
6932 writeln!(
6933 self.out,
6934 "{}if ({}::all({} == {}::uint3(0u))) {{",
6935 level,
6936 NAMESPACE,
6937 local_invocation_id
6938 .map(|name_key| self.names[name_key].as_str())
6939 .unwrap_or("__local_invocation_id"),
6940 NAMESPACE,
6941 )?;
6942
6943 let mut access_stack = AccessStack::new();
6944
6945 let vars = module.global_variables.iter().filter(|&(handle, var)| {
6946 !fun_info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup
6947 });
6948
6949 for (handle, var) in vars {
6950 access_stack.enter(Access::GlobalVariable(handle), |access_stack| {
6951 self.write_workgroup_variable_initialization(
6952 module,
6953 module_info,
6954 var.ty,
6955 access_stack,
6956 level.next(),
6957 )
6958 })?;
6959 }
6960
6961 writeln!(self.out, "{level}}}")?;
6962 self.write_barrier(crate::Barrier::WORK_GROUP, level)
6963 }
6964
6965 fn write_workgroup_variable_initialization(
6966 &mut self,
6967 module: &crate::Module,
6968 module_info: &valid::ModuleInfo,
6969 ty: Handle<crate::Type>,
6970 access_stack: &mut AccessStack,
6971 level: back::Level,
6972 ) -> BackendResult {
6973 if module_info[ty].contains(valid::TypeFlags::CONSTRUCTIBLE) {
6974 write!(self.out, "{level}")?;
6975 access_stack.write(&mut self.out, &self.names)?;
6976 writeln!(self.out, " = {{}};")?;
6977 } else {
6978 match module.types[ty].inner {
6979 crate::TypeInner::Atomic { .. } => {
6980 write!(
6981 self.out,
6982 "{level}{NAMESPACE}::atomic_store_explicit({ATOMIC_REFERENCE}"
6983 )?;
6984 access_stack.write(&mut self.out, &self.names)?;
6985 writeln!(self.out, ", 0, {NAMESPACE}::memory_order_relaxed);")?;
6986 }
6987 crate::TypeInner::Array { base, size, .. } => {
6988 let count = match size.resolve(module.to_ctx())? {
6989 proc::IndexableLength::Known(count) => count,
6990 proc::IndexableLength::Dynamic => unreachable!(),
6991 };
6992
6993 access_stack.enter_array(|access_stack, array_depth| {
6994 writeln!(
6995 self.out,
6996 "{level}for (int __i{array_depth} = 0; __i{array_depth} < {count}; __i{array_depth}++) {{"
6997 )?;
6998 self.write_workgroup_variable_initialization(
6999 module,
7000 module_info,
7001 base,
7002 access_stack,
7003 level.next(),
7004 )?;
7005 writeln!(self.out, "{level}}}")?;
7006 BackendResult::Ok(())
7007 })?;
7008 }
7009 crate::TypeInner::Struct { ref members, .. } => {
7010 for (index, member) in members.iter().enumerate() {
7011 access_stack.enter(
7012 Access::StructMember(ty, index as u32),
7013 |access_stack| {
7014 self.write_workgroup_variable_initialization(
7015 module,
7016 module_info,
7017 member.ty,
7018 access_stack,
7019 level,
7020 )
7021 },
7022 )?;
7023 }
7024 }
7025 _ => unreachable!(),
7026 }
7027 }
7028
7029 Ok(())
7030 }
7031 }
7032 }
7033
7034 #[test]
7035 fn test_stack_size() {
7036 use crate::valid::{Capabilities, ValidationFlags};
7037 // create a module with at least one expression nested
7038 let mut module = crate::Module::default();
7039 let mut fun = crate::Function::default();
7040 let const_expr = fun.expressions.append(
7041 crate::Expression::Literal(crate::Literal::F32(1.0)),
7042 Default::default(),
7043 );
7044 let nested_expr = fun.expressions.append(
7045 crate::Expression::Unary {
7046 op: crate::UnaryOperator::Negate,
7047 expr: const_expr,
7048 },
7049 Default::default(),
7050 );
7051 fun.body.push(
7052 crate::Statement::Emit(fun.expressions.range_from(1)),
7053 Default::default(),
7054 );
7055 fun.body.push(
7056 crate::Statement::If {
7057 condition: nested_expr,
7058 accept: crate::Block::new(),
7059 reject: crate::Block::new(),
7060 },
7061 Default::default(),
7062 );
7063 let _ = module.functions.append(fun, Default::default());
7064 // analyse the module
7065 let info = valid::Validator::new(ValidationFlags::empty(), Capabilities::empty())
7066 .validate(&module)
7067 .unwrap();
7068 // process the module
7069 let mut writer = Writer::new(String::new());
7070 writer
7071 .write(&module, &info, &Default::default(), &Default::default())
7072 .unwrap();
7073
7074 {
7075 // check expression stack
7076 let mut addresses_start = usize::MAX;
7077 let mut addresses_end = 0usize;
7078 for pointer in writer.put_expression_stack_pointers {
7079 addresses_start = addresses_start.min(pointer as usize);
7080 addresses_end = addresses_end.max(pointer as usize);
7081 }
7082 let stack_size = addresses_end - addresses_start;
7083 // check the size (in debug only)
7084 // last observed macOS value: 25904 (CI), 2025-04-29
7085 if !(11000..=27000).contains(&stack_size) {
7086 panic!("`put_expression` stack size {stack_size} has changed!");
7087 }
7088 }
7089
7090 {
7091 // check block stack
7092 let mut addresses_start = usize::MAX;
7093 let mut addresses_end = 0usize;
7094 for pointer in writer.put_block_stack_pointers {
7095 addresses_start = addresses_start.min(pointer as usize);
7096 addresses_end = addresses_end.max(pointer as usize);
7097 }
7098 let stack_size = addresses_end - addresses_start;
7099 // check the size (in debug only)
7100 // last observed macOS value: 22256 (CI)
7101 if !(15000..=25000).contains(&stack_size) {
7102 panic!("`put_block` stack size {stack_size} has changed!");
7103 }
7104 }
7105 }
7106
7107 impl crate::AtomicFunction {
7108 const fn to_msl(self) -> &'static str {
7109 match self {
7110 Self::Add => "fetch_add",
7111 Self::Subtract => "fetch_sub",
7112 Self::And => "fetch_and",
7113 Self::InclusiveOr => "fetch_or",
7114 Self::ExclusiveOr => "fetch_xor",
7115 Self::Min => "fetch_min",
7116 Self::Max => "fetch_max",
7117 Self::Exchange { compare: None } => "exchange",
7118 Self::Exchange { compare: Some(_) } => ATOMIC_COMP_EXCH_FUNCTION,
7119 }
7120 }
7121
7122 fn to_msl_64_bit(self) -> Result<&'static str, Error> {
7123 Ok(match self {
7124 Self::Min => "min",
7125 Self::Max => "max",
7126 _ => Err(Error::FeatureNotImplemented(
7127 "64-bit atomic operation other than min/max".to_string(),
7128 ))?,
7129 })
7130 }
7131 }