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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
use super::ir::{LlDeclaration, LlFunction, LlGep, LlGlobal, LlType, LlValue, TypedValue};
pub(super) use super::lex::{
    matching_angle, matching_paren, parse_bfloat_literal, parse_float_literal, parse_half_literal,
    parse_hex_literal, parse_i64_literal, parse_u32, parse_u64_literal, split_top_level,
    split_top_level_whitespace, strip_comment,
};
use crate::spirv_module::Operand;
use spirv::Op;

#[derive(Clone, Debug)]
pub(super) struct LlCall {
    pub(super) ret: LlType,
    pub(super) callee: String,
    pub(super) args: Vec<TypedValue>,
    pub(super) arg_aligns: Vec<Option<u64>>,
}

#[derive(Clone, Debug)]
pub(super) struct LlLoad {
    pub(super) result_ty: LlType,
    pub(super) ptr: TypedValue,
    pub(super) align: Option<u64>,
}

#[derive(Clone, Debug)]
pub(super) struct LlSwitch {
    pub(super) selector: TypedValue,
    pub(super) default_label: String,
    pub(super) cases: Vec<(LlValue, String)>,
}

pub(super) fn parse_function(
    lines: &[&str],
    start: usize,
) -> Result<(LlFunction, Vec<String>, usize), String> {
    let head = strip_comment(lines[start]).trim();
    let at = head
        .find('@')
        .ok_or_else(|| format!("native emitter: define without function name: {head}"))?;
    let open = head[at..]
        .find('(')
        .map(|p| p + at)
        .ok_or_else(|| format!("native emitter: define without params: {head}"))?;
    let close = matching_paren(head, open)
        .ok_or_else(|| format!("native emitter: unmatched params in define: {head}"))?;
    let name = head[at + 1..open].to_string();
    let ret = parse_return_type(&head["define".len()..at])?;
    let params = parse_params(&head[open + 1..close])?;
    let mut body = Vec::new();
    let mut i = start + 1;
    while i < lines.len() {
        let line = strip_comment(lines[i]).trim();
        if line == "}" {
            return Ok((
                LlFunction {
                    name,
                    ret,
                    params,
                    // Lowered to carriers by `LlModule::parse_inner` from the returned `body` lines,
                    // once the module type table is complete; the text is then dropped.
                    blocks: Vec::new(),
                },
                body,
                i + 1,
            ));
        }
        if line.starts_with("switch ") {
            let (switch_line, next) = collect_switch(lines, i)?;
            body.push(switch_line);
            i = next;
            continue;
        }
        body.push(lines[i].to_string());
        i += 1;
    }
    Err(format!("native emitter: unterminated function {name}"))
}

pub(super) fn collect_switch(lines: &[&str], start: usize) -> Result<(String, usize), String> {
    let mut out = String::new();
    let mut i = start;
    while i < lines.len() {
        let part = strip_comment(lines[i]).trim();
        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str(part);
        if part.contains(']') {
            return Ok((out, i + 1));
        }
        i += 1;
    }
    Err(format!(
        "native emitter: unterminated switch starting at `{}`",
        strip_comment(lines[start]).trim()
    ))
}

pub(super) fn parse_declaration(line: &str) -> Result<LlDeclaration, String> {
    let head = strip_comment(line).trim();
    let at = head
        .find('@')
        .ok_or_else(|| format!("native emitter: declare without function name: {head}"))?;
    let open = head[at..]
        .find('(')
        .map(|p| p + at)
        .ok_or_else(|| format!("native emitter: declare without params: {head}"))?;
    let close = matching_paren(head, open)
        .ok_or_else(|| format!("native emitter: unmatched params in declare: {head}"))?;
    let name = head[at + 1..open].to_string();
    let ret = parse_return_type(&head["declare".len()..at])?;
    let params = parse_decl_params(&head[open + 1..close])?;
    Ok(LlDeclaration { name, ret, params })
}

pub(super) fn parse_global(line: &str) -> Result<LlGlobal, String> {
    let (name, rest) = line
        .split_once(" = ")
        .ok_or_else(|| format!("native emitter: malformed global: {line}"))?;
    let addrspace = parse_addrspace(rest)?;
    let typed_init = rest
        .split_once(" constant ")
        .map(|(_, typed_init)| typed_init)
        .or_else(|| {
            rest.split_once(" global ")
                .map(|(_, typed_init)| typed_init)
        })
        .ok_or_else(|| format!("native emitter: global is not a constant/global: {line}"))?;
    let typed_init = split_top_level(typed_init.trim(), ',')
        .into_iter()
        .next()
        .ok_or_else(|| format!("native emitter: global has no initializer: {line}"))?;
    let initializer = parse_typed_value(typed_init.trim())?;
    Ok(LlGlobal {
        name: name.trim().to_string(),
        addrspace,
        ty: initializer.ty.clone(),
        initializer: Some(initializer),
    })
}

fn parse_addrspace(s: &str) -> Result<u32, String> {
    let Some(start) = s.find("addrspace(") else {
        return Ok(0);
    };
    let after = &s[start + "addrspace(".len()..];
    let Some(end) = after.find(')') else {
        return Err(format!(
            "native emitter: malformed addrspace in global: {s}"
        ));
    };
    after[..end]
        .parse::<u32>()
        .map_err(|e| format!("native emitter: bad global addrspace in `{s}`: {e}"))
}

