Skip to main content

naga/back/hlsl/
writer.rs

1use alloc::{
2    format,
3    string::{String, ToString},
4    vec::Vec,
5};
6use core::{
7    fmt::{self, Write as _},
8    mem,
9};
10
11use super::{
12    help,
13    help::{
14        WrappedArrayLength, WrappedConstructor, WrappedImageQuery, WrappedStructMatrixAccess,
15        WrappedZeroValue,
16    },
17    storage::StoreValue,
18    BackendResult, Error, FragmentEntryPoint, Options, PipelineOptions, ShaderModel,
19};
20use crate::{
21    back::{self, get_entry_points, Baked},
22    common,
23    proc::{self, index, ExternalTextureNameKey, NameKey},
24    valid, Handle, Module, RayQueryFunction, Scalar, ScalarKind, ShaderStage, TypeInner,
25};
26
27const LOCATION_SEMANTIC: &str = "LOC";
28const SPECIAL_CBUF_TYPE: &str = "NagaConstants";
29const SPECIAL_CBUF_VAR: &str = "_NagaConstants";
30const SPECIAL_FIRST_VERTEX: &str = "first_vertex";
31const SPECIAL_FIRST_INSTANCE: &str = "first_instance";
32const SPECIAL_OTHER: &str = "other";
33
34pub(crate) const MODF_FUNCTION: &str = "naga_modf";
35pub(crate) const FREXP_FUNCTION: &str = "naga_frexp";
36pub(crate) const EXTRACT_BITS_FUNCTION: &str = "naga_extractBits";
37pub(crate) const INSERT_BITS_FUNCTION: &str = "naga_insertBits";
38pub(crate) const SAMPLER_HEAP_VAR: &str = "nagaSamplerHeap";
39pub(crate) const COMPARISON_SAMPLER_HEAP_VAR: &str = "nagaComparisonSamplerHeap";
40pub(crate) const SAMPLE_EXTERNAL_TEXTURE_FUNCTION: &str = "nagaSampleExternalTexture";
41pub(crate) const ABS_FUNCTION: &str = "naga_abs";
42pub(crate) const DIV_FUNCTION: &str = "naga_div";
43pub(crate) const MOD_FUNCTION: &str = "naga_mod";
44pub(crate) const NEG_FUNCTION: &str = "naga_neg";
45pub(crate) const F2I32_FUNCTION: &str = "naga_f2i32";
46pub(crate) const F2U32_FUNCTION: &str = "naga_f2u32";
47pub(crate) const F2I64_FUNCTION: &str = "naga_f2i64";
48pub(crate) const F2U64_FUNCTION: &str = "naga_f2u64";
49pub(crate) const IMAGE_SAMPLE_BASE_CLAMP_TO_EDGE_FUNCTION: &str =
50    "nagaTextureSampleBaseClampToEdge";
51pub(crate) const IMAGE_LOAD_EXTERNAL_FUNCTION: &str = "nagaTextureLoadExternal";
52pub(crate) const RAY_QUERY_TRACKER_VARIABLE_PREFIX: &str = "naga_query_init_tracker_for_";
53/// Prefix for variables in a naga statement
54pub(crate) const INTERNAL_PREFIX: &str = "naga_";
55
56enum Index {
57    Expression(Handle<crate::Expression>),
58    Static(u32),
59}
60
61pub(super) struct EpStructMember {
62    pub(super) name: String,
63    pub(super) ty: Handle<crate::Type>,
64    // technically, this should always be `Some`
65    // (we `debug_assert!` this in `write_interface_struct`)
66    pub(super) binding: Option<crate::Binding>,
67    pub(super) index: u32,
68}
69
70/// Structure contains information required for generating
71/// wrapped structure of all entry points arguments
72pub(super) struct EntryPointBinding {
73    /// Name of the fake EP argument that contains the struct
74    /// with all the flattened input data.
75    pub(super) arg_name: String,
76    /// Generated structure name
77    pub(super) ty_name: String,
78    /// Members of generated structure
79    pub(super) members: Vec<EpStructMember>,
80    pub(super) local_invocation_index_name: Option<String>,
81}
82
83pub(super) struct EntryPointInterface {
84    /// If `Some`, the input of an entry point is gathered in a special
85    /// struct with members sorted by binding.
86    /// The `EntryPointBinding::members` array is sorted by index,
87    /// so that we can walk it in `write_ep_arguments_initialization`.
88    pub(crate) input: Option<EntryPointBinding>,
89    /// If `Some`, the output of an entry point is flattened.
90    /// The `EntryPointBinding::members` array is sorted by binding,
91    /// So that we can walk it in `Statement::Return` handler.
92    pub(crate) output: Option<EntryPointBinding>,
93    pub(crate) mesh_vertices: Option<EntryPointBinding>,
94    pub(crate) mesh_primitives: Option<EntryPointBinding>,
95    pub(crate) mesh_indices: Option<EntryPointBinding>,
96}
97
98#[derive(Clone, Eq, PartialEq, PartialOrd, Ord)]
99enum InterfaceKey {
100    Location(u32),
101    BuiltIn(crate::BuiltIn),
102    Other,
103}
104
105impl InterfaceKey {
106    const fn new(binding: Option<&crate::Binding>) -> Self {
107        match binding {
108            Some(&crate::Binding::Location { location, .. }) => Self::Location(location),
109            Some(&crate::Binding::BuiltIn(built_in)) => Self::BuiltIn(built_in),
110            None => Self::Other,
111        }
112    }
113}
114
115#[derive(Copy, Clone, PartialEq)]
116pub(super) enum Io {
117    Input,
118    Output,
119    MeshVertices,
120    MeshPrimitives,
121}
122
123/// Argument list for nested entry points
124pub(super) struct NestedEntryPointArgs {
125    /// Arguments literally declared by the user
126    pub user_args: Vec<String>,
127    pub task_payload: Option<String>,
128    pub local_invocation_index: String,
129}
130
131const fn is_subgroup_builtin_binding(binding: &Option<crate::Binding>) -> bool {
132    let &Some(crate::Binding::BuiltIn(builtin)) = binding else {
133        return false;
134    };
135    matches!(
136        builtin,
137        crate::BuiltIn::SubgroupSize
138            | crate::BuiltIn::SubgroupInvocationId
139            | crate::BuiltIn::NumSubgroups
140            | crate::BuiltIn::SubgroupId
141    )
142}
143
144/// The invocations that share the zero initialization of workgroup variables.
145#[derive(Clone, Copy)]
146struct WorkgroupInitInvocations<'a> {
147    /// Name of the local invocation index.
148    local_index: &'a str,
149    /// Number of invocations in the workgroup.
150    workgroup_size: u32,
151}
152
153/// Information for how to generate a `binding_array<sampler>` access.
154struct BindingArraySamplerInfo {
155    /// Variable name of the sampler heap
156    sampler_heap_name: &'static str,
157    /// Variable name of the sampler index buffer
158    sampler_index_buffer_name: String,
159    /// Variable name of the base index _into_ the sampler index buffer
160    binding_array_base_index_name: String,
161}
162
163impl<'a, W: fmt::Write> super::Writer<'a, W> {
164    pub fn new(out: W, options: &'a Options, pipeline_options: &'a PipelineOptions) -> Self {
165        Self {
166            out,
167            names: crate::FastHashMap::default(),
168            namer: proc::Namer::default(),
169            options,
170            pipeline_options,
171            entry_point_io: crate::FastHashMap::default(),
172            early_depth_test: None,
173            named_expressions: crate::NamedExpressions::default(),
174            wrapped: super::Wrapped::default(),
175            written_committed_intersection: false,
176            written_candidate_intersection: false,
177            continue_ctx: back::continue_forward::ContinueCtx::default(),
178            temp_access_chain: Vec::new(),
179            need_bake_expressions: Default::default(),
180            function_task_payload_var: Default::default(),
181            immediate_raw_names: crate::FastHashMap::default(),
182        }
183    }
184
185    fn reset(&mut self, module: &Module) {
186        self.names.clear();
187        self.namer.reset(
188            module,
189            &super::keywords::RESERVED_SET,
190            proc::KeywordSet::empty(),
191            &super::keywords::RESERVED_CASE_INSENSITIVE_SET,
192            super::keywords::RESERVED_PREFIXES,
193            &mut self.names,
194        );
195        self.entry_point_io.clear();
196        self.named_expressions.clear();
197        self.wrapped.clear();
198        self.written_committed_intersection = false;
199        self.written_candidate_intersection = false;
200        self.continue_ctx.clear();
201        self.need_bake_expressions.clear();
202        self.function_task_payload_var.clear();
203        self.immediate_raw_names.clear();
204    }
205
206    /// Generates statements to be inserted immediately before and at the very
207    /// start of the body of each loop, to defeat infinite loop reasoning.
208    /// The 0th item of the returned tuple should be inserted immediately prior
209    /// to the loop and the 1st item should be inserted at the very start of
210    /// the loop body.
211    ///
212    /// See [`back::msl::Writer::gen_force_bounded_loop_statements`] for details.
213    fn gen_force_bounded_loop_statements(
214        &mut self,
215        level: back::Level,
216    ) -> Option<(String, String)> {
217        if !self.options.force_loop_bounding {
218            return None;
219        }
220
221        let loop_bound_name = self.namer.call("loop_bound");
222        let max = u32::MAX;
223        // Count down from u32::MAX rather than up from 0 to avoid hang on
224        // certain Intel drivers. See <https://github.com/gfx-rs/wgpu/issues/7319>.
225        let decl = format!("{level}uint2 {loop_bound_name} = uint2({max}u, {max}u);");
226        let level = level.next();
227        let break_and_inc = format!(
228            "{level}if (all({loop_bound_name} == uint2(0u, 0u))) {{ break; }}
229{level}{loop_bound_name} -= uint2({loop_bound_name}.y == 0u, 1u);"
230        );
231
232        Some((decl, break_and_inc))
233    }
234
235    /// Helper method used to find which expressions of a given function require baking
236    ///
237    /// # Notes
238    /// Clears `need_bake_expressions` set before adding to it
239    fn update_expressions_to_bake(
240        &mut self,
241        module: &Module,
242        func: &crate::Function,
243        info: &valid::FunctionInfo,
244    ) {
245        use crate::Expression;
246        self.need_bake_expressions.clear();
247        for (exp_handle, expr) in func.expressions.iter() {
248            let expr_info = &info[exp_handle];
249            let min_ref_count = func.expressions[exp_handle].bake_ref_count();
250            if min_ref_count <= expr_info.ref_count {
251                self.need_bake_expressions.insert(exp_handle);
252            }
253            if let Expression::Load { pointer } = *expr {
254                if info[pointer]
255                    .ty
256                    .inner_with(&module.types)
257                    .is_atomic_pointer(&module.types)
258                {
259                    self.need_bake_expressions.insert(exp_handle);
260                }
261            }
262
263            if let Expression::Math { fun, arg, arg1, .. } = *expr {
264                match fun {
265                    crate::MathFunction::Asinh
266                    | crate::MathFunction::Acosh
267                    | crate::MathFunction::Atanh
268                    | crate::MathFunction::Unpack2x16float
269                    | crate::MathFunction::Unpack2x16snorm
270                    | crate::MathFunction::Unpack2x16unorm
271                    | crate::MathFunction::Unpack4x8snorm
272                    | crate::MathFunction::Unpack4x8unorm
273                    | crate::MathFunction::Unpack4xI8
274                    | crate::MathFunction::Unpack4xU8
275                    | crate::MathFunction::Pack2x16float
276                    | crate::MathFunction::Pack2x16snorm
277                    | crate::MathFunction::Pack2x16unorm
278                    | crate::MathFunction::Pack4x8snorm
279                    | crate::MathFunction::Pack4x8unorm
280                    | crate::MathFunction::Pack4xI8
281                    | crate::MathFunction::Pack4xU8
282                    | crate::MathFunction::Pack4xI8Clamp
283                    | crate::MathFunction::Pack4xU8Clamp => {
284                        self.need_bake_expressions.insert(arg);
285                    }
286                    crate::MathFunction::CountLeadingZeros => {
287                        let inner = info[exp_handle].ty.inner_with(&module.types);
288                        if let Some(ScalarKind::Sint) = inner.scalar_kind() {
289                            self.need_bake_expressions.insert(arg);
290                        }
291                    }
292                    crate::MathFunction::Dot4U8Packed | crate::MathFunction::Dot4I8Packed => {
293                        self.need_bake_expressions.insert(arg);
294                        self.need_bake_expressions.insert(arg1.unwrap());
295                    }
296                    _ => {}
297                }
298            }
299
300            if let Expression::Derivative { axis, ctrl, expr } = *expr {
301                use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl};
302                if axis == Axis::Width && (ctrl == Ctrl::Coarse || ctrl == Ctrl::Fine) {
303                    self.need_bake_expressions.insert(expr);
304                }
305            }
306
307            if let Expression::GlobalVariable(_) = *expr {
308                let inner = info[exp_handle].ty.inner_with(&module.types);
309
310                if let TypeInner::Sampler { .. } = *inner {
311                    self.need_bake_expressions.insert(exp_handle);
312                }
313            }
314        }
315        for statement in func.body.iter() {
316            match *statement {
317                crate::Statement::SubgroupCollectiveOperation {
318                    op: _,
319                    collective_op: crate::CollectiveOperation::InclusiveScan,
320                    argument,
321                    result: _,
322                } => {
323                    self.need_bake_expressions.insert(argument);
324                }
325                crate::Statement::Atomic {
326                    fun: crate::AtomicFunction::Exchange { compare: Some(cmp) },
327                    ..
328                } => {
329                    self.need_bake_expressions.insert(cmp);
330                }
331                _ => {}
332            }
333        }
334    }
335
336    pub fn write(
337        &mut self,
338        module: &Module,
339        module_info: &valid::ModuleInfo,
340        fragment_entry_point: Option<&FragmentEntryPoint<'_>>,
341    ) -> Result<super::ReflectionInfo, Error> {
342        self.reset(module);
343
344        if module.uses_mesh_shaders() && self.options.shader_model < ShaderModel::V6_5 {
345            return Err(Error::ShaderModelTooLow(
346                "mesh shaders".to_string(),
347                ShaderModel::V6_5,
348            ));
349        }
350
351        // Write special constants, if needed
352        if let Some(ref bt) = self.options.special_constants_binding {
353            writeln!(self.out, "struct {SPECIAL_CBUF_TYPE} {{")?;
354            writeln!(self.out, "{}int {};", back::INDENT, SPECIAL_FIRST_VERTEX)?;
355            writeln!(self.out, "{}int {};", back::INDENT, SPECIAL_FIRST_INSTANCE)?;
356            writeln!(self.out, "{}uint {};", back::INDENT, SPECIAL_OTHER)?;
357            writeln!(self.out, "}};")?;
358            write!(
359                self.out,
360                "ConstantBuffer<{}> {}: register(b{}",
361                SPECIAL_CBUF_TYPE, SPECIAL_CBUF_VAR, bt.register
362            )?;
363            if bt.space != 0 {
364                write!(self.out, ", space{}", bt.space)?;
365            }
366            writeln!(self.out, ");")?;
367
368            // Extra newline for readability
369            writeln!(self.out)?;
370        }
371
372        for (group, bt) in self.options.dynamic_storage_buffer_offsets_targets.iter() {
373            writeln!(self.out, "struct __dynamic_buffer_offsetsTy{group} {{")?;
374            for i in 0..bt.size {
375                writeln!(self.out, "{}uint _{};", back::INDENT, i)?;
376            }
377            writeln!(self.out, "}};")?;
378            writeln!(
379                self.out,
380                "ConstantBuffer<__dynamic_buffer_offsetsTy{}> __dynamic_buffer_offsets{}: register(b{}, space{});",
381                group, group, bt.register, bt.space
382            )?;
383
384            // Extra newline for readability
385            writeln!(self.out)?;
386        }
387
388        let ep_range = get_entry_points(module, self.pipeline_options.entry_point.as_ref())
389            .map_err(|(stage, name)| Error::EntryPointNotFound(stage, name))?;
390
391        // Save all entry point output types
392        let ep_results = module
393            .entry_points
394            .iter()
395            .map(|ep| (ep.stage, ep.function.result.clone()))
396            .collect::<Vec<(ShaderStage, Option<crate::FunctionResult>)>>();
397
398        self.write_all_mat_cx2_typedefs_and_functions(module)?;
399
400        // Write all structs
401        for (handle, ty) in module.types.iter() {
402            if let TypeInner::Struct { ref members, span } = ty.inner {
403                if module.types[members.last().unwrap().ty]
404                    .inner
405                    .is_dynamically_sized(&module.types)
406                {
407                    // unsized arrays can only be in storage buffers,
408                    // for which we use `ByteAddressBuffer` anyway.
409                    continue;
410                }
411
412                let ep_result = ep_results.iter().find(|e| {
413                    if let Some(ref result) = e.1 {
414                        result.ty == handle
415                    } else {
416                        false
417                    }
418                });
419
420                let early_depth_test = shared_early_depth_test(module, ep_range.clone(), handle);
421                self.with_early_depth_test(early_depth_test, |this| {
422                    this.write_struct(
423                        module,
424                        handle,
425                        members,
426                        span,
427                        ep_result.map(|r| (r.0, Io::Output)),
428                    )
429                })?;
430                writeln!(self.out)?;
431            }
432        }
433
434        self.write_special_functions(module)?;
435
436        self.write_wrapped_expression_functions(module, &module.global_expressions, None)?;
437        self.write_wrapped_zero_value_functions(module, &module.global_expressions)?;
438
439        // Write all named constants
440        let mut constants = module
441            .constants
442            .iter()
443            .filter(|&(_, c)| c.name.is_some())
444            .peekable();
445        while let Some((handle, _)) = constants.next() {
446            self.write_global_constant(module, handle)?;
447            // Add extra newline for readability on last iteration
448            if constants.peek().is_none() {
449                writeln!(self.out)?;
450            }
451        }
452
453        // Write all globals
454        for (global, _) in module.global_variables.iter() {
455            self.write_global(module, global)?;
456        }
457
458        // Write the functions that assemble the values of immediates
459        self.write_immediate_constructors(module)?;
460
461        if !module.global_variables.is_empty() {
462            // Add extra newline for readability
463            writeln!(self.out)?;
464        }
465
466        // Write all entry points wrapped structs
467        for index in ep_range.clone() {
468            let ep = &module.entry_points[index];
469            let ep_name = self.names[&NameKey::EntryPoint(index as u16)].clone();
470            let ep_io = self.write_ep_interface(module, ep, &ep_name, fragment_entry_point)?;
471            self.entry_point_io.insert(index, ep_io);
472        }
473
474        // Write all regular functions
475        for (handle, function) in module.functions.iter() {
476            let info = &module_info[handle];
477
478            // Check if all of the globals are accessible
479            if !self.options.fake_missing_bindings {
480                if let Some((var_handle, _)) =
481                    module
482                        .global_variables
483                        .iter()
484                        .find(|&(var_handle, var)| match var.binding {
485                            Some(ref binding) if !info[var_handle].is_empty() => {
486                                self.options.resolve_resource_binding(binding).is_err()
487                                    && self
488                                        .options
489                                        .resolve_external_texture_resource_binding(binding)
490                                        .is_err()
491                            }
492                            _ => false,
493                        })
494                {
495                    log::debug!(
496                        "Skipping function {:?} (name {:?}) because global {:?} is inaccessible",
497                        handle,
498                        function.name,
499                        var_handle
500                    );
501                    continue;
502                }
503            }
504
505            let ctx = back::FunctionCtx {
506                ty: back::FunctionType::Function(handle),
507                info,
508                expressions: &function.expressions,
509                named_expressions: &function.named_expressions,
510            };
511            let name = self.names[&NameKey::Function(handle)].clone();
512
513            self.write_wrapped_functions(module, &ctx)?;
514
515            self.write_function(module, name.as_str(), function, &ctx, info, String::new())?;
516
517            writeln!(self.out)?;
518        }
519
520        let mut translated_ep_names = Vec::with_capacity(ep_range.len());
521
522        // Write all entry points
523        for index in ep_range {
524            let ep = &module.entry_points[index];
525            let info = module_info.get_entry_point(index);
526
527            if !self.options.fake_missing_bindings {
528                let mut ep_error = None;
529                for (var_handle, var) in module.global_variables.iter() {
530                    match var.binding {
531                        Some(ref binding) if !info[var_handle].is_empty() => {
532                            if let Err(err) = self.options.resolve_resource_binding(binding) {
533                                if self
534                                    .options
535                                    .resolve_external_texture_resource_binding(binding)
536                                    .is_err()
537                                {
538                                    ep_error = Some(err);
539                                    break;
540                                }
541                            }
542                        }
543                        _ => {}
544                    }
545                }
546                if let Some(err) = ep_error {
547                    translated_ep_names.push(Err(err));
548                    continue;
549                }
550            }
551
552            let ctx = back::FunctionCtx {
553                ty: back::FunctionType::EntryPoint(index as u16),
554                info,
555                expressions: &ep.function.expressions,
556                named_expressions: &ep.function.named_expressions,
557            };
558
559            self.write_wrapped_functions(module, &ctx)?;
560
561            // Mesh/task shaders have a wrapper entry point which is declared after the "main"
562            // user-written function. We therefore cannot always just document the next function.
563            let mut attribute_string = String::new();
564            if ep.stage.compute_like() {
565                // HLSL is calling workgroup size "num threads"
566                let num_threads = ep.workgroup_size;
567                writeln!(
568                    attribute_string,
569                    "[numthreads({}, {}, {})]",
570                    num_threads[0], num_threads[1], num_threads[2]
571                )?;
572            }
573            if ep.stage == ShaderStage::Fragment
574                && ep.early_depth_test == Some(crate::EarlyDepthTest::Force)
575            {
576                writeln!(attribute_string, "[earlydepthstencil]")?;
577            }
578            if let Some(ref info) = ep.mesh_info {
579                let topology_str = match info.topology {
580                    crate::MeshOutputTopology::Points => unreachable!(),
581                    crate::MeshOutputTopology::Lines => "line",
582                    crate::MeshOutputTopology::Triangles => "triangle",
583                };
584                writeln!(attribute_string, "[outputtopology(\"{topology_str}\")]")?;
585            }
586
587            let name = self.names[&NameKey::EntryPoint(index as u16)].clone();
588            self.write_function(module, &name, &ep.function, &ctx, info, attribute_string)?;
589
590            if index < module.entry_points.len() - 1 {
591                writeln!(self.out)?;
592            }
593
594            translated_ep_names.push(Ok(name));
595        }
596
597        Ok(super::ReflectionInfo {
598            entry_point_names: translated_ep_names,
599        })
600    }
601
602    fn write_modifier(&mut self, binding: &crate::Binding) -> BackendResult {
603        match *binding {
604            crate::Binding::BuiltIn(crate::BuiltIn::Position { invariant }) => {
605                if invariant {
606                    write!(self.out, "precise ")?;
607                }
608                if self.conservative_depth().is_some() {
609                    // This is only valid for shaders that are not multisampled, which
610                    // `conservative_depth` ensures.
611                    write!(self.out, "noperspective centroid ")?;
612                }
613            }
614            crate::Binding::BuiltIn(crate::BuiltIn::Barycentric { perspective: false }) => {
615                write!(self.out, "noperspective ")?;
616            }
617            crate::Binding::Location {
618                interpolation,
619                sampling,
620                ..
621            } => {
622                if let Some(interpolation) = interpolation {
623                    if let Some(string) = interpolation.to_hlsl_str() {
624                        write!(self.out, "{string} ")?
625                    }
626                }
627
628                if let Some(sampling) = sampling {
629                    if let Some(string) = sampling.to_hlsl_str() {
630                        write!(self.out, "{string} ")?
631                    }
632                }
633            }
634            crate::Binding::BuiltIn(_) => {}
635        }
636
637        Ok(())
638    }
639
640    /// Gets the conservative depth that the fragment shader being written promises, if it is used.
641    ///
642    /// Fragment shaders expect the position input to be at the center of the pixel. DXC only
643    /// accepts `SV_DepthGreaterEqual` and `SV_DepthLessEqual` when the `SV_Position` input is
644    /// declared `noperspective centroid`. That is the pixel center when there is one sample per
645    /// pixel, but under MSAA it can differ, which would change the position that the shader sees.
646    /// Conservative depth is therefore only used for pipelines that are not multisampled.
647    /// Multisampled pipelines use an unrestricted depth output and leave the position input alone.
648    const fn conservative_depth(&self) -> Option<crate::ConservativeDepth> {
649        match self.early_depth_test {
650            Some(crate::EarlyDepthTest::Allow {
651                conservative:
652                    conservative @ (crate::ConservativeDepth::GreaterEqual
653                    | crate::ConservativeDepth::LessEqual),
654            }) if !self.pipeline_options.multisampled => Some(conservative),
655            _ => None,
656        }
657    }
658
659    /// Runs `write` with [`Self::early_depth_test`] set to `early_depth_test`.
660    fn with_early_depth_test<T>(
661        &mut self,
662        early_depth_test: Option<crate::EarlyDepthTest>,
663        write: impl FnOnce(&mut Self) -> T,
664    ) -> T {
665        self.early_depth_test = early_depth_test;
666        let result = write(self);
667        self.early_depth_test = None;
668        result
669    }
670
671    //TODO: we could force fragment outputs to always go through `entry_point_io.output` path
672    // if they are struct, so that the `stage` argument here could be omitted.
673    pub(super) fn write_semantic(
674        &mut self,
675        binding: &Option<crate::Binding>,
676        stage: Option<(ShaderStage, Io)>,
677    ) -> BackendResult {
678        let is_per_primitive = match *binding {
679            Some(crate::Binding::BuiltIn(builtin)) if !is_subgroup_builtin_binding(binding) => {
680                if builtin == crate::BuiltIn::ViewIndex
681                    && self.options.shader_model < ShaderModel::V6_1
682                {
683                    return Err(Error::ShaderModelTooLow(
684                        "used @builtin(view_index) or SV_ViewID".to_string(),
685                        ShaderModel::V6_1,
686                    ));
687                }
688                if let Some(builtin_str) = builtin.to_hlsl_str()? {
689                    let builtin_str = match (builtin, self.conservative_depth()) {
690                        (
691                            crate::BuiltIn::FragDepth,
692                            Some(crate::ConservativeDepth::GreaterEqual),
693                        ) => "SV_DepthGreaterEqual",
694                        (crate::BuiltIn::FragDepth, Some(crate::ConservativeDepth::LessEqual)) => {
695                            "SV_DepthLessEqual"
696                        }
697                        _ => builtin_str,
698                    };
699                    write!(self.out, " : {builtin_str}")?;
700                }
701                false
702            }
703            Some(crate::Binding::Location {
704                blend_src: Some(1),
705                per_primitive,
706                ..
707            }) => {
708                write!(self.out, " : SV_Target1")?;
709                per_primitive
710            }
711            Some(crate::Binding::Location {
712                location,
713                per_primitive,
714                ..
715            }) => {
716                if stage == Some((ShaderStage::Fragment, Io::Output)) {
717                    write!(self.out, " : SV_Target{location}")?;
718                } else {
719                    write!(self.out, " : {LOCATION_SEMANTIC}{location}")?;
720                }
721                per_primitive
722            }
723            _ => false,
724        };
725        if is_per_primitive {
726            write!(self.out, " : primitive")?;
727        }
728
729        Ok(())
730    }
731
732    pub(super) fn write_interface_struct(
733        &mut self,
734        module: &Module,
735        shader_stage: (ShaderStage, Io),
736        struct_name: String,
737        var_name: Option<&str>,
738        mut members: Vec<EpStructMember>,
739    ) -> Result<EntryPointBinding, Error> {
740        let struct_name = self.namer.call(&struct_name);
741        // Sort the members so that first come the user-defined varyings
742        // in ascending locations, and then built-ins. This allows VS and FS
743        // interfaces to match with regards to order.
744        members.sort_by_key(|m| InterfaceKey::new(m.binding.as_ref()));
745
746        write!(self.out, "struct {struct_name}")?;
747        writeln!(self.out, " {{")?;
748        let mut local_invocation_index_name = None;
749        let mut subgroup_id_used = false;
750        for m in members.iter() {
751            // Sanity check that each IO member is a built-in or is assigned a
752            // location. Also see note about nesting in `write_ep_input_struct`.
753            debug_assert!(m.binding.is_some());
754
755            match m.binding {
756                Some(crate::Binding::BuiltIn(crate::BuiltIn::SubgroupId)) => {
757                    subgroup_id_used = true;
758                }
759                Some(crate::Binding::BuiltIn(crate::BuiltIn::LocalInvocationIndex)) => {
760                    local_invocation_index_name = Some(m.name.clone());
761                }
762                _ => (),
763            }
764
765            if is_subgroup_builtin_binding(&m.binding) {
766                continue;
767            }
768            write!(self.out, "{}", back::INDENT)?;
769            if let Some(ref binding) = m.binding {
770                self.write_modifier(binding)?;
771            }
772            self.write_type(module, m.ty)?;
773            write!(self.out, " {}", m.name)?;
774            self.write_semantic(&m.binding, Some(shader_stage))?;
775            writeln!(self.out, ";")?;
776        }
777        if subgroup_id_used && local_invocation_index_name.is_none() {
778            let name = self.namer.call("local_invocation_index");
779            writeln!(self.out, "{}uint {name} : SV_GroupIndex;", back::INDENT)?;
780            local_invocation_index_name = Some(name);
781        }
782        writeln!(self.out, "}};")?;
783        writeln!(self.out)?;
784
785        // See ordering notes on EntryPointInterface fields
786        match shader_stage.1 {
787            Io::Input => {
788                // bring back the original order
789                members.sort_by_key(|m| m.index);
790            }
791            Io::Output | Io::MeshVertices | Io::MeshPrimitives => {
792                // keep it sorted by binding
793            }
794        }
795
796        Ok(EntryPointBinding {
797            arg_name: self
798                .namer
799                .call(var_name.unwrap_or(struct_name.to_lowercase().as_str())),
800            ty_name: struct_name,
801            members,
802            local_invocation_index_name,
803        })
804    }
805
806    /// Flatten all entry point arguments into a single struct.
807    /// This is needed since we need to re-order them: first placing user locations,
808    /// then built-ins.
809    fn write_ep_input_struct(
810        &mut self,
811        module: &Module,
812        func: &crate::Function,
813        stage: ShaderStage,
814        entry_point_name: &str,
815    ) -> Result<EntryPointBinding, Error> {
816        let struct_name = format!("{stage:?}Input_{entry_point_name}");
817
818        let mut fake_members = Vec::new();
819        for arg in func.arguments.iter() {
820            // NOTE: We don't need to handle nesting structs. All members must
821            // be either built-ins or assigned a location. I.E. `binding` is
822            // `Some`. This is checked in `VaryingContext::validate`. See:
823            // https://gpuweb.github.io/gpuweb/wgsl/#input-output-locations
824            match module.types[arg.ty].inner {
825                TypeInner::Struct { ref members, .. } => {
826                    for member in members.iter() {
827                        let name = self.namer.call_or(&member.name, "member");
828                        let index = fake_members.len() as u32;
829                        fake_members.push(EpStructMember {
830                            name,
831                            ty: member.ty,
832                            binding: member.binding.clone(),
833                            index,
834                        });
835                    }
836                }
837                _ => {
838                    let member_name = self.namer.call_or(&arg.name, "member");
839                    let index = fake_members.len() as u32;
840                    fake_members.push(EpStructMember {
841                        name: member_name,
842                        ty: arg.ty,
843                        binding: arg.binding.clone(),
844                        index,
845                    });
846                }
847            }
848        }
849
850        self.write_interface_struct(module, (stage, Io::Input), struct_name, None, fake_members)
851    }
852
853    /// Flatten all entry point results into a single struct.
854    /// This is needed since we need to re-order them: first placing user locations,
855    /// then built-ins.
856    fn write_ep_output_struct(
857        &mut self,
858        module: &Module,
859        entry_point: &crate::EntryPoint,
860        result: &crate::FunctionResult,
861        entry_point_name: &str,
862        frag_ep: Option<&FragmentEntryPoint<'_>>,
863    ) -> Result<EntryPointBinding, Error> {
864        let stage = entry_point.stage;
865        let struct_name = format!("{stage:?}Output_{entry_point_name}");
866
867        let empty = [];
868        let members = match module.types[result.ty].inner {
869            TypeInner::Struct { ref members, .. } => members,
870            ref other => {
871                log::error!("Unexpected {other:?} output type without a binding");
872                &empty[..]
873            }
874        };
875
876        // Gather list of fragment input locations. We use this below to remove user-defined
877        // varyings from VS outputs that aren't in the FS inputs. This makes the VS interface match
878        // as long as the FS inputs are a subset of the VS outputs. This is only applied if the
879        // writer is supplied with information about the fragment entry point.
880        let fs_input_locs = if let (Some(frag_ep), ShaderStage::Vertex) = (frag_ep, stage) {
881            let mut fs_input_locs = Vec::new();
882            for arg in frag_ep.func.arguments.iter() {
883                let mut push_if_location = |binding: &Option<crate::Binding>| match *binding {
884                    Some(crate::Binding::Location { location, .. }) => fs_input_locs.push(location),
885                    Some(crate::Binding::BuiltIn(_)) | None => {}
886                };
887
888                // NOTE: We don't need to handle struct nesting. See note in
889                // `write_ep_input_struct`.
890                match frag_ep.module.types[arg.ty].inner {
891                    TypeInner::Struct { ref members, .. } => {
892                        for member in members.iter() {
893                            push_if_location(&member.binding);
894                        }
895                    }
896                    _ => push_if_location(&arg.binding),
897                }
898            }
899            fs_input_locs.sort();
900            Some(fs_input_locs)
901        } else {
902            None
903        };
904
905        let mut fake_members = Vec::new();
906        for (index, member) in members.iter().enumerate() {
907            if let Some(ref fs_input_locs) = fs_input_locs {
908                match member.binding {
909                    Some(crate::Binding::Location { location, .. }) => {
910                        if fs_input_locs.binary_search(&location).is_err() {
911                            continue;
912                        }
913                    }
914                    Some(crate::Binding::BuiltIn(_)) | None => {}
915                }
916            }
917
918            if discards_frag_depth(entry_point) && is_frag_depth(member.binding.as_ref()) {
919                continue;
920            }
921
922            let member_name = self.namer.call_or(&member.name, "member");
923            fake_members.push(EpStructMember {
924                name: member_name,
925                ty: member.ty,
926                binding: member.binding.clone(),
927                index: index as u32,
928            });
929        }
930
931        self.write_interface_struct(module, (stage, Io::Output), struct_name, None, fake_members)
932    }
933
934    /// Writes special interface structures for an entry point. The special structures have
935    /// all the fields flattened into them and sorted by binding. They are needed to emulate
936    /// subgroup built-ins and to make the interfaces between VS outputs and FS inputs match.
937    fn write_ep_interface(
938        &mut self,
939        module: &Module,
940        ep: &crate::EntryPoint,
941        ep_name: &str,
942        frag_ep: Option<&FragmentEntryPoint<'_>>,
943    ) -> Result<EntryPointInterface, Error> {
944        let func = &ep.function;
945        let stage = ep.stage;
946        Ok(EntryPointInterface {
947            input: if !func.arguments.is_empty()
948                && (stage == ShaderStage::Fragment
949                    || func
950                        .arguments
951                        .iter()
952                        .any(|arg| is_subgroup_builtin_binding(&arg.binding)))
953            {
954                Some(self.with_early_depth_test(ep.early_depth_test, |this| {
955                    this.write_ep_input_struct(module, func, stage, ep_name)
956                })?)
957            } else {
958                None
959            },
960            output: match func.result {
961                Some(ref fr)
962                    if fr.binding.is_none()
963                        && (stage == ShaderStage::Vertex
964                            || (discards_frag_depth(ep)
965                                && !only_writes_discarded_depth(module, ep))) =>
966                {
967                    Some(self.write_ep_output_struct(module, ep, fr, ep_name, frag_ep)?)
968                }
969                _ => None,
970            },
971            mesh_vertices: if let Some(ref info) = ep.mesh_info {
972                Some(self.write_ep_mesh_output_struct(module, ep_name, false, info)?)
973            } else {
974                None
975            },
976            mesh_primitives: if let Some(ref info) = ep.mesh_info {
977                Some(self.write_ep_mesh_output_struct(module, ep_name, true, info)?)
978            } else {
979                None
980            },
981            mesh_indices: if let Some(ref info) = ep.mesh_info {
982                Some(self.write_ep_mesh_output_indices(info.topology)?)
983            } else {
984                None
985            },
986        })
987    }
988
989    fn write_ep_argument_initialization(
990        &mut self,
991        ep: &crate::EntryPoint,
992        ep_input: &EntryPointBinding,
993        fake_member: &EpStructMember,
994    ) -> BackendResult {
995        match fake_member.binding {
996            Some(crate::Binding::BuiltIn(crate::BuiltIn::SubgroupSize)) => {
997                write!(self.out, "WaveGetLaneCount()")?
998            }
999            Some(crate::Binding::BuiltIn(crate::BuiltIn::SubgroupInvocationId)) => {
1000                write!(self.out, "WaveGetLaneIndex()")?
1001            }
1002            Some(crate::Binding::BuiltIn(crate::BuiltIn::NumSubgroups)) => write!(
1003                self.out,
1004                "({}u + WaveGetLaneCount() - 1u) / WaveGetLaneCount()",
1005                ep.workgroup_size[0] * ep.workgroup_size[1] * ep.workgroup_size[2]
1006            )?,
1007            Some(crate::Binding::BuiltIn(crate::BuiltIn::SubgroupId)) => {
1008                write!(
1009                    self.out,
1010                    "{}.{} / WaveGetLaneCount()",
1011                    ep_input.arg_name,
1012                    // When writing SubgroupId, we always guarantee that local_invocation_index_name is written
1013                    ep_input.local_invocation_index_name.as_ref().unwrap()
1014                )?;
1015            }
1016            // WGSL's fragment `position.w` is 1/w of the clip position, D3D's `SV_Position.w` is w.
1017            Some(crate::Binding::BuiltIn(crate::BuiltIn::Position { .. }))
1018                if ep.stage == ShaderStage::Fragment =>
1019            {
1020                write!(
1021                    self.out,
1022                    "float4({0}.{1}.xyz, 1.0 / {0}.{1}.w)",
1023                    ep_input.arg_name, fake_member.name,
1024                )?;
1025            }
1026            Some(crate::Binding::Location {
1027                interpolation: Some(crate::Interpolation::PerVertex),
1028                ..
1029            }) => {
1030                if self.options.shader_model < ShaderModel::V6_1 {
1031                    return Err(Error::ShaderModelTooLow(
1032                        "per_vertex fragment inputs".to_string(),
1033                        ShaderModel::V6_1,
1034                    ));
1035                }
1036                write!(
1037                    self.out,
1038                    "{{ GetAttributeAtVertex({0}.{1}, 0), GetAttributeAtVertex({0}.{1}, 1), GetAttributeAtVertex({0}.{1}, 2) }}",
1039                    ep_input.arg_name,
1040                    fake_member.name,
1041                )?;
1042            }
1043            _ => {
1044                write!(self.out, "{}.{}", ep_input.arg_name, fake_member.name)?;
1045            }
1046        }
1047        Ok(())
1048    }
1049
1050    /// Write an entry point preface that initializes the arguments as specified in IR.
1051    fn write_ep_arguments_initialization(
1052        &mut self,
1053        module: &Module,
1054        func: &crate::Function,
1055        ep_index: u16,
1056    ) -> BackendResult {
1057        let ep = &module.entry_points[ep_index as usize];
1058        let ep_input = match self
1059            .entry_point_io
1060            .get_mut(&(ep_index as usize))
1061            .unwrap()
1062            .input
1063            .take()
1064        {
1065            Some(ep_input) => ep_input,
1066            None => return Ok(()),
1067        };
1068        let mut fake_iter = ep_input.members.iter();
1069        for (arg_index, arg) in func.arguments.iter().enumerate() {
1070            write!(self.out, "{}", back::INDENT)?;
1071            self.write_type(module, arg.ty)?;
1072            let arg_name = &self.names[&NameKey::EntryPointArgument(ep_index, arg_index as u32)];
1073            write!(self.out, " {arg_name}")?;
1074            match module.types[arg.ty].inner {
1075                TypeInner::Array { base, size, .. } => {
1076                    self.write_array_size(module, base, size)?;
1077                    write!(self.out, " = ")?;
1078                    self.write_ep_argument_initialization(
1079                        ep,
1080                        &ep_input,
1081                        fake_iter.next().unwrap(),
1082                    )?;
1083                    writeln!(self.out, ";")?;
1084                }
1085                TypeInner::Struct { ref members, .. } => {
1086                    write!(self.out, " = {{ ")?;
1087                    for index in 0..members.len() {
1088                        if index != 0 {
1089                            write!(self.out, ", ")?;
1090                        }
1091                        self.write_ep_argument_initialization(
1092                            ep,
1093                            &ep_input,
1094                            fake_iter.next().unwrap(),
1095                        )?;
1096                    }
1097                    writeln!(self.out, " }};")?;
1098                }
1099                _ => {
1100                    write!(self.out, " = ")?;
1101                    self.write_ep_argument_initialization(
1102                        ep,
1103                        &ep_input,
1104                        fake_iter.next().unwrap(),
1105                    )?;
1106                    writeln!(self.out, ";")?;
1107                }
1108            }
1109        }
1110        assert!(fake_iter.next().is_none());
1111        Ok(())
1112    }
1113
1114    /// Helper method used to write global variables
1115    /// # Notes
1116    /// Always adds a newline
1117    fn write_global(
1118        &mut self,
1119        module: &Module,
1120        handle: Handle<crate::GlobalVariable>,
1121    ) -> BackendResult {
1122        let global = &module.global_variables[handle];
1123        let inner = &module.types[global.ty].inner;
1124
1125        let handle_ty = match *inner {
1126            TypeInner::BindingArray { ref base, .. } => &module.types[*base].inner,
1127            _ => inner,
1128        };
1129
1130        // External textures are handled entirely differently, so defer entirely to that method.
1131        // We do so prior to calling resolve_resource_binding() below, as we even need to resolve
1132        // their bindings separately.
1133        if handle_ty.is_external_image() {
1134            return self.write_global_external_texture(module, handle, global);
1135        }
1136
1137        if let Some(ref binding) = global.binding {
1138            if let Err(err) = self.options.resolve_resource_binding(binding) {
1139                log::debug!(
1140                    "Skipping global {:?} (name {:?}) for being inaccessible: {}",
1141                    handle,
1142                    global.name,
1143                    err,
1144                );
1145                return Ok(());
1146            }
1147        }
1148
1149        // Samplers are handled entirely differently, so defer entirely to that method.
1150        let is_sampler = matches!(*handle_ty, TypeInner::Sampler { .. });
1151
1152        if is_sampler {
1153            return self.write_global_sampler(module, handle, global);
1154        }
1155
1156        // Immediates are handled entirely differently, so defer entirely to that method.
1157        if global.space == crate::AddressSpace::Immediate {
1158            return self.write_global_immediate(module, handle, global);
1159        }
1160
1161        // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-register
1162        let register_ty = match global.space {
1163            crate::AddressSpace::Function => unreachable!("Function address space"),
1164            crate::AddressSpace::Private => {
1165                write!(self.out, "static ")?;
1166                self.write_type(module, global.ty)?;
1167                ""
1168            }
1169            crate::AddressSpace::WorkGroup | crate::AddressSpace::TaskPayload => {
1170                write!(self.out, "groupshared ")?;
1171                self.write_type(module, global.ty)?;
1172                ""
1173            }
1174            crate::AddressSpace::Uniform => {
1175                // constant buffer declarations are expected to be inlined, e.g.
1176                // `cbuffer foo: register(b0) { field1: type1; }`
1177                write!(self.out, "cbuffer")?;
1178                "b"
1179            }
1180            crate::AddressSpace::Storage { access } => {
1181                if global
1182                    .memory_decorations
1183                    .contains(crate::MemoryDecorations::COHERENT)
1184                {
1185                    write!(self.out, "globallycoherent ")?;
1186                }
1187                let (prefix, register) = if access.contains(crate::StorageAccess::STORE) {
1188                    ("RW", "u")
1189                } else {
1190                    ("", "t")
1191                };
1192                write!(self.out, "{prefix}ByteAddressBuffer")?;
1193                register
1194            }
1195            crate::AddressSpace::Handle => {
1196                let register = match *handle_ty {
1197                    // all storage textures are UAV, unconditionally
1198                    TypeInner::Image {
1199                        class: crate::ImageClass::Storage { .. },
1200                        ..
1201                    } => "u",
1202                    _ => "t",
1203                };
1204                self.write_type(module, global.ty)?;
1205                register
1206            }
1207            crate::AddressSpace::Immediate => {
1208                unreachable!("Immediates are handled by `write_global_immediate`")
1209            }
1210            crate::AddressSpace::RayPayload | crate::AddressSpace::IncomingRayPayload => {
1211                unimplemented!()
1212            }
1213        };
1214
1215        let name = &self.names[&NameKey::GlobalVariable(handle)];
1216        write!(self.out, " {name}")?;
1217
1218        if let Some(ref binding) = global.binding {
1219            // this was already resolved earlier when we started evaluating an entry point.
1220            let bt = self.options.resolve_resource_binding(binding).unwrap();
1221
1222            // need to write the binding array size if the type was emitted with `write_type`
1223            if let TypeInner::BindingArray { base, size, .. } = module.types[global.ty].inner {
1224                if let Some(overridden_size) = bt.binding_array_size {
1225                    write!(self.out, "[{overridden_size}]")?;
1226                } else {
1227                    self.write_array_size(module, base, size)?;
1228                }
1229            }
1230
1231            write!(self.out, " : register({}{}", register_ty, bt.register)?;
1232            if bt.space != 0 {
1233                write!(self.out, ", space{}", bt.space)?;
1234            }
1235            write!(self.out, ")")?;
1236        } else {
1237            // need to write the array size if the type was emitted with `write_type`
1238            if let TypeInner::Array { base, size, .. } = module.types[global.ty].inner {
1239                self.write_array_size(module, base, size)?;
1240            }
1241            if global.space == crate::AddressSpace::Private {
1242                write!(self.out, " = ")?;
1243                if let Some(init) = global.init {
1244                    self.write_const_expression(module, init, &module.global_expressions)?;
1245                } else {
1246                    self.write_default_init(module, global.ty)?;
1247                }
1248            }
1249        }
1250
1251        if global.space == crate::AddressSpace::Uniform {
1252            write!(self.out, " {{ ")?;
1253
1254            self.write_global_type(module, global.ty)?;
1255
1256            write!(
1257                self.out,
1258                " {}",
1259                self.names[&NameKey::GlobalVariable(handle)]
1260            )?;
1261
1262            // need to write the array size if the type was emitted with `write_type`
1263            if let TypeInner::Array { base, size, .. } = module.types[global.ty].inner {
1264                self.write_array_size(module, base, size)?;
1265            }
1266
1267            writeln!(self.out, "; }}")?;
1268        } else {
1269            writeln!(self.out, ";")?;
1270        }
1271
1272        Ok(())
1273    }
1274
1275    fn write_global_sampler(
1276        &mut self,
1277        module: &Module,
1278        handle: Handle<crate::GlobalVariable>,
1279        global: &crate::GlobalVariable,
1280    ) -> BackendResult {
1281        let binding = *global.binding.as_ref().unwrap();
1282
1283        let key = super::SamplerIndexBufferKey {
1284            group: binding.group,
1285        };
1286        self.write_wrapped_sampler_buffer(key)?;
1287
1288        // This was already validated, so we can confidently unwrap it.
1289        let bt = self.options.resolve_resource_binding(&binding).unwrap();
1290
1291        match module.types[global.ty].inner {
1292            TypeInner::Sampler { comparison } => {
1293                // If we are generating a static access, we create a variable for the sampler.
1294                //
1295                // This prevents the DXIL from containing multiple lookups for the sampler, which
1296                // the backend compiler will then have to eliminate. AMD does seem to be able to
1297                // eliminate these, but better safe than sorry.
1298
1299                write!(self.out, "static const ")?;
1300                self.write_type(module, global.ty)?;
1301
1302                let heap_var = if comparison {
1303                    COMPARISON_SAMPLER_HEAP_VAR
1304                } else {
1305                    SAMPLER_HEAP_VAR
1306                };
1307
1308                let index_buffer_name = &self.wrapped.sampler_index_buffers[&key];
1309                let name = &self.names[&NameKey::GlobalVariable(handle)];
1310                writeln!(
1311                    self.out,
1312                    " {name} = {heap_var}[{index_buffer_name}[{register}]];",
1313                    register = bt.register
1314                )?;
1315            }
1316            TypeInner::BindingArray { .. } => {
1317                // If we are generating a binding array, we cannot directly access the sampler as the index
1318                // into the sampler index buffer is unknown at compile time. Instead we generate a constant
1319                // that represents the "base" index into the sampler index buffer. This constant is added
1320                // to the user provided index to get the final index into the sampler index buffer.
1321
1322                let name = &self.names[&NameKey::GlobalVariable(handle)];
1323                writeln!(
1324                    self.out,
1325                    "static const uint {name} = {register};",
1326                    register = bt.register
1327                )?;
1328            }
1329            _ => unreachable!(),
1330        };
1331
1332        Ok(())
1333    }
1334
1335    /// Write the declarations for an external texture global variable.
1336    /// These are emitted as multiple global variables: Three `Texture2D`s
1337    /// (one for each plane) and a parameters cbuffer.
1338    fn write_global_external_texture(
1339        &mut self,
1340        module: &Module,
1341        handle: Handle<crate::GlobalVariable>,
1342        global: &crate::GlobalVariable,
1343    ) -> BackendResult {
1344        let res_binding = global
1345            .binding
1346            .as_ref()
1347            .expect("External texture global variables must have a resource binding");
1348        let ext_tex_bindings = match self
1349            .options
1350            .resolve_external_texture_resource_binding(res_binding)
1351        {
1352            Ok(bindings) => bindings,
1353            Err(err) => {
1354                log::debug!(
1355                    "Skipping global {:?} (name {:?}) for being inaccessible: {}",
1356                    handle,
1357                    global.name,
1358                    err,
1359                );
1360                return Ok(());
1361            }
1362        };
1363
1364        let mut write_plane = |bt: &super::BindTarget, name| -> BackendResult {
1365            write!(
1366                self.out,
1367                "Texture2D<float4> {}: register(t{}",
1368                name, bt.register
1369            )?;
1370            if bt.space != 0 {
1371                write!(self.out, ", space{}", bt.space)?;
1372            }
1373            writeln!(self.out, ");")?;
1374            Ok(())
1375        };
1376        for (i, bt) in ext_tex_bindings.planes.iter().enumerate() {
1377            let plane_name = &self.names
1378                [&NameKey::ExternalTextureGlobalVariable(handle, ExternalTextureNameKey::Plane(i))];
1379            write_plane(bt, plane_name)?;
1380        }
1381
1382        let params_name = &self.names
1383            [&NameKey::ExternalTextureGlobalVariable(handle, ExternalTextureNameKey::Params)];
1384        let params_ty_name =
1385            &self.names[&NameKey::Type(module.special_types.external_texture_params.unwrap())];
1386        write!(
1387            self.out,
1388            "cbuffer {}: register(b{}",
1389            params_name, ext_tex_bindings.params.register
1390        )?;
1391        if ext_tex_bindings.params.space != 0 {
1392            write!(self.out, ", space{}", ext_tex_bindings.params.space)?;
1393        }
1394        writeln!(self.out, ") {{ {params_ty_name} {params_name}; }};")?;
1395
1396        Ok(())
1397    }
1398
1399    /// Helper method used to write global constants
1400    ///
1401    /// # Notes
1402    /// Ends in a newline
1403    fn write_global_constant(
1404        &mut self,
1405        module: &Module,
1406        handle: Handle<crate::Constant>,
1407    ) -> BackendResult {
1408        write!(self.out, "static const ")?;
1409        let constant = &module.constants[handle];
1410        self.write_type(module, constant.ty)?;
1411        let name = &self.names[&NameKey::Constant(handle)];
1412        write!(self.out, " {name}")?;
1413        // Write size for array type
1414        if let TypeInner::Array { base, size, .. } = module.types[constant.ty].inner {
1415            self.write_array_size(module, base, size)?;
1416        }
1417        write!(self.out, " = ")?;
1418        self.write_const_expression(module, constant.init, &module.global_expressions)?;
1419        writeln!(self.out, ";")?;
1420        Ok(())
1421    }
1422
1423    pub(super) fn write_array_size(
1424        &mut self,
1425        module: &Module,
1426        base: Handle<crate::Type>,
1427        size: crate::ArraySize,
1428    ) -> BackendResult {
1429        write!(self.out, "[")?;
1430
1431        match size.resolve(module.to_ctx())? {
1432            proc::IndexableLength::Known(size) => {
1433                write!(self.out, "{size}")?;
1434            }
1435            proc::IndexableLength::Dynamic => unreachable!(),
1436        }
1437
1438        write!(self.out, "]")?;
1439
1440        if let TypeInner::Array {
1441            base: next_base,
1442            size: next_size,
1443            ..
1444        } = module.types[base].inner
1445        {
1446            self.write_array_size(module, next_base, next_size)?;
1447        }
1448
1449        Ok(())
1450    }
1451
1452    /// Helper method used to write structs
1453    ///
1454    /// # Notes
1455    /// Ends in a newline
1456    fn write_struct(
1457        &mut self,
1458        module: &Module,
1459        handle: Handle<crate::Type>,
1460        members: &[crate::StructMember],
1461        span: u32,
1462        shader_stage: Option<(ShaderStage, Io)>,
1463    ) -> BackendResult {
1464        // Write struct name
1465        let struct_name = &self.names[&NameKey::Type(handle)];
1466        writeln!(self.out, "struct {struct_name} {{")?;
1467
1468        let mut last_offset = 0;
1469        for (index, member) in members.iter().enumerate() {
1470            if member.binding.is_none() && member.offset > last_offset {
1471                // using int as padding should work as long as the backend
1472                // doesn't support a type that's less than 4 bytes in size
1473                // (Error::UnsupportedScalar catches this)
1474                let padding = (member.offset - last_offset) / 4;
1475                for i in 0..padding {
1476                    writeln!(self.out, "{}int _pad{}_{};", back::INDENT, index, i)?;
1477                }
1478            }
1479            let ty_inner = &module.types[member.ty].inner;
1480            last_offset = member.offset + ty_inner.size_hlsl(module.to_ctx())?;
1481
1482            // The indentation is only for readability
1483            write!(self.out, "{}", back::INDENT)?;
1484
1485            match module.types[member.ty].inner {
1486                TypeInner::Array { base, size, .. } => {
1487                    // HLSL arrays are written as `type name[size]`
1488
1489                    self.write_global_type(module, member.ty)?;
1490
1491                    // Write `name`
1492                    write!(
1493                        self.out,
1494                        " {}",
1495                        self.names[&NameKey::StructMember(handle, index as u32)]
1496                    )?;
1497                    // Write [size]
1498                    self.write_array_size(module, base, size)?;
1499                }
1500                // We treat matrices of the form `matCx2` as a sequence of C `vec2`s.
1501                // See the module-level block comment in mod.rs for details.
1502                TypeInner::Matrix {
1503                    rows,
1504                    columns,
1505                    scalar,
1506                } if member.binding.is_none() && rows == crate::VectorSize::Bi => {
1507                    let vec_ty = TypeInner::Vector { size: rows, scalar };
1508                    let field_name_key = NameKey::StructMember(handle, index as u32);
1509
1510                    for i in 0..columns as u8 {
1511                        if i != 0 {
1512                            write!(self.out, "; ")?;
1513                        }
1514                        self.write_value_type(module, &vec_ty)?;
1515                        write!(self.out, " {}_{}", self.names[&field_name_key], i)?;
1516                    }
1517                }
1518                _ => {
1519                    // Write modifier before type
1520                    if let Some(ref binding) = member.binding {
1521                        self.write_modifier(binding)?;
1522                    }
1523
1524                    // Even though Naga IR matrices are column-major, we must describe
1525                    // matrices passed from the CPU as being in row-major order.
1526                    // See the module-level block comment in mod.rs for details.
1527                    if let TypeInner::Matrix { .. } = module.types[member.ty].inner {
1528                        write!(self.out, "row_major ")?;
1529                    }
1530
1531                    // Write the member type and name
1532                    self.write_type(module, member.ty)?;
1533                    write!(
1534                        self.out,
1535                        " {}",
1536                        self.names[&NameKey::StructMember(handle, index as u32)]
1537                    )?;
1538                }
1539            }
1540
1541            self.write_semantic(&member.binding, shader_stage)?;
1542            writeln!(self.out, ";")?;
1543        }
1544
1545        // add padding at the end since sizes of types don't get rounded up to their alignment in HLSL
1546        if members.last().unwrap().binding.is_none() && span > last_offset {
1547            let padding = (span - last_offset) / 4;
1548            for i in 0..padding {
1549                writeln!(self.out, "{}int _end_pad_{};", back::INDENT, i)?;
1550            }
1551        }
1552
1553        writeln!(self.out, "}};")?;
1554        Ok(())
1555    }
1556
1557    /// Helper method used to write global/structs non image/sampler types
1558    ///
1559    /// # Notes
1560    /// Adds no trailing or leading whitespace
1561    pub(super) fn write_global_type(
1562        &mut self,
1563        module: &Module,
1564        ty: Handle<crate::Type>,
1565    ) -> BackendResult {
1566        let matrix_data = get_inner_matrix_data(module, ty);
1567
1568        // We treat matrices of the form `matCx2` as a sequence of C `vec2`s.
1569        // See the module-level block comment in mod.rs for details.
1570        if let Some(MatrixType {
1571            columns,
1572            rows: crate::VectorSize::Bi,
1573            width,
1574        }) = matrix_data
1575        {
1576            write!(self.out, "__mat{}x2_f{}", columns as u8, width * 8)?;
1577        } else {
1578            // Even though Naga IR matrices are column-major, we must describe
1579            // matrices passed from the CPU as being in row-major order.
1580            // See the module-level block comment in mod.rs for details.
1581            if matrix_data.is_some() {
1582                write!(self.out, "row_major ")?;
1583            }
1584
1585            self.write_type(module, ty)?;
1586        }
1587
1588        Ok(())
1589    }
1590
1591    /// Helper method used to write non image/sampler types
1592    ///
1593    /// # Notes
1594    /// Adds no trailing or leading whitespace
1595    pub(super) fn write_type(&mut self, module: &Module, ty: Handle<crate::Type>) -> BackendResult {
1596        let inner = &module.types[ty].inner;
1597        match *inner {
1598            TypeInner::Struct { .. } => write!(self.out, "{}", self.names[&NameKey::Type(ty)])?,
1599            // hlsl array has the size separated from the base type
1600            TypeInner::Array { base, .. } | TypeInner::BindingArray { base, .. } => {
1601                self.write_type(module, base)?
1602            }
1603            ref other => self.write_value_type(module, other)?,
1604        }
1605
1606        Ok(())
1607    }
1608
1609    /// Helper method used to write value types
1610    ///
1611    /// # Notes
1612    /// Adds no trailing or leading whitespace
1613    pub(super) fn write_value_type(&mut self, module: &Module, inner: &TypeInner) -> BackendResult {
1614        match *inner {
1615            TypeInner::Scalar(scalar) | TypeInner::Atomic(scalar) => {
1616                write!(self.out, "{}", scalar.to_hlsl_str()?)?;
1617            }
1618            TypeInner::Vector { size, scalar } => {
1619                write!(
1620                    self.out,
1621                    "{}{}",
1622                    scalar.to_hlsl_str()?,
1623                    common::vector_size_str(size)
1624                )?;
1625            }
1626            TypeInner::Matrix {
1627                columns,
1628                rows,
1629                scalar,
1630            } => {
1631                // The IR supports only float matrix
1632                // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-matrix
1633
1634                // Because of the implicit transpose all matrices have in HLSL, we need to transpose the size as well.
1635                write!(
1636                    self.out,
1637                    "{}{}x{}",
1638                    scalar.to_hlsl_str()?,
1639                    common::vector_size_str(columns),
1640                    common::vector_size_str(rows),
1641                )?;
1642            }
1643            TypeInner::Image {
1644                dim,
1645                arrayed,
1646                class,
1647            } => {
1648                self.write_image_type(dim, arrayed, class)?;
1649            }
1650            TypeInner::Sampler { comparison } => {
1651                let sampler = if comparison {
1652                    "SamplerComparisonState"
1653                } else {
1654                    "SamplerState"
1655                };
1656                write!(self.out, "{sampler}")?;
1657            }
1658            // HLSL arrays are written as `type name[size]`
1659            // Current code is written arrays only as `[size]`
1660            // Base `type` and `name` should be written outside
1661            TypeInner::Array { base, size, .. } | TypeInner::BindingArray { base, size } => {
1662                self.write_array_size(module, base, size)?;
1663            }
1664            TypeInner::AccelerationStructure { .. } => {
1665                write!(self.out, "RaytracingAccelerationStructure")?;
1666            }
1667            TypeInner::RayQuery { .. } => {
1668                // these are constant flags, there are dynamic flags also but constant flags are not supported by naga
1669                write!(self.out, "RayQuery<RAY_FLAG_NONE>")?;
1670            }
1671            _ => return Err(Error::Unimplemented(format!("write_value_type {inner:?}"))),
1672        }
1673
1674        Ok(())
1675    }
1676
1677    /// Helper method used to write functions
1678    /// # Notes
1679    /// Ends in a newline
1680    fn write_function(
1681        &mut self,
1682        module: &Module,
1683        name: &str,
1684        func: &crate::Function,
1685        func_ctx: &back::FunctionCtx<'_>,
1686        info: &valid::FunctionInfo,
1687        header: String,
1688    ) -> BackendResult {
1689        // Function Declaration Syntax - https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-function-syntax
1690
1691        self.update_expressions_to_bake(module, func, info);
1692        let ep = match func_ctx.ty {
1693            back::FunctionType::EntryPoint(idx) => Some(&module.entry_points[idx as usize]),
1694            back::FunctionType::Function(_) => None,
1695        };
1696
1697        let nested = matches!(
1698            ep,
1699            Some(crate::EntryPoint {
1700                stage: ShaderStage::Task | ShaderStage::Mesh,
1701                ..
1702            })
1703        );
1704        if !nested {
1705            write!(self.out, "{header}")?;
1706        }
1707
1708        let result = func
1709            .result
1710            .as_ref()
1711            .filter(|_| !ep.is_some_and(|ep| only_writes_discarded_depth(module, ep)));
1712
1713        if let Some(result) = result {
1714            // Write typedef if return type is an array
1715            let array_return_type = match module.types[result.ty].inner {
1716                TypeInner::Array { base, size, .. } => {
1717                    let array_return_type = self.namer.call(&format!("ret_{name}"));
1718                    write!(self.out, "typedef ")?;
1719                    self.write_type(module, result.ty)?;
1720                    write!(self.out, " {array_return_type}")?;
1721                    self.write_array_size(module, base, size)?;
1722                    writeln!(self.out, ";")?;
1723                    Some(array_return_type)
1724                }
1725                _ => None,
1726            };
1727
1728            // Write modifier
1729            if let Some(
1730                ref binding @ crate::Binding::BuiltIn(crate::BuiltIn::Position { invariant: true }),
1731            ) = result.binding
1732            {
1733                self.write_modifier(binding)?;
1734            }
1735
1736            // Write return type
1737            match func_ctx.ty {
1738                back::FunctionType::Function(_) => {
1739                    if let Some(array_return_type) = array_return_type {
1740                        write!(self.out, "{array_return_type}")?;
1741                    } else {
1742                        self.write_type(module, result.ty)?;
1743                    }
1744                }
1745                back::FunctionType::EntryPoint(index) => {
1746                    if let Some(ref ep_output) =
1747                        self.entry_point_io.get(&(index as usize)).unwrap().output
1748                    {
1749                        write!(self.out, "{}", ep_output.ty_name)?;
1750                    } else {
1751                        self.write_type(module, result.ty)?;
1752                    }
1753                }
1754            }
1755        } else {
1756            write!(self.out, "void")?;
1757        }
1758
1759        let nested_name = if nested {
1760            self.namer.call(&format!("_{name}"))
1761        } else {
1762            name.to_string()
1763        };
1764
1765        // Write function name
1766        write!(self.out, " {nested_name}(")?;
1767
1768        let need_workgroup_variables_initialization =
1769            self.need_workgroup_variables_initialization(func_ctx, module);
1770
1771        let mut any_args_written = false;
1772        let mut separator = || {
1773            if any_args_written {
1774                ", "
1775            } else {
1776                any_args_written = true;
1777                ""
1778            }
1779        };
1780
1781        let needs_local_invocation_index_name = need_workgroup_variables_initialization || nested;
1782        let mut local_invocation_index_name = None;
1783        // For nested entry points, collect arg names as we write them so that
1784        // write_nested_function_outer can pass the exact same names to the call site.
1785        let mut nested_wgsl_args: Vec<String> = Vec::new();
1786        let mut nested_task_payload_name: Option<String> = None;
1787        // Write function arguments for non entry point functions
1788        match func_ctx.ty {
1789            back::FunctionType::Function(handle) => {
1790                for (index, arg) in func.arguments.iter().enumerate() {
1791                    write!(self.out, "{}", separator())?;
1792                    self.write_function_argument(module, handle, arg, index)?;
1793                }
1794                // If this reads a task payload variable the variable needs to be passed as an `in` argument
1795                for (var_handle, var) in module.global_variables.iter() {
1796                    let uses = info[var_handle];
1797                    if uses.contains(valid::GlobalUse::READ)
1798                        && !uses.contains(valid::GlobalUse::WRITE)
1799                        && var.space == crate::AddressSpace::TaskPayload
1800                    {
1801                        self.function_task_payload_var.insert(handle, var_handle);
1802                        write!(self.out, "{}in ", separator())?;
1803
1804                        self.write_type(module, var.ty)?;
1805                        let name = &self.names[&NameKey::GlobalVariable(var_handle)];
1806                        write!(self.out, " {name}")?;
1807                        break;
1808                    }
1809                }
1810            }
1811            back::FunctionType::EntryPoint(ep_index) => {
1812                let ep = &module.entry_points[ep_index as usize];
1813                if let Some(ref ep_input) =
1814                    self.entry_point_io.get(&(ep_index as usize)).unwrap().input
1815                {
1816                    write!(self.out, "{} {}", ep_input.ty_name, ep_input.arg_name)?;
1817                    separator();
1818                    nested_wgsl_args.push(ep_input.arg_name.clone());
1819                } else {
1820                    let stage = ep.stage;
1821                    for (index, arg) in func.arguments.iter().enumerate() {
1822                        write!(self.out, "{}", separator())?;
1823                        self.write_type(module, arg.ty)?;
1824
1825                        let argument_name =
1826                            &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)];
1827
1828                        if arg.binding
1829                            == Some(crate::Binding::BuiltIn(
1830                                crate::BuiltIn::LocalInvocationIndex,
1831                            ))
1832                        {
1833                            local_invocation_index_name = Some(argument_name.clone());
1834                        }
1835
1836                        nested_wgsl_args.push(argument_name.clone());
1837                        write!(self.out, " {argument_name}")?;
1838                        if let TypeInner::Array { base, size, .. } = module.types[arg.ty].inner {
1839                            self.write_array_size(module, base, size)?;
1840                        }
1841
1842                        self.write_semantic(&arg.binding, Some((stage, Io::Input)))?;
1843                    }
1844                }
1845                if ep.stage == ShaderStage::Mesh {
1846                    if let Some(var_handle) = ep.task_payload {
1847                        let var = &module.global_variables[var_handle];
1848                        write!(self.out, "{}in ", separator())?;
1849                        self.write_type(module, var.ty)?;
1850                        let arg_name = &self.names[&NameKey::GlobalVariable(var_handle)];
1851                        write!(self.out, " {arg_name}")?;
1852                        nested_task_payload_name = Some(arg_name.clone());
1853                        if let TypeInner::Array { base, size, .. } = module.types[var.ty].inner {
1854                            self.write_array_size(module, base, size)?;
1855                        }
1856                    }
1857                }
1858                if needs_local_invocation_index_name && local_invocation_index_name.is_none() {
1859                    let name = self.namer.call("local_invocation_index");
1860                    write!(self.out, "{}uint {name}", separator())?;
1861                    write!(self.out, " : SV_GroupIndex")?;
1862                    local_invocation_index_name = Some(name);
1863                }
1864            }
1865        }
1866        // Ends of arguments
1867        write!(self.out, ")")?;
1868
1869        // Write semantic if it present
1870        if let back::FunctionType::EntryPoint(index) = func_ctx.ty {
1871            let entry_point = &module.entry_points[index as usize];
1872            if let Some(result) = result {
1873                self.with_early_depth_test(entry_point.early_depth_test, |this| {
1874                    this.write_semantic(&result.binding, Some((entry_point.stage, Io::Output)))
1875                })?;
1876            }
1877        }
1878
1879        // Function body start
1880        writeln!(self.out)?;
1881        writeln!(self.out, "{{")?;
1882
1883        if need_workgroup_variables_initialization && !nested {
1884            // need_workgroup_variables_initialization forces this to be written
1885            // if the user doesn't specify it (so this must be Some())
1886            self.write_workgroup_variables_initialization(
1887                func_ctx,
1888                module,
1889                local_invocation_index_name.as_ref().unwrap(),
1890            )?;
1891        }
1892
1893        if let back::FunctionType::EntryPoint(index) = func_ctx.ty {
1894            self.write_ep_arguments_initialization(module, func, index)?;
1895        }
1896
1897        if let back::FunctionType::EntryPoint(_) = func_ctx.ty {
1898            self.write_immediates_initialization(module, info)?;
1899        }
1900
1901        // Write function local variables
1902        for (handle, local) in func.local_variables.iter() {
1903            // Write indentation (only for readability)
1904            write!(self.out, "{}", back::INDENT)?;
1905
1906            // Write the local name
1907            // The leading space is important
1908            self.write_type(module, local.ty)?;
1909            write!(self.out, " {}", self.names[&func_ctx.name_key(handle)])?;
1910            // Write size for array type
1911            if let TypeInner::Array { base, size, .. } = module.types[local.ty].inner {
1912                self.write_array_size(module, base, size)?;
1913            }
1914
1915            let is_ray_query = match module.types[local.ty].inner {
1916                // from https://microsoft.github.io/DirectX-Specs/d3d/Raytracing.html#tracerayinline-example-1 it seems that ray queries shouldn't be zeroed
1917                TypeInner::RayQuery { .. } => true,
1918                _ => {
1919                    write!(self.out, " = ")?;
1920                    // Write the local initializer if needed
1921                    if let Some(init) = local.init {
1922                        self.write_expr(module, init, func_ctx)?;
1923                    } else {
1924                        // Zero initialize local variables
1925                        self.write_default_init(module, local.ty)?;
1926                    }
1927                    false
1928                }
1929            };
1930            // Finish the local with `;` and add a newline (only for readability)
1931            writeln!(self.out, ";")?;
1932            // If it's a ray query, we also want a tracker variable
1933            if is_ray_query {
1934                write!(self.out, "{}", back::INDENT)?;
1935                self.write_value_type(module, &TypeInner::Scalar(Scalar::U32))?;
1936                writeln!(
1937                    self.out,
1938                    " {RAY_QUERY_TRACKER_VARIABLE_PREFIX}{} = 0;",
1939                    self.names[&func_ctx.name_key(handle)]
1940                )?;
1941            }
1942        }
1943
1944        if !func.local_variables.is_empty() {
1945            writeln!(self.out)?;
1946        }
1947
1948        // Write the function body (statement list)
1949        for sta in func.body.iter() {
1950            // The indentation should always be 1 when writing the function body
1951            self.write_stmt(module, sta, func_ctx, back::Level(1))?;
1952        }
1953
1954        writeln!(self.out, "}}")?;
1955
1956        if nested {
1957            self.write_nested_function_outer(
1958                module,
1959                func_ctx,
1960                &header,
1961                name,
1962                need_workgroup_variables_initialization,
1963                &nested_name,
1964                ep.unwrap(),
1965                NestedEntryPointArgs {
1966                    user_args: nested_wgsl_args,
1967                    task_payload: nested_task_payload_name,
1968                    // guaranteed to be set for nested functions (task/mesh shaders)
1969                    local_invocation_index: local_invocation_index_name.unwrap(),
1970                },
1971            )?;
1972        }
1973
1974        self.named_expressions.clear();
1975
1976        Ok(())
1977    }
1978
1979    fn write_function_argument(
1980        &mut self,
1981        module: &Module,
1982        handle: Handle<crate::Function>,
1983        arg: &crate::FunctionArgument,
1984        index: usize,
1985    ) -> BackendResult {
1986        // External texture arguments must be expanded into separate
1987        // arguments for each plane and the params buffer.
1988        if module.types[arg.ty].inner.is_external_image() {
1989            return self.write_function_external_texture_argument(module, handle, index);
1990        }
1991
1992        // Write argument type
1993        let arg_ty = match module.types[arg.ty].inner {
1994            // pointers in function arguments are expected and resolve to `inout`
1995            TypeInner::Pointer { base, .. } => {
1996                //TODO: can we narrow this down to just `in` when possible?
1997                write!(self.out, "inout ")?;
1998                base
1999            }
2000            _ => arg.ty,
2001        };
2002        self.write_type(module, arg_ty)?;
2003
2004        let argument_name = &self.names[&NameKey::FunctionArgument(handle, index as u32)];
2005
2006        // Write argument name. Space is important.
2007        write!(self.out, " {argument_name}")?;
2008        if let TypeInner::Array { base, size, .. } = module.types[arg_ty].inner {
2009            self.write_array_size(module, base, size)?;
2010        }
2011
2012        Ok(())
2013    }
2014
2015    fn write_function_external_texture_argument(
2016        &mut self,
2017        module: &Module,
2018        handle: Handle<crate::Function>,
2019        index: usize,
2020    ) -> BackendResult {
2021        let plane_names = [0, 1, 2].map(|i| {
2022            &self.names[&NameKey::ExternalTextureFunctionArgument(
2023                handle,
2024                index as u32,
2025                ExternalTextureNameKey::Plane(i),
2026            )]
2027        });
2028        let params_name = &self.names[&NameKey::ExternalTextureFunctionArgument(
2029            handle,
2030            index as u32,
2031            ExternalTextureNameKey::Params,
2032        )];
2033        let params_ty_name =
2034            &self.names[&NameKey::Type(module.special_types.external_texture_params.unwrap())];
2035        write!(
2036            self.out,
2037            "Texture2D<float4> {}, Texture2D<float4> {}, Texture2D<float4> {}, {params_ty_name} {params_name}",
2038            plane_names[0], plane_names[1], plane_names[2],
2039        )?;
2040        Ok(())
2041    }
2042
2043    fn need_workgroup_variables_initialization(
2044        &mut self,
2045        func_ctx: &back::FunctionCtx,
2046        module: &Module,
2047    ) -> bool {
2048        self.options.zero_initialize_workgroup_memory
2049            && func_ctx.ty.is_compute_like_entry_point(module)
2050            && module.global_variables.iter().any(|(handle, var)| {
2051                !func_ctx.info[handle].is_empty() && var.space.is_workgroup_like()
2052            })
2053    }
2054
2055    /// Writes code that zeroes `access`, of type `ty`, with the work spread over the workgroup.
2056    ///
2057    /// `struct_array_element` is true if `access` is an element of an array that is a struct member.
2058    fn write_compute_workgroup_init(
2059        &mut self,
2060        module: &Module,
2061        ty: proc::TypeResolution,
2062        access: &str,
2063        struct_array_element: bool,
2064        dimensions: &mut Vec<(String, u32)>,
2065        invocations: WorkgroupInitInvocations,
2066    ) -> BackendResult {
2067        match *ty.inner_with(&module.types) {
2068            TypeInner::Array { base, size, .. } => {
2069                let proc::IndexableLength::Known(count) = size.resolve(module.to_ctx())? else {
2070                    unreachable!();
2071                };
2072                let index = self.namer.call("zero_index");
2073                let element = format!("{access}[{index}]");
2074                dimensions.push((index, count));
2075                self.write_compute_workgroup_init(
2076                    module,
2077                    proc::TypeResolution::Handle(base),
2078                    &element,
2079                    struct_array_element,
2080                    dimensions,
2081                    invocations,
2082                )?;
2083                dimensions.pop();
2084            }
2085            TypeInner::Struct { ref members, .. } => {
2086                for (index, member) in members.iter().enumerate() {
2087                    let name =
2088                        &self.names[&NameKey::StructMember(ty.handle().unwrap(), index as u32)];
2089                    let field = format!("{access}.{name}");
2090                    match module.types[member.ty].inner {
2091                        TypeInner::Matrix {
2092                            columns,
2093                            rows: crate::VectorSize::Bi,
2094                            scalar,
2095                        } if member.binding.is_none() => {
2096                            for column in 0..columns as u8 {
2097                                self.write_compute_workgroup_init(
2098                                    module,
2099                                    proc::TypeResolution::Value(TypeInner::Vector {
2100                                        size: crate::VectorSize::Bi,
2101                                        scalar,
2102                                    }),
2103                                    &format!("{field}_{column}"),
2104                                    false,
2105                                    dimensions,
2106                                    invocations,
2107                                )?;
2108                            }
2109                        }
2110                        _ => {
2111                            self.write_compute_workgroup_init(
2112                                module,
2113                                proc::TypeResolution::Handle(member.ty),
2114                                &field,
2115                                matches!(module.types[member.ty].inner, TypeInner::Array { .. }),
2116                                dimensions,
2117                                invocations,
2118                            )?;
2119                        }
2120                    }
2121                }
2122            }
2123            ref inner => {
2124                let level = back::Level(1);
2125                let body = level.next();
2126                let WorkgroupInitInvocations {
2127                    local_index,
2128                    workgroup_size,
2129                } = invocations;
2130                if dimensions.is_empty() {
2131                    writeln!(self.out, "{level}if ({local_index} == 0) {{")?;
2132                } else {
2133                    let count = dimensions
2134                        .iter()
2135                        .try_fold(1u32, |total, &(_, size)| total.checked_mul(size))
2136                        .ok_or_else(|| {
2137                            Error::Custom("Workgroup array element count overflow".into())
2138                        })?;
2139                    let index = self.namer.call("zero_flat_index");
2140                    // Keep DXC from expanding large aggregate initializers during optimization.
2141                    writeln!(self.out, "{level}[loop]")?;
2142                    writeln!(self.out, "{level}for (uint {index} = {local_index}; {index} < {count}u; {index} += {workgroup_size}u) {{")?;
2143                    let mut stride = count;
2144                    for (i, &(ref dimension, size)) in dimensions.iter().enumerate() {
2145                        stride /= size;
2146                        let mut value = index.clone();
2147                        if stride != 1 {
2148                            value = format!("{value} / {stride}u");
2149                        }
2150                        // The loop bound keeps the outermost index in range.
2151                        if i != 0 {
2152                            if stride != 1 {
2153                                value = format!("({value})");
2154                            }
2155                            value = format!("{value} % {size}u");
2156                        }
2157                        writeln!(self.out, "{body}uint {dimension} = {value};")?;
2158                    }
2159                }
2160                write!(self.out, "{body}{access} = (")?;
2161                if struct_array_element
2162                    && matches!(
2163                        inner,
2164                        TypeInner::Matrix {
2165                            rows: crate::VectorSize::Bi,
2166                            ..
2167                        }
2168                    )
2169                {
2170                    self.write_global_type(module, ty.handle().unwrap())?;
2171                } else {
2172                    self.write_value_type(module, inner)?;
2173                }
2174                writeln!(self.out, ")0;")?;
2175                writeln!(self.out, "{level}}}")?;
2176            }
2177        }
2178        Ok(())
2179    }
2180
2181    /// Writes the zero initialization of the workgroup variables that the entry point uses,
2182    /// followed by a workgroup barrier.
2183    pub(super) fn write_workgroup_variables_initialization(
2184        &mut self,
2185        func_ctx: &back::FunctionCtx,
2186        module: &Module,
2187        local_invocation_index: &str,
2188    ) -> BackendResult {
2189        let back::FunctionType::EntryPoint(ep_index) = func_ctx.ty else {
2190            unreachable!();
2191        };
2192        let entry_point = &module.entry_points[ep_index as usize];
2193        let workgroup_size = entry_point
2194            .workgroup_size
2195            .iter()
2196            .try_fold(1u32, |total, &size| total.checked_mul(size))
2197            .ok_or_else(|| Error::Custom("Workgroup invocation count overflow".into()))?;
2198        for (handle, var) in module.global_variables.iter() {
2199            // The task payload is read-only in mesh shaders.
2200            let task_needs_zero = var.space == crate::AddressSpace::TaskPayload
2201                && entry_point.stage == ShaderStage::Task;
2202            if !func_ctx.info[handle].is_empty()
2203                && (var.space == crate::AddressSpace::WorkGroup || task_needs_zero)
2204            {
2205                let name = self.names[&NameKey::GlobalVariable(handle)].clone();
2206                self.write_compute_workgroup_init(
2207                    module,
2208                    proc::TypeResolution::Handle(var.ty),
2209                    &name,
2210                    false,
2211                    &mut Vec::new(),
2212                    WorkgroupInitInvocations {
2213                        local_index: local_invocation_index,
2214                        workgroup_size,
2215                    },
2216                )?;
2217            }
2218        }
2219        self.write_control_barrier(crate::Barrier::WORK_GROUP, back::Level(1))
2220    }
2221
2222    /// Helper method used to write switches
2223    fn write_switch(
2224        &mut self,
2225        module: &Module,
2226        func_ctx: &back::FunctionCtx<'_>,
2227        level: back::Level,
2228        selector: Handle<crate::Expression>,
2229        cases: &[crate::SwitchCase],
2230    ) -> BackendResult {
2231        // Write all cases
2232        let indent_level_1 = level.next();
2233        let indent_level_2 = indent_level_1.next();
2234
2235        // See docs of `back::continue_forward` module.
2236        if let Some(variable) = self.continue_ctx.enter_switch(&mut self.namer) {
2237            writeln!(self.out, "{level}bool {variable} = false;",)?;
2238        };
2239
2240        // Check if there is only one body, by seeing if all except the last case are fall through
2241        // with empty bodies. FXC doesn't handle these switches correctly, so
2242        // we generate a `do {} while(false);` loop instead. There must be a default case, so there
2243        // is no need to check if one of the cases would have matched.
2244        let one_body = cases
2245            .iter()
2246            .rev()
2247            .skip(1)
2248            .all(|case| case.fall_through && case.body.is_empty());
2249        if one_body {
2250            // Start the do-while
2251            writeln!(self.out, "{level}do {{")?;
2252            // Note: Expressions have no side-effects so we don't need to emit selector expression.
2253
2254            // Body
2255            if let Some(case) = cases.last() {
2256                for sta in case.body.iter() {
2257                    self.write_stmt(module, sta, func_ctx, indent_level_1)?;
2258                }
2259            }
2260            // End do-while
2261            writeln!(self.out, "{level}}} while(false);")?;
2262        } else {
2263            // Start the switch
2264            write!(self.out, "{level}")?;
2265            write!(self.out, "switch(")?;
2266            self.write_expr(module, selector, func_ctx)?;
2267            writeln!(self.out, ") {{")?;
2268
2269            for (i, case) in cases.iter().enumerate() {
2270                match case.value {
2271                    crate::SwitchValue::I32(value) => {
2272                        write!(self.out, "{indent_level_1}case {value}:")?
2273                    }
2274                    crate::SwitchValue::U32(value) => {
2275                        write!(self.out, "{indent_level_1}case {value}u:")?
2276                    }
2277                    crate::SwitchValue::Default => write!(self.out, "{indent_level_1}default:")?,
2278                }
2279
2280                // The new block is not only stylistic, it plays a role here:
2281                // We might end up having to write the same case body
2282                // multiple times due to FXC not supporting fallthrough.
2283                // Therefore, some `Expression`s written by `Statement::Emit`
2284                // will end up having the same name (`_expr<handle_index>`).
2285                // So we need to put each case in its own scope.
2286                let write_block_braces = !(case.fall_through && case.body.is_empty());
2287                if write_block_braces {
2288                    writeln!(self.out, " {{")?;
2289                } else {
2290                    writeln!(self.out)?;
2291                }
2292
2293                // Although FXC does support a series of case clauses before
2294                // a block[^yes], it does not support fallthrough from a
2295                // non-empty case block to the next[^no]. If this case has a
2296                // non-empty body with a fallthrough, emulate that by
2297                // duplicating the bodies of all the cases it would fall
2298                // into as extensions of this case's own body. This makes
2299                // the HLSL output potentially quadratic in the size of the
2300                // Naga IR.
2301                //
2302                // [^yes]: ```hlsl
2303                // case 1:
2304                // case 2: do_stuff()
2305                // ```
2306                // [^no]: ```hlsl
2307                // case 1: do_this();
2308                // case 2: do_that();
2309                // ```
2310                if case.fall_through && !case.body.is_empty() {
2311                    let curr_len = i + 1;
2312                    let end_case_idx = curr_len
2313                        + cases
2314                            .iter()
2315                            .skip(curr_len)
2316                            .position(|case| !case.fall_through)
2317                            .unwrap();
2318                    let indent_level_3 = indent_level_2.next();
2319                    for case in &cases[i..=end_case_idx] {
2320                        writeln!(self.out, "{indent_level_2}{{")?;
2321                        let prev_len = self.named_expressions.len();
2322                        for sta in case.body.iter() {
2323                            self.write_stmt(module, sta, func_ctx, indent_level_3)?;
2324                        }
2325                        // Clear all named expressions that were previously inserted by the statements in the block
2326                        self.named_expressions.truncate(prev_len);
2327                        writeln!(self.out, "{indent_level_2}}}")?;
2328                    }
2329
2330                    let last_case = &cases[end_case_idx];
2331                    if last_case.body.last().is_none_or(|s| !s.is_terminator()) {
2332                        writeln!(self.out, "{indent_level_2}break;")?;
2333                    }
2334                } else {
2335                    for sta in case.body.iter() {
2336                        self.write_stmt(module, sta, func_ctx, indent_level_2)?;
2337                    }
2338                    if !case.fall_through && case.body.last().is_none_or(|s| !s.is_terminator()) {
2339                        writeln!(self.out, "{indent_level_2}break;")?;
2340                    }
2341                }
2342
2343                if write_block_braces {
2344                    writeln!(self.out, "{indent_level_1}}}")?;
2345                }
2346            }
2347
2348            writeln!(self.out, "{level}}}")?;
2349        }
2350
2351        // Handle any forwarded continue statements.
2352        use back::continue_forward::ExitControlFlow;
2353        let op = match self.continue_ctx.exit_switch() {
2354            ExitControlFlow::None => None,
2355            ExitControlFlow::Continue { variable } => Some(("continue", variable)),
2356            ExitControlFlow::Break { variable } => Some(("break", variable)),
2357        };
2358        if let Some((control_flow, variable)) = op {
2359            writeln!(self.out, "{level}if ({variable}) {{")?;
2360            writeln!(self.out, "{indent_level_1}{control_flow};")?;
2361            writeln!(self.out, "{level}}}")?;
2362        }
2363
2364        Ok(())
2365    }
2366
2367    fn write_index(
2368        &mut self,
2369        module: &Module,
2370        index: Index,
2371        func_ctx: &back::FunctionCtx<'_>,
2372    ) -> BackendResult {
2373        match index {
2374            Index::Static(index) => {
2375                write!(self.out, "{index}")?;
2376            }
2377            Index::Expression(index) => {
2378                self.write_expr(module, index, func_ctx)?;
2379            }
2380        }
2381        Ok(())
2382    }
2383
2384    /// Helper method used to write statements
2385    ///
2386    /// # Notes
2387    /// Always adds a newline
2388    fn write_stmt(
2389        &mut self,
2390        module: &Module,
2391        stmt: &crate::Statement,
2392        func_ctx: &back::FunctionCtx<'_>,
2393        level: back::Level,
2394    ) -> BackendResult {
2395        use crate::Statement;
2396
2397        match *stmt {
2398            Statement::Emit(ref range) => {
2399                for handle in range.clone() {
2400                    let ptr_class = func_ctx.resolve_type(handle, &module.types).pointer_space();
2401                    let expr_name = if ptr_class.is_some() {
2402                        // HLSL can't save a pointer-valued expression in a variable,
2403                        // but we shouldn't ever need to: they should never be named expressions,
2404                        // and none of the expression types flagged by bake_ref_count can be pointer-valued.
2405                        None
2406                    } else if let Some(name) = func_ctx.named_expressions.get(&handle) {
2407                        // Front end provides names for all variables at the start of writing.
2408                        // But we write them to step by step. We need to recache them
2409                        // Otherwise, we could accidentally write variable name instead of full expression.
2410                        // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords.
2411                        Some(self.namer.call(name))
2412                    } else if self.need_bake_expressions.contains(&handle) {
2413                        Some(Baked(handle).to_string())
2414                    } else {
2415                        None
2416                    };
2417
2418                    if let Some(name) = expr_name {
2419                        write!(self.out, "{level}")?;
2420                        self.write_named_expr(module, handle, name, handle, func_ctx)?;
2421                    }
2422                }
2423            }
2424            // TODO: copy-paste from glsl-out
2425            Statement::Block(ref block) => {
2426                write!(self.out, "{level}")?;
2427                writeln!(self.out, "{{")?;
2428                for sta in block.iter() {
2429                    // Increase the indentation to help with readability
2430                    self.write_stmt(module, sta, func_ctx, level.next())?
2431                }
2432                writeln!(self.out, "{level}}}")?
2433            }
2434            // TODO: copy-paste from glsl-out
2435            Statement::If {
2436                condition,
2437                ref accept,
2438                ref reject,
2439            } => {
2440                write!(self.out, "{level}")?;
2441                write!(self.out, "if (")?;
2442                self.write_expr(module, condition, func_ctx)?;
2443                writeln!(self.out, ") {{")?;
2444
2445                let l2 = level.next();
2446                for sta in accept {
2447                    // Increase indentation to help with readability
2448                    self.write_stmt(module, sta, func_ctx, l2)?;
2449                }
2450
2451                // If there are no statements in the reject block we skip writing it
2452                // This is only for readability
2453                if !reject.is_empty() {
2454                    writeln!(self.out, "{level}}} else {{")?;
2455
2456                    for sta in reject {
2457                        // Increase indentation to help with readability
2458                        self.write_stmt(module, sta, func_ctx, l2)?;
2459                    }
2460                }
2461
2462                writeln!(self.out, "{level}}}")?
2463            }
2464            // TODO: copy-paste from glsl-out
2465            Statement::Kill => writeln!(self.out, "{level}discard;")?,
2466            Statement::Return { value: None } => {
2467                writeln!(self.out, "{level}return;")?;
2468            }
2469            Statement::Return { value: Some(_) } if returns_nothing(module, func_ctx) => {
2470                writeln!(self.out, "{level}return;")?;
2471            }
2472            Statement::Return { value: Some(expr) } => {
2473                let base_ty_res = &func_ctx.info[expr].ty;
2474                let mut resolved = base_ty_res.inner_with(&module.types);
2475                if let TypeInner::Pointer { base, space: _ } = *resolved {
2476                    resolved = &module.types[base].inner;
2477                }
2478
2479                if let TypeInner::Struct { .. } = *resolved {
2480                    // We can safely unwrap here, since we now we working with struct
2481                    let ty = base_ty_res.handle().unwrap();
2482                    let struct_name = &self.names[&NameKey::Type(ty)];
2483                    let variable_name = self.namer.call(&struct_name.to_lowercase());
2484                    write!(self.out, "{level}const {struct_name} {variable_name} = ",)?;
2485                    self.write_expr(module, expr, func_ctx)?;
2486                    writeln!(self.out, ";")?;
2487
2488                    // for entry point returns, we may need to reshuffle the outputs into a different struct
2489                    let ep_output = match func_ctx.ty {
2490                        back::FunctionType::Function(_) => None,
2491                        back::FunctionType::EntryPoint(index) => self
2492                            .entry_point_io
2493                            .get(&(index as usize))
2494                            .unwrap()
2495                            .output
2496                            .as_ref(),
2497                    };
2498                    let final_name = match ep_output {
2499                        Some(ep_output) => {
2500                            let final_name = self.namer.call(&variable_name);
2501                            write!(
2502                                self.out,
2503                                "{}const {} {} = {{ ",
2504                                level, ep_output.ty_name, final_name,
2505                            )?;
2506                            for (index, m) in ep_output.members.iter().enumerate() {
2507                                if index != 0 {
2508                                    write!(self.out, ", ")?;
2509                                }
2510                                let member_name = &self.names[&NameKey::StructMember(ty, m.index)];
2511                                write!(self.out, "{variable_name}.{member_name}")?;
2512                            }
2513                            writeln!(self.out, " }};")?;
2514                            final_name
2515                        }
2516                        None => variable_name,
2517                    };
2518                    writeln!(self.out, "{level}return {final_name};")?;
2519                } else {
2520                    write!(self.out, "{level}return ")?;
2521                    self.write_expr(module, expr, func_ctx)?;
2522                    writeln!(self.out, ";")?
2523                }
2524            }
2525            Statement::Store { pointer, value } => {
2526                let ty_inner = func_ctx.resolve_type(pointer, &module.types);
2527                if ty_inner.is_atomic_pointer(&module.types) {
2528                    let pointer_space = ty_inner.pointer_space().unwrap();
2529                    let dummy = self.namer.call("dummy");
2530                    write!(self.out, "{level}{{ ")?;
2531                    if let TypeInner::Pointer { base, .. } = *ty_inner {
2532                        self.write_value_type(module, &module.types[base].inner)?;
2533                    }
2534                    write!(self.out, " {dummy} = 0; ")?;
2535                    match pointer_space {
2536                        crate::AddressSpace::WorkGroup => {
2537                            write!(self.out, "InterlockedExchange(")?;
2538                            self.write_expr(module, pointer, func_ctx)?;
2539                        }
2540                        crate::AddressSpace::Storage { .. } => {
2541                            let var_handle = self.fill_access_chain(module, pointer, func_ctx)?;
2542                            let var_name = &self.names[&NameKey::GlobalVariable(var_handle)];
2543                            write!(self.out, "{var_name}.InterlockedExchange(")?;
2544                            let chain = mem::take(&mut self.temp_access_chain);
2545                            self.write_storage_address(module, &chain, func_ctx)?;
2546                            self.temp_access_chain = chain;
2547                        }
2548                        _ => unreachable!(),
2549                    }
2550                    write!(self.out, ", ")?;
2551                    self.write_expr(module, value, func_ctx)?;
2552                    writeln!(self.out, ", {dummy}); }}")?;
2553                } else if let Some(crate::AddressSpace::Storage { .. }) = ty_inner.pointer_space() {
2554                    let var_handle = self.fill_access_chain(module, pointer, func_ctx)?;
2555                    self.write_storage_store(
2556                        module,
2557                        var_handle,
2558                        StoreValue::Expression(value),
2559                        func_ctx,
2560                        level,
2561                        None,
2562                    )?;
2563                } else {
2564                    // We treat matrices of the form `matCx2` as a sequence of C `vec2`s.
2565                    // See the module-level block comment in mod.rs for details.
2566                    //
2567                    // We handle matrix Stores here directly (including sub accesses for Vectors and Scalars).
2568                    // Loads are handled by `Expression::AccessIndex` (since sub accesses work fine for Loads).
2569                    enum MatrixAccess {
2570                        Direct {
2571                            base: Handle<crate::Expression>,
2572                            index: u32,
2573                        },
2574                        Struct {
2575                            columns: crate::VectorSize,
2576                            width: u8,
2577                            base: Handle<crate::Expression>,
2578                        },
2579                    }
2580
2581                    let get_members = |expr: Handle<crate::Expression>| {
2582                        let resolved = func_ctx.resolve_type(expr, &module.types);
2583                        match *resolved {
2584                            TypeInner::Pointer { base, .. } => match module.types[base].inner {
2585                                TypeInner::Struct { ref members, .. } => Some(members),
2586                                _ => None,
2587                            },
2588                            _ => None,
2589                        }
2590                    };
2591
2592                    write!(self.out, "{level}")?;
2593
2594                    let matrix_access_on_lhs =
2595                        find_matrix_in_access_chain(module, pointer, func_ctx).and_then(
2596                            |(matrix_expr, vector, scalar)| match (
2597                                func_ctx.resolve_type(matrix_expr, &module.types),
2598                                &func_ctx.expressions[matrix_expr],
2599                            ) {
2600                                (
2601                                    &TypeInner::Pointer { base: ty, .. },
2602                                    &crate::Expression::AccessIndex { base, index },
2603                                ) if matches!(
2604                                    module.types[ty].inner,
2605                                    TypeInner::Matrix {
2606                                        rows: crate::VectorSize::Bi,
2607                                        ..
2608                                    }
2609                                ) && get_members(base)
2610                                    .map(|members| members[index as usize].binding.is_none())
2611                                    == Some(true) =>
2612                                {
2613                                    Some((MatrixAccess::Direct { base, index }, vector, scalar))
2614                                }
2615                                _ => {
2616                                    if let Some(MatrixType {
2617                                        columns,
2618                                        rows: crate::VectorSize::Bi,
2619                                        width,
2620                                    }) = get_inner_matrix_of_struct_array_member(
2621                                        module,
2622                                        matrix_expr,
2623                                        func_ctx,
2624                                        true,
2625                                    ) {
2626                                        Some((
2627                                            MatrixAccess::Struct {
2628                                                columns,
2629                                                width,
2630                                                base: matrix_expr,
2631                                            },
2632                                            vector,
2633                                            scalar,
2634                                        ))
2635                                    } else {
2636                                        None
2637                                    }
2638                                }
2639                            },
2640                        );
2641
2642                    match matrix_access_on_lhs {
2643                        Some((MatrixAccess::Direct { index, base }, vector, scalar)) => {
2644                            let base_ty_res = &func_ctx.info[base].ty;
2645                            let resolved = base_ty_res.inner_with(&module.types);
2646                            let ty = match *resolved {
2647                                TypeInner::Pointer { base, .. } => base,
2648                                _ => base_ty_res.handle().unwrap(),
2649                            };
2650
2651                            if let Some(Index::Static(vec_index)) = vector {
2652                                self.write_expr(module, base, func_ctx)?;
2653                                write!(
2654                                    self.out,
2655                                    ".{}_{}",
2656                                    self.names[&NameKey::StructMember(ty, index)],
2657                                    vec_index
2658                                )?;
2659
2660                                if let Some(scalar_index) = scalar {
2661                                    write!(self.out, "[")?;
2662                                    self.write_index(module, scalar_index, func_ctx)?;
2663                                    write!(self.out, "]")?;
2664                                }
2665
2666                                write!(self.out, " = ")?;
2667                                self.write_expr(module, value, func_ctx)?;
2668                                writeln!(self.out, ";")?;
2669                            } else {
2670                                let access = WrappedStructMatrixAccess { ty, index };
2671                                match (&vector, &scalar) {
2672                                    (&Some(_), &Some(_)) => {
2673                                        self.write_wrapped_struct_matrix_set_scalar_function_name(
2674                                            access,
2675                                        )?;
2676                                    }
2677                                    (&Some(_), &None) => {
2678                                        self.write_wrapped_struct_matrix_set_vec_function_name(
2679                                            access,
2680                                        )?;
2681                                    }
2682                                    (&None, _) => {
2683                                        self.write_wrapped_struct_matrix_set_function_name(access)?;
2684                                    }
2685                                }
2686
2687                                write!(self.out, "(")?;
2688                                self.write_expr(module, base, func_ctx)?;
2689                                write!(self.out, ", ")?;
2690                                self.write_expr(module, value, func_ctx)?;
2691
2692                                if let Some(Index::Expression(vec_index)) = vector {
2693                                    write!(self.out, ", ")?;
2694                                    self.write_expr(module, vec_index, func_ctx)?;
2695
2696                                    if let Some(scalar_index) = scalar {
2697                                        write!(self.out, ", ")?;
2698                                        self.write_index(module, scalar_index, func_ctx)?;
2699                                    }
2700                                }
2701                                writeln!(self.out, ");")?;
2702                            }
2703                        }
2704                        Some((
2705                            MatrixAccess::Struct {
2706                                columns,
2707                                width,
2708                                base,
2709                            },
2710                            Some(Index::Expression(vec_index)),
2711                            scalar,
2712                        )) => {
2713                            // We handle `Store`s to __matCx2 column vectors and scalar elements via
2714                            // the previously injected functions __set_col_of_matCx2 / __set_el_of_matCx2.
2715
2716                            if scalar.is_some() {
2717                                write!(
2718                                    self.out,
2719                                    "__set_el_of_mat{}x2_f{}",
2720                                    columns as u8,
2721                                    width * 8
2722                                )?;
2723                            } else {
2724                                write!(
2725                                    self.out,
2726                                    "__set_col_of_mat{}x2_f{}",
2727                                    columns as u8,
2728                                    width * 8
2729                                )?;
2730                            }
2731                            write!(self.out, "(")?;
2732                            self.write_expr(module, base, func_ctx)?;
2733                            write!(self.out, ", ")?;
2734                            self.write_expr(module, vec_index, func_ctx)?;
2735
2736                            if let Some(scalar_index) = scalar {
2737                                write!(self.out, ", ")?;
2738                                self.write_index(module, scalar_index, func_ctx)?;
2739                            }
2740
2741                            write!(self.out, ", ")?;
2742                            self.write_expr(module, value, func_ctx)?;
2743
2744                            writeln!(self.out, ");")?;
2745                        }
2746                        Some((MatrixAccess::Struct { .. }, Some(Index::Static(_)), _))
2747                        | Some((MatrixAccess::Struct { .. }, None, _))
2748                        | None => {
2749                            self.write_expr(module, pointer, func_ctx)?;
2750                            write!(self.out, " = ")?;
2751
2752                            // We cast the RHS of this store in cases where the LHS
2753                            // is a struct member with type:
2754                            //  - matCx2 or
2755                            //  - a (possibly nested) array of matCx2's
2756                            if let Some(MatrixType {
2757                                columns,
2758                                rows: crate::VectorSize::Bi,
2759                                width,
2760                            }) = get_inner_matrix_of_struct_array_member(
2761                                module, pointer, func_ctx, false,
2762                            ) {
2763                                let mut resolved = func_ctx.resolve_type(pointer, &module.types);
2764                                if let TypeInner::Pointer { base, .. } = *resolved {
2765                                    resolved = &module.types[base].inner;
2766                                }
2767
2768                                write!(self.out, "(__mat{}x2_f{}", columns as u8, width * 8)?;
2769                                if let TypeInner::Array { base, size, .. } = *resolved {
2770                                    self.write_array_size(module, base, size)?;
2771                                }
2772                                write!(self.out, ")")?;
2773                            }
2774
2775                            self.write_expr(module, value, func_ctx)?;
2776                            writeln!(self.out, ";")?
2777                        }
2778                    }
2779                }
2780            }
2781            Statement::Loop {
2782                ref body,
2783                ref continuing,
2784                break_if,
2785            } => {
2786                let force_loop_bound_statements = self.gen_force_bounded_loop_statements(level);
2787                let gate_name = (!continuing.is_empty() || break_if.is_some())
2788                    .then(|| self.namer.call("loop_init"));
2789
2790                if let Some((ref decl, _)) = force_loop_bound_statements {
2791                    writeln!(self.out, "{decl}")?;
2792                }
2793                if let Some(ref gate_name) = gate_name {
2794                    writeln!(self.out, "{level}bool {gate_name} = true;")?;
2795                }
2796
2797                self.continue_ctx.enter_loop();
2798                writeln!(self.out, "{level}while(true) {{")?;
2799                if let Some((_, ref break_and_inc)) = force_loop_bound_statements {
2800                    writeln!(self.out, "{break_and_inc}")?;
2801                }
2802                let l2 = level.next();
2803                if let Some(gate_name) = gate_name {
2804                    writeln!(self.out, "{l2}if (!{gate_name}) {{")?;
2805                    let l3 = l2.next();
2806                    for sta in continuing.iter() {
2807                        self.write_stmt(module, sta, func_ctx, l3)?;
2808                    }
2809                    if let Some(condition) = break_if {
2810                        write!(self.out, "{l3}if (")?;
2811                        self.write_expr(module, condition, func_ctx)?;
2812                        writeln!(self.out, ") {{")?;
2813                        writeln!(self.out, "{}break;", l3.next())?;
2814                        writeln!(self.out, "{l3}}}")?;
2815                    }
2816                    writeln!(self.out, "{l2}}}")?;
2817                    writeln!(self.out, "{l2}{gate_name} = false;")?;
2818                }
2819
2820                for sta in body.iter() {
2821                    self.write_stmt(module, sta, func_ctx, l2)?;
2822                }
2823
2824                writeln!(self.out, "{level}}}")?;
2825                self.continue_ctx.exit_loop();
2826            }
2827            Statement::Break => writeln!(self.out, "{level}break;")?,
2828            Statement::Continue => {
2829                if let Some(variable) = self.continue_ctx.continue_encountered() {
2830                    writeln!(self.out, "{level}{variable} = true;")?;
2831                    writeln!(self.out, "{level}break;")?
2832                } else {
2833                    writeln!(self.out, "{level}continue;")?
2834                }
2835            }
2836            Statement::ControlBarrier(barrier) => {
2837                self.write_control_barrier(barrier, level)?;
2838            }
2839            Statement::MemoryBarrier(barrier) => {
2840                self.write_memory_barrier(barrier, level)?;
2841            }
2842            Statement::ImageStore {
2843                image,
2844                coordinate,
2845                array_index,
2846                value,
2847            } => {
2848                write!(self.out, "{level}")?;
2849                self.write_expr(module, image, func_ctx)?;
2850
2851                write!(self.out, "[")?;
2852                if let Some(index) = array_index {
2853                    // Array index accepted only for texture_storage_2d_array, so we can safety use int3(coordinate, array_index) here
2854                    write!(self.out, "int3(")?;
2855                    self.write_expr(module, coordinate, func_ctx)?;
2856                    write!(self.out, ", ")?;
2857                    self.write_expr(module, index, func_ctx)?;
2858                    write!(self.out, ")")?;
2859                } else {
2860                    self.write_expr(module, coordinate, func_ctx)?;
2861                }
2862                write!(self.out, "]")?;
2863
2864                write!(self.out, " = ")?;
2865                self.write_expr(module, value, func_ctx)?;
2866                writeln!(self.out, ";")?;
2867            }
2868            Statement::Call {
2869                function,
2870                ref arguments,
2871                result,
2872            } => {
2873                write!(self.out, "{level}")?;
2874
2875                if let Some(expr) = result {
2876                    write!(self.out, "const ")?;
2877                    let name = Baked(expr).to_string();
2878                    let expr_ty = &func_ctx.info[expr].ty;
2879                    let ty_inner = match *expr_ty {
2880                        proc::TypeResolution::Handle(handle) => {
2881                            self.write_type(module, handle)?;
2882                            &module.types[handle].inner
2883                        }
2884                        proc::TypeResolution::Value(ref value) => {
2885                            self.write_value_type(module, value)?;
2886                            value
2887                        }
2888                    };
2889                    write!(self.out, " {name}")?;
2890                    if let TypeInner::Array { base, size, .. } = *ty_inner {
2891                        self.write_array_size(module, base, size)?;
2892                    }
2893                    write!(self.out, " = ")?;
2894                    self.named_expressions.insert(expr, name);
2895                }
2896                let func_name = &self.names[&NameKey::Function(function)];
2897                write!(self.out, "{func_name}(")?;
2898                let mut any_args_written = false;
2899                let mut separator = || {
2900                    if any_args_written {
2901                        ", "
2902                    } else {
2903                        any_args_written = true;
2904                        ""
2905                    }
2906                };
2907                for argument in arguments {
2908                    write!(self.out, "{}", separator())?;
2909                    self.write_expr(module, *argument, func_ctx)?;
2910                }
2911                if let Some(&var) = self.function_task_payload_var.get(&function) {
2912                    let name = &self.names[&NameKey::GlobalVariable(var)];
2913                    // Pass it through directly, whether its an in variable to this function or the global variable
2914                    write!(self.out, "{}{name}", separator())?;
2915                }
2916                writeln!(self.out, ");")?;
2917            }
2918            Statement::Atomic {
2919                pointer,
2920                ref fun,
2921                value,
2922                result,
2923            } => {
2924                write!(self.out, "{level}")?;
2925                let res_var_info = if let Some(res_handle) = result {
2926                    let name = Baked(res_handle).to_string();
2927                    match func_ctx.info[res_handle].ty {
2928                        proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?,
2929                        proc::TypeResolution::Value(ref value) => {
2930                            self.write_value_type(module, value)?
2931                        }
2932                    };
2933                    write!(self.out, " {name}; ")?;
2934                    self.named_expressions.insert(res_handle, name.clone());
2935                    Some((res_handle, name))
2936                } else {
2937                    None
2938                };
2939                let pointer_space = func_ctx
2940                    .resolve_type(pointer, &module.types)
2941                    .pointer_space()
2942                    .unwrap();
2943                let fun_str = fun.to_hlsl_suffix();
2944                let compare_expr = match *fun {
2945                    crate::AtomicFunction::Exchange { compare: Some(cmp) } => Some(cmp),
2946                    _ => None,
2947                };
2948                match pointer_space {
2949                    crate::AddressSpace::WorkGroup => {
2950                        write!(self.out, "Interlocked{fun_str}(")?;
2951                        self.write_expr(module, pointer, func_ctx)?;
2952                        self.emit_hlsl_atomic_tail(
2953                            module,
2954                            func_ctx,
2955                            fun,
2956                            compare_expr,
2957                            value,
2958                            &res_var_info,
2959                        )?;
2960                    }
2961                    crate::AddressSpace::Storage { .. } => {
2962                        let var_handle = self.fill_access_chain(module, pointer, func_ctx)?;
2963                        let var_name = &self.names[&NameKey::GlobalVariable(var_handle)];
2964                        let width = match func_ctx.resolve_type(value, &module.types) {
2965                            &TypeInner::Scalar(Scalar { width: 8, .. }) => "64",
2966                            _ => "",
2967                        };
2968                        write!(self.out, "{var_name}.Interlocked{fun_str}{width}(")?;
2969                        let chain = mem::take(&mut self.temp_access_chain);
2970                        self.write_storage_address(module, &chain, func_ctx)?;
2971                        self.temp_access_chain = chain;
2972                        self.emit_hlsl_atomic_tail(
2973                            module,
2974                            func_ctx,
2975                            fun,
2976                            compare_expr,
2977                            value,
2978                            &res_var_info,
2979                        )?;
2980                    }
2981                    ref other => {
2982                        return Err(Error::Custom(format!(
2983                            "invalid address space {other:?} for atomic statement"
2984                        )))
2985                    }
2986                }
2987                if let Some(cmp) = compare_expr {
2988                    if let Some(&(_res_handle, ref res_name)) = res_var_info.as_ref() {
2989                        write!(
2990                            self.out,
2991                            "{level}{res_name}.exchanged = ({res_name}.old_value == "
2992                        )?;
2993                        self.write_expr(module, cmp, func_ctx)?;
2994                        writeln!(self.out, ");")?;
2995                    }
2996                }
2997            }
2998            Statement::ImageAtomic {
2999                image,
3000                coordinate,
3001                array_index,
3002                fun,
3003                value,
3004            } => {
3005                write!(self.out, "{level}")?;
3006
3007                let fun_str = fun.to_hlsl_suffix();
3008                write!(self.out, "Interlocked{fun_str}(")?;
3009                self.write_expr(module, image, func_ctx)?;
3010                write!(self.out, "[")?;
3011                self.write_texture_coordinates(
3012                    "int",
3013                    coordinate,
3014                    array_index,
3015                    None,
3016                    module,
3017                    func_ctx,
3018                )?;
3019                write!(self.out, "],")?;
3020
3021                self.write_expr(module, value, func_ctx)?;
3022                writeln!(self.out, ");")?;
3023            }
3024            Statement::WorkGroupUniformLoad { pointer, result } => {
3025                self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?;
3026                write!(self.out, "{level}")?;
3027                let name = Baked(result).to_string();
3028                self.write_named_expr(module, pointer, name, result, func_ctx)?;
3029
3030                self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?;
3031            }
3032            Statement::Switch {
3033                selector,
3034                ref cases,
3035            } => {
3036                self.write_switch(module, func_ctx, level, selector, cases)?;
3037            }
3038            Statement::RayQuery { query, ref fun } => {
3039                // There are three possibilities for a ptr to be:
3040                // 1. A variable
3041                // 2. A function argument
3042                // 3. part of a struct
3043                //
3044                // 2 and 3 are not possible, a ray query (in naga IR)
3045                // is not allowed to be passed into a function, and
3046                // all languages disallow it in a struct (you get fun results if
3047                // you try it :) ).
3048                //
3049                // Therefore, the ray query expression must be a variable.
3050                let crate::Expression::LocalVariable(query_var) = func_ctx.expressions[query]
3051                else {
3052                    unreachable!()
3053                };
3054
3055                let tracker_expr_name = format!(
3056                    "{RAY_QUERY_TRACKER_VARIABLE_PREFIX}{}",
3057                    self.names[&func_ctx.name_key(query_var)]
3058                );
3059
3060                match *fun {
3061                    RayQueryFunction::Initialize {
3062                        acceleration_structure,
3063                        descriptor,
3064                    } => {
3065                        self.write_initialize_function(
3066                            module,
3067                            level,
3068                            query,
3069                            acceleration_structure,
3070                            descriptor,
3071                            &tracker_expr_name,
3072                            func_ctx,
3073                        )?;
3074                    }
3075                    RayQueryFunction::Proceed { result } => {
3076                        self.write_proceed(
3077                            module,
3078                            level,
3079                            query,
3080                            result,
3081                            &tracker_expr_name,
3082                            func_ctx,
3083                        )?;
3084                    }
3085                    RayQueryFunction::GenerateIntersection { hit_t } => {
3086                        self.write_generate_intersection(
3087                            module,
3088                            level,
3089                            query,
3090                            hit_t,
3091                            &tracker_expr_name,
3092                            func_ctx,
3093                        )?;
3094                    }
3095                    RayQueryFunction::ConfirmIntersection => {
3096                        self.write_confirm_intersection(
3097                            module,
3098                            level,
3099                            query,
3100                            &tracker_expr_name,
3101                            func_ctx,
3102                        )?;
3103                    }
3104                    RayQueryFunction::Terminate => {
3105                        self.write_terminate(module, level, query, &tracker_expr_name, func_ctx)?;
3106                    }
3107                    RayQueryFunction::Begin => {
3108                        if self.options.ray_query_initialization_tracking {
3109                            writeln!(self.out, "{level}{tracker_expr_name} = 0u;")?;
3110                        }
3111                    }
3112                }
3113            }
3114            Statement::SubgroupBallot { result, predicate } => {
3115                write!(self.out, "{level}")?;
3116                let name = Baked(result).to_string();
3117                write!(self.out, "const uint4 {name} = ")?;
3118                self.named_expressions.insert(result, name);
3119
3120                write!(self.out, "WaveActiveBallot(")?;
3121                match predicate {
3122                    Some(predicate) => self.write_expr(module, predicate, func_ctx)?,
3123                    None => write!(self.out, "true")?,
3124                }
3125                writeln!(self.out, ");")?;
3126            }
3127            Statement::SubgroupCollectiveOperation {
3128                op,
3129                collective_op,
3130                argument,
3131                result,
3132            } => {
3133                write!(self.out, "{level}")?;
3134                write!(self.out, "const ")?;
3135                let name = Baked(result).to_string();
3136                match func_ctx.info[result].ty {
3137                    proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?,
3138                    proc::TypeResolution::Value(ref value) => {
3139                        self.write_value_type(module, value)?
3140                    }
3141                };
3142                write!(self.out, " {name} = ")?;
3143                self.named_expressions.insert(result, name);
3144
3145                match (collective_op, op) {
3146                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::All) => {
3147                        write!(self.out, "WaveActiveAllTrue(")?
3148                    }
3149                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Any) => {
3150                        write!(self.out, "WaveActiveAnyTrue(")?
3151                    }
3152                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Add) => {
3153                        write!(self.out, "WaveActiveSum(")?
3154                    }
3155                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Mul) => {
3156                        write!(self.out, "WaveActiveProduct(")?
3157                    }
3158                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Max) => {
3159                        write!(self.out, "WaveActiveMax(")?
3160                    }
3161                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Min) => {
3162                        write!(self.out, "WaveActiveMin(")?
3163                    }
3164                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::And) => {
3165                        write!(self.out, "WaveActiveBitAnd(")?
3166                    }
3167                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Or) => {
3168                        write!(self.out, "WaveActiveBitOr(")?
3169                    }
3170                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Xor) => {
3171                        write!(self.out, "WaveActiveBitXor(")?
3172                    }
3173                    (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Add) => {
3174                        write!(self.out, "WavePrefixSum(")?
3175                    }
3176                    (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Mul) => {
3177                        write!(self.out, "WavePrefixProduct(")?
3178                    }
3179                    (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Add) => {
3180                        self.write_expr(module, argument, func_ctx)?;
3181                        write!(self.out, " + WavePrefixSum(")?;
3182                    }
3183                    (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Mul) => {
3184                        self.write_expr(module, argument, func_ctx)?;
3185                        write!(self.out, " * WavePrefixProduct(")?;
3186                    }
3187                    _ => unimplemented!(),
3188                }
3189                self.write_expr(module, argument, func_ctx)?;
3190                writeln!(self.out, ");")?;
3191            }
3192            Statement::SubgroupGather {
3193                mode,
3194                argument,
3195                result,
3196            } => {
3197                write!(self.out, "{level}")?;
3198                write!(self.out, "const ")?;
3199                let name = Baked(result).to_string();
3200                match func_ctx.info[result].ty {
3201                    proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?,
3202                    proc::TypeResolution::Value(ref value) => {
3203                        self.write_value_type(module, value)?
3204                    }
3205                };
3206                write!(self.out, " {name} = ")?;
3207                self.named_expressions.insert(result, name);
3208                match mode {
3209                    crate::GatherMode::BroadcastFirst => {
3210                        write!(self.out, "WaveReadLaneFirst(")?;
3211                        self.write_expr(module, argument, func_ctx)?;
3212                    }
3213                    crate::GatherMode::QuadBroadcast(index) => {
3214                        write!(self.out, "QuadReadLaneAt(")?;
3215                        self.write_expr(module, argument, func_ctx)?;
3216                        write!(self.out, ", ")?;
3217                        self.write_expr(module, index, func_ctx)?;
3218                    }
3219                    crate::GatherMode::QuadSwap(direction) => {
3220                        match direction {
3221                            crate::Direction::X => {
3222                                write!(self.out, "QuadReadAcrossX(")?;
3223                            }
3224                            crate::Direction::Y => {
3225                                write!(self.out, "QuadReadAcrossY(")?;
3226                            }
3227                            crate::Direction::Diagonal => {
3228                                write!(self.out, "QuadReadAcrossDiagonal(")?;
3229                            }
3230                        }
3231                        self.write_expr(module, argument, func_ctx)?;
3232                    }
3233                    _ => {
3234                        write!(self.out, "WaveReadLaneAt(")?;
3235                        self.write_expr(module, argument, func_ctx)?;
3236                        write!(self.out, ", ")?;
3237                        match mode {
3238                            crate::GatherMode::BroadcastFirst => unreachable!(),
3239                            crate::GatherMode::Broadcast(index)
3240                            | crate::GatherMode::Shuffle(index) => {
3241                                self.write_expr(module, index, func_ctx)?;
3242                            }
3243                            crate::GatherMode::ShuffleDown(index) => {
3244                                write!(self.out, "WaveGetLaneIndex() + ")?;
3245                                self.write_expr(module, index, func_ctx)?;
3246                            }
3247                            crate::GatherMode::ShuffleUp(index) => {
3248                                write!(self.out, "WaveGetLaneIndex() - ")?;
3249                                self.write_expr(module, index, func_ctx)?;
3250                            }
3251                            crate::GatherMode::ShuffleXor(index) => {
3252                                write!(self.out, "WaveGetLaneIndex() ^ ")?;
3253                                self.write_expr(module, index, func_ctx)?;
3254                            }
3255                            crate::GatherMode::QuadBroadcast(_) => unreachable!(),
3256                            crate::GatherMode::QuadSwap(_) => unreachable!(),
3257                        }
3258                    }
3259                }
3260                writeln!(self.out, ");")?;
3261            }
3262            Statement::SubgroupBallotFindBit {
3263                order,
3264                argument,
3265                result,
3266            } => {
3267                // Evaluate each ballot word once into a local, rather than
3268                // repeatedly writing `argument.x`/`.y`/`.z`/`.w` in the
3269                // ternary chain below.
3270                const COMPONENTS: [char; 4] = ['x', 'y', 'z', 'w'];
3271                let mut words: [String; 4] = core::array::from_fn(|_| String::new());
3272                for (word, &component) in words.iter_mut().zip(&COMPONENTS) {
3273                    write!(self.out, "{level}const uint ")?;
3274                    let name = self.namer.call("");
3275                    write!(self.out, "{name} = ")?;
3276                    self.write_expr(module, argument, func_ctx)?;
3277                    writeln!(self.out, ".{component};")?;
3278                    *word = name;
3279                }
3280
3281                write!(self.out, "{level}")?;
3282                write!(self.out, "const ")?;
3283                let name = Baked(result).to_string();
3284                match func_ctx.info[result].ty {
3285                    proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?,
3286                    proc::TypeResolution::Value(ref value) => {
3287                        self.write_value_type(module, value)?
3288                    }
3289                };
3290                write!(self.out, " {name} = ")?;
3291                self.named_expressions.insert(result, name);
3292
3293                self.write_ballot_find_bit(&words, order, 3)?;
3294                writeln!(self.out, ";")?;
3295            }
3296            Statement::CooperativeStore { .. } => unimplemented!(),
3297            Statement::RayPipelineFunction(_) | Statement::HitObject { .. } => unreachable!(),
3298            Statement::DebugPrintf { .. } => unimplemented!(),
3299        }
3300
3301        Ok(())
3302    }
3303
3304    #[allow(clippy::too_many_arguments)]
3305    fn write_math_expression(
3306        &mut self,
3307        module: &Module,
3308        fun: crate::MathFunction,
3309        arg: Handle<crate::Expression>,
3310        arg1: Option<Handle<crate::Expression>>,
3311        arg2: Option<Handle<crate::Expression>>,
3312        arg3: Option<Handle<crate::Expression>>,
3313        func_ctx: &back::FunctionCtx<'_>,
3314    ) -> BackendResult {
3315        use crate::MathFunction as Mf;
3316
3317        enum Function {
3318            Asincosh { is_sin: bool },
3319            Atanh,
3320            Pack2x16float,
3321            Pack2x16snorm,
3322            Pack2x16unorm,
3323            Pack4x8snorm,
3324            Pack4x8unorm,
3325            Pack4xI8,
3326            Pack4xU8,
3327            Pack4xI8Clamp,
3328            Pack4xU8Clamp,
3329            Unpack2x16float,
3330            Unpack2x16snorm,
3331            Unpack2x16unorm,
3332            Unpack4x8snorm,
3333            Unpack4x8unorm,
3334            Unpack4xI8,
3335            Unpack4xU8,
3336            Dot4I8Packed,
3337            Dot4U8Packed,
3338            QuantizeToF16,
3339            Sign,
3340            Regular(&'static str),
3341            MissingIntOverload(&'static str),
3342            MissingIntReturnType(&'static str),
3343            CountTrailingZeros,
3344            CountLeadingZeros,
3345        }
3346
3347        let fun = match fun {
3348            // comparison
3349            Mf::Abs => match func_ctx.resolve_type(arg, &module.types).scalar() {
3350                Some(Scalar::I32) => Function::Regular(ABS_FUNCTION),
3351                _ => Function::Regular("abs"),
3352            },
3353            Mf::Min => Function::Regular("min"),
3354            Mf::Max => Function::Regular("max"),
3355            Mf::Clamp => Function::Regular("clamp"),
3356            Mf::Saturate => Function::Regular("saturate"),
3357            // trigonometry
3358            Mf::Cos => Function::Regular("cos"),
3359            Mf::Cosh => Function::Regular("cosh"),
3360            Mf::Sin => Function::Regular("sin"),
3361            Mf::Sinh => Function::Regular("sinh"),
3362            Mf::Tan => Function::Regular("tan"),
3363            Mf::Tanh => Function::Regular("tanh"),
3364            Mf::Acos => Function::Regular("acos"),
3365            Mf::Asin => Function::Regular("asin"),
3366            Mf::Atan => Function::Regular("atan"),
3367            Mf::Atan2 => Function::Regular("atan2"),
3368            Mf::Asinh => Function::Asincosh { is_sin: true },
3369            Mf::Acosh => Function::Asincosh { is_sin: false },
3370            Mf::Atanh => Function::Atanh,
3371            Mf::Radians => Function::Regular("radians"),
3372            Mf::Degrees => Function::Regular("degrees"),
3373            // decomposition
3374            Mf::Ceil => Function::Regular("ceil"),
3375            Mf::Floor => Function::Regular("floor"),
3376            Mf::Round => Function::Regular("round"),
3377            Mf::Fract => Function::Regular("frac"),
3378            Mf::Trunc => Function::Regular("trunc"),
3379            Mf::Modf => Function::Regular(MODF_FUNCTION),
3380            Mf::Frexp => Function::Regular(FREXP_FUNCTION),
3381            Mf::Ldexp => Function::Regular("ldexp"),
3382            // exponent
3383            Mf::Exp => Function::Regular("exp"),
3384            Mf::Exp2 => Function::Regular("exp2"),
3385            Mf::Log => Function::Regular("log"),
3386            Mf::Log2 => Function::Regular("log2"),
3387            Mf::Pow => Function::Regular("pow"),
3388            // geometry
3389            Mf::Dot => Function::Regular("dot"),
3390            Mf::Dot4I8Packed => Function::Dot4I8Packed,
3391            Mf::Dot4U8Packed => Function::Dot4U8Packed,
3392            //Mf::Outer => ,
3393            Mf::Cross => Function::Regular("cross"),
3394            Mf::Distance => Function::Regular("distance"),
3395            Mf::Length => Function::Regular("length"),
3396            Mf::Normalize => Function::Regular("normalize"),
3397            Mf::FaceForward => Function::Regular("faceforward"),
3398            Mf::Reflect => Function::Regular("reflect"),
3399            Mf::Refract => Function::Regular("refract"),
3400            // computational
3401            Mf::Sign => Function::Sign,
3402            Mf::Fma => Function::Regular("mad"),
3403            Mf::Mix => Function::Regular("lerp"),
3404            Mf::Step => Function::Regular("step"),
3405            Mf::SmoothStep => Function::Regular("smoothstep"),
3406            Mf::Sqrt => Function::Regular("sqrt"),
3407            Mf::InverseSqrt => Function::Regular("rsqrt"),
3408            //Mf::Inverse =>,
3409            Mf::Transpose => Function::Regular("transpose"),
3410            Mf::Determinant => Function::Regular("determinant"),
3411            Mf::QuantizeToF16 => Function::QuantizeToF16,
3412            // bits
3413            Mf::CountTrailingZeros => Function::CountTrailingZeros,
3414            Mf::CountLeadingZeros => Function::CountLeadingZeros,
3415            Mf::CountOneBits => Function::MissingIntOverload("countbits"),
3416            Mf::ReverseBits => Function::MissingIntOverload("reversebits"),
3417            Mf::FirstTrailingBit => Function::MissingIntReturnType("firstbitlow"),
3418            Mf::FirstLeadingBit => Function::MissingIntReturnType("firstbithigh"),
3419            Mf::ExtractBits => Function::Regular(EXTRACT_BITS_FUNCTION),
3420            Mf::InsertBits => Function::Regular(INSERT_BITS_FUNCTION),
3421            // Data Packing
3422            Mf::Pack2x16float => Function::Pack2x16float,
3423            Mf::Pack2x16snorm => Function::Pack2x16snorm,
3424            Mf::Pack2x16unorm => Function::Pack2x16unorm,
3425            Mf::Pack4x8snorm => Function::Pack4x8snorm,
3426            Mf::Pack4x8unorm => Function::Pack4x8unorm,
3427            Mf::Pack4xI8 => Function::Pack4xI8,
3428            Mf::Pack4xU8 => Function::Pack4xU8,
3429            Mf::Pack4xI8Clamp => Function::Pack4xI8Clamp,
3430            Mf::Pack4xU8Clamp => Function::Pack4xU8Clamp,
3431            // Data Unpacking
3432            Mf::Unpack2x16float => Function::Unpack2x16float,
3433            Mf::Unpack2x16snorm => Function::Unpack2x16snorm,
3434            Mf::Unpack2x16unorm => Function::Unpack2x16unorm,
3435            Mf::Unpack4x8snorm => Function::Unpack4x8snorm,
3436            Mf::Unpack4x8unorm => Function::Unpack4x8unorm,
3437            Mf::Unpack4xI8 => Function::Unpack4xI8,
3438            Mf::Unpack4xU8 => Function::Unpack4xU8,
3439            _ => return Err(Error::Unimplemented(format!("write_expr_math {fun:?}"))),
3440        };
3441
3442        match fun {
3443            Function::Asincosh { is_sin } => {
3444                write!(self.out, "log(")?;
3445                self.write_expr(module, arg, func_ctx)?;
3446                write!(self.out, " + sqrt(")?;
3447                self.write_expr(module, arg, func_ctx)?;
3448                write!(self.out, " * ")?;
3449                self.write_expr(module, arg, func_ctx)?;
3450                match is_sin {
3451                    true => write!(self.out, " + 1.0))")?,
3452                    false => write!(self.out, " - 1.0))")?,
3453                }
3454            }
3455            Function::Atanh => {
3456                write!(self.out, "0.5 * log((1.0 + ")?;
3457                self.write_expr(module, arg, func_ctx)?;
3458                write!(self.out, ") / (1.0 - ")?;
3459                self.write_expr(module, arg, func_ctx)?;
3460                write!(self.out, "))")?;
3461            }
3462            Function::Pack2x16float => {
3463                write!(self.out, "(f32tof16(")?;
3464                self.write_expr(module, arg, func_ctx)?;
3465                write!(self.out, "[0]) | f32tof16(")?;
3466                self.write_expr(module, arg, func_ctx)?;
3467                write!(self.out, "[1]) << 16)")?;
3468            }
3469            Function::Pack2x16snorm => {
3470                let scale = 32767;
3471
3472                write!(self.out, "uint((int(round(clamp(")?;
3473                self.write_expr(module, arg, func_ctx)?;
3474                write!(
3475                    self.out,
3476                    "[0], -1.0, 1.0) * {scale}.0)) & 0xFFFF) | ((int(round(clamp("
3477                )?;
3478                self.write_expr(module, arg, func_ctx)?;
3479                write!(self.out, "[1], -1.0, 1.0) * {scale}.0)) & 0xFFFF) << 16))",)?;
3480            }
3481            Function::Pack2x16unorm => {
3482                let scale = 65535;
3483
3484                write!(self.out, "(uint(round(clamp(")?;
3485                self.write_expr(module, arg, func_ctx)?;
3486                write!(self.out, "[0], 0.0, 1.0) * {scale}.0)) | uint(round(clamp(")?;
3487                self.write_expr(module, arg, func_ctx)?;
3488                write!(self.out, "[1], 0.0, 1.0) * {scale}.0)) << 16)")?;
3489            }
3490            Function::Pack4x8snorm => {
3491                let scale = 127;
3492
3493                write!(self.out, "uint((int(round(clamp(")?;
3494                self.write_expr(module, arg, func_ctx)?;
3495                write!(
3496                    self.out,
3497                    "[0], -1.0, 1.0) * {scale}.0)) & 0xFF) | ((int(round(clamp("
3498                )?;
3499                self.write_expr(module, arg, func_ctx)?;
3500                write!(
3501                    self.out,
3502                    "[1], -1.0, 1.0) * {scale}.0)) & 0xFF) << 8) | ((int(round(clamp("
3503                )?;
3504                self.write_expr(module, arg, func_ctx)?;
3505                write!(
3506                    self.out,
3507                    "[2], -1.0, 1.0) * {scale}.0)) & 0xFF) << 16) | ((int(round(clamp("
3508                )?;
3509                self.write_expr(module, arg, func_ctx)?;
3510                write!(self.out, "[3], -1.0, 1.0) * {scale}.0)) & 0xFF) << 24))",)?;
3511            }
3512            Function::Pack4x8unorm => {
3513                let scale = 255;
3514
3515                write!(self.out, "(uint(round(clamp(")?;
3516                self.write_expr(module, arg, func_ctx)?;
3517                write!(self.out, "[0], 0.0, 1.0) * {scale}.0)) | uint(round(clamp(")?;
3518                self.write_expr(module, arg, func_ctx)?;
3519                write!(
3520                    self.out,
3521                    "[1], 0.0, 1.0) * {scale}.0)) << 8 | uint(round(clamp("
3522                )?;
3523                self.write_expr(module, arg, func_ctx)?;
3524                write!(
3525                    self.out,
3526                    "[2], 0.0, 1.0) * {scale}.0)) << 16 | uint(round(clamp("
3527                )?;
3528                self.write_expr(module, arg, func_ctx)?;
3529                write!(self.out, "[3], 0.0, 1.0) * {scale}.0)) << 24)")?;
3530            }
3531            fun @ (Function::Pack4xI8
3532            | Function::Pack4xU8
3533            | Function::Pack4xI8Clamp
3534            | Function::Pack4xU8Clamp) => {
3535                let was_signed = matches!(fun, Function::Pack4xI8 | Function::Pack4xI8Clamp);
3536                let clamp_bounds = match fun {
3537                    Function::Pack4xI8Clamp => Some(("-128", "127")),
3538                    Function::Pack4xU8Clamp => Some(("0", "255")),
3539                    _ => None,
3540                };
3541                if was_signed {
3542                    write!(self.out, "uint(")?;
3543                }
3544                let write_arg = |this: &mut Self| -> BackendResult {
3545                    if let Some((min, max)) = clamp_bounds {
3546                        write!(this.out, "clamp(")?;
3547                        this.write_expr(module, arg, func_ctx)?;
3548                        write!(this.out, ", {min}, {max})")?;
3549                    } else {
3550                        this.write_expr(module, arg, func_ctx)?;
3551                    }
3552                    Ok(())
3553                };
3554                write!(self.out, "(")?;
3555                write_arg(self)?;
3556                write!(self.out, "[0] & 0xFF) | ((")?;
3557                write_arg(self)?;
3558                write!(self.out, "[1] & 0xFF) << 8) | ((")?;
3559                write_arg(self)?;
3560                write!(self.out, "[2] & 0xFF) << 16) | ((")?;
3561                write_arg(self)?;
3562                write!(self.out, "[3] & 0xFF) << 24)")?;
3563                if was_signed {
3564                    write!(self.out, ")")?;
3565                }
3566            }
3567
3568            Function::Unpack2x16float => {
3569                write!(self.out, "float2(f16tof32(")?;
3570                self.write_expr(module, arg, func_ctx)?;
3571                write!(self.out, "), f16tof32((")?;
3572                self.write_expr(module, arg, func_ctx)?;
3573                write!(self.out, ") >> 16))")?;
3574            }
3575            Function::Unpack2x16snorm => {
3576                let scale = 32767;
3577
3578                write!(self.out, "(float2(int2(")?;
3579                self.write_expr(module, arg, func_ctx)?;
3580                write!(self.out, " << 16, ")?;
3581                self.write_expr(module, arg, func_ctx)?;
3582                write!(self.out, ") >> 16) / {scale}.0)")?;
3583            }
3584            Function::Unpack2x16unorm => {
3585                let scale = 65535;
3586
3587                write!(self.out, "(float2(")?;
3588                self.write_expr(module, arg, func_ctx)?;
3589                write!(self.out, " & 0xFFFF, ")?;
3590                self.write_expr(module, arg, func_ctx)?;
3591                write!(self.out, " >> 16) / {scale}.0)")?;
3592            }
3593            Function::Unpack4x8snorm => {
3594                let scale = 127;
3595
3596                write!(self.out, "(float4(int4(")?;
3597                self.write_expr(module, arg, func_ctx)?;
3598                write!(self.out, " << 24, ")?;
3599                self.write_expr(module, arg, func_ctx)?;
3600                write!(self.out, " << 16, ")?;
3601                self.write_expr(module, arg, func_ctx)?;
3602                write!(self.out, " << 8, ")?;
3603                self.write_expr(module, arg, func_ctx)?;
3604                write!(self.out, ") >> 24) / {scale}.0)")?;
3605            }
3606            Function::Unpack4x8unorm => {
3607                let scale = 255;
3608
3609                write!(self.out, "(float4(")?;
3610                self.write_expr(module, arg, func_ctx)?;
3611                write!(self.out, " & 0xFF, ")?;
3612                self.write_expr(module, arg, func_ctx)?;
3613                write!(self.out, " >> 8 & 0xFF, ")?;
3614                self.write_expr(module, arg, func_ctx)?;
3615                write!(self.out, " >> 16 & 0xFF, ")?;
3616                self.write_expr(module, arg, func_ctx)?;
3617                write!(self.out, " >> 24) / {scale}.0)")?;
3618            }
3619            fun @ (Function::Unpack4xI8 | Function::Unpack4xU8) => {
3620                write!(self.out, "(")?;
3621                if matches!(fun, Function::Unpack4xU8) {
3622                    write!(self.out, "u")?;
3623                }
3624                write!(self.out, "int4(")?;
3625                self.write_expr(module, arg, func_ctx)?;
3626                write!(self.out, ", ")?;
3627                self.write_expr(module, arg, func_ctx)?;
3628                write!(self.out, " >> 8, ")?;
3629                self.write_expr(module, arg, func_ctx)?;
3630                write!(self.out, " >> 16, ")?;
3631                self.write_expr(module, arg, func_ctx)?;
3632                write!(self.out, " >> 24) << 24 >> 24)")?;
3633            }
3634            fun @ (Function::Dot4I8Packed | Function::Dot4U8Packed) => {
3635                let arg1 = arg1.unwrap();
3636
3637                if self.options.shader_model >= ShaderModel::V6_4 {
3638                    // Intrinsics `dot4add_{i, u}8packed` are available in SM 6.4 and later.
3639                    let function_name = match fun {
3640                        Function::Dot4I8Packed => "dot4add_i8packed",
3641                        Function::Dot4U8Packed => "dot4add_u8packed",
3642                        _ => unreachable!(),
3643                    };
3644                    write!(self.out, "{function_name}(")?;
3645                    self.write_expr(module, arg, func_ctx)?;
3646                    write!(self.out, ", ")?;
3647                    self.write_expr(module, arg1, func_ctx)?;
3648                    write!(self.out, ", 0)")?;
3649                } else {
3650                    // Fall back to a polyfill as `dot4add_u8packed` is not available.
3651                    write!(self.out, "dot(")?;
3652
3653                    if matches!(fun, Function::Dot4U8Packed) {
3654                        write!(self.out, "u")?;
3655                    }
3656                    write!(self.out, "int4(")?;
3657                    self.write_expr(module, arg, func_ctx)?;
3658                    write!(self.out, ", ")?;
3659                    self.write_expr(module, arg, func_ctx)?;
3660                    write!(self.out, " >> 8, ")?;
3661                    self.write_expr(module, arg, func_ctx)?;
3662                    write!(self.out, " >> 16, ")?;
3663                    self.write_expr(module, arg, func_ctx)?;
3664                    write!(self.out, " >> 24) << 24 >> 24, ")?;
3665
3666                    if matches!(fun, Function::Dot4U8Packed) {
3667                        write!(self.out, "u")?;
3668                    }
3669                    write!(self.out, "int4(")?;
3670                    self.write_expr(module, arg1, func_ctx)?;
3671                    write!(self.out, ", ")?;
3672                    self.write_expr(module, arg1, func_ctx)?;
3673                    write!(self.out, " >> 8, ")?;
3674                    self.write_expr(module, arg1, func_ctx)?;
3675                    write!(self.out, " >> 16, ")?;
3676                    self.write_expr(module, arg1, func_ctx)?;
3677                    write!(self.out, " >> 24) << 24 >> 24)")?;
3678                }
3679            }
3680            Function::QuantizeToF16 => {
3681                write!(self.out, "f16tof32(f32tof16(")?;
3682                self.write_expr(module, arg, func_ctx)?;
3683                write!(self.out, "))")?;
3684            }
3685            // HLSL's `sign` always returns a signed integer, even for floating-point
3686            // arguments, so cast the result back to the WGSL result type.
3687            Function::Sign => {
3688                let inner = func_ctx.resolve_type(arg, &module.types);
3689                let is_float = inner.scalar_kind() == Some(ScalarKind::Float);
3690                if is_float {
3691                    self.write_value_type(module, inner)?;
3692                    write!(self.out, "(")?;
3693                }
3694                write!(self.out, "sign(")?;
3695                self.write_expr(module, arg, func_ctx)?;
3696                write!(self.out, ")")?;
3697                if is_float {
3698                    write!(self.out, ")")?;
3699                }
3700            }
3701            Function::Regular(fun_name) => {
3702                write!(self.out, "{fun_name}(")?;
3703                self.write_expr(module, arg, func_ctx)?;
3704                if let Some(arg) = arg1 {
3705                    write!(self.out, ", ")?;
3706                    self.write_expr(module, arg, func_ctx)?;
3707                }
3708                if let Some(arg) = arg2 {
3709                    write!(self.out, ", ")?;
3710                    self.write_expr(module, arg, func_ctx)?;
3711                }
3712                if let Some(arg) = arg3 {
3713                    write!(self.out, ", ")?;
3714                    self.write_expr(module, arg, func_ctx)?;
3715                }
3716                write!(self.out, ")")?
3717            }
3718            // These overloads are only missing on FXC, so this is only needed for 32bit types,
3719            // as non-32bit types are DXC only.
3720            Function::MissingIntOverload(fun_name) => {
3721                let scalar_kind = func_ctx.resolve_type(arg, &module.types).scalar();
3722                if let Some(Scalar::I32) = scalar_kind {
3723                    write!(self.out, "asint({fun_name}(asuint(")?;
3724                    self.write_expr(module, arg, func_ctx)?;
3725                    write!(self.out, ")))")?;
3726                } else {
3727                    write!(self.out, "{fun_name}(")?;
3728                    self.write_expr(module, arg, func_ctx)?;
3729                    write!(self.out, ")")?;
3730                }
3731            }
3732            // These overloads are only missing on FXC, so this is only needed for 32bit types,
3733            // as non-32bit types are DXC only.
3734            Function::MissingIntReturnType(fun_name) => {
3735                let scalar_kind = func_ctx.resolve_type(arg, &module.types).scalar();
3736                if let Some(Scalar::I32) = scalar_kind {
3737                    write!(self.out, "asint({fun_name}(")?;
3738                    self.write_expr(module, arg, func_ctx)?;
3739                    write!(self.out, "))")?;
3740                } else {
3741                    write!(self.out, "{fun_name}(")?;
3742                    self.write_expr(module, arg, func_ctx)?;
3743                    write!(self.out, ")")?;
3744                }
3745            }
3746            Function::CountTrailingZeros => {
3747                match *func_ctx.resolve_type(arg, &module.types) {
3748                    TypeInner::Vector { size, scalar } => {
3749                        let s = match size {
3750                            crate::VectorSize::Bi => ".xx",
3751                            crate::VectorSize::Tri => ".xxx",
3752                            crate::VectorSize::Quad => ".xxxx",
3753                        };
3754
3755                        let scalar_width_bits = scalar.width * 8;
3756
3757                        if scalar.kind == ScalarKind::Uint || scalar.width != 4 {
3758                            write!(self.out, "min(({scalar_width_bits}u){s}, firstbitlow(")?;
3759                            self.write_expr(module, arg, func_ctx)?;
3760                            write!(self.out, "))")?;
3761                        } else {
3762                            // This is only needed for the FXC path, on 32bit signed integers.
3763                            write!(
3764                                self.out,
3765                                "asint(min(({scalar_width_bits}u){s}, firstbitlow("
3766                            )?;
3767                            self.write_expr(module, arg, func_ctx)?;
3768                            write!(self.out, ")))")?;
3769                        }
3770                    }
3771                    TypeInner::Scalar(scalar) => {
3772                        let scalar_width_bits = scalar.width * 8;
3773
3774                        if scalar.kind == ScalarKind::Uint || scalar.width != 4 {
3775                            write!(self.out, "min({scalar_width_bits}u, firstbitlow(")?;
3776                            self.write_expr(module, arg, func_ctx)?;
3777                            write!(self.out, "))")?;
3778                        } else {
3779                            // This is only needed for the FXC path, on 32bit signed integers.
3780                            write!(self.out, "asint(min({scalar_width_bits}u, firstbitlow(")?;
3781                            self.write_expr(module, arg, func_ctx)?;
3782                            write!(self.out, ")))")?;
3783                        }
3784                    }
3785                    _ => unreachable!(),
3786                }
3787
3788                return Ok(());
3789            }
3790            Function::CountLeadingZeros => {
3791                match *func_ctx.resolve_type(arg, &module.types) {
3792                    TypeInner::Vector { size, scalar } => {
3793                        let s = match size {
3794                            crate::VectorSize::Bi => ".xx",
3795                            crate::VectorSize::Tri => ".xxx",
3796                            crate::VectorSize::Quad => ".xxxx",
3797                        };
3798
3799                        // scalar width - 1
3800                        let constant = scalar.width * 8 - 1;
3801
3802                        if scalar.kind == ScalarKind::Uint {
3803                            write!(self.out, "(({constant}u){s} - firstbithigh(")?;
3804                            self.write_expr(module, arg, func_ctx)?;
3805                            write!(self.out, "))")?;
3806                        } else {
3807                            let conversion_func = match scalar.width {
3808                                4 => "asint",
3809                                _ => "",
3810                            };
3811                            write!(self.out, "(")?;
3812                            self.write_expr(module, arg, func_ctx)?;
3813                            write!(
3814                                self.out,
3815                                " < (0){s} ? (0){s} : ({constant}){s} - {conversion_func}(firstbithigh("
3816                            )?;
3817                            self.write_expr(module, arg, func_ctx)?;
3818                            write!(self.out, ")))")?;
3819                        }
3820                    }
3821                    TypeInner::Scalar(scalar) => {
3822                        // scalar width - 1
3823                        let constant = scalar.width * 8 - 1;
3824
3825                        if let ScalarKind::Uint = scalar.kind {
3826                            write!(self.out, "({constant}u - firstbithigh(")?;
3827                            self.write_expr(module, arg, func_ctx)?;
3828                            write!(self.out, "))")?;
3829                        } else {
3830                            let conversion_func = match scalar.width {
3831                                4 => "asint",
3832                                _ => "",
3833                            };
3834                            write!(self.out, "(")?;
3835                            self.write_expr(module, arg, func_ctx)?;
3836                            write!(
3837                                self.out,
3838                                " < 0 ? 0 : {constant} - {conversion_func}(firstbithigh("
3839                            )?;
3840                            self.write_expr(module, arg, func_ctx)?;
3841                            write!(self.out, ")))")?;
3842                        }
3843                    }
3844                    _ => unreachable!(),
3845                }
3846            }
3847        }
3848
3849        Ok(())
3850    }
3851
3852    fn write_const_expression(
3853        &mut self,
3854        module: &Module,
3855        expr: Handle<crate::Expression>,
3856        arena: &crate::Arena<crate::Expression>,
3857    ) -> BackendResult {
3858        self.write_possibly_const_expression(module, expr, arena, |writer, expr| {
3859            writer.write_const_expression(module, expr, arena)
3860        })
3861    }
3862
3863    pub(super) fn write_literal(&mut self, literal: crate::Literal) -> BackendResult {
3864        match literal {
3865            crate::Literal::F64(value) => write!(self.out, "{value:?}L")?,
3866            crate::Literal::F32(value) => write!(self.out, "{value:?}")?,
3867            crate::Literal::F16(value) => write!(self.out, "{value:?}h")?,
3868            crate::Literal::U16(value) => write!(self.out, "uint16_t({value})")?,
3869            crate::Literal::I16(value) => write!(self.out, "int16_t({value})")?,
3870            crate::Literal::U32(value) => write!(self.out, "{value}u")?,
3871            // `-2147483648` is parsed by some compilers as unary negation of
3872            // positive 2147483648, which is too large for an int, causing
3873            // issues for some compilers. Neither DXC nor FXC appear to have
3874            // this problem, but this is not specified and could change. We
3875            // therefore use `-2147483647 - 1` as a precaution.
3876            crate::Literal::I32(value) if value == i32::MIN => {
3877                write!(self.out, "int({} - 1)", value + 1)?
3878            }
3879            // HLSL has no suffix for explicit i32 literals, but not using any suffix
3880            // makes the type ambiguous which prevents overload resolution from
3881            // working. So we explicitly use the int() constructor syntax.
3882            crate::Literal::I32(value) => write!(self.out, "int({value})")?,
3883            crate::Literal::U64(value) => write!(self.out, "{value}uL")?,
3884            // I64 version of the minimum I32 value issue described above.
3885            crate::Literal::I64(value) if value == i64::MIN => {
3886                write!(self.out, "({}L - 1L)", value + 1)?;
3887            }
3888            crate::Literal::I64(value) => write!(self.out, "{value}L")?,
3889            crate::Literal::Bool(value) => write!(self.out, "{value}")?,
3890            crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => {
3891                return Err(Error::Custom(
3892                    "Abstract types should not appear in IR presented to backends".into(),
3893                ));
3894            }
3895        }
3896        Ok(())
3897    }
3898
3899    fn write_possibly_const_expression<E>(
3900        &mut self,
3901        module: &Module,
3902        expr: Handle<crate::Expression>,
3903        expressions: &crate::Arena<crate::Expression>,
3904        write_expression: E,
3905    ) -> BackendResult
3906    where
3907        E: Fn(&mut Self, Handle<crate::Expression>) -> BackendResult,
3908    {
3909        use crate::Expression;
3910
3911        match expressions[expr] {
3912            Expression::Literal(literal) => {
3913                self.write_literal(literal)?;
3914            }
3915            Expression::Constant(handle) => {
3916                let constant = &module.constants[handle];
3917                if constant.name.is_some() {
3918                    write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?;
3919                } else {
3920                    self.write_const_expression(module, constant.init, &module.global_expressions)?;
3921                }
3922            }
3923            Expression::ZeroValue(ty) => {
3924                self.write_wrapped_zero_value_function_name(module, WrappedZeroValue { ty })?;
3925                write!(self.out, "()")?;
3926            }
3927            Expression::Compose { ty, ref components } => {
3928                match module.types[ty].inner {
3929                    TypeInner::Struct { .. } | TypeInner::Array { .. } => {
3930                        self.write_wrapped_constructor_function_name(
3931                            module,
3932                            WrappedConstructor { ty },
3933                        )?;
3934                    }
3935                    _ => {
3936                        self.write_type(module, ty)?;
3937                    }
3938                };
3939                write!(self.out, "(")?;
3940                for (index, component) in components.iter().enumerate() {
3941                    if index != 0 {
3942                        write!(self.out, ", ")?;
3943                    }
3944                    write_expression(self, *component)?;
3945                }
3946                write!(self.out, ")")?;
3947            }
3948            Expression::Splat { size, value } => {
3949                // hlsl is not supported one value constructor
3950                // if we write, for example, int4(0), dxc returns error:
3951                // error: too few elements in vector initialization (expected 4 elements, have 1)
3952                let number_of_components = match size {
3953                    crate::VectorSize::Bi => "xx",
3954                    crate::VectorSize::Tri => "xxx",
3955                    crate::VectorSize::Quad => "xxxx",
3956                };
3957                write!(self.out, "(")?;
3958                write_expression(self, value)?;
3959                write!(self.out, ").{number_of_components}")?
3960            }
3961            _ => {
3962                return Err(Error::Override);
3963            }
3964        }
3965
3966        Ok(())
3967    }
3968
3969    /// Write a polyfill for [`Statement::SubgroupBallotFindBit`], since HLSL has no
3970    /// built-in for it: a chain of ternaries over the already-evaluated ballot
3971    /// `words` (`words[0..4]` is `x, y, z, w`). `priority` counts up from 0 (the
3972    /// lowest-priority word, used as the fallback base case) to 3 (the
3973    /// highest-priority word, checked first: `x` for LSB, `w` for MSB), each
3974    /// overriding the lower-priority result when that word has any bit set.
3975    ///
3976    /// [`Statement::SubgroupBallotFindBit`]: crate::Statement::SubgroupBallotFindBit
3977    fn write_ballot_find_bit(
3978        &mut self,
3979        words: &[String; 4],
3980        order: crate::BallotFindBitOrder,
3981        priority: u32,
3982    ) -> BackendResult {
3983        let (word_index, base) = match (order, priority) {
3984            (crate::BallotFindBitOrder::Lsb, 0) => (3, 96),
3985            (crate::BallotFindBitOrder::Lsb, 1) => (2, 64),
3986            (crate::BallotFindBitOrder::Lsb, 2) => (1, 32),
3987            (crate::BallotFindBitOrder::Lsb, 3) => (0, 0),
3988            (crate::BallotFindBitOrder::Msb, 0) => (0, 0),
3989            (crate::BallotFindBitOrder::Msb, 1) => (1, 32),
3990            (crate::BallotFindBitOrder::Msb, 2) => (2, 64),
3991            (crate::BallotFindBitOrder::Msb, 3) => (3, 96),
3992            (_, _) => unreachable!(),
3993        };
3994        let word = &words[word_index];
3995
3996        if priority == 0 {
3997            self.write_ballot_find_bit_value(order, word, base)?;
3998        } else {
3999            write!(self.out, "({word} != 0u ? ")?;
4000            self.write_ballot_find_bit_value(order, word, base)?;
4001            write!(self.out, " : ")?;
4002            self.write_ballot_find_bit(words, order, priority - 1)?;
4003            write!(self.out, ")")?;
4004        }
4005        Ok(())
4006    }
4007
4008    /// Write `firstbitlow`/`firstbithigh` applied to an already-evaluated ballot
4009    /// word, offset by that word's base invocation index. Used by
4010    /// [`Self::write_ballot_find_bit`].
4011    fn write_ballot_find_bit_value(
4012        &mut self,
4013        order: crate::BallotFindBitOrder,
4014        word: &str,
4015        base: u32,
4016    ) -> BackendResult {
4017        let math_fn = match order {
4018            crate::BallotFindBitOrder::Lsb => "firstbitlow",
4019            crate::BallotFindBitOrder::Msb => "firstbithigh",
4020        };
4021        write!(self.out, "{math_fn}({word})")?;
4022        if base != 0 {
4023            write!(self.out, " + {base}u")?;
4024        }
4025        Ok(())
4026    }
4027
4028    /// Helper method to write expressions
4029    ///
4030    /// # Notes
4031    /// Doesn't add any newlines or leading/trailing spaces
4032    pub(super) fn write_expr(
4033        &mut self,
4034        module: &Module,
4035        expr: Handle<crate::Expression>,
4036        func_ctx: &back::FunctionCtx<'_>,
4037    ) -> BackendResult {
4038        use crate::Expression;
4039
4040        // Handle the special semantics of vertex_index/instance_index
4041        let ff_input = if self.options.special_constants_binding.is_some() {
4042            func_ctx.is_fixed_function_input(expr, module)
4043        } else {
4044            None
4045        };
4046        let closing_bracket = match ff_input {
4047            Some(crate::BuiltIn::VertexIndex) => {
4048                write!(self.out, "({SPECIAL_CBUF_VAR}.{SPECIAL_FIRST_VERTEX} + ")?;
4049                ")"
4050            }
4051            Some(crate::BuiltIn::InstanceIndex) => {
4052                write!(self.out, "({SPECIAL_CBUF_VAR}.{SPECIAL_FIRST_INSTANCE} + ",)?;
4053                ")"
4054            }
4055            Some(crate::BuiltIn::NumWorkGroups) => {
4056                // Note: despite their names (`FIRST_VERTEX` and `FIRST_INSTANCE`),
4057                // in compute shaders the special constants contain the number
4058                // of workgroups, which we are using here.
4059                write!(
4060                    self.out,
4061                    "uint3({SPECIAL_CBUF_VAR}.{SPECIAL_FIRST_VERTEX}, {SPECIAL_CBUF_VAR}.{SPECIAL_FIRST_INSTANCE}, {SPECIAL_CBUF_VAR}.{SPECIAL_OTHER})",
4062                )?;
4063                return Ok(());
4064            }
4065            _ => "",
4066        };
4067
4068        if let Some(name) = self.named_expressions.get(&expr) {
4069            write!(self.out, "{name}{closing_bracket}")?;
4070            return Ok(());
4071        }
4072
4073        let expression = &func_ctx.expressions[expr];
4074
4075        match *expression {
4076            Expression::Literal(_)
4077            | Expression::Constant(_)
4078            | Expression::ZeroValue(_)
4079            | Expression::Compose { .. }
4080            | Expression::Splat { .. } => {
4081                self.write_possibly_const_expression(
4082                    module,
4083                    expr,
4084                    func_ctx.expressions,
4085                    |writer, expr| writer.write_expr(module, expr, func_ctx),
4086                )?;
4087            }
4088            Expression::Override(_) => return Err(Error::Override),
4089            // Avoid undefined behaviour for addition, subtraction, and
4090            // multiplication of signed integers by casting operands to
4091            // unsigned, performing the operation, then casting the result back
4092            // to signed.
4093            // TODO(#7109): This relies on the asint()/asuint() functions which only work
4094            // for 32-bit types, so we must find another solution for different bit widths.
4095            Expression::Binary {
4096                op:
4097                    op @ crate::BinaryOperator::Add
4098                    | op @ crate::BinaryOperator::Subtract
4099                    | op @ crate::BinaryOperator::Multiply,
4100                left,
4101                right,
4102            } if matches!(
4103                func_ctx.resolve_type(expr, &module.types).scalar(),
4104                Some(Scalar::I32)
4105            ) =>
4106            {
4107                write!(self.out, "asint(asuint(",)?;
4108                self.write_expr(module, left, func_ctx)?;
4109                write!(self.out, ") {} asuint(", back::binary_operation_str(op))?;
4110                self.write_expr(module, right, func_ctx)?;
4111                write!(self.out, "))")?;
4112            }
4113            // All of the multiplication can be expressed as `mul`,
4114            // except vector * vector, which needs to use the "*" operator.
4115            Expression::Binary {
4116                op: crate::BinaryOperator::Multiply,
4117                left,
4118                right,
4119            } if func_ctx.resolve_type(left, &module.types).is_matrix()
4120                || func_ctx.resolve_type(right, &module.types).is_matrix() =>
4121            {
4122                // We intentionally flip the order of multiplication as our matrices are implicitly transposed.
4123                write!(self.out, "mul(")?;
4124                self.write_expr(module, right, func_ctx)?;
4125                write!(self.out, ", ")?;
4126                self.write_expr(module, left, func_ctx)?;
4127                write!(self.out, ")")?;
4128            }
4129
4130            // WGSL says that floating-point division by zero should return
4131            // infinity. Microsoft's Direct3D 11 functional specification
4132            // (https://microsoft.github.io/DirectX-Specs/d3d/archive/D3D11_3_FunctionalSpec.htm)
4133            // says:
4134            //
4135            //     Divide by 0 produces +/- INF, except 0/0 which results in NaN.
4136            //
4137            // which is what we want. The DXIL specification for the FDiv
4138            // instruction corroborates this:
4139            //
4140            // https://github.com/microsoft/DirectXShaderCompiler/blob/main/docs/DXIL.rst#fdiv
4141            Expression::Binary {
4142                op: crate::BinaryOperator::Divide,
4143                left,
4144                right,
4145            } if matches!(
4146                func_ctx.resolve_type(expr, &module.types).scalar_kind(),
4147                Some(ScalarKind::Sint | ScalarKind::Uint)
4148            ) =>
4149            {
4150                write!(self.out, "{DIV_FUNCTION}(")?;
4151                self.write_expr(module, left, func_ctx)?;
4152                write!(self.out, ", ")?;
4153                self.write_expr(module, right, func_ctx)?;
4154                write!(self.out, ")")?;
4155            }
4156
4157            Expression::Binary {
4158                op: crate::BinaryOperator::Modulo,
4159                left,
4160                right,
4161            } if matches!(
4162                func_ctx.resolve_type(expr, &module.types).scalar_kind(),
4163                Some(ScalarKind::Sint | ScalarKind::Uint | ScalarKind::Float)
4164            ) =>
4165            {
4166                write!(self.out, "{MOD_FUNCTION}(")?;
4167                self.write_expr(module, left, func_ctx)?;
4168                write!(self.out, ", ")?;
4169                self.write_expr(module, right, func_ctx)?;
4170                write!(self.out, ")")?;
4171            }
4172
4173            Expression::Binary { op, left, right } => {
4174                write!(self.out, "(")?;
4175                self.write_expr(module, left, func_ctx)?;
4176                write!(self.out, " {} ", back::binary_operation_str(op))?;
4177                self.write_expr(module, right, func_ctx)?;
4178                write!(self.out, ")")?;
4179            }
4180            Expression::Access { base, index } => {
4181                if let Some(crate::AddressSpace::Storage { .. }) =
4182                    func_ctx.resolve_type(expr, &module.types).pointer_space()
4183                {
4184                    // do nothing, the chain is written on `Load`/`Store`
4185                } else {
4186                    // We use the function __get_col_of_matCx2 here in cases
4187                    // where `base`s type resolves to a matCx2 and is part of a
4188                    // struct member with type of (possibly nested) array of matCx2's.
4189                    //
4190                    // Note that this only works for `Load`s and we handle
4191                    // `Store`s differently in `Statement::Store`.
4192                    if let Some(MatrixType {
4193                        columns,
4194                        rows: crate::VectorSize::Bi,
4195                        width,
4196                    }) = get_inner_matrix_of_struct_array_member(module, base, func_ctx, true)
4197                        .or_else(|| {
4198                            get_inner_matrix_of_global_uniform(module, base, func_ctx, true)
4199                        })
4200                    {
4201                        write!(
4202                            self.out,
4203                            "__get_col_of_mat{}x2_f{}(",
4204                            columns as u8,
4205                            width * 8
4206                        )?;
4207                        self.write_expr(module, base, func_ctx)?;
4208                        write!(self.out, ", ")?;
4209                        self.write_expr(module, index, func_ctx)?;
4210                        write!(self.out, ")")?;
4211                        return Ok(());
4212                    }
4213
4214                    let resolved = func_ctx.resolve_type(base, &module.types);
4215
4216                    let (indexing_binding_array, non_uniform_qualifier) = match *resolved {
4217                        TypeInner::BindingArray { .. } => {
4218                            let uniformity = &func_ctx.info[index].uniformity;
4219
4220                            (true, uniformity.non_uniform_result.is_some())
4221                        }
4222                        _ => (false, false),
4223                    };
4224
4225                    self.write_expr(module, base, func_ctx)?;
4226
4227                    let array_sampler_info = self.sampler_binding_array_info_from_expression(
4228                        module, func_ctx, base, resolved,
4229                    );
4230
4231                    if let Some(ref info) = array_sampler_info {
4232                        write!(self.out, "{}[", info.sampler_heap_name)?;
4233                    } else {
4234                        write!(self.out, "[")?;
4235                    }
4236
4237                    let needs_bound_check = self.options.restrict_indexing
4238                        && !indexing_binding_array
4239                        && match resolved.pointer_space() {
4240                            Some(
4241                                crate::AddressSpace::Function
4242                                | crate::AddressSpace::Private
4243                                | crate::AddressSpace::WorkGroup
4244                                | crate::AddressSpace::Immediate
4245                                | crate::AddressSpace::TaskPayload
4246                                | crate::AddressSpace::RayPayload
4247                                | crate::AddressSpace::IncomingRayPayload,
4248                            )
4249                            | None => true,
4250                            Some(crate::AddressSpace::Uniform) => {
4251                                // check if BindTarget.restrict_indexing is set, this is used for dynamic buffers
4252                                let var_handle = self.fill_access_chain(module, base, func_ctx)?;
4253                                let bind_target = self
4254                                    .options
4255                                    .resolve_resource_binding(
4256                                        module.global_variables[var_handle]
4257                                            .binding
4258                                            .as_ref()
4259                                            .unwrap(),
4260                                    )
4261                                    .unwrap();
4262                                bind_target.restrict_indexing
4263                            }
4264                            Some(
4265                                crate::AddressSpace::Handle | crate::AddressSpace::Storage { .. },
4266                            ) => unreachable!(),
4267                        };
4268                    // Decide whether this index needs to be clamped to fall within range.
4269                    let restriction_needed = if needs_bound_check {
4270                        index::access_needs_check(
4271                            base,
4272                            index::GuardedIndex::Expression(index),
4273                            module,
4274                            func_ctx.expressions,
4275                            func_ctx.info,
4276                        )
4277                    } else {
4278                        None
4279                    };
4280                    if let Some(limit) = restriction_needed {
4281                        write!(self.out, "min(uint(")?;
4282                        self.write_expr(module, index, func_ctx)?;
4283                        write!(self.out, "), ")?;
4284                        match limit {
4285                            index::IndexableLength::Known(limit) => {
4286                                write!(self.out, "{}u", limit - 1)?;
4287                            }
4288                            index::IndexableLength::Dynamic => unreachable!(),
4289                        }
4290                        write!(self.out, ")")?;
4291                    } else {
4292                        if non_uniform_qualifier {
4293                            write!(self.out, "NonUniformResourceIndex(")?;
4294                        }
4295                        if let Some(ref info) = array_sampler_info {
4296                            write!(
4297                                self.out,
4298                                "{}[{} + ",
4299                                info.sampler_index_buffer_name, info.binding_array_base_index_name,
4300                            )?;
4301                        }
4302                        self.write_expr(module, index, func_ctx)?;
4303                        if array_sampler_info.is_some() {
4304                            write!(self.out, "]")?;
4305                        }
4306                        if non_uniform_qualifier {
4307                            write!(self.out, ")")?;
4308                        }
4309                    }
4310
4311                    write!(self.out, "]")?;
4312                }
4313            }
4314            Expression::AccessIndex { base, index } => {
4315                if let Some(crate::AddressSpace::Storage { .. }) =
4316                    func_ctx.resolve_type(expr, &module.types).pointer_space()
4317                {
4318                    // do nothing, the chain is written on `Load`/`Store`
4319                } else {
4320                    // See if we need to write the matrix column access in a
4321                    // special way since the type of `base` is our special
4322                    // __matCx2 struct.
4323                    if let Some(MatrixType {
4324                        rows: crate::VectorSize::Bi,
4325                        ..
4326                    }) = get_inner_matrix_of_struct_array_member(module, base, func_ctx, true)
4327                        .or_else(|| {
4328                            get_inner_matrix_of_global_uniform(module, base, func_ctx, true)
4329                        })
4330                    {
4331                        self.write_expr(module, base, func_ctx)?;
4332                        write!(self.out, "._{index}")?;
4333                        return Ok(());
4334                    }
4335
4336                    let base_ty_res = &func_ctx.info[base].ty;
4337                    let mut resolved = base_ty_res.inner_with(&module.types);
4338                    let base_ty_handle = match *resolved {
4339                        TypeInner::Pointer { base, .. } => {
4340                            resolved = &module.types[base].inner;
4341                            Some(base)
4342                        }
4343                        _ => base_ty_res.handle(),
4344                    };
4345
4346                    // We treat matrices of the form `matCx2` as a sequence of C `vec2`s.
4347                    // See the module-level block comment in mod.rs for details.
4348                    //
4349                    // We handle matrix reconstruction here for Loads.
4350                    // Stores are handled directly by `Statement::Store`.
4351                    if let TypeInner::Struct { ref members, .. } = *resolved {
4352                        let member = &members[index as usize];
4353
4354                        match module.types[member.ty].inner {
4355                            TypeInner::Matrix {
4356                                rows: crate::VectorSize::Bi,
4357                                ..
4358                            } if member.binding.is_none() => {
4359                                let ty = base_ty_handle.unwrap();
4360                                self.write_wrapped_struct_matrix_get_function_name(
4361                                    WrappedStructMatrixAccess { ty, index },
4362                                )?;
4363                                write!(self.out, "(")?;
4364                                self.write_expr(module, base, func_ctx)?;
4365                                write!(self.out, ")")?;
4366                                return Ok(());
4367                            }
4368                            _ => {}
4369                        }
4370                    }
4371
4372                    let array_sampler_info = self.sampler_binding_array_info_from_expression(
4373                        module, func_ctx, base, resolved,
4374                    );
4375
4376                    if let Some(ref info) = array_sampler_info {
4377                        write!(
4378                            self.out,
4379                            "{}[{}",
4380                            info.sampler_heap_name, info.sampler_index_buffer_name
4381                        )?;
4382                    }
4383
4384                    self.write_expr(module, base, func_ctx)?;
4385
4386                    match *resolved {
4387                        // We specifically lift the ValuePointer to this case. While `[0]` is valid
4388                        // HLSL for any vector behind a value pointer, FXC completely miscompiles
4389                        // it and generates completely nonsensical DXBC.
4390                        //
4391                        // See https://github.com/gfx-rs/naga/issues/2095 for more details.
4392                        TypeInner::Vector { .. } | TypeInner::ValuePointer { .. } => {
4393                            // Write vector access as a swizzle
4394                            write!(self.out, ".{}", back::COMPONENTS[index as usize])?
4395                        }
4396                        TypeInner::Matrix { .. }
4397                        | TypeInner::Array { .. }
4398                        | TypeInner::BindingArray { .. } => {
4399                            if let Some(ref info) = array_sampler_info {
4400                                write!(
4401                                    self.out,
4402                                    "[{} + {index}]",
4403                                    info.binding_array_base_index_name
4404                                )?;
4405                            } else {
4406                                write!(self.out, "[{index}]")?;
4407                            }
4408                        }
4409                        TypeInner::Struct { .. } => {
4410                            // This will never panic in case the type is a `Struct`, this is not true
4411                            // for other types so we can only check while inside this match arm
4412                            let ty = base_ty_handle.unwrap();
4413
4414                            write!(
4415                                self.out,
4416                                ".{}",
4417                                self.names[&NameKey::StructMember(ty, index)]
4418                            )?
4419                        }
4420                        ref other => return Err(Error::Custom(format!("Cannot index {other:?}"))),
4421                    }
4422
4423                    if array_sampler_info.is_some() {
4424                        write!(self.out, "]")?;
4425                    }
4426                }
4427            }
4428            Expression::FunctionArgument(pos) => {
4429                let ty = func_ctx.resolve_type(expr, &module.types);
4430
4431                // We know that any external texture function argument has been expanded into
4432                // separate consecutive arguments for each plane and the parameters buffer. And we
4433                // also know that external textures can only ever be used as an argument to another
4434                // function. Therefore we can simply emit each of the expanded arguments in a
4435                // consecutive comma-separated list.
4436                if ty.is_external_image() {
4437                    let plane_names = [0, 1, 2].map(|i| {
4438                        &self.names[&func_ctx
4439                            .external_texture_argument_key(pos, ExternalTextureNameKey::Plane(i))]
4440                    });
4441                    let params_name = &self.names[&func_ctx
4442                        .external_texture_argument_key(pos, ExternalTextureNameKey::Params)];
4443                    write!(
4444                        self.out,
4445                        "{}, {}, {}, {}",
4446                        plane_names[0], plane_names[1], plane_names[2], params_name
4447                    )?;
4448                } else {
4449                    let key = func_ctx.argument_key(pos);
4450                    let name = &self.names[&key];
4451                    write!(self.out, "{name}")?;
4452                }
4453            }
4454            Expression::ImageSample {
4455                coordinate,
4456                image,
4457                sampler,
4458                clamp_to_edge: true,
4459                gather: None,
4460                array_index: None,
4461                offset: None,
4462                level: crate::SampleLevel::Zero,
4463                depth_ref: None,
4464            } => {
4465                write!(self.out, "{IMAGE_SAMPLE_BASE_CLAMP_TO_EDGE_FUNCTION}(")?;
4466                self.write_expr(module, image, func_ctx)?;
4467                write!(self.out, ", ")?;
4468                self.write_expr(module, sampler, func_ctx)?;
4469                write!(self.out, ", ")?;
4470                self.write_expr(module, coordinate, func_ctx)?;
4471                write!(self.out, ")")?;
4472            }
4473            Expression::ImageSample {
4474                image,
4475                sampler,
4476                gather,
4477                coordinate,
4478                array_index,
4479                offset,
4480                level,
4481                depth_ref,
4482                clamp_to_edge,
4483            } => {
4484                if clamp_to_edge {
4485                    return Err(Error::Custom(
4486                        "ImageSample::clamp_to_edge should have been validated out".to_string(),
4487                    ));
4488                }
4489
4490                use crate::SampleLevel as Sl;
4491                const COMPONENTS: [&str; 4] = ["", "Green", "Blue", "Alpha"];
4492
4493                let (base_str, component_str) = match gather {
4494                    Some(component) => ("Gather", COMPONENTS[component as usize]),
4495                    None => ("Sample", ""),
4496                };
4497                let cmp_str = match depth_ref {
4498                    Some(_) => "Cmp",
4499                    None => "",
4500                };
4501                let level_str = match level {
4502                    Sl::Zero if gather.is_none() => "LevelZero",
4503                    Sl::Auto | Sl::Zero => "",
4504                    Sl::Exact(_) => "Level",
4505                    Sl::Bias(_) => "Bias",
4506                    Sl::Gradient { .. } => "Grad",
4507                };
4508
4509                self.write_expr(module, image, func_ctx)?;
4510                write!(self.out, ".{base_str}{cmp_str}{component_str}{level_str}(")?;
4511                self.write_expr(module, sampler, func_ctx)?;
4512                write!(self.out, ", ")?;
4513                self.write_texture_coordinates(
4514                    "float",
4515                    coordinate,
4516                    array_index,
4517                    None,
4518                    module,
4519                    func_ctx,
4520                )?;
4521
4522                if let Some(depth_ref) = depth_ref {
4523                    write!(self.out, ", ")?;
4524                    self.write_expr(module, depth_ref, func_ctx)?;
4525                }
4526
4527                match level {
4528                    Sl::Auto | Sl::Zero => {}
4529                    Sl::Exact(expr) => {
4530                        write!(self.out, ", ")?;
4531                        self.write_expr(module, expr, func_ctx)?;
4532                    }
4533                    Sl::Bias(expr) => {
4534                        write!(self.out, ", ")?;
4535                        self.write_expr(module, expr, func_ctx)?;
4536                    }
4537                    Sl::Gradient { x, y } => {
4538                        write!(self.out, ", ")?;
4539                        self.write_expr(module, x, func_ctx)?;
4540                        write!(self.out, ", ")?;
4541                        self.write_expr(module, y, func_ctx)?;
4542                    }
4543                }
4544
4545                if let Some(offset) = offset {
4546                    write!(self.out, ", ")?;
4547                    // Work around https://github.com/microsoft/DirectXShaderCompiler/issues/5082#issuecomment-1540147807
4548                    let (size, scalar) = func_ctx
4549                        .resolve_type(offset, &module.types)
4550                        .vector_size_and_scalar()
4551                        .unwrap();
4552                    assert_eq!(scalar.kind, ScalarKind::Sint);
4553                    write!(self.out, "{}", scalar.to_hlsl_str()?)?;
4554                    if let Some(size) = size {
4555                        write!(self.out, "{}", common::vector_size_str(size))?;
4556                    }
4557                    write!(self.out, "(")?;
4558                    self.write_const_expression(module, offset, func_ctx.expressions)?;
4559                    write!(self.out, ")")?;
4560                }
4561
4562                write!(self.out, ")")?;
4563            }
4564            Expression::ImageQuery { image, query } => {
4565                // use wrapped image query function
4566                if let TypeInner::Image {
4567                    dim,
4568                    arrayed,
4569                    class,
4570                } = *func_ctx.resolve_type(image, &module.types)
4571                {
4572                    let wrapped_image_query = WrappedImageQuery {
4573                        dim,
4574                        arrayed,
4575                        class,
4576                        query: query.into(),
4577                    };
4578
4579                    self.write_wrapped_image_query_function_name(wrapped_image_query)?;
4580                    write!(self.out, "(")?;
4581                    // Image always first param
4582                    self.write_expr(module, image, func_ctx)?;
4583                    if let crate::ImageQuery::Size { level: Some(level) } = query {
4584                        write!(self.out, ", ")?;
4585                        self.write_expr(module, level, func_ctx)?;
4586                    }
4587                    write!(self.out, ")")?;
4588                }
4589            }
4590            Expression::ImageLoad {
4591                image,
4592                coordinate,
4593                array_index,
4594                sample,
4595                level,
4596            } => self.write_image_load(
4597                &module,
4598                expr,
4599                func_ctx,
4600                image,
4601                coordinate,
4602                array_index,
4603                sample,
4604                level,
4605            )?,
4606            Expression::GlobalVariable(handle) => {
4607                let global_variable = &module.global_variables[handle];
4608                let ty = &module.types[global_variable.ty].inner;
4609
4610                // In the case of binding arrays of samplers, we need to not write anything
4611                // as the we are in the wrong position to fully write the expression.
4612                //
4613                // The entire writing is done by AccessIndex.
4614                let is_binding_array_of_samplers = match *ty {
4615                    TypeInner::BindingArray { base, .. } => {
4616                        let base_ty = &module.types[base].inner;
4617                        matches!(*base_ty, TypeInner::Sampler { .. })
4618                    }
4619                    _ => false,
4620                };
4621
4622                let is_storage_space =
4623                    matches!(global_variable.space, crate::AddressSpace::Storage { .. });
4624
4625                // Our external texture global variable has been expanded into multiple
4626                // global variables, one for each plane and the parameters buffer.
4627                // External textures can only ever be used as arguments to a function
4628                // call, and we know that an external texture argument to any function
4629                // will have been expanded to separate consecutive arguments for each
4630                // plane and the parameters buffer. Therefore we can simply emit each of
4631                // the expanded global variables in a consecutive comma-separated list.
4632                if ty.is_external_image() {
4633                    let plane_names = [0, 1, 2].map(|i| {
4634                        &self.names[&NameKey::ExternalTextureGlobalVariable(
4635                            handle,
4636                            ExternalTextureNameKey::Plane(i),
4637                        )]
4638                    });
4639                    let params_name = &self.names[&NameKey::ExternalTextureGlobalVariable(
4640                        handle,
4641                        ExternalTextureNameKey::Params,
4642                    )];
4643                    write!(
4644                        self.out,
4645                        "{}, {}, {}, {}",
4646                        plane_names[0], plane_names[1], plane_names[2], params_name
4647                    )?;
4648                } else if !is_binding_array_of_samplers && !is_storage_space {
4649                    let name = &self.names[&NameKey::GlobalVariable(handle)];
4650                    write!(self.out, "{name}")?;
4651                }
4652            }
4653            Expression::LocalVariable(handle) => {
4654                write!(self.out, "{}", self.names[&func_ctx.name_key(handle)])?
4655            }
4656            Expression::Load { pointer } => {
4657                match func_ctx
4658                    .resolve_type(pointer, &module.types)
4659                    .pointer_space()
4660                {
4661                    Some(crate::AddressSpace::Storage { .. }) => {
4662                        let var_handle = self.fill_access_chain(module, pointer, func_ctx)?;
4663                        let result_ty = func_ctx.info[expr].ty.clone();
4664                        self.write_storage_load(module, var_handle, result_ty, func_ctx)?;
4665                    }
4666                    _ => {
4667                        let mut close_paren = false;
4668
4669                        // We cast the value loaded to a native HLSL floatCx2
4670                        // in cases where it is of type:
4671                        //  - __matCx2 or
4672                        //  - a (possibly nested) array of __matCx2's
4673                        if let Some(MatrixType {
4674                            rows: crate::VectorSize::Bi,
4675                            ..
4676                        }) = get_inner_matrix_of_struct_array_member(
4677                            module, pointer, func_ctx, false,
4678                        )
4679                        .or_else(|| {
4680                            get_inner_matrix_of_global_uniform(module, pointer, func_ctx, false)
4681                        }) {
4682                            let mut resolved = func_ctx.resolve_type(pointer, &module.types);
4683                            let ptr_tr = resolved.pointer_base_type();
4684                            if let Some(ptr_ty) =
4685                                ptr_tr.as_ref().map(|tr| tr.inner_with(&module.types))
4686                            {
4687                                resolved = ptr_ty;
4688                            }
4689
4690                            write!(self.out, "((")?;
4691                            if let TypeInner::Array { base, size, .. } = *resolved {
4692                                self.write_type(module, base)?;
4693                                self.write_array_size(module, base, size)?;
4694                            } else {
4695                                self.write_value_type(module, resolved)?;
4696                            }
4697                            write!(self.out, ")")?;
4698                            close_paren = true;
4699                        }
4700
4701                        self.write_expr(module, pointer, func_ctx)?;
4702
4703                        if close_paren {
4704                            write!(self.out, ")")?;
4705                        }
4706                    }
4707                }
4708            }
4709            Expression::Unary { op, expr } => {
4710                // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators#unary-operators
4711                let op_str = match op {
4712                    crate::UnaryOperator::Negate => {
4713                        match func_ctx.resolve_type(expr, &module.types).scalar() {
4714                            Some(Scalar::I32) => NEG_FUNCTION,
4715                            _ => "-",
4716                        }
4717                    }
4718                    crate::UnaryOperator::LogicalNot => "!",
4719                    crate::UnaryOperator::BitwiseNot => "~",
4720                };
4721                write!(self.out, "{op_str}(")?;
4722                self.write_expr(module, expr, func_ctx)?;
4723                write!(self.out, ")")?;
4724            }
4725            Expression::As { expr, target } => {
4726                let inner = func_ctx.resolve_type(expr, &module.types);
4727                if inner.scalar_kind() == Some(ScalarKind::Float)
4728                    && (target.kind == ScalarKind::Sint || target.kind == ScalarKind::Uint)
4729                    && matches!(target.width, 4 | 8)
4730                {
4731                    // Use helper functions for float to int casts in order to
4732                    // avoid undefined behaviour when value is out of range for
4733                    // the target type.
4734                    let fun_name = match (target.kind, target.width) {
4735                        (ScalarKind::Sint, 4) => F2I32_FUNCTION,
4736                        (ScalarKind::Uint, 4) => F2U32_FUNCTION,
4737                        (ScalarKind::Sint, 8) => F2I64_FUNCTION,
4738                        (ScalarKind::Uint, 8) => F2U64_FUNCTION,
4739                        _ => unreachable!(),
4740                    };
4741                    write!(self.out, "{fun_name}(")?;
4742                    self.write_expr(module, expr, func_ctx)?;
4743                    write!(self.out, ")")?;
4744                } else {
4745                    match *inner {
4746                        TypeInner::Vector { size, .. } => {
4747                            write!(
4748                                self.out,
4749                                "{}{}(",
4750                                target.to_hlsl_str()?,
4751                                common::vector_size_str(size)
4752                            )?;
4753                        }
4754                        TypeInner::Scalar(_) => {
4755                            write!(self.out, "{}(", target.to_hlsl_str()?,)?;
4756                        }
4757                        TypeInner::Matrix { columns, rows, .. } => {
4758                            write!(
4759                                self.out,
4760                                "{}{}x{}(",
4761                                target.to_hlsl_str()?,
4762                                common::vector_size_str(columns),
4763                                common::vector_size_str(rows)
4764                            )?;
4765                        }
4766                        _ => {
4767                            return Err(Error::Unimplemented(format!(
4768                                "write_expr expression::as {inner:?}"
4769                            )));
4770                        }
4771                    };
4772                    self.write_expr(module, expr, func_ctx)?;
4773                    write!(self.out, ")")?;
4774                }
4775            }
4776            Expression::Bitcast { expr, ty } => {
4777                let src_ty = func_ctx.resolve_type(expr, &module.types);
4778                let dst_ty = &module.types[ty].inner;
4779                let unsupported =
4780                    || Error::Unimplemented(format!("bitcast from {src_ty:?} to {dst_ty:?}"));
4781                let (Some((src_size, src)), Some((dst_size, dst))) = (
4782                    src_ty.vector_size_and_scalar(),
4783                    dst_ty.vector_size_and_scalar(),
4784                ) else {
4785                    return Err(unsupported());
4786                };
4787
4788                if let Some(wrapped) = help::WrappedBitcast::new(src_ty, dst_ty) {
4789                    write!(self.out, "{}(", wrapped.function_name()?)?;
4790                    self.write_expr(module, expr, func_ctx)?;
4791                    write!(self.out, ")")?;
4792                } else if src == dst {
4793                    self.write_expr(module, expr, func_ctx)?;
4794                } else {
4795                    debug_assert_eq!(src_size, dst_size);
4796                    let is_int =
4797                        |scalar: Scalar| matches!(scalar.kind, ScalarKind::Sint | ScalarKind::Uint);
4798                    // HLSL's `asint()`, `asuint()` and `asfloat()` only work on
4799                    // 32-bit types, and 16-bit types have `asint16()` and so
4800                    // on. For other widths of integers, use a constructor
4801                    // instead.
4802                    match (src.width, is_int(src) && is_int(dst)) {
4803                        (2 | 8, true) => {
4804                            write!(self.out, "{}", dst.to_hlsl_str()?)?;
4805                            if let Some(size) = dst_size {
4806                                write!(self.out, "{}", common::vector_size_str(size))?;
4807                            }
4808                            write!(self.out, "(")?;
4809                        }
4810                        (2, false) => write!(self.out, "{}(", dst.kind.to_hlsl_cast_16bit())?,
4811                        (4, _) => write!(self.out, "{}(", dst.kind.to_hlsl_cast())?,
4812                        _ => return Err(unsupported()),
4813                    };
4814                    self.write_expr(module, expr, func_ctx)?;
4815                    write!(self.out, ")")?;
4816                }
4817            }
4818            Expression::Math {
4819                fun,
4820                arg,
4821                arg1,
4822                arg2,
4823                arg3,
4824            } => {
4825                return self.write_math_expression(module, fun, arg, arg1, arg2, arg3, func_ctx);
4826            }
4827            Expression::Swizzle {
4828                size,
4829                vector,
4830                pattern,
4831            } => {
4832                self.write_expr(module, vector, func_ctx)?;
4833                write!(self.out, ".")?;
4834                for &sc in pattern[..size as usize].iter() {
4835                    self.out.write_char(back::COMPONENTS[sc as usize])?;
4836                }
4837            }
4838            Expression::ArrayLength(expr) => {
4839                let var_handle = match func_ctx.expressions[expr] {
4840                    Expression::AccessIndex { base, index: _ } => {
4841                        match func_ctx.expressions[base] {
4842                            Expression::GlobalVariable(handle) => handle,
4843                            _ => unreachable!(),
4844                        }
4845                    }
4846                    Expression::GlobalVariable(handle) => handle,
4847                    _ => unreachable!(),
4848                };
4849
4850                let var = &module.global_variables[var_handle];
4851                let (offset, stride) = match module.types[var.ty].inner {
4852                    TypeInner::Array { stride, .. } => (0, stride),
4853                    TypeInner::Struct { ref members, .. } => {
4854                        let last = members.last().unwrap();
4855                        let stride = match module.types[last.ty].inner {
4856                            TypeInner::Array { stride, .. } => stride,
4857                            _ => unreachable!(),
4858                        };
4859                        (last.offset, stride)
4860                    }
4861                    _ => unreachable!(),
4862                };
4863
4864                let storage_access = match var.space {
4865                    crate::AddressSpace::Storage { access } => access,
4866                    _ => crate::StorageAccess::default(),
4867                };
4868                let wrapped_array_length = WrappedArrayLength {
4869                    writable: storage_access.contains(crate::StorageAccess::STORE),
4870                };
4871
4872                write!(self.out, "((")?;
4873                self.write_wrapped_array_length_function_name(wrapped_array_length)?;
4874                let var_name = &self.names[&NameKey::GlobalVariable(var_handle)];
4875                write!(self.out, "({var_name}) - {offset}) / {stride})")?
4876            }
4877            Expression::Derivative { axis, ctrl, expr } => {
4878                use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl};
4879                if axis == Axis::Width && (ctrl == Ctrl::Coarse || ctrl == Ctrl::Fine) {
4880                    let tail = match ctrl {
4881                        Ctrl::Coarse => "coarse",
4882                        Ctrl::Fine => "fine",
4883                        Ctrl::None => unreachable!(),
4884                    };
4885                    write!(self.out, "abs(ddx_{tail}(")?;
4886                    self.write_expr(module, expr, func_ctx)?;
4887                    write!(self.out, ")) + abs(ddy_{tail}(")?;
4888                    self.write_expr(module, expr, func_ctx)?;
4889                    write!(self.out, "))")?
4890                } else {
4891                    let fun_str = match (axis, ctrl) {
4892                        (Axis::X, Ctrl::Coarse) => "ddx_coarse",
4893                        (Axis::X, Ctrl::Fine) => "ddx_fine",
4894                        (Axis::X, Ctrl::None) => "ddx",
4895                        (Axis::Y, Ctrl::Coarse) => "ddy_coarse",
4896                        (Axis::Y, Ctrl::Fine) => "ddy_fine",
4897                        (Axis::Y, Ctrl::None) => "ddy",
4898                        (Axis::Width, Ctrl::Coarse | Ctrl::Fine) => unreachable!(),
4899                        (Axis::Width, Ctrl::None) => "fwidth",
4900                    };
4901                    write!(self.out, "{fun_str}(")?;
4902                    self.write_expr(module, expr, func_ctx)?;
4903                    write!(self.out, ")")?
4904                }
4905            }
4906            Expression::Relational { fun, argument } => {
4907                use crate::RelationalFunction as Rf;
4908
4909                let fun_str = match fun {
4910                    Rf::All => "all",
4911                    Rf::Any => "any",
4912                    Rf::IsNan => "isnan",
4913                    Rf::IsInf => "isinf",
4914                };
4915                write!(self.out, "{fun_str}(")?;
4916                self.write_expr(module, argument, func_ctx)?;
4917                write!(self.out, ")")?
4918            }
4919            Expression::Select {
4920                condition,
4921                accept,
4922                reject,
4923            } => {
4924                write!(self.out, "(")?;
4925                self.write_expr(module, condition, func_ctx)?;
4926                write!(self.out, " ? ")?;
4927                self.write_expr(module, accept, func_ctx)?;
4928                write!(self.out, " : ")?;
4929                self.write_expr(module, reject, func_ctx)?;
4930                write!(self.out, ")")?
4931            }
4932            Expression::RayQueryGetIntersection { query, committed } => {
4933                // For reasoning, see write_stmt
4934                let Expression::LocalVariable(query_var) = func_ctx.expressions[query] else {
4935                    unreachable!()
4936                };
4937
4938                let tracker_expr_name = format!(
4939                    "{RAY_QUERY_TRACKER_VARIABLE_PREFIX}{}",
4940                    self.names[&func_ctx.name_key(query_var)]
4941                );
4942
4943                if committed {
4944                    write!(self.out, "GetCommittedIntersection(")?;
4945                    self.write_expr(module, query, func_ctx)?;
4946                    write!(self.out, ", {tracker_expr_name})")?;
4947                } else {
4948                    write!(self.out, "GetCandidateIntersection(")?;
4949                    self.write_expr(module, query, func_ctx)?;
4950                    write!(self.out, ", {tracker_expr_name})")?;
4951                }
4952            }
4953            // Not supported yet
4954            Expression::RayQueryVertexPositions { .. }
4955            | Expression::HitObjectQuery { .. }
4956            | Expression::CooperativeLoad { .. }
4957            | Expression::CooperativeMultiplyAdd { .. } => {
4958                unreachable!()
4959            }
4960            // Nothing to do here, since call expression already cached
4961            Expression::CallResult(_)
4962            | Expression::AtomicResult { .. }
4963            | Expression::WorkGroupUniformLoadResult { .. }
4964            | Expression::RayQueryProceedResult
4965            | Expression::SubgroupBallotResult
4966            | Expression::SubgroupOperationResult { .. } => {}
4967        }
4968
4969        if !closing_bracket.is_empty() {
4970            write!(self.out, "{closing_bracket}")?;
4971        }
4972        Ok(())
4973    }
4974
4975    #[allow(clippy::too_many_arguments)]
4976    fn write_image_load(
4977        &mut self,
4978        module: &&Module,
4979        expr: Handle<crate::Expression>,
4980        func_ctx: &back::FunctionCtx,
4981        image: Handle<crate::Expression>,
4982        coordinate: Handle<crate::Expression>,
4983        array_index: Option<Handle<crate::Expression>>,
4984        sample: Option<Handle<crate::Expression>>,
4985        level: Option<Handle<crate::Expression>>,
4986    ) -> Result<(), Error> {
4987        let mut wrapping_type = None;
4988        match *func_ctx.resolve_type(image, &module.types) {
4989            TypeInner::Image {
4990                class: crate::ImageClass::External,
4991                ..
4992            } => {
4993                write!(self.out, "{IMAGE_LOAD_EXTERNAL_FUNCTION}(")?;
4994                self.write_expr(module, image, func_ctx)?;
4995                write!(self.out, ", ")?;
4996                self.write_expr(module, coordinate, func_ctx)?;
4997                write!(self.out, ")")?;
4998                return Ok(());
4999            }
5000            TypeInner::Image {
5001                class: crate::ImageClass::Storage { format, .. },
5002                ..
5003            } if format.single_component() => {
5004                wrapping_type = Some(Scalar::from(format));
5005            }
5006            _ => {}
5007        }
5008        if let Some(scalar) = wrapping_type {
5009            write!(
5010                self.out,
5011                "{}{}(",
5012                help::IMAGE_STORAGE_LOAD_SCALAR_WRAPPER,
5013                scalar.to_hlsl_str()?
5014            )?;
5015        }
5016        // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-load
5017        self.write_expr(module, image, func_ctx)?;
5018        write!(self.out, ".Load(")?;
5019
5020        self.write_texture_coordinates("int", coordinate, array_index, level, module, func_ctx)?;
5021
5022        if let Some(sample) = sample {
5023            write!(self.out, ", ")?;
5024            self.write_expr(module, sample, func_ctx)?;
5025        }
5026
5027        // close bracket for Load function
5028        write!(self.out, ")")?;
5029
5030        if wrapping_type.is_some() {
5031            write!(self.out, ")")?;
5032        }
5033
5034        // return x component if return type is scalar
5035        if let TypeInner::Scalar(_) = *func_ctx.resolve_type(expr, &module.types) {
5036            write!(self.out, ".x")?;
5037        }
5038        Ok(())
5039    }
5040
5041    /// Find the [`BindingArraySamplerInfo`] from an expression so that such an access
5042    /// can be generated later.
5043    fn sampler_binding_array_info_from_expression(
5044        &mut self,
5045        module: &Module,
5046        func_ctx: &back::FunctionCtx<'_>,
5047        base: Handle<crate::Expression>,
5048        resolved: &TypeInner,
5049    ) -> Option<BindingArraySamplerInfo> {
5050        if let TypeInner::BindingArray {
5051            base: base_ty_handle,
5052            ..
5053        } = *resolved
5054        {
5055            let base_ty = &module.types[base_ty_handle].inner;
5056            if let TypeInner::Sampler { comparison, .. } = *base_ty {
5057                let base = &func_ctx.expressions[base];
5058
5059                if let crate::Expression::GlobalVariable(handle) = *base {
5060                    let variable = &module.global_variables[handle];
5061
5062                    let sampler_heap_name = match comparison {
5063                        true => COMPARISON_SAMPLER_HEAP_VAR,
5064                        false => SAMPLER_HEAP_VAR,
5065                    };
5066
5067                    return Some(BindingArraySamplerInfo {
5068                        sampler_heap_name,
5069                        sampler_index_buffer_name: self
5070                            .wrapped
5071                            .sampler_index_buffers
5072                            .get(&super::SamplerIndexBufferKey {
5073                                group: variable.binding.unwrap().group,
5074                            })
5075                            .unwrap()
5076                            .clone(),
5077                        binding_array_base_index_name: self.names[&NameKey::GlobalVariable(handle)]
5078                            .clone(),
5079                    });
5080                }
5081            }
5082        }
5083
5084        None
5085    }
5086
5087    fn write_named_expr(
5088        &mut self,
5089        module: &Module,
5090        handle: Handle<crate::Expression>,
5091        name: String,
5092        // The expression which is being named.
5093        // Generally, this is the same as handle, except in WorkGroupUniformLoad
5094        expr: Handle<crate::Expression>,
5095        func_ctx: &back::FunctionCtx,
5096    ) -> BackendResult {
5097        if let crate::Expression::Load { pointer } = func_ctx.expressions[expr] {
5098            let ty_inner = func_ctx.resolve_type(pointer, &module.types);
5099            if ty_inner.is_atomic_pointer(&module.types) {
5100                let pointer_space = ty_inner.pointer_space().unwrap();
5101                self.write_value_type(module, func_ctx.info[handle].ty.inner_with(&module.types))?;
5102                write!(self.out, " {name}; ")?;
5103                match pointer_space {
5104                    crate::AddressSpace::WorkGroup => {
5105                        write!(self.out, "InterlockedOr(")?;
5106                        self.write_expr(module, pointer, func_ctx)?;
5107                    }
5108                    crate::AddressSpace::Storage { .. } => {
5109                        let var_handle = self.fill_access_chain(module, pointer, func_ctx)?;
5110                        let var_name = &self.names[&NameKey::GlobalVariable(var_handle)];
5111                        write!(self.out, "{var_name}.InterlockedOr(")?;
5112                        let chain = mem::take(&mut self.temp_access_chain);
5113                        self.write_storage_address(module, &chain, func_ctx)?;
5114                        self.temp_access_chain = chain;
5115                    }
5116                    _ => unreachable!(),
5117                }
5118                writeln!(self.out, ", 0, {name});")?;
5119                self.named_expressions.insert(expr, name);
5120                return Ok(());
5121            }
5122        }
5123        match func_ctx.info[expr].ty {
5124            proc::TypeResolution::Handle(ty_handle) => match module.types[ty_handle].inner {
5125                TypeInner::Struct { .. } => {
5126                    let ty_name = &self.names[&NameKey::Type(ty_handle)];
5127                    write!(self.out, "{ty_name}")?;
5128                }
5129                _ => {
5130                    self.write_type(module, ty_handle)?;
5131                }
5132            },
5133            proc::TypeResolution::Value(ref inner) => {
5134                self.write_value_type(module, inner)?;
5135            }
5136        }
5137
5138        let resolved = func_ctx.resolve_type(expr, &module.types);
5139
5140        write!(self.out, " {name}")?;
5141        // If rhs is a array type, we should write array size
5142        if let TypeInner::Array { base, size, .. } = *resolved {
5143            self.write_array_size(module, base, size)?;
5144        }
5145        write!(self.out, " = ")?;
5146        self.write_expr(module, handle, func_ctx)?;
5147        writeln!(self.out, ";")?;
5148        self.named_expressions.insert(expr, name);
5149
5150        Ok(())
5151    }
5152
5153    /// Helper function that write default zero initialization
5154    pub(super) fn write_default_init(
5155        &mut self,
5156        module: &Module,
5157        ty: Handle<crate::Type>,
5158    ) -> BackendResult {
5159        write!(self.out, "(")?;
5160        self.write_type(module, ty)?;
5161        if let TypeInner::Array { base, size, .. } = module.types[ty].inner {
5162            self.write_array_size(module, base, size)?;
5163        }
5164        write!(self.out, ")0")?;
5165        Ok(())
5166    }
5167
5168    pub(super) fn write_control_barrier(
5169        &mut self,
5170        barrier: crate::Barrier,
5171        level: back::Level,
5172    ) -> BackendResult {
5173        if barrier.contains(crate::Barrier::STORAGE) {
5174            writeln!(self.out, "{level}DeviceMemoryBarrierWithGroupSync();")?;
5175        }
5176        if barrier.contains(crate::Barrier::WORK_GROUP) {
5177            writeln!(self.out, "{level}GroupMemoryBarrierWithGroupSync();")?;
5178        }
5179        if barrier.contains(crate::Barrier::SUB_GROUP) {
5180            // Does not exist in DirectX
5181        }
5182        if barrier.contains(crate::Barrier::TEXTURE) {
5183            writeln!(self.out, "{level}DeviceMemoryBarrierWithGroupSync();")?;
5184        }
5185        Ok(())
5186    }
5187
5188    fn write_memory_barrier(
5189        &mut self,
5190        barrier: crate::Barrier,
5191        level: back::Level,
5192    ) -> BackendResult {
5193        if barrier.contains(crate::Barrier::STORAGE) {
5194            writeln!(self.out, "{level}DeviceMemoryBarrier();")?;
5195        }
5196        if barrier.contains(crate::Barrier::WORK_GROUP) {
5197            writeln!(self.out, "{level}GroupMemoryBarrier();")?;
5198        }
5199        if barrier.contains(crate::Barrier::SUB_GROUP) {
5200            // Does not exist in DirectX
5201        }
5202        if barrier.contains(crate::Barrier::TEXTURE) {
5203            writeln!(self.out, "{level}DeviceMemoryBarrier();")?;
5204        }
5205        Ok(())
5206    }
5207
5208    /// Helper to emit the shared tail of an HLSL atomic call (arguments, value, result)
5209    fn emit_hlsl_atomic_tail(
5210        &mut self,
5211        module: &Module,
5212        func_ctx: &back::FunctionCtx<'_>,
5213        fun: &crate::AtomicFunction,
5214        compare_expr: Option<Handle<crate::Expression>>,
5215        value: Handle<crate::Expression>,
5216        res_var_info: &Option<(Handle<crate::Expression>, String)>,
5217    ) -> BackendResult {
5218        if let Some(cmp) = compare_expr {
5219            write!(self.out, ", ")?;
5220            self.write_expr(module, cmp, func_ctx)?;
5221        }
5222        write!(self.out, ", ")?;
5223        if let crate::AtomicFunction::Subtract = *fun {
5224            // we just wrote `InterlockedAdd`, so negate the argument
5225            write!(self.out, "-")?;
5226        }
5227        self.write_expr(module, value, func_ctx)?;
5228        if let Some(&(_res_handle, ref res_name)) = res_var_info.as_ref() {
5229            write!(self.out, ", ")?;
5230            if compare_expr.is_some() {
5231                write!(self.out, "{res_name}.old_value")?;
5232            } else {
5233                write!(self.out, "{res_name}")?;
5234            }
5235        }
5236        writeln!(self.out, ");")?;
5237        Ok(())
5238    }
5239}
5240
5241pub(super) struct MatrixType {
5242    pub(super) columns: crate::VectorSize,
5243    pub(super) rows: crate::VectorSize,
5244    pub(super) width: crate::Bytes,
5245}
5246
5247pub(super) fn get_inner_matrix_data(
5248    module: &Module,
5249    handle: Handle<crate::Type>,
5250) -> Option<MatrixType> {
5251    match module.types[handle].inner {
5252        TypeInner::Matrix {
5253            columns,
5254            rows,
5255            scalar,
5256        } => Some(MatrixType {
5257            columns,
5258            rows,
5259            width: scalar.width,
5260        }),
5261        TypeInner::Array { base, .. } => get_inner_matrix_data(module, base),
5262        _ => None,
5263    }
5264}
5265
5266/// Returns `true` if `binding` is the depth that a fragment shader writes.
5267const fn is_frag_depth(binding: Option<&crate::Binding>) -> bool {
5268    matches!(
5269        binding,
5270        Some(crate::Binding::BuiltIn(crate::BuiltIn::FragDepth))
5271    )
5272}
5273
5274/// Returns `true` if the depth that `entry_point` writes must be discarded.
5275///
5276/// HLSL has no way to specify that depth is unchanged. Discarding the depth has the same effect,
5277/// and keeps early depth tests enabled.
5278fn discards_frag_depth(entry_point: &crate::EntryPoint) -> bool {
5279    entry_point.stage == ShaderStage::Fragment
5280        && entry_point.early_depth_test
5281            == Some(crate::EarlyDepthTest::Allow {
5282                conservative: crate::ConservativeDepth::Unchanged,
5283            })
5284}
5285
5286/// Returns `true` if `entry_point` has nothing to return once its depth is discarded.
5287fn only_writes_discarded_depth(module: &Module, entry_point: &crate::EntryPoint) -> bool {
5288    discards_frag_depth(entry_point)
5289        && entry_point.function.result.as_ref().is_some_and(|result| {
5290            match module.types[result.ty].inner {
5291                TypeInner::Struct { ref members, .. } if result.binding.is_none() => members
5292                    .iter()
5293                    .all(|member| is_frag_depth(member.binding.as_ref())),
5294                _ => is_frag_depth(result.binding.as_ref()),
5295            }
5296        })
5297}
5298
5299/// Returns `true` if the function described by `func_ctx` is an entry point that returns nothing,
5300/// because the only thing it would return is a depth that is discarded.
5301fn returns_nothing(module: &Module, func_ctx: &back::FunctionCtx<'_>) -> bool {
5302    match func_ctx.ty {
5303        back::FunctionType::EntryPoint(index) => {
5304            only_writes_discarded_depth(module, &module.entry_points[index as usize])
5305        }
5306        back::FunctionType::Function(_) => false,
5307    }
5308}
5309
5310/// Gets the early depth test of the fragment entry points in `entry_points` that return `ty`.
5311///
5312/// Returns `None` if there are no such entry points or if they disagree. The semantic of a
5313/// depth output is part of the definition of the struct that contains it, so a struct that is
5314/// shared by entry points with different settings cannot use a conservative semantic.
5315fn shared_early_depth_test(
5316    module: &Module,
5317    entry_points: core::ops::Range<usize>,
5318    ty: Handle<crate::Type>,
5319) -> Option<crate::EarlyDepthTest> {
5320    let mut users = entry_points
5321        .map(|index| &module.entry_points[index])
5322        .filter(|ep| {
5323            ep.stage == ShaderStage::Fragment
5324                && ep.function.result.as_ref().is_some_and(|r| r.ty == ty)
5325        });
5326    let first = users.next()?.early_depth_test;
5327    if users.all(|ep| ep.early_depth_test == first) {
5328        first
5329    } else {
5330        None
5331    }
5332}
5333
5334/// If `base` is an access chain of the form `mat`, `mat[col]`, or `mat[col][row]`,
5335/// returns a tuple of the matrix, the column (vector) index (if present), and
5336/// the row (scalar) index (if present).
5337fn find_matrix_in_access_chain(
5338    module: &Module,
5339    base: Handle<crate::Expression>,
5340    func_ctx: &back::FunctionCtx<'_>,
5341) -> Option<(Handle<crate::Expression>, Option<Index>, Option<Index>)> {
5342    let mut current_base = base;
5343    let mut vector = None;
5344    let mut scalar = None;
5345    loop {
5346        let resolved_tr = func_ctx
5347            .resolve_type(current_base, &module.types)
5348            .pointer_base_type();
5349        let resolved = resolved_tr.as_ref()?.inner_with(&module.types);
5350
5351        match *resolved {
5352            TypeInner::Matrix { .. } => return Some((current_base, vector, scalar)),
5353            TypeInner::Scalar(_) | TypeInner::Vector { .. } => {}
5354            _ => return None,
5355        }
5356
5357        let index;
5358        (current_base, index) = match func_ctx.expressions[current_base] {
5359            crate::Expression::Access { base, index } => (base, Index::Expression(index)),
5360            crate::Expression::AccessIndex { base, index } => (base, Index::Static(index)),
5361            _ => return None,
5362        };
5363
5364        match *resolved {
5365            TypeInner::Scalar(_) => scalar = Some(index),
5366            TypeInner::Vector { .. } => vector = Some(index),
5367            _ => unreachable!(),
5368        }
5369    }
5370}
5371
5372/// Returns the matrix data if the access chain starting at `base`:
5373/// - starts with an expression with resolved type of [`TypeInner::Matrix`] if `direct = true`
5374/// - contains one or more expressions with resolved type of [`TypeInner::Array`] of [`TypeInner::Matrix`]
5375/// - ends at an expression with resolved type of [`TypeInner::Struct`]
5376pub(super) fn get_inner_matrix_of_struct_array_member(
5377    module: &Module,
5378    base: Handle<crate::Expression>,
5379    func_ctx: &back::FunctionCtx<'_>,
5380    direct: bool,
5381) -> Option<MatrixType> {
5382    let mut mat_data = None;
5383    let mut array_base = None;
5384
5385    let mut current_base = base;
5386    loop {
5387        let mut resolved = func_ctx.resolve_type(current_base, &module.types);
5388        if let TypeInner::Pointer { base, .. } = *resolved {
5389            resolved = &module.types[base].inner;
5390        };
5391
5392        match *resolved {
5393            TypeInner::Matrix {
5394                columns,
5395                rows,
5396                scalar,
5397            } => {
5398                mat_data = Some(MatrixType {
5399                    columns,
5400                    rows,
5401                    width: scalar.width,
5402                })
5403            }
5404            TypeInner::Array { base, .. } => {
5405                array_base = Some(base);
5406            }
5407            TypeInner::Struct { .. } => {
5408                if let Some(array_base) = array_base {
5409                    if direct {
5410                        return mat_data;
5411                    } else {
5412                        return get_inner_matrix_data(module, array_base);
5413                    }
5414                }
5415
5416                break;
5417            }
5418            _ => break,
5419        }
5420
5421        current_base = match func_ctx.expressions[current_base] {
5422            crate::Expression::Access { base, .. } => base,
5423            crate::Expression::AccessIndex { base, .. } => base,
5424            _ => break,
5425        };
5426    }
5427    None
5428}
5429
5430/// Returns the matrix data if the access chain starting at `base`:
5431/// - starts with an expression with resolved type of [`TypeInner::Matrix`], or
5432/// - contains zero or more expressions with resolved type of [`TypeInner::Array`] of [`TypeInner::Matrix`] if `direct = false`
5433/// - and ends with an [`Expression::GlobalVariable`](crate::Expression::GlobalVariable) in [`AddressSpace::Uniform`](crate::AddressSpace::Uniform)
5434fn get_inner_matrix_of_global_uniform(
5435    module: &Module,
5436    base: Handle<crate::Expression>,
5437    func_ctx: &back::FunctionCtx<'_>,
5438    direct: bool,
5439) -> Option<MatrixType> {
5440    let mut mat_data = None;
5441    let mut array_base = None;
5442
5443    let mut current_base = base;
5444    loop {
5445        let mut resolved = func_ctx.resolve_type(current_base, &module.types);
5446        if let TypeInner::Pointer { base, .. } = *resolved {
5447            resolved = &module.types[base].inner;
5448        };
5449
5450        match *resolved {
5451            TypeInner::Matrix {
5452                columns,
5453                rows,
5454                scalar,
5455            } => {
5456                mat_data = Some(MatrixType {
5457                    columns,
5458                    rows,
5459                    width: scalar.width,
5460                })
5461            }
5462            TypeInner::Array { base, .. } => {
5463                if !direct {
5464                    array_base = Some(base);
5465                }
5466            }
5467            _ => break,
5468        }
5469
5470        current_base = match func_ctx.expressions[current_base] {
5471            crate::Expression::Access { base, .. } => base,
5472            crate::Expression::AccessIndex { base, .. } => base,
5473            crate::Expression::GlobalVariable(handle)
5474                if module.global_variables[handle].space == crate::AddressSpace::Uniform =>
5475            {
5476                return mat_data.or_else(|| {
5477                    array_base.and_then(|array_base| get_inner_matrix_data(module, array_base))
5478                })
5479            }
5480            _ => break,
5481        };
5482    }
5483    None
5484}