llvm-native-core 0.1.11

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
//! LLVM Attributes — function, parameter, and return attributes.
//!
//! Clean-room behavioral reconstruction. Phase 2 — LLVM.IR.2 Court.
//!
//! @llvm_behavior: In LLVM, attributes are key-value annotations attached
//! to functions, parameters, and return values. They guide optimization,
//! code generation, and semantics. Function attributes like `noinline`,
//! `readnone`, and `noreturn` describe global properties. Parameter
//! attributes like `zeroext`, `align`, `dereferenceable` constrain
//! individual arguments.
//!
//! The attribute system supports:
//! - Enum attributes: fixed, well-known attribute kinds
//! - String attributes: arbitrary key-value pairs
//! - Attribute groups: bundles of attributes referenced by ID

use std::collections::HashMap;

/// Function attribute kinds — attributes that apply to a function as a whole.
///
/// @llvm_behavior: These correspond to `llvm::Attribute::AttrKind` in C++.
/// Each variant maps to a known LLVM function or call-site attribute.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AttributeKind {
    // === Optimization hints ===
    /// Disable inlining of this function.
    NoInline,
    /// Force inlining of this function (hint).
    AlwaysInline,
    /// Disable all optimizations on this function.
    OptimizeNone,
    /// Prefer optimizing for code size.
    OptimizeForSize,
    /// Prefer optimizing for speed.
    OptimizeForSpeed,

    // === Memory effects ===
    /// Function does not read or write memory.
    ReadNone,
    /// Function only reads memory (no writes).
    ReadOnly,
    /// Function only writes memory (no reads of accessible memory).
    WriteOnly,
    /// Function only accesses memory reachable through its arguments.
    ArgMemOnly,
    /// Function only accesses memory that is inaccessible to the caller.
    InaccessibleMemOnly,
    /// Function only accesses memory reachable through arguments or
    /// inaccessible memory.
    InaccessibleMemOrArgMemOnly,

    // === Exception handling ===
    /// Function does not unwind (no exceptions).
    NoUnwind,
    /// Function never returns (e.g., exit, abort).
    NoReturn,
    /// Function will return normally (not an infinite loop).
    WillReturn,

    // === Stack protection ===
    /// Enable stack protector (canary).
    Ssp,
    /// Require stack protector (always insert canary).
    SspReq,
    /// Strong stack protector (more aggressive heuristics).
    SspStrong,

    // === Sanitizers ===
    /// Enable AddressSanitizer instrumentation.
    SanitizeAddress,
    /// Enable ThreadSanitizer instrumentation.
    SanitizeThread,
    /// Enable MemorySanitizer instrumentation.
    SanitizeMemory,
    /// Enable Hardware-assisted AddressSanitizer instrumentation.
    SanitizeHwAddress,
    /// Disable sanitizer instrumentation for this function.
    NoSanitize,
    /// Enable SanitizerCoverage instrumentation.
    SanitizeCoverage,

    // === Security ===
    /// Enable ShadowCallStack instrumentation.
    ShadowCallStack,
    /// Enable Speculative Load Hardening mitigation.
    SpeculativeLoadHardening,
    /// Disable control-flow enforcement checks.
    NoCfCheck,

    // === Calling convention / ABI ===
    /// Align the stack to at least N bytes on entry.
    AlignStack(u32),
    /// Function uses a naked calling convention (no prologue/epilogue).
    Naked,
    /// Disable implicit floating-point instructions.
    NoImplicitFloat,
    /// Disable red zone (no stack access below SP).
    NoRedZone,
    /// Request unwind table generation.
    UWTable,
    /// Frame pointer management: all, none, non-leaf.
    FramePointer(FramePointerKind),

    // === Inlining / merging ===
    /// Hint that inlining this function is desirable.
    InlineHint,
    /// Prevent merging of identical functions.
    NoMerge,
    /// Function returns twice (like setjmp or fork).
    ReturnsTwice,
    /// Use jump table for switch lowering.
    JumpTable,

    // === Concurrency / progress ===
    /// Function will eventually return (makes forward progress).
    MustProgress,
    /// Function is convergent (threads must execute same path).
    Convergent,
    /// Function cannot diverge (no divergent branches).
    NoDivergenceSource,

    // === Profiling / debugging ===
    /// Disable profile instrumentation for this function.
    NoProfile,
    /// Skip profile-based optimizations.
    SkipProfile,
    /// Prefer optimization hints from source-level debug info.
    OptDebug,
    /// Optimize for fuzzing (add coverage instrumentation).
    OptForFuzzing,

    // === Allocator hints ===
    /// The function is an allocator: allocsize(N, M) indicates that
    /// parameter N contains the allocation size, and parameter M
    /// contains the element count (optional).
    AllocSize(u32, Option<u32>),
    /// Pointer argument is allocation result (for memory analysis).
    AllocPtr,

    // === Builtin / library ===
    /// Disable builtin recognition for this function.
    NoBuiltin,
    /// Function is a callback (may be called from unknown context).
    NoCallback,
    /// Lazy binding (PLT) not needed for this function.
    NonLazyBind,

    // === Security hardening ===
    /// Enable SafeStack for this function.
    SafeStack,
    /// Enable Memory Tagging Extension sanitizer.
    SanitizeMemTag,
    /// Disable sanitizer instrumentation entirely.
    DisableSanitizerInstrumentation,
    /// Patchable function entry for hotpatching.
    Hotpatch,
    /// FnRetThunkExtern: use external return thunk for mitigation.
    FnRetThunkExtern,

    // === Floating-point ===
    /// Restrict floating-point transformations for strict compliance.
    StrictFP,
    /// Classify which floating-point classes are valid for this function.
    NoFPClass(u32),

    // === Vector / scalable ===
    /// The function has unknown vscale range (scalable vector).
    VScaleRange(u32, u32),

    // === Speculation ===
    /// Function is speculatable (can be speculated safely).
    Speculatable,

    // === Other function attributes ===
    /// Function cannot be duplicated (e.g., for jump threading).
    NoDuplicate,
    /// Function does not recurse (no self or mutual recursion).
    NoRecurse,
    /// Function does not synchronize (no locks, atomics, or volatile).
    NoSync,
    /// Function does not free memory.
    NoFree,
    /// Function is cold (rarely executed).
    Cold,
    /// Function is hot (frequently executed).
    Hot,
    /// Minimize code size (stronger than OptimizeForSize).
    Minsize,
    /// The null pointer is valid for this function.
    NullPointerIsValid,
    /// Use sample-based profile data for this function.
    UseSampleProfile,

    // === String-keyed attribute ===
    /// A named attribute with a key and optional value string.
    /// Used for target-specific and extended attributes.
    StringAttribute(String, String),
}

/// Frame pointer kind for the `frame-pointer` attribute.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FramePointerKind {
    /// Always preserve frame pointer.
    All,
    /// Only preserve in non-leaf functions.
    NonLeaf,
    /// Never preserve frame pointer.
    None,
}

