Skip to main content

rustc_codegen_spirv/
abi.rs

1//! This file is responsible for translation from rustc tys (`TyAndLayout`) to spir-v types. It's
2//! surprisingly difficult.
3
4use crate::attr::{AggregatedSpirvAttributes, IntrinsicType};
5use crate::codegen_cx::CodegenCx;
6use crate::maybe_pqp_cg_ssa::traits::ConstCodegenMethods as _;
7use crate::spirv_type::{SpirvType, name_type_id};
8use itertools::Itertools;
9use rspirv::spirv::{Dim, ImageFormat, StorageClass, Word};
10use rustc_abi::ExternAbi as Abi;
11use rustc_abi::{
12    Align, BackendRepr, FieldIdx, FieldsShape, Primitive, Scalar, Size, VariantIdx, Variants,
13};
14use rustc_data_structures::fx::FxHashMap;
15use rustc_errors::ErrorGuaranteed;
16use rustc_index::Idx;
17use rustc_middle::ty::layout::{FnAbiOf, LayoutOf, TyAndLayout};
18use rustc_middle::ty::{
19    self, Const, CoroutineArgs, CoroutineArgsExt as _, FloatTy, IntTy, PolyFnSig, Ty, TyCtxt,
20    TyKind, UintTy, ValTreeKindExt,
21};
22use rustc_middle::ty::{GenericArgsRef, ScalarInt};
23use rustc_middle::util::Providers;
24use rustc_middle::{bug, span_bug};
25use rustc_session::config::OptLevel;
26use rustc_span::DUMMY_SP;
27use rustc_span::def_id::DefId;
28use rustc_span::{Span, Symbol};
29use rustc_target::callconv::{ArgAbi, ArgAttributes, FnAbi, PassMode};
30use std::cell::RefCell;
31use std::collections::hash_map::Entry;
32use std::fmt;
33
34fn rewrite_c_abi_to_rust<'tcx>(
35    fn_sig: ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>>,
36) -> ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>> {
37    fn_sig.map_bound(|outer| {
38        outer.map_bound(|inner: ty::FnSig<'_>| {
39            if let Abi::C { .. } = inner.abi() {
40                ty::FnSig {
41                    fn_sig_kind: inner.fn_sig_kind.set_abi(Abi::Rust),
42                    ..inner
43                }
44            } else {
45                inner
46            }
47        })
48    })
49}
50
51pub(crate) fn provide(providers: &mut Providers) {
52    // This is a lil weird: so, we obviously don't support C ABIs at all. However, libcore does declare some extern
53    // C functions:
54    // https://github.com/rust-lang/rust/blob/5fae56971d8487088c0099c82c0a5ce1638b5f62/library/core/src/slice/cmp.rs#L119
55    // However, those functions will be implemented by compiler-builtins:
56    // https://github.com/rust-lang/rust/blob/5fae56971d8487088c0099c82c0a5ce1638b5f62/library/core/src/lib.rs#L23-L27
57    // This theoretically then should be fine to leave as C, but, there's no backend hook for
58    // `FnAbi::adjust_for_cabi`, causing it to panic:
59    // https://github.com/rust-lang/rust/blob/5fae56971d8487088c0099c82c0a5ce1638b5f62/compiler/rustc_target/src/abi/call/mod.rs#L603
60    // So, treat any `extern "C"` functions as `extern "Rust"`, to be able to
61    // compile libcore with arch=spirv.
62    //
63    // NOTE: this used to rewrite to `extern "unadjusted"`, but rustc now
64    // validates `#[rustc_pass_indirectly_in_non_rustic_abis]` for non-Rust ABIs,
65    // and `Unadjusted` does not satisfy that requirement.
66    providers.queries.fn_sig = |tcx, def_id| {
67        // We can't capture the old fn_sig and just call that, because fn_sig is a `fn`, not a `Fn`, i.e. it can't
68        // capture variables. Fortunately, the defaults are exposed (thanks rustdoc), so use that instead.
69        let result = (rustc_interface::DEFAULT_QUERY_PROVIDERS.queries.fn_sig)(tcx, def_id);
70        rewrite_c_abi_to_rust(result)
71    };
72    providers.extern_queries.fn_sig = |tcx, def_id| {
73        // We can't capture the old fn_sig and just call that, because fn_sig is a `fn`, not a `Fn`, i.e. it can't
74        // capture variables. Fortunately, the defaults are exposed (thanks rustdoc), so use that instead.
75        let result = (rustc_interface::DEFAULT_QUERY_PROVIDERS
76            .extern_queries
77            .fn_sig)(tcx, def_id);
78        rewrite_c_abi_to_rust(result)
79    };
80
81    // For the Rust ABI, `FnAbi` adjustments are backend-agnostic, but they will
82    // use features like `PassMode::Cast`, that are incompatible with SPIR-V.
83    // By hooking the queries computing `FnAbi`s, we can recompute the `FnAbi`
84    // from the return/args layouts, to e.g. prefer using `PassMode::Direct`.
85    fn readjust_fn_abi<'tcx>(
86        tcx: TyCtxt<'tcx>,
87        fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
88    ) -> &'tcx FnAbi<'tcx, Ty<'tcx>> {
89        let readjust_arg_abi = |arg: &ArgAbi<'tcx, Ty<'tcx>>| {
90            let mut arg = ArgAbi::new(arg.layout, |_, _| ArgAttributes::new());
91            // FIXME: this is bad! https://github.com/rust-lang/rust/issues/115666
92            // <https://github.com/rust-lang/rust/commit/eaaa03faf77b157907894a4207d8378ecaec7b45>
93            // replaces removed `arg.make_direct_deprecated();`
94            arg.mode = if let PassMode::Indirect { .. } = arg.mode {
95                PassMode::Direct(ArgAttributes::new())
96            } else if arg.layout.is_zst() {
97                PassMode::Ignore
98            } else if let PassMode::Ignore | PassMode::Direct(..) | PassMode::Pair(..) = arg.mode {
99                arg.mode
100            } else {
101                panic!("Tried to make {:?} direct", arg.mode)
102            };
103
104            // Avoid pointlessly passing ZSTs, just like the official Rust ABI.
105            if arg.layout.is_zst() {
106                arg.mode = PassMode::Ignore;
107            }
108
109            arg
110        };
111        tcx.arena.alloc(FnAbi {
112            args: fn_abi.args.iter().map(readjust_arg_abi).collect(),
113            ret: readjust_arg_abi(&fn_abi.ret),
114
115            // FIXME(eddyb) validate some of these, and report errors - however,
116            // we can't just emit errors from here, since we have no `Span`, so
117            // we should have instead a check on MIR for e.g. C variadic calls.
118            c_variadic: fn_abi.c_variadic,
119            fixed_count: fn_abi.fixed_count,
120            conv: fn_abi.conv,
121            can_unwind: fn_abi.can_unwind,
122        })
123    }
124    providers.queries.fn_abi_of_fn_ptr = |tcx, key| {
125        let result = (rustc_interface::DEFAULT_QUERY_PROVIDERS
126            .queries
127            .fn_abi_of_fn_ptr)(tcx, key);
128        Ok(readjust_fn_abi(tcx, result?))
129    };
130    providers.queries.fn_abi_of_instance_no_deduced_attrs = |tcx, key| {
131        let result = (rustc_interface::DEFAULT_QUERY_PROVIDERS
132            .queries
133            .fn_abi_of_instance_no_deduced_attrs)(tcx, key);
134        // Keep this query in its original shape while `fn_abi_of_instance_raw`
135        // is being computed: rustc validates strict invariants there.
136        // Otherwise, if `fn_abi_of_instance` would route through this query
137        // directly (e.g. incremental or opt-level=0), apply SPIR-V readjustment.
138        if tcx.sess.opts.optimize != OptLevel::No && tcx.sess.opts.incremental.is_none() {
139            result
140        } else {
141            Ok(readjust_fn_abi(tcx, result?))
142        }
143    };
144    providers.queries.fn_abi_of_instance_raw = |tcx, key| {
145        let result = (rustc_interface::DEFAULT_QUERY_PROVIDERS
146            .queries
147            .fn_abi_of_instance_raw)(tcx, key);
148        Ok(readjust_fn_abi(tcx, result?))
149    };
150
151    // HACK(eddyb) work around https://github.com/rust-lang/rust/pull/132173
152    // (and further changes from https://github.com/rust-lang/rust/pull/132843)
153    // starting to ban SIMD ABI misuse (or at least starting to warn about it).
154    //
155    // FIXME(eddyb) same as the FIXME comment on `check_well_formed`:
156    // need to migrate away from `#[repr(simd)]` ASAP.
157    providers.queries.check_mono_item = |_, _| {};
158}
159
160/// If a struct contains a pointer to itself, even indirectly, then doing a naiive recursive walk
161/// of the fields will result in an infinite loop. Because pointers are the only thing that are
162/// allowed to be recursive, keep track of what pointers we've translated, or are currently in the
163/// progress of translating, and break the recursion that way. This struct manages that state
164/// tracking.
165#[derive(Default)]
166pub struct RecursivePointeeCache<'tcx> {
167    map: RefCell<FxHashMap<PointeeTy<'tcx>, PointeeDefState>>,
168}
169
170impl<'tcx> RecursivePointeeCache<'tcx> {
171    fn begin(&self, cx: &CodegenCx<'tcx>, span: Span, pointee: PointeeTy<'tcx>) -> Option<Word> {
172        match self.map.borrow_mut().entry(pointee) {
173            // State: This is the first time we've seen this type. Record that we're beginning to translate this type,
174            // and start doing the translation.
175            Entry::Vacant(entry) => {
176                entry.insert(PointeeDefState::Defining);
177                None
178            }
179            Entry::Occupied(mut entry) => match *entry.get() {
180                // State: This is the second time we've seen this type, and we're already translating this type. If we
181                // were to try to translate the type now, we'd get a stack overflow, due to continually recursing. So,
182                // emit an OpTypeForwardPointer, and use that ID. (This is the juicy part of this algorithm)
183                PointeeDefState::Defining => {
184                    let new_id = cx.emit_global().id();
185                    // NOTE(eddyb) we emit `StorageClass::Generic` here, but later
186                    // the linker will specialize the entire SPIR-V module to use
187                    // storage classes inferred from `OpVariable`s.
188                    cx.emit_global()
189                        .type_forward_pointer(new_id, StorageClass::Generic);
190                    entry.insert(PointeeDefState::DefiningWithForward(new_id));
191                    cx.zombie_with_span(
192                        new_id,
193                        span,
194                        "cannot create self-referential types, even through pointers",
195                    );
196                    Some(new_id)
197                }
198                // State: This is the third or more time we've seen this type, and we've already emitted an
199                // OpTypeForwardPointer. Just use the ID we've already emitted. (Alternatively, we already defined this
200                // type, so just use that.)
201                PointeeDefState::DefiningWithForward(id) | PointeeDefState::Defined(id) => Some(id),
202            },
203        }
204    }
205
206    fn end(
207        &self,
208        cx: &CodegenCx<'tcx>,
209        span: Span,
210        pointee: PointeeTy<'tcx>,
211        pointee_spv: Word,
212    ) -> Word {
213        match self.map.borrow_mut().entry(pointee) {
214            // We should have hit begin() on this type already, which always inserts an entry.
215            Entry::Vacant(_) => {
216                span_bug!(span, "RecursivePointeeCache::end should always have entry")
217            }
218            Entry::Occupied(mut entry) => match *entry.get() {
219                // State: There have been no recursive references to this type while defining it, and so no
220                // OpTypeForwardPointer has been emitted. This is the most common case.
221                PointeeDefState::Defining => {
222                    let id = SpirvType::Pointer {
223                        pointee: pointee_spv,
224                    }
225                    .def(span, cx);
226                    entry.insert(PointeeDefState::Defined(id));
227                    id
228                }
229                // State: There was a recursive reference to this type, and so an OpTypeForwardPointer has been emitted.
230                // Make sure to use the same ID.
231                PointeeDefState::DefiningWithForward(id) => {
232                    entry.insert(PointeeDefState::Defined(id));
233                    SpirvType::Pointer {
234                        pointee: pointee_spv,
235                    }
236                    .def_with_id(cx, span, id)
237                }
238                PointeeDefState::Defined(_) => {
239                    span_bug!(span, "RecursivePointeeCache::end defined pointer twice")
240                }
241            },
242        }
243    }
244}
245
246#[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
247enum PointeeTy<'tcx> {
248    Ty(TyAndLayout<'tcx>),
249    Fn(PolyFnSig<'tcx>),
250}
251
252impl fmt::Display for PointeeTy<'_> {
253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254        match self {
255            PointeeTy::Ty(ty) => write!(f, "{}", ty.ty),
256            PointeeTy::Fn(ty) => write!(f, "{ty}"),
257        }
258    }
259}
260
261enum PointeeDefState {
262    Defining,
263    DefiningWithForward(Word),
264    Defined(Word),
265}
266
267/// Various type-like things can be converted to a spirv type - normal types, function types, etc. - and this trait
268/// provides a uniform way of translating them.
269pub trait ConvSpirvType<'tcx> {
270    fn spirv_type(&self, span: Span, cx: &CodegenCx<'tcx>) -> Word;
271}
272
273impl<'tcx> ConvSpirvType<'tcx> for PointeeTy<'tcx> {
274    fn spirv_type(&self, span: Span, cx: &CodegenCx<'tcx>) -> Word {
275        match *self {
276            PointeeTy::Ty(ty) => ty.spirv_type(span, cx),
277            PointeeTy::Fn(ty) => cx
278                .fn_abi_of_fn_ptr(ty, ty::List::empty())
279                .spirv_type(span, cx),
280        }
281    }
282}
283
284impl<'tcx> ConvSpirvType<'tcx> for FnAbi<'tcx, Ty<'tcx>> {
285    fn spirv_type(&self, span: Span, cx: &CodegenCx<'tcx>) -> Word {
286        // FIXME(eddyb) use `AccumulateVec`s just like `rustc` itself does.
287        let mut argument_types = Vec::new();
288
289        let return_type = match self.ret.mode {
290            PassMode::Ignore => SpirvType::Void.def(span, cx),
291            PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.spirv_type(span, cx),
292            PassMode::Cast { .. } | PassMode::Indirect { .. } => span_bug!(
293                span,
294                "query hooks should've made this `PassMode` impossible: {:#?}",
295                self.ret
296            ),
297        };
298
299        for arg in self.args.iter() {
300            let arg_type = match arg.mode {
301                PassMode::Ignore => continue,
302                PassMode::Direct(_) => arg.layout.spirv_type(span, cx),
303                PassMode::Pair(_, _) => {
304                    argument_types.push(scalar_pair_element_backend_type(cx, span, arg.layout, 0));
305                    argument_types.push(scalar_pair_element_backend_type(cx, span, arg.layout, 1));
306                    continue;
307                }
308                PassMode::Cast { .. } | PassMode::Indirect { .. } => span_bug!(
309                    span,
310                    "query hooks should've made this `PassMode` impossible: {:#?}",
311                    arg
312                ),
313            };
314            argument_types.push(arg_type);
315        }
316
317        SpirvType::Function {
318            return_type,
319            arguments: &argument_types,
320        }
321        .def(span, cx)
322    }
323}
324
325/// If `layout` has exactly one non-ZST field positioned at offset 0 with size and
326/// alignment matching the outer layout, returns that field.
327///
328/// This captures the structural shape of a "newtype wrapper" — a single meaningful
329/// field padded out to the outer type, which can be substituted for the outer type
330/// in a SPIR-V type graph as long as the caller has *independently* verified that
331/// the ABIs match (either via `BackendRepr::eq_up_to_validity`, or via
332/// `#[repr(transparent)]`, which guarantees full ABI identity by construction).
333fn sole_structural_newtype_field<'tcx>(
334    cx: &CodegenCx<'tcx>,
335    layout: TyAndLayout<'tcx>,
336) -> Option<TyAndLayout<'tcx>> {
337    let mut non_zst = (0..layout.fields.count()).filter(|&i| !layout.field(cx, i).is_zst());
338    let i = non_zst.next()?;
339    if non_zst.next().is_some() {
340        return None;
341    }
342    let field = layout.field(cx, i);
343    // Only unpack a newtype if the field and the newtype line up
344    // perfectly, in every way that could potentially affect ABI.
345    (layout.fields.offset(i) == Size::ZERO
346        && field.size == layout.size
347        && field.align.abi == layout.align.abi
348        && field.backend_repr.eq_up_to_validity(&layout.backend_repr))
349    .then_some(field)
350}
351
352impl<'tcx> ConvSpirvType<'tcx> for TyAndLayout<'tcx> {
353    fn spirv_type(&self, mut span: Span, cx: &CodegenCx<'tcx>) -> Word {
354        if let TyKind::Adt(adt, args) = *self.ty.kind() {
355            if span == DUMMY_SP {
356                span = cx.tcx.def_span(adt.did());
357            }
358
359            let attrs = AggregatedSpirvAttributes::parse(
360                cx,
361                cx.tcx
362                    .get_attrs_by_path(
363                        adt.did(),
364                        &[cx.sym.rust_gpu, cx.sym.spirv_attr_with_version],
365                    )
366                    .chain(cx.tcx.get_attrs_by_path(
367                        adt.did(),
368                        &[cx.sym.rust_gpu, cx.sym.vector, cx.sym.v1],
369                    )),
370            );
371
372            if let Some(intrinsic_type_attr) = attrs.intrinsic_type.map(|attr| attr.value)
373                && let Ok(spirv_type) =
374                    trans_intrinsic_type(cx, span, *self, args, intrinsic_type_attr)
375            {
376                return spirv_type;
377            }
378        }
379
380        // Note: ty.layout is orthogonal to ty.ty, e.g. `ManuallyDrop<Result<isize, isize>>` has abi
381        // `ScalarPair`.
382        // There's a few layers that we go through here. First we inspect layout.backend_repr, then if relevant, layout.fields, etc.
383        match self.backend_repr {
384            _ if self.uninhabited => SpirvType::Adt {
385                def_id: def_id_for_spirv_type_adt(*self),
386                size: Some(Size::ZERO),
387                align: Align::from_bytes(0).unwrap(),
388                field_types: &[],
389                field_offsets: &[],
390                field_names: None,
391            }
392            .def_with_name(cx, span, TyLayoutNameKey::from(*self)),
393            BackendRepr::Scalar(scalar) => trans_scalar(cx, span, *self, scalar, Size::ZERO),
394            BackendRepr::ScalarPair { a, b, .. } => {
395                // NOTE(eddyb) unlike `BackendRepr::Scalar`'s simpler newtype-unpacking
396                // behavior, `BackendRepr::ScalarPair` can be composed in two ways:
397                // * two `BackendRepr::Scalar` fields (and any number of ZST fields),
398                //   gets handled the same as a `struct { a, b }`, further below
399                // * an `BackendRepr::ScalarPair` field (and any number of ZST fields),
400                //   which requires more work to allow taking a reference to
401                //   that field, and there are two potential approaches:
402                //   1. wrapping that field's SPIR-V type in a single-field
403                //      `OpTypeStruct` - this has the disadvantage that GEPs
404                //      would have to inject an extra `0` field index, and other
405                //      field-related operations would also need additional work
406                //   2. reusing that field's SPIR-V type, instead of defining
407                //      a new one, offering the `(a, b)` shape `rustc_codegen_ssa`
408                //      expects, while letting noop pointercasts access the sole
409                //      `BackendRepr::ScalarPair` field - this is the approach taken here
410                if let Some(field) = sole_structural_newtype_field(cx, *self) {
411                    return field.spirv_type(span, cx);
412                }
413
414                // Note: We can't use auto_struct_layout here because the spirv types here might be undefined due to
415                // recursive pointer types.
416                let a_offset = Size::ZERO;
417                let b_offset = a
418                    .primitive()
419                    .size(cx)
420                    .align_to(b.primitive().default_align(cx).abi);
421                let a = trans_scalar(cx, span, *self, a, a_offset);
422                let b = trans_scalar(cx, span, *self, b, b_offset);
423                let size = if self.is_unsized() {
424                    None
425                } else {
426                    Some(self.size)
427                };
428                // FIXME(eddyb) use `ArrayVec` here.
429                let mut field_names = Vec::new();
430                if let TyKind::Adt(adt, _) = self.ty.kind()
431                    && let Variants::Single { index } = self.variants
432                {
433                    for i in self.fields.index_by_increasing_offset() {
434                        let field = &adt.variants()[index].fields[FieldIdx::new(i)];
435                        field_names.push(field.name);
436                    }
437                }
438                SpirvType::Adt {
439                    def_id: def_id_for_spirv_type_adt(*self),
440                    size,
441                    align: self.align.abi,
442                    field_types: &[a, b],
443                    field_offsets: &[a_offset, b_offset],
444                    field_names: if field_names.len() == 2 {
445                        Some(&field_names)
446                    } else {
447                        None
448                    },
449                }
450                .def_with_name(cx, span, TyLayoutNameKey::from(*self))
451            }
452            BackendRepr::SimdVector { element, count } => {
453                let elem_spirv = trans_scalar(cx, span, *self, element, Size::ZERO);
454                SpirvType::Vector {
455                    element: elem_spirv,
456                    count: count.as_u32(),
457                    size: self.size,
458                    align: self.align.abi,
459                }
460                .def(span, cx)
461            }
462            BackendRepr::SimdScalableVector { .. } => cx
463                .tcx
464                .dcx()
465                .fatal("scalable vectors are not supported in SPIR-V backend"),
466            BackendRepr::Memory { sized: _ } => {
467                // For `#[repr(transparent)]` newtypes, reuse the single non-ZST
468                // field's SPIR-V type directly instead of wrapping it in an
469                // `OpTypeStruct`, if the type is `#[repr(transparent)]`.
470                // Otherwise, we're manipulating the abi too much and the
471                // format args decompiler fails.
472                if let TyKind::Adt(adt, _) = self.ty.kind()
473                    && adt.repr().transparent()
474                    && let Some(field) = sole_structural_newtype_field(cx, *self)
475                {
476                    let inner_id = field.spirv_type(span, cx);
477                    // Preserve the wrapper's name as an `OpName` alias on the
478                    // inner SPIR-V type so disassembly still shows it.
479                    name_type_id(cx, inner_id, TyLayoutNameKey::from(*self));
480                    return inner_id;
481                }
482                trans_aggregate(cx, span, *self)
483            }
484        }
485    }
486}
487
488/// Only pub for `LayoutTypeCodegenMethods::scalar_pair_element_backend_type`. Think about what you're
489/// doing before calling this.
490pub fn scalar_pair_element_backend_type<'tcx>(
491    cx: &CodegenCx<'tcx>,
492    span: Span,
493    ty: TyAndLayout<'tcx>,
494    index: usize,
495) -> Word {
496    let [a, b] = match ty.backend_repr {
497        BackendRepr::ScalarPair { a, b, .. } => [a, b],
498        other => span_bug!(
499            span,
500            "scalar_pair_element_backend_type invalid abi: {:?}",
501            other
502        ),
503    };
504    let offset = match index {
505        0 => Size::ZERO,
506        1 => a
507            .primitive()
508            .size(cx)
509            .align_to(b.primitive().default_align(cx).abi),
510        _ => unreachable!(),
511    };
512    trans_scalar(cx, span, ty, [a, b][index], offset)
513}
514
515/// A "scalar" is a basic building block: bools, ints, floats, pointers. (i.e. not something complex like a struct)
516/// A "scalar pair" is a bit of a strange concept: if there is a `fn f(x: (u32, u32))`, then what's preferred for
517/// performance is to compile that ABI to `f(x_1: u32, x_2: u32)`, i.e. splitting out the pair into their own arguments,
518/// and pretending that they're one unit. So, there's quite a bit of special handling around these scalar pairs to enable
519/// scenarios like that.
520/// I say it's "preferred", but spirv doesn't really care - only CPU ABIs really care here. However, following rustc's
521/// lead and doing what they want makes things go smoothly, so we'll implement it here too.
522fn trans_scalar<'tcx>(
523    cx: &CodegenCx<'tcx>,
524    span: Span,
525    ty: TyAndLayout<'tcx>,
526    scalar: Scalar,
527    offset: Size,
528) -> Word {
529    if scalar.is_bool() {
530        return SpirvType::Bool.def(span, cx);
531    }
532
533    match scalar.primitive() {
534        Primitive::Int(int_kind, signedness) => {
535            SpirvType::Integer(int_kind.size().bits() as u32, signedness).def(span, cx)
536        }
537        Primitive::Float(float_kind) => {
538            SpirvType::Float(float_kind.size().bits() as u32).def(span, cx)
539        }
540        Primitive::Pointer(_) => {
541            let pointee_ty = dig_scalar_pointee(cx, ty, offset);
542            // Pointers can be recursive. So, record what we're currently translating, and if we're already translating
543            // the same type, emit an OpTypeForwardPointer and use that ID.
544            if let Some(predefined_result) = cx
545                .type_cache
546                .recursive_pointee_cache
547                .begin(cx, span, pointee_ty)
548            {
549                predefined_result
550            } else {
551                let pointee = pointee_ty.spirv_type(span, cx);
552                cx.type_cache
553                    .recursive_pointee_cache
554                    .end(cx, span, pointee_ty, pointee)
555            }
556        }
557    }
558}
559
560// This is a really weird function, strap in...
561// So, rustc_codegen_ssa is designed around scalar pointers being opaque, you shouldn't know the type behind the
562// pointer. Unfortunately, that's impossible for us, we need to know the underlying pointee type for various reasons. In
563// some cases, this is pretty easy - if it's a TyKind::Ref, then the pointee will be the pointee of the ref (with
564// handling for wide pointers, etc.). Unfortunately, there's some pretty advanced processing going on in cx.layout_of:
565// for example, `ManuallyDrop<Result<ptr, ptr>>` has abi `ScalarPair`. This means that to figure out the pointee type,
566// we have to replicate the logic of cx.layout_of. Part of that is digging into types that are aggregates: for example,
567// ManuallyDrop<T> has a single field of type T. We "dig into" that field, and recurse, trying to find a base case that
568// we can handle, like TyKind::Ref.
569// If the above didn't make sense, please poke Ashley, it's probably easier to explain via conversation.
570fn dig_scalar_pointee<'tcx>(
571    cx: &CodegenCx<'tcx>,
572    layout: TyAndLayout<'tcx>,
573    offset: Size,
574) -> PointeeTy<'tcx> {
575    if let FieldsShape::Primitive = layout.fields {
576        assert_eq!(offset, Size::ZERO);
577        let pointee = match *layout.ty.kind() {
578            TyKind::Ref(_, pointee_ty, _) | TyKind::RawPtr(pointee_ty, _) => {
579                PointeeTy::Ty(cx.layout_of(pointee_ty))
580            }
581            TyKind::FnPtr(sig_tys, hdr) => PointeeTy::Fn(sig_tys.with(hdr)),
582            _ => bug!("Pointer is not `&T`, `*T` or `fn` pointer: {:#?}", layout),
583        };
584        return pointee;
585    }
586
587    let all_fields = (match &layout.variants {
588        Variants::Empty => 0..0,
589        Variants::Multiple { variants, .. } => 0..variants.len(),
590        Variants::Single { index } => {
591            let i = index.as_usize();
592            i..i + 1
593        }
594    })
595    .flat_map(|variant_idx| {
596        let variant = layout.for_variant(cx, VariantIdx::new(variant_idx));
597        (0..variant.fields.count()).map(move |field_idx| {
598            (
599                variant.field(cx, field_idx),
600                variant.fields.offset(field_idx),
601            )
602        })
603    });
604
605    let mut pointee = None;
606    for (field, field_offset) in all_fields {
607        if field.is_zst() {
608            continue;
609        }
610        if (field_offset..field_offset + field.size).contains(&offset) {
611            let new_pointee = dig_scalar_pointee(cx, field, offset - field_offset);
612            match pointee {
613                Some(old_pointee) if old_pointee != new_pointee => {
614                    cx.tcx.dcx().fatal(format!(
615                        "dig_scalar_pointee: unsupported Pointer with different \
616                         pointee types ({old_pointee:?} vs {new_pointee:?}) at offset {offset:?} in {layout:#?}"
617                    ));
618                }
619                _ => pointee = Some(new_pointee),
620            }
621        }
622    }
623    pointee.unwrap_or_else(|| {
624        bug!(
625            "field containing Pointer scalar at offset {:?} not found in {:#?}",
626            offset,
627            layout
628        )
629    })
630}
631
632// FIXME(eddyb) all `ty: TyAndLayout` variables should be `layout: TyAndLayout`,
633// the type is really more "Layout with Ty" (`.ty` field + `Deref`s to `Layout`).
634fn trans_aggregate<'tcx>(cx: &CodegenCx<'tcx>, span: Span, ty: TyAndLayout<'tcx>) -> Word {
635    fn create_zst<'tcx>(cx: &CodegenCx<'tcx>, span: Span, ty: TyAndLayout<'tcx>) -> Word {
636        assert_eq!(ty.size, Size::ZERO);
637        SpirvType::Adt {
638            def_id: def_id_for_spirv_type_adt(ty),
639            size: Some(Size::ZERO),
640            align: ty.align.abi,
641            field_types: &[],
642            field_offsets: &[],
643            field_names: None,
644        }
645        .def_with_name(cx, span, TyLayoutNameKey::from(ty))
646    }
647    match ty.fields {
648        FieldsShape::Primitive => span_bug!(
649            span,
650            "trans_aggregate called for FieldsShape::Primitive layout {:#?}",
651            ty
652        ),
653        FieldsShape::Union(_) => {
654            assert!(!ty.is_unsized(), "{ty:#?}");
655
656            // Represent the `union` with its largest case, which should work
657            // for at least `MaybeUninit<T>` (which is between `T` and `()`),
658            // but also potentially some other ones as well.
659            // NOTE(eddyb) even if long-term this may become a byte array, that
660            // only works for "data types" and not "opaque handles" (images etc.).
661            let largest_case = (0..ty.fields.count())
662                .map(|i| (FieldIdx::from_usize(i), ty.field(cx, i)))
663                .max_by_key(|(_, case)| case.size);
664
665            if let Some((case_idx, case)) = largest_case {
666                if ty.align != case.align {
667                    // HACK(eddyb) mismatched alignment requires a wrapper `struct`.
668                    trans_struct_or_union(cx, span, ty, Some(case_idx))
669                } else {
670                    assert_eq!(ty.size, case.size);
671                    case.spirv_type(span, cx)
672                }
673            } else {
674                create_zst(cx, span, ty)
675            }
676        }
677        FieldsShape::Array { stride, count } => {
678            let element_type = ty.field(cx, 0).spirv_type(span, cx);
679            if ty.is_unsized() {
680                // There's a potential for this array to be sized, but the element to be unsized, e.g. `[[u8]; 5]`.
681                // However, I think rust disallows all these cases, so assert this here.
682                assert_eq!(count, 0);
683                SpirvType::RuntimeArray {
684                    element: element_type,
685                }
686                .def(span, cx)
687            } else if count == 0 {
688                // spir-v doesn't support zero-sized arrays
689                create_zst(cx, span, ty)
690            } else {
691                let count_const = cx.constant_u32(span, count as u32);
692                let element_spv = cx.lookup_type(element_type);
693                let stride_spv = element_spv
694                    .sizeof(cx)
695                    .expect("Unexpected unsized type in sized FieldsShape::Array")
696                    .align_to(element_spv.alignof(cx));
697                assert_eq!(stride_spv, stride);
698                SpirvType::Array {
699                    element: element_type,
700                    count: count_const,
701                }
702                .def(span, cx)
703            }
704        }
705        FieldsShape::Arbitrary { .. } => trans_struct_or_union(cx, span, ty, None),
706    }
707}
708
709// returns (field_offsets, size, align)
710pub fn auto_struct_layout(
711    cx: &CodegenCx<'_>,
712    field_types: &[Word],
713) -> (Vec<Size>, Option<Size>, Align) {
714    // FIXME(eddyb) use `AccumulateVec`s just like `rustc` itself does.
715    let mut field_offsets = Vec::with_capacity(field_types.len());
716    let mut offset = Some(Size::ZERO);
717    let mut max_align = Align::from_bytes(0).unwrap();
718    for &field_type in field_types {
719        let spirv_type = cx.lookup_type(field_type);
720        let field_size = spirv_type.sizeof(cx);
721        let field_align = spirv_type.alignof(cx);
722        let this_offset = offset
723            .expect("Unsized values can only be the last field in a struct")
724            .align_to(field_align);
725
726        field_offsets.push(this_offset);
727        if field_align > max_align {
728            max_align = field_align;
729        }
730        offset = field_size.map(|size| this_offset + size);
731    }
732    (field_offsets, offset, max_align)
733}
734
735// see struct_llfields in librustc_codegen_llvm for implementation hints
736fn trans_struct_or_union<'tcx>(
737    cx: &CodegenCx<'tcx>,
738    span: Span,
739    ty: TyAndLayout<'tcx>,
740    union_case: Option<FieldIdx>,
741) -> Word {
742    let size = if ty.is_unsized() { None } else { Some(ty.size) };
743    let align = ty.align.abi;
744    // FIXME(eddyb) use `AccumulateVec`s just like `rustc` itself does.
745    let mut field_types = Vec::new();
746    let mut field_offsets = Vec::new();
747    let mut field_names = Vec::new();
748    for i in ty.fields.index_by_increasing_offset() {
749        if let Some(expected_field_idx) = union_case
750            && i != expected_field_idx.as_usize()
751        {
752            continue;
753        }
754
755        let field_ty = ty.field(cx, i);
756        field_types.push(field_ty.spirv_type(span, cx));
757        let offset = ty.fields.offset(i);
758        field_offsets.push(offset);
759        if let Variants::Single { index } = ty.variants {
760            if let TyKind::Adt(adt, _) = ty.ty.kind() {
761                let field = &adt.variants()[index].fields[FieldIdx::new(i)];
762                field_names.push(field.name);
763            } else {
764                // FIXME(eddyb) this looks like something that should exist in rustc.
765                field_names.push(Symbol::intern(&format!("{i}")));
766            }
767        } else {
768            if let TyKind::Adt(_, _) = ty.ty.kind() {
769            } else {
770                span_bug!(span, "Variants::Multiple not TyKind::Adt");
771            }
772            if i == 0 {
773                field_names.push(cx.sym.discriminant);
774            } else {
775                cx.tcx.dcx().fatal("Variants::Multiple has multiple fields")
776            }
777        };
778    }
779
780    // The loop above only emits a multi-variant `enum`'s tag, not its variant
781    // payloads. `rustc_codegen_ssa` accesses payload fields by byte offset
782    // (`inbounds_ptradd` after a downcast), so for `BackendRepr::Memory` `enum`s
783    // the payload fields must be present to recover a valid `OpAccessChain`,
784    // otherwise it's zombie'd as "cannot offset a pointer to an arbitrary element".
785    //
786    // So also emit each variant's non-ZST payload fields at their offsets,
787    // skipping any that overlap an already-present field (struct fields can't
788    // overlap). This should eventually be replaced with untyped memory + `qptr`.
789    if union_case.is_none()
790        && let Variants::Multiple { variants, .. } = &ty.variants
791    {
792        // Track the byte ranges already covered, to reject overlapping payloads.
793        let mut covered: Vec<(Size, Size)> = field_offsets
794            .iter()
795            .zip(&field_types)
796            .map(|(&offset, &field_ty)| {
797                let end = cx
798                    .lookup_type(field_ty)
799                    .sizeof(cx)
800                    .map_or(offset, |size| offset + size);
801                (offset, end)
802            })
803            .collect();
804
805        let mut extra = Vec::new();
806        for variant_idx in variants.indices() {
807            let variant = ty.for_variant(cx, variant_idx);
808            for i in variant.fields.index_by_increasing_offset() {
809                let field = variant.field(cx, i);
810                if field.is_zst() {
811                    continue;
812                }
813                let offset = variant.fields.offset(i);
814                let end = offset + field.size;
815                if covered.iter().any(|&(o, e)| offset < e && o < end) {
816                    continue;
817                }
818                covered.push((offset, end));
819                let name = match ty.ty.kind() {
820                    TyKind::Adt(adt, _) => {
821                        adt.variants()[variant_idx].fields[FieldIdx::new(i)].name
822                    }
823                    _ => Symbol::intern(&format!("variant{}_field{i}", variant_idx.as_usize())),
824                };
825                extra.push((offset, field.spirv_type(span, cx), name));
826            }
827        }
828
829        // Merge in the payload fields, sorted by offset so the tag stays field
830        // `0` (required by `recover_access_chain_from_offset` and discriminant
831        // access).
832        if !extra.is_empty() {
833            let mut merged: Vec<_> = field_offsets
834                .iter()
835                .zip(&field_types)
836                .zip(&field_names)
837                .map(|((&offset, &field_ty), &name)| (offset, field_ty, name))
838                .collect();
839            merged.extend(extra);
840            merged.sort_by_key(|&(offset, ..)| offset);
841
842            field_offsets.clear();
843            field_types.clear();
844            field_names.clear();
845            for (offset, field_ty, name) in merged {
846                field_offsets.push(offset);
847                field_types.push(field_ty);
848                field_names.push(name);
849            }
850        }
851    }
852
853    SpirvType::Adt {
854        def_id: def_id_for_spirv_type_adt(ty),
855        size,
856        align,
857        field_types: &field_types,
858        field_offsets: &field_offsets,
859        field_names: Some(&field_names),
860    }
861    .def_with_name(cx, span, TyLayoutNameKey::from(ty))
862}
863
864/// Grab a `DefId` from the type if possible to avoid too much deduplication,
865/// which could result in one SPIR-V `OpType*` having many names
866/// (not in itself an issue, but it makes error reporting harder).
867fn def_id_for_spirv_type_adt(layout: TyAndLayout<'_>) -> Option<DefId> {
868    match *layout.ty.kind() {
869        TyKind::Adt(def, _) => Some(def.did()),
870        TyKind::Foreign(def_id) | TyKind::Closure(def_id, _) | TyKind::Coroutine(def_id, ..) => {
871            Some(def_id)
872        }
873        _ => None,
874    }
875}
876
877fn span_for_spirv_type_adt(cx: &CodegenCx<'_>, layout: TyAndLayout<'_>) -> Option<Span> {
878    def_id_for_spirv_type_adt(layout).map(|did| cx.tcx.def_span(did))
879}
880
881/// Minimal and cheaply comparable/hashable subset of the information contained
882/// in `TyLayout` that can be used to generate a name (assuming a nominal type).
883#[derive(Copy, Clone, PartialEq, Eq, Hash)]
884pub struct TyLayoutNameKey<'tcx> {
885    ty: Ty<'tcx>,
886    variant: Option<VariantIdx>,
887}
888
889impl<'tcx> From<TyAndLayout<'tcx>> for TyLayoutNameKey<'tcx> {
890    fn from(layout: TyAndLayout<'tcx>) -> Self {
891        TyLayoutNameKey {
892            ty: layout.ty,
893            variant: match layout.variants {
894                Variants::Single { index } => Some(index),
895                _ => None,
896            },
897        }
898    }
899}
900
901impl fmt::Display for TyLayoutNameKey<'_> {
902    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903        write!(f, "{}", self.ty)?;
904        if let (TyKind::Adt(def, _), Some(index)) = (self.ty.kind(), self.variant)
905            && def.is_enum()
906            && !def.variants().is_empty()
907        {
908            write!(f, "::{}", def.variants()[index].name)?;
909        }
910        if let (TyKind::Coroutine(_, _), Some(index)) = (self.ty.kind(), self.variant) {
911            write!(f, "::{}", CoroutineArgs::variant_name(index))?;
912        }
913        Ok(())
914    }
915}
916
917fn trans_intrinsic_type<'tcx>(
918    cx: &CodegenCx<'tcx>,
919    span: Span,
920    ty: TyAndLayout<'tcx>,
921    args: GenericArgsRef<'tcx>,
922    intrinsic_type_attr: IntrinsicType,
923) -> Result<Word, ErrorGuaranteed> {
924    trait FromScalarInt: Sized {
925        fn from_scalar_int(n: ScalarInt) -> Option<Self>;
926    }
927
928    impl FromScalarInt for u32 {
929        fn from_scalar_int(n: ScalarInt) -> Option<Self> {
930            Some(n.try_to_bits(Size::from_bits(32)).ok()?.try_into().unwrap())
931        }
932    }
933
934    impl FromScalarInt for Dim {
935        fn from_scalar_int(n: ScalarInt) -> Option<Self> {
936            Dim::from_u32(u32::from_scalar_int(n)?)
937        }
938    }
939
940    impl FromScalarInt for ImageFormat {
941        fn from_scalar_int(n: ScalarInt) -> Option<Self> {
942            ImageFormat::from_u32(u32::from_scalar_int(n)?)
943        }
944    }
945
946    fn const_int_value<'tcx, P: FromScalarInt>(
947        cx: &CodegenCx<'tcx>,
948        const_: Const<'tcx>,
949    ) -> Result<P, ErrorGuaranteed> {
950        let ty::Value {
951            ty: const_ty,
952            valtree: const_val,
953        } = const_.to_value();
954        assert!(const_ty.is_integral());
955        const_val
956            .try_to_scalar()
957            .and_then(|scalar| scalar.try_to_scalar_int().ok())
958            .and_then(P::from_scalar_int)
959            .ok_or_else(|| {
960                cx.tcx
961                    .dcx()
962                    .err(format!("invalid value for const generic: {const_}"))
963            })
964    }
965
966    match intrinsic_type_attr {
967        IntrinsicType::GenericImageType => {
968            // see SpirvType::sizeof
969            if ty.size != Size::from_bytes(4) {
970                return Err(cx
971                    .tcx
972                    .dcx()
973                    .err("#[spirv(generic_image)] type must have size 4"));
974            }
975
976            // fn type_from_variant_discriminant<'tcx, P: FromPrimitive>(
977            //     cx: &CodegenCx<'tcx>,
978            //     const_: Const<'tcx>,
979            // ) -> P {
980            //     let adt_def = const_.ty.ty_adt_def().unwrap();
981            //     assert!(adt_def.is_enum());
982            //     let destructured = cx.tcx.destructure_const(TypingEnv::fully_monomorphized().and(const_));
983            //     let idx = destructured.variant.unwrap();
984            //     let value = const_.ty.discriminant_for_variant(cx.tcx, idx).unwrap().val as u64;
985            //     <_>::from_u64(value).unwrap()
986            // }
987
988            let sampled_type = match args.type_at(0).kind() {
989                TyKind::Int(int) => match int {
990                    IntTy::Isize => {
991                        SpirvType::Integer(cx.tcx.data_layout.pointer_size().bits() as u32, true)
992                            .def(span, cx)
993                    }
994                    IntTy::I8 => SpirvType::Integer(8, true).def(span, cx),
995                    IntTy::I16 => SpirvType::Integer(16, true).def(span, cx),
996                    IntTy::I32 => SpirvType::Integer(32, true).def(span, cx),
997                    IntTy::I64 => SpirvType::Integer(64, true).def(span, cx),
998                    IntTy::I128 => SpirvType::Integer(128, true).def(span, cx),
999                },
1000                TyKind::Uint(uint) => match uint {
1001                    UintTy::Usize => {
1002                        SpirvType::Integer(cx.tcx.data_layout.pointer_size().bits() as u32, false)
1003                            .def(span, cx)
1004                    }
1005                    UintTy::U8 => SpirvType::Integer(8, false).def(span, cx),
1006                    UintTy::U16 => SpirvType::Integer(16, false).def(span, cx),
1007                    UintTy::U32 => SpirvType::Integer(32, false).def(span, cx),
1008                    UintTy::U64 => SpirvType::Integer(64, false).def(span, cx),
1009                    UintTy::U128 => SpirvType::Integer(128, false).def(span, cx),
1010                },
1011                TyKind::Float(FloatTy::F32) => SpirvType::Float(32).def(span, cx),
1012                TyKind::Float(FloatTy::F64) => SpirvType::Float(64).def(span, cx),
1013                _ => {
1014                    return Err(cx
1015                        .tcx
1016                        .dcx()
1017                        .span_err(span, "Invalid sampled type to `Image`."));
1018                }
1019            };
1020
1021            // let dim: spirv::Dim = type_from_variant_discriminant(cx, args.const_at(1));
1022            // let depth: u32 = type_from_variant_discriminant(cx, args.const_at(2));
1023            // let arrayed: u32 = type_from_variant_discriminant(cx, args.const_at(3));
1024            // let multisampled: u32 = type_from_variant_discriminant(cx, args.const_at(4));
1025            // let sampled: u32 = type_from_variant_discriminant(cx, args.const_at(5));
1026            // let image_format: spirv::ImageFormat =
1027            //     type_from_variant_discriminant(cx, args.const_at(6));
1028
1029            let dim = const_int_value(cx, args.const_at(1))?;
1030            let depth = const_int_value(cx, args.const_at(2))?;
1031            let arrayed = const_int_value(cx, args.const_at(3))?;
1032            let multisampled = const_int_value(cx, args.const_at(4))?;
1033            let sampled = const_int_value(cx, args.const_at(5))?;
1034            let image_format = const_int_value(cx, args.const_at(6))?;
1035
1036            let ty = SpirvType::Image {
1037                sampled_type,
1038                dim,
1039                depth,
1040                arrayed,
1041                multisampled,
1042                sampled,
1043                image_format,
1044            };
1045            Ok(ty.def(span, cx))
1046        }
1047        IntrinsicType::Sampler => {
1048            // see SpirvType::sizeof
1049            if ty.size != Size::from_bytes(4) {
1050                return Err(cx.tcx.dcx().err("#[spirv(sampler)] type must have size 4"));
1051            }
1052            Ok(SpirvType::Sampler.def(span, cx))
1053        }
1054        IntrinsicType::AccelerationStructureKhr => {
1055            Ok(SpirvType::AccelerationStructureKhr.def(span, cx))
1056        }
1057        IntrinsicType::RayQueryKhr => Ok(SpirvType::RayQueryKhr.def(span, cx)),
1058        IntrinsicType::CooperativeMatrixKhr => {
1059            if ty.size != Size::from_bytes(4) {
1060                return Err(cx.tcx.dcx().err("cooperative_matrix type must have size 4"));
1061            }
1062
1063            // Generic arg 0: component type T
1064            let component_type = cx.layout_of(args.type_at(0)).spirv_type(span, cx);
1065            // Const generic 1: USE (MatrixA=0, MatrixB=1, MatrixAccumulator=2)
1066            let usage = cx
1067                .const_u32(const_int_value(cx, args.const_at(1))?)
1068                .def_cx(cx);
1069            // Const generic 2: ROWS
1070            let rows = cx
1071                .const_u32(const_int_value(cx, args.const_at(2))?)
1072                .def_cx(cx);
1073            // Const generic 3: COLS
1074            let columns = cx
1075                .const_u32(const_int_value(cx, args.const_at(3))?)
1076                .def_cx(cx);
1077            // Scope: Subgroup = 3
1078            let scope = cx.const_u32(3).def_cx(cx);
1079
1080            Ok(SpirvType::CooperativeMatrixKhr {
1081                component_type,
1082                usage,
1083                rows,
1084                columns,
1085                scope,
1086            }
1087            .def(span, cx))
1088        }
1089        IntrinsicType::SampledImage => {
1090            // see SpirvType::sizeof
1091            if ty.size != Size::from_bytes(4) {
1092                return Err(cx
1093                    .tcx
1094                    .dcx()
1095                    .err("#[spirv(sampled_image)] type must have size 4"));
1096            }
1097
1098            // We use a generic to indicate the underlying image type of the sampled image.
1099            // The spirv type of it will be generated by querying the type of the first generic.
1100            if let Some(image_ty) = args.types().next() {
1101                // TODO: enforce that the generic param is an image type?
1102                let image_type = cx.layout_of(image_ty).spirv_type(span, cx);
1103                Ok(SpirvType::SampledImage { image_type }.def(span, cx))
1104            } else {
1105                Err(cx
1106                    .tcx
1107                    .dcx()
1108                    .err("#[spirv(sampled_image)] type must have a generic image type"))
1109            }
1110        }
1111        IntrinsicType::RuntimeArray => {
1112            if ty.size != Size::from_bytes(4) {
1113                return Err(cx
1114                    .tcx
1115                    .dcx()
1116                    .err("#[spirv(runtime_array)] type must have size 4"));
1117            }
1118
1119            // We use a generic param to indicate the underlying element type.
1120            // The SPIR-V element type will be generated from the first generic param.
1121            if let Some(elem_ty) = args.types().next() {
1122                Ok(SpirvType::RuntimeArray {
1123                    element: cx.layout_of(elem_ty).spirv_type(span, cx),
1124                }
1125                .def(span, cx))
1126            } else {
1127                Err(cx
1128                    .tcx
1129                    .dcx()
1130                    .err("#[spirv(runtime_array)] type must have a generic element type"))
1131            }
1132        }
1133        IntrinsicType::TypedBuffer => {
1134            if ty.size != Size::from_bytes(4) {
1135                return Err(cx
1136                    .tcx
1137                    .sess
1138                    .dcx()
1139                    .err("#[spirv(typed_buffer)] type must have size 4"));
1140            }
1141
1142            // We use a generic param to indicate the underlying data type.
1143            // The SPIR-V data type will be generated from the first generic param.
1144            if let Some(data_ty) = args.types().next() {
1145                // HACK(eddyb) this should be a *pointer* to an "interface block",
1146                // but SPIR-V screwed up and used no explicit indirection for the
1147                // descriptor indexing case, and instead made a `RuntimeArray` of
1148                // `InterfaceBlock`s be an "array of typed buffer resources".
1149                Ok(SpirvType::InterfaceBlock {
1150                    inner_type: cx.layout_of(data_ty).spirv_type(span, cx),
1151                }
1152                .def(span, cx))
1153            } else {
1154                Err(cx
1155                    .tcx
1156                    .sess
1157                    .dcx()
1158                    .err("#[spirv(typed_buffer)] type must have a generic data type"))
1159            }
1160        }
1161        IntrinsicType::Matrix => {
1162            let span = span_for_spirv_type_adt(cx, ty).unwrap();
1163            let err_attr_name = "`#[spirv(matrix)]`";
1164            let (element, count) = trans_glam_like_struct(cx, span, ty, args, err_attr_name)?;
1165            match cx.lookup_type(element) {
1166                SpirvType::Vector { .. } => (),
1167                ty => {
1168                    return Err(cx
1169                        .tcx
1170                        .dcx()
1171                        .struct_span_err(
1172                            span,
1173                            format!("{err_attr_name} type fields must all be vectors"),
1174                        )
1175                        .with_note(format!("field type is {}", ty.debug(element, cx)))
1176                        .emit());
1177                }
1178            }
1179            Ok(SpirvType::Matrix { element, count }.def(span, cx))
1180        }
1181        IntrinsicType::Vector => {
1182            let span = span_for_spirv_type_adt(cx, ty).unwrap();
1183            let err_attr_name = "`#[spirv(vector)]`";
1184            let (element, count) = trans_glam_like_struct(cx, span, ty, args, err_attr_name)?;
1185            match cx.lookup_type(element) {
1186                SpirvType::Bool | SpirvType::Float { .. } | SpirvType::Integer { .. } => (),
1187                ty => {
1188                    return Err(cx
1189                        .tcx
1190                        .dcx()
1191                        .struct_span_err(
1192                            span,
1193                            format!(
1194                                "{err_attr_name} type fields must all be floats, integers or bools"
1195                            ),
1196                        )
1197                        .with_note(format!("field type is {}", ty.debug(element, cx)))
1198                        .emit());
1199                }
1200            }
1201            Ok(SpirvType::Vector {
1202                element,
1203                count,
1204                size: ty.size,
1205                align: ty.align.abi,
1206            }
1207            .def(span, cx))
1208        }
1209    }
1210}
1211
1212/// A struct with multiple fields of the same kind.
1213/// Used for `#[spirv(vector)]` and `#[spirv(matrix)]`.
1214fn trans_glam_like_struct<'tcx>(
1215    cx: &CodegenCx<'tcx>,
1216    span: Span,
1217    ty: TyAndLayout<'tcx>,
1218    args: GenericArgsRef<'tcx>,
1219    err_attr_name: &str,
1220) -> Result<(Word, u32), ErrorGuaranteed> {
1221    let tcx = cx.tcx;
1222    if let Some(adt) = ty.ty.ty_adt_def()
1223        && adt.is_struct()
1224    {
1225        let (count, element) = adt
1226            .non_enum_variant()
1227            .fields
1228            .iter()
1229            .map(|f| f.ty(tcx, args).skip_norm_wip())
1230            .dedup_with_count()
1231            .exactly_one()
1232            .map_err(|_e| {
1233                tcx.dcx().span_err(
1234                    span,
1235                    format!("{err_attr_name} member types must all be the same"),
1236                )
1237            })?;
1238
1239        let element = cx.layout_of(element);
1240        let element_word = element.spirv_type(span, cx);
1241        let count = u32::try_from(count)
1242            .ok()
1243            .filter(|count| 2 <= *count && *count <= 4)
1244            .ok_or_else(|| {
1245                tcx.dcx()
1246                    .span_err(span, format!("{err_attr_name} must have 2, 3 or 4 members"))
1247            })?;
1248
1249        for i in 0..ty.fields.count() {
1250            let expected = element.size.checked_mul(i as u64, cx).unwrap();
1251            let actual = ty.fields.offset(i);
1252            if actual != expected {
1253                let name: &str = adt
1254                    .non_enum_variant()
1255                    .fields
1256                    .get(FieldIdx::from(i))
1257                    .unwrap()
1258                    .name
1259                    .as_str();
1260                tcx.dcx().span_fatal(
1261                    span,
1262                    format!(
1263                        "Unexpected layout for {err_attr_name} annotated struct: \
1264                    Expected member `{name}` at offset {expected:?}, but was at {actual:?}"
1265                    ),
1266                )
1267            }
1268        }
1269
1270        Ok((element_word, count))
1271    } else {
1272        Err(tcx
1273            .dcx()
1274            .span_err(span, format!("{err_attr_name} type must be a struct")))
1275    }
1276}