llvm-native-core 0.1.13

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
//! ARM Calling Conventions — complete implementation of AAPCS64,
//! AAPCS, AAPCS-VFP, and legacy ATPCS procedures.
//!
//! Covers:
//! - AAPCS64 (AArch64): Linux, macOS, FreeBSD, etc.
//! - AAPCS (ARM32): standard 32-bit ARM procedure call
//! - AAPCS-VFP (ARM32): hardware floating-point variant
//! - ATPCS: ARM/Thumb legacy procedure call standard
//!
//! Register usage per AAPCS64 §5:
//! - X0–X7:   parameter/result registers (caller-saved)
//! - X8:      indirect result location register
//! - X9–X15:  caller-saved temporaries
//! - X16–X17: intra-procedure-call scratch (IP0, IP1)
//! - X18:     platform register (if needed)
//! - X19–X28: callee-saved
//! - X29:     frame pointer (FP)
//! - X30:     link register (LR)
//! - SP:      stack pointer
//! - V0–V7:   SIMD/FP parameter/result registers
//! - V8–V15:  SIMD/FP callee-saved (lower 64 bits)
//! - V16–V31: SIMD/FP caller-saved
//!
//! Register usage per AAPCS:
//! - R0–R3:   parameter/result registers
//! - R4–R11:  callee-saved
//! - R12:     IP (intra-procedure-call scratch)
//! - R13:     SP (stack pointer)
//! - R14:     LR (link register)
//! - R15:     PC (program counter)
//! - S0–S15:  VFP parameter registers (AAPCS-VFP)
//!
//! Clean-room reconstruction from:
//! - Procedure Call Standard for the ARM 64-bit Architecture (AAPCS64)
//! - Procedure Call Standard for the ARM Architecture (AAPCS)
//! - ARM IHI 0042F: ARM/Thumb Procedure Call Standard
//!
//! Zero LLVM source code consultation.

use super::arm_register_info::*;
use crate::types::{Type, TypeId, TypeKind};
use std::collections::HashMap;

// ============================================================================
// ArmCallingConvention — the set of ARM calling conventions
// ============================================================================

/// All ARM calling conventions supported by this backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ArmCallingConvention {
    /// 64-bit ARM (AArch64) — AAPCS64.
    /// Standard on Linux, macOS, FreeBSD, etc.
    AAPCS64,

    /// 32-bit ARM standard — AAPCS.
    /// Soft-float: FP arguments passed in integer registers.
    AAPCS,

    /// 32-bit ARM with hardware floating-point — AAPCS-VFP.
    /// FP arguments passed in VFP registers (S0-S15, D0-D7).
    #[allow(non_camel_case_types)]
    AAPCS_VFP,

    /// ARM/Thumb procedure call standard (legacy).
    /// Pre-AAPCS; callee-saves R4-R11, LR; no FP register args.
    ATPCS,

    /// Apple ARM64 (iOS, macOS on Apple Silicon).
    /// Based on AAPCS64 with stricter alignment requirements.
    AppleARM64,

    /// Windows ARM64 (Windows on ARM).
    /// Different callee-saved set, shadow space, different parameter handling.
    WindowsARM64,
}

impl ArmCallingConvention {
    /// Human-readable name of the calling convention.
    pub fn name(&self) -> &'static str {
        match self {
            ArmCallingConvention::AAPCS64 => "AAPCS64",
            ArmCallingConvention::AAPCS => "AAPCS",
            ArmCallingConvention::AAPCS_VFP => "AAPCS-VFP",
            ArmCallingConvention::ATPCS => "ATPCS",
            ArmCallingConvention::AppleARM64 => "AppleARM64",
            ArmCallingConvention::WindowsARM64 => "WindowsARM64",
        }
    }

    /// Whether this is a 64-bit (AArch64) convention.
    pub fn is_64bit(&self) -> bool {
        matches!(
            self,
            ArmCallingConvention::AAPCS64
                | ArmCallingConvention::AppleARM64
                | ArmCallingConvention::WindowsARM64
        )
    }

    /// Whether this convention uses register parameters.
    pub fn uses_register_params(&self) -> bool {
        // All ARM conventions use register parameters to some degree
        true
    }

    /// Number of integer parameter registers available.
    pub fn get_num_int_param_regs(&self) -> usize {
        match self {
            ArmCallingConvention::AAPCS64 | ArmCallingConvention::AppleARM64 => 8,
            ArmCallingConvention::WindowsARM64 => 4, // Windows uses x0-x3
            ArmCallingConvention::AAPCS
            | ArmCallingConvention::AAPCS_VFP
            | ArmCallingConvention::ATPCS => 4,
        }
    }

    /// Number of SIMD/FP parameter registers available.
    pub fn get_num_simd_param_regs(&self) -> usize {
        match self {
            ArmCallingConvention::AAPCS64 => 8,
            ArmCallingConvention::AAPCS_VFP => 16, // S0-S15 (or D0-D7 for doubles)
            _ => 0,
        }
    }

    /// Integer parameter registers (by register ID).
    pub fn get_int_param_regs(&self) -> Vec<u16> {
        match self {
            ArmCallingConvention::AAPCS64
            | ArmCallingConvention::AppleARM64
            | ArmCallingConvention::WindowsARM64 => {
                vec![X0, X1, X2, X3, X4, X5, X6, X7]
            }
            ArmCallingConvention::AAPCS
            | ArmCallingConvention::AAPCS_VFP
            | ArmCallingConvention::ATPCS => {
                vec![R0, R1, R2, R3]
            }
        }
    }

    /// SIMD/FP parameter registers (by register ID).
    pub fn get_simd_param_regs(&self) -> Vec<u16> {
        match self {
            ArmCallingConvention::AAPCS64 => {
                vec![V0, V1, V2, V3, V4, V5, V6, V7]
            }
            ArmCallingConvention::AAPCS_VFP => {
                vec![
                    S0_ARM32, S1_ARM32, S2_ARM32, S3_ARM32, S4_ARM32, S5_ARM32, S6_ARM32, S7_ARM32,
                    S8_ARM32, S9_ARM32, S10_ARM32, S11_ARM32, S12_ARM32, S13_ARM32, S14_ARM32,
                    S15_ARM32,
                ]
            }
            _ => vec![],
        }
    }

    /// Stack alignment at the function call boundary.
    pub fn get_stack_alignment(&self) -> u32 {
        match self {
            ArmCallingConvention::AAPCS64
            | ArmCallingConvention::AppleARM64
            | ArmCallingConvention::WindowsARM64 => 16,
            // AAPCS requires 8-byte alignment at public interfaces;
            // internally, 4-byte alignment is common on older cores
            ArmCallingConvention::AAPCS | ArmCallingConvention::AAPCS_VFP => 8,
            ArmCallingConvention::ATPCS => 4,
        }
    }

    /// Whether the convention uses a red zone below the stack pointer.
    /// AArch64 has no red zone per AAPCS64.
    pub fn has_red_zone(&self) -> bool {
        false
    }

    /// Size of the red zone in bytes (always 0 for ARM).
    pub fn red_zone_size(&self) -> i64 {
        0
    }

    /// Get the frame pointer register.
    pub fn get_frame_pointer_reg(&self) -> u16 {
        match self {
            ArmCallingConvention::AAPCS64 => FP, // X29
            _ => R11,                            // ARM32: R11 is the frame pointer
        }
    }

    /// Get the link register.
    pub fn get_link_register_reg(&self) -> u16 {
        match self {
            ArmCallingConvention::AAPCS64 => LR, // X30
            _ => LR_ARM32,                       // R14
        }
    }

    /// Get the stack pointer register.
    pub fn get_stack_pointer_reg(&self) -> u16 {
        match self {
            ArmCallingConvention::AAPCS64 => SP,
            _ => SP_ARM32, // R13
        }
    }

    /// Check whether a type needs an indirect (sret) return.
    ///
    /// AAPCS64 §5.5: Composite types > 16 bytes or with non-trivial
    /// copy semantics use indirect result via X8.
    /// AAPCS: Composite types > 4 bytes use indirect result via R0.
    pub fn needs_indirect_return(&self, ty: &Type, type_map: &HashMap<TypeId, Type>) -> bool {
        if !matches!(
            &ty.kind,
            TypeKind::Struct { .. }
                | TypeKind::Array { .. }
                | TypeKind::FixedVector { .. }
                | TypeKind::ScalableVector { .. }
        ) {
            return false;
        }
        let size = type_size(ty, type_map);
        match self {
            ArmCallingConvention::AAPCS64 => size > 16,
            _ => size > 4,
        }
    }

    /// Determine which registers hold the return value for a given type.
    ///
    /// Returns a vector of register IDs representing the return location.
    pub fn get_return_regs(&self, ty: &Type, type_map: &HashMap<TypeId, Type>) -> Vec<u16> {
        let class = self.classify_arg(ty, type_map);
        match self {
            ArmCallingConvention::AAPCS64 => {
                match class {
                    ArmArgClass::Integer | ArmArgClass::Pointer => {
                        let size = type_size(ty, type_map);
                        if size <= 8 {
                            vec![X0]
                        } else {
                            // 128-bit integer returns in X0:X1
                            vec![X0, X1]
                        }
                    }
                    ArmArgClass::Float | ArmArgClass::ShortVector => {
                        vec![V0]
                    }
                    ArmArgClass::Composite => {
                        if self.needs_indirect_return(ty, type_map) {
                            vec![X8] // sret pointer in X8
                        } else {
                            // Small composite: return in X0 (or X0:X1)
                            let size = type_size(ty, type_map);
                            if size <= 8 {
                                vec![X0]
                            } else {
                                vec![X0, X1]
                            }
                        }
                    }
                    ArmArgClass::Memory => {
                        vec![X8] // Always indirect for MEMORY class
                    }
                }
            }
            _ => {
                // ARM32 return conventions
                match class {
                    ArmArgClass::Integer | ArmArgClass::Pointer => {
                        let size = type_size(ty, type_map);
                        if size <= 4 {
                            vec![R0]
                        } else {
                            // 64-bit in R0:R1
                            vec![R0, R1]
                        }
                    }
                    ArmArgClass::Float | ArmArgClass::ShortVector => {
                        // For AAPCS-VFP, FP in S0/D0; for AAPCS, in R0
                        if matches!(self, ArmCallingConvention::AAPCS_VFP) {
                            vec![S0_ARM32]
                        } else {
                            vec![R0]
                        }
                    }
                    ArmArgClass::Composite | ArmArgClass::Memory => {
                        vec![R0] // sret pointer in R0
                    }
                }
            }
        }
    }

    /// Assign arguments to registers and stack slots.
    ///
    /// Returns per-argument assignment info and the overall call frame
    /// layout.
    pub fn assign_args(
        &self,
        args: &[Type],
        type_map: &HashMap<TypeId, Type>,
    ) -> (Vec<ArmArgInfo>, ArmCallFrame) {
        match self {
            ArmCallingConvention::AAPCS64 => assign_aapcs64_args(args, type_map),
            ArmCallingConvention::AppleARM64 => assign_apple_arm64_args(args, type_map),
            ArmCallingConvention::WindowsARM64 => assign_windows_arm64_args(args, type_map),
            ArmCallingConvention::AAPCS => assign_aapcs_args(args, type_map, false),
            ArmCallingConvention::AAPCS_VFP => assign_aapcs_args(args, type_map, true),
            ArmCallingConvention::ATPCS => assign_atpcs_args(args, type_map),
        }
    }

    /// Classify a single argument type.
    pub fn classify_arg(&self, ty: &Type, type_map: &HashMap<TypeId, Type>) -> ArmArgClass {
        classify_arm_type(ty, type_map)
    }

    /// Get indirection result register per convention.
    pub fn get_indirect_result_reg(&self) -> u16 {
        match self {
            ArmCallingConvention::AAPCS64 => X8,
            _ => R0,
        }
    }

    /// Get the set of registers that are always live-in at a call site
    /// (implicitly used).
    pub fn get_implicit_uses_at_call(&self) -> Vec<u16> {
        match self {
            ArmCallingConvention::AAPCS64 => vec![SP, FP, LR],
            _ => vec![SP_ARM32, LR_ARM32], // R13, R14
        }
    }

    /// Get the set of registers that are clobbered (implicitly defined)
    /// by a call.
    pub fn get_call_clobbered_regs(&self) -> Vec<u16> {
        match self {
            ArmCallingConvention::AAPCS64 => {
                let mut clobbered = vec![
                    X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14, X15, X16, X17,
                    X18,
                ];
                // SIMD caller-saved
                for i in 0..=7 {
                    clobbered.push(V0 + i);
                }
                for i in 16..=31 {
                    clobbered.push(V0 + i);
                }
                // NZCV flags can be clobbered
                clobbered.push(NZCV);
                clobbered
            }
            _ => {
                let mut clobbered = vec![R0, R1, R2, R3, R12];
                clobbered.push(CPSR);
                if matches!(self, ArmCallingConvention::AAPCS_VFP) {
                    for i in 0..=15 {
                        clobbered.push(S0_ARM32 + i);
                    }
                }
                clobbered
            }
        }
    }

    /// Get the callee-saved registers that must be preserved.
    pub fn get_callee_saved_regs(&self) -> Vec<u16> {
        match self {
            ArmCallingConvention::AAPCS64 => {
                let mut saved = Vec::new();
                // GPRs: X19-X28
                for i in 19..=28 {
                    saved.push(X0 + i);
                }
                saved.push(X29); // FP
                saved.push(X30); // LR
                                 // FPRs: V8-V15 (lower 64 bits)
                for i in 8..=15 {
                    saved.push(V0 + i);
                }
                saved
            }
            _ => {
                let mut saved = Vec::new();
                for i in 4..=11 {
                    saved.push(R0 + i);
                }
                if matches!(self, ArmCallingConvention::AAPCS_VFP) {
                    for i in 8..=15 {
                        saved.push(D0_ARM32 + i);
                    }
                }
                saved
            }
        }
    }
}