impl AttributeKind {
    /// Parse an attribute kind from its LLVM assembly string representation.
    ///
    /// @llvm_behavior: Recognizes the standard attribute names as emitted
    /// by `llvm-as` and `opt`. Returns `None` for unrecognized strings.
    pub fn from_string(s: &str) -> Option<Self> {
        match s {
            "noinline" => Some(AttributeKind::NoInline),
            "alwaysinline" => Some(AttributeKind::AlwaysInline),
            "optnone" => Some(AttributeKind::OptimizeNone),
            "optsize" => Some(AttributeKind::OptimizeForSize),
            "optforspeed" => Some(AttributeKind::OptimizeForSpeed),

            "readnone" | "memory(none)" => Some(AttributeKind::ReadNone),
            "readonly" | "memory(read)" => Some(AttributeKind::ReadOnly),
            "writeonly" | "memory(write)" => Some(AttributeKind::WriteOnly),
            "argmemonly" => Some(AttributeKind::ArgMemOnly),
            "inaccessiblememonly" => Some(AttributeKind::InaccessibleMemOnly),
            "inaccessiblemem_or_argmemonly" => Some(AttributeKind::InaccessibleMemOrArgMemOnly),

            "nounwind" => Some(AttributeKind::NoUnwind),
            "noreturn" => Some(AttributeKind::NoReturn),
            "willreturn" => Some(AttributeKind::WillReturn),

            "ssp" => Some(AttributeKind::Ssp),
            "sspreq" => Some(AttributeKind::SspReq),
            "sspstrong" => Some(AttributeKind::SspStrong),

            "sanitize_address" => Some(AttributeKind::SanitizeAddress),
            "sanitize_thread" => Some(AttributeKind::SanitizeThread),
            "sanitize_memory" => Some(AttributeKind::SanitizeMemory),
            "sanitize_hwaddress" => Some(AttributeKind::SanitizeHwAddress),
            "nosanitize" => Some(AttributeKind::NoSanitize),
            "sanitize_coverage" => Some(AttributeKind::SanitizeCoverage),

            "shadowcallstack" => Some(AttributeKind::ShadowCallStack),
            "speculative_load_hardening" => Some(AttributeKind::SpeculativeLoadHardening),
            "nocf_check" => Some(AttributeKind::NoCfCheck),

            "noduplicate" => Some(AttributeKind::NoDuplicate),
            "norecurse" => Some(AttributeKind::NoRecurse),
            "nosync" => Some(AttributeKind::NoSync),
            "nofree" => Some(AttributeKind::NoFree),
            "cold" => Some(AttributeKind::Cold),
            "hot" => Some(AttributeKind::Hot),
            "minsize" => Some(AttributeKind::Minsize),
            "null_pointer_is_valid" => Some(AttributeKind::NullPointerIsValid),
            "use_sample_profile" => Some(AttributeKind::UseSampleProfile),

            // === New: calling convention / ABI ===
            "naked" => Some(AttributeKind::Naked),
            "noimplicitfloat" => Some(AttributeKind::NoImplicitFloat),
            "noredzone" => Some(AttributeKind::NoRedZone),
            "uwtable" => Some(AttributeKind::UWTable),
            s if s.starts_with("alignstack(") => {
                let inner = &s["alignstack(".len()..s.len() - 1];
                inner.parse::<u32>().ok().map(AttributeKind::AlignStack)
            }
            s if s.starts_with("frame-pointer=") => {
                let kind = &s["frame-pointer=".len()..];
                Some(AttributeKind::FramePointer(match kind {
                    "all" => FramePointerKind::All,
                    "non-leaf" => FramePointerKind::NonLeaf,
                    _ => FramePointerKind::None,
                }))
            }

            // === New: inlining / merging ===
            "inlinehint" => Some(AttributeKind::InlineHint),
            "nomerge" => Some(AttributeKind::NoMerge),
            "returns_twice" => Some(AttributeKind::ReturnsTwice),
            "jumptable" => Some(AttributeKind::JumpTable),

            // === New: concurrency / progress ===
            "mustprogress" => Some(AttributeKind::MustProgress),
            "convergent" => Some(AttributeKind::Convergent),
            "noduplicatesource" => Some(AttributeKind::NoDivergenceSource),

            // === New: profiling / debugging ===
            "noprofile" => Some(AttributeKind::NoProfile),
            "skipprofile" => Some(AttributeKind::SkipProfile),
            "optdebug" => Some(AttributeKind::OptDebug),
            "optforfuzzing" => Some(AttributeKind::OptForFuzzing),

            // === New: allocator hints ===
            s if s.starts_with("allocsize(") => {
                let inner = &s["allocsize(".len()..s.len() - 1];
                let parts: Vec<&str> = inner.split(',').collect();
                let p0 = parts[0].trim().parse::<u32>().ok()?;
                let p1 = if parts.len() > 1 {
                    parts[1].trim().parse::<u32>().ok()
                } else {
                    None
                };
                Some(AttributeKind::AllocSize(p0, p1))
            }
            "allocptr" => Some(AttributeKind::AllocPtr),

            // === New: builtin / library ===
            "nobuiltin" => Some(AttributeKind::NoBuiltin),
            "nocallback" => Some(AttributeKind::NoCallback),
            "nonlazybind" => Some(AttributeKind::NonLazyBind),

            // === New: security hardening ===
            "safestack" => Some(AttributeKind::SafeStack),
            "sanitize_memtag" => Some(AttributeKind::SanitizeMemTag),
            "disable_sanitizer_instrumentation" => {
                Some(AttributeKind::DisableSanitizerInstrumentation)
            }
            "hotpatch" => Some(AttributeKind::Hotpatch),
            "fn_ret_thunk_extern" => Some(AttributeKind::FnRetThunkExtern),

            // === New: floating-point ===
            "strictfp" => Some(AttributeKind::StrictFP),
            s if s.starts_with("nofpclass(") => {
                let inner = &s["nofpclass(".len()..s.len() - 1];
                inner.parse::<u32>().ok().map(AttributeKind::NoFPClass)
            }

            // === New: vector / scalable ===
            s if s.starts_with("vscale_range(") => {
                let inner = &s["vscale_range(".len()..s.len() - 1];
                let parts: Vec<&str> = inner.split(',').collect();
                let min = parts[0].trim().parse::<u32>().ok()?;
                let max = if parts.len() > 1 {
                    parts[1].trim().parse::<u32>().ok()?
                } else {
                    min
                };
                Some(AttributeKind::VScaleRange(min, max))
            }

            // === New: speculation ===
            "speculatable" => Some(AttributeKind::Speculatable),

            _ => {
                // Try to parse as a string attribute: "key" or "key=value"
                if let Some(eq_pos) = s.find('=') {
                    let key = s[..eq_pos].to_string();
                    let value = s[eq_pos + 1..].to_string();
                    Some(AttributeKind::StringAttribute(key, value))
                } else {
                    None
                }
            }
        }
    }