pub(super) fn parse_decl_params(s: &str) -> Result<Vec<LlType>, String> {
    if s.trim().is_empty() {
        return Ok(vec![]);
    }
    split_top_level(s, ',')
        .into_iter()
        .map(parse_type_prefix)
        .collect()
}

pub(super) fn parse_return_type(prefix: &str) -> Result<LlType, String> {
    let toks = split_top_level_whitespace(prefix);
    for i in (0..toks.len()).rev() {
        let candidate = toks[i..].join(" ");
        if let Ok(ty) = parse_type(&candidate) {
            return Ok(ty);
        }
    }
    Err(format!(
        "native emitter: could not parse function return type from `{}`",
        prefix.trim()
    ))
}

pub(super) fn parse_params(s: &str) -> Result<Vec<(String, LlType)>, String> {
    let mut out = Vec::new();
    if s.trim().is_empty() {
        return Ok(out);
    }
    for raw in split_top_level(s, ',') {
        let raw = raw.trim();
        let pct = raw
            .rfind('%')
            .ok_or_else(|| format!("native emitter: parameter has no SSA name: {raw}"))?;
        let name = raw[pct..]
            .split_whitespace()
            .next()
            .ok_or_else(|| format!("native emitter: malformed parameter name: {raw}"))?
            .to_string();
        let ty = parse_type_prefix(raw[..pct].trim())?;
        out.push((name, ty));
    }
    Ok(out)
}

pub(super) fn parse_type_prefix(s: &str) -> Result<LlType, String> {
    let toks = split_top_level_whitespace(s);
    for i in (1..=toks.len()).rev() {
        let candidate = toks[..i].join(" ");
        if let Ok(ty) = parse_type(&candidate) {
            return Ok(ty);
        }
    }
    Err(format!(
        "native emitter: could not parse type prefix from `{s}`"
    ))
}

pub(super) fn parse_typed_value(s: &str) -> Result<TypedValue, String> {
    let s = s.trim();
    let toks = split_top_level_whitespace(s);
    let mut last_value_err = None;
    for value_start in (1..toks.len()).rev() {
        let value_text = toks[value_start..].join(" ");
        let value = match parse_value(value_text.trim()) {
            Ok(value) => value,
            Err(err) => {
                last_value_err = Some(err);
                continue;
            }
        };
        for ty_start in 0..value_start {
            for ty_end in ((ty_start + 1)..=value_start).rev() {
                let ty_text = toks[ty_start..ty_end].join(" ");
                if let Ok(ty) = parse_type(&ty_text) {
                    return Ok(TypedValue { ty, value });
                }
            }
        }
    }
    if let Some(err) = last_value_err {
        return Err(format!(
            "native emitter: malformed typed value `{s}` ({err})"
        ));
    }
    Err(format!("native emitter: malformed typed value `{s}`"))
}

pub(super) fn parse_value(s: &str) -> Result<LlValue, String> {
    let s = s.trim();
    if s == "undef" || s == "poison" {
        Ok(LlValue::Undef)
    } else if s == "zeroinitializer" || s == "null" {
        Ok(LlValue::Zero)
    } else if s == "true" {
        Ok(LlValue::Bool(true))
    } else if s == "false" {
        Ok(LlValue::Bool(false))
    } else if s.starts_with('<') && s.ends_with('>') {
        let inner = s[1..s.len() - 1].trim();
        if inner.starts_with('{') && inner.ends_with('}') {
            let fields = split_top_level(&inner[1..inner.len() - 1], ',')
                .into_iter()
                .map(parse_typed_value)
                .collect::<Result<Vec<_>, _>>()?;
            return Ok(LlValue::Struct(fields));
        }
        let lanes = split_top_level(inner, ',')
            .into_iter()
            .map(parse_typed_value)
            .collect::<Result<Vec<_>, _>>()?;
        Ok(LlValue::Vector(lanes))
    } else if s.starts_with('[') && s.ends_with(']') {
        let elems = split_top_level(&s[1..s.len() - 1], ',')
            .into_iter()
            .map(parse_typed_value)
            .collect::<Result<Vec<_>, _>>()?;
        Ok(LlValue::Array(elems))
    } else if s.starts_with('{') && s.ends_with('}') {
        let fields = split_top_level(&s[1..s.len() - 1], ',')
            .into_iter()
            .map(parse_typed_value)
            .collect::<Result<Vec<_>, _>>()?;
        Ok(LlValue::Struct(fields))
    } else if s.starts_with("c\"") && s.ends_with('"') {
        parse_byte_string_literal(s).map(|bytes| {
            LlValue::Array(
                bytes
                    .into_iter()
                    .map(|byte| TypedValue {
                        ty: LlType::Int(8),
                        value: LlValue::Int(byte as u64),
                    })
                    .collect(),
            )
        })
    } else if let Some(inner) = s.strip_prefix("splat (").and_then(|s| s.strip_suffix(')')) {
        Ok(LlValue::Splat(Box::new(parse_typed_value(inner)?)))
    } else if let Some(rest) = s.strip_prefix("getelementptr ") {
        Ok(LlValue::Gep(Box::new(parse_gep(rest)?)))
    } else if s.starts_with('%') {
        Ok(LlValue::Local(s.to_string()))
    } else if s.starts_with('@') {
        Ok(LlValue::Global(s.to_string()))
    } else if let Some(bits) = parse_half_literal(s) {
        Ok(LlValue::HalfBits(bits))
    } else if let Some(bits) = parse_bfloat_literal(s) {
        Ok(LlValue::BFloatBits(bits))
    } else if let Some(bits) = parse_hex_literal(s) {
        Ok(LlValue::Hex(bits))
    } else if let Ok(v) = parse_i64_literal(s) {
        Ok(LlValue::SignedInt(v))
    } else if let Ok(v) = parse_u64_literal(s) {
        Ok(LlValue::Int(v))
    } else if let Ok(v) = parse_float_literal(s) {
        Ok(LlValue::Float(v))
    } else {
        Err(format!("native emitter: unsupported value `{s}`"))
    }
}

