llvm-ir 0.11.3

LLVM IR in natural Rust data structures
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
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
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
use either::Either;
use itertools::Itertools;
use llvm_ir::function::{FunctionAttribute, ParameterAttribute};
use llvm_ir::instruction;
use llvm_ir::module::{Alignment, Endianness, Mangling, PointerLayout};
use llvm_ir::terminator;
use llvm_ir::types::{FPType, NamedStructDef, Typed};
use llvm_ir::HasDebugLoc;
use llvm_ir::{
    Constant, ConstantRef, Instruction, IntPredicate, Module, Name, Operand, Terminator, Type,
};
#[cfg(feature = "llvm-16-or-greater")]
use llvm_ir::function::MemoryEffect;
use std::convert::TryInto;
use std::path::{Path, PathBuf};

fn init_logging() {
    // capture log messages with test harness
    let _ = env_logger::builder().is_test(true).try_init();
}

const BC_DIR: &str = "tests/basic_bc/";

// Test against bitcode compiled with the same version of LLVM
fn llvm_bc_dir() -> PathBuf {
    if cfg!(feature = "llvm-9") {
        Path::new(BC_DIR).join("llvm9")
    } else if cfg!(feature = "llvm-10") {
        Path::new(BC_DIR).join("llvm10")
    } else if cfg!(feature = "llvm-11") {
        Path::new(BC_DIR).join("llvm11")
    } else if cfg!(feature = "llvm-12") {
        Path::new(BC_DIR).join("llvm12")
    } else if cfg!(feature = "llvm-13") {
        Path::new(BC_DIR).join("llvm13")
    } else if cfg!(feature = "llvm-14") {
        Path::new(BC_DIR).join("llvm14")
    } else if cfg!(feature = "llvm-15") {
        Path::new(BC_DIR).join("llvm15")
    } else if cfg!(feature = "llvm-16") {
        Path::new(BC_DIR).join("llvm16")
    } else if cfg!(feature = "llvm-17") {
        Path::new(BC_DIR).join("llvm17")
    } else if cfg!(feature = "llvm-18") {
        Path::new(BC_DIR).join("llvm18")
    } else if cfg!(feature = "llvm-19") {
        Path::new(BC_DIR).join("llvm19")
    } else {
        unimplemented!("new llvm version?")
    }
}

// Test against bitcode compiled with the same version of LLVM
fn cxx_llvm_bc_dir() -> PathBuf {
    if cfg!(feature = "llvm-9") {
        Path::new(BC_DIR).join("cxx-llvm9")
    } else if cfg!(feature = "llvm-10") {
        Path::new(BC_DIR).join("cxx-llvm10")
    } else if cfg!(feature = "llvm-11") {
        Path::new(BC_DIR).join("cxx-llvm11")
    } else if cfg!(feature = "llvm-12") {
        Path::new(BC_DIR).join("cxx-llvm12")
    } else if cfg!(feature = "llvm-13") {
        Path::new(BC_DIR).join("cxx-llvm13")
    } else if cfg!(feature = "llvm-14") {
        Path::new(BC_DIR).join("cxx-llvm14")
    } else if cfg!(feature = "llvm-15") {
        Path::new(BC_DIR).join("cxx-llvm15")
    } else if cfg!(feature = "llvm-16") {
        Path::new(BC_DIR).join("cxx-llvm16")
    } else if cfg!(feature = "llvm-17") {
        Path::new(BC_DIR).join("cxx-llvm17")
    } else if cfg!(feature = "llvm-18") {
        Path::new(BC_DIR).join("cxx-llvm18")
    } else if cfg!(feature = "llvm-19") {
        Path::new(BC_DIR).join("cxx-llvm19")
    } else {
        unimplemented!("new llvm version?")
    }
}

fn rust_bc_dir() -> PathBuf {
    Path::new(BC_DIR).join("rust")
}

#[test]
fn hellobc() {
    init_logging();
    let path = llvm_bc_dir().join("hello.bc");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");
    assert_eq!(&module.name, &path.to_str().unwrap());
    assert_eq!(module.source_file_name, "hello.c");
    #[cfg(feature = "llvm-10-or-lower")]
    assert_eq!(
        module.target_triple,
        Some("x86_64-apple-macosx10.16.0".into())
    );
    #[cfg(any(feature = "llvm-11", feature = "llvm-12", feature = "llvm-13"))]
    assert_eq!(
        module.target_triple,
        Some("x86_64-apple-macosx11.0.0".into())
    );
    #[cfg(feature = "llvm-14-or-greater")]
    assert_eq!(
        module.target_triple,
        Some("x86_64-apple-macosx12.0.0".into())
    );
    assert_eq!(module.functions.len(), 1);
    let func = &module.functions[0];
    assert_eq!(func.name, "main");
    assert_eq!(func.parameters.len(), 0);
    assert_eq!(func.is_var_arg, false);
    assert_eq!(func.return_type, module.types.int(32));
    assert_eq!(func.basic_blocks.len(), 1);
    let bb = &func.basic_blocks[0];
    assert_eq!(bb.name, Name::Number(0));
    assert_eq!(bb.instrs.len(), 0);
    let ret: &terminator::Ret = &bb
        .term
        .clone()
        .try_into()
        .unwrap_or_else(|_| panic!("Terminator should be a Ret but is {:?}", &bb.term));
    assert_eq!(
        ret.return_operand,
        Some(Operand::ConstantOperand(ConstantRef::new(Constant::Int {
            bits: 32,
            value: 0
        })))
    );
    assert_eq!(&ret.to_string(), "ret i32 0");

    // this file was compiled without debuginfo, so nothing should have a debugloc
    assert_eq!(func.debugloc, None);
    assert_eq!(ret.debugloc, None);
}

// this test relates to the version of the file compiled with debuginfo
#[test]
fn hellobcg() {
    init_logging();
    let path = llvm_bc_dir().join("hello.bc-g");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");
    assert_eq!(&module.name, &path.to_str().unwrap());
    assert_eq!(module.source_file_name, "hello.c");
    let debug_filename = "hello.c";
    let debug_directory_suffix = "/tests/basic_bc";

    let func = &module.functions[0];
    assert_eq!(func.name, "main");
    let debugloc = func
        .get_debug_loc()
        .as_ref()
        .expect("Expected main() to have a debugloc");
    assert_eq!(debugloc.line, 3);
    assert_eq!(debugloc.col, None);
    assert_eq!(debugloc.filename, debug_filename);
    assert!(debugloc.directory.as_ref().expect("directory should exist").ends_with(debug_directory_suffix));

    let bb = &func.basic_blocks[0];
    let ret: &terminator::Ret = &bb
        .term
        .clone()
        .try_into()
        .unwrap_or_else(|_| panic!("Terminator should be a Ret but is {:?}", &bb.term));
    let debugloc = ret
        .get_debug_loc()
        .as_ref()
        .expect("expected the Ret to have a debugloc");
    assert_eq!(debugloc.line, 4);
    assert_eq!(debugloc.col, Some(3));
    assert_eq!(debugloc.filename, debug_filename);
    assert!(debugloc.directory.as_ref().expect("directory should exist").ends_with(debug_directory_suffix));
    assert_eq!(&ret.to_string(), "ret i32 0 (with debugloc)");
}