    /// Convert this attribute kind to its LLVM assembly string representation.
    ///
    /// @llvm_behavior: Produces the canonical attribute name used in `.ll`
    /// files. String attributes are formatted as `"key"="value"`.
    pub fn to_string(&self) -> String {
        match self {
            AttributeKind::NoInline => "noinline".to_string(),
            AttributeKind::AlwaysInline => "alwaysinline".to_string(),
            AttributeKind::OptimizeNone => "optnone".to_string(),
            AttributeKind::OptimizeForSize => "optsize".to_string(),
            AttributeKind::OptimizeForSpeed => "optforspeed".to_string(),

            AttributeKind::ReadNone => "readnone".to_string(),
            AttributeKind::ReadOnly => "readonly".to_string(),
            AttributeKind::WriteOnly => "writeonly".to_string(),
            AttributeKind::ArgMemOnly => "argmemonly".to_string(),
            AttributeKind::InaccessibleMemOnly => "inaccessiblememonly".to_string(),
            AttributeKind::InaccessibleMemOrArgMemOnly => {
                "inaccessiblemem_or_argmemonly".to_string()
            }

            AttributeKind::NoUnwind => "nounwind".to_string(),
            AttributeKind::NoReturn => "noreturn".to_string(),
            AttributeKind::WillReturn => "willreturn".to_string(),

            AttributeKind::Ssp => "ssp".to_string(),
            AttributeKind::SspReq => "sspreq".to_string(),
            AttributeKind::SspStrong => "sspstrong".to_string(),

            AttributeKind::SanitizeAddress => "sanitize_address".to_string(),
            AttributeKind::SanitizeThread => "sanitize_thread".to_string(),
            AttributeKind::SanitizeMemory => "sanitize_memory".to_string(),
            AttributeKind::SanitizeHwAddress => "sanitize_hwaddress".to_string(),
            AttributeKind::NoSanitize => "nosanitize".to_string(),
            AttributeKind::SanitizeCoverage => "sanitize_coverage".to_string(),

            AttributeKind::ShadowCallStack => "shadowcallstack".to_string(),
            AttributeKind::SpeculativeLoadHardening => "speculative_load_hardening".to_string(),
            AttributeKind::NoCfCheck => "nocf_check".to_string(),

            AttributeKind::NoDuplicate => "noduplicate".to_string(),
            AttributeKind::NoRecurse => "norecurse".to_string(),
            AttributeKind::NoSync => "nosync".to_string(),
            AttributeKind::NoFree => "nofree".to_string(),
            AttributeKind::Cold => "cold".to_string(),
            AttributeKind::Hot => "hot".to_string(),
            AttributeKind::Minsize => "minsize".to_string(),
            AttributeKind::NullPointerIsValid => "null_pointer_is_valid".to_string(),
            AttributeKind::UseSampleProfile => "use_sample_profile".to_string(),

            // === New: calling convention / ABI ===
            AttributeKind::AlignStack(n) => format!("alignstack({})", n),
            AttributeKind::Naked => "naked".to_string(),
            AttributeKind::NoImplicitFloat => "noimplicitfloat".to_string(),
            AttributeKind::NoRedZone => "noredzone".to_string(),
            AttributeKind::UWTable => "uwtable".to_string(),
            AttributeKind::FramePointer(kind) => format!(
                "frame-pointer={}",
                match kind {
                    FramePointerKind::All => "all",
                    FramePointerKind::NonLeaf => "non-leaf",
                    FramePointerKind::None => "none",
                }
            ),

            // === New: inlining / merging ===
            AttributeKind::InlineHint => "inlinehint".to_string(),
            AttributeKind::NoMerge => "nomerge".to_string(),
            AttributeKind::ReturnsTwice => "returns_twice".to_string(),
            AttributeKind::JumpTable => "jumptable".to_string(),

            // === New: concurrency / progress ===
            AttributeKind::MustProgress => "mustprogress".to_string(),
            AttributeKind::Convergent => "convergent".to_string(),
            AttributeKind::NoDivergenceSource => "noduplicatesource".to_string(),

            // === New: profiling / debugging ===
            AttributeKind::NoProfile => "noprofile".to_string(),
            AttributeKind::SkipProfile => "skipprofile".to_string(),
            AttributeKind::OptDebug => "optdebug".to_string(),
            AttributeKind::OptForFuzzing => "optforfuzzing".to_string(),

            // === New: allocator hints ===
            AttributeKind::AllocSize(p0, Some(p1)) => format!("allocsize({}, {})", p0, p1),
            AttributeKind::AllocSize(p0, None) => format!("allocsize({})", p0),
            AttributeKind::AllocPtr => "allocptr".to_string(),

            // === New: builtin / library ===
            AttributeKind::NoBuiltin => "nobuiltin".to_string(),
            AttributeKind::NoCallback => "nocallback".to_string(),
            AttributeKind::NonLazyBind => "nonlazybind".to_string(),

            // === New: security hardening ===
            AttributeKind::SafeStack => "safestack".to_string(),
            AttributeKind::SanitizeMemTag => "sanitize_memtag".to_string(),
            AttributeKind::DisableSanitizerInstrumentation => {
                "disable_sanitizer_instrumentation".to_string()
            }
            AttributeKind::Hotpatch => "hotpatch".to_string(),
            AttributeKind::FnRetThunkExtern => "fn_ret_thunk_extern".to_string(),

            // === New: floating-point ===
            AttributeKind::StrictFP => "strictfp".to_string(),
            AttributeKind::NoFPClass(n) => format!("nofpclass({})", n),

            // === New: vector / scalable ===
            AttributeKind::VScaleRange(min, max) => format!("vscale_range({}, {})", min, max),

            // === New: speculation ===
            AttributeKind::Speculatable => "speculatable".to_string(),

            AttributeKind::StringAttribute(key, val) => format!("\"{}\"=\"{}\"", key, val),
        }
    }

    /// Returns true if this is a memory-effect attribute.
    pub fn is_memory_attr(&self) -> bool {
        matches!(
            self,
            AttributeKind::ReadNone
                | AttributeKind::ReadOnly
                | AttributeKind::WriteOnly
                | AttributeKind::ArgMemOnly
                | AttributeKind::InaccessibleMemOnly
                | AttributeKind::InaccessibleMemOrArgMemOnly
        )
    }

    /// Returns true if this is a sanitizer attribute.
    pub fn is_sanitizer_attr(&self) -> bool {
        matches!(
            self,
            AttributeKind::SanitizeAddress
                | AttributeKind::SanitizeThread
                | AttributeKind::SanitizeMemory
                | AttributeKind::SanitizeHwAddress
                | AttributeKind::NoSanitize
                | AttributeKind::SanitizeCoverage
                | AttributeKind::SanitizeMemTag
                | AttributeKind::DisableSanitizerInstrumentation
        )
    }

    /// Returns true if this is a security-related attribute.
    pub fn is_security_attr(&self) -> bool {
        matches!(
            self,
            AttributeKind::Ssp
                | AttributeKind::SspReq
                | AttributeKind::SspStrong
                | AttributeKind::ShadowCallStack
                | AttributeKind::SpeculativeLoadHardening
                | AttributeKind::NoCfCheck
                | AttributeKind::SafeStack
                | AttributeKind::Hotpatch
                | AttributeKind::FnRetThunkExtern
        )
    }

    /// Returns true if this is an inlining-related attribute.
    pub fn is_inline_attr(&self) -> bool {
        matches!(
            self,
            AttributeKind::NoInline
                | AttributeKind::AlwaysInline
                | AttributeKind::InlineHint
                | AttributeKind::NoMerge
        )
    }

    /// Returns true if this is a floating-point attribute.
    pub fn is_fp_attr(&self) -> bool {
        matches!(self, AttributeKind::StrictFP | AttributeKind::NoFPClass(_))
    }

    /// Returns true if this attribute carries a numeric argument.
    pub fn has_numeric_arg(&self) -> bool {
        matches!(
            self,
            AttributeKind::AlignStack(_)
                | AttributeKind::AllocSize(_, _)
                | AttributeKind::NoFPClass(_)
                | AttributeKind::VScaleRange(_, _)
        )
    }
}

/// Parameter and return value attribute kinds.
///
/// @llvm_behavior: These correspond to `llvm::Attribute` parameter/return
/// attributes. Some are parameter-only (like `ByVal`, `StructRet`), others
/// can appear on both parameters and return values (like `ZeroExt`,
/// `NoAlias`). Variants like `Dereferenceable` and `Align` carry numeric
/// arguments.
#[derive(Debug, Clone, PartialEq)]
pub enum ParamAttrKind {
    /// Zero-extend the value before passing (integer promotion).
    ZeroExt,
    /// Sign-extend the value before passing.
    SignExt,
    /// The parameter does not alias any other accessible memory.
    NoAlias,
    /// The parameter is not captured by the function.
    NoCapture,
    /// The function does not free this parameter.
    NoFree,
    /// The parameter cannot be null.
    NonNull,
    /// The parameter is only read (not written).
    ReadOnly,
    /// The parameter is only written (not read).
    WriteOnly,
    /// The pointer parameter is dereferenceable for at least N bytes.
    Dereferenceable(u64),
    /// The pointer parameter is dereferenceable for at least N bytes, or null.
    DereferenceableOrNull(u64),
    /// The parameter has at least the given alignment.
    Align(u32),
    /// Pass the argument by value (copy) using the given type.
    ByVal(crate::types::Type),
    /// The parameter is a struct return value (sret).
    StructRet(crate::types::Type),
    /// Pass the argument in a register.
    InReg,
    /// The value is returned (used in return position to refer to parameter).
    Returned,
    /// The argument is an immediate constant.
    ImmArg,
    /// Sign-extend the value (alias for SignExt, used in some contexts).
    SExt,
    /// The value has no undefined bits.
    NoUndef,
    /// Pass the argument by reference using the given type.
    ByRef(crate::types::Type),
    /// The parameter memory is preallocated (for coroutines).
    Preallocated(crate::types::Type),

    // === Extended parameter attributes ===
    /// The argument is passed in the inalloca slot (Windows x86).
    InAlloca(crate::types::Type),
    /// Nest pointer for calling conventions with nested functions.
    Nest,
    /// Element type for the pointer parameter.
    ElementType(crate::types::Type),
    /// The pointer argument is allocation result (for memory analysis).
    AllocPtr,
    /// Classify which floating-point classes are valid.
    NoFPClass(u32),
    /// Range of possible values: `range(min, max)`.
    Range(u64, u64),
    /// The parameter has a constant initial execution TLS model.
    InitialExec,
    /// Swift async context parameter.
    SwiftAsync,
    /// Swift error parameter.
    SwiftError,
    /// Swift self parameter (the `self` argument).
    SwiftSelf,
    /// Swift error parameter variant 2.
    SwiftError2,
}