fn parse_byte_string_literal(s: &str) -> Result<Vec<u8>, String> {
    let body = s
        .strip_prefix("c\"")
        .and_then(|s| s.strip_suffix('"'))
        .ok_or_else(|| format!("native emitter: malformed byte string `{s}`"))?;
    let bytes = body.as_bytes();
    let mut out = Vec::new();
    let mut i = 0usize;
    while i < bytes.len() {
        if bytes[i] != b'\\' {
            out.push(bytes[i]);
            i += 1;
            continue;
        }
        if i + 1 >= bytes.len() {
            return Err(format!("native emitter: trailing byte string escape `{s}`"));
        }
        if i + 2 < bytes.len() {
            if let (Some(hi), Some(lo)) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2])) {
                out.push((hi << 4) | lo);
                i += 3;
                continue;
            }
        }
        let escaped = match bytes[i + 1] {
            b'\\' => b'\\',
            b'"' => b'"',
            b'n' => b'\n',
            b'r' => b'\r',
            b't' => b'\t',
            other => {
                return Err(format!(
                    "native emitter: unsupported byte string escape `\\{}` in `{s}`",
                    other as char
                ));
            }
        };
        out.push(escaped);
        i += 2;
    }
    Ok(out)
}

fn hex_nibble(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

pub(super) fn fcmp_predicate(s: &str) -> Option<Op> {
    let pred = split_top_level_whitespace(s).into_iter().find(|tok| {
        matches!(
            *tok,
            "oeq"
                | "ogt"
                | "oge"
                | "olt"
                | "ole"
                | "one"
                | "ueq"
                | "ugt"
                | "uge"
                | "ult"
                | "ule"
                | "une"
        )
    })?;
    Some(match pred {
        "oeq" => Op::FOrdEqual,
        "ogt" => Op::FOrdGreaterThan,
        "oge" => Op::FOrdGreaterThanEqual,
        "olt" => Op::FOrdLessThan,
        "ole" => Op::FOrdLessThanEqual,
        "one" => Op::FOrdNotEqual,
        "ueq" => Op::FUnordEqual,
        "ugt" => Op::FUnordGreaterThan,
        "uge" => Op::FUnordGreaterThanEqual,
        "ult" => Op::FUnordLessThan,
        "ule" => Op::FUnordLessThanEqual,
        "une" => Op::FUnordNotEqual,
        _ => return None,
    })
}

pub(super) fn icmp_predicate(s: &str) -> Option<Op> {
    let pred = split_top_level_whitespace(s).into_iter().find(|tok| {
        matches!(
            *tok,
            "eq" | "ne" | "ugt" | "uge" | "ult" | "ule" | "sgt" | "sge" | "slt" | "sle"
        )
    })?;
    Some(match pred {
        "eq" => Op::IEqual,
        "ne" => Op::INotEqual,
        "ugt" => Op::UGreaterThan,
        "uge" => Op::UGreaterThanEqual,
        "ult" => Op::ULessThan,
        "ule" => Op::ULessThanEqual,
        "sgt" => Op::SGreaterThan,
        "sge" => Op::SGreaterThanEqual,
        "slt" => Op::SLessThan,
        "sle" => Op::SLessThanEqual,
        _ => return None,
    })
}

pub(super) fn int_compare_result_type(operand: &LlType) -> Result<LlType, String> {
    match operand {
        LlType::Int(_) => Ok(LlType::Bool),
        LlType::Vector(elem, lanes) if matches!(elem.as_ref(), LlType::Int(_)) => {
            Ok(LlType::Vector(Box::new(LlType::Bool), *lanes))
        }
        other => Err(format!(
            "native emitter: icmp needs integer scalar/vector operands, got {other:?}"
        )),
    }
}

pub(super) fn float_compare_result_type(operand: &LlType) -> Result<LlType, String> {
    match operand {
        LlType::Float | LlType::Half => Ok(LlType::Bool),
        LlType::Vector(elem, lanes) if matches!(elem.as_ref(), LlType::Float | LlType::Half) => {
            Ok(LlType::Vector(Box::new(LlType::Bool), *lanes))
        }
        other => Err(format!(
            "native emitter: fcmp needs float scalar/vector operands, got {other:?}"
        )),
    }
}

pub(super) fn is_ignored_intrinsic(name: &str) -> bool {
    name.starts_with("llvm.lifetime.")
        || name.starts_with("llvm.umax.")
        || name.starts_with("llvm.umin.")
        || name.starts_with("llvm.smax.")
        || name.starts_with("llvm.smin.")
        || name.starts_with("llvm.abs.")
        || name.starts_with("llvm.usub.sat.")
}

pub(super) fn is_ignored_call_line(line: &str) -> bool {
    let line = line.trim();
    let line = line.strip_prefix("tail ").unwrap_or(line);
    // A bare `call ...` (no `%result =`) is a void call. `llvm.lifetime.*` markers take (i64, ptr) so
    // they are matched by name; debug/scope markers (llvm.dbg.*, llvm.experimental.noalias.scope.decl,
    // ...) take only `metadata` operands and are matched STRUCTURALLY by operand type, not callee
    // name — both are no-ops to drop before their operands reach the value parser.
    if !line.starts_with("call ") {
        return false;
    }
    if line.contains("@llvm.lifetime.") {
        return true;
    }
    let Some(open) = line.find('(') else {
        return false;
    };
    let Some(close) = matching_paren(line, open) else {
        return false;
    };
    let args = line[open + 1..close].trim();
    !args.is_empty()
        && split_top_level(args, ',')
            .iter()
            .all(|arg| arg.trim().starts_with("metadata "))
}

pub(super) fn strip_call_prefix(s: &str) -> Option<&str> {
    let s = s.strip_prefix("tail ").unwrap_or(s);
    s.strip_prefix("call ")
}

/// Diagnostic for a call with no `@name` callee. An AIR call through a `%reg` value is an INDIRECT
/// call — in Metal these are typically Metal **visible function table** dispatches (`%reg` traces to
/// `air.get_function_pointer_visible_function_table(table, index)`): a runtime-bound function pointer
/// with no clean Logical-SPIR-V equivalent (R1). Name the function-pointer register explicitly and
/// classify it as an indirect call (the frontier bucketer keys on "indirect call"/"function pointer"),
/// rather than the generic "call without callee" which reads like a parse failure.
fn indirect_call_diagnostic(s: &str) -> String {
    // The callee register is the last whitespace-separated token before the argument list `(`.
    let fp = s
        .find('(')
        .map(|open| {
            s[..open]
                .split_whitespace()
                .last()
                .unwrap_or("")
                .to_string()
        })
        .filter(|t| t.starts_with('%'))
        .unwrap_or_default();
    if fp.is_empty() {
        format!("native emitter: call without callee: {s}")
    } else {
        format!(
            "native emitter: unsupported indirect call through function pointer {fp} \
             (Metal visible function table); not expressible in Logical SPIR-V: {s}"
        )
    }
}

pub(super) fn parse_call(s: &str) -> Result<LlCall, String> {
    let at = match s.find('@') {
        Some(at) => at,
        None => return Err(indirect_call_diagnostic(s)),
    };
    let open = s[at..]
        .find('(')
        .map(|p| p + at)
        .ok_or_else(|| format!("native emitter: call without argument list: {s}"))?;
    let close = matching_paren(s, open)
        .ok_or_else(|| format!("native emitter: unmatched call parens: {s}"))?;
    let ret = parse_return_type(&s[..at])?;
    let callee = s[at + 1..open].to_string();
    let args_text = &s[open + 1..close];
    let (args, arg_aligns) = if args_text.trim().is_empty() {
        (Vec::new(), Vec::new())
    } else {
        let arg_texts = split_top_level(args_text, ',');
        let mut args = Vec::with_capacity(arg_texts.len());
        let mut arg_aligns = Vec::with_capacity(arg_texts.len());
        for arg_text in arg_texts {
            arg_aligns.push(parse_argument_align(arg_text));
            args.push(parse_typed_value(arg_text)?);
        }
        (args, arg_aligns)
    };
    Ok(LlCall {
        ret,
        callee,
        args,
        arg_aligns,
    })
}

fn parse_argument_align(s: &str) -> Option<u64> {
    let toks = split_top_level_whitespace(s);
    toks.windows(2).find_map(|window| {
        if window[0] == "align" {
            window[1].parse().ok()
        } else {
            None
        }
    })
}

pub(super) fn parse_gep(s: &str) -> Result<LlGep, String> {
    let s = strip_wrapping_parens(strip_native_gep_flags(s));
    let parts = split_top_level(s, ',');
    if parts.len() < 3 {
        return Err(format!("native emitter: malformed getelementptr: {s}"));
    }
    let source_ty = parse_type(parts[0])?;
    let base = parse_typed_value(parts[1])?;
    let indices = parts[2..]
        .iter()
        .map(|idx| parse_typed_value(idx))
        .collect::<Result<Vec<_>, _>>()?;
    Ok(LlGep {
        source_ty,
        base,
        indices,
    })
}

fn strip_wrapping_parens(s: &str) -> &str {
    let s = s.trim();
    if s.starts_with('(') && matching_paren(s, 0) == Some(s.len() - 1) {
        return s[1..s.len() - 1].trim();
    }
    s
}

pub(super) fn strip_native_gep_flags(mut s: &str) -> &str {
    s = s.trim();
    loop {
        let mut matched = false;
        for flag in ["inbounds", "nuw", "nusw"] {
            if let Some(rest) = s.strip_prefix(flag) {
                if rest.is_empty() || rest.starts_with(char::is_whitespace) {
                    s = rest.trim_start();
                    matched = true;
                    break;
                }
            }
        }
        if !matched {
            return s;
        }
    }
}

pub(super) fn parse_load(s: &str) -> Result<LlLoad, String> {
    let parts = split_top_level(s, ',');
    if parts.len() < 2 {
        return Err(format!("native emitter: malformed load: {s}"));
    }
    Ok(LlLoad {
        result_ty: parse_type(parts[0])?,
        ptr: parse_typed_value(parts[1])?,
        align: parse_memory_alignment(&parts[2..])?,
    })
}

pub(super) fn parse_memory_alignment(parts: &[&str]) -> Result<Option<u64>, String> {
    for part in parts {
        let part = part.trim();
        let Some(value) = part.strip_prefix("align ") else {
            continue;
        };
        return value
            .trim()
            .parse()
            .map(Some)
            .map_err(|e| format!("native emitter: malformed memory alignment `{part}`: {e}"));
    }
    Ok(None)
}

/// Parse a `phi`'s operand text (`<ty> [ v0, %pred0 ], [ v1, %pred1 ], ...` — the rhs AFTER the `phi`
/// opcode) into the phi's (unresolved) result type and its `(value, predecessor-label)` incoming pairs.
/// Feeds the build-time `TirInst.phi_incoming` carrier so it derives values/labels from that input — the
/// values are then overlaid from the typed graph by
/// `phi_incoming_values`, but the predecessor LABELS exist only here (control-flow edges, not operands).
pub(super) fn parse_phi(rest: &str) -> Result<(LlType, Vec<(LlValue, String)>), String> {
    let first_incoming = rest
        .find('[')
        .ok_or_else(|| format!("native emitter: malformed phi: {rest}"))?;
    let phi_ty = parse_type(rest[..first_incoming].trim())?;
    let incoming = split_top_level(&rest[first_incoming..], ',')
        .into_iter()
        .map(|incoming| {
            let incoming = incoming
                .trim()
                .strip_prefix('[')
                .and_then(|s| s.strip_suffix(']'))
                .ok_or_else(|| format!("native emitter: malformed phi incoming: {incoming}"))?;
            let parts = split_top_level(incoming, ',');
            if parts.len() != 2 {
                return Err(format!(
                    "native emitter: malformed phi incoming fields: {incoming}"
                ));
            }
            Ok((parse_value(parts[0].trim())?, parts[1].trim().to_string()))
        })
        .collect::<Result<Vec<_>, String>>()?;
    Ok((phi_ty, incoming))
}

pub(super) fn parse_switch(s: &str) -> Result<LlSwitch, String> {
    let s = s.trim();
    let body = s
        .strip_prefix("switch ")
        .ok_or_else(|| format!("native emitter: malformed switch: {s}"))?;
    let open = body
        .find('[')
        .ok_or_else(|| format!("native emitter: switch missing case list: {s}"))?;
    let close = body
        .rfind(']')
        .ok_or_else(|| format!("native emitter: switch missing case terminator: {s}"))?;
    if close < open {
        return Err(format!("native emitter: malformed switch case list: {s}"));
    }
    let head = body[..open].trim();
    let head_parts = split_top_level(head, ',');
    if head_parts.len() != 2 {
        return Err(format!("native emitter: malformed switch header: {s}"));
    }
    let selector = parse_typed_value(head_parts[0])?;
    let default_label = parse_label_operand(head_parts[1])
        .ok_or_else(|| format!("native emitter: malformed switch default: {s}"))?;
    let mut cases = Vec::new();
    let mut rest = body[open + 1..close].trim();
    while !rest.is_empty() {
        let (value_text, after_value) = rest
            .split_once(',')
            .ok_or_else(|| format!("native emitter: malformed switch case: {rest}"))?;
        let value = parse_typed_value(value_text)?;
        if value.ty != selector.ty {
            return Err(format!(
                "native emitter: switch case type {:?} does not match selector {:?}",
                value.ty, selector.ty
            ));
        }
        let after_label = after_value
            .trim()
            .strip_prefix("label ")
            .ok_or_else(|| format!("native emitter: malformed switch case label: {rest}"))?;
        let label_end = after_label
            .find(char::is_whitespace)
            .unwrap_or(after_label.len());
        let label = after_label[..label_end].to_string();
        rest = after_label[label_end..].trim();
        cases.push((value.value, label));
    }
    Ok(LlSwitch {
        selector,
        default_label,
        cases,
    })
}

pub(super) fn parse_label_operand(s: &str) -> Option<String> {
    let label = s.trim().strip_prefix("label ")?.trim();
    Some(label.split_whitespace().next()?.to_string())
}

pub(super) fn switch_literal_operand(
    value: &LlValue,
    selector_ty: &LlType,
) -> Result<Operand, String> {
    let LlType::Int(bits) = selector_ty else {
        return Err(format!(
            "native emitter: switch selector must be integer, got {selector_ty:?}"
        ));
    };
    if *bits == 0 || *bits > 64 {
        return Err(format!(
            "native emitter: switch selector width {bits} is not covered"
        ));
    }
    let max = if *bits == 64 {
        u64::MAX as u128
    } else {
        (1u128 << *bits) - 1
    };
    let raw = match value {
        LlValue::Int(v) | LlValue::Hex(v) => {
            let v = *v as u128;
            if v > max {
                return Err(format!(
                    "native emitter: switch case value {v} overflows i{bits}"
                ));
            }
            v
        }
        LlValue::SignedInt(v) if *v >= 0 => {
            let v = *v as u128;
            if v > max {
                return Err(format!(
                    "native emitter: switch case value {v} overflows i{bits}"
                ));
            }
            v
        }
        LlValue::SignedInt(v) => {
            let modulus = if *bits == 64 {
                1u128 << 64
            } else {
                1u128 << *bits
            };
            let min = -(1i128 << (*bits - 1));
            if (*v as i128) < min {
                return Err(format!(
                    "native emitter: switch case value {v} overflows i{bits}"
                ));
            }
            (modulus as i128 + *v as i128) as u128
        }
        other => {
            return Err(format!(
                "native emitter: switch case must be an integer literal, got {other:?}"
            ))
        }
    };
    if *bits <= 32 {
        Ok(Operand::LiteralBit32(raw as u32))
    } else {
        Ok(Operand::LiteralBit64(raw as u64))
    }
}

pub(super) fn parse_identity_ptr_bitcast(line: &str) -> Option<(String, String)> {
    let t = line.trim();
    let eq = t.find(" = bitcast ")?;
    let res = t[..eq].trim().to_string();
    if !res.starts_with('%') {
        return None;
    }
    let rest = &t[eq + " = bitcast ".len()..];
    let to = rest.find(" to ")?;
    let src = rest[..to].trim();
    let dst = rest[to + " to ".len()..].trim();
    let base = src.rsplit(char::is_whitespace).next()?;
    if !base.starts_with('%') {
        return None;
    }
    let src_ty = src[..src.len() - base.len()].trim();
    if src_ty != dst {
        return None;
    }
    Some((res, base.to_string()))
}

pub(super) fn parse_phi_incoming_values(rest: &str) -> Result<Vec<LlValue>, String> {
    let first_incoming = rest
        .find('[')
        .ok_or_else(|| format!("native emitter: malformed phi: {rest}"))?;
    split_top_level(&rest[first_incoming..], ',')
        .into_iter()
        .map(|incoming| {
            let incoming = incoming
                .trim()
                .strip_prefix('[')
                .and_then(|s| s.strip_suffix(']'))
                .ok_or_else(|| format!("native emitter: malformed phi incoming: {incoming}"))?;
            let parts = split_top_level(incoming, ',');
            if parts.len() != 2 {
                return Err(format!(
                    "native emitter: malformed phi incoming fields: {incoming}"
                ));
            }
            parse_value(parts[0].trim())
        })
        .collect()
}

pub(super) fn parse_type(s: &str) -> Result<LlType, String> {
    let s = strip_leading_fast_math_flags(s.trim());
    if s == "void" {
        return Ok(LlType::Void);
    }
    // `metadata` is the operand type of debug/scope marker intrinsics (which `is_ignored_call_line`
    // drops structurally by operand type). Map it to a placeholder so an ignored intrinsic's
    // declaration parses rather than hard-erroring; it is never lowered.
    if s == "metadata" {
        return Ok(LlType::Void);
    }
    if s == "float" {
        return Ok(LlType::Float);
    }
    if s == "half" {
        return Ok(LlType::Half);
    }
    if s == "bfloat" {
        return Ok(LlType::BFloat);
    }
    if let Some(bits) = s.strip_prefix('i') {
        if bits.chars().all(|c| c.is_ascii_digit()) {
            return Ok(LlType::Int(
                bits.parse()
                    .map_err(|e| format!("native emitter: bad int type {s}: {e}"))?,
            ));
        }
    }
    if let Some(name) = s.strip_prefix('%') {
        if name.starts_with('"') && name.ends_with('"') {
            return Ok(LlType::Named(format!("%{name}")));
        }
        if !name.is_empty()
            && name
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_')
        {
            return Ok(LlType::Named(format!("%{name}")));
        }
    }
    if s == "ptr" {
        return Ok(LlType::Ptr(0));
    }
    if let Some(rest) = s.strip_prefix("ptr addrspace(") {
        let n = rest
            .strip_suffix(')')
            .ok_or_else(|| format!("native emitter: malformed pointer type `{s}`"))?;
        return Ok(LlType::Ptr(n.parse().map_err(|e| {
            format!("native emitter: bad addrspace in `{s}`: {e}")
        })?));
    }
    if s.starts_with('<') && s.ends_with('>') {
        let inner = s[1..s.len() - 1].trim();
        if inner.starts_with('{') && inner.ends_with('}') {
            return parse_struct_fields(&inner[1..inner.len() - 1]).map(LlType::Struct);
        }
        let (lanes, elem) = split_vector_type(inner)?;
        return Ok(LlType::Vector(Box::new(parse_type(elem)?), lanes));
    }
    if s.starts_with('{') && s.ends_with('}') {
        return parse_struct_fields(&s[1..s.len() - 1]).map(LlType::Struct);
    }
    if s.starts_with('[') && s.ends_with(']') {
        let inner = s[1..s.len() - 1].trim();
        let (len, elem) = split_vector_type(inner)?;
        return Ok(LlType::Array(Box::new(parse_type(elem)?), len));
    }
    Err(format!("native emitter: unsupported type `{s}`"))
}

fn strip_leading_fast_math_flags(mut s: &str) -> &str {
    loop {
        let toks = split_top_level_whitespace(s);
        let Some(flag) = toks.first().copied() else {
            return s;
        };
        if !matches!(
            flag,
            "fast" | "nnan" | "ninf" | "nsz" | "arcp" | "contract" | "afn" | "reassoc" | "volatile"
        ) {
            return s;
        }
        s = s[flag.len()..].trim_start();
    }
}

pub(super) fn parse_struct_fields(s: &str) -> Result<Vec<LlType>, String> {
    split_top_level(s, ',')
        .into_iter()
        .map(parse_type)
        .collect::<Result<Vec<_>, _>>()
}

pub(super) fn split_vector_type(s: &str) -> Result<(u32, &str), String> {
    let mut depth = 0i32;
    for (i, c) in s.char_indices() {
        match c {
            '<' | '[' | '{' | '(' => depth += 1,
            '>' | ']' | '}' | ')' => depth -= 1,
            'x' if depth == 0 => {
                let before = s[..i].trim();
                let after = s[i + 1..].trim();
                if before.chars().all(|c| c.is_ascii_digit()) {
                    return Ok((
                        before
                            .parse()
                            .map_err(|e| format!("native emitter: bad vector lane count: {e}"))?,
                        after,
                    ));
                }
            }
            _ => {}
        }
    }
    Err(format!("native emitter: malformed vector type `<{s}>`"))
}

pub(super) fn parse_constant_vector(s: &str) -> Result<TypedValue, String> {
    let s = s.trim();
    let end_ty = matching_angle(s, 0)
        .ok_or_else(|| format!("native emitter: malformed constant vector `{s}`"))?;
    let ty = parse_type(&s[..=end_ty])?;
    Ok(TypedValue {
        ty,
        value: LlValue::Undef,
    })
}

pub(super) fn parse_vector_i32_values(s: &str) -> Result<Vec<u32>, String> {
    let s = s.trim();
    let end_ty = matching_angle(s, 0)
        .ok_or_else(|| format!("native emitter: malformed vector constant `{s}`"))?;
    let ty = parse_type(&s[..=end_ty])?;
    let LlType::Vector(_, lanes) = ty else {
        return Err(format!(
            "native emitter: vector constant type is not a vector `{s}`"
        ));
    };
    let values = s[end_ty + 1..].trim();
    if values == "zeroinitializer" {
        return Ok(vec![0; lanes as usize]);
    }
    if !values.starts_with('<') || !values.ends_with('>') {
        return Err(format!(
            "native emitter: vector constant has no value list `{s}`"
        ));
    }
    split_top_level(&values[1..values.len() - 1], ',')
        .into_iter()
        .map(|v| {
            let v = v.trim();
            let n = v
                .strip_prefix("i32 ")
                .ok_or_else(|| format!("native emitter: expected i32 vector lane, got `{v}`"))?;
            match n.trim() {
                "poison" | "undef" => Ok(u32::MAX),
                n => parse_u32(n),
            }
        })
        .collect()
}

#[cfg(test)]
mod indirect_call_tests {
    use super::*;

    // An AIR call through a `%reg` callee (no `@name`) is an indirect call (Metal visible function
    // table). The diagnostic names the function-pointer register and uses the words the frontier
    // bucketer keys on ("indirect call" / "function pointer"), not the generic "call without callee".
    #[test]
    fn indirect_call_through_register_is_named() {
        let s = "fast <4 x float> %86(ptr addrspace(2) %0, ptr %91)";
        let msg = indirect_call_diagnostic(s);
        assert!(msg.contains("indirect call"), "{msg}");
        assert!(msg.contains("function pointer %86"), "{msg}");
        assert!(!msg.contains("call without callee"), "{msg}");
    }

    // A genuinely malformed call with no register callee still gets the generic message.
    #[test]
    fn malformed_call_without_register_falls_back_to_generic() {
        let s = "void ()";
        let msg = indirect_call_diagnostic(s);
        assert!(msg.contains("call without callee"), "{msg}");
    }
}

#[cfg(test)]
mod parse_tests {
    //! Type/value parser edge cases + a deterministic no-panic fuzz (refactor T8). `parse.rs` had
    //! two tests before this; the S7 emitter decomposition re-parses at emit time, so these pin the
    //! shapes it depends on. Pure-static (no external tools), part of the T2 inner-loop gate.
    use super::*;

    #[test]
    fn parse_type_scalars_and_ints() {
        assert_eq!(parse_type("void").unwrap(), LlType::Void);
        assert_eq!(parse_type("metadata").unwrap(), LlType::Void);
        assert_eq!(parse_type("float").unwrap(), LlType::Float);
        assert_eq!(parse_type("half").unwrap(), LlType::Half);
        assert_eq!(parse_type("bfloat").unwrap(), LlType::BFloat);
        assert_eq!(parse_type("i32").unwrap(), LlType::Int(32));
        assert_eq!(parse_type("i1").unwrap(), LlType::Int(1));
        // fast-math flags are stripped before the type
        assert_eq!(parse_type("nnan ninf float").unwrap(), LlType::Float);
    }

    #[test]
    fn parse_type_pointers() {
        assert_eq!(parse_type("ptr").unwrap(), LlType::Ptr(0));
        assert_eq!(parse_type("ptr addrspace(1)").unwrap(), LlType::Ptr(1));
        assert!(parse_type("ptr addrspace(2").is_err()); // missing ')'
        assert!(parse_type("ptr addrspace(x)").is_err()); // non-numeric
    }

    #[test]
    fn parse_type_named_and_quoted() {
        assert_eq!(
            parse_type("%struct.Foo").unwrap(),
            LlType::Named("%struct.Foo".to_string())
        );
        assert_eq!(
            parse_type(r#"%"a.b c""#).unwrap(),
            LlType::Named(r#"%"a.b c""#.to_string())
        );
    }

    #[test]
    fn parse_type_vectors_arrays_structs() {
        assert_eq!(
            parse_type("<4 x float>").unwrap(),
            LlType::Vector(Box::new(LlType::Float), 4)
        );
        // nested vector
        assert_eq!(
            parse_type("<2 x <4 x i8>>").unwrap(),
            LlType::Vector(Box::new(LlType::Vector(Box::new(LlType::Int(8)), 4)), 2)
        );
        assert_eq!(
            parse_type("[3 x i16]").unwrap(),
            LlType::Array(Box::new(LlType::Int(16)), 3)
        );
        assert_eq!(
            parse_type("{ float, i32 }").unwrap(),
            LlType::Struct(vec![LlType::Float, LlType::Int(32)])
        );
        // a vector wrapping a literal struct
        assert_eq!(
            parse_type("<{ i8, i8 }>").unwrap(),
            LlType::Struct(vec![LlType::Int(8), LlType::Int(8)])
        );
    }

    #[test]
    fn parse_type_rejects_garbage() {
        assert!(parse_type("banana").is_err());
        assert!(parse_type("iZ").is_err()); // 'i' then non-digits
        assert!(parse_type("").is_err());
    }

    #[test]
    fn parse_typed_value_backtracks_over_multiword_types() {
        // `parse_typed_value` scans splits of "type value"; a multi-token type must be recovered.
        // LlValue has no PartialEq (a production choice); match structurally instead of deriving it.
        let tv = parse_typed_value("i32 7").unwrap();
        assert_eq!(tv.ty, LlType::Int(32));
        assert!(matches!(tv.value, LlValue::Int(7)));

        let tv = parse_typed_value("<4 x float> zeroinitializer").unwrap();
        assert_eq!(tv.ty, LlType::Vector(Box::new(LlType::Float), 4));
        assert!(matches!(tv.value, LlValue::Zero));

        let tv = parse_typed_value("ptr addrspace(1) %0").unwrap();
        assert_eq!(tv.ty, LlType::Ptr(1));
        assert!(matches!(tv.value, LlValue::Local(ref s) if s == "%0"));

        assert!(parse_typed_value("i32").is_err()); // no value token
        assert!(parse_typed_value("").is_err());
    }

    #[test]
    fn switch_literal_operand_widths_and_overflow() {
        // small widths pack into a 32-bit literal
        let op = switch_literal_operand(&LlValue::Int(5), &LlType::Int(32)).unwrap();
        assert!(matches!(op, Operand::LiteralBit32(5)));
        // i64 selectors emit a 64-bit literal
        let op = switch_literal_operand(&LlValue::Int(5), &LlType::Int(64)).unwrap();
        assert!(matches!(op, Operand::LiteralBit64(5)));
        // negative case value is masked into the unsigned representation for the width
        let op = switch_literal_operand(&LlValue::SignedInt(-1), &LlType::Int(8)).unwrap();
        assert!(matches!(op, Operand::LiteralBit32(0xFF)));
        // overflow of the selector width is a clean Err, not a panic
        assert!(switch_literal_operand(&LlValue::Int(256), &LlType::Int(8)).is_err());
        // non-integer selector type rejected
        assert!(switch_literal_operand(&LlValue::Int(0), &LlType::Float).is_err());
        // width 0 / >64 rejected
        assert!(switch_literal_operand(&LlValue::Int(0), &LlType::Int(0)).is_err());
        assert!(switch_literal_operand(&LlValue::Int(0), &LlType::Int(128)).is_err());
    }

    // Deterministic, dependency-free fuzz: mutate valid seeds and assert the parsers return a
    // Result (never panic). A panic here is a real finding to journal, not something to paper over.
    #[test]
    fn parsers_never_panic_on_ascii_mutations() {
        let seeds = [
            "i32 7",
            "<4 x float> %0",
            "ptr addrspace(1) %v",
            "{ float, i32 } zeroinitializer",
            "[3 x i16] undef",
            "half 0xH3C00",
            "<2 x <4 x i8>> %x",
        ];
        // a small fixed alphabet of structurally-interesting bytes
        let alphabet = b"<>[]{}(),% x0123456789ifloat\"";
        for seed in seeds {
            let bytes = seed.as_bytes();
            for pos in 0..bytes.len() {
                for &b in alphabet {
                    // substitution
                    let mut m = bytes.to_vec();
                    m[pos] = b;
                    if let Ok(s) = std::str::from_utf8(&m) {
                        let _ = parse_type(s);
                        let _ = parse_typed_value(s);
                    }
                    // deletion
                    let mut d = bytes.to_vec();
                    d.remove(pos);
                    if let Ok(s) = std::str::from_utf8(&d) {
                        let _ = parse_type(s);
                        let _ = parse_typed_value(s);
                    }
                    // insertion
                    let mut ins = bytes.to_vec();
                    ins.insert(pos, b);
                    if let Ok(s) = std::str::from_utf8(&ins) {
                        let _ = parse_type(s);
                        let _ = parse_typed_value(s);
                    }
                }
            }
        }
    }
}