metal2vulkan 0.1.0

Translate Metal AIR / LLVM IR to Vulkan SPIR-V with a native Rust emitter
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
//! Static constant-branch pruning (FC-default dead-code elimination).
//!
//! Metal `[[function_constant]]`-gated optional features (an optional `mask` buffer, a
//! `do_causal` flag, ...) compile to AIR that loads a function-constant predicate global, branches
//! on it, and — in the not-taken arm — dereferences the optional buffer. We do NOT plumb runtime
//! function-constant specialization, so we model every function constant at its DISABLED DEFAULT
//! (the AIR `air.fc_initializer` global is `ConstantNull`). The optional buffer therefore has no
//! descriptor binding; `build_stage_input` demotes its unmodeled pointer param to a zero-init Private
//! placeholder SCALAR, and the dead arm's GEPs over-index that scalar -> spirv-val "reached
//! non-composite". The golden was captured with the SAME defaults, so the dead arm genuinely never
//! executes: statically pruning it (and the placeholder GEPs it feeds, even through pointer phis) is
//! semantics-preserving by construction.
//!
//! This is a small, GENERAL optimizer — constant propagation + conditional-branch folding +
//! unreachable-block removal + trivial-phi collapse + dead-code elimination, to a fixpoint. It keys
//! on NOTHING workload-specific: the only seed is "a scalar-int/bool global that is never stored and
//! has a constant initializer" plus "a scalar global stored exactly once (in the entry block, with no
//! preceding load) by a constant value" — both of which are the function-constant machinery the
//! emitter produced, identified structurally. Run as a failure-triggered, adopt-if-VALIDATES retry,
//! so it is floor-safe: a module that validates on the default path never reaches it, and a
//! non-validating pruned result is discarded.