impl ParamAttrKind {
    /// Parse a parameter attribute from its LLVM assembly string representation.
    ///
    /// @llvm_behavior: Recognizes standard parameter attribute names
    /// including those with numeric arguments like "align 8" or
    /// "dereferenceable(16)". Returns `None` for unrecognized strings.
    pub fn from_string(s: &str) -> Option<Self> {
        // Handle attributes with arguments: "align 8", "dereferenceable(16)", etc.
        if let Some(rest) = s.strip_prefix("align ") {
            return rest.parse::<u32>().ok().map(ParamAttrKind::Align);
        }
        if let Some(rest) = s.strip_prefix("alignstack ") {
            return rest.parse::<u32>().ok().map(ParamAttrKind::Align);
        }
        if let Some(rest) = s.strip_prefix("dereferenceable(") {
            if let Some(val_str) = rest.strip_suffix(')') {
                return val_str
                    .parse::<u64>()
                    .ok()
                    .map(ParamAttrKind::Dereferenceable);
            }
        }
        if let Some(rest) = s.strip_prefix("dereferenceable_or_null(") {
            if let Some(val_str) = rest.strip_suffix(')') {
                return val_str
                    .parse::<u64>()
                    .ok()
                    .map(ParamAttrKind::DereferenceableOrNull);
            }
        }

        // Simple keyword attributes
        match s {
            "zeroext" => Some(ParamAttrKind::ZeroExt),
            "signext" => Some(ParamAttrKind::SignExt),
            "noalias" => Some(ParamAttrKind::NoAlias),
            "nocapture" => Some(ParamAttrKind::NoCapture),
            "nofree" => Some(ParamAttrKind::NoFree),
            "nonnull" => Some(ParamAttrKind::NonNull),
            "readonly" => Some(ParamAttrKind::ReadOnly),
            "writeonly" => Some(ParamAttrKind::WriteOnly),
            "inreg" => Some(ParamAttrKind::InReg),
            "returned" => Some(ParamAttrKind::Returned),
            "immarg" => Some(ParamAttrKind::ImmArg),
            "sext" => Some(ParamAttrKind::SExt),
            "noundef" => Some(ParamAttrKind::NoUndef),
            "nest" => Some(ParamAttrKind::Nest),
            "allocptr" => Some(ParamAttrKind::AllocPtr),
            "initialexec" => Some(ParamAttrKind::InitialExec),
            "swiftasync" => Some(ParamAttrKind::SwiftAsync),
            "swifterror" => Some(ParamAttrKind::SwiftError),
            "swiftself" => Some(ParamAttrKind::SwiftSelf),
            "swifterror2" => Some(ParamAttrKind::SwiftError2),
            s if s.starts_with("nofpclass(") => {
                let inner = &s["nofpclass(".len()..s.len() - 1];
                inner.parse::<u32>().ok().map(ParamAttrKind::NoFPClass)
            }
            s if s.starts_with("range(") => {
                let inner = &s["range(".len()..s.len() - 1];
                let parts: Vec<&str> = inner.split(',').collect();
                let min = parts[0].trim().parse::<u64>().ok()?;
                let max = if parts.len() > 1 {
                    parts[1].trim().parse::<u64>().ok()?
                } else {
                    min
                };
                Some(ParamAttrKind::Range(min, max))
            }
            _ => None,
        }
    }

    /// Convert this parameter attribute to its LLVM assembly string representation.
    ///
    /// @llvm_behavior: Produces the canonical attribute string, including
    /// numeric arguments where applicable.
    pub fn to_string(&self) -> String {
        match self {
            ParamAttrKind::ZeroExt => "zeroext".to_string(),
            ParamAttrKind::SignExt => "signext".to_string(),
            ParamAttrKind::NoAlias => "noalias".to_string(),
            ParamAttrKind::NoCapture => "nocapture".to_string(),
            ParamAttrKind::NoFree => "nofree".to_string(),
            ParamAttrKind::NonNull => "nonnull".to_string(),
            ParamAttrKind::ReadOnly => "readonly".to_string(),
            ParamAttrKind::WriteOnly => "writeonly".to_string(),
            ParamAttrKind::Dereferenceable(n) => format!("dereferenceable({})", n),
            ParamAttrKind::DereferenceableOrNull(n) => format!("dereferenceable_or_null({})", n),
            ParamAttrKind::Align(n) => format!("align {}", n),
            ParamAttrKind::ByVal(_) => "byval".to_string(),
            ParamAttrKind::StructRet(_) => "sret".to_string(),
            ParamAttrKind::InReg => "inreg".to_string(),
            ParamAttrKind::Returned => "returned".to_string(),
            ParamAttrKind::ImmArg => "immarg".to_string(),
            ParamAttrKind::SExt => "sext".to_string(),
            ParamAttrKind::NoUndef => "noundef".to_string(),
            ParamAttrKind::ByRef(_) => "byref".to_string(),
            ParamAttrKind::Preallocated(_) => "preallocated".to_string(),
            ParamAttrKind::InAlloca(_) => "inalloca".to_string(),
            ParamAttrKind::Nest => "nest".to_string(),
            ParamAttrKind::ElementType(_) => "elementtype".to_string(),
            ParamAttrKind::AllocPtr => "allocptr".to_string(),
            ParamAttrKind::NoFPClass(n) => format!("nofpclass({})", n),
            ParamAttrKind::Range(min, max) => format!("range({}, {})", min, max),
            ParamAttrKind::InitialExec => "initialexec".to_string(),
            ParamAttrKind::SwiftAsync => "swiftasync".to_string(),
            ParamAttrKind::SwiftError => "swifterror".to_string(),
            ParamAttrKind::SwiftSelf => "swiftself".to_string(),
            ParamAttrKind::SwiftError2 => "swifterror2".to_string(),
        }
    }

    /// Returns true if this is a type-carrying attribute (needs a Type parameter).
    pub fn is_type_attr(&self) -> bool {
        matches!(
            self,
            ParamAttrKind::ByVal(_)
                | ParamAttrKind::StructRet(_)
                | ParamAttrKind::ByRef(_)
                | ParamAttrKind::Preallocated(_)
                | ParamAttrKind::InAlloca(_)
                | ParamAttrKind::ElementType(_)
        )
    }

    /// Returns true if this is a numeric-carrying attribute.
    pub fn is_numeric_attr(&self) -> bool {
        matches!(
            self,
            ParamAttrKind::Dereferenceable(_)
                | ParamAttrKind::DereferenceableOrNull(_)
                | ParamAttrKind::Align(_)
                | ParamAttrKind::NoFPClass(_)
                | ParamAttrKind::Range(_, _)
        )
    }

    /// Returns the kind discriminant (ignoring numeric/type arguments).
    pub fn kind_discriminant(&self) -> &'static str {
        match self {
            ParamAttrKind::ZeroExt => "zeroext",
            ParamAttrKind::SignExt => "signext",
            ParamAttrKind::NoAlias => "noalias",
            ParamAttrKind::NoCapture => "nocapture",
            ParamAttrKind::NoFree => "nofree",
            ParamAttrKind::NonNull => "nonnull",
            ParamAttrKind::ReadOnly => "readonly",
            ParamAttrKind::WriteOnly => "writeonly",
            ParamAttrKind::Dereferenceable(_) => "dereferenceable",
            ParamAttrKind::DereferenceableOrNull(_) => "dereferenceable_or_null",
            ParamAttrKind::Align(_) => "align",
            ParamAttrKind::ByVal(_) => "byval",
            ParamAttrKind::StructRet(_) => "sret",
            ParamAttrKind::InReg => "inreg",
            ParamAttrKind::Returned => "returned",
            ParamAttrKind::ImmArg => "immarg",
            ParamAttrKind::SExt => "sext",
            ParamAttrKind::NoUndef => "noundef",
            ParamAttrKind::ByRef(_) => "byref",
            ParamAttrKind::Preallocated(_) => "preallocated",
            ParamAttrKind::InAlloca(_) => "inalloca",
            ParamAttrKind::Nest => "nest",
            ParamAttrKind::ElementType(_) => "elementtype",
            ParamAttrKind::AllocPtr => "allocptr",
            ParamAttrKind::NoFPClass(_) => "nofpclass",
            ParamAttrKind::Range(_, _) => "range",
            ParamAttrKind::InitialExec => "initialexec",
            ParamAttrKind::SwiftAsync => "swiftasync",
            ParamAttrKind::SwiftError => "swifterror",
            ParamAttrKind::SwiftSelf => "swiftself",
            ParamAttrKind::SwiftError2 => "swifterror2",
        }
    }
}

