1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
use super::Builder;
use crate::builder_spirv::{SpirvValue, SpirvValueExt, SpirvValueKind};
use crate::spirv_type::SpirvType;
use rspirv::spirv::Word;
use rustc_codegen_ssa::traits::BuilderMethods;
use rustc_errors::ErrorGuaranteed;
use rustc_span::DUMMY_SP;
use rustc_target::abi::call::PassMode;
use rustc_target::abi::{Align, Size};

impl<'a, 'tcx> Builder<'a, 'tcx> {
    fn load_err(&mut self, original_type: Word, invalid_type: Word) -> SpirvValue {
        let mut err = self.struct_err(format!(
            "cannot load type {} in an untyped buffer load",
            self.debug_type(original_type)
        ));
        if original_type != invalid_type {
            err.note(format!(
                "due to containing type {}",
                self.debug_type(invalid_type)
            ));
        }
        err.emit();
        self.undef(invalid_type)
    }

    fn load_u32(
        &mut self,
        array: SpirvValue,
        dynamic_index: SpirvValue,
        constant_offset: u32,
    ) -> SpirvValue {
        let actual_index = if constant_offset != 0 {
            let const_offset_val = self.constant_u32(DUMMY_SP, constant_offset);
            self.add(dynamic_index, const_offset_val)
        } else {
            dynamic_index
        };
        let u32_ty = SpirvType::Integer(32, false).def(DUMMY_SP, self);
        let u32_ptr = self.type_ptr_to(u32_ty);
        let ptr = self
            .emit()
            .in_bounds_access_chain(u32_ptr, None, array.def(self), [actual_index.def(self)])
            .unwrap()
            .with_type(u32_ptr);
        self.load(u32_ty, ptr, Align::ONE)
    }

    #[allow(clippy::too_many_arguments)]
    fn load_vec_mat_arr(
        &mut self,
        original_type: Word,
        result_type: Word,
        array: SpirvValue,
        dynamic_word_index: SpirvValue,
        constant_word_offset: u32,
        element: Word,
        count: u32,
    ) -> SpirvValue {
        let element_size_bytes = match self.lookup_type(element).sizeof(self) {
            Some(size) => size,
            None => return self.load_err(original_type, result_type),
        };
        if element_size_bytes.bytes() % 4 != 0 {
            return self.load_err(original_type, result_type);
        }
        let element_size_words = (element_size_bytes.bytes() / 4) as u32;
        let args = (0..count)
            .map(|index| {
                self.recurse_load_type(
                    original_type,
                    element,
                    array,
                    dynamic_word_index,
                    constant_word_offset + element_size_words * index,
                )
                .def(self)
            })
            .collect::<Vec<_>>();
        self.emit()
            .composite_construct(result_type, None, args)
            .unwrap()
            .with_type(result_type)
    }

    fn recurse_load_type(
        &mut self,
        original_type: Word,
        result_type: Word,
        array: SpirvValue,
        dynamic_word_index: SpirvValue,
        constant_word_offset: u32,
    ) -> SpirvValue {
        match self.lookup_type(result_type) {
            SpirvType::Integer(32, signed) => {
                let val = self.load_u32(array, dynamic_word_index, constant_word_offset);
                self.intcast(val, result_type, signed)
            }
            SpirvType::Float(32) => {
                let val = self.load_u32(array, dynamic_word_index, constant_word_offset);
                self.bitcast(val, result_type)
            }
            SpirvType::Vector { element, count } | SpirvType::Matrix { element, count } => self
                .load_vec_mat_arr(
                    original_type,
                    result_type,
                    array,
                    dynamic_word_index,
                    constant_word_offset,
                    element,
                    count,
                ),
            SpirvType::Array { element, count } => {
                let count = match self.builder.lookup_const_u64(count) {
                    Some(count) => count as u32,
                    None => return self.load_err(original_type, result_type),
                };
                self.load_vec_mat_arr(
                    original_type,
                    result_type,
                    array,
                    dynamic_word_index,
                    constant_word_offset,
                    element,
                    count,
                )
            }
            SpirvType::Adt {
                size: Some(_),
                field_types,
                field_offsets,
                ..
            } => {
                let args = field_types
                    .iter()
                    .zip(field_offsets)
                    .map(|(&field_type, byte_offset)| {
                        if byte_offset.bytes() % 4 != 0 {
                            return None;
                        }
                        let word_offset = (byte_offset.bytes() / 4) as u32;
                        Some(
                            self.recurse_load_type(
                                original_type,
                                field_type,
                                array,
                                dynamic_word_index,
                                constant_word_offset + word_offset,
                            )
                            .def(self),
                        )
                    })
                    .collect::<Option<Vec<_>>>();
                match args {
                    None => self.load_err(original_type, result_type),
                    Some(args) => self
                        .emit()
                        .composite_construct(result_type, None, args)
                        .unwrap()
                        .with_type(result_type),
                }
            }

            _ => self.load_err(original_type, result_type),
        }
    }