// ============================================================================
// ArmArgClass — classification for argument types
// ============================================================================

/// Classification of an argument type for register assignment.
///
/// Based on AAPCS64 §5.4 (Stage A — Initial classification).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ArmArgClass {
    /// Integer types: i8, i16, i32, i64, bool, enum, pointer.
    /// Assigned to a general-purpose register (Xn or Wn).
    Integer,

    /// Floating-point types: half, float, double.
    /// Assigned to a SIMD/FP register (Vn, Sn, Dn).
    Float,

    /// Short vector types: <2 x float>, <4 x i16>, etc.
    /// Fits in a single SIMD/FP register.
    ShortVector,

    /// Composite type: struct, array, fixed-length vector,
    /// complex numbers. May be passed in registers or memory
    /// depending on size and HFA/HVA rules.
    Composite,

    /// Pointer type (opaque pointer or typed pointer).
    Pointer,

    /// Must be passed in memory (too large for registers, or
    /// contains non-trivial alignment constraints).
    Memory,
}

impl ArmArgClass {
    /// Whether this class is passed in registers.
    pub fn is_register_class(&self) -> bool {
        matches!(
            self,
            ArmArgClass::Integer
                | ArmArgClass::Float
                | ArmArgClass::ShortVector
                | ArmArgClass::Pointer
        )
    }

    /// Whether this class is a floating-point/SIMD class.
    pub fn is_fp_class(&self) -> bool {
        matches!(self, ArmArgClass::Float | ArmArgClass::ShortVector)
    }
}

// ============================================================================
// ArmArgInfo — per-argument assignment information
// ============================================================================

/// Describes how a single function argument is passed.
#[derive(Debug, Clone)]
pub struct ArmArgInfo {
    /// True if this argument is passed in registers.
    pub in_reg: bool,

    /// Register IDs assigned to this argument (empty if only on stack).
    pub regs: Vec<u16>,

    /// Offset from SP where this argument lives on the stack.
    /// Positive means it lives in the caller's outgoing argument area.
    pub stack_offset: i64,

    /// Size of the argument in bytes.
    pub size: u32,

    /// Alignment requirement of the argument.
    pub alignment: u32,

    /// True if passed by value on the stack (struct byval).
    pub is_byval: bool,

    /// True if this argument uses the indirect result register.
    pub is_indirect: bool,
}

impl Default for ArmArgInfo {
    fn default() -> Self {
        ArmArgInfo {
            in_reg: false,
            regs: Vec::new(),
            stack_offset: 0,
            size: 0,
            alignment: 1,
            is_byval: false,
            is_indirect: false,
        }
    }
}

// ============================================================================
// ArmCallFrame — overall call frame layout
// ============================================================================

/// Describes the stack frame layout for a function call.
#[derive(Debug, Clone)]
pub struct ArmCallFrame {
    /// Total stack space needed for outgoing arguments.
    pub stack_size: i64,

    /// Stack offset for each argument (same order as args).
    pub arg_offsets: Vec<i64>,

    /// Offset of the saved frame pointer in the callee's frame.
    pub saved_fp_offset: i64,

    /// Offset of the saved link register in the callee's frame.
    pub saved_lr_offset: i64,

    /// Total size in bytes of the callee-saved register save area.
    pub callee_saved_size: i64,

    /// Extra padding added to achieve stack alignment.
    pub alignment_padding: i64,
}