/// An attribute group — a collection of function attributes identified by
/// a numeric ID. Groups can be referenced from function definitions and
/// call instructions to avoid repeating attribute lists.
///
/// @llvm_behavior: Attribute groups in LLVM are identified by unsigned
/// integers and contain a list of attribute kinds. Groups are referenced
/// in IR as `#0`, `#1`, etc.
#[derive(Debug, Clone, PartialEq)]
pub struct AttrGroup {
    /// The numeric identifier for this attribute group.
    pub id: u32,
    /// The function attributes in this group.
    pub attrs: Vec<AttributeKind>,
}

impl AttrGroup {
    /// Create a new attribute group with the given ID.
    pub fn new(id: u32) -> Self {
        Self {
            id,
            attrs: Vec::new(),
        }
    }

    /// Add a function attribute to this group.
    pub fn add_attr(&mut self, attr: AttributeKind) {
        // Avoid duplicates
        if !self.attrs.contains(&attr) {
            self.attrs.push(attr);
        }
    }

    /// Remove a function attribute from this group.
    pub fn remove_attr(&mut self, attr: &AttributeKind) {
        self.attrs.retain(|a| a != attr);
    }

    /// Check if this group contains the given attribute.
    pub fn has_attr(&self, attr: &AttributeKind) -> bool {
        self.attrs.contains(attr)
    }

    /// Returns true if this group is empty.
    pub fn is_empty(&self) -> bool {
        self.attrs.is_empty()
    }

    /// Returns the number of attributes in this group.
    pub fn len(&self) -> usize {
        self.attrs.len()
    }
}

/// The complete attribute list for a function.
///
/// @llvm_behavior: A function has function-level attributes, return
/// attributes, and per-parameter attributes. This struct mirrors the
/// LLVM `AttributeList` class, holding all three categories plus
/// optional attribute groups.
#[derive(Debug, Clone, PartialEq)]
pub struct AttributeList {
    /// Function-level attributes.
    pub fn_attrs: Vec<AttributeKind>,
    /// Return value attributes.
    pub ret_attrs: Vec<ParamAttrKind>,
    /// Per-parameter attributes, indexed by parameter number.
    pub param_attrs: Vec<Vec<ParamAttrKind>>,
    /// Attribute groups referenced by ID.
    pub groups: HashMap<u32, AttrGroup>,
}

impl AttributeList {
    /// Create a new, empty attribute list.
    pub fn new() -> Self {
        Self {
            fn_attrs: Vec::new(),
            ret_attrs: Vec::new(),
            param_attrs: Vec::new(),
            groups: HashMap::new(),
        }
    }

    /// Add a function-level attribute.
    ///
    /// Duplicate attributes are silently ignored.
    pub fn add_fn_attr(&mut self, attr: AttributeKind) {
        if !self.fn_attrs.contains(&attr) {
            self.fn_attrs.push(attr);
        }
    }

    /// Remove a function-level attribute.
    pub fn remove_fn_attr(&mut self, attr: &AttributeKind) {
        self.fn_attrs.retain(|a| a != attr);
    }

    /// Add a return-value attribute.
    pub fn add_ret_attr(&mut self, attr: ParamAttrKind) {
        if !self.ret_attrs.contains(&attr) {
            self.ret_attrs.push(attr);
        }
    }

    /// Remove a return-value attribute.
    pub fn remove_ret_attr(&mut self, attr: &ParamAttrKind) {
        self.ret_attrs.retain(|a| a != attr);
    }

    /// Add a parameter attribute at the given parameter index.
    ///
    /// If the parameter vector needs to grow to accommodate the index,
    /// intermediate entries are filled with empty vectors.
    pub fn add_param_attr(&mut self, param_idx: u32, attr: ParamAttrKind) {
        let idx = param_idx as usize;
        while self.param_attrs.len() <= idx {
            self.param_attrs.push(Vec::new());
        }
        if !self.param_attrs[idx].contains(&attr) {
            self.param_attrs[idx].push(attr);
        }
    }

    /// Remove a parameter attribute at the given parameter index.
    pub fn remove_param_attr(&mut self, param_idx: u32, attr: &ParamAttrKind) {
        let idx = param_idx as usize;
        if idx < self.param_attrs.len() {
            self.param_attrs[idx].retain(|a| a != attr);
        }
    }

    /// Check if a function-level attribute is present.
    pub fn has_fn_attr(&self, kind: &AttributeKind) -> bool {
        self.fn_attrs.contains(kind)
    }

    /// Check if any function-level memory effect attribute is set.
    pub fn has_memory_attr(&self) -> bool {
        self.fn_attrs.iter().any(|a| a.is_memory_attr())
    }

    /// Check if a return-value attribute is present.
    pub fn has_ret_attr(&self, kind: &ParamAttrKind) -> bool {
        self.ret_attrs.contains(kind)
    }

    /// Get the attributes for a specific parameter index.
    ///
    /// Returns an empty slice if the index is out of bounds.
    pub fn get_param_attrs(&self, idx: u32) -> &[ParamAttrKind] {
        let idx = idx as usize;
        if idx < self.param_attrs.len() {
            &self.param_attrs[idx]
        } else {
            &[]
        }
    }

    /// Set the attributes for a specific parameter index (replaces existing).
    pub fn set_param_attrs(&mut self, param_idx: u32, attrs: Vec<ParamAttrKind>) {
        let idx = param_idx as usize;
        while self.param_attrs.len() <= idx {
            self.param_attrs.push(Vec::new());
        }
        self.param_attrs[idx] = attrs;
    }

    /// Returns the number of parameters that have attributes.
    pub fn num_param_slots(&self) -> usize {
        self.param_attrs.len()
    }

    /// Returns true if the attribute list is completely empty.
    pub fn is_empty(&self) -> bool {
        self.fn_attrs.is_empty()
            && self.ret_attrs.is_empty()
            && self.param_attrs.iter().all(|v| v.is_empty())
            && self.groups.is_empty()
    }

    // === Attribute groups ===

    /// Add an attribute group to the list.
    pub fn add_group(&mut self, group: AttrGroup) {
        self.groups.insert(group.id, group);
    }

    /// Get an attribute group by ID.
    pub fn get_group(&self, id: u32) -> Option<&AttrGroup> {
        self.groups.get(&id)
    }

    /// Remove an attribute group by ID.
    pub fn remove_group(&mut self, id: u32) {
        self.groups.remove(&id);
    }

    /// Create a group from a list of function attributes and return its ID.
    ///
    /// A new unique group ID is auto-generated.
    pub fn create_group(&mut self, attrs: Vec<AttributeKind>) -> u32 {
        let id = self.groups.len() as u32 + 1;
        let group = AttrGroup { id, attrs };
        self.groups.insert(id, group);
        id
    }

    // === Parsing ===

    /// Create an attribute list from LLVM assembly-style attribute strings.
    ///
    /// Handles both function attributes and parameter attributes.
    /// Example input: `["noinline", "nounwind", "readonly"]`
    pub fn from_fn_attr_strings(attr_strings: &[&str]) -> Self {
        let mut list = Self::new();
        for s in attr_strings {
            if let Some(attr) = AttributeKind::from_string(s) {
                list.add_fn_attr(attr);
            }
        }
        list
    }

    /// Build a complete attribute list from parsed attribute strings
    /// organized by category.
    pub fn from_parts(
        fn_attr_strs: &[&str],
        ret_attr_strs: &[&str],
        param_attr_strs: &[Vec<&str>],
    ) -> Self {
        let mut list = Self::new();
        for s in fn_attr_strs {
            if let Some(attr) = AttributeKind::from_string(s) {
                list.add_fn_attr(attr);
            }
        }
        for s in ret_attr_strs {
            if let Some(attr) = ParamAttrKind::from_string(s) {
                list.add_ret_attr(attr);
            }
        }
        for (i, attrs) in param_attr_strs.iter().enumerate() {
            for s in attrs {
                if let Some(attr) = ParamAttrKind::from_string(s) {
                    list.add_param_attr(i as u32, attr);
                }
            }
        }
        list
    }

    // === LLVM IR text emission ===

    /// Emit the function attribute list in LLVM IR assembly format.
    ///
    /// Produces output like: `noinline nounwind readnone`
    pub fn emit_fn_attr_string(&self) -> String {
        if self.fn_attrs.is_empty() {
            return String::new();
        }
        self.fn_attrs
            .iter()
            .map(|a| a.to_string())
            .collect::<Vec<_>>()
            .join(" ")
    }