#[test]
#[allow(clippy::cognitive_complexity)]
fn loopbc() {
    init_logging();
    let path = llvm_bc_dir().join("loop.bc");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");

    // get function and check info on it
    assert_eq!(module.functions.len(), 1);
    let func = &module.functions[0];
    assert_eq!(func.name, "loop");
    assert_eq!(func.parameters.len(), 2);
    assert_eq!(func.is_var_arg, false);
    assert_eq!(func.return_type, module.types.void());
    assert_eq!(
        module.type_of(func),
        module.types.func_type(
            module.types.void(),
            vec![module.types.i32(), module.types.i32()],
            false,
        )
    );
    assert_eq!(module.get_func_by_name("loop"), Some(func));

    // get parameters and check info on them
    let param0 = &func.parameters[0];
    let param1 = &func.parameters[1];
    assert_eq!(param0.name, Name::Number(0));
    assert_eq!(param1.name, Name::Number(1));
    assert_eq!(param0.ty, module.types.i32());
    assert_eq!(param1.ty, module.types.i32());
    assert_eq!(module.type_of(param0), module.types.i32());
    assert_eq!(module.type_of(param1), module.types.i32());

    // get basic blocks and check their names
    // different LLVM versions end up with different numbers of basic blocks for this function
    #[cfg(feature = "llvm-9-or-lower")]
    let bbs = {
        assert_eq!(func.basic_blocks.len(), 6);
        let bb2 = &func.basic_blocks[0];
        let bb7 = &func.basic_blocks[1];
        let bb10 = &func.basic_blocks[2];
        let bb14 = &func.basic_blocks[3];
        let bb19 = &func.basic_blocks[4];
        let bb22 = &func.basic_blocks[5];
        assert_eq!(bb2.name, Name::Number(2));
        assert_eq!(bb7.name, Name::Number(7));
        assert_eq!(bb10.name, Name::Number(10));
        assert_eq!(bb14.name, Name::Number(14));
        assert_eq!(bb19.name, Name::Number(19));
        assert_eq!(bb22.name, Name::Number(22));
        assert_eq!(func.get_bb_by_name(&Name::Number(2)), Some(bb2));
        assert_eq!(func.get_bb_by_name(&Name::Number(19)), Some(bb19));
        vec![bb2, bb7, bb10, bb14, bb19, bb22]
    };
    #[cfg(feature = "llvm-10")]
    let bbs = {
        assert_eq!(func.basic_blocks.len(), 4);
        let bb2 = &func.basic_blocks[0];
        let bb7 = &func.basic_blocks[1];
        let bb12 = &func.basic_blocks[2];
        let bb21 = &func.basic_blocks[3];
        assert_eq!(bb2.name, Name::Number(2));
        assert_eq!(bb7.name, Name::Number(7));
        assert_eq!(bb12.name, Name::Number(12));
        assert_eq!(bb21.name, Name::Number(21));
        assert_eq!(func.get_bb_by_name(&Name::Number(2)), Some(bb2));
        assert_eq!(func.get_bb_by_name(&Name::Number(12)), Some(bb12));
        vec![bb2, bb7, bb12, bb21]
    };
    #[cfg(feature = "llvm-11")]
    let bbs = {
        assert_eq!(func.basic_blocks.len(), 4);
        let bb2 = &func.basic_blocks[0];
        let bb7 = &func.basic_blocks[1];
        let bb14 = &func.basic_blocks[2];
        let bb24 = &func.basic_blocks[3];
        assert_eq!(bb2.name, Name::Number(2));
        assert_eq!(bb7.name, Name::Number(7));
        assert_eq!(bb14.name, Name::Number(14));
        assert_eq!(bb24.name, Name::Number(24));
        assert_eq!(func.get_bb_by_name(&Name::Number(2)), Some(bb2));
        assert_eq!(func.get_bb_by_name(&Name::Number(14)), Some(bb14));
        vec![bb2, bb7, bb14, bb24]
    };
    #[cfg(feature = "llvm-12")]
    let bbs = {
        assert_eq!(func.basic_blocks.len(), 8); // LLVM 12+ seems to do some unrolling in this example that previous LLVMs didn't
        let bb2 = &func.basic_blocks[0];
        let bb7 = &func.basic_blocks[1];
        let bb12 = &func.basic_blocks[2];
        let bb17 = &func.basic_blocks[3];
        let bb19 = &func.basic_blocks[4];
        let bb47 = &func.basic_blocks[7];
        // actually have 8 BBs, but we only use the first five and the last one
        assert_eq!(bb2.name, Name::Number(2));
        assert_eq!(bb7.name, Name::Number(7));
        assert_eq!(bb12.name, Name::Number(12));
        assert_eq!(bb17.name, Name::Number(17));
        assert_eq!(bb19.name, Name::Number(19));
        assert_eq!(bb47.name, Name::Number(47));
        vec![bb2, bb7, bb12, bb17, bb19, bb47]
    };
    #[cfg(feature = "llvm-13")]
    let bbs = {
        assert_eq!(func.basic_blocks.len(), 9);
        let bb2 = &func.basic_blocks[0];
        let bb6 = &func.basic_blocks[1];
        let bb12 = &func.basic_blocks[3];
        let bb17 = &func.basic_blocks[4];
        let bb19 = &func.basic_blocks[5];
        let bb47 = &func.basic_blocks[8];
        // actually have 9 BBs, but we only use these selected 6
        assert_eq!(bb2.name, Name::Number(2));
        assert_eq!(bb6.name, Name::Number(6));
        assert_eq!(bb12.name, Name::Number(12));
        assert_eq!(bb17.name, Name::Number(17));
        assert_eq!(bb19.name, Name::Number(19));
        assert_eq!(bb47.name, Name::Number(47));
        vec![bb2, bb6, bb12, bb17, bb19, bb47]
    };
    #[cfg(feature = "llvm-14")]
    let bbs = {
        assert_eq!(func.basic_blocks.len(), 8);
        let bb2 = &func.basic_blocks[0];
        let bb7 = &func.basic_blocks[1];
        let bb11 = &func.basic_blocks[2];
        let bb16 = &func.basic_blocks[3];
        let bb18 = &func.basic_blocks[4];
        let bb46 = &func.basic_blocks[7];
        // actually have 8 BBs, but we only use the first five and the last one
        assert_eq!(bb2.name, Name::Number(2));
        assert_eq!(bb7.name, Name::Number(7));
        assert_eq!(bb11.name, Name::Number(11));
        assert_eq!(bb16.name, Name::Number(16));
        assert_eq!(bb18.name, Name::Number(18));
        assert_eq!(bb46.name, Name::Number(46));
        vec![bb2, bb7, bb11, bb16, bb18, bb46]
    };
    #[cfg(all(feature = "llvm-15-or-greater", feature = "llvm-17-or-lower"))]
    let bbs = {
        assert_eq!(func.basic_blocks.len(), 8);
        let bb2 = &func.basic_blocks[0];
        let bb7 = &func.basic_blocks[1];
        let bb11 = &func.basic_blocks[2];
        let bb16 = &func.basic_blocks[3];
        let bb18 = &func.basic_blocks[4];
        let bb46 = &func.basic_blocks[7];
        // actually have 8 BBs, but we only use the first five and the last one
        assert_eq!(bb2.name, Name::Number(2));
        assert_eq!(bb7.name, Name::Number(6));
        assert_eq!(bb11.name, Name::Number(9));
        assert_eq!(bb16.name, Name::Number(14));
        assert_eq!(bb18.name, Name::Number(16));
        assert_eq!(bb46.name, Name::Number(44));
        vec![bb2, bb7, bb11, bb16, bb18, bb46]
    };
    #[cfg(feature = "llvm-18-or-greater")]
    let bbs = {
        assert_eq!(func.basic_blocks.len(), 8);
        let bb2 = &func.basic_blocks[0];
        let bb7 = &func.basic_blocks[1];
        let bb11 = &func.basic_blocks[2];
        let bb16 = &func.basic_blocks[3];
        let bb18 = &func.basic_blocks[4];
        let bb46 = &func.basic_blocks[7];
        // Some extra optimization removes a few instructions in Clang 18,
        // c.f. Clang 17
        assert_eq!(bb2.name, Name::Number(2));
        assert_eq!(bb7.name, Name::Number(6));
        assert_eq!(bb11.name, Name::Number(9));
        assert_eq!(bb16.name, Name::Number(14));
        assert_eq!(bb18.name, Name::Number(16));
        assert_eq!(bb46.name, Name::Number(41));
        vec![bb2, bb7, bb11, bb16, bb18, bb46]
    };

    // check details about the instructions in basic block %2
    let alloca: &instruction::Alloca = &bbs[0].instrs[0]
        .clone()
        .try_into()
        .expect("Should be an alloca");
    assert_eq!(alloca.dest, Name::Number(3));
    let allocated_type = module.types.array_of(module.types.i32(), 10);
    assert_eq!(alloca.allocated_type, allocated_type);
    assert_eq!(
        alloca.num_elements,
        Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 32, value: 1 })) // One element, which is an array of 10 elements. Not 10 elements, each of which are i32.
    );
    assert_eq!(alloca.alignment, 16);
    #[cfg(feature = "llvm-14-or-lower")]
    assert_eq!(
        module.type_of(alloca),
        module.types.pointer_to(allocated_type.clone()),
    );
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(module.type_of(alloca), module.types.pointer());
    assert_eq!(module.type_of(&alloca.num_elements), module.types.i32());
    assert_eq!(&alloca.to_string(), "%3 = alloca [10 x i32], align 16");
    #[cfg(feature = "llvm-14-or-lower")] // LLVM 15+ does not require bitcasts in this function
    {
        let bitcast: &instruction::BitCast = &bbs[0].instrs[1]
            .clone()
            .try_into()
            .expect("Should be a bitcast");
        assert_eq!(bitcast.dest, Name::Number(4));
        assert_eq!(bitcast.to_type, module.types.pointer_to(module.types.i8()));
        assert_eq!(
            bitcast.operand,
            Operand::LocalOperand {
                name: Name::Number(3),
                ty: module.types.pointer_to(allocated_type.clone())
            }
        );
        assert_eq!(
            module.type_of(bitcast),
            module.types.pointer_to(module.types.i8())
        );
        assert_eq!(
            module.type_of(&bitcast.operand),
            module.types.pointer_to(allocated_type.clone())
        );
        assert_eq!(&bitcast.to_string(), "%4 = bitcast [10 x i32]* %3 to i8*");
    }
    #[cfg(feature = "llvm-14-or-lower")]
    let lifetimestart: &instruction::Call = &bbs[0].instrs[2]
        .clone()
        .try_into()
        .expect("Should be a call");
    #[cfg(feature = "llvm-15-or-greater")]
    let lifetimestart: &instruction::Call = &bbs[0].instrs[1]
        .clone()
        .try_into()
        .expect("Should be a call");
    if let Either::Right(Operand::ConstantOperand(cref)) = &lifetimestart.function {
        if let Constant::GlobalReference { ref name, ref ty } = cref.as_ref() {
            assert!(matches!(
                module.type_of(&lifetimestart.function).as_ref(),
                Type::PointerType { .. }
            )); // lifetimestart.function should be a constant function pointer
            #[cfg(feature = "llvm-14-or-lower")]
            assert_eq!(*name, Name::from("llvm.lifetime.start.p0i8"));
            #[cfg(feature = "llvm-15-or-greater")]
            assert_eq!(*name, Name::from("llvm.lifetime.start.p0"));
            if let Type::FuncType {
                result_type,
                param_types,
                is_var_arg,
            } = ty.as_ref()
            {
                assert_eq!(result_type, &module.types.void());
                assert_eq!(
                    param_types,
                    &vec![
                        module.types.i64(),
                        #[cfg(feature = "llvm-14-or-lower")]
                        module.types.pointer_to(module.types.i8()),
                        #[cfg(feature = "llvm-15-or-greater")]
                        module.types.pointer(),
                    ]
                );
                assert_eq!(*is_var_arg, false);
            } else {
                panic!("lifetimestart.function has unexpected type {:?}", ty);
            }
        } else {
            panic!(
                "lifetimestart.function not a GlobalReference as expected; it is actually another kind of Constant: {:?}",
                cref
            );
        }
    } else {
        panic!(
            "lifetimestart.function not a GlobalReference as expected; it is actually {:?}",
            &lifetimestart.function
        );
    }
    let arg0 = &lifetimestart
        .arguments
        .get(0)
        .expect("Expected an argument 0");
    let arg1 = &lifetimestart
        .arguments
        .get(1)
        .expect("Expected an argument 1");
    assert_eq!(
        arg0.0,
        Operand::ConstantOperand(ConstantRef::new(Constant::Int {
            bits: 64,
            value: 40
        }))
    );
    #[cfg(feature = "llvm-14-or-lower")]
    let arg1_expected_name = Name::Number(4);
    #[cfg(feature = "llvm-15-or-greater")]
    let arg1_expected_name = Name::Number(3);
    #[cfg(feature = "llvm-14-or-lower")]
    let arg1_expected_ty = module.types.pointer_to(module.types.i8());
    #[cfg(feature = "llvm-15-or-greater")]
    let arg1_expected_ty = module.types.pointer();
    assert_eq!(
        arg1.0,
        Operand::LocalOperand {
            name: arg1_expected_name,
            ty: arg1_expected_ty,
        }
    );
    assert_eq!(arg0.1, vec![]); // should have no parameter attributes
    assert_eq!(arg1.1.len(), 1); // should have one parameter attribute
    assert_eq!(lifetimestart.dest, None);
    #[cfg(feature = "llvm-14-or-lower")]
    let expected_fmt = "call @llvm.lifetime.start.p0i8(i64 40, i8* %4)";
    #[cfg(feature = "llvm-15-or-greater")]
    let expected_fmt = "call @llvm.lifetime.start.p0(i64 40, ptr %3)";
    assert_eq!(&lifetimestart.to_string(), expected_fmt);
    #[cfg(feature = "llvm-14-or-lower")]
    let memset: &instruction::Call = &bbs[0].instrs[3]
        .clone()
        .try_into()
        .expect("Should be a call");
    #[cfg(feature = "llvm-15-or-greater")]
    let memset: &instruction::Call = &bbs[0].instrs[2]
        .clone()
        .try_into()
        .expect("Should be a call");
    if let Either::Right(Operand::ConstantOperand(cref)) = &memset.function {
        if let Constant::GlobalReference { ref name, ref ty } = cref.as_ref() {
            #[cfg(feature = "llvm-14-or-lower")]
            assert_eq!(*name, Name::from("llvm.memset.p0i8.i64"));
            #[cfg(feature = "llvm-15-or-greater")]
            assert_eq!(*name, Name::from("llvm.memset.p0.i64"));
            if let Type::FuncType {
                result_type,
                param_types,
                is_var_arg,
            } = ty.as_ref()
            {
                assert_eq!(result_type, &module.types.void());
                assert_eq!(
                    param_types,
                    &vec![
                        #[cfg(feature = "llvm-14-or-lower")]
                        module.types.pointer_to(module.types.i8()),
                        #[cfg(feature = "llvm-15-or-greater")]
                        module.types.pointer(),
                        module.types.i8(),
                        module.types.i64(),
                        module.types.bool()
                    ]
                );
                assert_eq!(*is_var_arg, false);
            } else {
                panic!("memset.function has unexpected type {:?}", ty);
            }
        } else {
            panic!(
                "memset.function not a GlobalReference as expected; it is actually another kind of Constant: {:?}",
                cref
            );
        }
    } else {
        panic!(
            "memset.function not a GlobalReference as expected; it is actually {:?}",
            memset.function
        );
    }
    assert_eq!(memset.arguments.len(), 4);
    #[cfg(feature = "llvm-14-or-lower")]
    let memset_arg0_expected_name = Name::Number(4);
    #[cfg(feature = "llvm-15-or-greater")]
    let memset_arg0_expected_name = Name::Number(3);
    #[cfg(feature = "llvm-14-or-lower")]
    let memset_arg0_expected_ty = module.types.pointer_to(module.types.i8());
    #[cfg(feature = "llvm-15-or-greater")]
    let memset_arg0_expected_ty = module.types.pointer();
    assert_eq!(
        memset.arguments[0].0,
        Operand::LocalOperand {
            name: memset_arg0_expected_name,
            ty: memset_arg0_expected_ty,
        }
    );
    assert_eq!(
        memset.arguments[1].0,
        Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 8, value: 0 }))
    );
    assert_eq!(
        memset.arguments[2].0,
        Operand::ConstantOperand(ConstantRef::new(Constant::Int {
            bits: 64,
            value: 40
        }))
    );
    assert_eq!(
        memset.arguments[3].0,
        Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 1, value: 1 }))
    );
    assert_eq!(memset.arguments[0].1.len(), 2); // should have two parameter attributes
    #[cfg(feature = "llvm-14-or-lower")]
    let expected_fmt = "call @llvm.memset.p0i8.i64(i8* %4, i8 0, i64 40, i1 true)";
    #[cfg(feature = "llvm-15-or-greater")]
    let expected_fmt = "call @llvm.memset.p0.i64(ptr %3, i8 0, i64 40, i1 true)";
    assert_eq!(&memset.to_string(), expected_fmt);
    #[cfg(feature = "llvm-12-or-lower")]
    {
        let add: &instruction::Add = &bbs[0].instrs[4]
            .clone()
            .try_into()
            .expect("Should be an add");
        assert_eq!(
            add.operand0,
            Operand::LocalOperand {
                name: Name::Number(1),
                ty: module.types.i32()
            }
        );
        assert_eq!(
            add.operand1,
            Operand::ConstantOperand(ConstantRef::new(Constant::Int {
                bits: 32,
                value: 0x0000_0000_FFFF_FFFF
            }))
        );
        assert_eq!(add.dest, Name::Number(5));
        assert_eq!(module.type_of(add), module.types.i32());
        assert_eq!(&add.to_string(), "%5 = add i32 %1, i32 -1");
    }
    #[cfg(feature = "llvm-13")]
    {
        let add: &instruction::Add = &bbs[1].instrs[0]
            .clone()
            .try_into()
            .expect("Should be an add");
        assert_eq!(
            add.operand0,
            Operand::LocalOperand {
                name: Name::Number(0),
                ty: module.types.i32()
            }
        );
        assert_eq!(
            add.operand1,
            Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 32, value: 3 }))
        );
        assert_eq!(add.dest, Name::Number(7));
        assert_eq!(module.type_of(add), module.types.i32());
        assert_eq!(&add.to_string(), "%7 = add i32 %0, i32 3");
    }
    #[cfg(feature = "llvm-14-or-greater")]
    {
        let add: &instruction::Add = &bbs[1].instrs[0]
            .clone()
            .try_into()
            .expect("Should be an add");
        assert_eq!(
            add.operand0,
            Operand::LocalOperand {
                name: Name::Number(0),
                ty: module.types.i32()
            }
        );
        assert_eq!(
            add.operand1,
            Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 32, value: 3 }))
        );
        #[cfg(feature = "llvm-14-or-lower")]
        assert_eq!(add.dest, Name::Number(8));
        #[cfg(feature = "llvm-15-or-greater")]
        assert_eq!(add.dest, Name::Number(7));
        assert_eq!(module.type_of(add), module.types.i32());
        #[cfg(feature = "llvm-17-or-greater")]
        assert_eq!(add.nuw, false);
        #[cfg(feature = "llvm-17-or-greater")]
        assert_eq!(add.nsw, true);
        #[cfg(feature = "llvm-14-or-lower")]
        assert_eq!(&add.to_string(), "%8 = add i32 %0, i32 3");
        #[cfg(any(feature = "llvm-15", feature = "llvm-16"))]
        assert_eq!(&add.to_string(), "%7 = add i32 %0, i32 3");
        #[cfg(feature = "llvm-17-or-greater")]
        assert_eq!(&add.to_string(), "%7 = add nsw i32 %0, i32 3");
    }
    #[cfg(feature = "llvm-12-or-lower")]
    {
        let icmp: &instruction::ICmp = &bbs[0].instrs[5]
            .clone()
            .try_into()
            .expect("Should be an icmp");
        assert_eq!(icmp.predicate, IntPredicate::ULT);
        assert_eq!(
            icmp.operand0,
            Operand::LocalOperand {
                name: Name::Number(5),
                ty: module.types.i32()
            }
        );
        assert_eq!(
            icmp.operand1,
            Operand::ConstantOperand(ConstantRef::new(Constant::Int {
                bits: 32,
                value: 10
            }))
        );
        assert_eq!(module.type_of(icmp), module.types.bool());
        assert_eq!(&icmp.to_string(), "%6 = icmp ult i32 %5, i32 10");
    }
    #[cfg(feature = "llvm-13")]
    {
        let icmp: &instruction::ICmp = &bbs[0].instrs[4]
            .clone()
            .try_into()
            .expect("Should be an icmp");
        assert_eq!(icmp.predicate, IntPredicate::SLT);
        assert_eq!(
            icmp.operand0,
            Operand::LocalOperand {
                name: Name::Number(1),
                ty: module.types.i32()
            }
        );
        assert_eq!(
            icmp.operand1,
            Operand::ConstantOperand(ConstantRef::new(Constant::Int {
                bits: 32,
                value: 11
            }))
        );
        assert_eq!(module.type_of(icmp), module.types.bool());
        assert_eq!(&icmp.to_string(), "%5 = icmp slt i32 %1, i32 11");
    }
    #[cfg(feature = "llvm-14-or-greater")]
    {
        #[cfg(feature = "llvm-14-or-lower")]
        let icmp: &instruction::ICmp = &bbs[0].instrs[5]
            .clone()
            .try_into()
            .expect("Should be an icmp");
        #[cfg(feature = "llvm-15-or-greater")]
        let icmp: &instruction::ICmp = &bbs[0].instrs[4]
            .clone()
            .try_into()
            .expect("Should be an icmp");
        assert_eq!(icmp.predicate, IntPredicate::ULT);
        #[cfg(feature = "llvm-14-or-lower")]
        assert_eq!(
            icmp.operand0,
            Operand::LocalOperand {
                name: Name::Number(5),
                ty: module.types.i32()
            }
        );
        #[cfg(feature = "llvm-15-or-greater")]
        assert_eq!(
            icmp.operand0,
            Operand::LocalOperand {
                name: Name::Number(4),
                ty: module.types.i32()
            }
        );
        assert_eq!(
            icmp.operand1,
            Operand::ConstantOperand(ConstantRef::new(Constant::Int {
                bits: 32,
                value: 10
            }))
        );
        assert_eq!(module.type_of(icmp), module.types.bool());
        #[cfg(feature = "llvm-14-or-lower")]
        assert_eq!(&icmp.to_string(), "%6 = icmp ult i32 %5, i32 10");
        #[cfg(feature = "llvm-15-or-greater")]
        assert_eq!(&icmp.to_string(), "%5 = icmp ult i32 %4, i32 10");
    }

    let condbr: &terminator::CondBr = &bbs[0].term.clone().try_into().expect("Should be a condbr");
    #[cfg(feature = "llvm-12-or-lower")]
    let expected_condition_op = Name::Number(6);
    #[cfg(feature = "llvm-13")]
    let expected_condition_op = Name::Number(5);
    #[cfg(feature = "llvm-14")]
    let expected_condition_op = Name::Number(6);
    #[cfg(feature = "llvm-15-or-greater")]
    let expected_condition_op = Name::Number(5);
    assert_eq!(
        condbr.condition,
        Operand::LocalOperand {
            name: expected_condition_op.clone(),
            ty: module.types.bool()
        }
    );
    #[cfg(feature = "llvm-12-or-lower")]
    let expected_true_dest = Name::Number(7);
    #[cfg(feature = "llvm-13")]
    let expected_true_dest = Name::Number(6);
    #[cfg(feature = "llvm-14")]
    let expected_true_dest = Name::Number(7);
    #[cfg(feature = "llvm-15-or-greater")]
    let expected_true_dest = Name::Number(6);
    assert_eq!(condbr.true_dest, expected_true_dest);
    let expected_false_dest = if cfg!(feature = "llvm-9-or-lower") {
        Name::Number(22)
    } else if cfg!(feature = "llvm-10") {
        Name::Number(21)
    } else if cfg!(feature = "llvm-11") {
        Name::Number(24)
    } else if cfg!(feature = "llvm-12") || cfg!(feature = "llvm-13") {
        Name::Number(47)
    } else if cfg!(feature = "llvm-14") {
        Name::Number(46)
    } else if cfg!(all(feature = "llvm-15-or-greater", feature = "llvm-17-or-lower")) {
        Name::Number(44)
    } else {
        Name::Number(41)
    };
    assert_eq!(condbr.false_dest, expected_false_dest);
    assert_eq!(module.type_of(condbr), module.types.void());
    assert_eq!(
        &condbr.to_string(),
        &format!(
            "br i1 {}, label {}, label {}",
            expected_condition_op, expected_true_dest, expected_false_dest,
        ),
    );

    // check details about certain instructions in basic block %7
    // not sure why LLVM 10+ puts a ZExt here instead of SExt. Maybe it can prove it's equivalent?
    // in LLVM 12+, the ZExt is in a different block
    #[cfg(feature = "llvm-9-or-lower")]
    let ext: &instruction::SExt = &bbs[1].instrs[1]
        .clone()
        .try_into()
        .expect("Should be a SExt");
    #[cfg(feature = "llvm-10")]
    let ext: &instruction::ZExt = &bbs[1].instrs[1]
        .clone()
        .try_into()
        .expect("Should be a ZExt");
    #[cfg(feature = "llvm-11")]
    let ext: &instruction::ZExt = &bbs[1].instrs[3]
        .clone()
        .try_into()
        .expect("Should be a ZExt");
    #[cfg(feature = "llvm-12-or-greater")]
    let ext: &instruction::ZExt = &bbs[2].instrs[0]
        .clone()
        .try_into()
        .expect("Should be a ZExt");
    let ext_input = if cfg!(feature = "llvm-10-or-lower") {
        Name::Number(1)
    } else if cfg!(any(feature = "llvm-11", feature = "llvm-12")) {
        Name::Number(10)
    } else {
        Name::Number(1)
    };
    let ext_dest = if cfg!(feature = "llvm-10-or-lower") {
        Name::Number(9)
    } else if cfg!(feature = "llvm-11") {
        Name::Number(11)
    } else if cfg!(feature = "llvm-12") || cfg!(feature = "llvm-13") {
        Name::Number(13)
    } else if cfg!(feature = "llvm-14") {
        Name::Number(12)
    } else {
        Name::Number(10)
    };
    assert_eq!(
        ext.operand,
        Operand::LocalOperand {
            name: ext_input,
            ty: module.types.i32()
        }
    );
    assert_eq!(ext.to_type, module.types.i64());
    assert_eq!(ext.dest, ext_dest);
    assert_eq!(module.type_of(ext), module.types.i64());
    #[cfg(feature = "llvm-9-or-lower")]
    assert_eq!(&ext.to_string(), "%9 = sext i32 %1 to i64");
    #[cfg(feature = "llvm-10")]
    assert_eq!(&ext.to_string(), "%9 = zext i32 %1 to i64");
    #[cfg(feature = "llvm-11")]
    assert_eq!(&ext.to_string(), "%11 = zext i32 %10 to i64");
    #[cfg(feature = "llvm-12")]
    assert_eq!(&ext.to_string(), "%13 = zext i32 %10 to i64");
    #[cfg(feature = "llvm-13")]
    assert_eq!(&ext.to_string(), "%13 = zext i32 %1 to i64");
    #[cfg(feature = "llvm-14")]
    assert_eq!(&ext.to_string(), "%12 = zext i32 %1 to i64");
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(&ext.to_string(), "%10 = zext i32 %1 to i64");
    #[cfg(feature = "llvm-9-or-lower")]
    {
        // LLVM 10 and 11 don't have a Br in this function
        let br: &terminator::Br = &bbs[1].term.clone().try_into().expect("Should be a Br");
        assert_eq!(br.dest, Name::Number(10));
        assert_eq!(&br.to_string(), "br label %10");
    }
    #[cfg(feature = "llvm-12-or-greater")]
    {
        let br: &terminator::Br = &bbs[3].term.clone().try_into().expect("Should be a Br");
        #[cfg(any(feature = "llvm-12", feature = "llvm-13"))]
        {
            assert_eq!(br.dest, Name::Number(19));
            assert_eq!(&br.to_string(), "br label %19");
        }
        #[cfg(feature = "llvm-14")]
        {
            assert_eq!(br.dest, Name::Number(18));
            assert_eq!(&br.to_string(), "br label %18");
        }
        #[cfg(feature = "llvm-15-or-greater")]
        {
            assert_eq!(br.dest, Name::Number(16));
            assert_eq!(&br.to_string(), "br label %16");
        }
    }

    // check details about certain instructions in basic block %10 (LLVM 9-) / %12 (LLVM 10) / %14 (LLVM 11) / %19 (LLVM 12+)
    #[cfg(feature = "llvm-11-or-lower")]
    let phi: &instruction::Phi = &bbs[2].instrs[0]
        .clone()
        .try_into()
        .expect("Should be a Phi");
    #[cfg(feature = "llvm-12-or-greater")]
    let phi: &instruction::Phi = &bbs[4].instrs[0]
        .clone()
        .try_into()
        .expect("Should be a Phi");
    let phi_dest = if cfg!(feature = "llvm-9-or-lower") {
        Name::Number(11)
    } else if cfg!(feature = "llvm-10") {
        Name::Number(13)
    } else if cfg!(feature = "llvm-11") {
        Name::Number(15)
    } else if cfg!(any(feature = "llvm-12", feature = "llvm-13")) {
        Name::Number(20)
    } else if cfg!(feature = "llvm-14") {
        Name::Number(19)
    } else {
        Name::Number(17)
    };
    assert_eq!(phi.dest, phi_dest);
    assert_eq!(phi.to_type, module.types.i64());
    #[cfg(feature = "llvm-9-or-lower")]
    assert_eq!(
        phi.incoming_values,
        vec![
            (
                Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 0 })),
                Name::Number(7)
            ),
            (
                Operand::LocalOperand {
                    name: Name::Number(20),
                    ty: module.types.i64()
                },
                Name::Number(19)
            ),
        ]
    );
    #[cfg(feature = "llvm-10")]
    assert_eq!(
        phi.incoming_values,
        vec![
            (
                Operand::LocalOperand {
                    name: Name::Number(19),
                    ty: module.types.i64()
                },
                Name::Number(12)
            ),
            (
                Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 1 })),
                Name::Number(7)
            ),
        ]
    );
    #[cfg(feature = "llvm-11")]
    assert_eq!(
        phi.incoming_values,
        vec![
            (
                Operand::LocalOperand {
                    name: Name::Number(22),
                    ty: module.types.i64()
                },
                Name::Number(14)
            ),
            (
                Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 1 })),
                Name::Number(7)
            ),
        ]
    );
    #[cfg(any(feature = "llvm-12", feature = "llvm-13"))]
    assert_eq!(
        phi.incoming_values,
        vec![
            (
                Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 1 })),
                Name::Number(17)
            ),
            (
                Operand::LocalOperand {
                    name: Name::Number(34),
                    ty: module.types.i64()
                },
                Name::Number(19)
            ),
        ]
    );
    #[cfg(feature = "llvm-14")]
    assert_eq!(
        phi.incoming_values,
        vec![
            (
                Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 1 })),
                Name::Number(16)
            ),
            (
                Operand::LocalOperand {
                    name: Name::Number(33),
                    ty: module.types.i64()
                },
                Name::Number(18)
            ),
        ]
    );
    #[cfg(all(feature = "llvm-15-or-greater", feature = "llvm-17-or-lower"))]
    assert_eq!(
        phi.incoming_values,
        vec![
            (
                Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 1 })),
                Name::Number(14)
            ),
            (
                Operand::LocalOperand {
                    name: Name::Number(31),
                    ty: module.types.i64()
                },
                Name::Number(16)
            ),
        ]
    );
    #[cfg(feature = "llvm-18-or-greater")]
    assert_eq!(
        phi.incoming_values,
        vec![
            (
                Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 1 })),
                Name::Number(14)
            ),
            (
                Operand::LocalOperand {
                    name: Name::Number(29),
                    ty: module.types.i64()
                },
                Name::Number(16)
            ),
        ]
    );
    #[cfg(feature = "llvm-9-or-lower")]
    assert_eq!(
        &phi.to_string(),
        "%11 = phi i64 [ i64 0, %7 ], [ i64 %20, %19 ]"
    );
    #[cfg(feature = "llvm-10")]
    assert_eq!(
        &phi.to_string(),
        "%13 = phi i64 [ i64 %19, %12 ], [ i64 1, %7 ]"
    );
    #[cfg(feature = "llvm-11")]
    assert_eq!(
        &phi.to_string(),
        "%15 = phi i64 [ i64 %22, %14 ], [ i64 1, %7 ]"
    );
    #[cfg(any(feature = "llvm-12", feature = "llvm-13"))]
    assert_eq!(
        &phi.to_string(),
        "%20 = phi i64 [ i64 1, %17 ], [ i64 %34, %19 ]"
    );
    #[cfg(feature = "llvm-14")]
    assert_eq!(
        &phi.to_string(),
        "%19 = phi i64 [ i64 1, %16 ], [ i64 %33, %18 ]"
    );
    #[cfg(all(feature = "llvm-15-or-greater", feature = "llvm-17-or-lower"))]
    assert_eq!(
        &phi.to_string(),
        "%17 = phi i64 [ i64 1, %14 ], [ i64 %31, %16 ]"
    );
    #[cfg(feature = "llvm-18-or-greater")]
    assert_eq!(
        &phi.to_string(),
        "%17 = phi i64 [ i64 1, %14 ], [ i64 %29, %16 ]"
    );

    #[cfg(feature = "llvm-11-or-lower")]
    let gep: &instruction::GetElementPtr = &bbs[2].instrs[1]
        .clone()
        .try_into()
        .expect("Should be a gep");
    #[cfg(feature = "llvm-12-or-greater")]
    let gep: &instruction::GetElementPtr = &bbs[4].instrs[2]
        .clone()
        .try_into()
        .expect("Should be a gep");
    #[cfg(feature = "llvm-14-or-lower")]
    let gep_addr_expected_ty = module.types.pointer_to(allocated_type.clone());
    #[cfg(feature = "llvm-15-or-greater")]
    let gep_addr_expected_ty = module.types.pointer();
    assert_eq!(
        gep.address,
        Operand::LocalOperand {
            name: Name::Number(3),
            ty: gep_addr_expected_ty,
        }
    );
    let gep_dest = if cfg!(feature = "llvm-9-or-lower") {
        Name::Number(12)
    } else if cfg!(feature = "llvm-10") {
        Name::Number(14)
    } else if cfg!(feature = "llvm-11") {
        Name::Number(16)
    } else if cfg!(feature = "llvm-12") || cfg!(feature = "llvm-13") {
        Name::Number(22)
    } else if cfg!(feature = "llvm-14") {
        Name::Number(21)
    } else {
        Name::Number(19)
    };
    assert_eq!(gep.dest, gep_dest);
    assert_eq!(gep.in_bounds, true);
    let index = if cfg!(feature = "llvm-9-or-lower") {
        Name::Number(11)
    } else if cfg!(feature = "llvm-10") {
        Name::Number(13)
    } else if cfg!(feature = "llvm-11") {
        Name::Number(15)
    } else if cfg!(feature = "llvm-12") || cfg!(feature = "llvm-13") {
        Name::Number(20)
    } else if cfg!(feature = "llvm-14") {
        Name::Number(19)
    } else {
        Name::Number(17)
    };
    assert_eq!(
        gep.indices,
        vec![
            Operand::ConstantOperand(ConstantRef::new(Constant::Int { bits: 64, value: 0 })),
            Operand::LocalOperand {
                name: index,
                ty: module.types.i64()
            },
        ]
    );
    #[cfg(feature = "llvm-14-or-lower")]
    assert_eq!(
        module.type_of(gep),
        module.types.pointer_to(module.types.i32())
    );
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(module.type_of(gep), module.types.pointer());
    #[cfg(feature = "llvm-9-or-lower")]
    assert_eq!(
        &gep.to_string(),
        "%12 = getelementptr inbounds [10 x i32]* %3, i64 0, i64 %11"
    );
    #[cfg(feature = "llvm-10")]
    assert_eq!(
        &gep.to_string(),
        "%14 = getelementptr inbounds [10 x i32]* %3, i64 0, i64 %13"
    );
    #[cfg(feature = "llvm-11")]
    assert_eq!(
        &gep.to_string(),
        "%16 = getelementptr inbounds [10 x i32]* %3, i64 0, i64 %15"
    );
    #[cfg(any(feature = "llvm-12", feature = "llvm-13"))]
    assert_eq!(
        &gep.to_string(),
        "%22 = getelementptr inbounds [10 x i32]* %3, i64 0, i64 %20"
    );
    #[cfg(feature = "llvm-14")]
    assert_eq!(
        &gep.to_string(),
        "%21 = getelementptr inbounds [10 x i32]* %3, i64 0, i64 %19"
    );
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(
        &gep.to_string(),
        "%19 = getelementptr inbounds ptr %3, i64 0, i64 %17"
    );
    #[cfg(feature = "llvm-11-or-lower")]
    let store_inst = &bbs[2].instrs[2];
    #[cfg(feature = "llvm-12-or-greater")]
    let store_inst = &bbs[4].instrs[3];
    let store: &instruction::Store = &store_inst.clone().try_into().expect("Should be a store");
    let address = if cfg!(feature = "llvm-9-or-lower") {
        Name::Number(12)
    } else if cfg!(feature = "llvm-10") {
        Name::Number(14)
    } else if cfg!(feature = "llvm-11") {
        Name::Number(16)
    } else if cfg!(feature = "llvm-12") || cfg!(feature = "llvm-13") {
        Name::Number(22)
    } else if cfg!(feature = "llvm-14") {
        Name::Number(21)
    } else {
        Name::Number(19)
    };
    #[cfg(feature = "llvm-14-or-lower")]
    let address_ty = module.types.pointer_to(module.types.i32());
    #[cfg(feature = "llvm-15-or-greater")]
    let address_ty = module.types.pointer();
    assert_eq!(
        store.address,
        Operand::LocalOperand {
            name: address,
            ty: address_ty,
        }
    );
    #[cfg(feature = "llvm-12-or-lower")]
    assert_eq!(
        store.value,
        Operand::LocalOperand {
            name: Name::Number(8),
            ty: module.types.i32()
        }
    );
    #[cfg(feature = "llvm-13")]
    assert_eq!(
        store.value,
        Operand::LocalOperand {
            name: Name::Number(7),
            ty: module.types.i32()
        }
    );
    #[cfg(feature = "llvm-14")]
    assert_eq!(
        store.value,
        Operand::LocalOperand {
            name: Name::Number(8),
            ty: module.types.i32()
        }
    );
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(
        store.value,
        Operand::LocalOperand {
            name: Name::Number(7),
            ty: module.types.i32()
        }
    );
    assert_eq!(store.volatile, true);
    assert_eq!(store.alignment, 4);
    assert_eq!(module.type_of(store), module.types.void());
    assert_eq!(store_inst.is_atomic(), false);
    #[cfg(feature = "llvm-9-or-lower")]
    assert_eq!(
        &store.to_string(),
        "store volatile i32 %8, i32* %12, align 4"
    );
    #[cfg(feature = "llvm-10")]
    assert_eq!(
        &store.to_string(),
        "store volatile i32 %8, i32* %14, align 4"
    );
    #[cfg(feature = "llvm-11")]
    assert_eq!(
        &store.to_string(),
        "store volatile i32 %8, i32* %16, align 4"
    );
    #[cfg(feature = "llvm-12")]
    assert_eq!(
        &store.to_string(),
        "store volatile i32 %8, i32* %22, align 4"
    );
    #[cfg(feature = "llvm-13")]
    assert_eq!(
        &store.to_string(),
        "store volatile i32 %7, i32* %22, align 4"
    );
    #[cfg(feature = "llvm-14")]
    assert_eq!(
        &store.to_string(),
        "store volatile i32 %8, i32* %21, align 4"
    );
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(
        &store.to_string(),
        "store volatile i32 %7, ptr %19, align 4"
    );

    // and finally other instructions of types we haven't seen yet
    let load_inst: &Instruction = if cfg!(feature = "llvm-9-or-lower") {
        &bbs[3].instrs[2]
    } else if cfg!(feature = "llvm-10") {
        &bbs[2].instrs[5]
    } else if cfg!(feature = "llvm-11") {
        &bbs[2].instrs[6]
    } else if cfg!(all(feature = "llvm-12-or-greater", feature = "llvm-17-or-lower")) {
        &bbs[4].instrs[7]
    }
    else {
        // Clang 18 removes some instructions in the loop body c.f. Clang 17
        &bbs[4].instrs[6]
    };
    let load: &instruction::Load = &load_inst.clone().try_into().expect("Should be a load");
    let load_addr = if cfg!(feature = "llvm-10-or-lower") {
        Name::Number(16)
    } else if cfg!(feature = "llvm-11") {
        Name::Number(19)
    } else if cfg!(feature = "llvm-12") || cfg!(feature = "llvm-13") {
        Name::Number(25)
    } else if cfg!(feature = "llvm-14") {
        Name::Number(24)
    } else if cfg!(all(feature = "llvm-14-or-greater", feature = "llvm-17-or-lower")) {
        Name::Number(22)
    } else {
        Name::Number(21)
    };
    #[cfg(feature = "llvm-14-or-lower")]
    let load_addr_expected_ty = module.types.pointer_to(module.types.i32());
    #[cfg(feature = "llvm-15-or-greater")]
    let load_addr_expected_ty = module.types.pointer();
    assert_eq!(
        load.address,
        Operand::LocalOperand {
            name: load_addr,
            ty: load_addr_expected_ty,
        }
    );
    #[cfg(feature = "llvm-10-or-lower")]
    assert_eq!(load.dest, Name::Number(17));
    #[cfg(feature = "llvm-11")]
    assert_eq!(load.dest, Name::Number(20));
    #[cfg(any(feature = "llvm-12", feature = "llvm-13"))]
    assert_eq!(load.dest, Name::Number(26));
    #[cfg(feature = "llvm-14")]
    assert_eq!(load.dest, Name::Number(25));
    #[cfg(all(feature = "llvm-15-or-greater", feature = "llvm-17-or-lower"))]
    assert_eq!(load.dest, Name::Number(23));
    #[cfg(feature = "llvm-18-or-greater")]
    assert_eq!(load.dest, Name::Number(22));

    assert_eq!(load.volatile, true);
    assert_eq!(load.alignment, 4);
    assert_eq!(module.type_of(load), module.types.i32());
    assert_eq!(load_inst.is_atomic(), false);
    #[cfg(feature = "llvm-10-or-lower")]
    assert_eq!(&load.to_string(), "%17 = load volatile i32* %16, align 4");
    #[cfg(feature = "llvm-11")]
    assert_eq!(&load.to_string(), "%20 = load volatile i32* %19, align 4");
    #[cfg(any(feature = "llvm-12", feature = "llvm-13"))]
    assert_eq!(&load.to_string(), "%26 = load volatile i32* %25, align 4");
    #[cfg(feature = "llvm-14")]
    assert_eq!(&load.to_string(), "%25 = load volatile i32* %24, align 4");
    #[cfg(all(feature = "llvm-15-or-greater", feature = "llvm-17-or-lower"))]
    assert_eq!(
        &load.to_string(),
        "%23 = load volatile i32, ptr %22, align 4"
    );
    #[cfg(feature = "llvm-18-or-greater")]
    assert_eq!(
        &load.to_string(),
        "%22 = load volatile i32, ptr %21, align 4"
    );
    let ret: &Terminator = if cfg!(feature = "llvm-9-or-lower") {
        &bbs[5].term
    } else if cfg!(feature = "llvm-10") || cfg!(feature = "llvm-11") {
        &bbs[3].term
    } else {
        &bbs[5].term
    };
    let ret: &terminator::Ret = &ret.clone().try_into().expect("Should be a ret");
    assert_eq!(ret.return_operand, None);
    assert_eq!(module.type_of(ret), module.types.void());
    assert_eq!(&ret.to_string(), "ret void");
}