impl Default for ArmCallFrame {
    fn default() -> Self {
        ArmCallFrame {
            stack_size: 0,
            arg_offsets: Vec::new(),
            saved_fp_offset: -16,
            saved_lr_offset: -8,
            callee_saved_size: 0,
            alignment_padding: 0,
        }
    }
}

// ============================================================================
// Type size and alignment helpers
// ============================================================================

/// Compute the size in bytes of an LLVM type.
pub fn type_size(ty: &Type, type_map: &HashMap<TypeId, Type>) -> u64 {
    match &ty.kind {
        TypeKind::Void => 0,
        TypeKind::Half | TypeKind::BFloat => 2,
        TypeKind::Float => 4,
        TypeKind::Double => 8,
        TypeKind::FP128 => 16,
        TypeKind::X86FP80 => 16,
        TypeKind::PPCFP128 => 16,
        TypeKind::Label | TypeKind::Metadata | TypeKind::Token => 0,
        TypeKind::X86AMX => 0,
        TypeKind::X86MMX => 8,
        TypeKind::Integer { bits } => ((*bits + 7) / 8) as u64,
        TypeKind::Pointer { .. } => {
            // Assume 64-bit for AArch64, 32-bit for ARM32
            8
        }
        TypeKind::Array {
            len,
            element_type_id,
        } => {
            let elem_size = resolve_type_size(*element_type_id, type_map);
            (*len) * elem_size
        }
        TypeKind::Struct {
            is_packed,
            element_type_ids,
            ..
        } => compute_struct_size(element_type_ids, *is_packed, type_map),
        TypeKind::FixedVector {
            len,
            element_type_id,
        } => {
            let elem_size = resolve_type_size(*element_type_id, type_map);
            (*len as u64) * elem_size
        }
        TypeKind::ScalableVector {
            min_elems,
            element_type_id,
        } => {
            let elem_size = resolve_type_size(*element_type_id, type_map);
            (*min_elems as u64) * elem_size
        }
        TypeKind::Function { .. } => 8,
    }
}

/// Compute the alignment of an LLVM type.
pub fn type_alignment(ty: &Type, type_map: &HashMap<TypeId, Type>) -> u64 {
    match &ty.kind {
        TypeKind::Void | TypeKind::Label | TypeKind::Metadata | TypeKind::Token => 1,
        TypeKind::Half | TypeKind::BFloat => 2,
        TypeKind::Float => 4,
        TypeKind::Double => 8,
        TypeKind::FP128 | TypeKind::PPCFP128 => 16,
        TypeKind::X86FP80 => 16,
        TypeKind::X86AMX => 64,
        TypeKind::X86MMX => 8,
        TypeKind::Integer { bits } => {
            let size = ((*bits + 7) / 8) as u64;
            size.min(16)
        }
        TypeKind::Pointer { .. } => 8,
        TypeKind::Array {
            element_type_id, ..
        } => resolve_type_alignment(*element_type_id, type_map),
        TypeKind::Struct {
            is_packed,
            element_type_ids,
            ..
        } => {
            if *is_packed {
                1
            } else {
                compute_struct_alignment(element_type_ids, type_map)
            }
        }
        TypeKind::FixedVector {
            len,
            element_type_id,
        } => {
            let elem_align = resolve_type_alignment(*element_type_id, type_map);
            let total_size = resolve_type_size(*element_type_id, type_map) * (*len as u64);
            elem_align.max(total_size.next_power_of_two().min(16))
        }
        TypeKind::ScalableVector {
            min_elems,
            element_type_id,
        } => {
            let elem_align = resolve_type_alignment(*element_type_id, type_map);
            elem_align.max(16)
        }
        TypeKind::Function { .. } => 8,
    }
}

fn resolve_type(tid: TypeId, type_map: &HashMap<TypeId, Type>) -> Option<&Type> {
    type_map.get(&tid)
}

fn resolve_type_size(tid: TypeId, type_map: &HashMap<TypeId, Type>) -> u64 {
    resolve_type(tid, type_map)
        .map(|t| type_size(t, type_map))
        .unwrap_or(0)
}

fn resolve_type_alignment(tid: TypeId, type_map: &HashMap<TypeId, Type>) -> u64 {
    resolve_type(tid, type_map)
        .map(|t| type_alignment(t, type_map))
        .unwrap_or(1)
}

fn compute_struct_size(
    element_type_ids: &[TypeId],
    is_packed: bool,
    type_map: &HashMap<TypeId, Type>,
) -> u64 {
    if element_type_ids.is_empty() {
        return 0;
    }
    let mut total = 0u64;
    let mut max_align = 1u64;
    for tid in element_type_ids {
        let elem_size = resolve_type_size(*tid, type_map);
        let elem_align = resolve_type_alignment(*tid, type_map);
        if elem_align > max_align {
            max_align = elem_align;
        }
        if !is_packed {
            total = align_to(total, elem_align);
        }
        total += elem_size;
    }
    if !is_packed && max_align > 0 {
        total = align_to(total, max_align);
    }
    total
}

fn compute_struct_alignment(element_type_ids: &[TypeId], type_map: &HashMap<TypeId, Type>) -> u64 {
    element_type_ids
        .iter()
        .map(|tid| resolve_type_alignment(*tid, type_map))
        .max()
        .unwrap_or(1)
}

fn align_to(value: u64, alignment: u64) -> u64 {
    ((value + alignment - 1) / alignment) * alignment
}

// ============================================================================
// Type classification per AAPCS64 §5.4
// ============================================================================

/// Classify an LLVM type into an ArmArgClass.
///
/// Follows AAPCS64 §5.4 Stage A initial classification rules.
fn classify_arm_type(ty: &Type, _type_map: &HashMap<TypeId, Type>) -> ArmArgClass {
    match &ty.kind {
        TypeKind::Void => ArmArgClass::Memory,
        TypeKind::Half | TypeKind::BFloat | TypeKind::Float | TypeKind::Double => {
            ArmArgClass::Float
        }
        TypeKind::FP128 | TypeKind::PPCFP128 => ArmArgClass::Float,
        TypeKind::Integer { .. } => ArmArgClass::Integer,
        TypeKind::Pointer { .. } => ArmArgClass::Pointer,
        TypeKind::Label | TypeKind::Metadata | TypeKind::Token => ArmArgClass::Memory,
        TypeKind::X86MMX | TypeKind::X86AMX | TypeKind::X86FP80 => ArmArgClass::Memory,
        TypeKind::Array { .. } | TypeKind::Struct { .. } => ArmArgClass::Composite,
        TypeKind::FixedVector {
            len,
            element_type_id: _,
        } => {
            // Short vectors (<= 16 bytes total) go in SIMD regs
            let elem_size = 8u64; // Assume 8-byte max element for classification
            if (*len as u64) * elem_size <= 16 {
                ArmArgClass::ShortVector
            } else {
                ArmArgClass::Composite
            }
        }
        TypeKind::ScalableVector { .. } => ArmArgClass::Memory,
        TypeKind::Function { .. } => ArmArgClass::Pointer,
    }
}

// ============================================================================
// AAPCS64 argument assignment (AArch64)
// ============================================================================