    /// Emit return attributes as an LLVM IR string.
    pub fn emit_ret_attr_string(&self) -> String {
        if self.ret_attrs.is_empty() {
            return String::new();
        }
        self.ret_attrs
            .iter()
            .map(|a| a.to_string())
            .collect::<Vec<_>>()
            .join(" ")
    }

    /// Emit parameter N attributes as an LLVM IR string.
    pub fn emit_param_attr_string(&self, param_idx: u32) -> String {
        let attrs = self.get_param_attrs(param_idx);
        if attrs.is_empty() {
            return String::new();
        }
        attrs
            .iter()
            .map(|a| a.to_string())
            .collect::<Vec<_>>()
            .join(" ")
    }

    // === Combinators ===

    /// Merge another attribute list into this one.
    ///
    /// Function attributes are merged (union). Parameter attributes at
    /// the same index are merged. Groups with colliding IDs are
    /// overwritten by `other`.
    pub fn merge(&mut self, other: &AttributeList) {
        for attr in &other.fn_attrs {
            self.add_fn_attr(attr.clone());
        }
        for attr in &other.ret_attrs {
            self.add_ret_attr(attr.clone());
        }
        for (i, attrs) in other.param_attrs.iter().enumerate() {
            for attr in attrs {
                self.add_param_attr(i as u32, attr.clone());
            }
        }
        for (id, group) in &other.groups {
            self.groups.insert(*id, group.clone());
        }
    }
}

impl Default for AttributeList {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Attribute Index Constants
// ============================================================================

/// Well-known attribute index values.
/// In LLVM, `AttributeList` uses signed indices:
/// - `ReturnIndex` (0) for return value attributes
/// - `FunctionIndex` (~0, i.e., -1) for function-level attributes
/// - Parameter indices start at 1
pub struct AttrIndex;

impl AttrIndex {
    /// Index for the return value.
    pub const RETURN: u32 = 0;
    /// Index for the function itself.
    pub const FUNCTION: u32 = u32::MAX; // LLVM uses ~0U
    /// First parameter index.
    pub const FIRST_PARAM: u32 = 1;

    /// Check if an index refers to the return value.
    pub fn is_return(idx: u32) -> bool {
        idx == Self::RETURN
    }
    /// Check if an index refers to the function.
    pub fn is_function(idx: u32) -> bool {
        idx == Self::FUNCTION
    }
    /// Check if an index refers to a parameter.
    pub fn is_param(idx: u32) -> bool {
        idx != Self::RETURN && idx != Self::FUNCTION
    }
}

// ============================================================================
// AttributeSet — attributes at a single index
// ============================================================================

/// A set of attributes applied at a single position (function, return, or
/// parameter index). This is the basic building block; `AttributeList`
/// aggregates multiple `AttributeSet`s at different indices.
///
/// @llvm_behavior: Corresponds to `llvm::AttributeSet` in C++. Unlike
/// `AttributeList` which holds attributes for all positions, `AttributeSet`
/// holds attributes for exactly one index.
#[derive(Debug, Clone, PartialEq)]
pub struct AttributeSet {
    /// The index this set applies to (function, return, or param N).
    pub index: u32,
    /// Function-level attributes at this index.
    pub fn_attrs: Vec<AttributeKind>,
    /// Parameter/return attributes at this index.
    pub param_attrs: Vec<ParamAttrKind>,
}

impl AttributeSet {
    /// Create an empty attribute set for the given index.
    pub fn new(index: u32) -> Self {
        Self {
            index,
            fn_attrs: Vec::new(),
            param_attrs: Vec::new(),
        }
    }

    /// Create a set of function attributes.
    pub fn for_function(attrs: Vec<AttributeKind>) -> Self {
        Self {
            index: AttrIndex::FUNCTION,
            fn_attrs: attrs,
            param_attrs: Vec::new(),
        }
    }

    /// Create a set of return attributes.
    pub fn for_return(param_attrs: Vec<ParamAttrKind>) -> Self {
        Self {
            index: AttrIndex::RETURN,
            fn_attrs: Vec::new(),
            param_attrs,
        }
    }

    /// Create a set of parameter attributes.
    pub fn for_param(param_idx: u32, param_attrs: Vec<ParamAttrKind>) -> Self {
        Self {
            index: param_idx,
            fn_attrs: Vec::new(),
            param_attrs,
        }
    }

    /// Add a function attribute.
    pub fn add_fn_attr(&mut self, attr: AttributeKind) {
        if !self.fn_attrs.contains(&attr) {
            self.fn_attrs.push(attr);
        }
    }

    /// Add a parameter/return attribute.
    pub fn add_param_attr(&mut self, attr: ParamAttrKind) {
        if !self.param_attrs.contains(&attr) {
            self.param_attrs.push(attr);
        }
    }

    /// Check if this set contains a specific function attribute.
    pub fn has_fn_attr(&self, attr: &AttributeKind) -> bool {
        self.fn_attrs.contains(attr)
    }

    /// Check if this set contains a specific parameter attribute.
    pub fn has_param_attr(&self, attr: &ParamAttrKind) -> bool {
        self.param_attrs.contains(attr)
    }

    /// Check if a function attribute with a specific discriminant exists.
    pub fn has_fn_attr_kind(&self, name: &str) -> bool {
        self.fn_attrs
            .iter()
            .any(|a| a.to_string().starts_with(name))
    }

    /// Get the alignment from the align attribute, if present.
    pub fn get_alignment(&self) -> Option<u32> {
        self.param_attrs.iter().find_map(|a| {
            if let ParamAttrKind::Align(n) = a {
                Some(*n)
            } else {
                None
            }
        })
    }

    /// Get the dereferenceable byte count, if present.
    pub fn get_dereferenceable_bytes(&self) -> Option<u64> {
        self.param_attrs.iter().find_map(|a| {
            if let ParamAttrKind::Dereferenceable(n) = a {
                Some(*n)
            } else {
                None
            }
        })
    }

    /// Check if this set has the `nonnull` attribute.
    pub fn is_non_null(&self) -> bool {
        self.has_param_attr(&ParamAttrKind::NonNull)
    }

    /// Check if this set has the `nocapture` attribute.
    pub fn is_no_capture(&self) -> bool {
        self.has_param_attr(&ParamAttrKind::NoCapture)
    }

    /// Check if this set has the `noalias` attribute.
    pub fn is_no_alias(&self) -> bool {
        self.has_param_attr(&ParamAttrKind::NoAlias)
    }

    /// Check if this set marks a sign-extended integer.
    pub fn is_sign_ext(&self) -> bool {
        self.has_param_attr(&ParamAttrKind::SignExt) || self.has_param_attr(&ParamAttrKind::SExt)
    }

    /// Check if this set marks a zero-extended integer.
    pub fn is_zero_ext(&self) -> bool {
        self.has_param_attr(&ParamAttrKind::ZeroExt)
    }

    /// Returns the number of function attributes.
    pub fn num_fn_attrs(&self) -> usize {
        self.fn_attrs.len()
    }

    /// Returns the number of parameter/return attributes.
    pub fn num_param_attrs(&self) -> usize {
        self.param_attrs.len()
    }

    /// Returns true if this set is completely empty.
    pub fn is_empty(&self) -> bool {
        self.fn_attrs.is_empty() && self.param_attrs.is_empty()
    }

    /// Merge another AttributeSet into this one (union of attributes).
    pub fn merge(&mut self, other: &AttributeSet) {
        for attr in &other.fn_attrs {
            self.add_fn_attr(attr.clone());
        }
        for attr in &other.param_attrs {
            self.add_param_attr(attr.clone());
        }
    }

    /// Emit this attribute set as an LLVM IR attribute string.
    pub fn to_llvm_string(&self) -> String {
        let mut parts = Vec::new();
        for attr in &self.fn_attrs {
            parts.push(attr.to_string());
        }
        for attr in &self.param_attrs {
            parts.push(attr.to_string());
        }
        parts.join(" ")
    }
}

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

    // === AttributeKind tests ===