#[test]
fn switchbc() {
    init_logging();
    let path = llvm_bc_dir().join("switch.bc");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");
    assert_eq!(module.functions.len(), 1);
    let func = &module.functions[0];
    assert_eq!(func.name, "has_a_switch");
    let bb = &func.basic_blocks[0];
    let switch: &terminator::Switch = &bb.term.clone().try_into().expect("Should be a switch");
    assert_eq!(
        switch.operand,
        Operand::LocalOperand {
            name: Name::Number(0),
            ty: module.types.i32()
        }
    );
    assert_eq!(switch.dests.len(), 9);
    assert_eq!(
        switch.dests[0],
        (
            ConstantRef::new(Constant::Int { bits: 32, value: 0 }),
            Name::Number(12)
        )
    );
    assert_eq!(
        switch.dests[1],
        (
            ConstantRef::new(Constant::Int { bits: 32, value: 1 }),
            Name::Number(2)
        )
    );
    assert_eq!(
        switch.dests[2],
        (
            ConstantRef::new(Constant::Int {
                bits: 32,
                value: 13
            }),
            Name::Number(3)
        )
    );
    assert_eq!(
        switch.dests[3],
        (
            ConstantRef::new(Constant::Int {
                bits: 32,
                value: 26
            }),
            Name::Number(4)
        )
    );
    assert_eq!(
        switch.dests[4],
        (
            ConstantRef::new(Constant::Int {
                bits: 32,
                value: 33
            }),
            Name::Number(5)
        )
    );
    assert_eq!(
        switch.dests[5],
        (
            ConstantRef::new(Constant::Int {
                bits: 32,
                value: 142
            }),
            Name::Number(6)
        )
    );
    assert_eq!(
        switch.dests[6],
        (
            ConstantRef::new(Constant::Int {
                bits: 32,
                value: 1678
            }),
            Name::Number(7)
        )
    );
    assert_eq!(
        switch.dests[7],
        (
            ConstantRef::new(Constant::Int {
                bits: 32,
                value: 88
            }),
            Name::Number(8)
        )
    );
    assert_eq!(
        switch.dests[8],
        (
            ConstantRef::new(Constant::Int {
                bits: 32,
                value: 101
            }),
            Name::Number(9)
        )
    );
    assert_eq!(switch.default_dest, Name::Number(10));
    assert_eq!(
        &switch.to_string(),
        "switch i32 %0, label %10 [ i32 0, label %12; i32 1, label %2; i32 13, label %3; i32 26, label %4; i32 33, label %5; i32 142, label %6; i32 1678, label %7; i32 88, label %8; i32 101, label %9; ]",
    );

    let phibb = &func
        .get_bb_by_name(&Name::Number(12))
        .expect("Failed to find bb %12");
    let phi: &instruction::Phi = &phibb.instrs[0].clone().try_into().expect("Should be a phi");
    assert_eq!(phi.incoming_values.len(), 10);
    assert_eq!(
        &phi.to_string(),
        "%13 = phi i32 [ i32 -1, %10 ], [ i32 -3, %9 ], [ i32 0, %8 ], [ i32 77, %7 ], [ i32 -33, %6 ], [ i32 1, %5 ], [ i32 -5, %4 ], [ i32 -7, %3 ], [ i32 5, %2 ], [ i32 3, %1 ]",
    );

    assert_eq!(
        module.get_func_decl_by_name("has_a_switch"),
        None,
        "has_a_switch should be a defined function, not a decl"
    );
    let decl = module
        .get_func_decl_by_name("puts")
        .expect("there should be a puts declaration");
    assert_eq!(decl.name, "puts");
    assert_eq!(decl.return_type, module.types.i32());
    assert_eq!(decl.parameters.len(), 1);
    #[cfg(feature = "llvm-14-or-lower")]
    let param_0_expected_ty = module.types.pointer_to(module.types.i8());
    #[cfg(feature = "llvm-15-or-greater")]
    let param_0_expected_ty = module.types.pointer();
    assert_eq!(module.type_of(&decl.parameters[0]), param_0_expected_ty,);
}