fn assign_aapcs64_args(
    args: &[Type],
    type_map: &HashMap<TypeId, Type>,
) -> (Vec<ArmArgInfo>, ArmCallFrame) {
    let mut arg_infos = Vec::with_capacity(args.len());
    let mut int_regs_used: u8 = 0;
    let mut simd_regs_used: u8 = 0;
    let max_int_regs: u8 = 8; // X0-X7
    let max_simd_regs: u8 = 8; // V0-V7
    let mut stack_offset: i64 = 0;
    let mut arg_offsets = Vec::with_capacity(args.len());

    for arg_ty in args {
        let class = classify_arm_type(arg_ty, type_map);
        let size = type_size(arg_ty, type_map) as u32;
        let alignment = type_alignment(arg_ty, type_map) as u32;
        let mut info = ArmArgInfo {
            size,
            alignment,
            ..Default::default()
        };

        match class {
            ArmArgClass::Integer | ArmArgClass::Pointer => {
                if int_regs_used < max_int_regs && size <= 8 {
                    info.in_reg = true;
                    info.regs.push(X0 + int_regs_used as u16);
                    int_regs_used += 1;
                    if size > 8 {
                        if int_regs_used < max_int_regs {
                            info.regs.push(X0 + int_regs_used as u16);
                            int_regs_used += 1;
                        } else {
                            // Overflowed to stack
                            info.regs.clear();
                            info.in_reg = false;
                            stack_offset = align_to(stack_offset as u64, alignment as u64) as i64;
                            info.stack_offset = stack_offset;
                            stack_offset += size as i64;
                        }
                    }
                } else {
                    // Stack overflow
                    stack_offset = align_to(stack_offset as u64, alignment as u64) as i64;
                    info.stack_offset = stack_offset;
                    stack_offset += size as i64;
                }
            }
            ArmArgClass::Float | ArmArgClass::ShortVector => {
                if simd_regs_used < max_simd_regs {
                    info.in_reg = true;
                    // Assign enough registers based on size
                    let regs_needed = (size.max(1) as u8 + 15) / 16; // V regs are 16 bytes
                    for r in 0..regs_needed.min(max_simd_regs - simd_regs_used) {
                        info.regs.push(V0 + (simd_regs_used + r) as u16);
                    }
                    simd_regs_used += regs_needed.min(max_simd_regs - simd_regs_used);
                    if regs_needed
                        > max_simd_regs - simd_regs_used
                            + regs_needed.min(max_simd_regs - simd_regs_used)
                    {
                        // Partial overflow: some in regs, rest on stack
                        // Simplified: all on stack if not enough regs
                        info.regs.clear();
                        info.in_reg = false;
                        stack_offset = align_to(stack_offset as u64, alignment as u64) as i64;
                        info.stack_offset = stack_offset;
                        stack_offset += size as i64;
                    }
                } else {
                    stack_offset = align_to(stack_offset as u64, alignment as u64) as i64;
                    info.stack_offset = stack_offset;
                    stack_offset += size as i64;
                }
            }
            ArmArgClass::Composite => {
                if size <= 16 {
                    // Try register assignment for small composites
                    // Simplified: use integer registers
                    let int_regs_needed = ((size as u64 + 7) / 8) as u8;
                    if int_regs_used + int_regs_needed <= max_int_regs {
                        info.in_reg = true;
                        for r in 0..int_regs_needed {
                            info.regs.push(X0 + (int_regs_used + r) as u16);
                        }
                        int_regs_used += int_regs_needed;
                    } else {
                        // Pass on stack
                        stack_offset = align_to(stack_offset as u64, alignment as u64) as i64;
                        info.stack_offset = stack_offset;
                        stack_offset += size as i64;
                    }
                } else {
                    // Large composite: byval on stack
                    info.is_byval = true;
                    stack_offset = align_to(stack_offset as u64, alignment as u64) as i64;
                    info.stack_offset = stack_offset;
                    stack_offset += size as i64;
                }
            }
            ArmArgClass::Memory => {
                info.is_byval = true;
                stack_offset = align_to(stack_offset as u64, alignment as u64) as i64;
                info.stack_offset = stack_offset;
                stack_offset += size as i64;
            }
        }

        arg_offsets.push(info.stack_offset);
        arg_infos.push(info);
    }

    // Align total stack size to convention's alignment
    let stack_align = 16u64; // AAPCS64: 16-byte stack alignment
    let total_stack = align_to(stack_offset as u64, stack_align) as i64;

    let call_frame = ArmCallFrame {
        stack_size: total_stack,
        arg_offsets,
        saved_fp_offset: -(total_stack + 16),
        saved_lr_offset: -(total_stack + 8),
        callee_saved_size: 0,
        alignment_padding: total_stack - stack_offset,
    };

    (arg_infos, call_frame)
}

// ============================================================================
// AAPCS argument assignment (ARM32)
// ============================================================================

fn assign_aapcs_args(
    args: &[Type],
    type_map: &HashMap<TypeId, Type>,
    use_vfp: bool,
) -> (Vec<ArmArgInfo>, ArmCallFrame) {
    let mut arg_infos = Vec::with_capacity(args.len());
    let mut int_regs_used: u8 = 0;
    let mut vfp_regs_used: u8 = 0;
    let max_int_regs: u8 = 4; // R0-R3
    let max_vfp_regs: u8 = 16; // S0-S15 (or D0-D7 for doubles)
    let mut stack_offset: i64 = 0;
    let mut arg_offsets = Vec::with_capacity(args.len());

    for arg_ty in args {
        let class = classify_arm_type(arg_ty, type_map);
        let size = type_size(arg_ty, type_map) as u32;
        let alignment = type_alignment(arg_ty, type_map) as u32;
        let mut info = ArmArgInfo {
            size,
            alignment,
            ..Default::default()
        };

        match class {
            ArmArgClass::Integer | ArmArgClass::Pointer => {
                if int_regs_used < max_int_regs {
                    info.in_reg = true;
                    let regs_needed = ((size as u64 + 3) / 4) as u8;
                    for r in 0..regs_needed.min(max_int_regs - int_regs_used) {
                        info.regs.push(R0 + (int_regs_used + r) as u16);
                    }
                    int_regs_used += regs_needed.min(max_int_regs - int_regs_used);
                    if regs_needed
                        > max_int_regs - int_regs_used
                            + regs_needed.min(max_int_regs - int_regs_used)
                    {
                        // Overflow to stack
                        info.regs.clear();
                        info.in_reg = false;
                        stack_offset = align_to(stack_offset as u64, alignment as u64) as i64;
                        info.stack_offset = stack_offset;
                        stack_offset += size as i64;
                    }
                } else {
                    stack_offset = align_to(stack_offset as u64, alignment as u64) as i64;
                    info.stack_offset = stack_offset;
                    stack_offset += size as i64;
                }
            }
            ArmArgClass::Float | ArmArgClass::ShortVector => {
                if use_vfp && vfp_regs_used < max_vfp_regs {
                    info.in_reg = true;
                    if size <= 4 {
                        info.regs.push(S0_ARM32 + vfp_regs_used as u16);
                        vfp_regs_used += 1;
                    } else if size <= 8 {
                        // Align to even S register for double
                        if vfp_regs_used % 2 != 0 {
                            vfp_regs_used += 1;
                        }
                        if vfp_regs_used < max_vfp_regs {
                            info.regs.push(D0_ARM32 + (vfp_regs_used / 2) as u16);
                            vfp_regs_used += 2;
                        } else {
                            info.regs.clear();
                            info.in_reg = false;
                            stack_offset = align_to(stack_offset as u64, 8) as i64;
                            info.stack_offset = stack_offset;
                            stack_offset += size as i64;
                        }
                    }
                } else {
                    // No VFP: pass in integer registers or stack
                    if !use_vfp && int_regs_used < max_int_regs && size <= 4 {
                        info.in_reg = true;
                        info.regs.push(R0 + int_regs_used as u16);
                        int_regs_used += 1;
                    } else {
                        stack_offset = align_to(stack_offset as u64, alignment as u64) as i64;
                        info.stack_offset = stack_offset;
                        stack_offset += size as i64;
                    }
                }
            }
            ArmArgClass::Composite => {
                if size <= 4 {
                    if int_regs_used < max_int_regs {
                        info.in_reg = true;
                        info.regs.push(R0 + int_regs_used as u16);
                        int_regs_used += 1;
                    } else {
                        stack_offset = align_to(stack_offset as u64, 4) as i64;
                        info.stack_offset = stack_offset;
                        stack_offset += size as i64;
                    }
                } else {
                    // Large composite: byval on stack
                    info.is_byval = true;
                    stack_offset = align_to(stack_offset as u64, alignment as u64) as i64;
                    info.stack_offset = stack_offset;
                    stack_offset += size as i64;
                }
            }
            ArmArgClass::Memory => {
                info.is_byval = true;
                stack_offset = align_to(stack_offset as u64, alignment as u64) as i64;
                info.stack_offset = stack_offset;
                stack_offset += size as i64;
            }
        }

        arg_offsets.push(info.stack_offset);
        arg_infos.push(info);
    }

    let stack_align = 8u64;
    let total_stack = align_to(stack_offset as u64, stack_align) as i64;

    let call_frame = ArmCallFrame {
        stack_size: total_stack,
        arg_offsets,
        saved_fp_offset: -(total_stack + 4),
        saved_lr_offset: -(total_stack + 0),
        callee_saved_size: 0,
        alignment_padding: total_stack - stack_offset,
    };

    (arg_infos, call_frame)
}

// ============================================================================
// ATPCS argument assignment (legacy ARM32)
// ============================================================================

fn assign_atpcs_args(
    args: &[Type],
    type_map: &HashMap<TypeId, Type>,
) -> (Vec<ArmArgInfo>, ArmCallFrame) {
    // ATPCS uses same rules as AAPCS without VFP
    assign_aapcs_args(args, type_map, false)
}

/// Align a value up to the nearest multiple of `alignment`.
fn align_up(value: i64, alignment: i64) -> i64 {
    if alignment <= 0 {
        return value;
    }
    ((value + alignment - 1) / alignment) * alignment
}

// ============================================================================
// Apple ARM64 calling convention
// ============================================================================