    #[test]
    fn test_attribute_kind_from_string_standard() {
        assert_eq!(
            AttributeKind::from_string("noinline"),
            Some(AttributeKind::NoInline)
        );
        assert_eq!(
            AttributeKind::from_string("alwaysinline"),
            Some(AttributeKind::AlwaysInline)
        );
        assert_eq!(
            AttributeKind::from_string("optnone"),
            Some(AttributeKind::OptimizeNone)
        );
        assert_eq!(
            AttributeKind::from_string("readnone"),
            Some(AttributeKind::ReadNone)
        );
        assert_eq!(
            AttributeKind::from_string("readonly"),
            Some(AttributeKind::ReadOnly)
        );
        assert_eq!(
            AttributeKind::from_string("nounwind"),
            Some(AttributeKind::NoUnwind)
        );
        assert_eq!(
            AttributeKind::from_string("noreturn"),
            Some(AttributeKind::NoReturn)
        );
        assert_eq!(
            AttributeKind::from_string("cold"),
            Some(AttributeKind::Cold)
        );
        assert_eq!(AttributeKind::from_string("hot"), Some(AttributeKind::Hot));
    }

    #[test]
    fn test_attribute_kind_from_string_memory_aliases() {
        assert_eq!(
            AttributeKind::from_string("memory(none)"),
            Some(AttributeKind::ReadNone)
        );
        assert_eq!(
            AttributeKind::from_string("memory(read)"),
            Some(AttributeKind::ReadOnly)
        );
        assert_eq!(
            AttributeKind::from_string("memory(write)"),
            Some(AttributeKind::WriteOnly)
        );
    }

    #[test]
    fn test_attribute_kind_from_string_sanitizers() {
        assert_eq!(
            AttributeKind::from_string("sanitize_address"),
            Some(AttributeKind::SanitizeAddress)
        );
        assert_eq!(
            AttributeKind::from_string("sanitize_thread"),
            Some(AttributeKind::SanitizeThread)
        );
        assert_eq!(
            AttributeKind::from_string("sanitize_memory"),
            Some(AttributeKind::SanitizeMemory)
        );
        assert_eq!(
            AttributeKind::from_string("nosanitize"),
            Some(AttributeKind::NoSanitize)
        );
    }

    #[test]
    fn test_attribute_kind_from_string_security() {
        assert_eq!(AttributeKind::from_string("ssp"), Some(AttributeKind::Ssp));
        assert_eq!(
            AttributeKind::from_string("sspreq"),
            Some(AttributeKind::SspReq)
        );
        assert_eq!(
            AttributeKind::from_string("sspstrong"),
            Some(AttributeKind::SspStrong)
        );
        assert_eq!(
            AttributeKind::from_string("shadowcallstack"),
            Some(AttributeKind::ShadowCallStack)
        );
        assert_eq!(
            AttributeKind::from_string("nocf_check"),
            Some(AttributeKind::NoCfCheck)
        );
    }

    #[test]
    fn test_attribute_kind_from_string_unknown() {
        assert_eq!(AttributeKind::from_string("nonexistent"), None);
        assert_eq!(AttributeKind::from_string(""), None);
    }

    #[test]
    fn test_attribute_kind_to_string_roundtrip() {
        let attrs = vec![
            AttributeKind::NoInline,
            AttributeKind::AlwaysInline,
            AttributeKind::ReadNone,
            AttributeKind::NoUnwind,
            AttributeKind::NoReturn,
            AttributeKind::Cold,
            AttributeKind::Hot,
        ];
        for attr in attrs {
            let s = attr.to_string();
            let parsed = AttributeKind::from_string(&s);
            assert!(
                parsed.is_some(),
                "Failed roundtrip for {:?} via string '{}'",
                attr,
                s
            );
        }
    }

    #[test]
    fn test_attribute_kind_is_memory_attr() {
        assert!(AttributeKind::ReadNone.is_memory_attr());
        assert!(AttributeKind::ReadOnly.is_memory_attr());
        assert!(AttributeKind::WriteOnly.is_memory_attr());
        assert!(AttributeKind::ArgMemOnly.is_memory_attr());
        assert!(AttributeKind::InaccessibleMemOnly.is_memory_attr());
        assert!(!AttributeKind::NoInline.is_memory_attr());
        assert!(!AttributeKind::Cold.is_memory_attr());
    }

    #[test]
    fn test_attribute_kind_is_sanitizer_attr() {
        assert!(AttributeKind::SanitizeAddress.is_sanitizer_attr());
        assert!(AttributeKind::SanitizeThread.is_sanitizer_attr());
        assert!(AttributeKind::NoSanitize.is_sanitizer_attr());
        assert!(!AttributeKind::NoInline.is_sanitizer_attr());
    }

    #[test]
    fn test_attribute_kind_is_security_attr() {
        assert!(AttributeKind::Ssp.is_security_attr());
        assert!(AttributeKind::SspReq.is_security_attr());
        assert!(AttributeKind::ShadowCallStack.is_security_attr());
        assert!(!AttributeKind::NoInline.is_security_attr());
    }

    // === ParamAttrKind tests ===

    #[test]
    fn test_param_attr_kind_from_string_simple() {
        assert_eq!(
            ParamAttrKind::from_string("zeroext"),
            Some(ParamAttrKind::ZeroExt)
        );
        assert_eq!(
            ParamAttrKind::from_string("signext"),
            Some(ParamAttrKind::SignExt)
        );
        assert_eq!(
            ParamAttrKind::from_string("noalias"),
            Some(ParamAttrKind::NoAlias)
        );
        assert_eq!(
            ParamAttrKind::from_string("nocapture"),
            Some(ParamAttrKind::NoCapture)
        );
        assert_eq!(
            ParamAttrKind::from_string("nonnull"),
            Some(ParamAttrKind::NonNull)
        );
        assert_eq!(
            ParamAttrKind::from_string("inreg"),
            Some(ParamAttrKind::InReg)
        );
        assert_eq!(
            ParamAttrKind::from_string("returned"),
            Some(ParamAttrKind::Returned)
        );
        assert_eq!(
            ParamAttrKind::from_string("immarg"),
            Some(ParamAttrKind::ImmArg)
        );
        assert_eq!(
            ParamAttrKind::from_string("noundef"),
            Some(ParamAttrKind::NoUndef)
        );
    }

    #[test]
    fn test_param_attr_kind_from_string_numeric() {
        assert_eq!(
            ParamAttrKind::from_string("align 8"),
            Some(ParamAttrKind::Align(8))
        );
        assert_eq!(
            ParamAttrKind::from_string("align 16"),
            Some(ParamAttrKind::Align(16))
        );
        assert_eq!(
            ParamAttrKind::from_string("dereferenceable(32)"),
            Some(ParamAttrKind::Dereferenceable(32))
        );
        assert_eq!(
            ParamAttrKind::from_string("dereferenceable_or_null(64)"),
            Some(ParamAttrKind::DereferenceableOrNull(64))
        );
    }

    #[test]
    fn test_param_attr_kind_from_string_invalid() {
        assert_eq!(ParamAttrKind::from_string("notanattr"), None);
        assert_eq!(ParamAttrKind::from_string("align"), None);
        assert_eq!(ParamAttrKind::from_string("align abc"), None);
    }

    #[test]
    fn test_param_attr_kind_to_string_roundtrip_simple() {
        let attrs = vec![
            ParamAttrKind::ZeroExt,
            ParamAttrKind::SignExt,
            ParamAttrKind::NoAlias,
            ParamAttrKind::NoCapture,
            ParamAttrKind::NonNull,
            ParamAttrKind::InReg,
            ParamAttrKind::Returned,
        ];
        for attr in attrs {
            let s = attr.to_string();
            let parsed = ParamAttrKind::from_string(&s);
            assert_eq!(
                Some(attr.clone()),
                parsed,
                "Failed roundtrip via string '{}'",
                s
            );
        }
    }

    #[test]
    fn test_param_attr_kind_to_string_numeric() {
        assert_eq!(ParamAttrKind::Align(8).to_string(), "align 8");
        assert_eq!(
            ParamAttrKind::Dereferenceable(16).to_string(),
            "dereferenceable(16)"
        );
        assert_eq!(
            ParamAttrKind::DereferenceableOrNull(32).to_string(),
            "dereferenceable_or_null(32)"
        );
    }

    #[test]
    fn test_param_attr_kind_is_type_attr() {
        assert!(!ParamAttrKind::ZeroExt.is_type_attr());
        assert!(!ParamAttrKind::Align(8).is_type_attr());
        // ByVal, StructRet, ByRef, Preallocated need types to construct,
        // so we skip creating them in a no-std-friendly test.
    }