#[test]
fn variablesbc() {
    init_logging();
    let path = llvm_bc_dir().join("variables.bc");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");
    assert_eq!(module.global_vars.len(), 1);
    let var = &module.global_vars[0];
    assert_eq!(var.name, Name::from("global"));
    assert_eq!(var.is_constant, false);
    #[cfg(feature = "llvm-14-or-lower")]
    assert_eq!(var.ty, module.types.pointer_to(module.types.i32()));
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(var.ty, module.types.pointer());
    assert_eq!(
        var.initializer,
        Some(ConstantRef::new(Constant::Int { bits: 32, value: 5 }))
    );
    assert_eq!(var.alignment, 4);
    assert!(var.get_debug_loc().is_none()); // this file was compiled without debuginfo

    assert_eq!(module.functions.len(), 1);
    let func = &module.functions[0];
    assert_eq!(func.name, "variables");
    let bb = &func.basic_blocks[0];
    let store: &instruction::Store = &bb.instrs[2].clone().try_into().expect("Should be a store");
    #[cfg(feature = "llvm-14-or-lower")]
    let store_addr_expected_ty = module.types.pointer_to(module.types.i32());
    #[cfg(feature = "llvm-15-or-greater")]
    let store_addr_expected_ty = module.types.pointer();
    assert_eq!(
        store.address,
        Operand::LocalOperand {
            name: Name::Number(3),
            ty: store_addr_expected_ty,
        }
    );
    assert_eq!(module.type_of(store), module.types.void());
    #[cfg(feature = "llvm-14-or-lower")]
    let expected_fmt = "store volatile i32 %0, i32* %3, align 4";
    #[cfg(feature = "llvm-15-or-greater")]
    let expected_fmt = "store volatile i32 %0, ptr %3, align 4";
    assert_eq!(&store.to_string(), expected_fmt);
    #[cfg(feature = "llvm-14-or-lower")]
    let load: &instruction::Load = &bb.instrs[8].clone().try_into().expect("Should be a load");
    #[cfg(feature = "llvm-15-or-greater")]
    let load: &instruction::Load = &bb.instrs[6].clone().try_into().expect("Should be a load");
    #[cfg(feature = "llvm-14-or-lower")]
    let load_addr_expected_ty = module.types.pointer_to(module.types.i32());
    #[cfg(feature = "llvm-15-or-greater")]
    let load_addr_expected_ty = module.types.pointer();
    assert_eq!(
        load.address,
        Operand::LocalOperand {
            name: Name::Number(4),
            ty: load_addr_expected_ty,
        }
    );
    assert_eq!(module.type_of(load), module.types.i32());
    #[cfg(feature = "llvm-14-or-lower")]
    let expected_fmt = "%8 = load volatile i32* %4, align 4";
    #[cfg(feature = "llvm-15-or-greater")]
    let expected_fmt = "%6 = load volatile i32, ptr %4, align 4";
    assert_eq!(&load.to_string(), expected_fmt);
    #[cfg(feature = "llvm-14-or-lower")]
    let global_load: &instruction::Load =
        &bb.instrs[14].clone().try_into().expect("Should be a load");
    #[cfg(feature = "llvm-15-or-greater")]
    let global_load: &instruction::Load =
        &bb.instrs[12].clone().try_into().expect("Should be a load");
    assert_eq!(
        global_load.address,
        Operand::ConstantOperand(ConstantRef::new(Constant::GlobalReference {
            name: Name::from("global"),
            ty: module.types.i32()
        }))
    );
    assert_eq!(module.type_of(global_load), module.types.i32());
    #[cfg(feature = "llvm-14-or-lower")]
    let expected_fmt = "%12 = load volatile i32* @global, align 4";
    #[cfg(feature = "llvm-15-or-greater")]
    let expected_fmt = "%10 = load volatile i32, ptr @global, align 4";
    assert_eq!(&global_load.to_string(), expected_fmt);
    #[cfg(feature = "llvm-14-or-lower")]
    let global_store: &instruction::Store =
        &bb.instrs[16].clone().try_into().expect("Should be a store");
    #[cfg(feature = "llvm-15-or-greater")]
    let global_store: &instruction::Store =
        &bb.instrs[14].clone().try_into().expect("Should be a store");
    assert_eq!(
        global_store.address,
        Operand::ConstantOperand(ConstantRef::new(Constant::GlobalReference {
            name: Name::from("global"),
            ty: module.types.i32()
        }))
    );
    assert_eq!(module.type_of(global_store), module.types.void());
    #[cfg(feature = "llvm-14-or-lower")]
    let expected_fmt = "store volatile i32 %13, i32* @global, align 4";
    #[cfg(feature = "llvm-15-or-greater")]
    let expected_fmt = "store volatile i32 %11, ptr @global, align 4";
    assert_eq!(&global_store.to_string(), expected_fmt);

    assert_eq!(
        module.get_func_decl_by_name("variables"),
        None,
        "variables should be a defined function, not a decl"
    );
    let decl = module
        .get_func_decl_by_name("malloc")
        .expect("there should be a malloc declaration");
    assert_eq!(decl.name, "malloc");
    #[cfg(feature = "llvm-14-or-lower")]
    assert_eq!(decl.return_type, module.types.pointer_to(module.types.i8()));
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(decl.return_type, module.types.pointer());
    assert!(decl
        .return_attributes
        .contains(&ParameterAttribute::NoAlias));
    assert_eq!(decl.parameters.len(), 1);
    assert_eq!(module.type_of(&decl.parameters[0]), module.types.i64());
    #[cfg(feature = "llvm-12-or-lower")]
    assert_eq!(decl.parameters[0].attributes, vec![]);
    #[cfg(feature = "llvm-13-or-greater")]
    assert_eq!(
        decl.parameters[0].attributes,
        vec![ParameterAttribute::NoUndef]
    );
}