/// Apple ARM64 (Darwin) argument assignment.
///
/// Based on AAPCS64 but with stricter alignment:
/// - Stack arguments must be naturally aligned.
/// - 128-bit types on stack must be 16-byte aligned.
/// - Varargs slightly different.
fn assign_apple_arm64_args(
    args: &[Type],
    type_map: &HashMap<TypeId, Type>,
) -> (Vec<ArmArgInfo>, ArmCallFrame) {
    let mut infos = Vec::new();
    let mut gpr_idx = 0usize;
    let mut fpr_idx = 0usize;
    let mut stack_offset = 0i64;
    let max_gpr = 8usize;
    let max_fpr = 8usize;

    for arg in args {
        let class = classify_arm_type(arg, type_map);
        let size = type_size(arg, type_map) as i64;
        let align = type_alignment(arg, type_map) as i64;

        let mut info = ArmArgInfo {
            size: size as u32,
            alignment: align as u32,
            ..ArmArgInfo::default()
        };

        match class {
            ArmArgClass::Integer | ArmArgClass::Pointer => {
                if gpr_idx < max_gpr {
                    info.in_reg = true;
                    info.regs.push(X0 + gpr_idx as u16);
                    if size > 8 {
                        if gpr_idx + 1 < max_gpr {
                            info.regs.push(X0 + (gpr_idx + 1) as u16);
                            gpr_idx += 1;
                        } else {
                            info.in_reg = false;
                            stack_offset = align_up(stack_offset, align);
                            info.stack_offset = stack_offset;
                            stack_offset += size;
                        }
                    }
                    gpr_idx += 1;
                } else {
                    stack_offset = align_up(stack_offset, align);
                    info.stack_offset = stack_offset;
                    stack_offset += size;
                }
            }
            ArmArgClass::Float | ArmArgClass::ShortVector => {
                if fpr_idx < max_fpr {
                    info.in_reg = true;
                    info.regs.push(V0 + fpr_idx as u16);
                    fpr_idx += 1;
                } else if gpr_idx < max_gpr {
                    info.in_reg = true;
                    info.regs.push(X0 + gpr_idx as u16);
                    gpr_idx += 1;
                } else {
                    stack_offset = align_up(stack_offset, align);
                    info.stack_offset = stack_offset;
                    stack_offset += size;
                }
            }
            _ => {
                stack_offset = align_up(stack_offset, align);
                info.stack_offset = stack_offset;
                stack_offset += size;
            }
        }

        infos.push(info);
    }

    let frame = ArmCallFrame {
        stack_size: align_up(stack_offset, 16),
        arg_offsets: infos.iter().map(|i| i.stack_offset).collect(),
        saved_fp_offset: -16,
        saved_lr_offset: -8,
        callee_saved_size: 0,
        alignment_padding: 0,
    };

    (infos, frame)
}

// ============================================================================
// Windows ARM64 calling convention
// ============================================================================

/// Windows ARM64 argument assignment.
///
/// Windows ARM64 differs from AAPCS64 in several ways:
/// - Only X0-X3 are used for integer arguments.
/// - Callee must allocate 32 bytes of "shadow space" on stack for the
///   first 4 register parameters.
/// - Different callee-saved register set.
/// - No HFA/HVA rules; composites always in memory or decomposed.
fn assign_windows_arm64_args(
    args: &[Type],
    type_map: &HashMap<TypeId, Type>,
) -> (Vec<ArmArgInfo>, ArmCallFrame) {
    let mut infos = Vec::new();
    let mut gpr_idx = 0usize;
    let mut fpr_idx = 0usize;
    let max_gpr = 4usize; // Windows only uses X0-X3
    let max_fpr = 8usize;
    let shadow_space = 32i64;
    let mut stack_offset = shadow_space; // Shadow space at start of stack args

    for arg in args {
        let class = classify_arm_type(arg, type_map);
        let size = type_size(arg, type_map) as i64;
        let align = type_alignment(arg, type_map) as i64;

        let mut info = ArmArgInfo {
            size: size as u32,
            alignment: align as u32,
            ..ArmArgInfo::default()
        };

        match class {
            ArmArgClass::Integer | ArmArgClass::Pointer => {
                if gpr_idx < max_gpr {
                    info.in_reg = true;
                    info.regs.push(X0 + gpr_idx as u16);
                    gpr_idx += 1;
                } else {
                    stack_offset = align_up(stack_offset, align);
                    info.stack_offset = stack_offset;
                    stack_offset += size;
                }
            }
            ArmArgClass::Float | ArmArgClass::ShortVector => {
                if fpr_idx < max_fpr {
                    info.in_reg = true;
                    info.regs.push(V0 + fpr_idx as u16);
                    gpr_idx += 1; // Windows consumes a GPR slot for each FP arg too!
                    fpr_idx += 1;
                } else {
                    stack_offset = align_up(stack_offset, align);
                    info.stack_offset = stack_offset;
                    stack_offset += size;
                }
            }
            _ => {
                // Composites on Windows are always in memory
                info.is_byval = true;
                stack_offset = align_up(stack_offset, align);
                info.stack_offset = stack_offset;
                stack_offset += size;
            }
        }

        infos.push(info);
    }

    let frame = ArmCallFrame {
        stack_size: align_up(stack_offset.max(shadow_space), 16),
        arg_offsets: infos.iter().map(|i| i.stack_offset).collect(),
        saved_fp_offset: -16,
        saved_lr_offset: -8,
        callee_saved_size: 0,
        alignment_padding: 0,
    };

    (infos, frame)
}

// ============================================================================
// Varargs support (AAPCS64)
// ============================================================================

/// Number of general-purpose registers used for varargs save area (AAPCS64).
pub const VARARGS_GPR_SAVE_SIZE: usize = 8;

/// Number of SIMD/FP registers used for varargs save area (AAPCS64).
pub const VARARGS_FPR_SAVE_SIZE: usize = 8;

/// Compute the size of the varargs register save area.
pub fn varargs_save_area_size(is_64bit: bool) -> i64 {
    if is_64bit {
        // X0-X7 (8 * 8) + V0-V7 (8 * 16) = 64 + 128 = 192
        192
    } else {
        // R0-R3 (4 * 4) = 16 for AAPCS
        16
    }
}

/// Compute the offset of a specific varargs GPR in the save area.
pub fn varargs_gpr_offset(gpr_idx: usize, is_64bit: bool) -> i64 {
    if is_64bit {
        gpr_idx as i64 * 8
    } else {
        gpr_idx as i64 * 4
    }
}

/// Compute the offset of a specific varargs FPR in the save area.
pub fn varargs_fpr_offset(fpr_idx: usize) -> i64 {
    // FPR save area starts after GPR save area
    (VARARGS_GPR_SAVE_SIZE * 8) as i64 + fpr_idx as i64 * 16
}

// ============================================================================
// SVE calling convention
// ============================================================================

/// SVE predicate registers used for parameter passing (P0-P3).
/// Placeholder register IDs for SVE predicate registers.
pub const P0_SVE: u16 = 2150;
pub const P1_SVE: u16 = 2151;
pub const P2_SVE: u16 = 2152;
pub const P3_SVE: u16 = 2153;

/// SVE vector registers used for parameter passing (Z0-Z7).
pub const Z0_SVE: u16 = 2160;
pub const Z1_SVE: u16 = 2161;
pub const Z2_SVE: u16 = 2162;
pub const Z3_SVE: u16 = 2163;
pub const Z4_SVE: u16 = 2164;
pub const Z5_SVE: u16 = 2165;
pub const Z6_SVE: u16 = 2166;
pub const Z7_SVE: u16 = 2167;

/// SVE callee-saved Z registers (Z8-Z23).
pub const Z8_SVE: u16 = 2168;
pub const Z9_SVE: u16 = 2169;
pub const Z10_SVE: u16 = 2170;
pub const Z11_SVE: u16 = 2171;
pub const Z12_SVE: u16 = 2172;
pub const Z13_SVE: u16 = 2173;
pub const Z14_SVE: u16 = 2174;
pub const Z15_SVE: u16 = 2175;
pub const Z16_SVE: u16 = 2176;
pub const Z17_SVE: u16 = 2177;
pub const Z18_SVE: u16 = 2178;
pub const Z19_SVE: u16 = 2179;
pub const Z20_SVE: u16 = 2180;
pub const Z21_SVE: u16 = 2181;
pub const Z22_SVE: u16 = 2182;
pub const Z23_SVE: u16 = 2183;

