spirq 1.2.2

Light weight SPIR-V query utility for graphics.
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
use crate::prelude::*;
use crate::ty;
use fnv::{FnvHashMap as HashMap, FnvHashSet as HashSet};
use inline_spirv::*;

macro_rules! gen_entries(
    ($stage:ident, $src:expr, $lang:ident) => {{
        static SPV: &'static [u32] = inline_spirv!($src, $stage, $lang, vulkan1_2);
        ReflectConfig::new()
            .spv(SPV)
            .combine_img_samplers(true)
            .ref_all_rscs(true)
            .reflect()
            .unwrap()
    }}
);
macro_rules! gen_one_entry(
    ($stage:ident, $glsl:expr) => {{
        let entries = gen_entries!($stage, $glsl, glsl);
        assert_eq!(entries.len(), 1, "expected 1 entry point, found {}", entries.len());
        entries[0].clone()
    }}
);
macro_rules! gen_one_entry_hlsl(
    ($stage:ident, $hlsl:expr) => {{
        let entries = gen_entries!($stage, $hlsl, hlsl);
        assert_eq!(entries.len(), 1, "expected 1 entry point, found {}", entries.len());
        entries[0].clone()
    }}
);

#[test]
fn test_basic_shader_stage() {
    macro_rules! x(
        ($stage:ident, $exec_model:ident) => {{
            let entry = gen_one_entry!($stage, "#version 450 core\nvoid main() {}");
            assert_eq!(entry.exec_model, ExecutionModel::$exec_model, "shader stage execution model mismatched");
            assert!(entry.vars.is_empty(), "unexpected specialization");
        }}
    );
    x!(vert, Vertex);
    x!(frag, Fragment);
}
// For maximal compatibility interface varriables like the output of vertex
// buffer is not forced empty, because it requires prior knowledge from the
// users, that this shader is a vertex shader. The reflection algorithm should
// be able to extract metadata for ANY type of shaders, including those haven't
// been created yet.
#[test]
fn test_vs_input_loc() {
    let entry = gen_one_entry!(
        vert,
        r#"
        #version 450 core
        layout(location=0, component=0)
        in uint a;
        layout(location=0, component=1)
        in vec3 b;
        layout(location=1)
        in vec4 c;
        layout(location=3)
        in uvec4 d;
        layout(location=4, component=2)
        in uvec2 e;
        void main() { gl_Position = vec4(a, b) + c + vec4(d) + vec4(e,0,0); }
    "#
    );
    let locations = entry
        .vars
        .into_iter()
        .filter_map(|x| {
            if let Variable::Input { location, .. } = x {
                Some(location)
            } else {
                None
            }
        })
        .collect::<HashSet<_>>();
    assert!(locations.contains(&InterfaceLocation::new(0, 0)));
    assert!(locations.contains(&InterfaceLocation::new(0, 1)));
    assert!(locations.contains(&InterfaceLocation::new(1, 0)));
    assert!(locations.contains(&InterfaceLocation::new(3, 0)));
    assert!(locations.contains(&InterfaceLocation::new(4, 2)));
    assert!(!locations.contains(&InterfaceLocation::new(0, 2)));
    assert!(!locations.contains(&InterfaceLocation::new(1, 1)));
}
#[test]
fn test_fs_output_loc() {
    // Note that fragment shader location-sharing outputs must have the same
    // type.
    let entry = gen_one_entry!(
        frag,
        r#"
        #version 450 core
        layout(location=0, component=0)
        out float a;
        layout(location=0, component=1)
        out vec3 b;
        layout(location=1)
        out vec4 c;
        layout(location=3)
        out uvec4 d;
        layout(location=4, component=2)
        out uvec2 e;
        void main() { a = 0; b = vec3(0,0,0); c = vec4(0,0,0,0); d = uvec4(0,0,0,0); e = uvec2(0,0); }
    "#
    );
    let locations = entry
        .vars
        .into_iter()
        .filter_map(|x| {
            if let Variable::Output { location, .. } = x {
                Some(location)
            } else {
                None
            }
        })
        .collect::<HashSet<_>>();
    assert!(locations.contains(&InterfaceLocation::new(0, 0)));
    assert!(locations.contains(&InterfaceLocation::new(0, 1)));
    assert!(locations.contains(&InterfaceLocation::new(1, 0)));
    assert!(locations.contains(&InterfaceLocation::new(3, 0)));
    assert!(locations.contains(&InterfaceLocation::new(4, 2)));
    assert!(!locations.contains(&InterfaceLocation::new(0, 2)));
    assert!(!locations.contains(&InterfaceLocation::new(1, 1)));
}
#[test]
fn test_spec_consts() {
    let entry = gen_one_entry!(
        geom,
        r#"
        #version 450 core
        layout(points) in;
        layout(points, max_vertices=1) out;
        layout(constant_id=233) const float a = 0;
        layout(constant_id=234) const float b = 0;
        layout(constant_id=235) const float c = 0;
        void main() { gl_Position = vec4(a,b,c,0); EmitVertex(); EndPrimitive(); }
    "#
    );
    let spec_ids = entry
        .vars
        .into_iter()
        .filter_map(|x| {
            if let Variable::SpecConstant { spec_id, .. } = x {
                Some(spec_id)
            } else {
                None
            }
        })
        .collect::<HashSet<_>>();
    assert!(spec_ids.contains(&233));
    assert!(spec_ids.contains(&234));
    assert!(spec_ids.contains(&235));
    assert!(!spec_ids.contains(&0));
    assert!(!spec_ids.contains(&1));
    assert!(!spec_ids.contains(&236));
}
#[test]
fn test_desc_tys() {
    let entry = gen_one_entry!(
        frag,
        r#"
        #version 450 core
        layout(std140, set=0, binding=0)
        uniform A {
            uint a;
        } aa;
        layout(std430, binding=1)
        buffer B {
            float b;
        } bb;
        layout(set=1, binding=0)
        uniform sampler2D c;
        layout(rgba32f, set=3, binding=4) readonly
        uniform image2D d;
        layout(input_attachment_index=3, set=1, binding=3)
        uniform subpassInput e;
        layout(binding=3)
        uniform samplerBuffer f;
        layout(rgba32f, set=3, binding=5) writeonly
        uniform image2D g;
        void main() {
            bb.b = 0.0;
            vec4 x = texelFetch(f, 0) + vec4(aa.a,0,0,0) + bb.b * texture(c, vec2(0,0)) + subpassLoad(e) + imageLoad(d, ivec2(0,0));
            imageStore(g, ivec2(0,0), x);
        }
    "#
    );
    let desc_binds = entry
        .vars
        .into_iter()
        .filter_map(|x| {
            if let Variable::Descriptor {
                desc_bind, desc_ty, ..
            } = x
            {
                Some((desc_bind, desc_ty))
            } else {
                None
            }
        })
        .collect::<HashMap<_, _>>();
    assert!(desc_binds.contains_key(&DescriptorBinding::new(0, 0)));
    assert_eq!(
        *desc_binds.get(&DescriptorBinding::new(0, 0)).unwrap(),
        DescriptorType::UniformBuffer()
    );
    assert!(desc_binds.contains_key(&DescriptorBinding::new(0, 1)));
    assert_eq!(
        *desc_binds.get(&DescriptorBinding::new(0, 1)).unwrap(),
        DescriptorType::StorageBuffer(AccessType::ReadWrite)
    );
    assert!(desc_binds.contains_key(&DescriptorBinding::new(1, 0)));
    assert_eq!(
        *desc_binds.get(&DescriptorBinding::new(1, 0)).unwrap(),
        DescriptorType::CombinedImageSampler()
    );
    assert!(desc_binds.contains_key(&DescriptorBinding::new(3, 4)));
    assert_eq!(
        *desc_binds.get(&DescriptorBinding::new(3, 4)).unwrap(),
        DescriptorType::StorageImage(AccessType::ReadOnly)
    );
    assert!(desc_binds.contains_key(&DescriptorBinding::new(3, 5)));
    assert_eq!(
        *desc_binds.get(&DescriptorBinding::new(3, 5)).unwrap(),
        DescriptorType::StorageImage(AccessType::WriteOnly)
    );
    assert!(desc_binds.contains_key(&DescriptorBinding::new(1, 3)));
    assert_eq!(
        *desc_binds.get(&DescriptorBinding::new(1, 3)).unwrap(),
        DescriptorType::InputAttachment(3)
    );
    assert!(desc_binds.contains_key(&DescriptorBinding::new(0, 3)));
    assert_eq!(
        *desc_binds.get(&DescriptorBinding::new(0, 3)).unwrap(),
        DescriptorType::UniformTexelBuffer()
    );
    assert!(!desc_binds.contains_key(&DescriptorBinding::new(0, 2)));
}
#[test]
fn test_push_consts() {
    let entry = gen_one_entry!(
        vert,
        r#"
        #version 450 core
        layout(push_constant)
        uniform A {
            float a;
        } aa;
        void main() { gl_Position = vec4(aa.a,0,0,0); }
    "#
    );
    entry
        .vars
        .into_iter()
        .filter_map(|x| {
            if let Variable::PushConstant { .. } = x {
                Some(())
            } else {
                None
            }
        })
        .next()
        .unwrap();
}
#[test]
fn test_implicit_sampled_img() {
    // Currently only shaderc is outputting binding-sharing image and sampler.
    let _entry = gen_one_entry_hlsl!(
        vert,
        r#"
        [[vk::binding(0, 0)]]
        Texture2D img;
        [[vk::binding(0, 0)]]
        SamplerState samp;
        float4 main() : SV_POSITION { return img.Sample(samp, float2(0,0)); }
    "#
    );
}
#[test]
fn test_dyn_multibind() {
    let entry = gen_one_entry!(
        frag,
        r#"
        #version 450 core
        #extension GL_EXT_nonuniform_qualifier: enable
        
        layout(binding = 0, set = 0)
        uniform sampler2D arr_dyn[];
        layout(binding = 1, set = 0)
        uniform sampler2D arr[5];

        layout(location = 0)
        in flat uint xx;

        void main() {
            texture(arr[0], vec2(0,0)) + texture(arr_dyn[xx], vec2(0,0));
        }
    "#
    );
    let descs = entry
        .vars
        .into_iter()
        .filter_map(|x| {
            if let Variable::Descriptor {
                desc_bind, nbind, ..
            } = x
            {
                Some((desc_bind, nbind))
            } else {
                None
            }
        })
        .collect::<HashMap<_, _>>();
    assert_eq!(*descs.get(&DescriptorBinding::new(0, 0)).unwrap(), 0);
    assert_eq!(*descs.get(&DescriptorBinding::new(0, 1)).unwrap(), 5);
}
#[test]
fn test_spec_const_arrays() {
    static SPV: &'static [u32] = inline_spirv!(
        r#"
        #version 450 core

        layout(constant_id = 1)
        const double DOUBLE_NUM = 3.0;
        layout(constant_id = 2)
        const uint OFFSET = 2;
        layout(constant_id = 3)
        const uint NUM = 42;
        layout(constant_id = 4)
        const int PERMUTATION = 12;

        layout(binding = 0, set = 0)
        uniform sampler2D arr_spec[NUM * PERMUTATION + 1];

        layout(binding = 1, set = 0, std140)
        uniform Param {
            vec4 padding;
            vec4 trailing_array[NUM];
        } u;

        layout(location = 0)
        in flat uint xx;

        void main() {
            for (uint i = 0; i < NUM; i++) {
                texture(arr_spec[i], vec2(0,0)) + u.padding;
            }
        }
    "#,
        frag,
        vulkan1_2
    );
    let entries = ReflectConfig::new()
        .spv(SPV)
        .combine_img_samplers(true)
        .specialize(1, ConstantValue::from(4.0 as f32))
        .specialize(3, ConstantValue::from(7 as u32))
        .specialize(4, ConstantValue::from(9 as i32))
        .reflect()
        .unwrap();
    assert_eq!(
        entries.len(),
        1,
        "expected 1 entry point, found {}",
        entries.len()
    );
    let entry = entries[0].clone();
    let spec_consts = entry
        .vars
        .iter()
        .filter_map(|x| {
            if let Variable::SpecConstant { spec_id, ty, .. } = x {
                Some((spec_id, ty.clone()))
            } else {
                None
            }
        })
        .collect::<HashMap<_, _>>();
    let descs = entry
        .vars
        .iter()
        .filter_map(|x| {
            if let Variable::Descriptor {
                desc_bind,
                nbind,
                ty,
                ..
            } = x
            {
                Some((desc_bind, (nbind, ty.nbyte())))
            } else {
                None
            }
        })
        .collect::<HashMap<_, _>>();
    assert_eq!(spec_consts.len(), 1);
    assert_eq!(
        *spec_consts.get(&2).unwrap(),
        ty::Type::Scalar(ty::ScalarType::u32())
    );
    assert_eq!(
        *descs.get(&DescriptorBinding::new(0, 0)).unwrap(),
        (&64, None)
    );
    assert_eq!(
        *descs.get(&DescriptorBinding::new(0, 1)).unwrap(),
        (&1, Some(128))
    );
}
#[test]
fn test_ray_tracing() {
    let entry = gen_one_entry!(
        rgen,
        r#"
        #version 460 core
        #extension GL_EXT_ray_tracing: enable

        uniform accelerationStructureEXT acc;

        layout(location = 0) rayPayloadEXT vec4 payload;

        void main() {
            traceRayEXT(acc, gl_RayFlagsOpaqueEXT, 0xff, 0,
                0, 0, vec3(0, 0, 0), 0.0,
                vec3(0, 0, 0), 100.0f, 0);
        }
    "#
    );
    let desc_binds = entry
        .vars
        .into_iter()
        .filter_map(|x| {
            if let Variable::Descriptor {
                desc_bind, desc_ty, ..
            } = x
            {
                Some((desc_bind, desc_ty))
            } else {
                None
            }
        })
        .collect::<HashMap<_, _>>();
    assert_eq!(
        *desc_binds.get(&DescriptorBinding::new(0, 0)).unwrap(),
        DescriptorType::AccelStruct()
    );
}
#[test]
fn test_combine_image_sampler() {
    let entry = gen_one_entry_hlsl!(
        frag,
        r#"
        [[vk::binding(0, 0)]]
        Texture2D shaderTexture;
        [[vk::binding(1, 0)]]
        SamplerState SampleType;

        [[vk::binding(1, 1)]]
        Texture2D shaderTexture2;
        [[vk::binding(1, 1)]]
        SamplerState SampleType2;

        struct PixelInputType
        {
            float4 position : SV_POSITION;
            float2 tex : TEXCOORD0;
        };

        float4 main(PixelInputType input) : SV_TARGET
        {
            float4 textureColor, textureColor2;

            textureColor = shaderTexture.Sample(SampleType, input.tex) + shaderTexture2.Sample(SampleType2, input.tex);

            return textureColor;
        }
    "#
    );
    let desc_binds = entry
        .vars
        .into_iter()
        .filter_map(|x| {
            if let Variable::Descriptor {
                desc_bind, desc_ty, ..
            } = x
            {
                Some((desc_bind, desc_ty))
            } else {
                None
            }
        })
        .collect::<HashMap<_, _>>();
    assert_eq!(desc_binds.len(), 3);
    assert_eq!(
        *desc_binds.get(&DescriptorBinding::new(0, 0)).unwrap(),
        DescriptorType::SampledImage()
    );
    assert_eq!(
        *desc_binds.get(&DescriptorBinding::new(0, 1)).unwrap(),
        DescriptorType::Sampler()
    );
    assert_eq!(
        *desc_binds.get(&DescriptorBinding::new(1, 1)).unwrap(),
        DescriptorType::CombinedImageSampler()
    );
}
#[test]
fn test_old_store_buf() {
    let entry = {
        static SPV: &'static [u32] = inline_spirv!(
            r#"
            #version 460 core
            layout(set=0, binding=0) buffer X {
                uint a[];
            } xs[2];
            void main() {
            }
        "#,
            comp,
            glsl,
            vulkan1_0
        );
        ReflectConfig::new()
            .spv(SPV)
            .ref_all_rscs(true)
            .reflect()
            .unwrap()
            .first()
            .unwrap()
            .clone()
    };
    let desc_binds = entry
        .vars
        .into_iter()
        .filter_map(|x| {
            if let Variable::Descriptor {
                desc_bind, desc_ty, ..
            } = x
            {
                Some((desc_bind, desc_ty))
            } else {
                None
            }
        })
        .collect::<HashMap<_, _>>();
    assert_eq!(
        *desc_binds.get(&DescriptorBinding::new(0, 0)).unwrap(),
        DescriptorType::StorageBuffer(AccessType::ReadWrite)
    );
}
#[test]
fn test_linked_list() {
    let _entry = gen_one_entry!(
        rgen,
        r#"
        #version 460 core
        #extension GL_EXT_ray_tracing : require
        #extension GL_EXT_nonuniform_qualifier : enable
        #extension GL_EXT_buffer_reference2 : require
        #extension GL_EXT_scalar_block_layout : enable
        #extension GL_EXT_shader_explicit_arithmetic_types_int64 : require

        layout(buffer_reference) buffer blockType;

        layout(buffer_reference, std430, buffer_reference_align = 16) buffer blockType {
            int x;
            blockType next;
        };
        
        layout(binding = 0, std430) buffer rootBlock {
            blockType root;
        } r;
        
        void main()
        {
            blockType b = r.root;
            b = b.next.next.next.next.next;
        }
    "#
    );
}
#[test]
fn test_issue_84() {
    let _entry: EntryPoint = gen_one_entry!(
        comp,
        r#"
        #version 450

        struct Foo {
            mat4 matrix;
        };

        layout(set = 0, binding = 0) uniform FooData {
            Foo data;
        } u_foo_data;

        void main() {
            Foo f = u_foo_data.data;
        }
    "#
    );
}
#[test]
fn test_matrix_stride() {
    let entry: EntryPoint = gen_one_entry!(
        comp,
        r#"
        #version 450
        layout(set=0, binding=0, std140) uniform _0 {
            layout(row_major) mat2x2 a;
            layout(column_major) mat4x4 b;
        };
        layout(set=0, binding=1, std430) buffer _1 {
            layout(row_major) mat2x2 c;
            layout(column_major) mat4x4 d;
        };
        layout(set=0, binding=2, std140) uniform _2 {
            mat2x2 e;
        };
        layout(set=0, binding=3, std430) buffer _3 {
            mat2x2 f;
        };
        void main() {
        }
    "#
    );
    for var in entry.vars {
        if let Variable::Descriptor { desc_bind, ty, .. } = var {
            match desc_bind.bind() {
                0 => {
                    let struct_ty = ty.as_struct().unwrap();
                    {
                        assert!(struct_ty.members[0].offset == Some(0));
                        let mat_ty = struct_ty.members[0].ty.as_matrix().unwrap();
                        assert!(mat_ty.stride == Some(16));
                    }
                    {
                        assert!(struct_ty.members[1].offset == Some(32));
                        let mat_ty = struct_ty.members[1].ty.as_matrix().unwrap();
                        assert!(mat_ty.stride == Some(16));
                    }
                }
                1 => {
                    let struct_ty = ty.as_struct().unwrap();
                    {
                        assert!(struct_ty.members[0].offset == Some(0));
                        let mat_ty = struct_ty.members[0].ty.as_matrix().unwrap();
                        assert!(mat_ty.stride == Some(8));
                    }
                    {
                        assert!(struct_ty.members[1].offset == Some(16));
                        let mat_ty = struct_ty.members[1].ty.as_matrix().unwrap();
                        assert!(mat_ty.stride == Some(16));
                    }
                }
                2 => {
                    let struct_ty = ty.as_struct().unwrap();
                    assert!(struct_ty.members[0].offset == Some(0));
                    let mat_ty = struct_ty.members[0].ty.as_matrix().unwrap();
                    assert!(mat_ty.stride == Some(16));
                }
                3 => {
                    let struct_ty = ty.as_struct().unwrap();
                    assert!(struct_ty.members[0].offset == Some(0));
                    let mat_ty = struct_ty.members[0].ty.as_matrix().unwrap();
                    assert!(mat_ty.stride == Some(8));
                }
                _ => {}
            }
        }
    }
}
#[test]
fn test_resource_in_chained_call() {
    static SPV: &'static [u32] = inline_spirv!(
        r#"
        #version 450
        layout(set=1, binding=2) buffer _0 {
            int a;
        };
        layout(set=1, binding=3) buffer _1 {
            int b;
        };
        void assign_a(int x) {
            a = x;
        }
        void main() {
            assign_a(1);
        }
        "#,
        comp,
        glsl,
        vulkan1_2
    );
    let entry = ReflectConfig::new()
        .spv(SPV)
        .ref_all_rscs(false)
        .reflect()
        .unwrap()
        .pop()
        .unwrap();
    let desc_binds = entry
        .vars
        .into_iter()
        .filter_map(|x| {
            if let Variable::Descriptor {
                desc_bind, desc_ty, ..
            } = x
            {
                Some((desc_bind, desc_ty))
            } else {
                None
            }
        })
        .collect::<HashMap<_, _>>();
    assert_eq!(
        *desc_binds.get(&DescriptorBinding::new(1, 2)).unwrap(),
        DescriptorType::StorageBuffer(AccessType::ReadWrite)
    );
    // Ensure the unreferenced one is not in the map.
    assert_eq!(desc_binds.get(&DescriptorBinding::new(1, 3)), None);
}