// this test relates to the version of the file compiled with debuginfo
#[test]
fn variablesbcg() {
    init_logging();
    let path = llvm_bc_dir().join("variables.bc-g");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");
    let debug_filename = "variables.c";
    let debug_directory_suffix = "/tests/basic_bc";

    // really all we want to check is the debugloc of the global variable.
    // other debuginfo stuff is covered in other tests
    assert_eq!(module.global_vars.len(), 1);
    let var = &module.global_vars[0];
    assert_eq!(var.name, Name::from("global"));
    let debugloc = var
        .get_debug_loc()
        .as_ref()
        .expect("expected the global to have a debugloc");
    assert_eq!(debugloc.line, 5);
    assert_eq!(debugloc.col, None); // only `Instruction`s and `Terminator`s get column numbers
    assert_eq!(debugloc.filename, debug_filename);
    assert!(debugloc.directory.as_ref().expect("directory should exist").ends_with(debug_directory_suffix));
}

/// this test checks for regression on issue #4
#[test]
fn issue4() {
    init_logging();
    let path = llvm_bc_dir().join("issue_4.bc");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");
    assert_eq!(module.functions.len(), 1);
    let func = &module.functions[0];

    // not part of issue 4 proper, but let's check that we have the correct number of function attributes
    let expected_num_function_attributes = if cfg!(feature = "llvm-9") {
        22
    } else if cfg!(feature = "llvm-10") || cfg!(feature = "llvm-11") {
        // LLVM 10+ seems to have combined the two attributes
        // "no-frame-pointer-elim=true" and "no-frame-pointer-elim-non-leaf"
        // into a single attribute, "frame-pointer=all"
        21
    } else if cfg!(feature = "llvm-12") {
        // LLVM 12+ adds "willreturn"
        22
    } else if cfg!(feature = "llvm-13") || cfg!(feature = "llvm-14") {
        // LLVM 13+ adds "mustprogress" and "nosync"
        // LLVM 13+ removes the following string attributes:
        //   "disable-tail-calls=false"
        //   "less-precise-fpmad=false"
        //   "no-infs-fp-math=false"
        //   "no-jump-tables=false"
        //   "no-nans-fp-math=false"
        //   "no-signed-zeroes-fp-math=false"
        //   "unsafe-fp-math=false"
        //   "use-soft-float=false"
        // for a net of -6 attributes
        16
    } else if cfg!(feature = "llvm-15") {
        // LLVM 15+ adds "argmemonly"
        17
    } else if cfg!(feature = "llvm-16-or-greater") {
        // LLVM 16+ merges "argmemonly", "inaccessiblememonly", etc. into a single memory attribute
        // See https://discourse.llvm.org/t/rfc-unify-memory-effect-attributes/65579/20
        16
    } else {
        panic!("Shouldn't reach this")
    };
    assert_eq!(
        func.function_attributes.len(),
        expected_num_function_attributes,
        "Expected {} function attributes but have {}: {:?}",
        expected_num_function_attributes,
        func.function_attributes.len(),
        func.function_attributes
    );
    // and that all but 6 of them are StringAttributes (7 for LLVM 12; 9 for LLVM 13/14; 10 for LLVM 15+)
    let expected_num_enum_attrs = if cfg!(feature = "llvm-11-or-lower") {
        6
    } else if cfg!(feature = "llvm-12") {
        7 // adds "willreturn"
    } else if cfg!(feature = "llvm-13") || cfg!(feature = "llvm-14") {
        9 // adds "mustprogress" and "nosync"
    } else if cfg!(feature = "llvm-15") {
        10 // adds "argmemonly"
    } else if cfg!(feature = "llvm-16-or-greater") {
        9 // new "memory" attribute combines "argmemonly" and related attributes
    } else {
        unreachable!("Shouldn't reach this")
    };
    let string_attrs = func.function_attributes.iter().filter(|attr| {
        if let FunctionAttribute::StringAttribute { .. } = attr {
            true
        } else {
            false
        }
    });
    assert_eq!(
        string_attrs.count(),
        expected_num_function_attributes - expected_num_enum_attrs
    );

    // now check that the first parameter has 3 attributes (4 in LLVM 11/12/13, 5 in LLVM 14) and the second parameter has 0
    assert_eq!(func.parameters.len(), 2);
    let first_param_attrs = &func.parameters[0].attributes;
    #[cfg(feature = "llvm-10-or-lower")]
    assert_eq!(first_param_attrs.len(), 3);
    #[cfg(any(feature = "llvm-11", feature = "llvm-12", feature = "llvm-13"))]
    assert_eq!(first_param_attrs.len(), 4);
    #[cfg(all(feature = "llvm-14-or-greater", feature = "llvm-17-or-lower"))]
    assert_eq!(first_param_attrs.len(), 5);
    #[cfg(feature = "llvm-18-or-greater")]
    assert_eq!(first_param_attrs.len(), 7); // Clang 18 adds dead_on_unwind and writable
    let second_param_attrs = &func.parameters[1].attributes;
    #[cfg(feature = "llvm-13-or-lower")]
    assert_eq!(second_param_attrs.len(), 0);
    #[cfg(feature = "llvm-14-or-greater")]
    assert_eq!(second_param_attrs.len(), 1); // LLVM 14+ adds 'noundef' to the second param

    // and that one of the parameter attributes is SRet
    #[cfg(feature = "llvm-11-or-lower")]
    let is_sret = |attr: &ParameterAttribute| match attr {
        ParameterAttribute::SRet => true,
        _ => false,
    };
    #[cfg(feature = "llvm-12-or-greater")]
    let is_sret = |attr: &ParameterAttribute| match attr {
        ParameterAttribute::SRet(_) => true,
        _ => false,
    };
    assert!(first_param_attrs.iter().any(is_sret));
}

/// This test checks for regression on issue 42
#[cfg(feature = "llvm-14-or-greater")]
#[test]
fn issue42() {
    init_logging();
    let path = Path::new(BC_DIR).join("issue-42.ll");
    let _ = Module::from_ir_path(&path).expect("Failed to parse module");
    // just check the module parses without errors
}

/// This test checks for regression on issue 57
#[cfg(feature = "llvm-16-or-greater")] // although the issue probably affects all of our supported versions (IFunc has existed since at least LLVM 8), the provided bitcode was produced with LLVM 16
#[test]
fn issue57() {
    init_logging();
    let path = Path::new(BC_DIR).join("ifunc_minimal.ll");
    let module = Module::from_ir_path(&path).expect("Failed to parse module");
    let ifunc = module.get_global_ifunc_by_name(&Name::from("__libc_strstr")).expect("failed to find global ifunc");
    assert_eq!(ifunc.ty, module.types.pointer());
    match ifunc.resolver_fn.as_ref() {
        Constant::GlobalReference { name, ty } => {
            assert_eq!(name, &Name::from("__libc_strstr_ifunc"));
            assert_eq!(ty, &module.types.func_type(module.types.pointer(), vec![], false));
        }
        _ => panic!("expected a GlobalReference"),
    }

    let path = Path::new(BC_DIR).join("strstr.o.bc");
    let _ = Module::from_bc_path(&path).expect("Failed to parse module");
    // just check the module parses without errors
}

#[test]
fn rustbc() {
    // This tests against the checked-in rust.bc, which was generated from the checked-in rust.rs with rustc 1.39.0
    init_logging();
    let path = rust_bc_dir().join("rust.bc");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");
    let func = module
        .get_func_by_name("_ZN4rust9rust_loop17h3ed0672b8cf44eb1E")
        .expect("Failed to find function");

    assert_eq!(func.parameters.len(), 3);
    assert_eq!(func.parameters[0].name, Name::from("a"));
    assert_eq!(func.parameters[1].name, Name::from("b"));
    assert_eq!(func.parameters[2].name, Name::from("v"));
    assert_eq!(func.parameters[0].ty, module.types.i64());
    assert_eq!(func.parameters[1].ty, module.types.i64());
    #[cfg(feature = "llvm-14-or-lower")]
    assert_eq!(
        func.parameters[2].ty,
        module
            .types
            .pointer_to(module.types.named_struct("alloc::vec::Vec<isize>"))
    );
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(func.parameters[2].ty, module.types.pointer());

    let startbb = func
        .get_bb_by_name(&Name::from("start"))
        .expect("Failed to find bb 'start'");
    let alloca_iter: &instruction::Alloca = &startbb.instrs[5]
        .clone()
        .try_into()
        .expect("Should be an alloca");
    assert_eq!(alloca_iter.dest, Name::from("iter"));
    #[cfg(feature = "llvm-14-or-lower")]
    let expected_fmt = "%iter = alloca { i64*, i64* }, align 8";
    #[cfg(feature = "llvm-15-or-greater")]
    let expected_fmt = "%iter = alloca { ptr, ptr }, align 8";
    assert_eq!(&alloca_iter.to_string(), expected_fmt);
    let alloca_sum: &instruction::Alloca = &startbb.instrs[6]
        .clone()
        .try_into()
        .expect("Should be an alloca");
    assert_eq!(alloca_sum.dest, Name::from("sum"));
    assert_eq!(&alloca_sum.to_string(), "%sum = alloca i64, align 8");
    let store: &instruction::Store = &startbb.instrs[7]
        .clone()
        .try_into()
        .expect("Should be a store");
    #[cfg(feature = "llvm-14-or-lower")]
    let store_addr_expected_ty = module.types.pointer_to(module.types.i64());
    #[cfg(feature = "llvm-15-or-greater")]
    let store_addr_expected_ty = module.types.pointer();
    assert_eq!(
        store.address,
        Operand::LocalOperand {
            name: Name::from("sum"),
            ty: store_addr_expected_ty,
        }
    );
    #[cfg(feature = "llvm-14-or-lower")]
    let expected_fmt = "store i64 0, i64* %sum, align 8";
    #[cfg(feature = "llvm-15-or-greater")]
    let expected_fmt = "store i64 0, ptr %sum, align 8";
    assert_eq!(&store.to_string(), expected_fmt);
    let call: &instruction::Call = &startbb.instrs[8]
        .clone()
        .try_into()
        .expect("Should be a call");
    #[cfg(feature = "llvm-14-or-lower")]
    let param_type = module
        .types
        .pointer_to(module.types.named_struct("alloc::vec::Vec<isize>"));
    #[cfg(feature = "llvm-15-or-greater")]
    let param_type = module.types.pointer();
    let ret_type = module.types.struct_of(
        vec![
            #[cfg(feature = "llvm-14-or-lower")]
            module
                .types
                .pointer_to(module.types.array_of(module.types.i64(), 0)),
            #[cfg(feature = "llvm-15-or-greater")]
            module.types.pointer(),
            module.types.i64(),
        ],
        false,
    );
    if let Either::Right(Operand::ConstantOperand(cref)) = &call.function {
        if let Constant::GlobalReference { ref name, ref ty } = cref.as_ref() {
            assert_eq!(name, &Name::from("_ZN68_$LT$alloc..vec..Vec$LT$T$GT$$u20$as$u20$core..ops..deref..Deref$GT$5deref17h378128d7d9378466E"));
            match ty.as_ref() {
                Type::FuncType {
                    result_type,
                    param_types,
                    is_var_arg,
                } => {
                    assert_eq!(result_type, &ret_type);
                    assert_eq!(&param_types[0], &param_type);
                    assert_eq!(*is_var_arg, false);
                },
                _ => panic!("Expected called global to have FuncType, but got {:?}", ty),
            }
            assert_eq!(module.type_of(call), ret_type);
        } else {
            panic!(
                "call.function not a GlobalReference as expected; it is actually another kind of Constant: {:?}",
                cref
            );
        }
    } else {
        panic!(
            "call.function not a GlobalReference as expected; it is actually {:?}",
            call.function
        );
    }
    assert_eq!(call.arguments.len(), 1);
    assert_eq!(
        call.arguments[0].0,
        Operand::LocalOperand {
            name: Name::from("v"),
            ty: param_type,
        }
    );
    assert_eq!(call.dest, Some(Name::Number(0)));
    #[cfg(feature = "llvm-14-or-lower")]
    let expected_fmt = "%0 = call @_ZN68_$LT$alloc..vec..Vec$LT$T$GT$$u20$as$u20$core..ops..deref..Deref$GT$5deref17h378128d7d9378466E(%alloc::vec::Vec<isize>* %v)";
    #[cfg(feature = "llvm-15-or-greater")]
    let expected_fmt = "%0 = call @_ZN68_$LT$alloc..vec..Vec$LT$T$GT$$u20$as$u20$core..ops..deref..Deref$GT$5deref17h378128d7d9378466E(ptr %v)";
    assert_eq!(&call.to_string(), expected_fmt);

    // this file was compiled without debuginfo, so nothing should have a debugloc
    assert!(func.get_debug_loc().is_none());
    assert!(alloca_iter.get_debug_loc().is_none());
    assert!(alloca_sum.get_debug_loc().is_none());
    assert!(store.get_debug_loc().is_none());
    assert!(call.get_debug_loc().is_none());
}