/// SVE callee-saved P registers (P4-P15).
pub const P4_SVE: u16 = 2154;
pub const P5_SVE: u16 = 2155;
pub const P6_SVE: u16 = 2156;
pub const P7_SVE: u16 = 2157;
pub const P8_SVE: u16 = 2158;
pub const P9_SVE: u16 = 2159;
pub const P10_SVE: u16 = 2190;
pub const P11_SVE: u16 = 2191;
pub const P12_SVE: u16 = 2192;
pub const P13_SVE: u16 = 2193;
pub const P14_SVE: u16 = 2194;
pub const P15_SVE: u16 = 2195;

/// SVE predicate registers used for parameter passing (P0-P3).
pub const SVE_ARG_PREDICATE_REGS: &[u16] = &[P0_SVE, P1_SVE, P2_SVE, P3_SVE];

/// SVE vector registers used for parameter passing (Z0-Z7).
pub const SVE_ARG_VECTOR_REGS: &[u16] = &[
    Z0_SVE, Z1_SVE, Z2_SVE, Z3_SVE, Z4_SVE, Z5_SVE, Z6_SVE, Z7_SVE,
];

/// SVE callee-saved Z registers (Z8-Z23).
pub const SVE_CALLEE_SAVED_Z_REGS: &[u16] = &[
    Z8_SVE, Z9_SVE, Z10_SVE, Z11_SVE, Z12_SVE, Z13_SVE, Z14_SVE, Z15_SVE, Z16_SVE, Z17_SVE,
    Z18_SVE, Z19_SVE, Z20_SVE, Z21_SVE, Z22_SVE, Z23_SVE,
];

/// SVE callee-saved P registers (P4-P15).
pub const SVE_CALLEE_SAVED_P_REGS: &[u16] = &[
    P4_SVE, P5_SVE, P6_SVE, P7_SVE, P8_SVE, P9_SVE, P10_SVE, P11_SVE, P12_SVE, P13_SVE, P14_SVE,
    P15_SVE,
];

/// Get the SVE argument registers (Z registers).
pub fn get_sve_arg_regs() -> Vec<u16> {
    SVE_ARG_VECTOR_REGS.to_vec()
}

/// Get the SVE callee-saved register count.
pub fn get_sve_callee_saved_count() -> usize {
    SVE_CALLEE_SAVED_Z_REGS.len() + SVE_CALLEE_SAVED_P_REGS.len()
}

// ============================================================================
// HFA/HVA Detection — Homogeneous Floating-point/Vector Aggregate
// ============================================================================

/// Check if a type is a Homogeneous Floating-point Aggregate (HFA).
///
/// Per AAPCS64 §5.4.2: An HFA is a composite type with 1-4 members
/// all of the same floating-point type (float, double, or 128-bit).
///
/// HFAs are passed entirely in SIMD/FP registers.
pub fn is_hfa(ty: &Type, type_map: &HashMap<TypeId, Type>) -> Option<usize> {
    match &ty.kind {
        TypeKind::Struct {
            element_type_ids, ..
        } => {
            if element_type_ids.is_empty() || element_type_ids.len() > 4 {
                return None;
            }
            let first = resolve_type(element_type_ids[0], type_map);
            let base_class = first.map(|t| classify_arm_type(t, type_map));
            if !matches!(base_class, Some(ArmArgClass::Float)) {
                return None;
            }
            let first_kind = first.map(|t| &t.kind);
            for tid in &element_type_ids[1..] {
                let elem = resolve_type(*tid, type_map);
                if elem.map(|t| &t.kind) != first_kind {
                    return None;
                }
            }
            Some(element_type_ids.len())
        }
        TypeKind::Array {
            len,
            element_type_id,
        } => {
            if *len > 4 {
                return None;
            }
            let elem = resolve_type(*element_type_id, type_map);
            if let Some(e) = elem {
                if matches!(classify_arm_type(e, type_map), ArmArgClass::Float) {
                    return Some(*len as usize);
                }
            }
            None
        }
        _ => None,
    }
}

