naga/back/glsl/
writer.rs

1use super::*;
2
3/// Writer responsible for all code generation.
4pub struct Writer<'a, W> {
5    // Inputs
6    /// The module being written.
7    pub(in crate::back::glsl) module: &'a crate::Module,
8    /// The module analysis.
9    pub(in crate::back::glsl) info: &'a valid::ModuleInfo,
10    /// The output writer.
11    out: W,
12    /// User defined configuration to be used.
13    pub(in crate::back::glsl) options: &'a Options,
14    /// The bound checking policies to be used
15    pub(in crate::back::glsl) policies: proc::BoundsCheckPolicies,
16
17    // Internal State
18    /// Features manager used to store all the needed features and write them.
19    pub(in crate::back::glsl) features: FeaturesManager,
20    namer: proc::Namer,
21    /// A map with all the names needed for writing the module
22    /// (generated by a [`Namer`](crate::proc::Namer)).
23    names: crate::FastHashMap<NameKey, String>,
24    /// A map with the names of global variables needed for reflections.
25    reflection_names_globals: crate::FastHashMap<Handle<crate::GlobalVariable>, String>,
26    /// The selected entry point.
27    pub(in crate::back::glsl) entry_point: &'a crate::EntryPoint,
28    /// The index of the selected entry point.
29    pub(in crate::back::glsl) entry_point_idx: proc::EntryPointIndex,
30    /// A generator for unique block numbers.
31    block_id: IdGenerator,
32    /// Set of expressions that have associated temporary variables.
33    named_expressions: crate::NamedExpressions,
34    /// Set of expressions that need to be baked to avoid unnecessary repetition in output
35    need_bake_expressions: back::NeedBakeExpressions,
36    /// Information about nesting of loops and switches.
37    ///
38    /// Used for forwarding continue statements in switches that have been
39    /// transformed to `do {} while(false);` loops.
40    continue_ctx: back::continue_forward::ContinueCtx,
41    /// How many views to render to, if doing multiview rendering.
42    pub(in crate::back::glsl) multiview: Option<core::num::NonZeroU32>,
43    /// Mapping of varying variables to their location. Needed for reflections.
44    varying: crate::FastHashMap<String, VaryingLocation>,
45    /// Number of user-defined clip planes. Only non-zero for vertex shaders.
46    clip_distance_count: u32,
47}
48
49impl<'a, W: Write> Writer<'a, W> {
50    /// Creates a new [`Writer`] instance.
51    ///
52    /// # Errors
53    /// - If the version specified is invalid or supported.
54    /// - If the entry point couldn't be found in the module.
55    /// - If the version specified doesn't support some used features.
56    pub fn new(
57        out: W,
58        module: &'a crate::Module,
59        info: &'a valid::ModuleInfo,
60        options: &'a Options,
61        pipeline_options: &'a PipelineOptions,
62        policies: proc::BoundsCheckPolicies,
63    ) -> Result<Self, Error> {
64        // Check if the requested version is supported
65        if !options.version.is_supported() {
66            log::error!("Version {}", options.version);
67            return Err(Error::VersionNotSupported);
68        }
69
70        // Try to find the entry point and corresponding index
71        let ep_idx = module
72            .entry_points
73            .iter()
74            .position(|ep| {
75                pipeline_options.shader_stage == ep.stage && pipeline_options.entry_point == ep.name
76            })
77            .ok_or(Error::EntryPointNotFound)?;
78
79        // Generate a map with names required to write the module
80        let mut names = crate::FastHashMap::default();
81        let mut namer = proc::Namer::default();
82        namer.reset(
83            module,
84            &keywords::RESERVED_KEYWORD_SET,
85            proc::KeywordSet::empty(),
86            proc::CaseInsensitiveKeywordSet::empty(),
87            &[
88                "gl_",                  // all GL built-in variables
89                "_group",               // all normal bindings
90                "_immediates_binding_", // all immediate data bindings
91            ],
92            &mut names,
93        );
94
95        // Build the instance
96        let mut this = Self {
97            module,
98            info,
99            out,
100            options,
101            policies,
102
103            namer,
104            features: FeaturesManager::new(),
105            names,
106            reflection_names_globals: crate::FastHashMap::default(),
107            entry_point: &module.entry_points[ep_idx],
108            entry_point_idx: ep_idx as u16,
109            multiview: pipeline_options.multiview,
110            block_id: IdGenerator::default(),
111            named_expressions: Default::default(),
112            need_bake_expressions: Default::default(),
113            continue_ctx: back::continue_forward::ContinueCtx::default(),
114            varying: Default::default(),
115            clip_distance_count: 0,
116        };
117
118        // Find all features required to print this module
119        this.collect_required_features()?;
120
121        Ok(this)
122    }
123
124    /// Writes the [`Module`](crate::Module) as glsl to the output
125    ///
126    /// # Notes
127    /// If an error occurs while writing, the output might have been written partially
128    ///
129    /// # Panics
130    /// Might panic if the module is invalid
131    pub fn write(&mut self) -> Result<ReflectionInfo, Error> {
132        // We use `writeln!(self.out)` throughout the write to add newlines
133        // to make the output more readable
134
135        let es = self.options.version.is_es();
136
137        // Write the version (It must be the first thing or it isn't a valid glsl output)
138        writeln!(self.out, "#version {}", self.options.version)?;
139        // Write all the needed extensions
140        //
141        // This used to be the last thing being written as it allowed to search for features while
142        // writing the module saving some loops but some older versions (420 or less) required the
143        // extensions to appear before being used, even though extensions are part of the
144        // preprocessor not the processor ¯\_(ツ)_/¯
145        self.features.write(self.options, &mut self.out)?;
146
147        // glsl es requires a precision to be specified for floats and ints
148        // TODO: Should this be user configurable?
149        if es {
150            writeln!(self.out)?;
151            writeln!(self.out, "precision highp float;")?;
152            writeln!(self.out, "precision highp int;")?;
153            writeln!(self.out)?;
154        }
155
156        if self.entry_point.stage == ShaderStage::Compute {
157            let workgroup_size = self.entry_point.workgroup_size;
158            writeln!(
159                self.out,
160                "layout(local_size_x = {}, local_size_y = {}, local_size_z = {}) in;",
161                workgroup_size[0], workgroup_size[1], workgroup_size[2]
162            )?;
163            writeln!(self.out)?;
164        }
165
166        if self.entry_point.stage == ShaderStage::Vertex
167            && !self
168                .options
169                .writer_flags
170                .contains(WriterFlags::DRAW_PARAMETERS)
171            && self.features.contains(Features::INSTANCE_INDEX)
172        {
173            writeln!(self.out, "uniform uint {FIRST_INSTANCE_BINDING};")?;
174            writeln!(self.out)?;
175        }
176
177        // Enable early depth tests if needed
178        if let Some(early_depth_test) = self.entry_point.early_depth_test {
179            // If early depth test is supported for this version of GLSL
180            if self.options.version.supports_early_depth_test() {
181                match early_depth_test {
182                    crate::EarlyDepthTest::Force => {
183                        writeln!(self.out, "layout(early_fragment_tests) in;")?;
184                    }
185                    crate::EarlyDepthTest::Allow { conservative, .. } => {
186                        use crate::ConservativeDepth as Cd;
187                        let depth = match conservative {
188                            Cd::GreaterEqual => "greater",
189                            Cd::LessEqual => "less",
190                            Cd::Unchanged => "unchanged",
191                        };
192                        writeln!(self.out, "layout (depth_{depth}) out float gl_FragDepth;")?;
193                    }
194                }
195            } else {
196                log::warn!(
197                    "Early depth testing is not supported for this version of GLSL: {}",
198                    self.options.version
199                );
200            }
201        }
202
203        if self.entry_point.stage == ShaderStage::Vertex && self.options.version.is_webgl() {
204            if let Some(multiview) = self.multiview.as_ref() {
205                writeln!(self.out, "layout(num_views = {multiview}) in;")?;
206                writeln!(self.out)?;
207            }
208        }
209
210        // Write struct types.
211        //
212        // This are always ordered because the IR is structured in a way that
213        // you can't make a struct without adding all of its members first.
214        for (handle, ty) in self.module.types.iter() {
215            if let TypeInner::Struct { ref members, .. } = ty.inner {
216                let struct_name = &self.names[&NameKey::Type(handle)];
217
218                // Structures ending with runtime-sized arrays can only be
219                // rendered as shader storage blocks in GLSL, not stand-alone
220                // struct types.
221                if !self.module.types[members.last().unwrap().ty]
222                    .inner
223                    .is_dynamically_sized(&self.module.types)
224                {
225                    write!(self.out, "struct {struct_name} ")?;
226                    self.write_struct_body(handle, members)?;
227                    writeln!(self.out, ";")?;
228                }
229            }
230        }
231
232        // Write functions for special types.
233        for (type_key, struct_ty) in self.module.special_types.predeclared_types.iter() {
234            match type_key {
235                &crate::PredeclaredType::ModfResult { size, scalar }
236                | &crate::PredeclaredType::FrexpResult { size, scalar } => {
237                    let struct_name = &self.names[&NameKey::Type(*struct_ty)];
238                    let arg_type_name_owner;
239                    let arg_type_name = if let Some(size) = size {
240                        arg_type_name_owner = format!(
241                            "{}vec{}",
242                            if scalar.width == 8 { "d" } else { "" },
243                            size as u8
244                        );
245                        &arg_type_name_owner
246                    } else if scalar.width == 8 {
247                        "double"
248                    } else {
249                        "float"
250                    };
251
252                    let other_type_name_owner;
253                    let (defined_func_name, called_func_name, other_type_name) =
254                        if matches!(type_key, &crate::PredeclaredType::ModfResult { .. }) {
255                            (MODF_FUNCTION, "modf", arg_type_name)
256                        } else {
257                            let other_type_name = if let Some(size) = size {
258                                other_type_name_owner = format!("ivec{}", size as u8);
259                                &other_type_name_owner
260                            } else {
261                                "int"
262                            };
263                            (FREXP_FUNCTION, "frexp", other_type_name)
264                        };
265
266                    writeln!(self.out)?;
267                    if !self.options.version.supports_frexp_function()
268                        && matches!(type_key, &crate::PredeclaredType::FrexpResult { .. })
269                    {
270                        writeln!(
271                            self.out,
272                            "{struct_name} {defined_func_name}({arg_type_name} arg) {{
273    {other_type_name} other = arg == {arg_type_name}(0) ? {other_type_name}(0) : {other_type_name}({arg_type_name}(1) + log2(arg));
274    {arg_type_name} fract = arg * exp2({arg_type_name}(-other));
275    return {struct_name}(fract, other);
276}}",
277                        )?;
278                    } else {
279                        writeln!(
280                            self.out,
281                            "{struct_name} {defined_func_name}({arg_type_name} arg) {{
282    {other_type_name} other;
283    {arg_type_name} fract = {called_func_name}(arg, other);
284    return {struct_name}(fract, other);
285}}",
286                        )?;
287                    }
288                }
289                &crate::PredeclaredType::AtomicCompareExchangeWeakResult(_) => {
290                    // Handled by the general struct writing loop earlier.
291                }
292            }
293        }
294
295        // Write all named constants
296        let mut constants = self
297            .module
298            .constants
299            .iter()
300            .filter(|&(_, c)| c.name.is_some())
301            .peekable();
302        while let Some((handle, _)) = constants.next() {
303            self.write_global_constant(handle)?;
304            // Add extra newline for readability on last iteration
305            if constants.peek().is_none() {
306                writeln!(self.out)?;
307            }
308        }
309
310        let ep_info = self.info.get_entry_point(self.entry_point_idx as usize);
311
312        // Write the globals
313        //
314        // Unless explicitly disabled with WriterFlags::INCLUDE_UNUSED_ITEMS,
315        // we filter all globals that aren't used by the selected entry point as they might be
316        // interfere with each other (i.e. two globals with the same location but different with
317        // different classes)
318        let include_unused = self
319            .options
320            .writer_flags
321            .contains(WriterFlags::INCLUDE_UNUSED_ITEMS);
322        for (handle, global) in self.module.global_variables.iter() {
323            let is_unused = ep_info[handle].is_empty();
324            if !include_unused && is_unused {
325                continue;
326            }
327
328            match self.module.types[global.ty].inner {
329                // We treat images separately because they might require
330                // writing the storage format
331                TypeInner::Image {
332                    mut dim,
333                    arrayed,
334                    class,
335                } => {
336                    // Gather the storage format if needed
337                    let storage_format_access = match self.module.types[global.ty].inner {
338                        TypeInner::Image {
339                            class: crate::ImageClass::Storage { format, access },
340                            ..
341                        } => Some((format, access)),
342                        _ => None,
343                    };
344
345                    if dim == crate::ImageDimension::D1 && es {
346                        dim = crate::ImageDimension::D2
347                    }
348
349                    // Gether the location if needed
350                    let layout_binding = if self.options.version.supports_explicit_locations() {
351                        let br = global.binding.as_ref().unwrap();
352                        self.options.binding_map.get(br).cloned()
353                    } else {
354                        None
355                    };
356
357                    // Write all the layout qualifiers
358                    if layout_binding.is_some() || storage_format_access.is_some() {
359                        write!(self.out, "layout(")?;
360                        if let Some(binding) = layout_binding {
361                            write!(self.out, "binding = {binding}")?;
362                        }
363                        if let Some((format, _)) = storage_format_access {
364                            let format_str = glsl_storage_format(format)?;
365                            let separator = match layout_binding {
366                                Some(_) => ",",
367                                None => "",
368                            };
369                            write!(self.out, "{separator}{format_str}")?;
370                        }
371                        write!(self.out, ") ")?;
372                    }
373
374                    if let Some((_, access)) = storage_format_access {
375                        self.write_storage_access(access)?;
376                    }
377
378                    // All images in glsl are `uniform`
379                    // The trailing space is important
380                    write!(self.out, "uniform ")?;
381
382                    // write the type
383                    //
384                    // This is way we need the leading space because `write_image_type` doesn't add
385                    // any spaces at the beginning or end
386                    self.write_image_type(dim, arrayed, class)?;
387
388                    // Finally write the name and end the global with a `;`
389                    // The leading space is important
390                    let global_name = self.get_global_name(handle, global);
391                    writeln!(self.out, " {global_name};")?;
392                    writeln!(self.out)?;
393
394                    self.reflection_names_globals.insert(handle, global_name);
395                }
396                // glsl has no concept of samplers so we just ignore it
397                TypeInner::Sampler { .. } => continue,
398                // All other globals are written by `write_global`
399                _ => {
400                    self.write_global(handle, global)?;
401                    // Add a newline (only for readability)
402                    writeln!(self.out)?;
403                }
404            }
405        }
406
407        for arg in self.entry_point.function.arguments.iter() {
408            self.write_varying(arg.binding.as_ref(), arg.ty, false)?;
409        }
410        if let Some(ref result) = self.entry_point.function.result {
411            self.write_varying(result.binding.as_ref(), result.ty, true)?;
412        }
413        writeln!(self.out)?;
414
415        // Write all regular functions
416        for (handle, function) in self.module.functions.iter() {
417            // Check that the function doesn't use globals that aren't supported
418            // by the current entry point
419            if !include_unused && !ep_info.dominates_global_use(&self.info[handle]) {
420                continue;
421            }
422
423            let fun_info = &self.info[handle];
424
425            // Skip functions that that are not compatible with this entry point's stage.
426            //
427            // When validation is enabled, it rejects modules whose entry points try to call
428            // incompatible functions, so if we got this far, then any functions incompatible
429            // with our selected entry point must not be used.
430            //
431            // When validation is disabled, `fun_info.available_stages` is always just
432            // `ShaderStages::all()`, so this will write all functions in the module, and
433            // the downstream GLSL compiler will catch any problems.
434            if !fun_info.available_stages.contains(ep_info.available_stages) {
435                continue;
436            }
437
438            // Write the function
439            self.write_function(back::FunctionType::Function(handle), function, fun_info)?;
440
441            writeln!(self.out)?;
442        }
443
444        self.write_function(
445            back::FunctionType::EntryPoint(self.entry_point_idx),
446            &self.entry_point.function,
447            ep_info,
448        )?;
449
450        // Add newline at the end of file
451        writeln!(self.out)?;
452
453        // Collect all reflection info and return it to the user
454        self.collect_reflection_info()
455    }
456
457    fn write_array_size(
458        &mut self,
459        base: Handle<crate::Type>,
460        size: crate::ArraySize,
461    ) -> BackendResult {
462        write!(self.out, "[")?;
463
464        // Write the array size
465        // Writes nothing if `IndexableLength::Dynamic`
466        match size.resolve(self.module.to_ctx())? {
467            proc::IndexableLength::Known(size) => {
468                write!(self.out, "{size}")?;
469            }
470            proc::IndexableLength::Dynamic => (),
471        }
472
473        write!(self.out, "]")?;
474
475        if let TypeInner::Array {
476            base: next_base,
477            size: next_size,
478            ..
479        } = self.module.types[base].inner
480        {
481            self.write_array_size(next_base, next_size)?;
482        }
483
484        Ok(())
485    }
486
487    /// Helper method used to write value types
488    ///
489    /// # Notes
490    /// Adds no trailing or leading whitespace
491    fn write_value_type(&mut self, inner: &TypeInner) -> BackendResult {
492        match *inner {
493            // Scalars are simple we just get the full name from `glsl_scalar`
494            TypeInner::Scalar(scalar)
495            | TypeInner::Atomic(scalar)
496            | TypeInner::ValuePointer {
497                size: None,
498                scalar,
499                space: _,
500            } => write!(self.out, "{}", glsl_scalar(scalar)?.full)?,
501            // Vectors are just `gvecN` where `g` is the scalar prefix and `N` is the vector size
502            TypeInner::Vector { size, scalar }
503            | TypeInner::ValuePointer {
504                size: Some(size),
505                scalar,
506                space: _,
507            } => write!(self.out, "{}vec{}", glsl_scalar(scalar)?.prefix, size as u8)?,
508            // Matrices are written with `gmatMxN` where `g` is the scalar prefix (only floats and
509            // doubles are allowed), `M` is the columns count and `N` is the rows count
510            //
511            // glsl supports a matrix shorthand `gmatN` where `N` = `M` but it doesn't justify the
512            // extra branch to write matrices this way
513            TypeInner::Matrix {
514                columns,
515                rows,
516                scalar,
517            } => write!(
518                self.out,
519                "{}mat{}x{}",
520                glsl_scalar(scalar)?.prefix,
521                columns as u8,
522                rows as u8
523            )?,
524            // GLSL arrays are written as `type name[size]`
525            // Here we only write the size of the array i.e. `[size]`
526            // Base `type` and `name` should be written outside
527            TypeInner::Array { base, size, .. } => self.write_array_size(base, size)?,
528            // Write all variants instead of `_` so that if new variants are added a
529            // no exhaustiveness error is thrown
530            TypeInner::Pointer { .. }
531            | TypeInner::Struct { .. }
532            | TypeInner::Image { .. }
533            | TypeInner::Sampler { .. }
534            | TypeInner::AccelerationStructure { .. }
535            | TypeInner::RayQuery { .. }
536            | TypeInner::BindingArray { .. }
537            | TypeInner::CooperativeMatrix { .. } => {
538                return Err(Error::Custom(format!("Unable to write type {inner:?}")))
539            }
540        }
541
542        Ok(())
543    }
544
545    /// Helper method used to write non image/sampler types
546    ///
547    /// # Notes
548    /// Adds no trailing or leading whitespace
549    fn write_type(&mut self, ty: Handle<crate::Type>) -> BackendResult {
550        match self.module.types[ty].inner {
551            // glsl has no pointer types so just write types as normal and loads are skipped
552            TypeInner::Pointer { base, .. } => self.write_type(base),
553            // glsl structs are written as just the struct name
554            TypeInner::Struct { .. } => {
555                // Get the struct name
556                let name = &self.names[&NameKey::Type(ty)];
557                write!(self.out, "{name}")?;
558                Ok(())
559            }
560            // glsl array has the size separated from the base type
561            TypeInner::Array { base, .. } => self.write_type(base),
562            ref other => self.write_value_type(other),
563        }
564    }
565
566    /// Helper method to write a image type
567    ///
568    /// # Notes
569    /// Adds no leading or trailing whitespace
570    fn write_image_type(
571        &mut self,
572        dim: crate::ImageDimension,
573        arrayed: bool,
574        class: crate::ImageClass,
575    ) -> BackendResult {
576        // glsl images consist of four parts the scalar prefix, the image "type", the dimensions
577        // and modifiers
578        //
579        // There exists two image types
580        // - sampler - for sampled images
581        // - image - for storage images
582        //
583        // There are three possible modifiers that can be used together and must be written in
584        // this order to be valid
585        // - MS - used if it's a multisampled image
586        // - Array - used if it's an image array
587        // - Shadow - used if it's a depth image
588        use crate::ImageClass as Ic;
589        use crate::Scalar as S;
590        let float = S {
591            kind: crate::ScalarKind::Float,
592            width: 4,
593        };
594        let (base, scalar, ms, comparison) = match class {
595            Ic::Sampled { kind, multi: true } => ("sampler", S { kind, width: 4 }, "MS", ""),
596            Ic::Sampled { kind, multi: false } => ("sampler", S { kind, width: 4 }, "", ""),
597            Ic::Depth { multi: true } => ("sampler", float, "MS", ""),
598            Ic::Depth { multi: false } => ("sampler", float, "", "Shadow"),
599            Ic::Storage { format, .. } => ("image", format.into(), "", ""),
600            Ic::External => unimplemented!(),
601        };
602
603        let precision = if self.options.version.is_es() {
604            "highp "
605        } else {
606            ""
607        };
608
609        write!(
610            self.out,
611            "{}{}{}{}{}{}{}",
612            precision,
613            glsl_scalar(scalar)?.prefix,
614            base,
615            glsl_dimension(dim),
616            ms,
617            if arrayed { "Array" } else { "" },
618            comparison
619        )?;
620
621        Ok(())
622    }
623
624    /// Helper method used by [Self::write_global] to write just the layout part of
625    /// a non image/sampler global variable, if applicable.
626    ///
627    /// # Notes
628    ///
629    /// Adds trailing whitespace if any layout qualifier is written
630    fn write_global_layout(&mut self, global: &crate::GlobalVariable) -> BackendResult {
631        // Determine which (if any) explicit memory layout to use, and whether we support it
632        let layout = match global.space {
633            crate::AddressSpace::Uniform => {
634                if !self.options.version.supports_std140_layout() {
635                    return Err(Error::Custom(
636                        "Uniform address space requires std140 layout support".to_string(),
637                    ));
638                }
639
640                Some("std140")
641            }
642            crate::AddressSpace::Storage { .. } => {
643                if !self.options.version.supports_std430_layout() {
644                    return Err(Error::Custom(
645                        "Storage address space requires std430 layout support".to_string(),
646                    ));
647                }
648
649                Some("std430")
650            }
651            _ => None,
652        };
653
654        // If our version supports explicit layouts, we can also output the explicit binding
655        // if we have it
656        if self.options.version.supports_explicit_locations() {
657            if let Some(ref br) = global.binding {
658                match self.options.binding_map.get(br) {
659                    Some(binding) => {
660                        write!(self.out, "layout(")?;
661
662                        if let Some(layout) = layout {
663                            write!(self.out, "{layout}, ")?;
664                        }
665
666                        write!(self.out, "binding = {binding}) ")?;
667
668                        return Ok(());
669                    }
670                    None => {
671                        log::debug!("unassigned binding for {:?}", global.name);
672                    }
673                }
674            }
675        }
676
677        // Either no explicit bindings are supported or we didn't have any.
678        // Write just the memory layout.
679        if let Some(layout) = layout {
680            write!(self.out, "layout({layout}) ")?;
681        }
682
683        Ok(())
684    }
685
686    /// Helper method used to write non images/sampler globals
687    ///
688    /// # Notes
689    /// Adds a newline
690    ///
691    /// # Panics
692    /// If the global has type sampler
693    fn write_global(
694        &mut self,
695        handle: Handle<crate::GlobalVariable>,
696        global: &crate::GlobalVariable,
697    ) -> BackendResult {
698        self.write_global_layout(global)?;
699
700        if let crate::AddressSpace::Storage { access } = global.space {
701            self.write_storage_access(access)?;
702            if global
703                .memory_decorations
704                .contains(crate::MemoryDecorations::COHERENT)
705            {
706                write!(self.out, "coherent ")?;
707            }
708            if global
709                .memory_decorations
710                .contains(crate::MemoryDecorations::VOLATILE)
711            {
712                write!(self.out, "volatile ")?;
713            }
714        }
715
716        if let Some(storage_qualifier) = glsl_storage_qualifier(global.space) {
717            write!(self.out, "{storage_qualifier} ")?;
718        }
719
720        match global.space {
721            crate::AddressSpace::Private => {
722                self.write_simple_global(handle, global)?;
723            }
724            crate::AddressSpace::WorkGroup => {
725                self.write_simple_global(handle, global)?;
726            }
727            crate::AddressSpace::Immediate => {
728                self.write_simple_global(handle, global)?;
729            }
730            crate::AddressSpace::Uniform => {
731                self.write_interface_block(handle, global)?;
732            }
733            crate::AddressSpace::Storage { .. } => {
734                self.write_interface_block(handle, global)?;
735            }
736            crate::AddressSpace::TaskPayload => {
737                self.write_interface_block(handle, global)?;
738            }
739            // A global variable in the `Function` address space is a
740            // contradiction in terms.
741            crate::AddressSpace::Function => unreachable!(),
742            // Textures and samplers are handled directly in `Writer::write`.
743            crate::AddressSpace::Handle => unreachable!(),
744            // ray tracing pipelines unsupported
745            crate::AddressSpace::RayPayload | crate::AddressSpace::IncomingRayPayload => {
746                unreachable!()
747            }
748        }
749
750        Ok(())
751    }
752
753    fn write_simple_global(
754        &mut self,
755        handle: Handle<crate::GlobalVariable>,
756        global: &crate::GlobalVariable,
757    ) -> BackendResult {
758        self.write_type(global.ty)?;
759        write!(self.out, " ")?;
760        self.write_global_name(handle, global)?;
761
762        if let TypeInner::Array { base, size, .. } = self.module.types[global.ty].inner {
763            self.write_array_size(base, size)?;
764        }
765
766        if global.space.initializable() && is_value_init_supported(self.module, global.ty) {
767            write!(self.out, " = ")?;
768            if let Some(init) = global.init {
769                self.write_const_expr(init, &self.module.global_expressions)?;
770            } else {
771                self.write_zero_init_value(global.ty)?;
772            }
773        }
774
775        writeln!(self.out, ";")?;
776
777        if let crate::AddressSpace::Immediate = global.space {
778            let global_name = self.get_global_name(handle, global);
779            self.reflection_names_globals.insert(handle, global_name);
780        }
781
782        Ok(())
783    }
784
785    /// Write an interface block for a single Naga global.
786    ///
787    /// Write `block_name { members }`. Since `block_name` must be unique
788    /// between blocks and structs, we add `_block_ID` where `ID` is a
789    /// `IdGenerator` generated number. Write `members` in the same way we write
790    /// a struct's members.
791    fn write_interface_block(
792        &mut self,
793        handle: Handle<crate::GlobalVariable>,
794        global: &crate::GlobalVariable,
795    ) -> BackendResult {
796        // Write the block name, it's just the struct name appended with `_block_ID`
797        let ty_name = &self.names[&NameKey::Type(global.ty)];
798        let block_name = format!(
799            "{}_block_{}{:?}",
800            // avoid double underscores as they are reserved in GLSL
801            ty_name.trim_end_matches('_'),
802            self.block_id.generate(),
803            self.entry_point.stage,
804        );
805        write!(self.out, "{block_name} ")?;
806        self.reflection_names_globals.insert(handle, block_name);
807
808        match self.module.types[global.ty].inner {
809            TypeInner::Struct { ref members, .. }
810                if self.module.types[members.last().unwrap().ty]
811                    .inner
812                    .is_dynamically_sized(&self.module.types) =>
813            {
814                // Structs with dynamically sized arrays must have their
815                // members lifted up as members of the interface block. GLSL
816                // can't write such struct types anyway.
817                self.write_struct_body(global.ty, members)?;
818                write!(self.out, " ")?;
819                self.write_global_name(handle, global)?;
820            }
821            _ => {
822                // A global of any other type is written as the sole member
823                // of the interface block. Since the interface block is
824                // anonymous, this becomes visible in the global scope.
825                write!(self.out, "{{ ")?;
826                self.write_type(global.ty)?;
827                write!(self.out, " ")?;
828                self.write_global_name(handle, global)?;
829                if let TypeInner::Array { base, size, .. } = self.module.types[global.ty].inner {
830                    self.write_array_size(base, size)?;
831                }
832                write!(self.out, "; }}")?;
833            }
834        }
835
836        writeln!(self.out, ";")?;
837
838        Ok(())
839    }
840
841    /// Helper method used to find which expressions of a given function require baking
842    ///
843    /// # Notes
844    /// Clears `need_bake_expressions` set before adding to it
845    fn update_expressions_to_bake(&mut self, func: &crate::Function, info: &valid::FunctionInfo) {
846        use crate::Expression;
847        self.need_bake_expressions.clear();
848        for (fun_handle, expr) in func.expressions.iter() {
849            let expr_info = &info[fun_handle];
850            let min_ref_count = func.expressions[fun_handle].bake_ref_count();
851            if min_ref_count <= expr_info.ref_count {
852                self.need_bake_expressions.insert(fun_handle);
853            }
854
855            let inner = expr_info.ty.inner_with(&self.module.types);
856
857            if let Expression::Math {
858                fun,
859                arg,
860                arg1,
861                arg2,
862                ..
863            } = *expr
864            {
865                match fun {
866                    crate::MathFunction::Dot => {
867                        // if the expression is a Dot product with integer arguments,
868                        // then the args needs baking as well
869                        if let TypeInner::Scalar(crate::Scalar {
870                            kind: crate::ScalarKind::Sint | crate::ScalarKind::Uint,
871                            ..
872                        }) = *inner
873                        {
874                            self.need_bake_expressions.insert(arg);
875                            self.need_bake_expressions.insert(arg1.unwrap());
876                        }
877                    }
878                    crate::MathFunction::Dot4U8Packed | crate::MathFunction::Dot4I8Packed => {
879                        self.need_bake_expressions.insert(arg);
880                        self.need_bake_expressions.insert(arg1.unwrap());
881                    }
882                    crate::MathFunction::Pack4xI8
883                    | crate::MathFunction::Pack4xU8
884                    | crate::MathFunction::Pack4xI8Clamp
885                    | crate::MathFunction::Pack4xU8Clamp
886                    | crate::MathFunction::Unpack4xI8
887                    | crate::MathFunction::Unpack4xU8
888                    | crate::MathFunction::QuantizeToF16 => {
889                        self.need_bake_expressions.insert(arg);
890                    }
891                    /* crate::MathFunction::Pack4x8unorm | */
892                    crate::MathFunction::Unpack4x8snorm
893                        if !self.options.version.supports_pack_unpack_4x8() =>
894                    {
895                        // We have a fallback if the platform doesn't natively support these
896                        self.need_bake_expressions.insert(arg);
897                    }
898                    /* crate::MathFunction::Pack4x8unorm | */
899                    crate::MathFunction::Unpack4x8unorm
900                        if !self.options.version.supports_pack_unpack_4x8() =>
901                    {
902                        self.need_bake_expressions.insert(arg);
903                    }
904                    /* crate::MathFunction::Pack2x16snorm |  */
905                    crate::MathFunction::Unpack2x16snorm
906                        if !self.options.version.supports_pack_unpack_snorm_2x16() =>
907                    {
908                        self.need_bake_expressions.insert(arg);
909                    }
910                    /* crate::MathFunction::Pack2x16unorm | */
911                    crate::MathFunction::Unpack2x16unorm
912                        if !self.options.version.supports_pack_unpack_unorm_2x16() =>
913                    {
914                        self.need_bake_expressions.insert(arg);
915                    }
916                    crate::MathFunction::ExtractBits => {
917                        // Only argument 1 is re-used.
918                        self.need_bake_expressions.insert(arg1.unwrap());
919                    }
920                    crate::MathFunction::InsertBits => {
921                        // Only argument 2 is re-used.
922                        self.need_bake_expressions.insert(arg2.unwrap());
923                    }
924                    crate::MathFunction::CountLeadingZeros => {
925                        if let Some(crate::ScalarKind::Sint) = inner.scalar_kind() {
926                            self.need_bake_expressions.insert(arg);
927                        }
928                    }
929                    _ => {}
930                }
931            }
932        }
933
934        for statement in func.body.iter() {
935            match *statement {
936                crate::Statement::Atomic {
937                    fun: crate::AtomicFunction::Exchange { compare: Some(cmp) },
938                    ..
939                } => {
940                    self.need_bake_expressions.insert(cmp);
941                }
942                _ => {}
943            }
944        }
945    }
946
947    /// Helper method used to get a name for a global
948    ///
949    /// Globals have different naming schemes depending on their binding:
950    /// - Globals without bindings use the name from the [`Namer`](crate::proc::Namer)
951    /// - Globals with resource binding are named `_group_X_binding_Y` where `X`
952    ///   is the group and `Y` is the binding
953    fn get_global_name(
954        &self,
955        handle: Handle<crate::GlobalVariable>,
956        global: &crate::GlobalVariable,
957    ) -> String {
958        match (&global.binding, global.space) {
959            (&Some(ref br), _) => {
960                format!(
961                    "_group_{}_binding_{}_{}",
962                    br.group,
963                    br.binding,
964                    self.entry_point.stage.to_str()
965                )
966            }
967            (&None, crate::AddressSpace::Immediate) => {
968                format!("_immediates_binding_{}", self.entry_point.stage.to_str())
969            }
970            (&None, _) => self.names[&NameKey::GlobalVariable(handle)].clone(),
971        }
972    }
973
974    /// Helper method used to write a name for a global without additional heap allocation
975    fn write_global_name(
976        &mut self,
977        handle: Handle<crate::GlobalVariable>,
978        global: &crate::GlobalVariable,
979    ) -> BackendResult {
980        match (&global.binding, global.space) {
981            (&Some(ref br), _) => write!(
982                self.out,
983                "_group_{}_binding_{}_{}",
984                br.group,
985                br.binding,
986                self.entry_point.stage.to_str()
987            )?,
988            (&None, crate::AddressSpace::Immediate) => write!(
989                self.out,
990                "_immediates_binding_{}",
991                self.entry_point.stage.to_str()
992            )?,
993            (&None, _) => write!(
994                self.out,
995                "{}",
996                &self.names[&NameKey::GlobalVariable(handle)]
997            )?,
998        }
999
1000        Ok(())
1001    }
1002
1003    /// Write a GLSL global that will carry a Naga entry point's argument or return value.
1004    ///
1005    /// A Naga entry point's arguments and return value are rendered in GLSL as
1006    /// variables at global scope with the `in` and `out` storage qualifiers.
1007    /// The code we generate for `main` loads from all the `in` globals into
1008    /// appropriately named locals. Before it returns, `main` assigns the
1009    /// components of its return value into all the `out` globals.
1010    ///
1011    /// This function writes a declaration for one such GLSL global,
1012    /// representing a value passed into or returned from [`self.entry_point`]
1013    /// that has a [`Location`] binding. The global's name is generated based on
1014    /// the location index and the shader stages being connected; see
1015    /// [`VaryingName`]. This means we don't need to know the names of
1016    /// arguments, just their types and bindings.
1017    ///
1018    /// Emit nothing for entry point arguments or return values with [`BuiltIn`]
1019    /// bindings; `main` will read from or assign to the appropriate GLSL
1020    /// special variable; these are pre-declared. As an exception, we do declare
1021    /// `gl_Position` or `gl_FragCoord` with the `invariant` qualifier if
1022    /// needed.
1023    ///
1024    /// Use `output` together with [`self.entry_point.stage`] to determine which
1025    /// shader stages are being connected, and choose the `in` or `out` storage
1026    /// qualifier.
1027    ///
1028    /// [`self.entry_point`]: Writer::entry_point
1029    /// [`self.entry_point.stage`]: crate::EntryPoint::stage
1030    /// [`Location`]: crate::Binding::Location
1031    /// [`BuiltIn`]: crate::Binding::BuiltIn
1032    fn write_varying(
1033        &mut self,
1034        binding: Option<&crate::Binding>,
1035        ty: Handle<crate::Type>,
1036        output: bool,
1037    ) -> Result<(), Error> {
1038        // For a struct, emit a separate global for each member with a binding.
1039        if let TypeInner::Struct { ref members, .. } = self.module.types[ty].inner {
1040            for member in members {
1041                self.write_varying(member.binding.as_ref(), member.ty, output)?;
1042            }
1043            return Ok(());
1044        }
1045
1046        let binding = match binding {
1047            None => return Ok(()),
1048            Some(binding) => binding,
1049        };
1050
1051        let (location, interpolation, sampling, blend_src) = match *binding {
1052            crate::Binding::Location {
1053                location,
1054                interpolation,
1055                sampling,
1056                blend_src,
1057                per_primitive: _,
1058            } => (location, interpolation, sampling, blend_src),
1059            crate::Binding::BuiltIn(built_in) => {
1060                match built_in {
1061                    crate::BuiltIn::Position { invariant: true } => {
1062                        match (self.options.version, self.entry_point.stage) {
1063                            (
1064                                Version::Embedded {
1065                                    version: 300,
1066                                    is_webgl: true,
1067                                },
1068                                ShaderStage::Fragment,
1069                            ) => {
1070                                // `invariant gl_FragCoord` is not allowed in WebGL2 and possibly
1071                                // OpenGL ES in general (waiting on confirmation).
1072                                //
1073                                // See https://github.com/KhronosGroup/WebGL/issues/3518
1074                            }
1075                            _ => {
1076                                writeln!(
1077                                    self.out,
1078                                    "invariant {};",
1079                                    glsl_built_in(
1080                                        built_in,
1081                                        VaryingOptions::from_writer_options(self.options, output)
1082                                    )
1083                                )?;
1084                            }
1085                        }
1086                    }
1087                    crate::BuiltIn::ClipDistances => {
1088                        // Re-declare `gl_ClipDistance` with number of clip planes.
1089                        let TypeInner::Array { size, .. } = self.module.types[ty].inner else {
1090                            unreachable!();
1091                        };
1092                        let proc::IndexableLength::Known(size) =
1093                            size.resolve(self.module.to_ctx())?
1094                        else {
1095                            unreachable!();
1096                        };
1097                        self.clip_distance_count = size;
1098                        writeln!(self.out, "out float gl_ClipDistance[{size}];")?;
1099                    }
1100                    _ => {}
1101                }
1102                return Ok(());
1103            }
1104        };
1105
1106        // Write the interpolation modifier if needed
1107        //
1108        // We ignore all interpolation and auxiliary modifiers that aren't used in fragment
1109        // shaders' input globals or vertex shaders' output globals.
1110        let emit_interpolation_and_auxiliary = match self.entry_point.stage {
1111            ShaderStage::Vertex => output,
1112            ShaderStage::Fragment => !output,
1113            ShaderStage::Compute => false,
1114            ShaderStage::Task
1115            | ShaderStage::Mesh
1116            | ShaderStage::RayGeneration
1117            | ShaderStage::AnyHit
1118            | ShaderStage::ClosestHit
1119            | ShaderStage::Miss => unreachable!(),
1120        };
1121
1122        // Write the I/O locations, if allowed
1123        let io_location = if self.options.version.supports_explicit_locations()
1124            || !emit_interpolation_and_auxiliary
1125        {
1126            if self.options.version.supports_io_locations() {
1127                if let Some(blend_src) = blend_src {
1128                    write!(
1129                        self.out,
1130                        "layout(location = {location}, index = {blend_src}) "
1131                    )?;
1132                } else {
1133                    write!(self.out, "layout(location = {location}) ")?;
1134                }
1135                None
1136            } else {
1137                Some(VaryingLocation {
1138                    location,
1139                    index: blend_src.unwrap_or(0),
1140                })
1141            }
1142        } else {
1143            None
1144        };
1145
1146        // Write the interpolation qualifier.
1147        if let Some(interp) = interpolation {
1148            if emit_interpolation_and_auxiliary {
1149                write!(self.out, "{} ", glsl_interpolation(interp))?;
1150            }
1151        }
1152
1153        // Write the sampling auxiliary qualifier.
1154        //
1155        // Before GLSL 4.2, the `centroid` and `sample` qualifiers were required to appear
1156        // immediately before the `in` / `out` qualifier, so we'll just follow that rule
1157        // here, regardless of the version.
1158        if let Some(sampling) = sampling {
1159            if emit_interpolation_and_auxiliary {
1160                if let Some(qualifier) = glsl_sampling(sampling)? {
1161                    write!(self.out, "{qualifier} ")?;
1162                }
1163            }
1164        }
1165
1166        // Write the input/output qualifier.
1167        write!(self.out, "{} ", if output { "out" } else { "in" })?;
1168
1169        // Write the type
1170        // `write_type` adds no leading or trailing spaces
1171        self.write_type(ty)?;
1172
1173        // Finally write the global name and end the global with a `;` and a newline
1174        // Leading space is important
1175        let vname = VaryingName {
1176            binding: &crate::Binding::Location {
1177                location,
1178                interpolation: None,
1179                sampling: None,
1180                blend_src,
1181                per_primitive: false,
1182            },
1183            stage: self.entry_point.stage,
1184            options: VaryingOptions::from_writer_options(self.options, output),
1185        };
1186        writeln!(self.out, " {vname};")?;
1187
1188        if let Some(location) = io_location {
1189            self.varying.insert(vname.to_string(), location);
1190        }
1191
1192        Ok(())
1193    }
1194
1195    /// Helper method used to write functions (both entry points and regular functions)
1196    ///
1197    /// # Notes
1198    /// Adds a newline
1199    fn write_function(
1200        &mut self,
1201        ty: back::FunctionType,
1202        func: &crate::Function,
1203        info: &valid::FunctionInfo,
1204    ) -> BackendResult {
1205        // Create a function context for the function being written
1206        let ctx = back::FunctionCtx {
1207            ty,
1208            info,
1209            expressions: &func.expressions,
1210            named_expressions: &func.named_expressions,
1211        };
1212
1213        self.named_expressions.clear();
1214        self.update_expressions_to_bake(func, info);
1215
1216        // Write the function header
1217        //
1218        // glsl headers are the same as in c:
1219        // `ret_type name(args)`
1220        // `ret_type` is the return type
1221        // `name` is the function name
1222        // `args` is a comma separated list of `type name`
1223        //  | - `type` is the argument type
1224        //  | - `name` is the argument name
1225
1226        // Start by writing the return type if any otherwise write void
1227        // This is the only place where `void` is a valid type
1228        // (though it's more a keyword than a type)
1229        if let back::FunctionType::EntryPoint(_) = ctx.ty {
1230            write!(self.out, "void")?;
1231        } else if let Some(ref result) = func.result {
1232            self.write_type(result.ty)?;
1233            if let TypeInner::Array { base, size, .. } = self.module.types[result.ty].inner {
1234                self.write_array_size(base, size)?
1235            }
1236        } else {
1237            write!(self.out, "void")?;
1238        }
1239
1240        // Write the function name and open parentheses for the argument list
1241        let function_name = match ctx.ty {
1242            back::FunctionType::Function(handle) => &self.names[&NameKey::Function(handle)],
1243            back::FunctionType::EntryPoint(_) => "main",
1244        };
1245        write!(self.out, " {function_name}(")?;
1246
1247        // Write the comma separated argument list
1248        //
1249        // We need access to `Self` here so we use the reference passed to the closure as an
1250        // argument instead of capturing as that would cause a borrow checker error
1251        let arguments = match ctx.ty {
1252            back::FunctionType::EntryPoint(_) => &[][..],
1253            back::FunctionType::Function(_) => &func.arguments,
1254        };
1255        let arguments: Vec<_> = arguments
1256            .iter()
1257            .enumerate()
1258            .filter(|&(_, arg)| match self.module.types[arg.ty].inner {
1259                TypeInner::Sampler { .. } => false,
1260                _ => true,
1261            })
1262            .collect();
1263        self.write_slice(&arguments, |this, _, &(i, arg)| {
1264            // Write the argument type
1265            match this.module.types[arg.ty].inner {
1266                // We treat images separately because they might require
1267                // writing the storage format
1268                TypeInner::Image {
1269                    dim,
1270                    arrayed,
1271                    class,
1272                } => {
1273                    // Write the storage format if needed
1274                    if let TypeInner::Image {
1275                        class: crate::ImageClass::Storage { format, .. },
1276                        ..
1277                    } = this.module.types[arg.ty].inner
1278                    {
1279                        write!(this.out, "layout({}) ", glsl_storage_format(format)?)?;
1280                    }
1281
1282                    // write the type
1283                    //
1284                    // This is way we need the leading space because `write_image_type` doesn't add
1285                    // any spaces at the beginning or end
1286                    this.write_image_type(dim, arrayed, class)?;
1287                }
1288                TypeInner::Pointer { base, .. } => {
1289                    // write parameter qualifiers
1290                    write!(this.out, "inout ")?;
1291                    this.write_type(base)?;
1292                }
1293                // All other types are written by `write_type`
1294                _ => {
1295                    this.write_type(arg.ty)?;
1296                }
1297            }
1298
1299            // Write the argument name
1300            // The leading space is important
1301            write!(this.out, " {}", &this.names[&ctx.argument_key(i as u32)])?;
1302
1303            // Write array size
1304            match this.module.types[arg.ty].inner {
1305                TypeInner::Array { base, size, .. } => {
1306                    this.write_array_size(base, size)?;
1307                }
1308                TypeInner::Pointer { base, .. } => {
1309                    if let TypeInner::Array { base, size, .. } = this.module.types[base].inner {
1310                        this.write_array_size(base, size)?;
1311                    }
1312                }
1313                _ => {}
1314            }
1315
1316            Ok(())
1317        })?;
1318
1319        // Close the parentheses and open braces to start the function body
1320        writeln!(self.out, ") {{")?;
1321
1322        if self.options.zero_initialize_workgroup_memory
1323            && ctx.ty.is_compute_like_entry_point(self.module)
1324        {
1325            self.write_workgroup_variables_initialization(&ctx)?;
1326        }
1327
1328        // Compose the function arguments from globals, in case of an entry point.
1329        if let back::FunctionType::EntryPoint(ep_index) = ctx.ty {
1330            let stage = self.module.entry_points[ep_index as usize].stage;
1331            for (index, arg) in func.arguments.iter().enumerate() {
1332                write!(self.out, "{}", back::INDENT)?;
1333                self.write_type(arg.ty)?;
1334                let name = &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)];
1335                write!(self.out, " {name}")?;
1336                write!(self.out, " = ")?;
1337                match self.module.types[arg.ty].inner {
1338                    TypeInner::Struct { ref members, .. } => {
1339                        self.write_type(arg.ty)?;
1340                        write!(self.out, "(")?;
1341                        for (index, member) in members.iter().enumerate() {
1342                            let varying_name = VaryingName {
1343                                binding: member.binding.as_ref().unwrap(),
1344                                stage,
1345                                options: VaryingOptions::from_writer_options(self.options, false),
1346                            };
1347                            if index != 0 {
1348                                write!(self.out, ", ")?;
1349                            }
1350                            write!(self.out, "{varying_name}")?;
1351                        }
1352                        writeln!(self.out, ");")?;
1353                    }
1354                    _ => {
1355                        let varying_name = VaryingName {
1356                            binding: arg.binding.as_ref().unwrap(),
1357                            stage,
1358                            options: VaryingOptions::from_writer_options(self.options, false),
1359                        };
1360                        writeln!(self.out, "{varying_name};")?;
1361                    }
1362                }
1363            }
1364        }
1365
1366        // Write all function locals
1367        // Locals are `type name (= init)?;` where the init part (including the =) are optional
1368        //
1369        // Always adds a newline
1370        for (handle, local) in func.local_variables.iter() {
1371            // Write indentation (only for readability) and the type
1372            // `write_type` adds no trailing space
1373            write!(self.out, "{}", back::INDENT)?;
1374            self.write_type(local.ty)?;
1375
1376            // Write the local name
1377            // The leading space is important
1378            write!(self.out, " {}", self.names[&ctx.name_key(handle)])?;
1379            // Write size for array type
1380            if let TypeInner::Array { base, size, .. } = self.module.types[local.ty].inner {
1381                self.write_array_size(base, size)?;
1382            }
1383            // Write the local initializer if needed
1384            if let Some(init) = local.init {
1385                // Put the equal signal only if there's a initializer
1386                // The leading and trailing spaces aren't needed but help with readability
1387                write!(self.out, " = ")?;
1388
1389                // Write the constant
1390                // `write_constant` adds no trailing or leading space/newline
1391                self.write_expr(init, &ctx)?;
1392            } else if is_value_init_supported(self.module, local.ty) {
1393                write!(self.out, " = ")?;
1394                self.write_zero_init_value(local.ty)?;
1395            }
1396
1397            // Finish the local with `;` and add a newline (only for readability)
1398            writeln!(self.out, ";")?
1399        }
1400
1401        // Write the function body (statement list)
1402        for sta in func.body.iter() {
1403            // Write a statement, the indentation should always be 1 when writing the function body
1404            // `write_stmt` adds a newline
1405            self.write_stmt(sta, &ctx, back::Level(1))?;
1406        }
1407
1408        // Close braces and add a newline
1409        writeln!(self.out, "}}")?;
1410
1411        Ok(())
1412    }
1413
1414    fn write_workgroup_variables_initialization(
1415        &mut self,
1416        ctx: &back::FunctionCtx,
1417    ) -> BackendResult {
1418        let mut vars = self
1419            .module
1420            .global_variables
1421            .iter()
1422            .filter(|&(handle, var)| {
1423                !ctx.info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup
1424            })
1425            .peekable();
1426
1427        if vars.peek().is_some() {
1428            let level = back::Level(1);
1429
1430            writeln!(self.out, "{level}if (gl_LocalInvocationID == uvec3(0u)) {{")?;
1431
1432            for (handle, var) in vars {
1433                let name = &self.names[&NameKey::GlobalVariable(handle)];
1434                write!(self.out, "{}{} = ", level.next(), name)?;
1435                self.write_zero_init_value(var.ty)?;
1436                writeln!(self.out, ";")?;
1437            }
1438
1439            writeln!(self.out, "{level}}}")?;
1440            self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?;
1441        }
1442
1443        Ok(())
1444    }
1445
1446    /// Write a list of comma separated `T` values using a writer function `F`.
1447    ///
1448    /// The writer function `F` receives a mutable reference to `self` that if needed won't cause
1449    /// borrow checker issues (using for example a closure with `self` will cause issues), the
1450    /// second argument is the 0 based index of the element on the list, and the last element is
1451    /// a reference to the element `T` being written
1452    ///
1453    /// # Notes
1454    /// - Adds no newlines or leading/trailing whitespace
1455    /// - The last element won't have a trailing `,`
1456    fn write_slice<T, F: FnMut(&mut Self, u32, &T) -> BackendResult>(
1457        &mut self,
1458        data: &[T],
1459        mut f: F,
1460    ) -> BackendResult {
1461        // Loop through `data` invoking `f` for each element
1462        for (index, item) in data.iter().enumerate() {
1463            if index != 0 {
1464                write!(self.out, ", ")?;
1465            }
1466            f(self, index as u32, item)?;
1467        }
1468
1469        Ok(())
1470    }
1471
1472    /// Helper method used to write global constants
1473    fn write_global_constant(&mut self, handle: Handle<crate::Constant>) -> BackendResult {
1474        write!(self.out, "const ")?;
1475        let constant = &self.module.constants[handle];
1476        self.write_type(constant.ty)?;
1477        let name = &self.names[&NameKey::Constant(handle)];
1478        write!(self.out, " {name}")?;
1479        if let TypeInner::Array { base, size, .. } = self.module.types[constant.ty].inner {
1480            self.write_array_size(base, size)?;
1481        }
1482        write!(self.out, " = ")?;
1483        self.write_const_expr(constant.init, &self.module.global_expressions)?;
1484        writeln!(self.out, ";")?;
1485        Ok(())
1486    }
1487
1488    /// Helper method used to output a dot product as an arithmetic expression
1489    ///
1490    fn write_dot_product(
1491        &mut self,
1492        arg: Handle<crate::Expression>,
1493        arg1: Handle<crate::Expression>,
1494        size: usize,
1495        ctx: &back::FunctionCtx,
1496    ) -> BackendResult {
1497        // Write parentheses around the dot product expression to prevent operators
1498        // with different precedences from applying earlier.
1499        write!(self.out, "(")?;
1500
1501        // Cycle through all the components of the vector
1502        for index in 0..size {
1503            let component = back::COMPONENTS[index];
1504            // Write the addition to the previous product
1505            // This will print an extra '+' at the beginning but that is fine in glsl
1506            write!(self.out, " + ")?;
1507            // Write the first vector expression, this expression is marked to be
1508            // cached so unless it can't be cached (for example, it's a Constant)
1509            // it shouldn't produce large expressions.
1510            self.write_expr(arg, ctx)?;
1511            // Access the current component on the first vector
1512            write!(self.out, ".{component} * ")?;
1513            // Write the second vector expression, this expression is marked to be
1514            // cached so unless it can't be cached (for example, it's a Constant)
1515            // it shouldn't produce large expressions.
1516            self.write_expr(arg1, ctx)?;
1517            // Access the current component on the second vector
1518            write!(self.out, ".{component}")?;
1519        }
1520
1521        write!(self.out, ")")?;
1522        Ok(())
1523    }
1524
1525    /// Helper method used to write structs
1526    ///
1527    /// # Notes
1528    /// Ends in a newline
1529    fn write_struct_body(
1530        &mut self,
1531        handle: Handle<crate::Type>,
1532        members: &[crate::StructMember],
1533    ) -> BackendResult {
1534        // glsl structs are written as in C
1535        // `struct name() { members };`
1536        //  | `struct` is a keyword
1537        //  | `name` is the struct name
1538        //  | `members` is a semicolon separated list of `type name`
1539        //      | `type` is the member type
1540        //      | `name` is the member name
1541        writeln!(self.out, "{{")?;
1542
1543        for (idx, member) in members.iter().enumerate() {
1544            // The indentation is only for readability
1545            write!(self.out, "{}", back::INDENT)?;
1546
1547            match self.module.types[member.ty].inner {
1548                TypeInner::Array {
1549                    base,
1550                    size,
1551                    stride: _,
1552                } => {
1553                    self.write_type(base)?;
1554                    write!(
1555                        self.out,
1556                        " {}",
1557                        &self.names[&NameKey::StructMember(handle, idx as u32)]
1558                    )?;
1559                    // Write [size]
1560                    self.write_array_size(base, size)?;
1561                    // Newline is important
1562                    writeln!(self.out, ";")?;
1563                }
1564                _ => {
1565                    // Write the member type
1566                    // Adds no trailing space
1567                    self.write_type(member.ty)?;
1568
1569                    // Write the member name and put a semicolon
1570                    // The leading space is important
1571                    // All members must have a semicolon even the last one
1572                    writeln!(
1573                        self.out,
1574                        " {};",
1575                        &self.names[&NameKey::StructMember(handle, idx as u32)]
1576                    )?;
1577                }
1578            }
1579        }
1580
1581        write!(self.out, "}}")?;
1582        Ok(())
1583    }
1584
1585    /// Helper method used to write statements
1586    ///
1587    /// # Notes
1588    /// Always adds a newline
1589    fn write_stmt(
1590        &mut self,
1591        sta: &crate::Statement,
1592        ctx: &back::FunctionCtx,
1593        level: back::Level,
1594    ) -> BackendResult {
1595        use crate::Statement;
1596
1597        match *sta {
1598            // This is where we can generate intermediate constants for some expression types.
1599            Statement::Emit(ref range) => {
1600                for handle in range.clone() {
1601                    let ptr_class = ctx.resolve_type(handle, &self.module.types).pointer_space();
1602                    let expr_name = if ptr_class.is_some() {
1603                        // GLSL can't save a pointer-valued expression in a variable,
1604                        // but we shouldn't ever need to: they should never be named expressions,
1605                        // and none of the expression types flagged by bake_ref_count can be pointer-valued.
1606                        None
1607                    } else if let Some(name) = ctx.named_expressions.get(&handle) {
1608                        // Front end provides names for all variables at the start of writing.
1609                        // But we write them to step by step. We need to recache them
1610                        // Otherwise, we could accidentally write variable name instead of full expression.
1611                        // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords.
1612                        Some(self.namer.call(name))
1613                    } else if self.need_bake_expressions.contains(&handle) {
1614                        Some(Baked(handle).to_string())
1615                    } else {
1616                        None
1617                    };
1618
1619                    // If we are going to write an `ImageLoad` next and the target image
1620                    // is sampled and we are using the `Restrict` policy for bounds
1621                    // checking images we need to write a local holding the clamped lod.
1622                    if let crate::Expression::ImageLoad {
1623                        image,
1624                        level: Some(level_expr),
1625                        ..
1626                    } = ctx.expressions[handle]
1627                    {
1628                        if let TypeInner::Image {
1629                            class: crate::ImageClass::Sampled { .. },
1630                            ..
1631                        } = *ctx.resolve_type(image, &self.module.types)
1632                        {
1633                            if let proc::BoundsCheckPolicy::Restrict = self.policies.image_load {
1634                                write!(self.out, "{level}")?;
1635                                self.write_clamped_lod(ctx, handle, image, level_expr)?
1636                            }
1637                        }
1638                    }
1639
1640                    if let Some(name) = expr_name {
1641                        write!(self.out, "{level}")?;
1642                        self.write_named_expr(handle, name, handle, ctx)?;
1643                    }
1644                }
1645            }
1646            // Blocks are simple we just need to write the block statements between braces
1647            // We could also just print the statements but this is more readable and maps more
1648            // closely to the IR
1649            Statement::Block(ref block) => {
1650                write!(self.out, "{level}")?;
1651                writeln!(self.out, "{{")?;
1652                for sta in block.iter() {
1653                    // Increase the indentation to help with readability
1654                    self.write_stmt(sta, ctx, level.next())?
1655                }
1656                writeln!(self.out, "{level}}}")?
1657            }
1658            // Ifs are written as in C:
1659            // ```
1660            // if(condition) {
1661            //  accept
1662            // } else {
1663            //  reject
1664            // }
1665            // ```
1666            Statement::If {
1667                condition,
1668                ref accept,
1669                ref reject,
1670            } => {
1671                write!(self.out, "{level}")?;
1672                write!(self.out, "if (")?;
1673                self.write_expr(condition, ctx)?;
1674                writeln!(self.out, ") {{")?;
1675
1676                for sta in accept {
1677                    // Increase indentation to help with readability
1678                    self.write_stmt(sta, ctx, level.next())?;
1679                }
1680
1681                // If there are no statements in the reject block we skip writing it
1682                // This is only for readability
1683                if !reject.is_empty() {
1684                    writeln!(self.out, "{level}}} else {{")?;
1685
1686                    for sta in reject {
1687                        // Increase indentation to help with readability
1688                        self.write_stmt(sta, ctx, level.next())?;
1689                    }
1690                }
1691
1692                writeln!(self.out, "{level}}}")?
1693            }
1694            // Switch are written as in C:
1695            // ```
1696            // switch (selector) {
1697            //      // Fallthrough
1698            //      case label:
1699            //          block
1700            //      // Non fallthrough
1701            //      case label:
1702            //          block
1703            //          break;
1704            //      default:
1705            //          block
1706            //  }
1707            //  ```
1708            //  Where the `default` case happens isn't important but we put it last
1709            //  so that we don't need to print a `break` for it
1710            Statement::Switch {
1711                selector,
1712                ref cases,
1713            } => {
1714                let l2 = level.next();
1715                // Some GLSL consumers may not handle switches with a single
1716                // body correctly: See wgpu#4514. Write such switch statements
1717                // as a `do {} while(false);` loop instead.
1718                //
1719                // Since doing so may inadvertently capture `continue`
1720                // statements in the switch body, we must apply continue
1721                // forwarding. See the `naga::back::continue_forward` module
1722                // docs for details.
1723                let one_body = cases
1724                    .iter()
1725                    .rev()
1726                    .skip(1)
1727                    .all(|case| case.fall_through && case.body.is_empty());
1728                if one_body {
1729                    // Unlike HLSL, in GLSL `continue_ctx` only needs to know
1730                    // about [`Switch`] statements that are being rendered as
1731                    // `do-while` loops.
1732                    if let Some(variable) = self.continue_ctx.enter_switch(&mut self.namer) {
1733                        writeln!(self.out, "{level}bool {variable} = false;",)?;
1734                    };
1735                    writeln!(self.out, "{level}do {{")?;
1736                    // Note: Expressions have no side-effects so we don't need to emit selector expression.
1737
1738                    // Body
1739                    if let Some(case) = cases.last() {
1740                        for sta in case.body.iter() {
1741                            self.write_stmt(sta, ctx, l2)?;
1742                        }
1743                    }
1744                    // End do-while
1745                    writeln!(self.out, "{level}}} while(false);")?;
1746
1747                    // Handle any forwarded continue statements.
1748                    use back::continue_forward::ExitControlFlow;
1749                    let op = match self.continue_ctx.exit_switch() {
1750                        ExitControlFlow::None => None,
1751                        ExitControlFlow::Continue { variable } => Some(("continue", variable)),
1752                        ExitControlFlow::Break { variable } => Some(("break", variable)),
1753                    };
1754                    if let Some((control_flow, variable)) = op {
1755                        writeln!(self.out, "{level}if ({variable}) {{")?;
1756                        writeln!(self.out, "{l2}{control_flow};")?;
1757                        writeln!(self.out, "{level}}}")?;
1758                    }
1759                } else {
1760                    // Start the switch
1761                    write!(self.out, "{level}")?;
1762                    write!(self.out, "switch(")?;
1763                    self.write_expr(selector, ctx)?;
1764                    writeln!(self.out, ") {{")?;
1765
1766                    // Write all cases
1767                    for case in cases {
1768                        match case.value {
1769                            crate::SwitchValue::I32(value) => {
1770                                write!(self.out, "{l2}case {value}:")?
1771                            }
1772                            crate::SwitchValue::U32(value) => {
1773                                write!(self.out, "{l2}case {value}u:")?
1774                            }
1775                            crate::SwitchValue::Default => write!(self.out, "{l2}default:")?,
1776                        }
1777
1778                        let write_block_braces = !(case.fall_through && case.body.is_empty());
1779                        if write_block_braces {
1780                            writeln!(self.out, " {{")?;
1781                        } else {
1782                            writeln!(self.out)?;
1783                        }
1784
1785                        for sta in case.body.iter() {
1786                            self.write_stmt(sta, ctx, l2.next())?;
1787                        }
1788
1789                        if !case.fall_through && case.body.last().is_none_or(|s| !s.is_terminator())
1790                        {
1791                            writeln!(self.out, "{}break;", l2.next())?;
1792                        }
1793
1794                        if write_block_braces {
1795                            writeln!(self.out, "{l2}}}")?;
1796                        }
1797                    }
1798
1799                    writeln!(self.out, "{level}}}")?
1800                }
1801            }
1802            // Loops in naga IR are based on wgsl loops, glsl can emulate the behaviour by using a
1803            // while true loop and appending the continuing block to the body resulting on:
1804            // ```
1805            // bool loop_init = true;
1806            // while(true) {
1807            //  if (!loop_init) { <continuing> }
1808            //  loop_init = false;
1809            //  <body>
1810            // }
1811            // ```
1812            Statement::Loop {
1813                ref body,
1814                ref continuing,
1815                break_if,
1816            } => {
1817                self.continue_ctx.enter_loop();
1818                if !continuing.is_empty() || break_if.is_some() {
1819                    let gate_name = self.namer.call("loop_init");
1820                    writeln!(self.out, "{level}bool {gate_name} = true;")?;
1821                    writeln!(self.out, "{level}while(true) {{")?;
1822                    let l2 = level.next();
1823                    let l3 = l2.next();
1824                    writeln!(self.out, "{l2}if (!{gate_name}) {{")?;
1825                    for sta in continuing {
1826                        self.write_stmt(sta, ctx, l3)?;
1827                    }
1828                    if let Some(condition) = break_if {
1829                        write!(self.out, "{l3}if (")?;
1830                        self.write_expr(condition, ctx)?;
1831                        writeln!(self.out, ") {{")?;
1832                        writeln!(self.out, "{}break;", l3.next())?;
1833                        writeln!(self.out, "{l3}}}")?;
1834                    }
1835                    writeln!(self.out, "{l2}}}")?;
1836                    writeln!(self.out, "{}{} = false;", level.next(), gate_name)?;
1837                } else {
1838                    writeln!(self.out, "{level}while(true) {{")?;
1839                }
1840                for sta in body {
1841                    self.write_stmt(sta, ctx, level.next())?;
1842                }
1843                writeln!(self.out, "{level}}}")?;
1844                self.continue_ctx.exit_loop();
1845            }
1846            // Break, continue and return as written as in C
1847            // `break;`
1848            Statement::Break => {
1849                write!(self.out, "{level}")?;
1850                writeln!(self.out, "break;")?
1851            }
1852            // `continue;`
1853            Statement::Continue => {
1854                // Sometimes we must render a `Continue` statement as a `break`.
1855                // See the docs for the `back::continue_forward` module.
1856                if let Some(variable) = self.continue_ctx.continue_encountered() {
1857                    writeln!(self.out, "{level}{variable} = true;",)?;
1858                    writeln!(self.out, "{level}break;")?
1859                } else {
1860                    writeln!(self.out, "{level}continue;")?
1861                }
1862            }
1863            // `return expr;`, `expr` is optional
1864            Statement::Return { value } => {
1865                write!(self.out, "{level}")?;
1866                match ctx.ty {
1867                    back::FunctionType::Function(_) => {
1868                        write!(self.out, "return")?;
1869                        // Write the expression to be returned if needed
1870                        if let Some(expr) = value {
1871                            write!(self.out, " ")?;
1872                            self.write_expr(expr, ctx)?;
1873                        }
1874                        writeln!(self.out, ";")?;
1875                    }
1876                    back::FunctionType::EntryPoint(ep_index) => {
1877                        let mut has_point_size = false;
1878                        let ep = &self.module.entry_points[ep_index as usize];
1879                        if let Some(ref result) = ep.function.result {
1880                            let value = value.unwrap();
1881                            match self.module.types[result.ty].inner {
1882                                TypeInner::Struct { ref members, .. } => {
1883                                    let temp_struct_name = match ctx.expressions[value] {
1884                                        crate::Expression::Compose { .. } => {
1885                                            let return_struct = "_tmp_return";
1886                                            write!(
1887                                                self.out,
1888                                                "{} {} = ",
1889                                                &self.names[&NameKey::Type(result.ty)],
1890                                                return_struct
1891                                            )?;
1892                                            self.write_expr(value, ctx)?;
1893                                            writeln!(self.out, ";")?;
1894                                            write!(self.out, "{level}")?;
1895                                            Some(return_struct)
1896                                        }
1897                                        _ => None,
1898                                    };
1899
1900                                    for (index, member) in members.iter().enumerate() {
1901                                        if let Some(crate::Binding::BuiltIn(
1902                                            crate::BuiltIn::PointSize,
1903                                        )) = member.binding
1904                                        {
1905                                            has_point_size = true;
1906                                        }
1907
1908                                        let varying_name = VaryingName {
1909                                            binding: member.binding.as_ref().unwrap(),
1910                                            stage: ep.stage,
1911                                            options: VaryingOptions::from_writer_options(
1912                                                self.options,
1913                                                true,
1914                                            ),
1915                                        };
1916                                        write!(self.out, "{varying_name} = ")?;
1917
1918                                        if let Some(struct_name) = temp_struct_name {
1919                                            write!(self.out, "{struct_name}")?;
1920                                        } else {
1921                                            self.write_expr(value, ctx)?;
1922                                        }
1923
1924                                        // Write field name
1925                                        writeln!(
1926                                            self.out,
1927                                            ".{};",
1928                                            &self.names
1929                                                [&NameKey::StructMember(result.ty, index as u32)]
1930                                        )?;
1931                                        write!(self.out, "{level}")?;
1932                                    }
1933                                }
1934                                _ => {
1935                                    let name = VaryingName {
1936                                        binding: result.binding.as_ref().unwrap(),
1937                                        stage: ep.stage,
1938                                        options: VaryingOptions::from_writer_options(
1939                                            self.options,
1940                                            true,
1941                                        ),
1942                                    };
1943                                    write!(self.out, "{name} = ")?;
1944                                    self.write_expr(value, ctx)?;
1945                                    writeln!(self.out, ";")?;
1946                                    write!(self.out, "{level}")?;
1947                                }
1948                            }
1949                        }
1950
1951                        let is_vertex_stage = self.module.entry_points[ep_index as usize].stage
1952                            == ShaderStage::Vertex;
1953                        if is_vertex_stage
1954                            && self
1955                                .options
1956                                .writer_flags
1957                                .contains(WriterFlags::ADJUST_COORDINATE_SPACE)
1958                        {
1959                            writeln!(
1960                                self.out,
1961                                "gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w);",
1962                            )?;
1963                            write!(self.out, "{level}")?;
1964                        }
1965
1966                        if is_vertex_stage
1967                            && self
1968                                .options
1969                                .writer_flags
1970                                .contains(WriterFlags::FORCE_POINT_SIZE)
1971                            && !has_point_size
1972                        {
1973                            writeln!(self.out, "gl_PointSize = 1.0;")?;
1974                            write!(self.out, "{level}")?;
1975                        }
1976                        writeln!(self.out, "return;")?;
1977                    }
1978                }
1979            }
1980            // This is one of the places were glsl adds to the syntax of C in this case the discard
1981            // keyword which ceases all further processing in a fragment shader, it's called OpKill
1982            // in spir-v that's why it's called `Statement::Kill`
1983            Statement::Kill => writeln!(self.out, "{level}discard;")?,
1984            Statement::ControlBarrier(flags) => {
1985                self.write_control_barrier(flags, level)?;
1986            }
1987            Statement::MemoryBarrier(flags) => {
1988                self.write_memory_barrier(flags, level)?;
1989            }
1990            // Stores in glsl are just variable assignments written as `pointer = value;`
1991            Statement::Store { pointer, value } => {
1992                write!(self.out, "{level}")?;
1993                self.write_expr(pointer, ctx)?;
1994                write!(self.out, " = ")?;
1995                self.write_expr(value, ctx)?;
1996                writeln!(self.out, ";")?
1997            }
1998            Statement::WorkGroupUniformLoad { pointer, result } => {
1999                // GLSL doesn't have pointers, which means that this backend needs to ensure that
2000                // the actual "loading" is happening between the two barriers.
2001                // This is done in `Emit` by never emitting a variable name for pointer variables
2002                self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?;
2003
2004                let result_name = Baked(result).to_string();
2005                write!(self.out, "{level}")?;
2006                // Expressions cannot have side effects, so just writing the expression here is fine.
2007                self.write_named_expr(pointer, result_name, result, ctx)?;
2008
2009                self.write_control_barrier(crate::Barrier::WORK_GROUP, level)?;
2010            }
2011            // Stores a value into an image.
2012            Statement::ImageStore {
2013                image,
2014                coordinate,
2015                array_index,
2016                value,
2017            } => {
2018                write!(self.out, "{level}")?;
2019                self.write_image_store(ctx, image, coordinate, array_index, value)?
2020            }
2021            // A `Call` is written `name(arguments)` where `arguments` is a comma separated expressions list
2022            Statement::Call {
2023                function,
2024                ref arguments,
2025                result,
2026            } => {
2027                write!(self.out, "{level}")?;
2028                if let Some(expr) = result {
2029                    let name = Baked(expr).to_string();
2030                    let result = self.module.functions[function].result.as_ref().unwrap();
2031                    self.write_type(result.ty)?;
2032                    write!(self.out, " {name}")?;
2033                    if let TypeInner::Array { base, size, .. } = self.module.types[result.ty].inner
2034                    {
2035                        self.write_array_size(base, size)?
2036                    }
2037                    write!(self.out, " = ")?;
2038                    self.named_expressions.insert(expr, name);
2039                }
2040                write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?;
2041                let arguments: Vec<_> = arguments
2042                    .iter()
2043                    .enumerate()
2044                    .filter_map(|(i, arg)| {
2045                        let arg_ty = self.module.functions[function].arguments[i].ty;
2046                        match self.module.types[arg_ty].inner {
2047                            TypeInner::Sampler { .. } => None,
2048                            _ => Some(*arg),
2049                        }
2050                    })
2051                    .collect();
2052                self.write_slice(&arguments, |this, _, arg| this.write_expr(*arg, ctx))?;
2053                writeln!(self.out, ");")?
2054            }
2055            Statement::Atomic {
2056                pointer,
2057                ref fun,
2058                value,
2059                result,
2060            } => {
2061                write!(self.out, "{level}")?;
2062
2063                match *fun {
2064                    crate::AtomicFunction::Exchange {
2065                        compare: Some(compare_expr),
2066                    } => {
2067                        let result_handle = result.expect("CompareExchange must have a result");
2068                        let res_name = Baked(result_handle).to_string();
2069                        self.write_type(ctx.info[result_handle].ty.handle().unwrap())?;
2070                        write!(self.out, " {res_name};")?;
2071                        write!(self.out, " {res_name}.old_value = atomicCompSwap(")?;
2072                        self.write_expr(pointer, ctx)?;
2073                        write!(self.out, ", ")?;
2074                        self.write_expr(compare_expr, ctx)?;
2075                        write!(self.out, ", ")?;
2076                        self.write_expr(value, ctx)?;
2077                        writeln!(self.out, ");")?;
2078
2079                        write!(
2080                            self.out,
2081                            "{level}{res_name}.exchanged = ({res_name}.old_value == "
2082                        )?;
2083                        self.write_expr(compare_expr, ctx)?;
2084                        writeln!(self.out, ");")?;
2085                        self.named_expressions.insert(result_handle, res_name);
2086                    }
2087                    _ => {
2088                        if let Some(result) = result {
2089                            let res_name = Baked(result).to_string();
2090                            self.write_type(ctx.info[result].ty.handle().unwrap())?;
2091                            write!(self.out, " {res_name} = ")?;
2092                            self.named_expressions.insert(result, res_name);
2093                        }
2094                        let fun_str = fun.to_glsl();
2095                        write!(self.out, "atomic{fun_str}(")?;
2096                        self.write_expr(pointer, ctx)?;
2097                        write!(self.out, ", ")?;
2098                        if let crate::AtomicFunction::Subtract = *fun {
2099                            // Emulate `atomicSub` with `atomicAdd` by negating the value.
2100                            write!(self.out, "-")?;
2101                        }
2102                        self.write_expr(value, ctx)?;
2103                        writeln!(self.out, ");")?;
2104                    }
2105                }
2106            }
2107            // Stores a value into an image.
2108            Statement::ImageAtomic {
2109                image,
2110                coordinate,
2111                array_index,
2112                fun,
2113                value,
2114            } => {
2115                write!(self.out, "{level}")?;
2116                self.write_image_atomic(ctx, image, coordinate, array_index, fun, value)?
2117            }
2118            Statement::RayQuery { .. } => unreachable!(),
2119            Statement::SubgroupBallot { result, predicate } => {
2120                write!(self.out, "{level}")?;
2121                let res_name = Baked(result).to_string();
2122                let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
2123                self.write_value_type(res_ty)?;
2124                write!(self.out, " {res_name} = ")?;
2125                self.named_expressions.insert(result, res_name);
2126
2127                write!(self.out, "subgroupBallot(")?;
2128                match predicate {
2129                    Some(predicate) => self.write_expr(predicate, ctx)?,
2130                    None => write!(self.out, "true")?,
2131                }
2132                writeln!(self.out, ");")?;
2133            }
2134            Statement::SubgroupCollectiveOperation {
2135                op,
2136                collective_op,
2137                argument,
2138                result,
2139            } => {
2140                write!(self.out, "{level}")?;
2141                let res_name = Baked(result).to_string();
2142                let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
2143                self.write_value_type(res_ty)?;
2144                write!(self.out, " {res_name} = ")?;
2145                self.named_expressions.insert(result, res_name);
2146
2147                match (collective_op, op) {
2148                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::All) => {
2149                        write!(self.out, "subgroupAll(")?
2150                    }
2151                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Any) => {
2152                        write!(self.out, "subgroupAny(")?
2153                    }
2154                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Add) => {
2155                        write!(self.out, "subgroupAdd(")?
2156                    }
2157                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Mul) => {
2158                        write!(self.out, "subgroupMul(")?
2159                    }
2160                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Max) => {
2161                        write!(self.out, "subgroupMax(")?
2162                    }
2163                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Min) => {
2164                        write!(self.out, "subgroupMin(")?
2165                    }
2166                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::And) => {
2167                        write!(self.out, "subgroupAnd(")?
2168                    }
2169                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Or) => {
2170                        write!(self.out, "subgroupOr(")?
2171                    }
2172                    (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Xor) => {
2173                        write!(self.out, "subgroupXor(")?
2174                    }
2175                    (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Add) => {
2176                        write!(self.out, "subgroupExclusiveAdd(")?
2177                    }
2178                    (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Mul) => {
2179                        write!(self.out, "subgroupExclusiveMul(")?
2180                    }
2181                    (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Add) => {
2182                        write!(self.out, "subgroupInclusiveAdd(")?
2183                    }
2184                    (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Mul) => {
2185                        write!(self.out, "subgroupInclusiveMul(")?
2186                    }
2187                    _ => unimplemented!(),
2188                }
2189                self.write_expr(argument, ctx)?;
2190                writeln!(self.out, ");")?;
2191            }
2192            Statement::SubgroupGather {
2193                mode,
2194                argument,
2195                result,
2196            } => {
2197                write!(self.out, "{level}")?;
2198                let res_name = Baked(result).to_string();
2199                let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
2200                self.write_value_type(res_ty)?;
2201                write!(self.out, " {res_name} = ")?;
2202                self.named_expressions.insert(result, res_name);
2203
2204                match mode {
2205                    crate::GatherMode::BroadcastFirst => {
2206                        write!(self.out, "subgroupBroadcastFirst(")?;
2207                    }
2208                    crate::GatherMode::Broadcast(_) => {
2209                        write!(self.out, "subgroupBroadcast(")?;
2210                    }
2211                    crate::GatherMode::Shuffle(_) => {
2212                        write!(self.out, "subgroupShuffle(")?;
2213                    }
2214                    crate::GatherMode::ShuffleDown(_) => {
2215                        write!(self.out, "subgroupShuffleDown(")?;
2216                    }
2217                    crate::GatherMode::ShuffleUp(_) => {
2218                        write!(self.out, "subgroupShuffleUp(")?;
2219                    }
2220                    crate::GatherMode::ShuffleXor(_) => {
2221                        write!(self.out, "subgroupShuffleXor(")?;
2222                    }
2223                    crate::GatherMode::QuadBroadcast(_) => {
2224                        write!(self.out, "subgroupQuadBroadcast(")?;
2225                    }
2226                    crate::GatherMode::QuadSwap(direction) => match direction {
2227                        crate::Direction::X => {
2228                            write!(self.out, "subgroupQuadSwapHorizontal(")?;
2229                        }
2230                        crate::Direction::Y => {
2231                            write!(self.out, "subgroupQuadSwapVertical(")?;
2232                        }
2233                        crate::Direction::Diagonal => {
2234                            write!(self.out, "subgroupQuadSwapDiagonal(")?;
2235                        }
2236                    },
2237                }
2238                self.write_expr(argument, ctx)?;
2239                match mode {
2240                    crate::GatherMode::BroadcastFirst => {}
2241                    crate::GatherMode::Broadcast(index)
2242                    | crate::GatherMode::Shuffle(index)
2243                    | crate::GatherMode::ShuffleDown(index)
2244                    | crate::GatherMode::ShuffleUp(index)
2245                    | crate::GatherMode::ShuffleXor(index)
2246                    | crate::GatherMode::QuadBroadcast(index) => {
2247                        write!(self.out, ", ")?;
2248                        self.write_expr(index, ctx)?;
2249                    }
2250                    crate::GatherMode::QuadSwap(_) => {}
2251                }
2252                writeln!(self.out, ");")?;
2253            }
2254            Statement::CooperativeStore { .. } => unimplemented!(),
2255            Statement::RayPipelineFunction(_) => unimplemented!(),
2256        }
2257
2258        Ok(())
2259    }
2260
2261    /// Write a const expression.
2262    ///
2263    /// Write `expr`, a handle to an [`Expression`] in the current [`Module`]'s
2264    /// constant expression arena, as GLSL expression.
2265    ///
2266    /// # Notes
2267    /// Adds no newlines or leading/trailing whitespace
2268    ///
2269    /// [`Expression`]: crate::Expression
2270    /// [`Module`]: crate::Module
2271    fn write_const_expr(
2272        &mut self,
2273        expr: Handle<crate::Expression>,
2274        arena: &crate::Arena<crate::Expression>,
2275    ) -> BackendResult {
2276        self.write_possibly_const_expr(
2277            expr,
2278            arena,
2279            |expr| &self.info[expr],
2280            |writer, expr| writer.write_const_expr(expr, arena),
2281        )
2282    }
2283
2284    /// Write [`Expression`] variants that can occur in both runtime and const expressions.
2285    ///
2286    /// Write `expr`, a handle to an [`Expression`] in the arena `expressions`,
2287    /// as as GLSL expression. This must be one of the [`Expression`] variants
2288    /// that is allowed to occur in constant expressions.
2289    ///
2290    /// Use `write_expression` to write subexpressions.
2291    ///
2292    /// This is the common code for `write_expr`, which handles arbitrary
2293    /// runtime expressions, and `write_const_expr`, which only handles
2294    /// const-expressions. Each of those callers passes itself (essentially) as
2295    /// the `write_expression` callback, so that subexpressions are restricted
2296    /// to the appropriate variants.
2297    ///
2298    /// # Notes
2299    /// Adds no newlines or leading/trailing whitespace
2300    ///
2301    /// [`Expression`]: crate::Expression
2302    fn write_possibly_const_expr<'w, I, E>(
2303        &'w mut self,
2304        expr: Handle<crate::Expression>,
2305        expressions: &crate::Arena<crate::Expression>,
2306        info: I,
2307        write_expression: E,
2308    ) -> BackendResult
2309    where
2310        I: Fn(Handle<crate::Expression>) -> &'w proc::TypeResolution,
2311        E: Fn(&mut Self, Handle<crate::Expression>) -> BackendResult,
2312    {
2313        use crate::Expression;
2314
2315        match expressions[expr] {
2316            Expression::Literal(literal) => {
2317                match literal {
2318                    // Floats are written using `Debug` instead of `Display` because it always appends the
2319                    // decimal part even it's zero which is needed for a valid glsl float constant
2320                    crate::Literal::F64(value) => write!(self.out, "{value:?}LF")?,
2321                    crate::Literal::F32(value) => write!(self.out, "{value:?}")?,
2322                    crate::Literal::F16(_) => {
2323                        return Err(Error::Custom("GLSL has no 16-bit float type".into()));
2324                    }
2325                    // Unsigned integers need a `u` at the end
2326                    //
2327                    // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we
2328                    // always write it as the extra branch wouldn't have any benefit in readability
2329                    crate::Literal::U32(value) => write!(self.out, "{value}u")?,
2330                    crate::Literal::I32(value) => write!(self.out, "{value}")?,
2331                    crate::Literal::Bool(value) => write!(self.out, "{value}")?,
2332                    crate::Literal::I64(_) => {
2333                        return Err(Error::Custom("GLSL has no 64-bit integer type".into()));
2334                    }
2335                    crate::Literal::U64(_) => {
2336                        return Err(Error::Custom("GLSL has no 64-bit integer type".into()));
2337                    }
2338                    crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => {
2339                        return Err(Error::Custom(
2340                            "Abstract types should not appear in IR presented to backends".into(),
2341                        ));
2342                    }
2343                }
2344            }
2345            Expression::Constant(handle) => {
2346                let constant = &self.module.constants[handle];
2347                if constant.name.is_some() {
2348                    write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?;
2349                } else {
2350                    self.write_const_expr(constant.init, &self.module.global_expressions)?;
2351                }
2352            }
2353            Expression::ZeroValue(ty) => {
2354                self.write_zero_init_value(ty)?;
2355            }
2356            Expression::Compose { ty, ref components } => {
2357                self.write_type(ty)?;
2358
2359                if let TypeInner::Array { base, size, .. } = self.module.types[ty].inner {
2360                    self.write_array_size(base, size)?;
2361                }
2362
2363                write!(self.out, "(")?;
2364                for (index, component) in components.iter().enumerate() {
2365                    if index != 0 {
2366                        write!(self.out, ", ")?;
2367                    }
2368                    write_expression(self, *component)?;
2369                }
2370                write!(self.out, ")")?
2371            }
2372            // `Splat` needs to actually write down a vector, it's not always inferred in GLSL.
2373            Expression::Splat { size: _, value } => {
2374                let resolved = info(expr).inner_with(&self.module.types);
2375                self.write_value_type(resolved)?;
2376                write!(self.out, "(")?;
2377                write_expression(self, value)?;
2378                write!(self.out, ")")?
2379            }
2380            _ => {
2381                return Err(Error::Override);
2382            }
2383        }
2384
2385        Ok(())
2386    }
2387
2388    /// Helper method to write expressions
2389    ///
2390    /// # Notes
2391    /// Doesn't add any newlines or leading/trailing spaces
2392    fn write_expr(
2393        &mut self,
2394        expr: Handle<crate::Expression>,
2395        ctx: &back::FunctionCtx,
2396    ) -> BackendResult {
2397        use crate::Expression;
2398
2399        if let Some(name) = self.named_expressions.get(&expr) {
2400            write!(self.out, "{name}")?;
2401            return Ok(());
2402        }
2403
2404        match ctx.expressions[expr] {
2405            Expression::Literal(_)
2406            | Expression::Constant(_)
2407            | Expression::ZeroValue(_)
2408            | Expression::Compose { .. }
2409            | Expression::Splat { .. } => {
2410                self.write_possibly_const_expr(
2411                    expr,
2412                    ctx.expressions,
2413                    |expr| &ctx.info[expr].ty,
2414                    |writer, expr| writer.write_expr(expr, ctx),
2415                )?;
2416            }
2417            Expression::Override(_) => return Err(Error::Override),
2418            // `Access` is applied to arrays, vectors and matrices and is written as indexing
2419            Expression::Access { base, index } => {
2420                self.write_expr(base, ctx)?;
2421                write!(self.out, "[")?;
2422                self.write_expr(index, ctx)?;
2423                write!(self.out, "]")?
2424            }
2425            // `AccessIndex` is the same as `Access` except that the index is a constant and it can
2426            // be applied to structs, in this case we need to find the name of the field at that
2427            // index and write `base.field_name`
2428            Expression::AccessIndex { base, index } => {
2429                self.write_expr(base, ctx)?;
2430
2431                let base_ty_res = &ctx.info[base].ty;
2432                let mut resolved = base_ty_res.inner_with(&self.module.types);
2433                let base_ty_handle = match *resolved {
2434                    TypeInner::Pointer { base, space: _ } => {
2435                        resolved = &self.module.types[base].inner;
2436                        Some(base)
2437                    }
2438                    _ => base_ty_res.handle(),
2439                };
2440
2441                match *resolved {
2442                    TypeInner::Vector { .. } => {
2443                        // Write vector access as a swizzle
2444                        write!(self.out, ".{}", back::COMPONENTS[index as usize])?
2445                    }
2446                    TypeInner::Matrix { .. }
2447                    | TypeInner::Array { .. }
2448                    | TypeInner::ValuePointer { .. } => write!(self.out, "[{index}]")?,
2449                    TypeInner::Struct { .. } => {
2450                        // This will never panic in case the type is a `Struct`, this is not true
2451                        // for other types so we can only check while inside this match arm
2452                        let ty = base_ty_handle.unwrap();
2453
2454                        write!(
2455                            self.out,
2456                            ".{}",
2457                            &self.names[&NameKey::StructMember(ty, index)]
2458                        )?
2459                    }
2460                    ref other => return Err(Error::Custom(format!("Cannot index {other:?}"))),
2461                }
2462            }
2463            // `Swizzle` adds a few letters behind the dot.
2464            Expression::Swizzle {
2465                size,
2466                vector,
2467                pattern,
2468            } => {
2469                self.write_expr(vector, ctx)?;
2470                write!(self.out, ".")?;
2471                for &sc in pattern[..size as usize].iter() {
2472                    self.out.write_char(back::COMPONENTS[sc as usize])?;
2473                }
2474            }
2475            // Function arguments are written as the argument name
2476            Expression::FunctionArgument(pos) => {
2477                write!(self.out, "{}", &self.names[&ctx.argument_key(pos)])?
2478            }
2479            // Global variables need some special work for their name but
2480            // `get_global_name` does the work for us
2481            Expression::GlobalVariable(handle) => {
2482                let global = &self.module.global_variables[handle];
2483                self.write_global_name(handle, global)?
2484            }
2485            // A local is written as it's name
2486            Expression::LocalVariable(handle) => {
2487                write!(self.out, "{}", self.names[&ctx.name_key(handle)])?
2488            }
2489            // glsl has no pointers so there's no load operation, just write the pointer expression
2490            Expression::Load { pointer } => self.write_expr(pointer, ctx)?,
2491            // `ImageSample` is a bit complicated compared to the rest of the IR.
2492            //
2493            // First there are three variations depending whether the sample level is explicitly set,
2494            // if it's automatic or it it's bias:
2495            // `texture(image, coordinate)` - Automatic sample level
2496            // `texture(image, coordinate, bias)` - Bias sample level
2497            // `textureLod(image, coordinate, level)` - Zero or Exact sample level
2498            //
2499            // Furthermore if `depth_ref` is some we need to append it to the coordinate vector
2500            Expression::ImageSample {
2501                image,
2502                sampler: _, //TODO?
2503                gather,
2504                coordinate,
2505                array_index,
2506                offset,
2507                level,
2508                depth_ref,
2509                clamp_to_edge: _,
2510            } => {
2511                let (dim, class, arrayed) = match *ctx.resolve_type(image, &self.module.types) {
2512                    TypeInner::Image {
2513                        dim,
2514                        class,
2515                        arrayed,
2516                        ..
2517                    } => (dim, class, arrayed),
2518                    _ => unreachable!(),
2519                };
2520                let mut err = None;
2521                if dim == crate::ImageDimension::Cube {
2522                    if offset.is_some() {
2523                        err = Some("gsamplerCube[Array][Shadow] doesn't support texture sampling with offsets");
2524                    }
2525                    if arrayed
2526                        && matches!(class, crate::ImageClass::Depth { .. })
2527                        && matches!(level, crate::SampleLevel::Gradient { .. })
2528                    {
2529                        err = Some("samplerCubeArrayShadow don't support textureGrad");
2530                    }
2531                }
2532                if gather.is_some() && level != crate::SampleLevel::Zero {
2533                    err = Some("textureGather doesn't support LOD parameters");
2534                }
2535                if let Some(err) = err {
2536                    return Err(Error::Custom(String::from(err)));
2537                }
2538
2539                // `textureLod[Offset]` on `sampler2DArrayShadow` and `samplerCubeShadow` does not exist in GLSL,
2540                // unless `GL_EXT_texture_shadow_lod` is present.
2541                // But if the target LOD is zero, we can emulate that by using `textureGrad[Offset]` with a constant gradient of 0.
2542                let workaround_lod_with_grad = ((dim == crate::ImageDimension::Cube && !arrayed)
2543                    || (dim == crate::ImageDimension::D2 && arrayed))
2544                    && level == crate::SampleLevel::Zero
2545                    && matches!(class, crate::ImageClass::Depth { .. })
2546                    && !self.features.contains(Features::TEXTURE_SHADOW_LOD);
2547
2548                // Write the function to be used depending on the sample level
2549                let fun_name = match level {
2550                    crate::SampleLevel::Zero if gather.is_some() => "textureGather",
2551                    crate::SampleLevel::Zero if workaround_lod_with_grad => "textureGrad",
2552                    crate::SampleLevel::Auto | crate::SampleLevel::Bias(_) => "texture",
2553                    crate::SampleLevel::Zero | crate::SampleLevel::Exact(_) => "textureLod",
2554                    crate::SampleLevel::Gradient { .. } => "textureGrad",
2555                };
2556                let offset_name = match offset {
2557                    Some(_) => "Offset",
2558                    None => "",
2559                };
2560
2561                write!(self.out, "{fun_name}{offset_name}(")?;
2562
2563                // Write the image that will be used
2564                self.write_expr(image, ctx)?;
2565                // The space here isn't required but it helps with readability
2566                write!(self.out, ", ")?;
2567
2568                // TODO: handle clamp_to_edge
2569                // https://github.com/gfx-rs/wgpu/issues/7791
2570
2571                // We need to get the coordinates vector size to later build a vector that's `size + 1`
2572                // if `depth_ref` is some, if it isn't a vector we panic as that's not a valid expression
2573                let mut coord_dim = match *ctx.resolve_type(coordinate, &self.module.types) {
2574                    TypeInner::Vector { size, .. } => size as u8,
2575                    TypeInner::Scalar { .. } => 1,
2576                    _ => unreachable!(),
2577                };
2578
2579                if array_index.is_some() {
2580                    coord_dim += 1;
2581                }
2582                let merge_depth_ref = depth_ref.is_some() && gather.is_none() && coord_dim < 4;
2583                if merge_depth_ref {
2584                    coord_dim += 1;
2585                }
2586
2587                let tex_1d_hack = dim == crate::ImageDimension::D1 && self.options.version.is_es();
2588                let is_vec = tex_1d_hack || coord_dim != 1;
2589                // Compose a new texture coordinates vector
2590                if is_vec {
2591                    write!(self.out, "vec{}(", coord_dim + tex_1d_hack as u8)?;
2592                }
2593                self.write_expr(coordinate, ctx)?;
2594                if tex_1d_hack {
2595                    write!(self.out, ", 0.0")?;
2596                }
2597                if let Some(expr) = array_index {
2598                    write!(self.out, ", ")?;
2599                    self.write_expr(expr, ctx)?;
2600                }
2601                if merge_depth_ref {
2602                    write!(self.out, ", ")?;
2603                    self.write_expr(depth_ref.unwrap(), ctx)?;
2604                }
2605                if is_vec {
2606                    write!(self.out, ")")?;
2607                }
2608
2609                if let (Some(expr), false) = (depth_ref, merge_depth_ref) {
2610                    write!(self.out, ", ")?;
2611                    self.write_expr(expr, ctx)?;
2612                }
2613
2614                match level {
2615                    // Auto needs no more arguments
2616                    crate::SampleLevel::Auto => (),
2617                    // Zero needs level set to 0
2618                    crate::SampleLevel::Zero => {
2619                        if workaround_lod_with_grad {
2620                            let vec_dim = match dim {
2621                                crate::ImageDimension::Cube => 3,
2622                                _ => 2,
2623                            };
2624                            write!(self.out, ", vec{vec_dim}(0.0), vec{vec_dim}(0.0)")?;
2625                        } else if gather.is_none() {
2626                            write!(self.out, ", 0.0")?;
2627                        }
2628                    }
2629                    // Exact and bias require another argument
2630                    crate::SampleLevel::Exact(expr) => {
2631                        write!(self.out, ", ")?;
2632                        self.write_expr(expr, ctx)?;
2633                    }
2634                    crate::SampleLevel::Bias(_) => {
2635                        // This needs to be done after the offset writing
2636                    }
2637                    crate::SampleLevel::Gradient { x, y } => {
2638                        // If we are using sampler2D to replace sampler1D, we also
2639                        // need to make sure to use vec2 gradients
2640                        if tex_1d_hack {
2641                            write!(self.out, ", vec2(")?;
2642                            self.write_expr(x, ctx)?;
2643                            write!(self.out, ", 0.0)")?;
2644                            write!(self.out, ", vec2(")?;
2645                            self.write_expr(y, ctx)?;
2646                            write!(self.out, ", 0.0)")?;
2647                        } else {
2648                            write!(self.out, ", ")?;
2649                            self.write_expr(x, ctx)?;
2650                            write!(self.out, ", ")?;
2651                            self.write_expr(y, ctx)?;
2652                        }
2653                    }
2654                }
2655
2656                if let Some(constant) = offset {
2657                    write!(self.out, ", ")?;
2658                    if tex_1d_hack {
2659                        write!(self.out, "ivec2(")?;
2660                    }
2661                    self.write_const_expr(constant, ctx.expressions)?;
2662                    if tex_1d_hack {
2663                        write!(self.out, ", 0)")?;
2664                    }
2665                }
2666
2667                // Bias is always the last argument
2668                if let crate::SampleLevel::Bias(expr) = level {
2669                    write!(self.out, ", ")?;
2670                    self.write_expr(expr, ctx)?;
2671                }
2672
2673                if let (Some(component), None) = (gather, depth_ref) {
2674                    write!(self.out, ", {}", component as usize)?;
2675                }
2676
2677                // End the function
2678                write!(self.out, ")")?
2679            }
2680            Expression::ImageLoad {
2681                image,
2682                coordinate,
2683                array_index,
2684                sample,
2685                level,
2686            } => self.write_image_load(expr, ctx, image, coordinate, array_index, sample, level)?,
2687            // Query translates into one of the:
2688            // - textureSize/imageSize
2689            // - textureQueryLevels
2690            // - textureSamples/imageSamples
2691            Expression::ImageQuery { image, query } => {
2692                use crate::ImageClass;
2693
2694                // This will only panic if the module is invalid
2695                let (dim, class) = match *ctx.resolve_type(image, &self.module.types) {
2696                    TypeInner::Image {
2697                        dim,
2698                        arrayed: _,
2699                        class,
2700                    } => (dim, class),
2701                    _ => unreachable!(),
2702                };
2703                let components = match dim {
2704                    crate::ImageDimension::D1 => 1,
2705                    crate::ImageDimension::D2 => 2,
2706                    crate::ImageDimension::D3 => 3,
2707                    crate::ImageDimension::Cube => 2,
2708                };
2709
2710                if let crate::ImageQuery::Size { .. } = query {
2711                    match components {
2712                        1 => write!(self.out, "uint(")?,
2713                        _ => write!(self.out, "uvec{components}(")?,
2714                    }
2715                } else {
2716                    write!(self.out, "uint(")?;
2717                }
2718
2719                match query {
2720                    crate::ImageQuery::Size { level } => {
2721                        match class {
2722                            ImageClass::Sampled { multi, .. } | ImageClass::Depth { multi } => {
2723                                write!(self.out, "textureSize(")?;
2724                                self.write_expr(image, ctx)?;
2725                                if let Some(expr) = level {
2726                                    let cast_to_int = matches!(
2727                                        *ctx.resolve_type(expr, &self.module.types),
2728                                        TypeInner::Scalar(crate::Scalar {
2729                                            kind: crate::ScalarKind::Uint,
2730                                            ..
2731                                        })
2732                                    );
2733
2734                                    write!(self.out, ", ")?;
2735
2736                                    if cast_to_int {
2737                                        write!(self.out, "int(")?;
2738                                    }
2739
2740                                    self.write_expr(expr, ctx)?;
2741
2742                                    if cast_to_int {
2743                                        write!(self.out, ")")?;
2744                                    }
2745                                } else if !multi {
2746                                    // All textureSize calls requires an lod argument
2747                                    // except for multisampled samplers
2748                                    write!(self.out, ", 0")?;
2749                                }
2750                            }
2751                            ImageClass::Storage { .. } => {
2752                                write!(self.out, "imageSize(")?;
2753                                self.write_expr(image, ctx)?;
2754                            }
2755                            ImageClass::External => unimplemented!(),
2756                        }
2757                        write!(self.out, ")")?;
2758                        if components != 1 || self.options.version.is_es() {
2759                            write!(self.out, ".{}", &"xyz"[..components])?;
2760                        }
2761                    }
2762                    crate::ImageQuery::NumLevels => {
2763                        write!(self.out, "textureQueryLevels(",)?;
2764                        self.write_expr(image, ctx)?;
2765                        write!(self.out, ")",)?;
2766                    }
2767                    crate::ImageQuery::NumLayers => {
2768                        let fun_name = match class {
2769                            ImageClass::Sampled { .. } | ImageClass::Depth { .. } => "textureSize",
2770                            ImageClass::Storage { .. } => "imageSize",
2771                            ImageClass::External => unimplemented!(),
2772                        };
2773                        write!(self.out, "{fun_name}(")?;
2774                        self.write_expr(image, ctx)?;
2775                        // All textureSize calls requires an lod argument
2776                        // except for multisampled samplers
2777                        if !class.is_multisampled() {
2778                            write!(self.out, ", 0")?;
2779                        }
2780                        write!(self.out, ")")?;
2781                        if components != 1 || self.options.version.is_es() {
2782                            write!(self.out, ".{}", back::COMPONENTS[components])?;
2783                        }
2784                    }
2785                    crate::ImageQuery::NumSamples => {
2786                        let fun_name = match class {
2787                            ImageClass::Sampled { .. } | ImageClass::Depth { .. } => {
2788                                "textureSamples"
2789                            }
2790                            ImageClass::Storage { .. } => "imageSamples",
2791                            ImageClass::External => unimplemented!(),
2792                        };
2793                        write!(self.out, "{fun_name}(")?;
2794                        self.write_expr(image, ctx)?;
2795                        write!(self.out, ")",)?;
2796                    }
2797                }
2798
2799                write!(self.out, ")")?;
2800            }
2801            Expression::Unary { op, expr } => {
2802                let operator_or_fn = match op {
2803                    crate::UnaryOperator::Negate => "-",
2804                    crate::UnaryOperator::LogicalNot => {
2805                        match *ctx.resolve_type(expr, &self.module.types) {
2806                            TypeInner::Vector { .. } => "not",
2807                            _ => "!",
2808                        }
2809                    }
2810                    crate::UnaryOperator::BitwiseNot => "~",
2811                };
2812                write!(self.out, "{operator_or_fn}(")?;
2813
2814                self.write_expr(expr, ctx)?;
2815
2816                write!(self.out, ")")?
2817            }
2818            // `Binary` we just write `left op right`, except when dealing with
2819            // comparison operations on vectors as they are implemented with
2820            // builtin functions.
2821            // Once again we wrap everything in parentheses to avoid precedence issues
2822            Expression::Binary {
2823                mut op,
2824                left,
2825                right,
2826            } => {
2827                // Holds `Some(function_name)` if the binary operation is
2828                // implemented as a function call
2829                use crate::{BinaryOperator as Bo, ScalarKind as Sk, TypeInner as Ti};
2830
2831                let left_inner = ctx.resolve_type(left, &self.module.types);
2832                let right_inner = ctx.resolve_type(right, &self.module.types);
2833
2834                let function = match (left_inner, right_inner) {
2835                    (&Ti::Vector { scalar, .. }, &Ti::Vector { .. }) => match op {
2836                        Bo::Less
2837                        | Bo::LessEqual
2838                        | Bo::Greater
2839                        | Bo::GreaterEqual
2840                        | Bo::Equal
2841                        | Bo::NotEqual => BinaryOperation::VectorCompare,
2842                        Bo::Modulo if scalar.kind == Sk::Float => BinaryOperation::Modulo,
2843                        Bo::And if scalar.kind == Sk::Bool => {
2844                            op = crate::BinaryOperator::LogicalAnd;
2845                            BinaryOperation::VectorComponentWise
2846                        }
2847                        Bo::InclusiveOr if scalar.kind == Sk::Bool => {
2848                            op = crate::BinaryOperator::LogicalOr;
2849                            BinaryOperation::VectorComponentWise
2850                        }
2851                        _ => BinaryOperation::Other,
2852                    },
2853                    _ => match (left_inner.scalar_kind(), right_inner.scalar_kind()) {
2854                        (Some(Sk::Float), _) | (_, Some(Sk::Float)) => match op {
2855                            Bo::Modulo => BinaryOperation::Modulo,
2856                            _ => BinaryOperation::Other,
2857                        },
2858                        (Some(Sk::Bool), Some(Sk::Bool)) => match op {
2859                            Bo::InclusiveOr => {
2860                                op = crate::BinaryOperator::LogicalOr;
2861                                BinaryOperation::Other
2862                            }
2863                            Bo::And => {
2864                                op = crate::BinaryOperator::LogicalAnd;
2865                                BinaryOperation::Other
2866                            }
2867                            _ => BinaryOperation::Other,
2868                        },
2869                        _ => BinaryOperation::Other,
2870                    },
2871                };
2872
2873                match function {
2874                    BinaryOperation::VectorCompare => {
2875                        let op_str = match op {
2876                            Bo::Less => "lessThan(",
2877                            Bo::LessEqual => "lessThanEqual(",
2878                            Bo::Greater => "greaterThan(",
2879                            Bo::GreaterEqual => "greaterThanEqual(",
2880                            Bo::Equal => "equal(",
2881                            Bo::NotEqual => "notEqual(",
2882                            _ => unreachable!(),
2883                        };
2884                        write!(self.out, "{op_str}")?;
2885                        self.write_expr(left, ctx)?;
2886                        write!(self.out, ", ")?;
2887                        self.write_expr(right, ctx)?;
2888                        write!(self.out, ")")?;
2889                    }
2890                    BinaryOperation::VectorComponentWise => {
2891                        self.write_value_type(left_inner)?;
2892                        write!(self.out, "(")?;
2893
2894                        let size = match *left_inner {
2895                            Ti::Vector { size, .. } => size,
2896                            _ => unreachable!(),
2897                        };
2898
2899                        for i in 0..size as usize {
2900                            if i != 0 {
2901                                write!(self.out, ", ")?;
2902                            }
2903
2904                            self.write_expr(left, ctx)?;
2905                            write!(self.out, ".{}", back::COMPONENTS[i])?;
2906
2907                            write!(self.out, " {} ", back::binary_operation_str(op))?;
2908
2909                            self.write_expr(right, ctx)?;
2910                            write!(self.out, ".{}", back::COMPONENTS[i])?;
2911                        }
2912
2913                        write!(self.out, ")")?;
2914                    }
2915                    // TODO: handle undefined behavior of BinaryOperator::Modulo
2916                    //
2917                    // sint:
2918                    // if right == 0 return 0
2919                    // if left == min(type_of(left)) && right == -1 return 0
2920                    // if sign(left) == -1 || sign(right) == -1 return result as defined by WGSL
2921                    //
2922                    // uint:
2923                    // if right == 0 return 0
2924                    //
2925                    // float:
2926                    // if right == 0 return ? see https://github.com/gpuweb/gpuweb/issues/2798
2927                    BinaryOperation::Modulo => {
2928                        write!(self.out, "(")?;
2929
2930                        // write `e1 - e2 * trunc(e1 / e2)`
2931                        self.write_expr(left, ctx)?;
2932                        write!(self.out, " - ")?;
2933                        self.write_expr(right, ctx)?;
2934                        write!(self.out, " * ")?;
2935                        write!(self.out, "trunc(")?;
2936                        self.write_expr(left, ctx)?;
2937                        write!(self.out, " / ")?;
2938                        self.write_expr(right, ctx)?;
2939                        write!(self.out, ")")?;
2940
2941                        write!(self.out, ")")?;
2942                    }
2943                    BinaryOperation::Other => {
2944                        write!(self.out, "(")?;
2945
2946                        self.write_expr(left, ctx)?;
2947                        write!(self.out, " {} ", back::binary_operation_str(op))?;
2948                        self.write_expr(right, ctx)?;
2949
2950                        write!(self.out, ")")?;
2951                    }
2952                }
2953            }
2954            // `Select` is written as `condition ? accept : reject`
2955            // We wrap everything in parentheses to avoid precedence issues
2956            Expression::Select {
2957                condition,
2958                accept,
2959                reject,
2960            } => {
2961                let cond_ty = ctx.resolve_type(condition, &self.module.types);
2962                let vec_select = if let TypeInner::Vector { .. } = *cond_ty {
2963                    true
2964                } else {
2965                    false
2966                };
2967
2968                // TODO: Boolean mix on desktop required GL_EXT_shader_integer_mix
2969                if vec_select {
2970                    // Glsl defines that for mix when the condition is a boolean the first element
2971                    // is picked if condition is false and the second if condition is true
2972                    write!(self.out, "mix(")?;
2973                    self.write_expr(reject, ctx)?;
2974                    write!(self.out, ", ")?;
2975                    self.write_expr(accept, ctx)?;
2976                    write!(self.out, ", ")?;
2977                    self.write_expr(condition, ctx)?;
2978                } else {
2979                    write!(self.out, "(")?;
2980                    self.write_expr(condition, ctx)?;
2981                    write!(self.out, " ? ")?;
2982                    self.write_expr(accept, ctx)?;
2983                    write!(self.out, " : ")?;
2984                    self.write_expr(reject, ctx)?;
2985                }
2986
2987                write!(self.out, ")")?
2988            }
2989            // `Derivative` is a function call to a glsl provided function
2990            Expression::Derivative { axis, ctrl, expr } => {
2991                use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl};
2992                let fun_name = if self.options.version.supports_derivative_control() {
2993                    match (axis, ctrl) {
2994                        (Axis::X, Ctrl::Coarse) => "dFdxCoarse",
2995                        (Axis::X, Ctrl::Fine) => "dFdxFine",
2996                        (Axis::X, Ctrl::None) => "dFdx",
2997                        (Axis::Y, Ctrl::Coarse) => "dFdyCoarse",
2998                        (Axis::Y, Ctrl::Fine) => "dFdyFine",
2999                        (Axis::Y, Ctrl::None) => "dFdy",
3000                        (Axis::Width, Ctrl::Coarse) => "fwidthCoarse",
3001                        (Axis::Width, Ctrl::Fine) => "fwidthFine",
3002                        (Axis::Width, Ctrl::None) => "fwidth",
3003                    }
3004                } else {
3005                    match axis {
3006                        Axis::X => "dFdx",
3007                        Axis::Y => "dFdy",
3008                        Axis::Width => "fwidth",
3009                    }
3010                };
3011                write!(self.out, "{fun_name}(")?;
3012                self.write_expr(expr, ctx)?;
3013                write!(self.out, ")")?
3014            }
3015            // `Relational` is a normal function call to some glsl provided functions
3016            Expression::Relational { fun, argument } => {
3017                use crate::RelationalFunction as Rf;
3018
3019                let fun_name = match fun {
3020                    Rf::IsInf => "isinf",
3021                    Rf::IsNan => "isnan",
3022                    Rf::All => "all",
3023                    Rf::Any => "any",
3024                };
3025                write!(self.out, "{fun_name}(")?;
3026
3027                self.write_expr(argument, ctx)?;
3028
3029                write!(self.out, ")")?
3030            }
3031            Expression::Math {
3032                fun,
3033                arg,
3034                arg1,
3035                arg2,
3036                arg3,
3037            } => {
3038                use crate::MathFunction as Mf;
3039
3040                let fun_name = match fun {
3041                    // comparison
3042                    Mf::Abs => "abs",
3043                    Mf::Min => "min",
3044                    Mf::Max => "max",
3045                    Mf::Clamp => {
3046                        let scalar_kind = ctx
3047                            .resolve_type(arg, &self.module.types)
3048                            .scalar_kind()
3049                            .unwrap();
3050                        match scalar_kind {
3051                            crate::ScalarKind::Float => "clamp",
3052                            // Clamp is undefined if min > max. In practice this means it can use a median-of-three
3053                            // instruction to determine the value. This is fine according to the WGSL spec for float
3054                            // clamp, but integer clamp _must_ use min-max. As such we write out min/max.
3055                            _ => {
3056                                write!(self.out, "min(max(")?;
3057                                self.write_expr(arg, ctx)?;
3058                                write!(self.out, ", ")?;
3059                                self.write_expr(arg1.unwrap(), ctx)?;
3060                                write!(self.out, "), ")?;
3061                                self.write_expr(arg2.unwrap(), ctx)?;
3062                                write!(self.out, ")")?;
3063
3064                                return Ok(());
3065                            }
3066                        }
3067                    }
3068                    Mf::Saturate => {
3069                        write!(self.out, "clamp(")?;
3070
3071                        self.write_expr(arg, ctx)?;
3072
3073                        match *ctx.resolve_type(arg, &self.module.types) {
3074                            TypeInner::Vector { size, .. } => write!(
3075                                self.out,
3076                                ", vec{}(0.0), vec{0}(1.0)",
3077                                common::vector_size_str(size)
3078                            )?,
3079                            _ => write!(self.out, ", 0.0, 1.0")?,
3080                        }
3081
3082                        write!(self.out, ")")?;
3083
3084                        return Ok(());
3085                    }
3086                    // trigonometry
3087                    Mf::Cos => "cos",
3088                    Mf::Cosh => "cosh",
3089                    Mf::Sin => "sin",
3090                    Mf::Sinh => "sinh",
3091                    Mf::Tan => "tan",
3092                    Mf::Tanh => "tanh",
3093                    Mf::Acos => "acos",
3094                    Mf::Asin => "asin",
3095                    Mf::Atan => "atan",
3096                    Mf::Asinh => "asinh",
3097                    Mf::Acosh => "acosh",
3098                    Mf::Atanh => "atanh",
3099                    Mf::Radians => "radians",
3100                    Mf::Degrees => "degrees",
3101                    // glsl doesn't have atan2 function
3102                    // use two-argument variation of the atan function
3103                    Mf::Atan2 => "atan",
3104                    // decomposition
3105                    Mf::Ceil => "ceil",
3106                    Mf::Floor => "floor",
3107                    Mf::Round => "roundEven",
3108                    Mf::Fract => "fract",
3109                    Mf::Trunc => "trunc",
3110                    Mf::Modf => MODF_FUNCTION,
3111                    Mf::Frexp => FREXP_FUNCTION,
3112                    Mf::Ldexp => "ldexp",
3113                    // exponent
3114                    Mf::Exp => "exp",
3115                    Mf::Exp2 => "exp2",
3116                    Mf::Log => "log",
3117                    Mf::Log2 => "log2",
3118                    Mf::Pow => "pow",
3119                    // geometry
3120                    Mf::Dot => match *ctx.resolve_type(arg, &self.module.types) {
3121                        TypeInner::Vector {
3122                            scalar:
3123                                crate::Scalar {
3124                                    kind: crate::ScalarKind::Float,
3125                                    ..
3126                                },
3127                            ..
3128                        } => "dot",
3129                        TypeInner::Vector { size, .. } => {
3130                            return self.write_dot_product(arg, arg1.unwrap(), size as usize, ctx)
3131                        }
3132                        _ => unreachable!(
3133                            "Correct TypeInner for dot product should be already validated"
3134                        ),
3135                    },
3136                    fun @ (Mf::Dot4I8Packed | Mf::Dot4U8Packed) => {
3137                        let conversion = match fun {
3138                            Mf::Dot4I8Packed => "int",
3139                            Mf::Dot4U8Packed => "",
3140                            _ => unreachable!(),
3141                        };
3142
3143                        let arg1 = arg1.unwrap();
3144
3145                        // Write parentheses around the dot product expression to prevent operators
3146                        // with different precedences from applying earlier.
3147                        write!(self.out, "(")?;
3148                        for i in 0..4 {
3149                            // Since `bitfieldExtract` only sign extends if the value is signed, we
3150                            // need to convert the inputs to `int` in case of `Dot4I8Packed`. For
3151                            // `Dot4U8Packed`, the code below only introduces parenthesis around
3152                            // each factor, which aren't strictly needed because both operands are
3153                            // baked, but which don't hurt either.
3154                            write!(self.out, "bitfieldExtract({conversion}(")?;
3155                            self.write_expr(arg, ctx)?;
3156                            write!(self.out, "), {}, 8)", i * 8)?;
3157
3158                            write!(self.out, " * bitfieldExtract({conversion}(")?;
3159                            self.write_expr(arg1, ctx)?;
3160                            write!(self.out, "), {}, 8)", i * 8)?;
3161
3162                            if i != 3 {
3163                                write!(self.out, " + ")?;
3164                            }
3165                        }
3166                        write!(self.out, ")")?;
3167
3168                        return Ok(());
3169                    }
3170                    Mf::Outer => "outerProduct",
3171                    Mf::Cross => "cross",
3172                    Mf::Distance => "distance",
3173                    Mf::Length => "length",
3174                    Mf::Normalize => "normalize",
3175                    Mf::FaceForward => "faceforward",
3176                    Mf::Reflect => "reflect",
3177                    Mf::Refract => "refract",
3178                    // computational
3179                    Mf::Sign => "sign",
3180                    Mf::Fma => {
3181                        if self.options.version.supports_fma_function() {
3182                            // Use the fma function when available
3183                            "fma"
3184                        } else {
3185                            // No fma support. Transform the function call into an arithmetic expression
3186                            write!(self.out, "(")?;
3187
3188                            self.write_expr(arg, ctx)?;
3189                            write!(self.out, " * ")?;
3190
3191                            let arg1 =
3192                                arg1.ok_or_else(|| Error::Custom("Missing fma arg1".to_owned()))?;
3193                            self.write_expr(arg1, ctx)?;
3194                            write!(self.out, " + ")?;
3195
3196                            let arg2 =
3197                                arg2.ok_or_else(|| Error::Custom("Missing fma arg2".to_owned()))?;
3198                            self.write_expr(arg2, ctx)?;
3199                            write!(self.out, ")")?;
3200
3201                            return Ok(());
3202                        }
3203                    }
3204                    Mf::Mix => "mix",
3205                    Mf::Step => "step",
3206                    Mf::SmoothStep => "smoothstep",
3207                    Mf::Sqrt => "sqrt",
3208                    Mf::InverseSqrt => "inversesqrt",
3209                    Mf::Inverse => "inverse",
3210                    Mf::Transpose => "transpose",
3211                    Mf::Determinant => "determinant",
3212                    Mf::QuantizeToF16 => match *ctx.resolve_type(arg, &self.module.types) {
3213                        TypeInner::Scalar { .. } => {
3214                            write!(self.out, "unpackHalf2x16(packHalf2x16(vec2(")?;
3215                            self.write_expr(arg, ctx)?;
3216                            write!(self.out, "))).x")?;
3217                            return Ok(());
3218                        }
3219                        TypeInner::Vector {
3220                            size: crate::VectorSize::Bi,
3221                            ..
3222                        } => {
3223                            write!(self.out, "unpackHalf2x16(packHalf2x16(")?;
3224                            self.write_expr(arg, ctx)?;
3225                            write!(self.out, "))")?;
3226                            return Ok(());
3227                        }
3228                        TypeInner::Vector {
3229                            size: crate::VectorSize::Tri,
3230                            ..
3231                        } => {
3232                            write!(self.out, "vec3(unpackHalf2x16(packHalf2x16(")?;
3233                            self.write_expr(arg, ctx)?;
3234                            write!(self.out, ".xy)), unpackHalf2x16(packHalf2x16(")?;
3235                            self.write_expr(arg, ctx)?;
3236                            write!(self.out, ".zz)).x)")?;
3237                            return Ok(());
3238                        }
3239                        TypeInner::Vector {
3240                            size: crate::VectorSize::Quad,
3241                            ..
3242                        } => {
3243                            write!(self.out, "vec4(unpackHalf2x16(packHalf2x16(")?;
3244                            self.write_expr(arg, ctx)?;
3245                            write!(self.out, ".xy)), unpackHalf2x16(packHalf2x16(")?;
3246                            self.write_expr(arg, ctx)?;
3247                            write!(self.out, ".zw)))")?;
3248                            return Ok(());
3249                        }
3250                        _ => unreachable!(
3251                            "Correct TypeInner for QuantizeToF16 should be already validated"
3252                        ),
3253                    },
3254                    // bits
3255                    Mf::CountTrailingZeros => {
3256                        match *ctx.resolve_type(arg, &self.module.types) {
3257                            TypeInner::Vector { size, scalar, .. } => {
3258                                let s = common::vector_size_str(size);
3259                                if let crate::ScalarKind::Uint = scalar.kind {
3260                                    write!(self.out, "min(uvec{s}(findLSB(")?;
3261                                    self.write_expr(arg, ctx)?;
3262                                    write!(self.out, ")), uvec{s}(32u))")?;
3263                                } else {
3264                                    write!(self.out, "ivec{s}(min(uvec{s}(findLSB(")?;
3265                                    self.write_expr(arg, ctx)?;
3266                                    write!(self.out, ")), uvec{s}(32u)))")?;
3267                                }
3268                            }
3269                            TypeInner::Scalar(scalar) => {
3270                                if let crate::ScalarKind::Uint = scalar.kind {
3271                                    write!(self.out, "min(uint(findLSB(")?;
3272                                    self.write_expr(arg, ctx)?;
3273                                    write!(self.out, ")), 32u)")?;
3274                                } else {
3275                                    write!(self.out, "int(min(uint(findLSB(")?;
3276                                    self.write_expr(arg, ctx)?;
3277                                    write!(self.out, ")), 32u))")?;
3278                                }
3279                            }
3280                            _ => unreachable!(),
3281                        };
3282                        return Ok(());
3283                    }
3284                    Mf::CountLeadingZeros => {
3285                        if self.options.version.supports_integer_functions() {
3286                            match *ctx.resolve_type(arg, &self.module.types) {
3287                                TypeInner::Vector { size, scalar } => {
3288                                    let s = common::vector_size_str(size);
3289
3290                                    if let crate::ScalarKind::Uint = scalar.kind {
3291                                        write!(self.out, "uvec{s}(ivec{s}(31) - findMSB(")?;
3292                                        self.write_expr(arg, ctx)?;
3293                                        write!(self.out, "))")?;
3294                                    } else {
3295                                        write!(self.out, "mix(ivec{s}(31) - findMSB(")?;
3296                                        self.write_expr(arg, ctx)?;
3297                                        write!(self.out, "), ivec{s}(0), lessThan(")?;
3298                                        self.write_expr(arg, ctx)?;
3299                                        write!(self.out, ", ivec{s}(0)))")?;
3300                                    }
3301                                }
3302                                TypeInner::Scalar(scalar) => {
3303                                    if let crate::ScalarKind::Uint = scalar.kind {
3304                                        write!(self.out, "uint(31 - findMSB(")?;
3305                                    } else {
3306                                        write!(self.out, "(")?;
3307                                        self.write_expr(arg, ctx)?;
3308                                        write!(self.out, " < 0 ? 0 : 31 - findMSB(")?;
3309                                    }
3310
3311                                    self.write_expr(arg, ctx)?;
3312                                    write!(self.out, "))")?;
3313                                }
3314                                _ => unreachable!(),
3315                            };
3316                        } else {
3317                            match *ctx.resolve_type(arg, &self.module.types) {
3318                                TypeInner::Vector { size, scalar } => {
3319                                    let s = common::vector_size_str(size);
3320
3321                                    if let crate::ScalarKind::Uint = scalar.kind {
3322                                        write!(self.out, "uvec{s}(")?;
3323                                        write!(self.out, "vec{s}(31.0) - floor(log2(vec{s}(")?;
3324                                        self.write_expr(arg, ctx)?;
3325                                        write!(self.out, ") + 0.5)))")?;
3326                                    } else {
3327                                        write!(self.out, "ivec{s}(")?;
3328                                        write!(self.out, "mix(vec{s}(31.0) - floor(log2(vec{s}(")?;
3329                                        self.write_expr(arg, ctx)?;
3330                                        write!(self.out, ") + 0.5)), ")?;
3331                                        write!(self.out, "vec{s}(0.0), lessThan(")?;
3332                                        self.write_expr(arg, ctx)?;
3333                                        write!(self.out, ", ivec{s}(0u))))")?;
3334                                    }
3335                                }
3336                                TypeInner::Scalar(scalar) => {
3337                                    if let crate::ScalarKind::Uint = scalar.kind {
3338                                        write!(self.out, "uint(31.0 - floor(log2(float(")?;
3339                                        self.write_expr(arg, ctx)?;
3340                                        write!(self.out, ") + 0.5)))")?;
3341                                    } else {
3342                                        write!(self.out, "(")?;
3343                                        self.write_expr(arg, ctx)?;
3344                                        write!(self.out, " < 0 ? 0 : int(")?;
3345                                        write!(self.out, "31.0 - floor(log2(float(")?;
3346                                        self.write_expr(arg, ctx)?;
3347                                        write!(self.out, ") + 0.5))))")?;
3348                                    }
3349                                }
3350                                _ => unreachable!(),
3351                            };
3352                        }
3353
3354                        return Ok(());
3355                    }
3356                    Mf::CountOneBits => "bitCount",
3357                    Mf::ReverseBits => "bitfieldReverse",
3358                    Mf::ExtractBits => {
3359                        // The behavior of ExtractBits is undefined when offset + count > bit_width. We need
3360                        // to first sanitize the offset and count first. If we don't do this, AMD and Intel chips
3361                        // will return out-of-spec values if the extracted range is not within the bit width.
3362                        //
3363                        // This encodes the exact formula specified by the wgsl spec, without temporary values:
3364                        // https://gpuweb.github.io/gpuweb/wgsl/#extractBits-unsigned-builtin
3365                        //
3366                        // w = sizeof(x) * 8
3367                        // o = min(offset, w)
3368                        // c = min(count, w - o)
3369                        //
3370                        // bitfieldExtract(x, o, c)
3371                        //
3372                        // extract_bits(e, min(offset, w), min(count, w - min(offset, w))))
3373                        let scalar_bits = ctx
3374                            .resolve_type(arg, &self.module.types)
3375                            .scalar_width()
3376                            .unwrap()
3377                            * 8;
3378
3379                        write!(self.out, "bitfieldExtract(")?;
3380                        self.write_expr(arg, ctx)?;
3381                        write!(self.out, ", int(min(")?;
3382                        self.write_expr(arg1.unwrap(), ctx)?;
3383                        write!(self.out, ", {scalar_bits}u)), int(min(",)?;
3384                        self.write_expr(arg2.unwrap(), ctx)?;
3385                        write!(self.out, ", {scalar_bits}u - min(")?;
3386                        self.write_expr(arg1.unwrap(), ctx)?;
3387                        write!(self.out, ", {scalar_bits}u))))")?;
3388
3389                        return Ok(());
3390                    }
3391                    Mf::InsertBits => {
3392                        // InsertBits has the same considerations as ExtractBits above
3393                        let scalar_bits = ctx
3394                            .resolve_type(arg, &self.module.types)
3395                            .scalar_width()
3396                            .unwrap()
3397                            * 8;
3398
3399                        write!(self.out, "bitfieldInsert(")?;
3400                        self.write_expr(arg, ctx)?;
3401                        write!(self.out, ", ")?;
3402                        self.write_expr(arg1.unwrap(), ctx)?;
3403                        write!(self.out, ", int(min(")?;
3404                        self.write_expr(arg2.unwrap(), ctx)?;
3405                        write!(self.out, ", {scalar_bits}u)), int(min(",)?;
3406                        self.write_expr(arg3.unwrap(), ctx)?;
3407                        write!(self.out, ", {scalar_bits}u - min(")?;
3408                        self.write_expr(arg2.unwrap(), ctx)?;
3409                        write!(self.out, ", {scalar_bits}u))))")?;
3410
3411                        return Ok(());
3412                    }
3413                    Mf::FirstTrailingBit => "findLSB",
3414                    Mf::FirstLeadingBit => "findMSB",
3415                    // data packing
3416                    Mf::Pack4x8snorm => {
3417                        if self.options.version.supports_pack_unpack_4x8() {
3418                            "packSnorm4x8"
3419                        } else {
3420                            // polyfill should go here. Needs a corresponding entry in `need_bake_expression`
3421                            return Err(Error::UnsupportedExternal("packSnorm4x8".into()));
3422                        }
3423                    }
3424                    Mf::Pack4x8unorm => {
3425                        if self.options.version.supports_pack_unpack_4x8() {
3426                            "packUnorm4x8"
3427                        } else {
3428                            return Err(Error::UnsupportedExternal("packUnorm4x8".to_owned()));
3429                        }
3430                    }
3431                    Mf::Pack2x16snorm => {
3432                        if self.options.version.supports_pack_unpack_snorm_2x16() {
3433                            "packSnorm2x16"
3434                        } else {
3435                            return Err(Error::UnsupportedExternal("packSnorm2x16".to_owned()));
3436                        }
3437                    }
3438                    Mf::Pack2x16unorm => {
3439                        if self.options.version.supports_pack_unpack_unorm_2x16() {
3440                            "packUnorm2x16"
3441                        } else {
3442                            return Err(Error::UnsupportedExternal("packUnorm2x16".to_owned()));
3443                        }
3444                    }
3445                    Mf::Pack2x16float => {
3446                        if self.options.version.supports_pack_unpack_half_2x16() {
3447                            "packHalf2x16"
3448                        } else {
3449                            return Err(Error::UnsupportedExternal("packHalf2x16".to_owned()));
3450                        }
3451                    }
3452
3453                    fun @ (Mf::Pack4xI8 | Mf::Pack4xU8 | Mf::Pack4xI8Clamp | Mf::Pack4xU8Clamp) => {
3454                        let was_signed = matches!(fun, Mf::Pack4xI8 | Mf::Pack4xI8Clamp);
3455                        let clamp_bounds = match fun {
3456                            Mf::Pack4xI8Clamp => Some(("-128", "127")),
3457                            Mf::Pack4xU8Clamp => Some(("0", "255")),
3458                            _ => None,
3459                        };
3460                        let const_suffix = if was_signed { "" } else { "u" };
3461                        if was_signed {
3462                            write!(self.out, "uint(")?;
3463                        }
3464                        let write_arg = |this: &mut Self| -> BackendResult {
3465                            if let Some((min, max)) = clamp_bounds {
3466                                write!(this.out, "clamp(")?;
3467                                this.write_expr(arg, ctx)?;
3468                                write!(this.out, ", {min}{const_suffix}, {max}{const_suffix})")?;
3469                            } else {
3470                                this.write_expr(arg, ctx)?;
3471                            }
3472                            Ok(())
3473                        };
3474                        write!(self.out, "(")?;
3475                        write_arg(self)?;
3476                        write!(self.out, "[0] & 0xFF{const_suffix}) | ((")?;
3477                        write_arg(self)?;
3478                        write!(self.out, "[1] & 0xFF{const_suffix}) << 8) | ((")?;
3479                        write_arg(self)?;
3480                        write!(self.out, "[2] & 0xFF{const_suffix}) << 16) | ((")?;
3481                        write_arg(self)?;
3482                        write!(self.out, "[3] & 0xFF{const_suffix}) << 24)")?;
3483                        if was_signed {
3484                            write!(self.out, ")")?;
3485                        }
3486
3487                        return Ok(());
3488                    }
3489                    // data unpacking
3490                    Mf::Unpack2x16float => {
3491                        if self.options.version.supports_pack_unpack_half_2x16() {
3492                            "unpackHalf2x16"
3493                        } else {
3494                            return Err(Error::UnsupportedExternal("unpackHalf2x16".into()));
3495                        }
3496                    }
3497                    Mf::Unpack2x16snorm => {
3498                        if self.options.version.supports_pack_unpack_snorm_2x16() {
3499                            "unpackSnorm2x16"
3500                        } else {
3501                            let scale = 32767;
3502
3503                            write!(self.out, "(vec2(ivec2(")?;
3504                            self.write_expr(arg, ctx)?;
3505                            write!(self.out, " << 16, ")?;
3506                            self.write_expr(arg, ctx)?;
3507                            write!(self.out, ") >> 16) / {scale}.0)")?;
3508                            return Ok(());
3509                        }
3510                    }
3511                    Mf::Unpack2x16unorm => {
3512                        if self.options.version.supports_pack_unpack_unorm_2x16() {
3513                            "unpackUnorm2x16"
3514                        } else {
3515                            let scale = 65535;
3516
3517                            write!(self.out, "(vec2(")?;
3518                            self.write_expr(arg, ctx)?;
3519                            write!(self.out, " & 0xFFFFu, ")?;
3520                            self.write_expr(arg, ctx)?;
3521                            write!(self.out, " >> 16) / {scale}.0)")?;
3522                            return Ok(());
3523                        }
3524                    }
3525                    Mf::Unpack4x8snorm => {
3526                        if self.options.version.supports_pack_unpack_4x8() {
3527                            "unpackSnorm4x8"
3528                        } else {
3529                            let scale = 127;
3530
3531                            write!(self.out, "(vec4(ivec4(")?;
3532                            self.write_expr(arg, ctx)?;
3533                            write!(self.out, " << 24, ")?;
3534                            self.write_expr(arg, ctx)?;
3535                            write!(self.out, " << 16, ")?;
3536                            self.write_expr(arg, ctx)?;
3537                            write!(self.out, " << 8, ")?;
3538                            self.write_expr(arg, ctx)?;
3539                            write!(self.out, ") >> 24) / {scale}.0)")?;
3540                            return Ok(());
3541                        }
3542                    }
3543                    Mf::Unpack4x8unorm => {
3544                        if self.options.version.supports_pack_unpack_4x8() {
3545                            "unpackUnorm4x8"
3546                        } else {
3547                            let scale = 255;
3548
3549                            write!(self.out, "(vec4(")?;
3550                            self.write_expr(arg, ctx)?;
3551                            write!(self.out, " & 0xFFu, ")?;
3552                            self.write_expr(arg, ctx)?;
3553                            write!(self.out, " >> 8 & 0xFFu, ")?;
3554                            self.write_expr(arg, ctx)?;
3555                            write!(self.out, " >> 16 & 0xFFu, ")?;
3556                            self.write_expr(arg, ctx)?;
3557                            write!(self.out, " >> 24) / {scale}.0)")?;
3558                            return Ok(());
3559                        }
3560                    }
3561                    fun @ (Mf::Unpack4xI8 | Mf::Unpack4xU8) => {
3562                        let sign_prefix = match fun {
3563                            Mf::Unpack4xI8 => 'i',
3564                            Mf::Unpack4xU8 => 'u',
3565                            _ => unreachable!(),
3566                        };
3567                        write!(self.out, "{sign_prefix}vec4(")?;
3568                        for i in 0..4 {
3569                            write!(self.out, "bitfieldExtract(")?;
3570                            // Since bitfieldExtract only sign extends if the value is signed, this
3571                            // cast is needed
3572                            match fun {
3573                                Mf::Unpack4xI8 => {
3574                                    write!(self.out, "int(")?;
3575                                    self.write_expr(arg, ctx)?;
3576                                    write!(self.out, ")")?;
3577                                }
3578                                Mf::Unpack4xU8 => self.write_expr(arg, ctx)?,
3579                                _ => unreachable!(),
3580                            };
3581                            write!(self.out, ", {}, 8)", i * 8)?;
3582                            if i != 3 {
3583                                write!(self.out, ", ")?;
3584                            }
3585                        }
3586                        write!(self.out, ")")?;
3587
3588                        return Ok(());
3589                    }
3590                };
3591
3592                let extract_bits = fun == Mf::ExtractBits;
3593                let insert_bits = fun == Mf::InsertBits;
3594
3595                // Some GLSL functions always return signed integers (like findMSB),
3596                // so they need to be cast to uint if the argument is also an uint.
3597                let ret_might_need_int_to_uint = matches!(
3598                    fun,
3599                    Mf::FirstTrailingBit | Mf::FirstLeadingBit | Mf::CountOneBits | Mf::Abs
3600                );
3601
3602                // Some GLSL functions only accept signed integers (like abs),
3603                // so they need their argument cast from uint to int.
3604                let arg_might_need_uint_to_int = matches!(fun, Mf::Abs);
3605
3606                // Check if the argument is an unsigned integer and return the vector size
3607                // in case it's a vector
3608                let maybe_uint_size = match *ctx.resolve_type(arg, &self.module.types) {
3609                    TypeInner::Scalar(crate::Scalar {
3610                        kind: crate::ScalarKind::Uint,
3611                        ..
3612                    }) => Some(None),
3613                    TypeInner::Vector {
3614                        scalar:
3615                            crate::Scalar {
3616                                kind: crate::ScalarKind::Uint,
3617                                ..
3618                            },
3619                        size,
3620                    } => Some(Some(size)),
3621                    _ => None,
3622                };
3623
3624                // Cast to uint if the function needs it
3625                if ret_might_need_int_to_uint {
3626                    if let Some(maybe_size) = maybe_uint_size {
3627                        match maybe_size {
3628                            Some(size) => write!(self.out, "uvec{}(", size as u8)?,
3629                            None => write!(self.out, "uint(")?,
3630                        }
3631                    }
3632                }
3633
3634                write!(self.out, "{fun_name}(")?;
3635
3636                // Cast to int if the function needs it
3637                if arg_might_need_uint_to_int {
3638                    if let Some(maybe_size) = maybe_uint_size {
3639                        match maybe_size {
3640                            Some(size) => write!(self.out, "ivec{}(", size as u8)?,
3641                            None => write!(self.out, "int(")?,
3642                        }
3643                    }
3644                }
3645
3646                self.write_expr(arg, ctx)?;
3647
3648                // Close the cast from uint to int
3649                if arg_might_need_uint_to_int && maybe_uint_size.is_some() {
3650                    write!(self.out, ")")?
3651                }
3652
3653                if let Some(arg) = arg1 {
3654                    write!(self.out, ", ")?;
3655                    if extract_bits {
3656                        write!(self.out, "int(")?;
3657                        self.write_expr(arg, ctx)?;
3658                        write!(self.out, ")")?;
3659                    } else {
3660                        self.write_expr(arg, ctx)?;
3661                    }
3662                }
3663                if let Some(arg) = arg2 {
3664                    write!(self.out, ", ")?;
3665                    if extract_bits || insert_bits {
3666                        write!(self.out, "int(")?;
3667                        self.write_expr(arg, ctx)?;
3668                        write!(self.out, ")")?;
3669                    } else {
3670                        self.write_expr(arg, ctx)?;
3671                    }
3672                }
3673                if let Some(arg) = arg3 {
3674                    write!(self.out, ", ")?;
3675                    if insert_bits {
3676                        write!(self.out, "int(")?;
3677                        self.write_expr(arg, ctx)?;
3678                        write!(self.out, ")")?;
3679                    } else {
3680                        self.write_expr(arg, ctx)?;
3681                    }
3682                }
3683                write!(self.out, ")")?;
3684
3685                // Close the cast from int to uint
3686                if ret_might_need_int_to_uint && maybe_uint_size.is_some() {
3687                    write!(self.out, ")")?
3688                }
3689            }
3690            // `As` is always a call.
3691            // If `convert` is true the function name is the type
3692            // Else the function name is one of the glsl provided bitcast functions
3693            Expression::As {
3694                expr,
3695                kind: target_kind,
3696                convert,
3697            } => {
3698                let inner = ctx.resolve_type(expr, &self.module.types);
3699                match convert {
3700                    Some(width) => {
3701                        // this is similar to `write_type`, but with the target kind
3702                        let scalar = glsl_scalar(crate::Scalar {
3703                            kind: target_kind,
3704                            width,
3705                        })?;
3706                        match *inner {
3707                            TypeInner::Matrix { columns, rows, .. } => write!(
3708                                self.out,
3709                                "{}mat{}x{}",
3710                                scalar.prefix, columns as u8, rows as u8
3711                            )?,
3712                            TypeInner::Vector { size, .. } => {
3713                                write!(self.out, "{}vec{}", scalar.prefix, size as u8)?
3714                            }
3715                            _ => write!(self.out, "{}", scalar.full)?,
3716                        }
3717
3718                        write!(self.out, "(")?;
3719                        self.write_expr(expr, ctx)?;
3720                        write!(self.out, ")")?
3721                    }
3722                    None => {
3723                        use crate::ScalarKind as Sk;
3724
3725                        let target_vector_type = match *inner {
3726                            TypeInner::Vector { size, scalar } => Some(TypeInner::Vector {
3727                                size,
3728                                scalar: crate::Scalar {
3729                                    kind: target_kind,
3730                                    width: scalar.width,
3731                                },
3732                            }),
3733                            _ => None,
3734                        };
3735
3736                        let source_kind = inner.scalar_kind().unwrap();
3737
3738                        match (source_kind, target_kind, target_vector_type) {
3739                            // No conversion needed
3740                            (Sk::Sint, Sk::Sint, _)
3741                            | (Sk::Uint, Sk::Uint, _)
3742                            | (Sk::Float, Sk::Float, _)
3743                            | (Sk::Bool, Sk::Bool, _) => {
3744                                self.write_expr(expr, ctx)?;
3745                                return Ok(());
3746                            }
3747
3748                            // Cast to/from floats
3749                            (Sk::Float, Sk::Sint, _) => write!(self.out, "floatBitsToInt")?,
3750                            (Sk::Float, Sk::Uint, _) => write!(self.out, "floatBitsToUint")?,
3751                            (Sk::Sint, Sk::Float, _) => write!(self.out, "intBitsToFloat")?,
3752                            (Sk::Uint, Sk::Float, _) => write!(self.out, "uintBitsToFloat")?,
3753
3754                            // Cast between vector types
3755                            (_, _, Some(vector)) => {
3756                                self.write_value_type(&vector)?;
3757                            }
3758
3759                            // There is no way to bitcast between Uint/Sint in glsl. Use constructor conversion
3760                            (Sk::Uint | Sk::Bool, Sk::Sint, None) => write!(self.out, "int")?,
3761                            (Sk::Sint | Sk::Bool, Sk::Uint, None) => write!(self.out, "uint")?,
3762                            (Sk::Bool, Sk::Float, None) => write!(self.out, "float")?,
3763                            (Sk::Sint | Sk::Uint | Sk::Float, Sk::Bool, None) => {
3764                                write!(self.out, "bool")?
3765                            }
3766
3767                            (Sk::AbstractInt | Sk::AbstractFloat, _, _)
3768                            | (_, Sk::AbstractInt | Sk::AbstractFloat, _) => unreachable!(),
3769                        };
3770
3771                        write!(self.out, "(")?;
3772                        self.write_expr(expr, ctx)?;
3773                        write!(self.out, ")")?;
3774                    }
3775                }
3776            }
3777            // These expressions never show up in `Emit`.
3778            Expression::CallResult(_)
3779            | Expression::AtomicResult { .. }
3780            | Expression::RayQueryProceedResult
3781            | Expression::WorkGroupUniformLoadResult { .. }
3782            | Expression::SubgroupOperationResult { .. }
3783            | Expression::SubgroupBallotResult => unreachable!(),
3784            // `ArrayLength` is written as `expr.length()` and we convert it to a uint
3785            Expression::ArrayLength(expr) => {
3786                write!(self.out, "uint(")?;
3787                self.write_expr(expr, ctx)?;
3788                write!(self.out, ".length())")?
3789            }
3790            // not supported yet
3791            Expression::RayQueryGetIntersection { .. }
3792            | Expression::RayQueryVertexPositions { .. }
3793            | Expression::CooperativeLoad { .. }
3794            | Expression::CooperativeMultiplyAdd { .. } => unreachable!(),
3795        }
3796
3797        Ok(())
3798    }
3799
3800    /// Helper function to write the local holding the clamped lod
3801    fn write_clamped_lod(
3802        &mut self,
3803        ctx: &back::FunctionCtx,
3804        expr: Handle<crate::Expression>,
3805        image: Handle<crate::Expression>,
3806        level_expr: Handle<crate::Expression>,
3807    ) -> Result<(), Error> {
3808        // Define our local and start a call to `clamp`
3809        write!(
3810            self.out,
3811            "int {}{} = clamp(",
3812            Baked(expr),
3813            CLAMPED_LOD_SUFFIX
3814        )?;
3815        // Write the lod that will be clamped
3816        self.write_expr(level_expr, ctx)?;
3817        // Set the min value to 0 and start a call to `textureQueryLevels` to get
3818        // the maximum value
3819        write!(self.out, ", 0, textureQueryLevels(")?;
3820        // Write the target image as an argument to `textureQueryLevels`
3821        self.write_expr(image, ctx)?;
3822        // Close the call to `textureQueryLevels` subtract 1 from it since
3823        // the lod argument is 0 based, close the `clamp` call and end the
3824        // local declaration statement.
3825        writeln!(self.out, ") - 1);")?;
3826
3827        Ok(())
3828    }
3829
3830    // Helper method used to retrieve how many elements a coordinate vector
3831    // for the images operations need.
3832    fn get_coordinate_vector_size(&self, dim: crate::ImageDimension, arrayed: bool) -> u8 {
3833        // openGL es doesn't have 1D images so we need workaround it
3834        let tex_1d_hack = dim == crate::ImageDimension::D1 && self.options.version.is_es();
3835        // Get how many components the coordinate vector needs for the dimensions only
3836        let tex_coord_size = match dim {
3837            crate::ImageDimension::D1 => 1,
3838            crate::ImageDimension::D2 => 2,
3839            crate::ImageDimension::D3 => 3,
3840            crate::ImageDimension::Cube => 2,
3841        };
3842        // Calculate the true size of the coordinate vector by adding 1 for arrayed images
3843        // and another 1 if we need to workaround 1D images by making them 2D
3844        tex_coord_size + tex_1d_hack as u8 + arrayed as u8
3845    }
3846
3847    /// Helper method to write the coordinate vector for image operations
3848    fn write_texture_coord(
3849        &mut self,
3850        ctx: &back::FunctionCtx,
3851        vector_size: u8,
3852        coordinate: Handle<crate::Expression>,
3853        array_index: Option<Handle<crate::Expression>>,
3854        // Emulate 1D images as 2D for profiles that don't support it (glsl es)
3855        tex_1d_hack: bool,
3856    ) -> Result<(), Error> {
3857        match array_index {
3858            // If the image needs an array indice we need to add it to the end of our
3859            // coordinate vector, to do so we will use the `ivec(ivec, scalar)`
3860            // constructor notation (NOTE: the inner `ivec` can also be a scalar, this
3861            // is important for 1D arrayed images).
3862            Some(layer_expr) => {
3863                write!(self.out, "ivec{vector_size}(")?;
3864                self.write_expr(coordinate, ctx)?;
3865                write!(self.out, ", ")?;
3866                // If we are replacing sampler1D with sampler2D we also need
3867                // to add another zero to the coordinates vector for the y component
3868                if tex_1d_hack {
3869                    write!(self.out, "0, ")?;
3870                }
3871                self.write_expr(layer_expr, ctx)?;
3872                write!(self.out, ")")?;
3873            }
3874            // Otherwise write just the expression (and the 1D hack if needed)
3875            None => {
3876                let uvec_size = match *ctx.resolve_type(coordinate, &self.module.types) {
3877                    TypeInner::Scalar(crate::Scalar {
3878                        kind: crate::ScalarKind::Uint,
3879                        ..
3880                    }) => Some(None),
3881                    TypeInner::Vector {
3882                        size,
3883                        scalar:
3884                            crate::Scalar {
3885                                kind: crate::ScalarKind::Uint,
3886                                ..
3887                            },
3888                    } => Some(Some(size as u32)),
3889                    _ => None,
3890                };
3891                if tex_1d_hack {
3892                    write!(self.out, "ivec2(")?;
3893                } else if uvec_size.is_some() {
3894                    match uvec_size {
3895                        Some(None) => write!(self.out, "int(")?,
3896                        Some(Some(size)) => write!(self.out, "ivec{size}(")?,
3897                        _ => {}
3898                    }
3899                }
3900                self.write_expr(coordinate, ctx)?;
3901                if tex_1d_hack {
3902                    write!(self.out, ", 0)")?;
3903                } else if uvec_size.is_some() {
3904                    write!(self.out, ")")?;
3905                }
3906            }
3907        }
3908
3909        Ok(())
3910    }
3911
3912    /// Helper method to write the `ImageStore` statement
3913    fn write_image_store(
3914        &mut self,
3915        ctx: &back::FunctionCtx,
3916        image: Handle<crate::Expression>,
3917        coordinate: Handle<crate::Expression>,
3918        array_index: Option<Handle<crate::Expression>>,
3919        value: Handle<crate::Expression>,
3920    ) -> Result<(), Error> {
3921        use crate::ImageDimension as IDim;
3922
3923        // NOTE: openGL requires that `imageStore`s have no effects when the texel is invalid
3924        // so we don't need to generate bounds checks (OpenGL 4.2 Core §3.9.20)
3925
3926        // This will only panic if the module is invalid
3927        let dim = match *ctx.resolve_type(image, &self.module.types) {
3928            TypeInner::Image { dim, .. } => dim,
3929            _ => unreachable!(),
3930        };
3931
3932        // Begin our call to `imageStore`
3933        write!(self.out, "imageStore(")?;
3934        self.write_expr(image, ctx)?;
3935        // Separate the image argument from the coordinates
3936        write!(self.out, ", ")?;
3937
3938        // openGL es doesn't have 1D images so we need workaround it
3939        let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es();
3940        // Write the coordinate vector
3941        self.write_texture_coord(
3942            ctx,
3943            // Get the size of the coordinate vector
3944            self.get_coordinate_vector_size(dim, array_index.is_some()),
3945            coordinate,
3946            array_index,
3947            tex_1d_hack,
3948        )?;
3949
3950        // Separate the coordinate from the value to write and write the expression
3951        // of the value to write.
3952        write!(self.out, ", ")?;
3953        self.write_expr(value, ctx)?;
3954        // End the call to `imageStore` and the statement.
3955        writeln!(self.out, ");")?;
3956
3957        Ok(())
3958    }
3959
3960    /// Helper method to write the `ImageAtomic` statement
3961    fn write_image_atomic(
3962        &mut self,
3963        ctx: &back::FunctionCtx,
3964        image: Handle<crate::Expression>,
3965        coordinate: Handle<crate::Expression>,
3966        array_index: Option<Handle<crate::Expression>>,
3967        fun: crate::AtomicFunction,
3968        value: Handle<crate::Expression>,
3969    ) -> Result<(), Error> {
3970        use crate::ImageDimension as IDim;
3971
3972        // NOTE: openGL requires that `imageAtomic`s have no effects when the texel is invalid
3973        // so we don't need to generate bounds checks (OpenGL 4.2 Core §3.9.20)
3974
3975        // This will only panic if the module is invalid
3976        let dim = match *ctx.resolve_type(image, &self.module.types) {
3977            TypeInner::Image { dim, .. } => dim,
3978            _ => unreachable!(),
3979        };
3980
3981        // Begin our call to `imageAtomic`
3982        let fun_str = fun.to_glsl();
3983        write!(self.out, "imageAtomic{fun_str}(")?;
3984        self.write_expr(image, ctx)?;
3985        // Separate the image argument from the coordinates
3986        write!(self.out, ", ")?;
3987
3988        // openGL es doesn't have 1D images so we need workaround it
3989        let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es();
3990        // Write the coordinate vector
3991        self.write_texture_coord(
3992            ctx,
3993            // Get the size of the coordinate vector
3994            self.get_coordinate_vector_size(dim, false),
3995            coordinate,
3996            array_index,
3997            tex_1d_hack,
3998        )?;
3999
4000        // Separate the coordinate from the value to write and write the expression
4001        // of the value to write.
4002        write!(self.out, ", ")?;
4003        self.write_expr(value, ctx)?;
4004        // End the call to `imageAtomic` and the statement.
4005        writeln!(self.out, ");")?;
4006
4007        Ok(())
4008    }
4009
4010    /// Helper method for writing an `ImageLoad` expression.
4011    #[allow(clippy::too_many_arguments)]
4012    fn write_image_load(
4013        &mut self,
4014        handle: Handle<crate::Expression>,
4015        ctx: &back::FunctionCtx,
4016        image: Handle<crate::Expression>,
4017        coordinate: Handle<crate::Expression>,
4018        array_index: Option<Handle<crate::Expression>>,
4019        sample: Option<Handle<crate::Expression>>,
4020        level: Option<Handle<crate::Expression>>,
4021    ) -> Result<(), Error> {
4022        use crate::ImageDimension as IDim;
4023
4024        // `ImageLoad` is a bit complicated.
4025        // There are two functions one for sampled
4026        // images another for storage images, the former uses `texelFetch` and the
4027        // latter uses `imageLoad`.
4028        //
4029        // Furthermore we have `level` which is always `Some` for sampled images
4030        // and `None` for storage images, so we end up with two functions:
4031        // - `texelFetch(image, coordinate, level)` for sampled images
4032        // - `imageLoad(image, coordinate)` for storage images
4033        //
4034        // Finally we also have to consider bounds checking, for storage images
4035        // this is easy since openGL requires that invalid texels always return
4036        // 0, for sampled images we need to either verify that all arguments are
4037        // in bounds (`ReadZeroSkipWrite`) or make them a valid texel (`Restrict`).
4038
4039        // This will only panic if the module is invalid
4040        let (dim, class) = match *ctx.resolve_type(image, &self.module.types) {
4041            TypeInner::Image {
4042                dim,
4043                arrayed: _,
4044                class,
4045            } => (dim, class),
4046            _ => unreachable!(),
4047        };
4048
4049        // Get the name of the function to be used for the load operation
4050        // and the policy to be used with it.
4051        let (fun_name, policy) = match class {
4052            // Sampled images inherit the policy from the user passed policies
4053            crate::ImageClass::Sampled { .. } => ("texelFetch", self.policies.image_load),
4054            crate::ImageClass::Storage { .. } => {
4055                // OpenGL ES 3.1 mentions in Chapter "8.22 Texture Image Loads and Stores" that:
4056                // "Invalid image loads will return a vector where the value of R, G, and B components
4057                // is 0 and the value of the A component is undefined."
4058                //
4059                // OpenGL 4.2 Core mentions in Chapter "3.9.20 Texture Image Loads and Stores" that:
4060                // "Invalid image loads will return zero."
4061                //
4062                // So, we only inject bounds checks for ES
4063                let policy = if self.options.version.is_es() {
4064                    self.policies.image_load
4065                } else {
4066                    proc::BoundsCheckPolicy::Unchecked
4067                };
4068                ("imageLoad", policy)
4069            }
4070            // TODO: Is there even a function for this?
4071            crate::ImageClass::Depth { multi: _ } => {
4072                return Err(Error::Custom(
4073                    "WGSL `textureLoad` from depth textures is not supported in GLSL".to_string(),
4074                ))
4075            }
4076            crate::ImageClass::External => unimplemented!(),
4077        };
4078
4079        // openGL es doesn't have 1D images so we need workaround it
4080        let tex_1d_hack = dim == IDim::D1 && self.options.version.is_es();
4081        // Get the size of the coordinate vector
4082        let vector_size = self.get_coordinate_vector_size(dim, array_index.is_some());
4083
4084        if let proc::BoundsCheckPolicy::ReadZeroSkipWrite = policy {
4085            // To write the bounds checks for `ReadZeroSkipWrite` we will use a
4086            // ternary operator since we are in the middle of an expression and
4087            // need to return a value.
4088            //
4089            // NOTE: glsl does short circuit when evaluating logical
4090            // expressions so we can be sure that after we test a
4091            // condition it will be true for the next ones
4092
4093            // Write parentheses around the ternary operator to prevent problems with
4094            // expressions emitted before or after it having more precedence
4095            write!(self.out, "(",)?;
4096
4097            // The lod check needs to precede the size check since we need
4098            // to use the lod to get the size of the image at that level.
4099            if let Some(level_expr) = level {
4100                self.write_expr(level_expr, ctx)?;
4101                write!(self.out, " < textureQueryLevels(",)?;
4102                self.write_expr(image, ctx)?;
4103                // Chain the next check
4104                write!(self.out, ") && ")?;
4105            }
4106
4107            // Check that the sample arguments doesn't exceed the number of samples
4108            if let Some(sample_expr) = sample {
4109                self.write_expr(sample_expr, ctx)?;
4110                write!(self.out, " < textureSamples(",)?;
4111                self.write_expr(image, ctx)?;
4112                // Chain the next check
4113                write!(self.out, ") && ")?;
4114            }
4115
4116            // We now need to write the size checks for the coordinates and array index
4117            // first we write the comparison function in case the image is 1D non arrayed
4118            // (and no 1D to 2D hack was needed) we are comparing scalars so the less than
4119            // operator will suffice, but otherwise we'll be comparing two vectors so we'll
4120            // need to use the `lessThan` function but it returns a vector of booleans (one
4121            // for each comparison) so we need to fold it all in one scalar boolean, since
4122            // we want all comparisons to pass we use the `all` function which will only
4123            // return `true` if all the elements of the boolean vector are also `true`.
4124            //
4125            // So we'll end with one of the following forms
4126            // - `coord < textureSize(image, lod)` for 1D images
4127            // - `all(lessThan(coord, textureSize(image, lod)))` for normal images
4128            // - `all(lessThan(ivec(coord, array_index), textureSize(image, lod)))`
4129            //    for arrayed images
4130            // - `all(lessThan(coord, textureSize(image)))` for multi sampled images
4131
4132            if vector_size != 1 {
4133                write!(self.out, "all(lessThan(")?;
4134            }
4135
4136            // Write the coordinate vector
4137            self.write_texture_coord(ctx, vector_size, coordinate, array_index, tex_1d_hack)?;
4138
4139            if vector_size != 1 {
4140                // If we used the `lessThan` function we need to separate the
4141                // coordinates from the image size.
4142                write!(self.out, ", ")?;
4143            } else {
4144                // If we didn't use it (ie. 1D images) we perform the comparison
4145                // using the less than operator.
4146                write!(self.out, " < ")?;
4147            }
4148
4149            // Call `textureSize` to get our image size
4150            write!(self.out, "textureSize(")?;
4151            self.write_expr(image, ctx)?;
4152            // `textureSize` uses the lod as a second argument for mipmapped images
4153            if let Some(level_expr) = level {
4154                // Separate the image from the lod
4155                write!(self.out, ", ")?;
4156                self.write_expr(level_expr, ctx)?;
4157            }
4158            // Close the `textureSize` call
4159            write!(self.out, ")")?;
4160
4161            if vector_size != 1 {
4162                // Close the `all` and `lessThan` calls
4163                write!(self.out, "))")?;
4164            }
4165
4166            // Finally end the condition part of the ternary operator
4167            write!(self.out, " ? ")?;
4168        }
4169
4170        // Begin the call to the function used to load the texel
4171        write!(self.out, "{fun_name}(")?;
4172        self.write_expr(image, ctx)?;
4173        write!(self.out, ", ")?;
4174
4175        // If we are using `Restrict` bounds checking we need to pass valid texel
4176        // coordinates, to do so we use the `clamp` function to get a value between
4177        // 0 and the image size - 1 (indexing begins at 0)
4178        if let proc::BoundsCheckPolicy::Restrict = policy {
4179            write!(self.out, "clamp(")?;
4180        }
4181
4182        // Write the coordinate vector
4183        self.write_texture_coord(ctx, vector_size, coordinate, array_index, tex_1d_hack)?;
4184
4185        // If we are using `Restrict` bounds checking we need to write the rest of the
4186        // clamp we initiated before writing the coordinates.
4187        if let proc::BoundsCheckPolicy::Restrict = policy {
4188            // Write the min value 0
4189            if vector_size == 1 {
4190                write!(self.out, ", 0")?;
4191            } else {
4192                write!(self.out, ", ivec{vector_size}(0)")?;
4193            }
4194            // Start the `textureSize` call to use as the max value.
4195            write!(self.out, ", textureSize(")?;
4196            self.write_expr(image, ctx)?;
4197            // If the image is mipmapped we need to add the lod argument to the
4198            // `textureSize` call, but this needs to be the clamped lod, this should
4199            // have been generated earlier and put in a local.
4200            if class.is_mipmapped() {
4201                write!(self.out, ", {}{}", Baked(handle), CLAMPED_LOD_SUFFIX)?;
4202            }
4203            // Close the `textureSize` call
4204            write!(self.out, ")")?;
4205
4206            // Subtract 1 from the `textureSize` call since the coordinates are zero based.
4207            if vector_size == 1 {
4208                write!(self.out, " - 1")?;
4209            } else {
4210                write!(self.out, " - ivec{vector_size}(1)")?;
4211            }
4212
4213            // Close the `clamp` call
4214            write!(self.out, ")")?;
4215
4216            // Add the clamped lod (if present) as the second argument to the
4217            // image load function.
4218            if level.is_some() {
4219                write!(self.out, ", {}{}", Baked(handle), CLAMPED_LOD_SUFFIX)?;
4220            }
4221
4222            // If a sample argument is needed we need to clamp it between 0 and
4223            // the number of samples the image has.
4224            if let Some(sample_expr) = sample {
4225                write!(self.out, ", clamp(")?;
4226                self.write_expr(sample_expr, ctx)?;
4227                // Set the min value to 0 and start the call to `textureSamples`
4228                write!(self.out, ", 0, textureSamples(")?;
4229                self.write_expr(image, ctx)?;
4230                // Close the `textureSamples` call, subtract 1 from it since the sample
4231                // argument is zero based, and close the `clamp` call
4232                writeln!(self.out, ") - 1)")?;
4233            }
4234        } else if let Some(sample_or_level) = sample.or(level) {
4235            // GLSL only support SInt on this field while WGSL support also UInt
4236            let cast_to_int = matches!(
4237                *ctx.resolve_type(sample_or_level, &self.module.types),
4238                TypeInner::Scalar(crate::Scalar {
4239                    kind: crate::ScalarKind::Uint,
4240                    ..
4241                })
4242            );
4243
4244            // If no bounds checking is need just add the sample or level argument
4245            // after the coordinates
4246            write!(self.out, ", ")?;
4247
4248            if cast_to_int {
4249                write!(self.out, "int(")?;
4250            }
4251
4252            self.write_expr(sample_or_level, ctx)?;
4253
4254            if cast_to_int {
4255                write!(self.out, ")")?;
4256            }
4257        }
4258
4259        // Close the image load function.
4260        write!(self.out, ")")?;
4261
4262        // If we were using the `ReadZeroSkipWrite` policy we need to end the first branch
4263        // (which is taken if the condition is `true`) with a colon (`:`) and write the
4264        // second branch which is just a 0 value.
4265        if let proc::BoundsCheckPolicy::ReadZeroSkipWrite = policy {
4266            // Get the kind of the output value.
4267            let kind = match class {
4268                // Only sampled images can reach here since storage images
4269                // don't need bounds checks and depth images aren't implemented
4270                crate::ImageClass::Sampled { kind, .. } => kind,
4271                _ => unreachable!(),
4272            };
4273
4274            // End the first branch
4275            write!(self.out, " : ")?;
4276            // Write the 0 value
4277            write!(
4278                self.out,
4279                "{}vec4(",
4280                glsl_scalar(crate::Scalar { kind, width: 4 })?.prefix,
4281            )?;
4282            self.write_zero_init_scalar(kind)?;
4283            // Close the zero value constructor
4284            write!(self.out, ")")?;
4285            // Close the parentheses surrounding our ternary
4286            write!(self.out, ")")?;
4287        }
4288
4289        Ok(())
4290    }
4291
4292    fn write_named_expr(
4293        &mut self,
4294        handle: Handle<crate::Expression>,
4295        name: String,
4296        // The expression which is being named.
4297        // Generally, this is the same as handle, except in WorkGroupUniformLoad
4298        named: Handle<crate::Expression>,
4299        ctx: &back::FunctionCtx,
4300    ) -> BackendResult {
4301        match ctx.info[named].ty {
4302            proc::TypeResolution::Handle(ty_handle) => match self.module.types[ty_handle].inner {
4303                TypeInner::Struct { .. } => {
4304                    let ty_name = &self.names[&NameKey::Type(ty_handle)];
4305                    write!(self.out, "{ty_name}")?;
4306                }
4307                _ => {
4308                    self.write_type(ty_handle)?;
4309                }
4310            },
4311            proc::TypeResolution::Value(ref inner) => {
4312                self.write_value_type(inner)?;
4313            }
4314        }
4315
4316        let resolved = ctx.resolve_type(named, &self.module.types);
4317
4318        write!(self.out, " {name}")?;
4319        if let TypeInner::Array { base, size, .. } = *resolved {
4320            self.write_array_size(base, size)?;
4321        }
4322        write!(self.out, " = ")?;
4323        self.write_expr(handle, ctx)?;
4324        writeln!(self.out, ";")?;
4325        self.named_expressions.insert(named, name);
4326
4327        Ok(())
4328    }
4329
4330    /// Helper function that write string with default zero initialization for supported types
4331    fn write_zero_init_value(&mut self, ty: Handle<crate::Type>) -> BackendResult {
4332        let inner = &self.module.types[ty].inner;
4333        match *inner {
4334            TypeInner::Scalar(scalar) | TypeInner::Atomic(scalar) => {
4335                self.write_zero_init_scalar(scalar.kind)?;
4336            }
4337            TypeInner::Vector { scalar, .. } => {
4338                self.write_value_type(inner)?;
4339                write!(self.out, "(")?;
4340                self.write_zero_init_scalar(scalar.kind)?;
4341                write!(self.out, ")")?;
4342            }
4343            TypeInner::Matrix { .. } => {
4344                self.write_value_type(inner)?;
4345                write!(self.out, "(")?;
4346                self.write_zero_init_scalar(crate::ScalarKind::Float)?;
4347                write!(self.out, ")")?;
4348            }
4349            TypeInner::Array { base, size, .. } => {
4350                let count = match size.resolve(self.module.to_ctx())? {
4351                    proc::IndexableLength::Known(count) => count,
4352                    proc::IndexableLength::Dynamic => return Ok(()),
4353                };
4354                self.write_type(base)?;
4355                self.write_array_size(base, size)?;
4356                write!(self.out, "(")?;
4357                for _ in 1..count {
4358                    self.write_zero_init_value(base)?;
4359                    write!(self.out, ", ")?;
4360                }
4361                // write last parameter without comma and space
4362                self.write_zero_init_value(base)?;
4363                write!(self.out, ")")?;
4364            }
4365            TypeInner::Struct { ref members, .. } => {
4366                let name = &self.names[&NameKey::Type(ty)];
4367                write!(self.out, "{name}(")?;
4368                for (index, member) in members.iter().enumerate() {
4369                    if index != 0 {
4370                        write!(self.out, ", ")?;
4371                    }
4372                    self.write_zero_init_value(member.ty)?;
4373                }
4374                write!(self.out, ")")?;
4375            }
4376            _ => unreachable!(),
4377        }
4378
4379        Ok(())
4380    }
4381
4382    /// Helper function that write string with zero initialization for scalar
4383    fn write_zero_init_scalar(&mut self, kind: crate::ScalarKind) -> BackendResult {
4384        match kind {
4385            crate::ScalarKind::Bool => write!(self.out, "false")?,
4386            crate::ScalarKind::Uint => write!(self.out, "0u")?,
4387            crate::ScalarKind::Float => write!(self.out, "0.0")?,
4388            crate::ScalarKind::Sint => write!(self.out, "0")?,
4389            crate::ScalarKind::AbstractInt | crate::ScalarKind::AbstractFloat => {
4390                return Err(Error::Custom(
4391                    "Abstract types should not appear in IR presented to backends".to_string(),
4392                ))
4393            }
4394        }
4395
4396        Ok(())
4397    }
4398
4399    /// Issue a control barrier.
4400    fn write_control_barrier(
4401        &mut self,
4402        flags: crate::Barrier,
4403        level: back::Level,
4404    ) -> BackendResult {
4405        self.write_memory_barrier(flags, level)?;
4406        writeln!(self.out, "{level}barrier();")?;
4407        Ok(())
4408    }
4409
4410    /// Issue a memory barrier.
4411    fn write_memory_barrier(&mut self, flags: crate::Barrier, level: back::Level) -> BackendResult {
4412        if flags.contains(crate::Barrier::STORAGE) {
4413            writeln!(self.out, "{level}memoryBarrierBuffer();")?;
4414        }
4415        if flags.contains(crate::Barrier::WORK_GROUP) {
4416            writeln!(self.out, "{level}memoryBarrierShared();")?;
4417        }
4418        if flags.contains(crate::Barrier::SUB_GROUP) {
4419            writeln!(self.out, "{level}subgroupMemoryBarrier();")?;
4420        }
4421        if flags.contains(crate::Barrier::TEXTURE) {
4422            writeln!(self.out, "{level}memoryBarrierImage();")?;
4423        }
4424        Ok(())
4425    }
4426
4427    /// Helper function that return the glsl storage access string of [`StorageAccess`](crate::StorageAccess)
4428    ///
4429    /// glsl allows adding both `readonly` and `writeonly` but this means that
4430    /// they can only be used to query information about the resource which isn't what
4431    /// we want here so when storage access is both `LOAD` and `STORE` add no modifiers
4432    fn write_storage_access(&mut self, storage_access: crate::StorageAccess) -> BackendResult {
4433        if storage_access.contains(crate::StorageAccess::ATOMIC) {
4434            return Ok(());
4435        }
4436        if !storage_access.contains(crate::StorageAccess::STORE) {
4437            write!(self.out, "readonly ")?;
4438        }
4439        if !storage_access.contains(crate::StorageAccess::LOAD) {
4440            write!(self.out, "writeonly ")?;
4441        }
4442        Ok(())
4443    }
4444
4445    /// Helper method used to produce the reflection info that's returned to the user
4446    fn collect_reflection_info(&mut self) -> Result<ReflectionInfo, Error> {
4447        let info = self.info.get_entry_point(self.entry_point_idx as usize);
4448        let mut texture_mapping = crate::FastHashMap::default();
4449        let mut uniforms = crate::FastHashMap::default();
4450
4451        for sampling in info.sampling_set.iter() {
4452            let tex_name = self.reflection_names_globals[&sampling.image].clone();
4453
4454            match texture_mapping.entry(tex_name) {
4455                hash_map::Entry::Vacant(v) => {
4456                    v.insert(TextureMapping {
4457                        texture: sampling.image,
4458                        sampler: Some(sampling.sampler),
4459                    });
4460                }
4461                hash_map::Entry::Occupied(e) => {
4462                    if e.get().sampler != Some(sampling.sampler) {
4463                        log::error!("Conflicting samplers for {}", e.key());
4464                        return Err(Error::ImageMultipleSamplers);
4465                    }
4466                }
4467            }
4468        }
4469
4470        let mut immediates_info = None;
4471        for (handle, var) in self.module.global_variables.iter() {
4472            if info[handle].is_empty() {
4473                continue;
4474            }
4475            match self.module.types[var.ty].inner {
4476                TypeInner::Image { .. } => {
4477                    let tex_name = self.reflection_names_globals[&handle].clone();
4478                    match texture_mapping.entry(tex_name) {
4479                        hash_map::Entry::Vacant(v) => {
4480                            v.insert(TextureMapping {
4481                                texture: handle,
4482                                sampler: None,
4483                            });
4484                        }
4485                        hash_map::Entry::Occupied(_) => {
4486                            // already used with a sampler, do nothing
4487                        }
4488                    }
4489                }
4490                _ => match var.space {
4491                    crate::AddressSpace::Uniform | crate::AddressSpace::Storage { .. } => {
4492                        let name = self.reflection_names_globals[&handle].clone();
4493                        uniforms.insert(handle, name);
4494                    }
4495                    crate::AddressSpace::Immediate => {
4496                        let name = self.reflection_names_globals[&handle].clone();
4497                        immediates_info = Some((name, var.ty));
4498                    }
4499                    _ => (),
4500                },
4501            }
4502        }
4503
4504        let mut immediates_segments = Vec::new();
4505        let mut immediates_items = vec![];
4506
4507        if let Some((name, ty)) = immediates_info {
4508            // We don't have a layouter available to us, so we need to create one.
4509            //
4510            // This is potentially a bit wasteful, but the set of types in the program
4511            // shouldn't be too large.
4512            let mut layouter = proc::Layouter::default();
4513            layouter.update(self.module.to_ctx()).unwrap();
4514
4515            // We start with the name of the binding itself.
4516            immediates_segments.push(name);
4517
4518            // We then recursively collect all the uniform fields of the immediate data.
4519            self.collect_immediates_items(
4520                ty,
4521                &mut immediates_segments,
4522                &layouter,
4523                &mut 0,
4524                &mut immediates_items,
4525            );
4526        }
4527
4528        Ok(ReflectionInfo {
4529            texture_mapping,
4530            uniforms,
4531            varying: mem::take(&mut self.varying),
4532            immediates_items,
4533            clip_distance_count: self.clip_distance_count,
4534        })
4535    }
4536
4537    fn collect_immediates_items(
4538        &mut self,
4539        ty: Handle<crate::Type>,
4540        segments: &mut Vec<String>,
4541        layouter: &proc::Layouter,
4542        offset: &mut u32,
4543        items: &mut Vec<ImmediateItem>,
4544    ) {
4545        // At this point in the recursion, `segments` contains the path
4546        // needed to access `ty` from the root.
4547
4548        let layout = &layouter[ty];
4549        *offset = layout.alignment.round_up(*offset);
4550        match self.module.types[ty].inner {
4551            // All these types map directly to GL uniforms.
4552            TypeInner::Scalar { .. } | TypeInner::Vector { .. } | TypeInner::Matrix { .. } => {
4553                // Build the full name, by combining all current segments.
4554                let name: String = segments.iter().map(String::as_str).collect();
4555                items.push(ImmediateItem {
4556                    access_path: name,
4557                    offset: *offset,
4558                    ty,
4559                });
4560                *offset += layout.size;
4561            }
4562            // Arrays are recursed into.
4563            TypeInner::Array { base, size, .. } => {
4564                let crate::ArraySize::Constant(count) = size else {
4565                    unreachable!("Cannot have dynamic arrays in immediates");
4566                };
4567
4568                for i in 0..count.get() {
4569                    // Add the array accessor and recurse.
4570                    segments.push(format!("[{i}]"));
4571                    self.collect_immediates_items(base, segments, layouter, offset, items);
4572                    segments.pop();
4573                }
4574
4575                // Ensure the stride is kept by rounding up to the alignment.
4576                *offset = layout.alignment.round_up(*offset)
4577            }
4578            TypeInner::Struct { ref members, .. } => {
4579                for (index, member) in members.iter().enumerate() {
4580                    // Add struct accessor and recurse.
4581                    segments.push(format!(
4582                        ".{}",
4583                        self.names[&NameKey::StructMember(ty, index as u32)]
4584                    ));
4585                    self.collect_immediates_items(member.ty, segments, layouter, offset, items);
4586                    segments.pop();
4587                }
4588
4589                // Ensure ending padding is kept by rounding up to the alignment.
4590                *offset = layout.alignment.round_up(*offset)
4591            }
4592            _ => unreachable!(),
4593        }
4594    }
4595}