// this test relates to the version of the file compiled with debuginfo
#[test]
fn rustbcg() {
    init_logging();
    let path = rust_bc_dir().join("rust.bc-g");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");
    let debug_filename = "rust.rs";
    let debug_directory_suffix = "/tests/basic_bc";

    let func = module
        .get_func_by_name("_ZN4rust9rust_loop17h3ed0672b8cf44eb1E")
        .expect("Failed to find function");
    let debugloc = func
        .get_debug_loc()
        .as_ref()
        .expect("Expected function to have a debugloc");
    assert_eq!(debugloc.line, 3);
    assert_eq!(debugloc.col, None);
    assert_eq!(debugloc.filename, debug_filename);
    assert!(debugloc.directory.as_ref().expect("directory should exist").ends_with(debug_directory_suffix));

    let startbb = func
        .get_bb_by_name(&Name::from("start"))
        .expect("Failed to find bb 'start'");

    // the first 17 instructions in the function should not have debuglocs - they are just setting up the stack frame
    for i in 0..17 {
        assert!(startbb.instrs[i].get_debug_loc().is_none());
    }

    #[cfg(feature = "llvm-18-or-lower")]
    const EXPECTED_STORE_INSTRUCTION_INDEX : usize = 31;
    #[cfg(feature = "llvm-19-or-greater")]
    const EXPECTED_STORE_INSTRUCTION_INDEX : usize = 19;

    #[cfg(feature = "llvm-18-or-lower")]
    const EXPECTED_CALL_INSTRUCTION_INDEX : usize = 33;
    #[cfg(feature = "llvm-19-or-greater")]
    const EXPECTED_CALL_INSTRUCTION_INDEX : usize = 21;

    let store_debugloc = startbb.instrs[EXPECTED_STORE_INSTRUCTION_INDEX]
        .get_debug_loc()
        .as_ref()
        .expect("Expected this store to have a debugloc");
    assert_eq!(store_debugloc.line, 4);
    assert_eq!(store_debugloc.col, Some(18));
    assert_eq!(store_debugloc.filename, debug_filename);
    assert!(debugloc.directory.as_ref().expect("directory should exist").ends_with(debug_directory_suffix));
    #[cfg(feature = "llvm-14-or-lower")]
    let expected_fmt = "store i64 0, i64* %sum, align 8 (with debugloc)";
    #[cfg(feature = "llvm-15-or-greater")]
    let expected_fmt = "store i64 0, ptr %sum, align 8 (with debugloc)";
    assert_eq!(&startbb.instrs[EXPECTED_STORE_INSTRUCTION_INDEX].to_string(), expected_fmt);
    let call_debugloc = startbb.instrs[EXPECTED_CALL_INSTRUCTION_INDEX]
        .get_debug_loc()
        .as_ref()
        .expect("Expected this call to have a debugloc");
    assert_eq!(call_debugloc.line, 5);
    assert_eq!(call_debugloc.col, Some(13));
    assert_eq!(call_debugloc.filename, debug_filename);
    assert!(debugloc.directory.as_ref().expect("directory should exist").ends_with(debug_directory_suffix));
    #[cfg(feature = "llvm-14-or-lower")]
    let expected_fmt = "%4 = call @_ZN68_$LT$alloc..vec..Vec$LT$T$GT$$u20$as$u20$core..ops..deref..Deref$GT$5deref17h378128d7d9378466E(%alloc::vec::Vec<isize>* %3) (with debugloc)";
    #[cfg(feature = "llvm-15-or-greater")]
    let expected_fmt = "%4 = call @_ZN68_$LT$alloc..vec..Vec$LT$T$GT$$u20$as$u20$core..ops..deref..Deref$GT$5deref17h378128d7d9378466E(ptr %3) (with debugloc)";
    assert_eq!(&startbb.instrs[EXPECTED_CALL_INSTRUCTION_INDEX].to_string(), expected_fmt);
}

#[test]
fn simple_linked_list() {
    init_logging();
    let path = llvm_bc_dir().join("linkedlist.bc");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");

    let struct_name: String = "struct.SimpleLinkedList".into();
    let structty = module.types.named_struct(&struct_name);
    match structty.as_ref() {
        Type::NamedStructType { name } => {
            assert_eq!(name, &struct_name);
        },
        ty => panic!(
            "Expected {} to be NamedStructType, but got {:?}",
            struct_name, ty
        ),
    }
    let structty_inner = match module.types.named_struct_def(&struct_name) {
        None => panic!(
            "Failed to find {} with module.types.named_struct_def(); have names {:?}",
            struct_name,
            module.types.all_struct_names().collect::<Vec<_>>()
        ),
        Some(NamedStructDef::Opaque) => panic!("{} should not be an opaque type", struct_name),
        Some(NamedStructDef::Defined(ty)) => ty,
    };
    if let Type::StructType { element_types, .. } = structty_inner.as_ref() {
        assert_eq!(element_types.len(), 2);
        assert_eq!(element_types[0], module.types.i32());
        #[cfg(feature = "llvm-14-or-lower")]
        if let Type::PointerType { pointee_type, .. } = element_types[1].as_ref() {
            if let Type::NamedStructType { name } = pointee_type.as_ref() {
                assert_eq!(name, &struct_name);
            } else {
                panic!(
                    "Expected pointee type to be a NamedStructType, got {:?}",
                    pointee_type
                );
            }
        } else {
            panic!(
                "Expected inner type to be a PointerType, got {:?}",
                element_types[1]
            );
        }
        #[cfg(feature = "llvm-15-or-greater")]
        assert!(matches!(
            element_types[1].as_ref(),
            Type::PointerType { .. }
        ));
    } else {
        panic!(
            "Expected {} to be a StructType, got {:?}",
            struct_name, structty
        );
    }

    let func = module
        .get_func_by_name("simple_linked_list")
        .expect("Failed to find function");
    let alloca: &instruction::Alloca = &func.basic_blocks[0].instrs[1]
        .clone()
        .try_into()
        .expect("Should be an alloca");
    if let Type::NamedStructType { name } = alloca.allocated_type.as_ref() {
        assert_eq!(name, &struct_name);
    } else {
        panic!(
            "Expected alloca.allocated_type to be a NamedStructType, got {:?}",
            alloca.allocated_type
        );
    }
    assert_eq!(
        &alloca.to_string(),
        "%3 = alloca %struct.SimpleLinkedList, align 8"
    );

    // LLVM 15 has no need for the SomeOpaqueStruct due to opaque pointer types
    #[cfg(feature = "llvm-14-or-lower")]
    {
        let struct_name: String = "struct.SomeOpaqueStruct".into();
        let structty = module.types.named_struct(&struct_name);
        match structty.as_ref() {
            Type::NamedStructType { name } => {
                assert_eq!(name, &struct_name);
            },
            ty => panic!(
                "Expected {} to be a NamedStructType, but got {:?}",
                struct_name, ty
            ),
        }
        match module.types.named_struct_def(&struct_name) {
            None => panic!(
                "Failed to find {} with module.types.named_struct_def(); have names {:?}",
                struct_name,
                module.types.all_struct_names().collect::<Vec<_>>()
            ),
            Some(NamedStructDef::Opaque) => (),
            Some(NamedStructDef::Defined(def)) => panic!(
                "{} should be an opaque type; got def {:?}",
                struct_name, def
            ),
        }
    }

    let func = module
        .get_func_by_name("takes_opaque_struct")
        .expect("Failed to find function");
    let paramty = &func.parameters[0].ty;
    #[cfg(feature = "llvm-14-or-lower")]
    match paramty.as_ref() {
        Type::PointerType { pointee_type, .. } => match pointee_type.as_ref() {
            Type::NamedStructType { name } => {
                assert_eq!(name, "struct.SomeOpaqueStruct");
            },
            ty => panic!(
                "Expected parameter type to be pointer to named struct, but got pointer to {:?}",
                ty
            ),
        },
        _ => panic!(
            "Expected parameter type to be pointer type, but got {:?}",
            paramty
        ),
    };
    #[cfg(feature = "llvm-15-or-greater")]
    assert!(matches!(paramty.as_ref(), Type::PointerType { .. }));
}

// this test relates to the version of the file compiled with debuginfo
#[test]
fn simple_linked_list_g() {
    init_logging();
    let path = llvm_bc_dir().join("linkedlist.bc-g");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");
    let debug_filename = "linkedlist.c";
    let debug_directory_suffix = "/tests/basic_bc";

    let func = module
        .get_func_by_name("simple_linked_list")
        .expect("Failed to find function");
    let debugloc = func
        .get_debug_loc()
        .as_ref()
        .expect("expected simple_linked_list to have a debugloc");
    assert_eq!(debugloc.line, 8);
    assert_eq!(debugloc.col, None);
    assert_eq!(debugloc.filename, debug_filename);
    assert!(debugloc.directory.as_ref().expect("directory should exist").ends_with(debug_directory_suffix));

    // the first seven instructions shouldn't have debuglocs - they are just setting up the stack frame
    for i in 0..7 {
        assert!(func.basic_blocks[0].instrs[i].get_debug_loc().is_none());
    }

    // As of LLVM 19, debug info is now metadata instead of intrinsics
    #[cfg(feature = "llvm-18-or-lower")]
    {
        // the eighth instruction should have a debugloc
        let debugloc = func.basic_blocks[0].instrs[7]
            .get_debug_loc()
            .as_ref()
            .expect("expected this instruction to have a debugloc");
        assert_eq!(debugloc.line, 8);
        assert_eq!(debugloc.col, Some(28));
        assert_eq!(debugloc.filename, debug_filename);
        assert!(debugloc.directory.as_ref().expect("directory should exist").ends_with(debug_directory_suffix));
        assert_eq!(
            &func.basic_blocks[0].instrs[7].to_string(),
            "call @llvm.dbg.declare(<metadata>, <metadata>, <metadata>) (with debugloc)",
        );
    }

    // the tenth instruction should have a different debugloc
    let debugloc = func.basic_blocks[0].instrs[9]
        .get_debug_loc()
        .as_ref()
        .expect("expected this instruction to have a debugloc");
    assert_eq!(debugloc.line, 9);
    assert_eq!(debugloc.col, Some(34));
    assert_eq!(debugloc.filename, debug_filename);
    assert!(debugloc.directory.as_ref().expect("directory should exist").ends_with(debug_directory_suffix));

    #[cfg(feature = "llvm-14-or-lower")]
    let expected_fmt =
        "%8 = getelementptr inbounds %struct.SimpleLinkedList* %3, i32 0, i32 0 (with debugloc)";
    #[cfg(all(feature = "llvm-15-or-greater", feature = "llvm-18-or-lower"))]
    let expected_fmt = "%8 = getelementptr inbounds ptr %3, i32 0, i32 0 (with debugloc)";
    #[cfg(feature = "llvm-19-or-greater")]
    let expected_fmt = "store i32 %9, ptr %8, align 8 (with debugloc)";

    assert_eq!(&func.basic_blocks[0].instrs[9].to_string(), expected_fmt);
}

#[test]
fn indirectly_recursive_type() {
    init_logging();
    let path = llvm_bc_dir().join("linkedlist.bc");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");

    let struct_name_a: String = "struct.NodeA".into();
    let aty = module.types.named_struct(&struct_name_a);
    match aty.as_ref() {
        Type::NamedStructType { name } => {
            assert_eq!(name, &struct_name_a);
        },
        ty => panic!(
            "Expected {} to be a NamedStructType, but got {:?}",
            struct_name_a, ty
        ),
    }
    let aty_inner = match module.types.named_struct_def(&struct_name_a) {
        None => panic!(
            "Failed to find {} with module.types.named_struct_def(); have names {:?}",
            struct_name_a,
            module.types.all_struct_names().collect::<Vec<_>>()
        ),
        Some(NamedStructDef::Opaque) => panic!("{} should not be an opaque type", &struct_name_a),
        Some(NamedStructDef::Defined(ty)) => ty,
    };
    let struct_name_b: String = "struct.NodeB".into();
    let bty = module.types.named_struct(&struct_name_b);
    match bty.as_ref() {
        Type::NamedStructType { name } => {
            assert_eq!(name, &struct_name_b);
        },
        ty => panic!(
            "Expected {} to be a NamedStructType, but got {:?}",
            struct_name_b, ty
        ),
    }
    let bty_inner = match module.types.named_struct_def(&struct_name_b) {
        None => panic!(
            "Failed to find {} with module.types.named_struct_def(); have names {:?}",
            struct_name_b,
            module.types.all_struct_names().collect::<Vec<_>>()
        ),
        Some(NamedStructDef::Opaque) => panic!("{} should not be an opaque type", &struct_name_b),
        Some(NamedStructDef::Defined(ty)) => ty,
    };
    if let Type::StructType { element_types, .. } = aty_inner.as_ref() {
        assert_eq!(element_types.len(), 2);
        assert_eq!(element_types[0], module.types.i32());
        #[cfg(feature = "llvm-14-or-lower")]
        if let Type::PointerType { pointee_type, .. } = element_types[1].as_ref() {
            if let Type::NamedStructType { name } = pointee_type.as_ref() {
                assert_eq!(name, &struct_name_b);
            } else {
                panic!(
                    "Expected pointee type to be a NamedStructType, got {:?}",
                    pointee_type.as_ref()
                );
            }
        } else {
            panic!(
                "Expected inner type to be a PointerType, got {:?}",
                element_types[1]
            );
        }
        #[cfg(feature = "llvm-15-or-greater")]
        assert!(matches!(
            element_types[1].as_ref(),
            Type::PointerType { .. }
        ));
    } else {
        panic!(
            "Expected NodeA inner type to be a StructType, got {:?}",
            aty
        );
    }
    if let Type::StructType { element_types, .. } = bty_inner.as_ref() {
        assert_eq!(element_types.len(), 2);
        assert_eq!(element_types[0], module.types.i32());
        #[cfg(feature = "llvm-14-or-lower")]
        if let Type::PointerType { pointee_type, .. } = element_types[1].as_ref() {
            if let Type::NamedStructType { name } = pointee_type.as_ref() {
                assert_eq!(name, &struct_name_a);
            } else {
                panic!(
                    "Expected pointee type to be a NamedStructType, got {:?}",
                    pointee_type.as_ref()
                );
            }
        } else {
            panic!(
                "Expected inner type to be a PointerType, got {:?}",
                element_types[1]
            );
        }
        #[cfg(feature = "llvm-15-or-greater")]
        assert!(matches!(
            element_types[1].as_ref(),
            Type::PointerType { .. }
        ));
    } else {
        panic!(
            "Expected NodeB inner type to be a StructType, got {:?}",
            bty
        );
    }

    let func = module
        .get_func_by_name("indirectly_recursive_type")
        .expect("Failed to find function");
    let alloca_a: &instruction::Alloca = &func.basic_blocks[0].instrs[1]
        .clone()
        .try_into()
        .expect("Should be an alloca");
    let alloca_b: &instruction::Alloca = &func.basic_blocks[0].instrs[2]
        .clone()
        .try_into()
        .expect("Should be an alloca");
    if let Type::NamedStructType { name } = alloca_a.allocated_type.as_ref() {
        assert_eq!(name, &struct_name_a);
    } else {
        panic!(
            "Expected alloca_a.allocated_type to be a NamedStructType, got {:?}",
            alloca_a.allocated_type
        );
    }
    if let Type::NamedStructType { name } = alloca_b.allocated_type.as_ref() {
        assert_eq!(name, &struct_name_b);
    } else {
        panic!(
            "Expected alloca_b.allocated_type to be a NamedStructType, got {:?}",
            alloca_b.allocated_type
        );
    }
    assert_eq!(&alloca_a.to_string(), "%3 = alloca %struct.NodeA, align 8");
    assert_eq!(&alloca_b.to_string(), "%4 = alloca %struct.NodeB, align 8");
}