mod prune;
pub(in crate::native) use prune::*;
mod constants;
pub(in crate::native) use constants::*;
mod nonzero;
pub(in crate::native) use nonzero::*;
mod eval;
pub(in crate::native) use eval::*;
mod simplify;
pub(in crate::native) use simplify::*;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::spirv_module::Operand;
    use crate::spirv_module::{Block, Function, Instruction, Module, ModuleHeader};
    use spirv::{Op, StorageClass, Word};

    fn inst(op: Op, ty: Option<Word>, res: Option<Word>, ops: Vec<Operand>) -> Instruction {
        Instruction::new(op, ty, res, ops)
    }

    // A function-constant predicate computed as `(fc >> 0) & 1` over a disabled-default
    // (`OpConstantNull` = 0) FC global must fold to 0, so the arm it gates is statically dead and
    // pruned. This exercises the `OpBitwiseAnd`/`OpShiftRightLogical` modeling in `forward_eval`
    // (the `air.normalize_function_constant_predicate` lowering shape): without it the predicate
    // stays unknown and the dead arm survives.
    #[test]
    fn prunes_dead_arm_gated_by_bitwise_fc_predicate() {
        // ids: uint=1 bool=2 ptrPrivUint=3 | uint_0=10 uint_1=11 null=12 | fc_global=20
        //      labels: entry=30 then=34 else=35 merge=36 | %31 load %32 shr %33 and %38 ieq
        let mut m = Module::new();
        m.header = Some(ModuleHeader::new(40));
        m.types_global_values = vec![
            inst(
                Op::TypeInt,
                None,
                Some(1),
                vec![Operand::LiteralBit32(32), Operand::LiteralBit32(0)],
            ),
            inst(Op::TypeBool, None, Some(2), vec![]),
            inst(
                Op::TypePointer,
                None,
                Some(3),
                vec![
                    Operand::StorageClass(StorageClass::Private),
                    Operand::IdRef(1),
                ],
            ),
            inst(
                Op::Constant,
                Some(1),
                Some(10),
                vec![Operand::LiteralBit32(0)],
            ),
            inst(
                Op::Constant,
                Some(1),
                Some(11),
                vec![Operand::LiteralBit32(1)],
            ),
            inst(Op::ConstantNull, Some(1), Some(12), vec![]),
            inst(
                Op::Variable,
                Some(3),
                Some(20),
                vec![
                    Operand::StorageClass(StorageClass::Private),
                    Operand::IdRef(12),
                ],
            ),
        ];
        let entry = Block {
            label: Some(inst(Op::Label, None, Some(30), vec![])),
            instructions: vec![
                inst(Op::Load, Some(1), Some(31), vec![Operand::IdRef(20)]),
                // %32 = (fc >> 0)
                inst(
                    Op::ShiftRightLogical,
                    Some(1),
                    Some(32),
                    vec![Operand::IdRef(31), Operand::IdRef(10)],
                ),
                // %33 = %32 & 1
                inst(
                    Op::BitwiseAnd,
                    Some(1),
                    Some(33),
                    vec![Operand::IdRef(32), Operand::IdRef(11)],
                ),
                // %38 = (%33 == 0)  -> true, so the conditional takes %then and %else is dead
                inst(
                    Op::IEqual,
                    Some(2),
                    Some(38),
                    vec![Operand::IdRef(33), Operand::IdRef(10)],
                ),
                inst(
                    Op::SelectionMerge,
                    None,
                    None,
                    vec![
                        Operand::IdRef(36),
                        Operand::SelectionControl(spirv::SelectionControl::NONE),
                    ],
                ),
                inst(
                    Op::BranchConditional,
                    None,
                    None,
                    vec![Operand::IdRef(38), Operand::IdRef(34), Operand::IdRef(35)],
                ),
            ],
        };
        let then_b = Block {
            label: Some(inst(Op::Label, None, Some(34), vec![])),
            instructions: vec![inst(Op::Branch, None, None, vec![Operand::IdRef(36)])],
        };
        let else_b = Block {
            label: Some(inst(Op::Label, None, Some(35), vec![])),
            instructions: vec![inst(Op::Branch, None, None, vec![Operand::IdRef(36)])],
        };
        let merge_b = Block {
            label: Some(inst(Op::Label, None, Some(36), vec![])),
            instructions: vec![inst(Op::Return, None, None, vec![])],
        };
        let mut func = Function::new();
        func.blocks = vec![entry, then_b, else_b, merge_b];
        m.functions = vec![func];

        assert!(prune_constant_branches(&mut m), "expected a fold");
        let labels: Vec<Word> = m.functions[0]
            .blocks
            .iter()
            .filter_map(|b| b.label.as_ref().and_then(|l| l.result_id))
            .collect();
        assert!(
            !labels.contains(&35),
            "dead else-arm (%35) should be pruned: {labels:?}"
        );
        assert!(
            labels.contains(&34),
            "taken then-arm (%34) should survive: {labels:?}"
        );
    }

    #[test]
    fn keeps_loop_exit_gated_by_loop_carried_phi() {
        // A loop induction phi has one constant entry arm and one backedge defined by the loop body.
        // The backedge is not known during the first SCCP sweep; treating that unknown as neutral
        // folds `%i` to 0, then `%next < 48` to true, and incorrectly deletes the exit.
        let mut m = Module::new();
        m.header = Some(ModuleHeader::new(70));
        m.types_global_values = vec![
            inst(
                Op::TypeInt,
                None,
                Some(1),
                vec![Operand::LiteralBit32(32), Operand::LiteralBit32(0)],
            ),
            inst(Op::TypeBool, None, Some(2), vec![]),
            inst(
                Op::Constant,
                Some(1),
                Some(10),
                vec![Operand::LiteralBit32(0)],
            ),
            inst(
                Op::Constant,
                Some(1),
                Some(11),
                vec![Operand::LiteralBit32(1)],
            ),
            inst(
                Op::Constant,
                Some(1),
                Some(12),
                vec![Operand::LiteralBit32(48)],
            ),
        ];
        let entry = Block {
            label: Some(inst(Op::Label, None, Some(30), vec![])),
            instructions: vec![inst(Op::Branch, None, None, vec![Operand::IdRef(31)])],
        };
        let header = Block {
            label: Some(inst(Op::Label, None, Some(31), vec![])),
            instructions: vec![
                inst(
                    Op::Phi,
                    Some(1),
                    Some(50),
                    vec![
                        Operand::IdRef(10),
                        Operand::IdRef(30),
                        Operand::IdRef(51),
                        Operand::IdRef(32),
                    ],
                ),
                inst(
                    Op::IAdd,
                    Some(1),
                    Some(51),
                    vec![Operand::IdRef(50), Operand::IdRef(11)],
                ),
                inst(
                    Op::ULessThan,
                    Some(2),
                    Some(52),
                    vec![Operand::IdRef(51), Operand::IdRef(12)],
                ),
                inst(
                    Op::LoopMerge,
                    None,
                    None,
                    vec![
                        Operand::IdRef(33),
                        Operand::IdRef(32),
                        Operand::LoopControl(spirv::LoopControl::NONE),
                    ],
                ),
                inst(
                    Op::BranchConditional,
                    None,
                    None,
                    vec![Operand::IdRef(52), Operand::IdRef(32), Operand::IdRef(33)],
                ),
            ],
        };
        let latch = Block {
            label: Some(inst(Op::Label, None, Some(32), vec![])),
            instructions: vec![inst(Op::Branch, None, None, vec![Operand::IdRef(31)])],
        };
        let exit = Block {
            label: Some(inst(Op::Label, None, Some(33), vec![])),
            instructions: vec![inst(Op::Return, None, None, vec![])],
        };
        let mut func = Function::new();
        func.blocks = vec![entry, header, latch, exit];
        m.functions = vec![func];

        prune_constant_branches(&mut m);

        let labels: Vec<Word> = m.functions[0]
            .blocks
            .iter()
            .filter_map(|b| b.label.as_ref().and_then(|l| l.result_id))
            .collect();
        assert!(
            labels.contains(&33),
            "loop exit must not be pruned from an unknown induction phi: {labels:?}"
        );
        let header_term = m.functions[0].blocks[1]
            .instructions
            .last()
            .expect("header terminator");
        assert_eq!(header_term.class.opcode, Op::BranchConditional);
    }

    // A self-referential DEAD pointer-induction cycle — `%50 = OpPhi [%51 latch] [%base pre]` whose
    // only remaining reference is its own back-edge `%51 = OpPtrAccessChain %50` (the consumer load
    // pruned with a dead arm) — must be collected by DCE. The naive "any operand reference = used"
    // mark keeps it alive forever (phi marks the access chain used, the access chain marks the phi
    // used); transitive liveness from sinks drops the whole cycle. With an external use it stays.
    fn module_with_ptr_cycle(extra_use: bool) -> Module {
        // ids: float=1 ptrUC_float=2 | base=12 uint_1=11 | pre=30 hdr=31 latch=32 exit=33
        //      phi=50 step=51 | sink load=60
        let mut m = Module::new();
        m.header = Some(ModuleHeader::new(70));
        m.types_global_values = vec![
            inst(
                Op::TypeFloat,
                None,
                Some(1),
                vec![Operand::LiteralBit32(32)],
            ),
            inst(
                Op::TypePointer,
                None,
                Some(2),
                vec![
                    Operand::StorageClass(StorageClass::UniformConstant),
                    Operand::IdRef(1),
                ],
            ),
            inst(
                Op::Constant,
                Some(1),
                Some(11),
                vec![Operand::LiteralBit32(1)],
            ),
            inst(Op::ConstantNull, Some(2), Some(12), vec![]),
            // Private float* type (%3) + a Private sink variable (%20) for the live-case store.
            inst(
                Op::TypePointer,
                None,
                Some(3),
                vec![
                    Operand::StorageClass(StorageClass::Private),
                    Operand::IdRef(1),
                ],
            ),
            inst(
                Op::Variable,
                Some(3),
                Some(20),
                vec![Operand::StorageClass(StorageClass::Private)],
            ),
        ];
        let pre = Block {
            label: Some(inst(Op::Label, None, Some(30), vec![])),
            instructions: vec![inst(Op::Branch, None, None, vec![Operand::IdRef(31)])],
        };
        let hdr = Block {
            label: Some(inst(Op::Label, None, Some(31), vec![])),
            instructions: vec![
                inst(
                    Op::Phi,
                    Some(2),
                    Some(50),
                    vec![
                        Operand::IdRef(51),
                        Operand::IdRef(32),
                        Operand::IdRef(12),
                        Operand::IdRef(30),
                    ],
                ),
                inst(Op::Branch, None, None, vec![Operand::IdRef(32)]),
            ],
        };
        let mut latch_insts = vec![inst(
            Op::PtrAccessChain,
            Some(2),
            Some(51),
            vec![Operand::IdRef(50), Operand::IdRef(11)],
        )];
        if extra_use {
            // A genuine sink: load through the cycle pointer and STORE the value to a Private global
            // (a non-pure use), so the whole cycle is reachable from a sink and must survive.
            latch_insts.push(inst(Op::Load, Some(1), Some(60), vec![Operand::IdRef(50)]));
            latch_insts.push(inst(
                Op::Store,
                None,
                None,
                vec![Operand::IdRef(20), Operand::IdRef(60)],
            ));
        }
        latch_insts.push(inst(Op::Branch, None, None, vec![Operand::IdRef(31)]));
        let latch = Block {
            label: Some(inst(Op::Label, None, Some(32), vec![])),
            instructions: latch_insts,
        };
        let mut func = Function::new();
        func.blocks = vec![pre, hdr, latch];
        m.functions = vec![func];
        m
    }

    #[test]
    fn dce_collects_dead_pointer_induction_cycle() {
        let mut m = module_with_ptr_cycle(false);
        assert!(dce(&mut m), "expected the dead cycle to be removed");
        let results: Vec<Word> = m.functions[0]
            .blocks
            .iter()
            .flat_map(|b| b.instructions.iter().filter_map(|i| i.result_id))
            .collect();
        assert!(
            !results.contains(&50) && !results.contains(&51),
            "dead self-referential pointer cycle (%50/%51) should be gone: {results:?}"
        );
    }

    #[test]
    fn dce_keeps_live_pointer_induction_cycle() {
        let mut m = module_with_ptr_cycle(true);
        dce(&mut m);
        let results: Vec<Word> = m.functions[0]
            .blocks
            .iter()
            .flat_map(|b| b.instructions.iter().filter_map(|i| i.result_id))
            .collect();
        assert!(
            results.contains(&50) && results.contains(&51),
            "a cycle with an external consumer (%60) must survive: {results:?}"
        );
    }

    // A guard `C[0] == 0` over a VECTOR function constant whose disabled default is a null vector
    // (`OpConstantNull %v4ushort`) must fold: element 0 of the null vector is 0, so the equality is
    // true and the arm it gates is dead. Exercises the composite-constant + `OpCompositeExtract`
    // modeling — without it the vector load stays opaque and the dead arm survives.
    #[test]
    fn prunes_dead_arm_gated_by_vector_fc_element() {
        // ids: ushort=1 bool=2 v4ushort=3 ptrPrivV4=4 | ushort_0=10 nullv4=11 | Cglobal=20
        //      labels entry=30 then=34 else=35 merge=36 | %31 load %32 extract %33 ieq
        let mut m = Module::new();
        m.header = Some(ModuleHeader::new(40));
        m.types_global_values = vec![
            inst(
                Op::TypeInt,
                None,
                Some(1),
                vec![Operand::LiteralBit32(16), Operand::LiteralBit32(0)],
            ),
            inst(Op::TypeBool, None, Some(2), vec![]),
            inst(
                Op::TypeVector,
                None,
                Some(3),
                vec![Operand::IdRef(1), Operand::LiteralBit32(4)],
            ),
            inst(
                Op::TypePointer,
                None,
                Some(4),
                vec![
                    Operand::StorageClass(StorageClass::Private),
                    Operand::IdRef(3),
                ],
            ),
            inst(Op::ConstantNull, Some(1), Some(10), vec![]),
            inst(Op::ConstantNull, Some(3), Some(11), vec![]),
            inst(
                Op::Variable,
                Some(4),
                Some(20),
                vec![
                    Operand::StorageClass(StorageClass::Private),
                    Operand::IdRef(11),
                ],
            ),
        ];
        let entry = Block {
            label: Some(inst(Op::Label, None, Some(30), vec![])),
            instructions: vec![
                inst(Op::Load, Some(3), Some(31), vec![Operand::IdRef(20)]),
                inst(
                    Op::CompositeExtract,
                    Some(1),
                    Some(32),
                    vec![Operand::IdRef(31), Operand::LiteralBit32(0)],
                ),
                inst(
                    Op::IEqual,
                    Some(2),
                    Some(33),
                    vec![Operand::IdRef(32), Operand::IdRef(10)],
                ),
                inst(
                    Op::SelectionMerge,
                    None,
                    None,
                    vec![
                        Operand::IdRef(36),
                        Operand::SelectionControl(spirv::SelectionControl::NONE),
                    ],
                ),
                inst(
                    Op::BranchConditional,
                    None,
                    None,
                    vec![Operand::IdRef(33), Operand::IdRef(34), Operand::IdRef(35)],
                ),
            ],
        };
        let then_b = Block {
            label: Some(inst(Op::Label, None, Some(34), vec![])),
            instructions: vec![inst(Op::Branch, None, None, vec![Operand::IdRef(36)])],
        };
        let else_b = Block {
            label: Some(inst(Op::Label, None, Some(35), vec![])),
            instructions: vec![inst(Op::Branch, None, None, vec![Operand::IdRef(36)])],
        };
        let merge_b = Block {
            label: Some(inst(Op::Label, None, Some(36), vec![])),
            instructions: vec![inst(Op::Return, None, None, vec![])],
        };
        let mut func = Function::new();
        func.blocks = vec![entry, then_b, else_b, merge_b];
        m.functions = vec![func];

        assert!(prune_constant_branches(&mut m), "expected a fold");
        let labels: Vec<Word> = m.functions[0]
            .blocks
            .iter()
            .filter_map(|b| b.label.as_ref().and_then(|l| l.result_id))
            .collect();
        assert!(
            !labels.contains(&35),
            "dead else-arm should be pruned: {labels:?}"
        );
        assert!(
            labels.contains(&34),
            "taken then-arm should survive: {labels:?}"
        );
    }

    // A grid-stride early-return guard `stride > stride - 1` folds to a taken return: `stride` is a
    // `NumWorkgroups`-derived value (>= 1 for any executing invocation), so `X > X-1` is statically
    // true and the guarded compute arm is dead. Exercises the nonzero analysis + affine self-minus-one
    // guard fold; without it the guard stays opaque and the arm survives.
    #[test]
    fn folds_grid_stride_early_return_guard() {
        // ids: uint=1 bool=2 v3uint=3 ptrInV3=4 | allones=10 (also a nonzero const seed) | nwg=20
        //      entry=30 body=34 ret=35 | %31 load %32 extract %33 iadd(X,-1) %38 ugt
        let mut m = Module::new();
        m.header = Some(ModuleHeader::new(40));
        m.types_global_values = vec![
            inst(
                Op::TypeInt,
                None,
                Some(1),
                vec![Operand::LiteralBit32(32), Operand::LiteralBit32(0)],
            ),
            inst(Op::TypeBool, None, Some(2), vec![]),
            inst(
                Op::TypeVector,
                None,
                Some(3),
                vec![Operand::IdRef(1), Operand::LiteralBit32(3)],
            ),
            inst(
                Op::TypePointer,
                None,
                Some(4),
                vec![
                    Operand::StorageClass(StorageClass::Input),
                    Operand::IdRef(3),
                ],
            ),
            inst(
                Op::Constant,
                Some(1),
                Some(10),
                vec![Operand::LiteralBit32(0xFFFF_FFFF)],
            ),
            inst(
                Op::Variable,
                Some(4),
                Some(20),
                vec![Operand::StorageClass(StorageClass::Input)],
            ),
        ];
        m.annotations = vec![inst(
            Op::Decorate,
            None,
            None,
            vec![
                Operand::IdRef(20),
                Operand::Decoration(spirv::Decoration::BuiltIn),
                Operand::BuiltIn(spirv::BuiltIn::NumWorkgroups),
            ],
        )];
        let entry = Block {
            label: Some(inst(Op::Label, None, Some(30), vec![])),
            instructions: vec![
                inst(Op::Load, Some(3), Some(31), vec![Operand::IdRef(20)]),
                inst(
                    Op::CompositeExtract,
                    Some(1),
                    Some(32),
                    vec![Operand::IdRef(31), Operand::LiteralBit32(0)],
                ),
                // %33 = X + 0xFFFFFFFF = X - 1
                inst(
                    Op::IAdd,
                    Some(1),
                    Some(33),
                    vec![Operand::IdRef(32), Operand::IdRef(10)],
                ),
                // %38 = X > X-1 -> folds true, so %35 (return) is taken and %34 is dead
                inst(
                    Op::UGreaterThan,
                    Some(2),
                    Some(38),
                    vec![Operand::IdRef(32), Operand::IdRef(33)],
                ),
                inst(
                    Op::SelectionMerge,
                    None,
                    None,
                    vec![
                        Operand::IdRef(34),
                        Operand::SelectionControl(spirv::SelectionControl::NONE),
                    ],
                ),
                inst(
                    Op::BranchConditional,
                    None,
                    None,
                    vec![Operand::IdRef(38), Operand::IdRef(35), Operand::IdRef(34)],
                ),
            ],
        };
        let body_b = Block {
            label: Some(inst(Op::Label, None, Some(34), vec![])),
            instructions: vec![inst(Op::Branch, None, None, vec![Operand::IdRef(35)])],
        };
        let ret_b = Block {
            label: Some(inst(Op::Label, None, Some(35), vec![])),
            instructions: vec![inst(Op::Return, None, None, vec![])],
        };
        let mut func = Function::new();
        func.blocks = vec![entry, body_b, ret_b];
        m.functions = vec![func];

        assert!(
            prune_constant_branches(&mut m),
            "expected the guard to fold"
        );
        let labels: Vec<Word> = m.functions[0]
            .blocks
            .iter()
            .filter_map(|b| b.label.as_ref().and_then(|l| l.result_id))
            .collect();
        assert!(
            !labels.contains(&34),
            "dead compute arm (%34) should be pruned: {labels:?}"
        );
    }

    // A grid-bounds guard `tile < (W*H)` where the scalar dimension FCs W,H fold to 0 (disabled
    // default) must fold: `x < 0` is false for every unsigned x, so the compute arm it gates is dead
    // — even though `tile` is a runtime (unknown) dispatch value. Exercises the one-sided unsigned
    // bound in `ucmp_fold`; without it the guard stays opaque and the FC-zero-work MXU arm survives.
    #[test]
    fn folds_unsigned_less_than_zero_bounds_guard() {
        // ids: uint=1 bool=2 ptrPrivU=3 ptrInU=4 | null=10 | Wg=20 Hg=21 tileVar=22
        //      entry=30 compute=34 skip=35 | %31 loadW %32 loadH %33 mul %36 loadTile %38 ult
        let mut m = Module::new();
        m.header = Some(ModuleHeader::new(40));
        m.types_global_values = vec![
            inst(
                Op::TypeInt,
                None,
                Some(1),
                vec![Operand::LiteralBit32(32), Operand::LiteralBit32(0)],
            ),
            inst(Op::TypeBool, None, Some(2), vec![]),
            inst(
                Op::TypePointer,
                None,
                Some(3),
                vec![
                    Operand::StorageClass(StorageClass::Private),
                    Operand::IdRef(1),
                ],
            ),
            inst(
                Op::TypePointer,
                None,
                Some(4),
                vec![
                    Operand::StorageClass(StorageClass::Input),
                    Operand::IdRef(1),
                ],
            ),
            inst(Op::ConstantNull, Some(1), Some(10), vec![]),
            inst(
                Op::Variable,
                Some(3),
                Some(20),
                vec![
                    Operand::StorageClass(StorageClass::Private),
                    Operand::IdRef(10),
                ],
            ),
            inst(
                Op::Variable,
                Some(3),
                Some(21),
                vec![
                    Operand::StorageClass(StorageClass::Private),
                    Operand::IdRef(10),
                ],
            ),
            inst(
                Op::Variable,
                Some(4),
                Some(22),
                vec![Operand::StorageClass(StorageClass::Input)],
            ),
        ];
        let entry = Block {
            label: Some(inst(Op::Label, None, Some(30), vec![])),
            instructions: vec![
                inst(Op::Load, Some(1), Some(31), vec![Operand::IdRef(20)]),
                inst(Op::Load, Some(1), Some(32), vec![Operand::IdRef(21)]),
                inst(
                    Op::IMul,
                    Some(1),
                    Some(33),
                    vec![Operand::IdRef(31), Operand::IdRef(32)],
                ),
                inst(Op::Load, Some(1), Some(36), vec![Operand::IdRef(22)]),
                // %38 = tile < (W*H) = tile < 0 -> false, so %35 (skip) is taken and %34 is dead
                inst(
                    Op::ULessThan,
                    Some(2),
                    Some(38),
                    vec![Operand::IdRef(36), Operand::IdRef(33)],
                ),
                inst(
                    Op::SelectionMerge,
                    None,
                    None,
                    vec![
                        Operand::IdRef(35),
                        Operand::SelectionControl(spirv::SelectionControl::NONE),
                    ],
                ),
                inst(
                    Op::BranchConditional,
                    None,
                    None,
                    vec![Operand::IdRef(38), Operand::IdRef(34), Operand::IdRef(35)],
                ),
            ],
        };
        let compute_b = Block {
            label: Some(inst(Op::Label, None, Some(34), vec![])),
            instructions: vec![inst(Op::Branch, None, None, vec![Operand::IdRef(35)])],
        };
        let skip_b = Block {
            label: Some(inst(Op::Label, None, Some(35), vec![])),
            instructions: vec![inst(Op::Return, None, None, vec![])],
        };
        let mut func = Function::new();
        func.blocks = vec![entry, compute_b, skip_b];
        m.functions = vec![func];

        assert!(
            prune_constant_branches(&mut m),
            "expected the guard to fold"
        );
        let labels: Vec<Word> = m.functions[0]
            .blocks
            .iter()
            .filter_map(|b| b.label.as_ref().and_then(|l| l.result_id))
            .collect();
        assert!(
            !labels.contains(&34),
            "dead compute arm (%34) should be pruned: {labels:?}"
        );
    }
}