spirv-webgpu-transform 0.1.6

Transform SPIRV to be webgpu friendly
Documentation
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
use super::*;

// Opaque types cannot be operated on in the same way as non-opaque types.
// We need tools to trace the instruction chain up to the point an opaque type becomes a non-opaque.
//
// We care about OpTypeSampler and OpTypeImage, or more specifically, textures, storage textures,
// and samplers.
//
// My notes on the instruction structure:
//
// ```
// Textures:
// - OpLoad
//     - OpImageFetch
//     - OpImageGather
//     - OpImageDrefGather
//     - OpSampledImage (DAG NODE)
//         - OpImageSampleImplicitLod
//         - OpImageSampleExplicitLod
//         - OpImageSampleDrefImplicitLod
//         - OpImageSampleDrefExplicitLod
//         - OpImageSampleProjImplicitLod
//         - OpImageSampleProjExplicitLod
//         - OpImageSampleProjDrefImplicitLod
//         - OpImageSampleProjDrefExplicitLod
//         - (SparseResidency Capability)
//             - OpImageSparseSample*
//     OpImageGather
//     OpImageDrefGather
//     - (ImageQuery Capability)
//         - OpImageQuerySizeLod
//         - OpImageQuerySize
//         - OpImageQueryLevels
//         - OpImageQuerySamples
//         - OpImageQueryLod
//         - OpImageQueryFormat
//         - OpImageQueryOrder
//     - (SparseResidency Capability)
//         - OpImageSparseFetch
//         - OpImageSparseGather
//         - OpImageSparseDrefGather
//
// Storage Textures:
// - OpLoad
//     - OpImageRead
//     - OpImageWrite
//     - OpImageSparseRead
//     - OpImageTexelPointer
//     - (ImageQuery Capability)
//         - OpImageQuerySizeLod
//         - OpImageQuerySize
//         - OpImageQueryLevels
//         - OpImageQuerySamples
//         - OpImageQueryLod
//         - OpImageQueryFormat
//         - OpImageQueryOrder
//
// Samplers:
// - OpLoad
//     - OpSampledImage (DAG NODE)
// ```
//
// We can build a DAG for the instruction chains, but if we handle sampler's `OpSampledImage`
// separately, we can get away with a tree, or just a `struct`
//

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OpaqueLoadTrace {
    pub load_idx: usize,
    pub next: OpaqueImageOp,
}