#[test]
fn param_and_func_attributes() {
    let _ = env_logger::builder().is_test(true).try_init(); // capture log messages with test harness
    let path = llvm_bc_dir().join("param_and_func_attributes.ll.bc");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");

    // Return attributes
    let zeroext_fn = module.get_func_by_name("f.zeroext").unwrap();
    assert_eq!(zeroext_fn.return_attributes.len(), 1);
    assert_eq!(zeroext_fn.return_attributes[0], ParameterAttribute::ZeroExt);
    let signext_fn = module.get_func_by_name("f.signext").unwrap();
    assert_eq!(signext_fn.return_attributes.len(), 1);
    assert_eq!(signext_fn.return_attributes[0], ParameterAttribute::SignExt);
    let inreg_fn = module.get_func_by_name("f.inreg").unwrap();
    assert_eq!(inreg_fn.return_attributes.len(), 1);
    assert_eq!(inreg_fn.return_attributes[0], ParameterAttribute::InReg);
    let noalias_fn = module.get_func_by_name("f.noalias").unwrap();
    assert_eq!(noalias_fn.return_attributes.len(), 1);
    assert_eq!(noalias_fn.return_attributes[0], ParameterAttribute::NoAlias);
    let nonnull_fn = module.get_func_by_name("f.nonnull").unwrap();
    assert_eq!(nonnull_fn.return_attributes.len(), 1);
    assert_eq!(nonnull_fn.return_attributes[0], ParameterAttribute::NonNull);
    let deref4_fn = module.get_func_by_name("f.dereferenceable4").unwrap();
    assert_eq!(deref4_fn.return_attributes.len(), 1);
    assert_eq!(
        deref4_fn.return_attributes[0],
        ParameterAttribute::Dereferenceable(4)
    );
    let deref8_fn = module.get_func_by_name("f.dereferenceable8").unwrap();
    assert_eq!(deref8_fn.return_attributes.len(), 1);
    assert_eq!(
        deref8_fn.return_attributes[0],
        ParameterAttribute::Dereferenceable(8)
    );
    let deref4ornull_fn = module
        .get_func_by_name("f.dereferenceable4_or_null")
        .unwrap();
    assert_eq!(deref4ornull_fn.return_attributes.len(), 1);
    assert_eq!(
        deref4ornull_fn.return_attributes[0],
        ParameterAttribute::DereferenceableOrNull(4)
    );
    let deref8ornull_fn = module
        .get_func_by_name("f.dereferenceable8_or_null")
        .unwrap();
    assert_eq!(deref8ornull_fn.return_attributes.len(), 1);
    assert_eq!(
        deref8ornull_fn.return_attributes[0],
        ParameterAttribute::DereferenceableOrNull(8)
    );

    // Parameter attributes
    let f = module.get_func_by_name("f.param.zeroext").unwrap();
    assert_eq!(f.parameters.len(), 1);
    let param = &f.parameters[0];
    assert_eq!(param.attributes.len(), 1);
    assert_eq!(param.attributes[0], ParameterAttribute::ZeroExt);
    let f = module.get_func_by_name("f.param.signext").unwrap();
    assert_eq!(f.parameters.len(), 1);
    let param = &f.parameters[0];
    assert_eq!(param.attributes.len(), 1);
    assert_eq!(param.attributes[0], ParameterAttribute::SignExt);
    let f = module.get_func_by_name("f.param.inreg").unwrap();
    assert_eq!(f.parameters.len(), 1);
    let param = &f.parameters[0];
    assert_eq!(param.attributes.len(), 1);
    assert_eq!(param.attributes[0], ParameterAttribute::InReg);
    let f = module.get_func_by_name("f.param.byval").unwrap();
    assert_eq!(f.parameters.len(), 1);
    let param = &f.parameters[0];
    assert_eq!(param.attributes.len(), 1);
    #[cfg(feature = "llvm-11-or-lower")]
    assert_eq!(param.attributes[0], ParameterAttribute::UnknownAttribute);
    #[cfg(feature = "llvm-12-or-greater")]
    match &param.attributes[0] {
        ParameterAttribute::ByVal(ty) => match ty.as_ref() {
            Type::StructType {
                element_types,
                is_packed: false,
            } => {
                assert_eq!(element_types.len(), 2);
            },
            ty => panic!("Expected a StructType with is_packed=false, got {:?}", ty),
        },
        attr => panic!("Expected a ByVal, got {:?}", attr),
    }
    let f = module.get_func_by_name("f.param.inalloca").unwrap();
    assert_eq!(f.parameters.len(), 1);
    let param = &f.parameters[0];
    assert_eq!(param.attributes.len(), 1);
    #[cfg(feature = "llvm-12-or-lower")]
    assert_eq!(param.attributes[0], ParameterAttribute::InAlloca);
    #[cfg(feature = "llvm-13-or-greater")]
    match &param.attributes[0] {
        ParameterAttribute::InAlloca(ty) => match ty.as_ref() {
            Type::IntegerType { bits: 8 } => {},
            ty => panic!("Expected i8, got {:?}", ty),
        },
        attr => panic!("Expected an InAlloca, got {:?}", attr),
    }
    let f = module.get_func_by_name("f.param.sret").unwrap();
    assert_eq!(f.parameters.len(), 1);
    let param = &f.parameters[0];
    assert_eq!(param.attributes.len(), 1);
    #[cfg(feature = "llvm-11-or-lower")]
    assert_eq!(param.attributes[0], ParameterAttribute::SRet);
    #[cfg(feature = "llvm-12-or-greater")]
    match &param.attributes[0] {
        ParameterAttribute::SRet(ty) => match ty.as_ref() {
            Type::IntegerType { bits: 8 } => {},
            ty => panic!("Expected i8, got {:?}", ty),
        },
        attr => panic!("Expected an SRet, got {:?}", attr),
    }
    let f = module.get_func_by_name("f.param.noalias").unwrap();
    assert_eq!(f.parameters.len(), 1);
    let param = &f.parameters[0];
    assert_eq!(param.attributes.len(), 1);
    assert_eq!(param.attributes[0], ParameterAttribute::NoAlias);
    let f = module.get_func_by_name("f.param.nocapture").unwrap();
    assert_eq!(f.parameters.len(), 1);
    let param = &f.parameters[0];
    assert_eq!(param.attributes.len(), 1);
    assert_eq!(param.attributes[0], ParameterAttribute::NoCapture);
    let f = module.get_func_by_name("f.param.nest").unwrap();
    assert_eq!(f.parameters.len(), 1);
    let param = &f.parameters[0];
    assert_eq!(param.attributes.len(), 1);
    assert_eq!(param.attributes[0], ParameterAttribute::Nest);
    let f = module.get_func_by_name("f.param.returned").unwrap();
    assert_eq!(f.parameters.len(), 1);
    let param = &f.parameters[0];
    assert_eq!(param.attributes.len(), 1);
    assert_eq!(param.attributes[0], ParameterAttribute::Returned);
    let f = module.get_func_by_name("f.param.nonnull").unwrap();
    assert_eq!(f.parameters.len(), 1);
    let param = &f.parameters[0];
    assert_eq!(param.attributes.len(), 1);
    assert_eq!(param.attributes[0], ParameterAttribute::NonNull);
    let f = module.get_func_by_name("f.param.dereferenceable").unwrap();
    assert_eq!(f.parameters.len(), 1);
    let param = &f.parameters[0];
    assert_eq!(param.attributes.len(), 1);
    assert_eq!(param.attributes[0], ParameterAttribute::Dereferenceable(4));
    let f = module
        .get_func_by_name("f.param.dereferenceable_or_null")
        .unwrap();
    assert_eq!(f.parameters.len(), 1);
    let param = &f.parameters[0];
    assert_eq!(param.attributes.len(), 1);
    assert_eq!(
        param.attributes[0],
        ParameterAttribute::DereferenceableOrNull(4)
    );

    // Function attributes
    let f = module.get_func_by_name("f.alignstack4").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::AlignStack(4));
    let f = module.get_func_by_name("f.alignstack8").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::AlignStack(8));
    let f = module.get_func_by_name("f.alwaysinline").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::AlwaysInline);
    let f = module.get_func_by_name("f.cold").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::Cold);
    let f = module.get_func_by_name("f.convergent").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::Convergent);
    let f = module.get_func_by_name("f.inlinehint").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::InlineHint);
    let f = module.get_func_by_name("f.jumptable").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::JumpTable);
    let f = module.get_func_by_name("f.minsize").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::MinimizeSize);
    let f = module.get_func_by_name("f.naked").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::Naked);
    let f = module.get_func_by_name("f.nobuiltin").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::NoBuiltin);
    let f = module.get_func_by_name("f.noduplicate").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::NoDuplicate);
    let f = module.get_func_by_name("f.noimplicitfloat").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::NoImplicitFloat);
    let f = module.get_func_by_name("f.nonlazybind").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::NonLazyBind);
    let f = module.get_func_by_name("f.noredzone").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::NoRedZone);
    let f = module.get_func_by_name("f.noreturn").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::NoReturn);
    let f = module.get_func_by_name("f.nounwind").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::NoUnwind);
    let f = module.get_func_by_name("f.optnone").unwrap();
    assert_eq!(f.function_attributes.len(), 2);
    assert_eq!(f.function_attributes[0], FunctionAttribute::NoInline);
    assert_eq!(f.function_attributes[1], FunctionAttribute::OptNone);
    let f = module.get_func_by_name("f.optsize").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::OptSize);
    let f = module.get_func_by_name("f.readnone").unwrap();
    assert_eq!(f.function_attributes.len(), 1);

    // LLVM 16 no longer has the ReadNone attribute
    #[cfg(feature="llvm-15-or-lower")]
    assert_eq!(f.function_attributes[0], FunctionAttribute::ReadNone);

    let f = module.get_func_by_name("f.readonly").unwrap();
    assert_eq!(f.function_attributes.len(), 1);

    // LLVM 16 no longer has the ReadOnly attribute
    #[cfg(feature="llvm-15-or-lower")]
    assert_eq!(f.function_attributes[0], FunctionAttribute::ReadOnly);

    let f = module.get_func_by_name("f.returns_twice").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::ReturnsTwice);
    let f = module.get_func_by_name("f.safestack").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::SafeStack);
    let f = module.get_func_by_name("f.sanitize_address").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::SanitizeAddress);
    let f = module.get_func_by_name("f.sanitize_memory").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::SanitizeMemory);
    let f = module.get_func_by_name("f.sanitize_thread").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::SanitizeThread);
    let f = module.get_func_by_name("f.ssp").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::StackProtect);
    let f = module.get_func_by_name("f.sspreq").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::StackProtectReq);
    let f = module.get_func_by_name("f.sspstrong").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(
        f.function_attributes[0],
        FunctionAttribute::StackProtectStrong
    );
    let f = module.get_func_by_name("f.thunk").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(
        f.function_attributes[0],
        FunctionAttribute::StringAttribute {
            kind: "thunk".into(),
            value: "".into()
        }
    );
    let f = module.get_func_by_name("f.uwtable").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::UWTable);
    let f = module.get_func_by_name("f.kvpair").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(
        f.function_attributes[0],
        FunctionAttribute::StringAttribute {
            kind: "cpu".into(),
            value: "cortex-a8".into()
        }
    );
    let f = module.get_func_by_name("f.norecurse").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::NoRecurse);
    let f = module.get_func_by_name("f.inaccessiblememonly").unwrap();
    assert_eq!(f.function_attributes.len(), 1);

    // LLVM 16 no longer has InaccessibleMemOnly attribute
    #[cfg(feature="llvm-15-or-lower")]
    assert_eq!(
        f.function_attributes[0],
        FunctionAttribute::InaccessibleMemOnly
    );

    let f = module
        .get_func_by_name("f.inaccessiblemem_or_argmemonly")
        .unwrap();
    assert_eq!(f.function_attributes.len(), 1);

    // LLVM 16 no longer has InaccessibleMemOrArgMemOnly attribute
    #[cfg(feature="llvm-15-or-lower")]
    assert_eq!(
        f.function_attributes[0],
        FunctionAttribute::InaccessibleMemOrArgMemOnly
    );

    let f = module.get_func_by_name("f.strictfp").unwrap();
    assert_eq!(f.function_attributes.len(), 1);
    assert_eq!(f.function_attributes[0], FunctionAttribute::StrictFP);

    // Test the memory(...) attribute that's in LLVM 16+
    #[cfg(feature = "llvm-16-or-greater")]
    {
        let f = module.get_func_by_name("f.default_none").unwrap();
        assert_eq!(f.function_attributes.len(), 1);
        assert_eq!(f.function_attributes[0], FunctionAttribute::Memory {
            default: MemoryEffect::None,
            argmem: MemoryEffect::None,
            inaccessible_mem: MemoryEffect::None
        });

        let f = module.get_func_by_name("f.default_read").unwrap();
        assert_eq!(f.function_attributes.len(), 1);
        assert_eq!(f.function_attributes[0], FunctionAttribute::Memory {
            default: MemoryEffect::Read,
            argmem: MemoryEffect::Read,
            inaccessible_mem: MemoryEffect::Read
        });

        let f = module.get_func_by_name("f.default_write").unwrap();
        assert_eq!(f.function_attributes.len(), 1);
        assert_eq!(f.function_attributes[0], FunctionAttribute::Memory {
            default: MemoryEffect::Write,
            argmem: MemoryEffect::Write,
            inaccessible_mem: MemoryEffect::Write
        });

        let f = module.get_func_by_name("f.default_readwrite").unwrap();
        assert_eq!(f.function_attributes.len(), 1);
        assert_eq!(f.function_attributes[0], FunctionAttribute::Memory {
            default: MemoryEffect::ReadWrite,
            argmem: MemoryEffect::ReadWrite,
            inaccessible_mem: MemoryEffect::ReadWrite
        });

        let f = module.get_func_by_name("f.default_none_arg_readwrite").unwrap();
        assert_eq!(f.function_attributes.len(), 1);
        assert_eq!(f.function_attributes[0], FunctionAttribute::Memory {
            default: MemoryEffect::None,
            argmem: MemoryEffect::ReadWrite,
            inaccessible_mem: MemoryEffect::None
        });

        let f = module.get_func_by_name("f.default_readwrite_arg_none").unwrap();
        assert_eq!(f.function_attributes.len(), 1);
        assert_eq!(f.function_attributes[0], FunctionAttribute::Memory {
            default: MemoryEffect::ReadWrite,
            argmem: MemoryEffect::None,
            inaccessible_mem: MemoryEffect::ReadWrite
        });

        let f = module.get_func_by_name("f.arg_read").unwrap();
        assert_eq!(f.function_attributes.len(), 1);
        assert_eq!(f.function_attributes[0], FunctionAttribute::Memory {
            default: MemoryEffect::None,
            argmem: MemoryEffect::Read,
            inaccessible_mem: MemoryEffect::None
        });

        let f = module.get_func_by_name("f.inaccessiblemem_read").unwrap();
        assert_eq!(f.function_attributes.len(), 1);
        assert_eq!(f.function_attributes[0], FunctionAttribute::Memory {
            default: MemoryEffect::None,
            argmem: MemoryEffect::None,
            inaccessible_mem: MemoryEffect::Read
        });

        let f = module.get_func_by_name("f.default_read_inaccessiblemem_write_arg_none").unwrap();
        assert_eq!(f.function_attributes.len(), 1);
        assert_eq!(f.function_attributes[0], FunctionAttribute::Memory {
            default: MemoryEffect::Read,
            argmem: MemoryEffect::None,
            inaccessible_mem: MemoryEffect::Write
        });
    }
}