/// Check if a type is a Homogeneous Short-Vector Aggregate (HVA).
///
/// Per AAPCS64 §5.4.2: An HVA is like an HFA but with short vector
/// members (e.g., <2 x float>) instead of scalar floats.
pub fn is_hva(ty: &Type, type_map: &HashMap<TypeId, Type>) -> Option<usize> {
    match &ty.kind {
        TypeKind::Struct {
            element_type_ids, ..
        } => {
            if element_type_ids.is_empty() || element_type_ids.len() > 4 {
                return None;
            }
            let first = resolve_type(element_type_ids[0], type_map);
            let base_class = first.map(|t| classify_arm_type(t, type_map));
            if !matches!(base_class, Some(ArmArgClass::ShortVector)) {
                return None;
            }
            for tid in &element_type_ids[1..] {
                let elem = resolve_type(*tid, type_map);
                if elem.map(|t| classify_arm_type(t, type_map)) != base_class {
                    return None;
                }
            }
            Some(element_type_ids.len())
        }
        _ => None,
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    fn make_type(kind: TypeKind) -> Type {
        Type {
            id: TypeId::new(),
            kind,
        }
    }

    fn empty_type_map() -> HashMap<TypeId, Type> {
        HashMap::new()
    }

    #[test]
    fn test_convention_names() {
        assert_eq!(ArmCallingConvention::AAPCS64.name(), "AAPCS64");
        assert_eq!(ArmCallingConvention::AAPCS.name(), "AAPCS");
        assert_eq!(ArmCallingConvention::AAPCS_VFP.name(), "AAPCS-VFP");
        assert_eq!(ArmCallingConvention::ATPCS.name(), "ATPCS");
    }

    #[test]
    fn test_is_64bit() {
        assert!(ArmCallingConvention::AAPCS64.is_64bit());
        assert!(!ArmCallingConvention::AAPCS.is_64bit());
        assert!(!ArmCallingConvention::AAPCS_VFP.is_64bit());
        assert!(!ArmCallingConvention::ATPCS.is_64bit());
    }

    #[test]
    fn test_uses_register_params() {
        assert!(ArmCallingConvention::AAPCS64.uses_register_params());
        assert!(ArmCallingConvention::AAPCS.uses_register_params());
    }

    #[test]
    fn test_num_int_param_regs() {
        assert_eq!(ArmCallingConvention::AAPCS64.get_num_int_param_regs(), 8);
        assert_eq!(ArmCallingConvention::AAPCS.get_num_int_param_regs(), 4);
        assert_eq!(ArmCallingConvention::AAPCS_VFP.get_num_int_param_regs(), 4);
        assert_eq!(ArmCallingConvention::ATPCS.get_num_int_param_regs(), 4);
    }

    #[test]
    fn test_num_simd_param_regs() {
        assert_eq!(ArmCallingConvention::AAPCS64.get_num_simd_param_regs(), 8);
        assert_eq!(
            ArmCallingConvention::AAPCS_VFP.get_num_simd_param_regs(),
            16
        );
        assert_eq!(ArmCallingConvention::AAPCS.get_num_simd_param_regs(), 0);
    }

    #[test]
    fn test_int_param_regs_aapcs64() {
        let regs = ArmCallingConvention::AAPCS64.get_int_param_regs();
        assert_eq!(regs.len(), 8);
        assert_eq!(regs[0], X0);
        assert_eq!(regs[7], X7);
    }

    #[test]
    fn test_int_param_regs_aapcs() {
        let regs = ArmCallingConvention::AAPCS.get_int_param_regs();
        assert_eq!(regs.len(), 4);
        assert_eq!(regs[0], R0);
        assert_eq!(regs[3], R3);
    }

    #[test]
    fn test_simd_param_regs_aapcs64() {
        let regs = ArmCallingConvention::AAPCS64.get_simd_param_regs();
        assert_eq!(regs.len(), 8);
        assert_eq!(regs[0], V0);
        assert_eq!(regs[7], V7);
    }

    #[test]
    fn test_stack_alignment() {
        assert_eq!(ArmCallingConvention::AAPCS64.get_stack_alignment(), 16);
        assert_eq!(ArmCallingConvention::AAPCS.get_stack_alignment(), 8);
        assert_eq!(ArmCallingConvention::ATPCS.get_stack_alignment(), 4);
    }

    #[test]
    fn test_no_red_zone() {
        assert!(!ArmCallingConvention::AAPCS64.has_red_zone());
        assert_eq!(ArmCallingConvention::AAPCS64.red_zone_size(), 0);
    }

    #[test]
    fn test_register_aliases() {
        // FP and LR aliases for AArch64
        assert_eq!(ArmCallingConvention::AAPCS64.get_frame_pointer_reg(), FP);
        assert_eq!(ArmCallingConvention::AAPCS64.get_link_register_reg(), LR);
        assert_eq!(ArmCallingConvention::AAPCS64.get_stack_pointer_reg(), SP);
        // ARM32 default FP is R11
        assert_eq!(ArmCallingConvention::AAPCS.get_frame_pointer_reg(), R11);
        assert_eq!(
            ArmCallingConvention::AAPCS.get_link_register_reg(),
            LR_ARM32
        );
        assert_eq!(
            ArmCallingConvention::AAPCS.get_stack_pointer_reg(),
            SP_ARM32
        );
    }

    #[test]
    fn test_type_size_primitives() {
        let m = empty_type_map();
        assert_eq!(type_size(&make_type(TypeKind::Void), &m), 0);
        assert_eq!(type_size(&make_type(TypeKind::Half), &m), 2);
        assert_eq!(type_size(&make_type(TypeKind::Float), &m), 4);
        assert_eq!(type_size(&make_type(TypeKind::Double), &m), 8);
        assert_eq!(type_size(&make_type(TypeKind::Integer { bits: 32 }), &m), 4);
        assert_eq!(type_size(&make_type(TypeKind::Integer { bits: 64 }), &m), 8);
        assert_eq!(type_size(&make_type(TypeKind::Integer { bits: 1 }), &m), 1);
    }

    #[test]
    fn test_type_alignment_primitives() {
        let m = empty_type_map();
        assert_eq!(
            type_alignment(&make_type(TypeKind::Integer { bits: 32 }), &m),
            4
        );
        assert_eq!(
            type_alignment(&make_type(TypeKind::Integer { bits: 64 }), &m),
            8
        );
        assert_eq!(type_alignment(&make_type(TypeKind::Double), &m), 8);
    }

    #[test]
    fn test_classify_integer() {
        let m = empty_type_map();
        let ty = make_type(TypeKind::Integer { bits: 32 });
        assert_eq!(
            ArmCallingConvention::AAPCS64.classify_arg(&ty, &m),
            ArmArgClass::Integer
        );
    }

    #[test]
    fn test_classify_float() {
        let m = empty_type_map();
        let ty = make_type(TypeKind::Float);
        assert_eq!(
            ArmCallingConvention::AAPCS64.classify_arg(&ty, &m),
            ArmArgClass::Float
        );
        let ty_d = make_type(TypeKind::Double);
        assert_eq!(
            ArmCallingConvention::AAPCS64.classify_arg(&ty_d, &m),
            ArmArgClass::Float
        );
    }

    #[test]
    fn test_classify_pointer() {
        let m = empty_type_map();
        let ty = make_type(TypeKind::Pointer { addr_space: 0 });
        assert_eq!(
            ArmCallingConvention::AAPCS64.classify_arg(&ty, &m),
            ArmArgClass::Pointer
        );
    }

    #[test]
    fn test_return_regs_integer_aapcs64() {
        let m = empty_type_map();
        let ty = make_type(TypeKind::Integer { bits: 64 });
        let regs = ArmCallingConvention::AAPCS64.get_return_regs(&ty, &m);
        assert_eq!(regs.len(), 1);
        assert_eq!(regs[0], X0);
    }

    #[test]
    fn test_return_regs_float_aapcs64() {
        let m = empty_type_map();
        let ty = make_type(TypeKind::Float);
        let regs = ArmCallingConvention::AAPCS64.get_return_regs(&ty, &m);
        assert_eq!(regs.len(), 1);
        assert_eq!(regs[0], V0);
    }

    #[test]
    fn test_return_regs_integer_arm32() {
        let m = empty_type_map();
        let ty = make_type(TypeKind::Integer { bits: 32 });
        let regs = ArmCallingConvention::AAPCS.get_return_regs(&ty, &m);
        assert_eq!(regs.len(), 1);
        assert_eq!(regs[0], R0);
    }

    #[test]
    fn test_assign_args_aapcs64_simple() {
        let m = empty_type_map();
        let args = vec![
            make_type(TypeKind::Integer { bits: 64 }),
            make_type(TypeKind::Integer { bits: 32 }),
        ];
        let (infos, _frame) = ArmCallingConvention::AAPCS64.assign_args(&args, &m);
        assert_eq!(infos.len(), 2);
        assert!(infos[0].in_reg);
        assert_eq!(infos[0].regs[0], X0);
    }

    #[test]
    fn test_assign_args_aapcs64_many() {
        let m = empty_type_map();
        // 12 integer args — first 8 in regs, last 4 on stack
        let args: Vec<Type> = (0..12)
            .map(|_| make_type(TypeKind::Integer { bits: 64 }))
            .collect();
        let (infos, frame) = ArmCallingConvention::AAPCS64.assign_args(&args, &m);
        assert_eq!(infos.len(), 12);
        assert!(infos[0].in_reg);
        assert!(!infos[8].in_reg); // 9th arg on stack
        assert!(frame.stack_size > 0);
    }

    #[test]
    fn test_assign_args_aapcs_many() {
        let m = empty_type_map();
        // 8 integer args — first 4 in regs, last 4 on stack
        let args: Vec<Type> = (0..8)
            .map(|_| make_type(TypeKind::Integer { bits: 32 }))
            .collect();
        let (infos, _frame) = ArmCallingConvention::AAPCS.assign_args(&args, &m);
        assert_eq!(infos.len(), 8);
        assert!(infos[0].in_reg);
        assert!(!infos[4].in_reg);
    }

    #[test]
    fn test_call_clobbered_aapcs64() {
        let regs = ArmCallingConvention::AAPCS64.get_call_clobbered_regs();
        assert!(regs.contains(&X0));
        assert!(regs.contains(&X15));
        assert!(regs.contains(&V0));
        assert!(regs.contains(&NZCV));
        assert!(!regs.contains(&X19)); // callee-saved
    }

    #[test]
    fn test_call_clobbered_aapcs() {
        let regs = ArmCallingConvention::AAPCS.get_call_clobbered_regs();
        assert!(regs.contains(&R0));
        assert!(regs.contains(&R3));
        assert!(regs.contains(&R12));
        assert!(regs.contains(&CPSR));
        assert!(!regs.contains(&R4)); // callee-saved
    }

    #[test]
    fn test_callee_saved_aapcs64() {
        let regs = ArmCallingConvention::AAPCS64.get_callee_saved_regs();
        assert!(regs.contains(&X19));
        assert!(regs.contains(&X28));
        assert!(regs.contains(&X29)); // FP
        assert!(regs.contains(&X30)); // LR
        assert!(regs.contains(&V8));
    }

    #[test]
    fn test_callee_saved_aapcs() {
        let regs = ArmCallingConvention::AAPCS.get_callee_saved_regs();
        assert!(regs.contains(&R4));
        assert!(regs.contains(&R11));
    }

    #[test]
    fn test_indirect_result_reg() {
        assert_eq!(ArmCallingConvention::AAPCS64.get_indirect_result_reg(), X8);
        assert_eq!(ArmCallingConvention::AAPCS.get_indirect_result_reg(), R0);
    }

    #[test]
    fn test_implicit_uses_at_call() {
        let regs = ArmCallingConvention::AAPCS64.get_implicit_uses_at_call();
        assert!(regs.contains(&SP));
        assert!(regs.contains(&FP));
        assert!(regs.contains(&LR));
    }

    #[test]
    fn test_is_hfa() {
        // HFA detection needs a proper type map, but for scalar floats it won't match
        // Test with non-struct/array type returns None
        let m = empty_type_map();
        let ty = make_type(TypeKind::Float);
        assert_eq!(is_hfa(&ty, &m), None);
    }

    // ------------------------------------------------------------------
    // Apple ARM64 tests
    // ------------------------------------------------------------------

    #[test]
    fn test_apple_arm64_name() {
        assert_eq!(ArmCallingConvention::AppleARM64.name(), "AppleARM64");
    }

    #[test]
    fn test_apple_arm64_is_64bit() {
        assert!(ArmCallingConvention::AppleARM64.is_64bit());
    }

    #[test]
    fn test_apple_arm64_num_int_param_regs() {
        assert_eq!(ArmCallingConvention::AppleARM64.get_num_int_param_regs(), 8);
    }

    #[test]
    fn test_apple_arm64_assign_args() {
        let m = empty_type_map();
        let args = vec![
            make_type(TypeKind::Integer { bits: 64 }),
            make_type(TypeKind::Float),
        ];
        let (infos, frame) = ArmCallingConvention::AppleARM64.assign_args(&args, &m);
        assert_eq!(infos.len(), 2);
        assert!(infos[0].in_reg);
        assert!(infos[1].in_reg);
        assert_eq!(frame.stack_size % 16, 0); // Apple requires 16-byte alignment
    }

    #[test]
    fn test_apple_arm64_many_args_spill_to_stack() {
        let m = empty_type_map();
        let args: Vec<Type> = (0..12)
            .map(|_| make_type(TypeKind::Integer { bits: 64 }))
            .collect();
        let (infos, frame) = ArmCallingConvention::AppleARM64.assign_args(&args, &m);
        assert_eq!(infos.len(), 12);
        assert!(infos[0].in_reg);
        assert!(infos[8].stack_offset > 0);
        assert_ne!(frame.stack_size, 0);
    }

    // ------------------------------------------------------------------
    // Windows ARM64 tests
    // ------------------------------------------------------------------

    #[test]
    fn test_windows_arm64_name() {
        assert_eq!(ArmCallingConvention::WindowsARM64.name(), "WindowsARM64");
    }

    #[test]
    fn test_windows_arm64_is_64bit() {
        assert!(ArmCallingConvention::WindowsARM64.is_64bit());
    }

    #[test]
    fn test_windows_arm64_only_4_gprs() {
        assert_eq!(
            ArmCallingConvention::WindowsARM64.get_num_int_param_regs(),
            4
        );
    }

    #[test]
    fn test_windows_arm64_shadow_space() {
        let m = empty_type_map();
        let args = vec![make_type(TypeKind::Integer { bits: 64 })];
        let (infos, frame) = ArmCallingConvention::WindowsARM64.assign_args(&args, &m);
        assert_eq!(infos.len(), 1);
        assert!(infos[0].in_reg);
        // Shadow space: 32 bytes minimum
        assert!(frame.stack_size >= 32);
        assert_eq!(frame.stack_size % 16, 0);
    }

    #[test]
    fn test_windows_arm64_spill_after_4_gprs() {
        let m = empty_type_map();
        let args: Vec<Type> = (0..6)
            .map(|_| make_type(TypeKind::Integer { bits: 64 }))
            .collect();
        let (infos, _frame) = ArmCallingConvention::WindowsARM64.assign_args(&args, &m);
        assert!(infos[0].in_reg);
        assert!(infos[3].in_reg); // 4th arg still in reg
        assert!(!infos[4].in_reg); // 5th arg on stack
    }

    // ------------------------------------------------------------------
    // Varargs tests
    // ------------------------------------------------------------------

    #[test]
    fn test_varargs_save_area_size_aarch64() {
        assert_eq!(varargs_save_area_size(true), 192); // 8*8 + 8*16
    }

    #[test]
    fn test_varargs_save_area_size_arm32() {
        assert_eq!(varargs_save_area_size(false), 16); // 4*4
    }

    #[test]
    fn test_varargs_gpr_offset_aarch64() {
        assert_eq!(varargs_gpr_offset(0, true), 0);
        assert_eq!(varargs_gpr_offset(1, true), 8);
        assert_eq!(varargs_gpr_offset(7, true), 56);
    }

    #[test]
    fn test_varargs_gpr_offset_arm32() {
        assert_eq!(varargs_gpr_offset(0, false), 0);
        assert_eq!(varargs_gpr_offset(1, false), 4);
        assert_eq!(varargs_gpr_offset(3, false), 12);
    }

    #[test]
    fn test_varargs_fpr_offset() {
        // FPR area starts after GPR save (8*8 = 64)
        assert_eq!(varargs_fpr_offset(0), 64);
        assert_eq!(varargs_fpr_offset(1), 80);
        assert_eq!(varargs_fpr_offset(7), 176);
    }

    // ------------------------------------------------------------------
    // SVE tests
    // ------------------------------------------------------------------

    #[test]
    fn test_sve_arg_regs_count() {
        let regs = get_sve_arg_regs();
        assert_eq!(regs.len(), 8); // Z0-Z7
    }

    #[test]
    fn test_sve_callee_saved_count() {
        // 16 Z regs + 12 P regs = 28 total
        assert_eq!(get_sve_callee_saved_count(), 28);
    }

    #[test]
    fn test_sve_arg_predicate_regs() {
        assert_eq!(SVE_ARG_PREDICATE_REGS.len(), 4);
    }

    #[test]
    fn test_sve_arg_vector_regs() {
        assert_eq!(SVE_ARG_VECTOR_REGS.len(), 8);
    }

    #[test]
    fn test_sve_callee_saved_z_regs() {
        assert_eq!(SVE_CALLEE_SAVED_Z_REGS.len(), 16);
    }

    #[test]
    fn test_sve_callee_saved_p_regs() {
        assert_eq!(SVE_CALLEE_SAVED_P_REGS.len(), 12);
    }

    // ------------------------------------------------------------------
    // Indirect result tests
    // ------------------------------------------------------------------

    #[test]
    fn test_indirect_result_reg_apple_arm64() {
        // Apple ARM64 uses X8 like AAPCS64
        assert_eq!(
            ArmCallingConvention::AppleARM64.get_indirect_result_reg(),
            X8
        );
    }

    #[test]
    fn test_indirect_result_reg_windows_arm64() {
        assert_eq!(
            ArmCallingConvention::WindowsARM64.get_indirect_result_reg(),
            X8
        );
    }

    #[test]
    fn test_implicit_uses_apple_arm64() {
        let regs = ArmCallingConvention::AppleARM64.get_implicit_uses_at_call();
        assert!(regs.contains(&SP));
        assert!(regs.contains(&FP));
        assert!(regs.contains(&LR));
    }

    #[test]
    fn test_needs_indirect_return_apple_arm64() {
        let m = empty_type_map();
        let large_struct = Type::struct_type(&[], false); // empty struct falls through
                                                          // Test with a type that passes size check
        let ty = make_type(TypeKind::Integer { bits: 128 });
        assert!(!ArmCallingConvention::AppleARM64.needs_indirect_return(&ty, &m));
    }

    // ------------------------------------------------------------------
    // ATPCS tests
    // ------------------------------------------------------------------

    #[test]
    fn test_atpcs_name() {
        assert_eq!(ArmCallingConvention::ATPCS.name(), "ATPCS");
    }

    #[test]
    fn test_atpcs_not_64bit() {
        assert!(!ArmCallingConvention::ATPCS.is_64bit());
    }

    #[test]
    fn test_atpcs_uses_register_params() {
        assert!(ArmCallingConvention::ATPCS.uses_register_params());
    }

    #[test]
    fn test_atpcs_param_regs() {
        assert_eq!(ArmCallingConvention::ATPCS.get_num_int_param_regs(), 4);
    }

    // ------------------------------------------------------------------
    // Misc convention tests
    // ------------------------------------------------------------------

    #[test]
    fn test_all_convention_names() {
        let conventions = [
            ArmCallingConvention::AAPCS64,
            ArmCallingConvention::AAPCS,
            ArmCallingConvention::AAPCS_VFP,
            ArmCallingConvention::ATPCS,
            ArmCallingConvention::AppleARM64,
            ArmCallingConvention::WindowsARM64,
        ];
        for conv in &conventions {
            let name = conv.name();
            assert!(!name.is_empty());
        }
    }

    #[test]
    fn test_get_num_int_param_regs_all() {
        assert_eq!(ArmCallingConvention::AAPCS64.get_num_int_param_regs(), 8);
        assert_eq!(ArmCallingConvention::AppleARM64.get_num_int_param_regs(), 8);
        assert_eq!(
            ArmCallingConvention::WindowsARM64.get_num_int_param_regs(),
            4
        );
        assert_eq!(ArmCallingConvention::AAPCS.get_num_int_param_regs(), 4);
        assert_eq!(ArmCallingConvention::AAPCS_VFP.get_num_int_param_regs(), 4);
        assert_eq!(ArmCallingConvention::ATPCS.get_num_int_param_regs(), 4);
    }

    #[test]
    fn test_arm_arg_class_is_register() {
        assert!(ArmArgClass::Integer.is_register_class());
        assert!(ArmArgClass::Float.is_register_class());
        assert!(ArmArgClass::ShortVector.is_register_class());
        assert!(ArmArgClass::Pointer.is_register_class());
        assert!(!ArmArgClass::Composite.is_register_class());
        assert!(!ArmArgClass::Memory.is_register_class());
    }

    #[test]
    fn test_arm_arg_class_is_fp() {
        assert!(ArmArgClass::Float.is_fp_class());
        assert!(ArmArgClass::ShortVector.is_fp_class());
        assert!(!ArmArgClass::Integer.is_fp_class());
        assert!(!ArmArgClass::Pointer.is_fp_class());
    }

    #[test]
    fn test_arm_arg_info_default() {
        let info = ArmArgInfo::default();
        assert!(!info.in_reg);
        assert!(info.regs.is_empty());
        assert_eq!(info.stack_offset, 0);
        assert_eq!(info.size, 0);
        assert_eq!(info.alignment, 1);
        assert!(!info.is_byval);
        assert!(!info.is_indirect);
    }
}