impl OpaqueLoadTrace {
    pub fn last_result_id(&self) -> usize {
        match self.next {
            OpaqueImageOp::RawImage(raw_image_op) => raw_image_op.result_idx(),
            OpaqueImageOp::RawStorage(storage_texture_op) => storage_texture_op.result_idx(),
            OpaqueImageOp::Sampled(sampled_image_op) => sampled_image_op.next.result_idx(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpaqueImageOp {
    RawImage(RawImageOp),
    RawStorage(StorageTextureOp),
    Sampled(SampledImageOp),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RawImageOp {
    Fetch(usize),
    Gather(usize),
    DrefGather(usize),
    // TODO: Image Query Capability
}

impl RawImageOp {
    pub fn result_idx(&self) -> usize {
        match self {
            RawImageOp::Fetch(i) | RawImageOp::Gather(i) | RawImageOp::DrefGather(i) => *i,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SampledImageParent {
    Image,
    Sampler,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SampledImageOp {
    pub idx: usize,
    pub parent: SampledImageParent,
    pub next: SampledImageVariant,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SampledImageVariant {
    SampleImplicitLod(usize),
    SampleExplicitLod(usize),
    SampleDrefImplicitLod(usize),
    SampleDrefExplicitLod(usize),
    SampleProjImplicitLod(usize),
    SampleProjExplicitLod(usize),
    SampleProjDrefImplicitLod(usize),
    SampleProjDrefExplicitLod(usize),
    Gather(usize),
    DrefGather(usize),
    // TODO: Image Query Capability
    // TODO: Sparse Residency Capability
}

impl SampledImageVariant {
    pub fn result_idx(&self) -> usize {
        match self {
            SampledImageVariant::SampleImplicitLod(i)
            | SampledImageVariant::SampleExplicitLod(i)
            | SampledImageVariant::SampleDrefImplicitLod(i)
            | SampledImageVariant::SampleDrefExplicitLod(i)
            | SampledImageVariant::SampleProjImplicitLod(i)
            | SampledImageVariant::SampleProjExplicitLod(i)
            | SampledImageVariant::SampleProjDrefImplicitLod(i)
            | SampledImageVariant::SampleProjDrefExplicitLod(i)
            | SampledImageVariant::Gather(i)
            | SampledImageVariant::DrefGather(i) => *i,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StorageTextureOp {
    Read(usize),
    Write(usize),
    SparseRead(usize),
    TexelPointer(usize),
    // TODO: Image Query Capability
}

impl StorageTextureOp {
    // OpImageWrite has no result; all other storage ops do.
    pub fn result_idx(&self) -> usize {
        match self {
            StorageTextureOp::Read(i)
            | StorageTextureOp::SparseRead(i)
            | StorageTextureOp::TexelPointer(i)
            | StorageTextureOp::Write(i) => *i,
        }
    }
}

// Generally, spv[idx + 1] => result type, spv[idx + 2] => result, spv[idx + 3] => image / sampled image
pub fn trace_loaded_opaques(spv: &[u32], load_idxs: &[usize]) -> Vec<OpaqueLoadTrace> {
    // TODO: Memoize, we can do better than this.
    let mut op_sampled_image_idxs = vec![];
    let mut raw_image_op_idxs: Vec<(u16, usize)> = vec![];
    let mut sampled_image_op_idxs: Vec<(u16, usize)> = vec![];
    let mut storage_op_idxs: Vec<(u16, usize)> = vec![];

    let mut spv_idx = 0;
    while spv_idx < spv.len() {
        let op = spv[spv_idx];
        let word_count = hiword(op) as usize;
        let instruction = loword(op);

        match instruction {
            SPV_INSTRUCTION_OP_SAMPLED_IMAGE => op_sampled_image_idxs.push(spv_idx),
            SPV_INSTRUCTION_OP_IMAGE_FETCH
            | SPV_INSTRUCTION_OP_IMAGE_GATHER
            | SPV_INSTRUCTION_OP_IMAGE_DREF_GATHER => {
                raw_image_op_idxs.push((instruction, spv_idx))
            }
            SPV_INSTRUCTION_OP_IMAGE_SAMPLE_IMPLICIT_LOD
            | SPV_INSTRUCTION_OP_IMAGE_SAMPLE_EXPLICIT_LOD
            | SPV_INSTRUCTION_OP_IMAGE_SAMPLE_DREF_IMPLICIT_LOD
            | SPV_INSTRUCTION_OP_IMAGE_SAMPLE_DREF_EXPLICIT_LOD
            | SPV_INSTRUCTION_OP_IMAGE_SAMPLE_PROJ_IMPLICIT_LOD
            | SPV_INSTRUCTION_OP_IMAGE_SAMPLE_PROJ_EXPLICIT_LOD
            | SPV_INSTRUCTION_OP_IMAGE_SAMPLE_PROJ_DREF_IMPLICIT_LOD
            | SPV_INSTRUCTION_OP_IMAGE_SAMPLE_PROJ_DREF_EXPLICIT_LOD => {
                sampled_image_op_idxs.push((instruction, spv_idx))
            }
            SPV_INSTRUCTION_OP_IMAGE_READ
            | SPV_INSTRUCTION_OP_IMAGE_WRITE
            | SPV_INSTRUCTION_OP_IMAGE_SPARSE_READ
            | SPV_INSTRUCTION_OP_IMAGE_TEXEL_POINTER => {
                storage_op_idxs.push((instruction, spv_idx))
            }
            _ => {}
        }

        spv_idx += word_count;
    }

    let load_result_ids = load_idxs
        .iter()
        .map(|&idx| (spv[idx + 2], idx))
        .collect::<HashMap<_, _>>();

    let mut results = vec![];

    for &(instruction, idx) in &raw_image_op_idxs {
        let loaded_image_id = spv[idx + 3];
        if let Some(&load_idx) = load_result_ids.get(&loaded_image_id) {
            let op = match instruction {
                SPV_INSTRUCTION_OP_IMAGE_FETCH => RawImageOp::Fetch(idx),
                SPV_INSTRUCTION_OP_IMAGE_GATHER => RawImageOp::Gather(idx),
                SPV_INSTRUCTION_OP_IMAGE_DREF_GATHER => RawImageOp::DrefGather(idx),
                _ => unreachable!(),
            };
            results.push(OpaqueLoadTrace {
                load_idx,
                next: OpaqueImageOp::RawImage(op),
            });
        }
    }

    for &(instruction, idx) in &storage_op_idxs {
        let image_id = if instruction == SPV_INSTRUCTION_OP_IMAGE_WRITE {
            spv[idx + 1]
        } else {
            spv[idx + 3]
        };
        if let Some(&load_idx) = load_result_ids.get(&image_id) {
            let op = match instruction {
                SPV_INSTRUCTION_OP_IMAGE_READ => StorageTextureOp::Read(idx),
                SPV_INSTRUCTION_OP_IMAGE_WRITE => StorageTextureOp::Write(idx),
                SPV_INSTRUCTION_OP_IMAGE_SPARSE_READ => StorageTextureOp::SparseRead(idx),
                SPV_INSTRUCTION_OP_IMAGE_TEXEL_POINTER => StorageTextureOp::TexelPointer(idx),
                _ => unreachable!(),
            };
            results.push(OpaqueLoadTrace {
                load_idx,
                next: OpaqueImageOp::RawStorage(op),
            });
        }
    }

    // (result_id, sampled_image_idx, load_idx, parent) for OpSampledImage nodes rooted at our loads.
    let sampled_image_entries = op_sampled_image_idxs
        .iter()
        .filter_map(|&si_idx| {
            let image_load = load_result_ids.get(&spv[si_idx + 3]).copied();
            let sampler_load = load_result_ids.get(&spv[si_idx + 4]).copied();
            match (image_load, sampler_load) {
                (Some(_), Some(_)) => {
                    panic!("DAG node: OpSampledImage at {si_idx} has both image and sampler from tracked loads")
                }
                (Some(load_idx), None) => {
                    Some((spv[si_idx + 2], si_idx, load_idx, SampledImageParent::Image))
                }
                (None, Some(load_idx)) => {
                    Some((spv[si_idx + 2], si_idx, load_idx, SampledImageParent::Sampler))
                }
                (None, None) => None,
            }
        })
        .collect::<Vec<_>>();

    for &(instruction, idx) in sampled_image_op_idxs.iter() {
        let Some(&(_, si_idx, load_idx, parent)) =
            sampled_image_entries.iter().find(|(result_id, _, _, _)| {
                let loaded_image_id = spv[idx + 3];
                *result_id == loaded_image_id
            })
        else {
            continue;
        };
        let variant = match instruction {
            SPV_INSTRUCTION_OP_IMAGE_SAMPLE_IMPLICIT_LOD => {
                SampledImageVariant::SampleImplicitLod(idx)
            }
            SPV_INSTRUCTION_OP_IMAGE_SAMPLE_EXPLICIT_LOD => {
                SampledImageVariant::SampleExplicitLod(idx)
            }
            SPV_INSTRUCTION_OP_IMAGE_SAMPLE_DREF_IMPLICIT_LOD => {
                SampledImageVariant::SampleDrefImplicitLod(idx)
            }
            SPV_INSTRUCTION_OP_IMAGE_SAMPLE_DREF_EXPLICIT_LOD => {
                SampledImageVariant::SampleDrefExplicitLod(idx)
            }
            SPV_INSTRUCTION_OP_IMAGE_SAMPLE_PROJ_IMPLICIT_LOD => {
                SampledImageVariant::SampleProjImplicitLod(idx)
            }
            SPV_INSTRUCTION_OP_IMAGE_SAMPLE_PROJ_EXPLICIT_LOD => {
                SampledImageVariant::SampleProjExplicitLod(idx)
            }
            SPV_INSTRUCTION_OP_IMAGE_SAMPLE_PROJ_DREF_IMPLICIT_LOD => {
                SampledImageVariant::SampleProjDrefImplicitLod(idx)
            }
            SPV_INSTRUCTION_OP_IMAGE_SAMPLE_PROJ_DREF_EXPLICIT_LOD => {
                SampledImageVariant::SampleProjDrefExplicitLod(idx)
            }
            _ => unreachable!(),
        };
        results.push(OpaqueLoadTrace {
            load_idx,
            next: OpaqueImageOp::Sampled(SampledImageOp {
                idx: si_idx,
                parent,
                next: variant,
            }),
        });
    }

    for &(instruction, idx) in &raw_image_op_idxs {
        let Some(&(_, si_idx, load_idx, parent)) =
            sampled_image_entries.iter().find(|(result_id, _, _, _)| {
                let loaded_image_id = spv[idx + 3];
                *result_id == loaded_image_id
            })
        else {
            continue;
        };
        let variant = match instruction {
            SPV_INSTRUCTION_OP_IMAGE_GATHER => SampledImageVariant::Gather(idx),
            SPV_INSTRUCTION_OP_IMAGE_DREF_GATHER => SampledImageVariant::DrefGather(idx),
            _ => continue,
        };
        results.push(OpaqueLoadTrace {
            load_idx,
            next: OpaqueImageOp::Sampled(SampledImageOp {
                idx: si_idx,
                parent,
                next: variant,
            }),
        });
    }

    results
}

pub fn reconstruct_opaque_trace_and_overwrite(
    spv: &[u32],
    new_spv: &mut [u32],
    trace: &OpaqueLoadTrace,
) -> Vec<u32> {
    fn take_instruction(spv: &[u32], idx: usize) -> &[u32] {
        let word_count = hiword(spv[idx]) as usize;
        &spv[idx..idx + word_count]
    }

    fn write_nop_instruction(new_spv: &mut [u32], idx: usize) {
        let word_count = hiword(new_spv[idx]) as usize;
        new_spv[idx..idx + word_count].fill(encode_word(1, SPV_INSTRUCTION_OP_NOP));
    }

    let mut out = take_instruction(spv, trace.load_idx).to_vec();
    write_nop_instruction(new_spv, trace.load_idx);

    match &trace.next {
        OpaqueImageOp::RawImage(op) => {
            let op_idx = match op {
                RawImageOp::Fetch(i) | RawImageOp::Gather(i) | RawImageOp::DrefGather(i) => *i,
            };
            out.extend_from_slice(take_instruction(spv, op_idx));
            write_nop_instruction(new_spv, op_idx);
        }
        OpaqueImageOp::RawStorage(op) => {
            let op_idx = match op {
                StorageTextureOp::Read(i)
                | StorageTextureOp::Write(i)
                | StorageTextureOp::SparseRead(i)
                | StorageTextureOp::TexelPointer(i) => *i,
            };
            out.extend_from_slice(take_instruction(spv, op_idx));
            write_nop_instruction(new_spv, op_idx);
        }
        OpaqueImageOp::Sampled(SampledImageOp {
            idx: si_idx, next, ..
        }) => {
            out.extend_from_slice(take_instruction(spv, *si_idx));
            write_nop_instruction(new_spv, *si_idx);

            let op_idx = match next {
                SampledImageVariant::SampleImplicitLod(i)
                | SampledImageVariant::SampleExplicitLod(i)
                | SampledImageVariant::SampleDrefImplicitLod(i)
                | SampledImageVariant::SampleDrefExplicitLod(i)
                | SampledImageVariant::SampleProjImplicitLod(i)
                | SampledImageVariant::SampleProjExplicitLod(i)
                | SampledImageVariant::SampleProjDrefImplicitLod(i)
                | SampledImageVariant::SampleProjDrefExplicitLod(i)
                | SampledImageVariant::Gather(i)
                | SampledImageVariant::DrefGather(i) => *i,
            };
            out.extend_from_slice(take_instruction(spv, op_idx));
            write_nop_instruction(new_spv, op_idx);
        }
    }

    out
}

#[test]
fn raw_image_fetch() {
    #[rustfmt::skip]
    let spv: &[u32] = &[
        encode_word(4, SPV_INSTRUCTION_OP_LOAD), 10, 20, 30,
        encode_word(5, SPV_INSTRUCTION_OP_IMAGE_FETCH), 11, 21, 20, 40,
    ];
    let traces = trace_loaded_opaques(spv, &[0]);
    assert_eq!(traces.len(), 1);
    assert!(matches!(
        traces[0],
        OpaqueLoadTrace {
            load_idx: 0,
            next: OpaqueImageOp::RawImage(RawImageOp::Fetch(4))
        }
    ));
}

#[test]
fn sampled_image_implicit_lod() {
    #[rustfmt::skip]
    let spv: &[u32] = &[
        encode_word(4, SPV_INSTRUCTION_OP_LOAD), 10, 20, 30,
        encode_word(4, SPV_INSTRUCTION_OP_LOAD), 11, 21, 31,
        encode_word(5, SPV_INSTRUCTION_OP_SAMPLED_IMAGE), 12, 22, 20, 21,
        encode_word(5, SPV_INSTRUCTION_OP_IMAGE_SAMPLE_IMPLICIT_LOD), 13, 23, 22, 40,
    ];
    let traces = trace_loaded_opaques(spv, &[0]);
    assert_eq!(traces.len(), 1);
    assert!(matches!(
        traces[0],
        OpaqueLoadTrace {
            load_idx: 0,
            next: OpaqueImageOp::Sampled(SampledImageOp {
                idx: 8,
                parent: SampledImageParent::Image,
                next: SampledImageVariant::SampleImplicitLod(13),
            })
        }
    ));
}

#[test]
fn storage_image_write() {
    #[rustfmt::skip]
    let spv: &[u32] = &[
        encode_word(4, SPV_INSTRUCTION_OP_LOAD), 10, 20, 30,
        encode_word(4, SPV_INSTRUCTION_OP_IMAGE_WRITE), 20, 40, 50,
    ];
    let traces = trace_loaded_opaques(spv, &[0]);
    assert_eq!(traces.len(), 1);
    assert!(matches!(
        traces[0],
        OpaqueLoadTrace {
            load_idx: 0,
            next: OpaqueImageOp::RawStorage(StorageTextureOp::Write(4))
        }
    ));
}