#[cfg(feature = "llvm-11-or-greater")]
#[test]
fn float_types() {
    init_logging();
    let path = llvm_bc_dir().join("float_types.bc");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");

    let f = module.get_func_by_name("takes_half").unwrap();
    assert_eq!(
        module.type_of(f.parameters.get(0).unwrap()),
        module.types.fp(FPType::Half)
    );
    let f = module.get_func_by_name("takes_bfloat").unwrap();
    assert_eq!(
        module.type_of(f.parameters.get(0).unwrap()),
        module.types.fp(FPType::BFloat)
    );
    let f = module.get_func_by_name("takes_float").unwrap();
    assert_eq!(
        module.type_of(f.parameters.get(0).unwrap()),
        module.types.fp(FPType::Single)
    );
    let f = module.get_func_by_name("takes_double").unwrap();
    assert_eq!(
        module.type_of(f.parameters.get(0).unwrap()),
        module.types.fp(FPType::Double)
    );
    let f = module.get_func_by_name("takes_fp128").unwrap();
    assert_eq!(
        module.type_of(f.parameters.get(0).unwrap()),
        module.types.fp(FPType::FP128)
    );
    let f = module.get_func_by_name("takes_x86_fp80").unwrap();
    assert_eq!(
        module.type_of(f.parameters.get(0).unwrap()),
        module.types.fp(FPType::X86_FP80)
    );
    let f = module.get_func_by_name("takes_ppc_fp128").unwrap();
    assert_eq!(
        module.type_of(f.parameters.get(0).unwrap()),
        module.types.fp(FPType::PPC_FP128)
    );

    let f = module.get_func_by_name("returns_half").unwrap();
    #[cfg(feature = "llvm-14-or-lower")]
    assert_eq!(
        f.return_type,
        module.types.pointer_to(module.types.fp(FPType::Half))
    );
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(f.return_type, module.types.pointer());
    let f = module.get_func_by_name("returns_bfloat").unwrap();
    #[cfg(feature = "llvm-14-or-lower")]
    assert_eq!(
        f.return_type,
        module.types.pointer_to(module.types.fp(FPType::BFloat))
    );
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(f.return_type, module.types.pointer());
    let f = module.get_func_by_name("returns_float").unwrap();
    #[cfg(feature = "llvm-14-or-lower")]
    assert_eq!(
        f.return_type,
        module.types.pointer_to(module.types.fp(FPType::Single))
    );
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(f.return_type, module.types.pointer());
    let f = module.get_func_by_name("returns_double").unwrap();
    #[cfg(feature = "llvm-14-or-lower")]
    assert_eq!(
        f.return_type,
        module.types.pointer_to(module.types.fp(FPType::Double))
    );
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(f.return_type, module.types.pointer());
    let f = module.get_func_by_name("returns_fp128").unwrap();
    #[cfg(feature = "llvm-14-or-lower")]
    assert_eq!(
        f.return_type,
        module.types.pointer_to(module.types.fp(FPType::FP128))
    );
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(f.return_type, module.types.pointer());
    let f = module.get_func_by_name("returns_x86_fp80").unwrap();
    #[cfg(feature = "llvm-14-or-lower")]
    assert_eq!(
        f.return_type,
        module.types.pointer_to(module.types.fp(FPType::X86_FP80))
    );
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(f.return_type, module.types.pointer());
    let f = module.get_func_by_name("returns_ppc_fp128").unwrap();
    #[cfg(feature = "llvm-14-or-lower")]
    assert_eq!(
        f.return_type,
        module.types.pointer_to(module.types.fp(FPType::PPC_FP128))
    );
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(f.return_type, module.types.pointer());
}

#[test]
fn datalayouts() {
    init_logging();
    let path = llvm_bc_dir().join("hello.bc");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");
    let data_layout = &module.data_layout;

    // Data layout changed from Clang 17 to 18, even w/ an explicit --target=x86_64-apple-macosx12.0.0
    #[cfg(feature = "llvm-18-or-greater")]
    {
        assert_eq!(
            &data_layout.layout_str,
            "e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
        );
        assert_eq!(&data_layout.endianness, &Endianness::LittleEndian);
        assert_eq!(&data_layout.mangling, &Some(Mangling::MachO));
        assert_eq!(
            data_layout.alignments.ptr_alignment(270),
            &PointerLayout {
                size: 32,
                alignment: Alignment { abi: 32, pref: 32 },
                index_size: 32
            }
        );
        assert_eq!(
            data_layout.alignments.ptr_alignment(271),
            &PointerLayout {
                size: 32,
                alignment: Alignment { abi: 32, pref: 32 },
                index_size: 32
            }
        );
        assert_eq!(
            data_layout.alignments.ptr_alignment(272),
            &PointerLayout {
                size: 64,
                alignment: Alignment { abi: 64, pref: 64 },
                index_size: 64
            }
        );
        assert_eq!(
            data_layout.alignments.ptr_alignment(0),
            &PointerLayout {
                size: 64,
                alignment: Alignment { abi: 64, pref: 64 },
                index_size: 64
            }
        );
        assert_eq!(
            data_layout.alignments.ptr_alignment(33),
            &PointerLayout {
                size: 64,
                alignment: Alignment { abi: 64, pref: 64 },
                index_size: 64
            }
        );
        assert_eq!(
            data_layout.alignments.int_alignment(64),
            &Alignment { abi: 64, pref: 64 }
        );
        assert_eq!(
            data_layout.alignments.int_alignment(7),
            &Alignment { abi: 8, pref: 8 }
        );
        assert_eq!(
            data_layout.alignments.int_alignment(26),
            &Alignment { abi: 32, pref: 32 }
        );
        assert_eq!(
            data_layout.alignments.int_alignment(123456),
            &Alignment { abi: 128, pref: 128 }
        );
        assert_eq!(
            data_layout.alignments.fp_alignment(FPType::Double),
            &Alignment { abi: 64, pref: 64 }
        );
        assert_eq!(
            data_layout.alignments.fp_alignment(FPType::X86_FP80),
            &Alignment {
                abi: 128,
                pref: 128
            }
        );
        assert_eq!(
            data_layout
                .native_int_widths
                .as_ref()
                .unwrap()
                .iter()
                .copied()
                .sorted()
                .collect::<Vec<_>>(),
            vec![8, 16, 32, 64]
        );
        assert_eq!(data_layout.stack_alignment, Some(128));
    }

    #[cfg(all(feature = "llvm-10-or-greater", feature = "llvm-17-or-lower"))]
    {
        assert_eq!(
            &data_layout.layout_str,
            "e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
        );
        assert_eq!(&data_layout.endianness, &Endianness::LittleEndian);
        assert_eq!(&data_layout.mangling, &Some(Mangling::MachO));
        assert_eq!(
            data_layout.alignments.ptr_alignment(270),
            &PointerLayout {
                size: 32,
                alignment: Alignment { abi: 32, pref: 32 },
                index_size: 32
            }
        );
        assert_eq!(
            data_layout.alignments.ptr_alignment(271),
            &PointerLayout {
                size: 32,
                alignment: Alignment { abi: 32, pref: 32 },
                index_size: 32
            }
        );
        assert_eq!(
            data_layout.alignments.ptr_alignment(272),
            &PointerLayout {
                size: 64,
                alignment: Alignment { abi: 64, pref: 64 },
                index_size: 64
            }
        );
        assert_eq!(
            data_layout.alignments.ptr_alignment(0),
            &PointerLayout {
                size: 64,
                alignment: Alignment { abi: 64, pref: 64 },
                index_size: 64
            }
        );
        assert_eq!(
            data_layout.alignments.ptr_alignment(33),
            &PointerLayout {
                size: 64,
                alignment: Alignment { abi: 64, pref: 64 },
                index_size: 64
            }
        );
        assert_eq!(
            data_layout.alignments.int_alignment(64),
            &Alignment { abi: 64, pref: 64 }
        );
        assert_eq!(
            data_layout.alignments.int_alignment(7),
            &Alignment { abi: 8, pref: 8 }
        );
        assert_eq!(
            data_layout.alignments.int_alignment(26),
            &Alignment { abi: 32, pref: 32 }
        );
        assert_eq!(
            data_layout.alignments.int_alignment(123456),
            &Alignment { abi: 64, pref: 64 }
        );
        assert_eq!(
            data_layout.alignments.fp_alignment(FPType::Double),
            &Alignment { abi: 64, pref: 64 }
        );
        assert_eq!(
            data_layout.alignments.fp_alignment(FPType::X86_FP80),
            &Alignment {
                abi: 128,
                pref: 128
            }
        );
        assert_eq!(
            data_layout
                .native_int_widths
                .as_ref()
                .unwrap()
                .iter()
                .copied()
                .sorted()
                .collect::<Vec<_>>(),
            vec![8, 16, 32, 64]
        );
        assert_eq!(data_layout.stack_alignment, Some(128));
    }
    #[cfg(feature = "llvm-9-or-lower")]
    {
        assert_eq!(
            &data_layout.layout_str,
            "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
        );
        assert_eq!(&data_layout.endianness, &Endianness::LittleEndian);
        assert_eq!(&data_layout.mangling, &Some(Mangling::MachO));
        assert_eq!(
            data_layout.alignments.ptr_alignment(0),
            &PointerLayout {
                size: 64,
                alignment: Alignment { abi: 64, pref: 64 },
                index_size: 64
            }
        );
        assert_eq!(
            data_layout.alignments.ptr_alignment(33),
            &PointerLayout {
                size: 64,
                alignment: Alignment { abi: 64, pref: 64 },
                index_size: 64
            }
        );
        assert_eq!(
            data_layout.alignments.int_alignment(64),
            &Alignment { abi: 64, pref: 64 }
        );
        assert_eq!(
            data_layout.alignments.int_alignment(7),
            &Alignment { abi: 8, pref: 8 }
        );
        assert_eq!(
            data_layout.alignments.int_alignment(26),
            &Alignment { abi: 32, pref: 32 }
        );
        assert_eq!(
            data_layout.alignments.int_alignment(123456),
            &Alignment { abi: 64, pref: 64 }
        );
        assert_eq!(
            data_layout.alignments.fp_alignment(FPType::Double),
            &Alignment { abi: 64, pref: 64 }
        );
        assert_eq!(
            data_layout.alignments.fp_alignment(FPType::X86_FP80),
            &Alignment {
                abi: 128,
                pref: 128
            }
        );
        assert_eq!(
            data_layout
                .native_int_widths
                .as_ref()
                .unwrap()
                .iter()
                .copied()
                .sorted()
                .collect::<Vec<_>>(),
            vec![8, 16, 32, 64]
        );
        assert_eq!(data_layout.stack_alignment, Some(128));
    }

    assert_eq!(
        data_layout.alignments.type_alignment(&module.types.int(26)),
        &Alignment { abi: 32, pref: 32 }
    );
    #[cfg(feature = "llvm-14-or-lower")]
    assert_eq!(
        data_layout
            .alignments
            .type_alignment(&module.types.pointer_in_addr_space(module.types.int(32), 2)),
        &Alignment { abi: 64, pref: 64 }
    );
    #[cfg(feature = "llvm-15-or-greater")]
    assert_eq!(
        data_layout
            .alignments
            .type_alignment(&module.types.pointer_in_addr_space(2)),
        &Alignment { abi: 64, pref: 64 }
    );
    #[cfg(feature = "llvm-14-or-lower")]
    assert_eq!(
        data_layout
            .alignments
            .type_alignment(&module.types.pointer_to(module.types.func_type(
                module.types.void(),
                vec![],
                false
            ))),
        &Alignment { abi: 64, pref: 64 }
    );
}

#[test]
fn throw() {
    let _ = env_logger::builder().is_test(true).try_init(); // capture log messages with test harness
    let path = cxx_llvm_bc_dir().join("throw.bc");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");

    // See https://github.com/cdisselkoen/llvm-ir/pull/30
    for func in module.functions {
        for block in func.basic_blocks {
            if let Terminator::Invoke(i) = block.term {
                i.get_type(&module.types);
            }
        }
    }
}

/*
#[test]
fn fences() {
    init_logging();
    let path = llvm_bc_dir().join("fences.ll.bc");
    let module = Module::from_bc_path(&path).expect("Failed to parse module");
    let f = module.get_func_by_name("fences").unwrap();
    let block = &f.basic_blocks[0];
    let seq_cst: &instruction::Fence = &block.instrs[0].clone().try_into().expect("Should be a fence");
    assert_eq!(seq_cst.atomicity.mem_ordering, MemoryOrdering::SequentiallyConsistent);
    let acq: &instruction::Fence = &block.instrs[1].clone().try_into().expect("Should be a fence");
    assert_eq!(acq.atomicity.mem_ordering, MemoryOrdering::Acquire);
    let rel: &instruction::Fence = &block.instrs[2].clone().try_into().expect("Should be a fence");
    assert_eq!(rel.atomicity.mem_ordering, MemoryOrdering::Release);
    let acq_rel: &instruction::Fence = &block.instrs[3].clone().try_into().expect("Should be a fence");
    assert_eq!(acq_rel.atomicity.mem_ordering, MemoryOrdering::AcquireRelease);
    let syncscope: &instruction::Fence = &block.instrs[4].clone().try_into().expect("Should be a fence");
    assert_eq!(syncscope.atomicity.mem_ordering, MemoryOrdering::SequentiallyConsistent);
    assert_eq!(syncscope.atomicity.synch_scope, SynchronizationScope::SingleThread);
}
*/

#[test]
fn parseir() -> Result<(), Box<dyn std::error::Error>> {
    let ir = "define void @f() { ret void }";

    let module = Module::from_ir_str(ir)?;
    assert_eq!(module.functions.len(), 1);
    let func = &module.functions[0];
    assert_eq!(func.name, "f");
    assert_eq!(func.parameters.len(), 0);
    assert_eq!(func.is_var_arg, false);
    assert_eq!(func.return_type, module.types.void());
    assert_eq!(func.basic_blocks.len(), 1);
    let bb = &func.basic_blocks[0];
    assert_eq!(bb.name, Name::Number(0));
    assert_eq!(bb.instrs.len(), 0);
    let ret: &terminator::Ret = &bb
        .term
        .clone()
        .try_into()
        .unwrap_or_else(|_| panic!("Terminator should be a Ret but is {:?}", &bb.term));
    assert_eq!(
        ret.return_operand,
        None
    );
    assert_eq!(&ret.to_string(), "ret void");

    // this file was compiled without debuginfo, so nothing should have a debugloc
    assert_eq!(func.debugloc, None);
    assert_eq!(ret.debugloc, None);
    Ok(())
}