    #[test]
    fn test_param_attr_kind_kind_discriminant() {
        assert_eq!(ParamAttrKind::ZeroExt.kind_discriminant(), "zeroext");
        assert_eq!(ParamAttrKind::Align(8).kind_discriminant(), "align");
        assert_eq!(
            ParamAttrKind::Dereferenceable(4).kind_discriminant(),
            "dereferenceable"
        );
    }

    // === AttrGroup tests ===

    #[test]
    fn test_attr_group_new() {
        let group = AttrGroup::new(42);
        assert_eq!(group.id, 42);
        assert!(group.is_empty());
        assert_eq!(group.len(), 0);
    }

    #[test]
    fn test_attr_group_add_and_check() {
        let mut group = AttrGroup::new(1);
        group.add_attr(AttributeKind::NoInline);
        group.add_attr(AttributeKind::NoUnwind);
        assert_eq!(group.len(), 2);
        assert!(group.has_attr(&AttributeKind::NoInline));
        assert!(group.has_attr(&AttributeKind::NoUnwind));
        assert!(!group.has_attr(&AttributeKind::Cold));
    }

    #[test]
    fn test_attr_group_remove() {
        let mut group = AttrGroup::new(1);
        group.add_attr(AttributeKind::NoInline);
        group.add_attr(AttributeKind::NoUnwind);
        group.remove_attr(&AttributeKind::NoInline);
        assert_eq!(group.len(), 1);
        assert!(!group.has_attr(&AttributeKind::NoInline));
        assert!(group.has_attr(&AttributeKind::NoUnwind));
    }

    #[test]
    fn test_attr_group_no_duplicates() {
        let mut group = AttrGroup::new(1);
        group.add_attr(AttributeKind::NoInline);
        group.add_attr(AttributeKind::NoInline);
        assert_eq!(group.len(), 1);
    }

    // === AttributeList tests ===

    #[test]
    fn test_attribute_list_new_empty() {
        let list = AttributeList::new();
        assert!(list.is_empty());
        assert_eq!(list.fn_attrs.len(), 0);
        assert_eq!(list.ret_attrs.len(), 0);
        assert_eq!(list.num_param_slots(), 0);
    }

    #[test]
    fn test_attribute_list_add_fn_attrs() {
        let mut list = AttributeList::new();
        list.add_fn_attr(AttributeKind::NoInline);
        list.add_fn_attr(AttributeKind::ReadNone);
        assert!(list.has_fn_attr(&AttributeKind::NoInline));
        assert!(list.has_fn_attr(&AttributeKind::ReadNone));
        assert!(!list.has_fn_attr(&AttributeKind::Cold));
    }

    #[test]
    fn test_attribute_list_add_param_attr() {
        let mut list = AttributeList::new();
        list.add_param_attr(0, ParamAttrKind::ZeroExt);
        list.add_param_attr(0, ParamAttrKind::NonNull);
        list.add_param_attr(1, ParamAttrKind::SignExt);

        let p0 = list.get_param_attrs(0);
        assert_eq!(p0.len(), 2);
        assert!(p0.contains(&ParamAttrKind::ZeroExt));
        assert!(p0.contains(&ParamAttrKind::NonNull));

        let p1 = list.get_param_attrs(1);
        assert_eq!(p1.len(), 1);
        assert!(p1.contains(&ParamAttrKind::SignExt));

        let p2 = list.get_param_attrs(2);
        assert!(p2.is_empty());
    }

    #[test]
    fn test_attribute_list_merge() {
        let mut list1 = AttributeList::new();
        list1.add_fn_attr(AttributeKind::NoInline);
        list1.add_param_attr(0, ParamAttrKind::ZeroExt);

        let mut list2 = AttributeList::new();
        list2.add_fn_attr(AttributeKind::NoUnwind);
        list2.add_param_attr(0, ParamAttrKind::NonNull);
        list2.add_param_attr(1, ParamAttrKind::SignExt);

        list1.merge(&list2);

        assert!(list1.has_fn_attr(&AttributeKind::NoInline));
        assert!(list1.has_fn_attr(&AttributeKind::NoUnwind));

        let p0 = list1.get_param_attrs(0);
        assert_eq!(p0.len(), 2);
        assert!(p0.contains(&ParamAttrKind::ZeroExt));
        assert!(p0.contains(&ParamAttrKind::NonNull));

        let p1 = list1.get_param_attrs(1);
        assert_eq!(p1.len(), 1);
        assert!(p1.contains(&ParamAttrKind::SignExt));
    }

    #[test]
    fn test_attribute_list_from_parts() {
        let list = AttributeList::from_parts(
            &["noinline", "nounwind"],
            &["zeroext"],
            &[vec!["nocapture", "nonnull"], vec!["signext"]],
        );

        assert!(list.has_fn_attr(&AttributeKind::NoInline));
        assert!(list.has_fn_attr(&AttributeKind::NoUnwind));
        assert!(list.has_ret_attr(&ParamAttrKind::ZeroExt));

        let p0 = list.get_param_attrs(0);
        assert!(p0.contains(&ParamAttrKind::NoCapture));
        assert!(p0.contains(&ParamAttrKind::NonNull));

        let p1 = list.get_param_attrs(1);
        assert!(p1.contains(&ParamAttrKind::SignExt));
    }

    #[test]
    fn test_attribute_list_emit_fn_attr_string() {
        let mut list = AttributeList::new();
        list.add_fn_attr(AttributeKind::NoInline);
        list.add_fn_attr(AttributeKind::ReadNone);
        let s = list.emit_fn_attr_string();
        assert!(s.contains("noinline"));
        assert!(s.contains("readnone"));
    }

    #[test]
    fn test_attribute_list_groups() {
        let mut list = AttributeList::new();
        let id = list.create_group(vec![AttributeKind::NoInline, AttributeKind::ReadNone]);

        let group = list.get_group(id);
        assert!(group.is_some());
        let group = group.unwrap();
        assert_eq!(group.id, id);
        assert!(group.has_attr(&AttributeKind::NoInline));
        assert!(group.has_attr(&AttributeKind::ReadNone));

        list.remove_group(id);
        assert!(list.get_group(id).is_none());
    }

    #[test]
    fn test_attribute_list_string_attribute() {
        let attr =
            AttributeKind::StringAttribute("my_custom_attr".to_string(), "some_value".to_string());
        let s = attr.to_string();
        assert!(s.contains("my_custom_attr"));
        assert!(s.contains("some_value"));
    }

    #[test]
    fn test_attribute_kind_minsize_and_optforsize() {
        let mut list = AttributeList::new();
        list.add_fn_attr(AttributeKind::Minsize);
        list.add_fn_attr(AttributeKind::OptimizeForSize);
        assert!(list.has_fn_attr(&AttributeKind::Minsize));
        assert!(list.has_fn_attr(&AttributeKind::OptimizeForSize));
    }

    #[test]
    fn test_param_attr_no_duplicates() {
        let mut list = AttributeList::new();
        list.add_param_attr(0, ParamAttrKind::NoAlias);
        list.add_param_attr(0, ParamAttrKind::NoAlias);
        assert_eq!(list.get_param_attrs(0).len(), 1);
    }

    #[test]
    fn test_attribute_list_default() {
        let list = AttributeList::default();
        assert!(list.is_empty());
    }

    #[test]
    fn test_attribute_kind_no_sync_no_free() {
        assert_eq!(
            AttributeKind::from_string("nosync"),
            Some(AttributeKind::NoSync)
        );
        assert_eq!(
            AttributeKind::from_string("nofree"),
            Some(AttributeKind::NoFree)
        );
        assert_eq!(
            AttributeKind::from_string("norecurse"),
            Some(AttributeKind::NoRecurse)
        );
        assert_eq!(
            AttributeKind::from_string("noduplicate"),
            Some(AttributeKind::NoDuplicate)
        );
    }

    #[test]
    fn test_attribute_kind_willreturn() {
        assert_eq!(
            AttributeKind::from_string("willreturn"),
            Some(AttributeKind::WillReturn)
        );
        assert_eq!(AttributeKind::WillReturn.to_string(), "willreturn");
    }

    #[test]
    fn test_attribute_kind_null_pointer_is_valid() {
        let attr = AttributeKind::NullPointerIsValid;
        assert_eq!(attr.to_string(), "null_pointer_is_valid");
        assert_eq!(
            AttributeKind::from_string("null_pointer_is_valid"),
            Some(AttributeKind::NullPointerIsValid)
        );
    }
}