    /// Note: DOES NOT do bounds checking! Bounds checking is expected to be done in the caller.
    pub fn codegen_buffer_load_intrinsic(
        &mut self,
        result_type: Word,
        args: &[SpirvValue],
        pass_mode: &PassMode,
    ) -> SpirvValue {
        match pass_mode {
            PassMode::Ignore => {
                return SpirvValue {
                    kind: SpirvValueKind::IllegalTypeUsed(result_type),
                    ty: result_type,
                };
            }
            // PassMode::Pair is identical to PassMode::Direct - it's returned as a struct
            PassMode::Direct(_) | PassMode::Pair(_, _) => (),
            PassMode::Cast { .. } => {
                self.fatal("PassMode::Cast not supported in codegen_buffer_load_intrinsic")
            }
            PassMode::Indirect { .. } => {
                self.fatal("PassMode::Indirect not supported in codegen_buffer_load_intrinsic")
            }
        }

        // Signature: fn load<T>(array: &[u32], index: u32) -> T;
        if args.len() != 3 {
            self.fatal(format!(
                "buffer_load_intrinsic should have 3 args, it has {}",
                args.len()
            ));
        }
        // Note that the &[u32] gets split into two arguments - pointer, length
        let array = args[0];
        let byte_index = args[2];
        let two = self.constant_u32(DUMMY_SP, 2);
        let word_index = self.lshr(byte_index, two);
        self.recurse_load_type(result_type, result_type, array, word_index, 0)
    }

    fn store_err(&mut self, original_type: Word, value: SpirvValue) -> Result<(), ErrorGuaranteed> {
        let mut err = self.struct_err(format!(
            "cannot store type {} in an untyped buffer store",
            self.debug_type(original_type)
        ));
        if original_type != value.ty {
            err.note(format!("due to containing type {}", value.ty));
        }
        Err(err.emit())
    }

    fn store_u32(
        &mut self,
        array: SpirvValue,
        dynamic_index: SpirvValue,
        constant_offset: u32,
        value: SpirvValue,
    ) -> Result<(), ErrorGuaranteed> {
        let actual_index = if constant_offset != 0 {
            let const_offset_val = self.constant_u32(DUMMY_SP, constant_offset);
            self.add(dynamic_index, const_offset_val)
        } else {
            dynamic_index
        };
        let u32_ty = SpirvType::Integer(32, false).def(DUMMY_SP, self);
        let u32_ptr = self.type_ptr_to(u32_ty);
        let ptr = self
            .emit()
            .in_bounds_access_chain(u32_ptr, None, array.def(self), [actual_index.def(self)])
            .unwrap()
            .with_type(u32_ptr);
        self.store(value, ptr, Align::ONE);
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    fn store_vec_mat_arr(
        &mut self,
        original_type: Word,
        value: SpirvValue,
        array: SpirvValue,
        dynamic_word_index: SpirvValue,
        constant_word_offset: u32,
        element: Word,
        count: u32,
    ) -> Result<(), ErrorGuaranteed> {
        let element_size_bytes = match self.lookup_type(element).sizeof(self) {
            Some(size) => size,
            None => return self.store_err(original_type, value),
        };
        if element_size_bytes.bytes() % 4 != 0 {
            return self.store_err(original_type, value);
        }
        let element_size_words = (element_size_bytes.bytes() / 4) as u32;
        for index in 0..count {
            let element = self.extract_value(value, index as u64);
            self.recurse_store_type(
                original_type,
                element,
                array,
                dynamic_word_index,
                constant_word_offset + element_size_words * index,
            )?;
        }
        Ok(())
    }

    fn recurse_store_type(
        &mut self,
        original_type: Word,
        value: SpirvValue,
        array: SpirvValue,
        dynamic_word_index: SpirvValue,
        constant_word_offset: u32,
    ) -> Result<(), ErrorGuaranteed> {
        match self.lookup_type(value.ty) {
            SpirvType::Integer(32, signed) => {
                let u32_ty = SpirvType::Integer(32, false).def(DUMMY_SP, self);
                let value_u32 = self.intcast(value, u32_ty, signed);
                self.store_u32(array, dynamic_word_index, constant_word_offset, value_u32)
            }
            SpirvType::Float(32) => {
                let u32_ty = SpirvType::Integer(32, false).def(DUMMY_SP, self);
                let value_u32 = self.bitcast(value, u32_ty);
                self.store_u32(array, dynamic_word_index, constant_word_offset, value_u32)
            }
            SpirvType::Vector { element, count } | SpirvType::Matrix { element, count } => self
                .store_vec_mat_arr(
                    original_type,
                    value,
                    array,
                    dynamic_word_index,
                    constant_word_offset,
                    element,
                    count,
                ),
            SpirvType::Array { element, count } => {
                let count = match self.builder.lookup_const_u64(count) {
                    Some(count) => count as u32,
                    None => return self.store_err(original_type, value),
                };
                self.store_vec_mat_arr(
                    original_type,
                    value,
                    array,
                    dynamic_word_index,
                    constant_word_offset,
                    element,
                    count,
                )
            }
            SpirvType::Adt {
                size: Some(_),
                field_offsets,
                ..
            } => {
                for (index, byte_offset) in field_offsets.iter().enumerate() {
                    if byte_offset.bytes() % 4 != 0 {
                        return self.store_err(original_type, value);
                    }
                    let word_offset = (byte_offset.bytes() / 4) as u32;
                    let field = self.extract_value(value, index as u64);
                    self.recurse_store_type(
                        original_type,
                        field,
                        array,
                        dynamic_word_index,
                        constant_word_offset + word_offset,
                    )?;
                }
                Ok(())
            }

            _ => self.store_err(original_type, value),
        }
    }

    /// Note: DOES NOT do bounds checking! Bounds checking is expected to be done in the caller.
    pub fn codegen_buffer_store_intrinsic(&mut self, args: &[SpirvValue], pass_mode: &PassMode) {
        // Signature: fn store<T>(array: &[u32], index: u32, value: T);
        let is_pair = match pass_mode {
            // haha shrug
            PassMode::Ignore => return,
            PassMode::Direct(_) => false,
            PassMode::Pair(_, _) => true,
            PassMode::Cast { .. } => {
                self.fatal("PassMode::Cast not supported in codegen_buffer_store_intrinsic")
            }
            PassMode::Indirect { .. } => {
                self.fatal("PassMode::Indirect not supported in codegen_buffer_store_intrinsic")
            }
        };
        let expected_args = if is_pair { 5 } else { 4 };
        if args.len() != expected_args {
            self.fatal(format!(
                "buffer_store_intrinsic should have {} args, it has {}",
                expected_args,
                args.len()
            ));
        }
        // Note that the &[u32] gets split into two arguments - pointer, length
        let array = args[0];
        let byte_index = args[2];
        let two = self.constant_u32(DUMMY_SP, 2);
        let word_index = self.lshr(byte_index, two);
        if is_pair {
            let value_one = args[3];
            let value_two = args[4];
            let one_result = self.recurse_store_type(value_one.ty, value_one, array, word_index, 0);

            let size_of_one = self.lookup_type(value_one.ty).sizeof(self);
            if one_result.is_ok() && size_of_one != Some(Size::from_bytes(4)) {
                self.fatal("Expected PassMode::Pair first element to have size 4");
            }

            let _ = self.recurse_store_type(value_two.ty, value_two, array, word_index, 1);
        } else {
            let value = args[3];
            let _ = self.recurse_store_type(value.ty, value, array, word_index, 0);
        }
    }
}