aboutsummaryrefslogtreecommitdiff
path: root/src/type.zig
blob: 5a94f9c57a63ebef6312d6a04f303a7ca04412b3 (plain)
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
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
const std = @import("std");
const builtin = @import("builtin");
const Value = @import("value.zig").Value;
const assert = std.debug.assert;
const Target = std.Target;
const Module = @import("Module.zig");
const log = std.log.scoped(.Type);
const target_util = @import("target.zig");
const TypedValue = @import("TypedValue.zig");
const Sema = @import("Sema.zig");
const InternPool = @import("InternPool.zig");
const Alignment = InternPool.Alignment;

/// Both types and values are canonically represented by a single 32-bit integer
/// which is an index into an `InternPool` data structure.
/// This struct abstracts around this storage by providing methods only
/// applicable to types rather than values in general.
pub const Type = struct {
    ip_index: InternPool.Index,

    pub fn zigTypeTag(ty: Type, mod: *const Module) std.builtin.TypeId {
        return ty.zigTypeTagOrPoison(mod) catch unreachable;
    }

    pub fn zigTypeTagOrPoison(ty: Type, mod: *const Module) error{GenericPoison}!std.builtin.TypeId {
        return mod.intern_pool.zigTypeTagOrPoison(ty.toIntern());
    }

    pub fn baseZigTypeTag(self: Type, mod: *Module) std.builtin.TypeId {
        return switch (self.zigTypeTag(mod)) {
            .ErrorUnion => self.errorUnionPayload(mod).baseZigTypeTag(mod),
            .Optional => {
                return self.optionalChild(mod).baseZigTypeTag(mod);
            },
            else => |t| t,
        };
    }

    pub fn isSelfComparable(ty: Type, mod: *const Module, is_equality_cmp: bool) bool {
        return switch (ty.zigTypeTag(mod)) {
            .Int,
            .Float,
            .ComptimeFloat,
            .ComptimeInt,
            => true,

            .Vector => ty.elemType2(mod).isSelfComparable(mod, is_equality_cmp),

            .Bool,
            .Type,
            .Void,
            .ErrorSet,
            .Fn,
            .Opaque,
            .AnyFrame,
            .Enum,
            .EnumLiteral,
            => is_equality_cmp,

            .NoReturn,
            .Array,
            .Struct,
            .Undefined,
            .Null,
            .ErrorUnion,
            .Union,
            .Frame,
            => false,

            .Pointer => !ty.isSlice(mod) and (is_equality_cmp or ty.isCPtr(mod)),
            .Optional => {
                if (!is_equality_cmp) return false;
                return ty.optionalChild(mod).isSelfComparable(mod, is_equality_cmp);
            },
        };
    }

    /// If it is a function pointer, returns the function type. Otherwise returns null.
    pub fn castPtrToFn(ty: Type, mod: *const Module) ?Type {
        if (ty.zigTypeTag(mod) != .Pointer) return null;
        const elem_ty = ty.childType(mod);
        if (elem_ty.zigTypeTag(mod) != .Fn) return null;
        return elem_ty;
    }

    /// Asserts the type is a pointer.
    pub fn ptrIsMutable(ty: Type, mod: *const Module) bool {
        return !mod.intern_pool.indexToKey(ty.toIntern()).ptr_type.flags.is_const;
    }

    pub const ArrayInfo = struct {
        elem_type: Type,
        sentinel: ?Value = null,
        len: u64,
    };

    pub fn arrayInfo(self: Type, mod: *const Module) ArrayInfo {
        return .{
            .len = self.arrayLen(mod),
            .sentinel = self.sentinel(mod),
            .elem_type = self.childType(mod),
        };
    }

    pub fn ptrInfo(ty: Type, mod: *const Module) InternPool.Key.PtrType {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .ptr_type => |p| p,
            .opt_type => |child| switch (mod.intern_pool.indexToKey(child)) {
                .ptr_type => |p| p,
                else => unreachable,
            },
            else => unreachable,
        };
    }

    pub fn eql(a: Type, b: Type, mod: *const Module) bool {
        _ = mod; // TODO: remove this parameter
        // The InternPool data structure hashes based on Key to make interned objects
        // unique. An Index can be treated simply as u32 value for the
        // purpose of Type/Value hashing and equality.
        return a.toIntern() == b.toIntern();
    }

    pub fn format(ty: Type, comptime unused_fmt_string: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
        _ = ty;
        _ = unused_fmt_string;
        _ = options;
        _ = writer;
        @compileError("do not format types directly; use either ty.fmtDebug() or ty.fmt()");
    }

    pub fn fmt(ty: Type, module: *Module) std.fmt.Formatter(format2) {
        return .{ .data = .{
            .ty = ty,
            .module = module,
        } };
    }

    const FormatContext = struct {
        ty: Type,
        module: *Module,
    };

    fn format2(
        ctx: FormatContext,
        comptime unused_format_string: []const u8,
        options: std.fmt.FormatOptions,
        writer: anytype,
    ) !void {
        comptime assert(unused_format_string.len == 0);
        _ = options;
        return print(ctx.ty, writer, ctx.module);
    }

    pub fn fmtDebug(ty: Type) std.fmt.Formatter(dump) {
        return .{ .data = ty };
    }

    /// This is a debug function. In order to print types in a meaningful way
    /// we also need access to the module.
    pub fn dump(
        start_type: Type,
        comptime unused_format_string: []const u8,
        options: std.fmt.FormatOptions,
        writer: anytype,
    ) @TypeOf(writer).Error!void {
        _ = options;
        comptime assert(unused_format_string.len == 0);
        return writer.print("{any}", .{start_type.ip_index});
    }

    /// Prints a name suitable for `@typeName`.
    pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void {
        const ip = &mod.intern_pool;
        switch (ip.indexToKey(ty.toIntern())) {
            .int_type => |int_type| {
                const sign_char: u8 = switch (int_type.signedness) {
                    .signed => 'i',
                    .unsigned => 'u',
                };
                return writer.print("{c}{d}", .{ sign_char, int_type.bits });
            },
            .ptr_type => {
                const info = ty.ptrInfo(mod);

                if (info.sentinel != .none) switch (info.flags.size) {
                    .One, .C => unreachable,
                    .Many => try writer.print("[*:{}]", .{info.sentinel.toValue().fmtValue(info.child.toType(), mod)}),
                    .Slice => try writer.print("[:{}]", .{info.sentinel.toValue().fmtValue(info.child.toType(), mod)}),
                } else switch (info.flags.size) {
                    .One => try writer.writeAll("*"),
                    .Many => try writer.writeAll("[*]"),
                    .C => try writer.writeAll("[*c]"),
                    .Slice => try writer.writeAll("[]"),
                }
                if (info.flags.alignment != .none or
                    info.packed_offset.host_size != 0 or
                    info.flags.vector_index != .none)
                {
                    const alignment = if (info.flags.alignment != .none)
                        info.flags.alignment
                    else
                        info.child.toType().abiAlignment(mod);
                    try writer.print("align({d}", .{alignment.toByteUnits(0)});

                    if (info.packed_offset.bit_offset != 0 or info.packed_offset.host_size != 0) {
                        try writer.print(":{d}:{d}", .{
                            info.packed_offset.bit_offset, info.packed_offset.host_size,
                        });
                    }
                    if (info.flags.vector_index == .runtime) {
                        try writer.writeAll(":?");
                    } else if (info.flags.vector_index != .none) {
                        try writer.print(":{d}", .{@intFromEnum(info.flags.vector_index)});
                    }
                    try writer.writeAll(") ");
                }
                if (info.flags.address_space != .generic) {
                    try writer.print("addrspace(.{s}) ", .{@tagName(info.flags.address_space)});
                }
                if (info.flags.is_const) try writer.writeAll("const ");
                if (info.flags.is_volatile) try writer.writeAll("volatile ");
                if (info.flags.is_allowzero and info.flags.size != .C) try writer.writeAll("allowzero ");

                try print(info.child.toType(), writer, mod);
                return;
            },
            .array_type => |array_type| {
                if (array_type.sentinel == .none) {
                    try writer.print("[{d}]", .{array_type.len});
                    try print(array_type.child.toType(), writer, mod);
                } else {
                    try writer.print("[{d}:{}]", .{
                        array_type.len,
                        array_type.sentinel.toValue().fmtValue(array_type.child.toType(), mod),
                    });
                    try print(array_type.child.toType(), writer, mod);
                }
                return;
            },
            .vector_type => |vector_type| {
                try writer.print("@Vector({d}, ", .{vector_type.len});
                try print(vector_type.child.toType(), writer, mod);
                try writer.writeAll(")");
                return;
            },
            .opt_type => |child| {
                try writer.writeByte('?');
                return print(child.toType(), writer, mod);
            },
            .error_union_type => |error_union_type| {
                try print(error_union_type.error_set_type.toType(), writer, mod);
                try writer.writeByte('!');
                try print(error_union_type.payload_type.toType(), writer, mod);
                return;
            },
            .inferred_error_set_type => |func_index| {
                try writer.writeAll("@typeInfo(@typeInfo(@TypeOf(");
                const owner_decl = mod.funcOwnerDeclPtr(func_index);
                try owner_decl.renderFullyQualifiedName(mod, writer);
                try writer.writeAll(")).Fn.return_type.?).ErrorUnion.error_set");
            },
            .error_set_type => |error_set_type| {
                const names = error_set_type.names;
                try writer.writeAll("error{");
                for (names.get(ip), 0..) |name, i| {
                    if (i != 0) try writer.writeByte(',');
                    try writer.print("{}", .{name.fmt(ip)});
                }
                try writer.writeAll("}");
            },
            .simple_type => |s| switch (s) {
                .f16,
                .f32,
                .f64,
                .f80,
                .f128,
                .usize,
                .isize,
                .c_char,
                .c_short,
                .c_ushort,
                .c_int,
                .c_uint,
                .c_long,
                .c_ulong,
                .c_longlong,
                .c_ulonglong,
                .c_longdouble,
                .anyopaque,
                .bool,
                .void,
                .type,
                .anyerror,
                .comptime_int,
                .comptime_float,
                .noreturn,
                .adhoc_inferred_error_set,
                => return writer.writeAll(@tagName(s)),

                .null,
                .undefined,
                => try writer.print("@TypeOf({s})", .{@tagName(s)}),

                .enum_literal => try writer.print("@TypeOf(.{s})", .{@tagName(s)}),
                .atomic_order => try writer.writeAll("std.builtin.AtomicOrder"),
                .atomic_rmw_op => try writer.writeAll("std.builtin.AtomicRmwOp"),
                .calling_convention => try writer.writeAll("std.builtin.CallingConvention"),
                .address_space => try writer.writeAll("std.builtin.AddressSpace"),
                .float_mode => try writer.writeAll("std.builtin.FloatMode"),
                .reduce_op => try writer.writeAll("std.builtin.ReduceOp"),
                .call_modifier => try writer.writeAll("std.builtin.CallModifier"),
                .prefetch_options => try writer.writeAll("std.builtin.PrefetchOptions"),
                .export_options => try writer.writeAll("std.builtin.ExportOptions"),
                .extern_options => try writer.writeAll("std.builtin.ExternOptions"),
                .type_info => try writer.writeAll("std.builtin.Type"),

                .generic_poison => unreachable,
            },
            .struct_type => |struct_type| {
                if (struct_type.decl.unwrap()) |decl_index| {
                    const decl = mod.declPtr(decl_index);
                    try decl.renderFullyQualifiedName(mod, writer);
                } else if (struct_type.namespace.unwrap()) |namespace_index| {
                    const namespace = mod.namespacePtr(namespace_index);
                    try namespace.renderFullyQualifiedName(mod, .empty, writer);
                } else {
                    try writer.writeAll("@TypeOf(.{})");
                }
            },
            .anon_struct_type => |anon_struct| {
                if (anon_struct.types.len == 0) {
                    return writer.writeAll("@TypeOf(.{})");
                }
                try writer.writeAll("struct{");
                for (anon_struct.types.get(ip), anon_struct.values.get(ip), 0..) |field_ty, val, i| {
                    if (i != 0) try writer.writeAll(", ");
                    if (val != .none) {
                        try writer.writeAll("comptime ");
                    }
                    if (anon_struct.names.len != 0) {
                        try writer.print("{}: ", .{anon_struct.names.get(ip)[i].fmt(&mod.intern_pool)});
                    }

                    try print(field_ty.toType(), writer, mod);

                    if (val != .none) {
                        try writer.print(" = {}", .{val.toValue().fmtValue(field_ty.toType(), mod)});
                    }
                }
                try writer.writeAll("}");
            },

            .union_type => |union_type| {
                const decl = mod.declPtr(union_type.decl);
                try decl.renderFullyQualifiedName(mod, writer);
            },
            .opaque_type => |opaque_type| {
                const decl = mod.declPtr(opaque_type.decl);
                try decl.renderFullyQualifiedName(mod, writer);
            },
            .enum_type => |enum_type| {
                const decl = mod.declPtr(enum_type.decl);
                try decl.renderFullyQualifiedName(mod, writer);
            },
            .func_type => |fn_info| {
                if (fn_info.is_noinline) {
                    try writer.writeAll("noinline ");
                }
                try writer.writeAll("fn (");
                const param_types = fn_info.param_types.get(&mod.intern_pool);
                for (param_types, 0..) |param_ty, i| {
                    if (i != 0) try writer.writeAll(", ");
                    if (std.math.cast(u5, i)) |index| {
                        if (fn_info.paramIsComptime(index)) {
                            try writer.writeAll("comptime ");
                        }
                        if (fn_info.paramIsNoalias(index)) {
                            try writer.writeAll("noalias ");
                        }
                    }
                    if (param_ty == .generic_poison_type) {
                        try writer.writeAll("anytype");
                    } else {
                        try print(param_ty.toType(), writer, mod);
                    }
                }
                if (fn_info.is_var_args) {
                    if (param_types.len != 0) {
                        try writer.writeAll(", ");
                    }
                    try writer.writeAll("...");
                }
                try writer.writeAll(") ");
                if (fn_info.alignment.toByteUnitsOptional()) |a| {
                    try writer.print("align({d}) ", .{a});
                }
                if (fn_info.cc != .Unspecified) {
                    try writer.writeAll("callconv(.");
                    try writer.writeAll(@tagName(fn_info.cc));
                    try writer.writeAll(") ");
                }
                if (fn_info.return_type == .generic_poison_type) {
                    try writer.writeAll("anytype");
                } else {
                    try print(fn_info.return_type.toType(), writer, mod);
                }
            },
            .anyframe_type => |child| {
                if (child == .none) return writer.writeAll("anyframe");
                try writer.writeAll("anyframe->");
                return print(child.toType(), writer, mod);
            },

            // values, not types
            .undef,
            .runtime_value,
            .simple_value,
            .variable,
            .extern_func,
            .func,
            .int,
            .err,
            .error_union,
            .enum_literal,
            .enum_tag,
            .empty_enum_value,
            .float,
            .ptr,
            .opt,
            .aggregate,
            .un,
            // memoization, not types
            .memoized_call,
            => unreachable,
        }
    }

    pub fn toIntern(ty: Type) InternPool.Index {
        assert(ty.ip_index != .none);
        return ty.ip_index;
    }

    pub fn toValue(self: Type) Value {
        return self.toIntern().toValue();
    }

    const RuntimeBitsError = Module.CompileError || error{NeedLazy};

    /// true if and only if the type takes up space in memory at runtime.
    /// There are two reasons a type will return false:
    /// * the type is a comptime-only type. For example, the type `type` itself.
    ///   - note, however, that a struct can have mixed fields and only the non-comptime-only
    ///     fields will count towards the ABI size. For example, `struct {T: type, x: i32}`
    ///     hasRuntimeBits()=true and abiSize()=4
    /// * the type has only one possible value, making its ABI size 0.
    ///   - an enum with an explicit tag type has the ABI size of the integer tag type,
    ///     making it one-possible-value only if the integer tag type has 0 bits.
    /// When `ignore_comptime_only` is true, then types that are comptime-only
    /// may return false positives.
    pub fn hasRuntimeBitsAdvanced(
        ty: Type,
        mod: *Module,
        ignore_comptime_only: bool,
        strat: AbiAlignmentAdvancedStrat,
    ) RuntimeBitsError!bool {
        const ip = &mod.intern_pool;
        return switch (ty.toIntern()) {
            // False because it is a comptime-only type.
            .empty_struct_type => false,
            else => switch (ip.indexToKey(ty.toIntern())) {
                .int_type => |int_type| int_type.bits != 0,
                .ptr_type => {
                    // Pointers to zero-bit types still have a runtime address; however, pointers
                    // to comptime-only types do not, with the exception of function pointers.
                    if (ignore_comptime_only) return true;
                    if (strat == .sema) return !(try strat.sema.typeRequiresComptime(ty));
                    return !comptimeOnly(ty, mod);
                },
                .anyframe_type => true,
                .array_type => |array_type| {
                    if (array_type.sentinel != .none) {
                        return array_type.child.toType().hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat);
                    } else {
                        return array_type.len > 0 and
                            try array_type.child.toType().hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat);
                    }
                },
                .vector_type => |vector_type| {
                    return vector_type.len > 0 and
                        try vector_type.child.toType().hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat);
                },
                .opt_type => |child| {
                    const child_ty = child.toType();
                    if (child_ty.isNoReturn(mod)) {
                        // Then the optional is comptime-known to be null.
                        return false;
                    }
                    if (ignore_comptime_only) {
                        return true;
                    } else if (strat == .sema) {
                        return !(try strat.sema.typeRequiresComptime(child_ty));
                    } else {
                        return !comptimeOnly(child_ty, mod);
                    }
                },
                .error_union_type,
                .error_set_type,
                .inferred_error_set_type,
                => true,

                // These are function *bodies*, not pointers.
                // They return false here because they are comptime-only types.
                // Special exceptions have to be made when emitting functions due to
                // this returning false.
                .func_type => false,

                .simple_type => |t| switch (t) {
                    .f16,
                    .f32,
                    .f64,
                    .f80,
                    .f128,
                    .usize,
                    .isize,
                    .c_char,
                    .c_short,
                    .c_ushort,
                    .c_int,
                    .c_uint,
                    .c_long,
                    .c_ulong,
                    .c_longlong,
                    .c_ulonglong,
                    .c_longdouble,
                    .bool,
                    .anyerror,
                    .adhoc_inferred_error_set,
                    .anyopaque,
                    .atomic_order,
                    .atomic_rmw_op,
                    .calling_convention,
                    .address_space,
                    .float_mode,
                    .reduce_op,
                    .call_modifier,
                    .prefetch_options,
                    .export_options,
                    .extern_options,
                    => true,

                    // These are false because they are comptime-only types.
                    .void,
                    .type,
                    .comptime_int,
                    .comptime_float,
                    .noreturn,
                    .null,
                    .undefined,
                    .enum_literal,
                    .type_info,
                    => false,

                    .generic_poison => unreachable,
                },
                .struct_type => |struct_type| {
                    if (struct_type.assumeRuntimeBitsIfFieldTypesWip(ip)) {
                        // In this case, we guess that hasRuntimeBits() for this type is true,
                        // and then later if our guess was incorrect, we emit a compile error.
                        return true;
                    }
                    switch (strat) {
                        .sema => |sema| _ = try sema.resolveTypeFields(ty),
                        .eager => assert(struct_type.haveFieldTypes(ip)),
                        .lazy => if (!struct_type.haveFieldTypes(ip)) return error.NeedLazy,
                    }
                    for (0..struct_type.field_types.len) |i| {
                        if (struct_type.comptime_bits.getBit(ip, i)) continue;
                        const field_ty = struct_type.field_types.get(ip)[i].toType();
                        if (try field_ty.hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat))
                            return true;
                    } else {
                        return false;
                    }
                },
                .anon_struct_type => |tuple| {
                    for (tuple.types.get(ip), tuple.values.get(ip)) |field_ty, val| {
                        if (val != .none) continue; // comptime field
                        if (try field_ty.toType().hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat)) return true;
                    }
                    return false;
                },

                .union_type => |union_type| {
                    switch (union_type.flagsPtr(ip).runtime_tag) {
                        .none => {
                            if (union_type.flagsPtr(ip).status == .field_types_wip) {
                                // In this case, we guess that hasRuntimeBits() for this type is true,
                                // and then later if our guess was incorrect, we emit a compile error.
                                union_type.flagsPtr(ip).assumed_runtime_bits = true;
                                return true;
                            }
                        },
                        .safety, .tagged => {
                            const tag_ty = union_type.tagTypePtr(ip).*;
                            // tag_ty will be `none` if this union's tag type is not resolved yet,
                            // in which case we want control flow to continue down below.
                            if (tag_ty != .none and
                                try tag_ty.toType().hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat))
                            {
                                return true;
                            }
                        },
                    }
                    switch (strat) {
                        .sema => |sema| _ = try sema.resolveTypeFields(ty),
                        .eager => assert(union_type.flagsPtr(ip).status.haveFieldTypes()),
                        .lazy => if (!union_type.flagsPtr(ip).status.haveFieldTypes())
                            return error.NeedLazy,
                    }
                    const union_obj = ip.loadUnionType(union_type);
                    for (0..union_obj.field_types.len) |field_index| {
                        const field_ty = union_obj.field_types.get(ip)[field_index].toType();
                        if (try field_ty.hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat))
                            return true;
                    } else {
                        return false;
                    }
                },

                .opaque_type => true,
                .enum_type => |enum_type| enum_type.tag_ty.toType().hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat),

                // values, not types
                .undef,
                .runtime_value,
                .simple_value,
                .variable,
                .extern_func,
                .func,
                .int,
                .err,
                .error_union,
                .enum_literal,
                .enum_tag,
                .empty_enum_value,
                .float,
                .ptr,
                .opt,
                .aggregate,
                .un,
                // memoization, not types
                .memoized_call,
                => unreachable,
            },
        };
    }

    /// true if and only if the type has a well-defined memory layout
    /// readFrom/writeToMemory are supported only for types with a well-
    /// defined memory layout
    pub fn hasWellDefinedLayout(ty: Type, mod: *Module) bool {
        const ip = &mod.intern_pool;
        return switch (ip.indexToKey(ty.toIntern())) {
            .int_type,
            .vector_type,
            => true,

            .error_union_type,
            .error_set_type,
            .inferred_error_set_type,
            .anon_struct_type,
            .opaque_type,
            .anyframe_type,
            // These are function bodies, not function pointers.
            .func_type,
            => false,

            .array_type => |array_type| array_type.child.toType().hasWellDefinedLayout(mod),
            .opt_type => ty.isPtrLikeOptional(mod),
            .ptr_type => |ptr_type| ptr_type.flags.size != .Slice,

            .simple_type => |t| switch (t) {
                .f16,
                .f32,
                .f64,
                .f80,
                .f128,
                .usize,
                .isize,
                .c_char,
                .c_short,
                .c_ushort,
                .c_int,
                .c_uint,
                .c_long,
                .c_ulong,
                .c_longlong,
                .c_ulonglong,
                .c_longdouble,
                .bool,
                .void,
                => true,

                .anyerror,
                .adhoc_inferred_error_set,
                .anyopaque,
                .atomic_order,
                .atomic_rmw_op,
                .calling_convention,
                .address_space,
                .float_mode,
                .reduce_op,
                .call_modifier,
                .prefetch_options,
                .export_options,
                .extern_options,
                .type,
                .comptime_int,
                .comptime_float,
                .noreturn,
                .null,
                .undefined,
                .enum_literal,
                .type_info,
                .generic_poison,
                => false,
            },
            .struct_type => |struct_type| {
                // Struct with no fields have a well-defined layout of no bits.
                return struct_type.layout != .Auto or struct_type.field_types.len == 0;
            },
            .union_type => |union_type| switch (union_type.flagsPtr(ip).runtime_tag) {
                .none, .safety => union_type.flagsPtr(ip).layout != .Auto,
                .tagged => false,
            },
            .enum_type => |enum_type| switch (enum_type.tag_mode) {
                .auto => false,
                .explicit, .nonexhaustive => true,
            },

            // values, not types
            .undef,
            .runtime_value,
            .simple_value,
            .variable,
            .extern_func,
            .func,
            .int,
            .err,
            .error_union,
            .enum_literal,
            .enum_tag,
            .empty_enum_value,
            .float,
            .ptr,
            .opt,
            .aggregate,
            .un,
            // memoization, not types
            .memoized_call,
            => unreachable,
        };
    }

    pub fn hasRuntimeBits(ty: Type, mod: *Module) bool {
        return hasRuntimeBitsAdvanced(ty, mod, false, .eager) catch unreachable;
    }

    pub fn hasRuntimeBitsIgnoreComptime(ty: Type, mod: *Module) bool {
        return hasRuntimeBitsAdvanced(ty, mod, true, .eager) catch unreachable;
    }

    pub fn isFnOrHasRuntimeBits(ty: Type, mod: *Module) bool {
        switch (ty.zigTypeTag(mod)) {
            .Fn => {
                const fn_info = mod.typeToFunc(ty).?;
                if (fn_info.is_generic) return false;
                if (fn_info.is_var_args) return true;
                switch (fn_info.cc) {
                    // If there was a comptime calling convention,
                    // it should also return false here.
                    .Inline => return false,
                    else => {},
                }
                if (fn_info.return_type.toType().comptimeOnly(mod)) return false;
                return true;
            },
            else => return ty.hasRuntimeBits(mod),
        }
    }

    /// Same as `isFnOrHasRuntimeBits` but comptime-only types may return a false positive.
    pub fn isFnOrHasRuntimeBitsIgnoreComptime(ty: Type, mod: *Module) bool {
        return switch (ty.zigTypeTag(mod)) {
            .Fn => true,
            else => return ty.hasRuntimeBitsIgnoreComptime(mod),
        };
    }

    pub fn isNoReturn(ty: Type, mod: *Module) bool {
        return mod.intern_pool.isNoReturn(ty.toIntern());
    }

    /// Returns `none` if the pointer is naturally aligned and the element type is 0-bit.
    pub fn ptrAlignment(ty: Type, mod: *Module) Alignment {
        return ptrAlignmentAdvanced(ty, mod, null) catch unreachable;
    }

    pub fn ptrAlignmentAdvanced(ty: Type, mod: *Module, opt_sema: ?*Sema) !Alignment {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .ptr_type => |ptr_type| {
                if (ptr_type.flags.alignment != .none)
                    return ptr_type.flags.alignment;

                if (opt_sema) |sema| {
                    const res = try ptr_type.child.toType().abiAlignmentAdvanced(mod, .{ .sema = sema });
                    return res.scalar;
                }

                return (ptr_type.child.toType().abiAlignmentAdvanced(mod, .eager) catch unreachable).scalar;
            },
            .opt_type => |child| child.toType().ptrAlignmentAdvanced(mod, opt_sema),
            else => unreachable,
        };
    }

    pub fn ptrAddressSpace(ty: Type, mod: *const Module) std.builtin.AddressSpace {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .ptr_type => |ptr_type| ptr_type.flags.address_space,
            .opt_type => |child| mod.intern_pool.indexToKey(child).ptr_type.flags.address_space,
            else => unreachable,
        };
    }

    /// Returns `none` for 0-bit types.
    pub fn abiAlignment(ty: Type, mod: *Module) Alignment {
        return (ty.abiAlignmentAdvanced(mod, .eager) catch unreachable).scalar;
    }

    /// May capture a reference to `ty`.
    /// Returned value has type `comptime_int`.
    pub fn lazyAbiAlignment(ty: Type, mod: *Module) !Value {
        switch (try ty.abiAlignmentAdvanced(mod, .lazy)) {
            .val => |val| return val,
            .scalar => |x| return mod.intValue(Type.comptime_int, x.toByteUnits(0)),
        }
    }

    pub const AbiAlignmentAdvanced = union(enum) {
        scalar: Alignment,
        val: Value,
    };

    pub const AbiAlignmentAdvancedStrat = union(enum) {
        eager,
        lazy,
        sema: *Sema,
    };

    /// If you pass `eager` you will get back `scalar` and assert the type is resolved.
    /// In this case there will be no error, guaranteed.
    /// If you pass `lazy` you may get back `scalar` or `val`.
    /// If `val` is returned, a reference to `ty` has been captured.
    /// If you pass `sema` you will get back `scalar` and resolve the type if
    /// necessary, possibly returning a CompileError.
    pub fn abiAlignmentAdvanced(
        ty: Type,
        mod: *Module,
        strat: AbiAlignmentAdvancedStrat,
    ) Module.CompileError!AbiAlignmentAdvanced {
        const target = mod.getTarget();
        const ip = &mod.intern_pool;

        const opt_sema = switch (strat) {
            .sema => |sema| sema,
            else => null,
        };

        switch (ty.toIntern()) {
            .empty_struct_type => return AbiAlignmentAdvanced{ .scalar = .none },
            else => switch (ip.indexToKey(ty.toIntern())) {
                .int_type => |int_type| {
                    if (int_type.bits == 0) return AbiAlignmentAdvanced{ .scalar = .none };
                    return .{ .scalar = intAbiAlignment(int_type.bits, target) };
                },
                .ptr_type, .anyframe_type => {
                    return .{ .scalar = Alignment.fromByteUnits(@divExact(target.ptrBitWidth(), 8)) };
                },
                .array_type => |array_type| {
                    return array_type.child.toType().abiAlignmentAdvanced(mod, strat);
                },
                .vector_type => |vector_type| {
                    const bits_u64 = try bitSizeAdvanced(vector_type.child.toType(), mod, opt_sema);
                    const bits: u32 = @intCast(bits_u64);
                    const bytes = ((bits * vector_type.len) + 7) / 8;
                    const alignment = std.math.ceilPowerOfTwoAssert(u32, bytes);
                    return .{ .scalar = Alignment.fromByteUnits(alignment) };
                },

                .opt_type => return abiAlignmentAdvancedOptional(ty, mod, strat),
                .error_union_type => |info| return abiAlignmentAdvancedErrorUnion(ty, mod, strat, info.payload_type.toType()),

                // TODO revisit this when we have the concept of the error tag type
                .error_set_type, .inferred_error_set_type => return .{ .scalar = .@"2" },

                // represents machine code; not a pointer
                .func_type => |func_type| return .{
                    .scalar = if (func_type.alignment != .none)
                        func_type.alignment
                    else
                        target_util.defaultFunctionAlignment(target),
                },

                .simple_type => |t| switch (t) {
                    .bool,
                    .atomic_order,
                    .atomic_rmw_op,
                    .calling_convention,
                    .address_space,
                    .float_mode,
                    .reduce_op,
                    .call_modifier,
                    .prefetch_options,
                    .anyopaque,
                    => return .{ .scalar = .@"1" },

                    .usize,
                    .isize,
                    .export_options,
                    .extern_options,
                    => return .{
                        .scalar = Alignment.fromByteUnits(@divExact(target.ptrBitWidth(), 8)),
                    },

                    .c_char => return .{ .scalar = cTypeAlign(target, .char) },
                    .c_short => return .{ .scalar = cTypeAlign(target, .short) },
                    .c_ushort => return .{ .scalar = cTypeAlign(target, .ushort) },
                    .c_int => return .{ .scalar = cTypeAlign(target, .int) },
                    .c_uint => return .{ .scalar = cTypeAlign(target, .uint) },
                    .c_long => return .{ .scalar = cTypeAlign(target, .long) },
                    .c_ulong => return .{ .scalar = cTypeAlign(target, .ulong) },
                    .c_longlong => return .{ .scalar = cTypeAlign(target, .longlong) },
                    .c_ulonglong => return .{ .scalar = cTypeAlign(target, .ulonglong) },
                    .c_longdouble => return .{ .scalar = cTypeAlign(target, .longdouble) },

                    .f16 => return .{ .scalar = .@"2" },
                    .f32 => return .{ .scalar = cTypeAlign(target, .float) },
                    .f64 => switch (target.c_type_bit_size(.double)) {
                        64 => return .{ .scalar = cTypeAlign(target, .double) },
                        else => return .{ .scalar = .@"8" },
                    },
                    .f80 => switch (target.c_type_bit_size(.longdouble)) {
                        80 => return .{ .scalar = cTypeAlign(target, .longdouble) },
                        else => {
                            const u80_ty: Type = .{ .ip_index = .u80_type };
                            return .{ .scalar = abiAlignment(u80_ty, mod) };
                        },
                    },
                    .f128 => switch (target.c_type_bit_size(.longdouble)) {
                        128 => return .{ .scalar = cTypeAlign(target, .longdouble) },
                        else => return .{ .scalar = .@"16" },
                    },

                    // TODO revisit this when we have the concept of the error tag type
                    .anyerror,
                    .adhoc_inferred_error_set,
                    => return .{ .scalar = .@"2" },

                    .void,
                    .type,
                    .comptime_int,
                    .comptime_float,
                    .null,
                    .undefined,
                    .enum_literal,
                    .type_info,
                    => return .{ .scalar = .none },

                    .noreturn => unreachable,
                    .generic_poison => unreachable,
                },
                .struct_type => |struct_type| {
                    if (struct_type.layout == .Packed) {
                        switch (strat) {
                            .sema => |sema| try sema.resolveTypeLayout(ty),
                            .lazy => if (struct_type.backingIntType(ip).* == .none) return .{
                                .val = (try mod.intern(.{ .int = .{
                                    .ty = .comptime_int_type,
                                    .storage = .{ .lazy_align = ty.toIntern() },
                                } })).toValue(),
                            },
                            .eager => {},
                        }
                        return .{ .scalar = struct_type.backingIntType(ip).toType().abiAlignment(mod) };
                    }

                    const flags = struct_type.flagsPtr(ip).*;
                    if (flags.alignment != .none) return .{ .scalar = flags.alignment };

                    return switch (strat) {
                        .eager => unreachable, // struct alignment not resolved
                        .sema => |sema| .{
                            .scalar = try sema.resolveStructAlignment(ty.toIntern(), struct_type),
                        },
                        .lazy => .{ .val = (try mod.intern(.{ .int = .{
                            .ty = .comptime_int_type,
                            .storage = .{ .lazy_align = ty.toIntern() },
                        } })).toValue() },
                    };
                },
                .anon_struct_type => |tuple| {
                    var big_align: Alignment = .none;
                    for (tuple.types.get(ip), tuple.values.get(ip)) |field_ty, val| {
                        if (val != .none) continue; // comptime field
                        if (!(field_ty.toType().hasRuntimeBits(mod))) continue;

                        switch (try field_ty.toType().abiAlignmentAdvanced(mod, strat)) {
                            .scalar => |field_align| big_align = big_align.max(field_align),
                            .val => switch (strat) {
                                .eager => unreachable, // field type alignment not resolved
                                .sema => unreachable, // passed to abiAlignmentAdvanced above
                                .lazy => return .{ .val = (try mod.intern(.{ .int = .{
                                    .ty = .comptime_int_type,
                                    .storage = .{ .lazy_align = ty.toIntern() },
                                } })).toValue() },
                            },
                        }
                    }
                    return .{ .scalar = big_align };
                },

                .union_type => |union_type| {
                    if (opt_sema) |sema| {
                        if (union_type.flagsPtr(ip).status == .field_types_wip) {
                            // We'll guess "pointer-aligned", if the union has an
                            // underaligned pointer field then some allocations
                            // might require explicit alignment.
                            return .{ .scalar = Alignment.fromByteUnits(@divExact(target.ptrBitWidth(), 8)) };
                        }
                        _ = try sema.resolveTypeFields(ty);
                    }
                    if (!union_type.haveFieldTypes(ip)) switch (strat) {
                        .eager => unreachable, // union layout not resolved
                        .sema => unreachable, // handled above
                        .lazy => return .{ .val = (try mod.intern(.{ .int = .{
                            .ty = .comptime_int_type,
                            .storage = .{ .lazy_align = ty.toIntern() },
                        } })).toValue() },
                    };
                    const union_obj = ip.loadUnionType(union_type);
                    if (union_obj.field_names.len == 0) {
                        if (union_obj.hasTag(ip)) {
                            return abiAlignmentAdvanced(union_obj.enum_tag_ty.toType(), mod, strat);
                        } else {
                            return .{
                                .scalar = Alignment.fromByteUnits(@intFromBool(union_obj.flagsPtr(ip).layout == .Extern)),
                            };
                        }
                    }

                    var max_align: Alignment = .none;
                    if (union_obj.hasTag(ip)) max_align = union_obj.enum_tag_ty.toType().abiAlignment(mod);
                    for (0..union_obj.field_names.len) |field_index| {
                        const field_ty = union_obj.field_types.get(ip)[field_index].toType();
                        const field_align = if (union_obj.field_aligns.len == 0)
                            .none
                        else
                            union_obj.field_aligns.get(ip)[field_index];
                        if (!(field_ty.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
                            error.NeedLazy => return .{ .val = (try mod.intern(.{ .int = .{
                                .ty = .comptime_int_type,
                                .storage = .{ .lazy_align = ty.toIntern() },
                            } })).toValue() },
                            else => |e| return e,
                        })) continue;

                        const field_align_bytes: Alignment = if (field_align != .none)
                            field_align
                        else switch (try field_ty.abiAlignmentAdvanced(mod, strat)) {
                            .scalar => |a| a,
                            .val => switch (strat) {
                                .eager => unreachable, // struct layout not resolved
                                .sema => unreachable, // handled above
                                .lazy => return .{ .val = (try mod.intern(.{ .int = .{
                                    .ty = .comptime_int_type,
                                    .storage = .{ .lazy_align = ty.toIntern() },
                                } })).toValue() },
                            },
                        };
                        max_align = max_align.max(field_align_bytes);
                    }
                    return .{ .scalar = max_align };
                },
                .opaque_type => return .{ .scalar = .@"1" },
                .enum_type => |enum_type| return .{
                    .scalar = enum_type.tag_ty.toType().abiAlignment(mod),
                },

                // values, not types
                .undef,
                .runtime_value,
                .simple_value,
                .variable,
                .extern_func,
                .func,
                .int,
                .err,
                .error_union,
                .enum_literal,
                .enum_tag,
                .empty_enum_value,
                .float,
                .ptr,
                .opt,
                .aggregate,
                .un,
                // memoization, not types
                .memoized_call,
                => unreachable,
            },
        }
    }

    fn abiAlignmentAdvancedErrorUnion(
        ty: Type,
        mod: *Module,
        strat: AbiAlignmentAdvancedStrat,
        payload_ty: Type,
    ) Module.CompileError!AbiAlignmentAdvanced {
        // This code needs to be kept in sync with the equivalent switch prong
        // in abiSizeAdvanced.
        const code_align = abiAlignment(Type.anyerror, mod);
        switch (strat) {
            .eager, .sema => {
                if (!(payload_ty.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
                    error.NeedLazy => return .{ .val = (try mod.intern(.{ .int = .{
                        .ty = .comptime_int_type,
                        .storage = .{ .lazy_align = ty.toIntern() },
                    } })).toValue() },
                    else => |e| return e,
                })) {
                    return .{ .scalar = code_align };
                }
                return .{ .scalar = code_align.max(
                    (try payload_ty.abiAlignmentAdvanced(mod, strat)).scalar,
                ) };
            },
            .lazy => {
                switch (try payload_ty.abiAlignmentAdvanced(mod, strat)) {
                    .scalar => |payload_align| return .{ .scalar = code_align.max(payload_align) },
                    .val => {},
                }
                return .{ .val = (try mod.intern(.{ .int = .{
                    .ty = .comptime_int_type,
                    .storage = .{ .lazy_align = ty.toIntern() },
                } })).toValue() };
            },
        }
    }

    fn abiAlignmentAdvancedOptional(
        ty: Type,
        mod: *Module,
        strat: AbiAlignmentAdvancedStrat,
    ) Module.CompileError!AbiAlignmentAdvanced {
        const target = mod.getTarget();
        const child_type = ty.optionalChild(mod);

        switch (child_type.zigTypeTag(mod)) {
            .Pointer => return .{
                .scalar = Alignment.fromByteUnits(@divExact(target.ptrBitWidth(), 8)),
            },
            .ErrorSet => return abiAlignmentAdvanced(Type.anyerror, mod, strat),
            .NoReturn => return .{ .scalar = .none },
            else => {},
        }

        switch (strat) {
            .eager, .sema => {
                if (!(child_type.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
                    error.NeedLazy => return .{ .val = (try mod.intern(.{ .int = .{
                        .ty = .comptime_int_type,
                        .storage = .{ .lazy_align = ty.toIntern() },
                    } })).toValue() },
                    else => |e| return e,
                })) {
                    return .{ .scalar = .@"1" };
                }
                return child_type.abiAlignmentAdvanced(mod, strat);
            },
            .lazy => switch (try child_type.abiAlignmentAdvanced(mod, strat)) {
                .scalar => |x| return .{ .scalar = x.max(.@"1") },
                .val => return .{ .val = (try mod.intern(.{ .int = .{
                    .ty = .comptime_int_type,
                    .storage = .{ .lazy_align = ty.toIntern() },
                } })).toValue() },
            },
        }
    }

    /// May capture a reference to `ty`.
    pub fn lazyAbiSize(ty: Type, mod: *Module) !Value {
        switch (try ty.abiSizeAdvanced(mod, .lazy)) {
            .val => |val| return val,
            .scalar => |x| return mod.intValue(Type.comptime_int, x),
        }
    }

    /// Asserts the type has the ABI size already resolved.
    /// Types that return false for hasRuntimeBits() return 0.
    pub fn abiSize(ty: Type, mod: *Module) u64 {
        return (abiSizeAdvanced(ty, mod, .eager) catch unreachable).scalar;
    }

    const AbiSizeAdvanced = union(enum) {
        scalar: u64,
        val: Value,
    };

    /// If you pass `eager` you will get back `scalar` and assert the type is resolved.
    /// In this case there will be no error, guaranteed.
    /// If you pass `lazy` you may get back `scalar` or `val`.
    /// If `val` is returned, a reference to `ty` has been captured.
    /// If you pass `sema` you will get back `scalar` and resolve the type if
    /// necessary, possibly returning a CompileError.
    pub fn abiSizeAdvanced(
        ty: Type,
        mod: *Module,
        strat: AbiAlignmentAdvancedStrat,
    ) Module.CompileError!AbiSizeAdvanced {
        const target = mod.getTarget();
        const ip = &mod.intern_pool;

        switch (ty.toIntern()) {
            .empty_struct_type => return AbiSizeAdvanced{ .scalar = 0 },

            else => switch (ip.indexToKey(ty.toIntern())) {
                .int_type => |int_type| {
                    if (int_type.bits == 0) return AbiSizeAdvanced{ .scalar = 0 };
                    return AbiSizeAdvanced{ .scalar = intAbiSize(int_type.bits, target) };
                },
                .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
                    .Slice => return .{ .scalar = @divExact(target.ptrBitWidth(), 8) * 2 },
                    else => return .{ .scalar = @divExact(target.ptrBitWidth(), 8) },
                },
                .anyframe_type => return AbiSizeAdvanced{ .scalar = @divExact(target.ptrBitWidth(), 8) },

                .array_type => |array_type| {
                    const len = array_type.len + @intFromBool(array_type.sentinel != .none);
                    switch (try array_type.child.toType().abiSizeAdvanced(mod, strat)) {
                        .scalar => |elem_size| return .{ .scalar = len * elem_size },
                        .val => switch (strat) {
                            .sema, .eager => unreachable,
                            .lazy => return .{ .val = (try mod.intern(.{ .int = .{
                                .ty = .comptime_int_type,
                                .storage = .{ .lazy_size = ty.toIntern() },
                            } })).toValue() },
                        },
                    }
                },
                .vector_type => |vector_type| {
                    const opt_sema = switch (strat) {
                        .sema => |sema| sema,
                        .eager => null,
                        .lazy => return .{ .val = (try mod.intern(.{ .int = .{
                            .ty = .comptime_int_type,
                            .storage = .{ .lazy_size = ty.toIntern() },
                        } })).toValue() },
                    };
                    const elem_bits = try vector_type.child.toType().bitSizeAdvanced(mod, opt_sema);
                    const total_bits = elem_bits * vector_type.len;
                    const total_bytes = (total_bits + 7) / 8;
                    const alignment = switch (try ty.abiAlignmentAdvanced(mod, strat)) {
                        .scalar => |x| x,
                        .val => return .{ .val = (try mod.intern(.{ .int = .{
                            .ty = .comptime_int_type,
                            .storage = .{ .lazy_size = ty.toIntern() },
                        } })).toValue() },
                    };
                    return AbiSizeAdvanced{ .scalar = alignment.forward(total_bytes) };
                },

                .opt_type => return ty.abiSizeAdvancedOptional(mod, strat),

                // TODO revisit this when we have the concept of the error tag type
                .error_set_type, .inferred_error_set_type => return AbiSizeAdvanced{ .scalar = 2 },

                .error_union_type => |error_union_type| {
                    const payload_ty = error_union_type.payload_type.toType();
                    // This code needs to be kept in sync with the equivalent switch prong
                    // in abiAlignmentAdvanced.
                    const code_size = abiSize(Type.anyerror, mod);
                    if (!(payload_ty.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
                        error.NeedLazy => return .{ .val = (try mod.intern(.{ .int = .{
                            .ty = .comptime_int_type,
                            .storage = .{ .lazy_size = ty.toIntern() },
                        } })).toValue() },
                        else => |e| return e,
                    })) {
                        // Same as anyerror.
                        return AbiSizeAdvanced{ .scalar = code_size };
                    }
                    const code_align = abiAlignment(Type.anyerror, mod);
                    const payload_align = abiAlignment(payload_ty, mod);
                    const payload_size = switch (try payload_ty.abiSizeAdvanced(mod, strat)) {
                        .scalar => |elem_size| elem_size,
                        .val => switch (strat) {
                            .sema => unreachable,
                            .eager => unreachable,
                            .lazy => return .{ .val = (try mod.intern(.{ .int = .{
                                .ty = .comptime_int_type,
                                .storage = .{ .lazy_size = ty.toIntern() },
                            } })).toValue() },
                        },
                    };

                    var size: u64 = 0;
                    if (code_align.compare(.gt, payload_align)) {
                        size += code_size;
                        size = payload_align.forward(size);
                        size += payload_size;
                        size = code_align.forward(size);
                    } else {
                        size += payload_size;
                        size = code_align.forward(size);
                        size += code_size;
                        size = payload_align.forward(size);
                    }
                    return AbiSizeAdvanced{ .scalar = size };
                },
                .func_type => unreachable, // represents machine code; not a pointer
                .simple_type => |t| switch (t) {
                    .bool,
                    .atomic_order,
                    .atomic_rmw_op,
                    .calling_convention,
                    .address_space,
                    .float_mode,
                    .reduce_op,
                    .call_modifier,
                    => return AbiSizeAdvanced{ .scalar = 1 },

                    .f16 => return AbiSizeAdvanced{ .scalar = 2 },
                    .f32 => return AbiSizeAdvanced{ .scalar = 4 },
                    .f64 => return AbiSizeAdvanced{ .scalar = 8 },
                    .f128 => return AbiSizeAdvanced{ .scalar = 16 },
                    .f80 => switch (target.c_type_bit_size(.longdouble)) {
                        80 => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.longdouble) },
                        else => {
                            const u80_ty: Type = .{ .ip_index = .u80_type };
                            return AbiSizeAdvanced{ .scalar = abiSize(u80_ty, mod) };
                        },
                    },

                    .usize,
                    .isize,
                    => return AbiSizeAdvanced{ .scalar = @divExact(target.ptrBitWidth(), 8) },

                    .c_char => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.char) },
                    .c_short => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.short) },
                    .c_ushort => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.ushort) },
                    .c_int => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.int) },
                    .c_uint => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.uint) },
                    .c_long => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.long) },
                    .c_ulong => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.ulong) },
                    .c_longlong => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.longlong) },
                    .c_ulonglong => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.ulonglong) },
                    .c_longdouble => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.longdouble) },

                    .anyopaque,
                    .void,
                    .type,
                    .comptime_int,
                    .comptime_float,
                    .null,
                    .undefined,
                    .enum_literal,
                    => return AbiSizeAdvanced{ .scalar = 0 },

                    // TODO revisit this when we have the concept of the error tag type
                    .anyerror,
                    .adhoc_inferred_error_set,
                    => return AbiSizeAdvanced{ .scalar = 2 },

                    .prefetch_options => unreachable, // missing call to resolveTypeFields
                    .export_options => unreachable, // missing call to resolveTypeFields
                    .extern_options => unreachable, // missing call to resolveTypeFields

                    .type_info => unreachable,
                    .noreturn => unreachable,
                    .generic_poison => unreachable,
                },
                .struct_type => |struct_type| {
                    switch (strat) {
                        .sema => |sema| try sema.resolveTypeLayout(ty),
                        .lazy => switch (struct_type.layout) {
                            .Packed => {
                                if (struct_type.backingIntType(ip).* == .none) return .{
                                    .val = (try mod.intern(.{ .int = .{
                                        .ty = .comptime_int_type,
                                        .storage = .{ .lazy_size = ty.toIntern() },
                                    } })).toValue(),
                                };
                            },
                            .Auto, .Extern => {
                                if (!struct_type.haveLayout(ip)) return .{
                                    .val = (try mod.intern(.{ .int = .{
                                        .ty = .comptime_int_type,
                                        .storage = .{ .lazy_size = ty.toIntern() },
                                    } })).toValue(),
                                };
                            },
                        },
                        .eager => {},
                    }
                    return switch (struct_type.layout) {
                        .Packed => .{
                            .scalar = struct_type.backingIntType(ip).toType().abiSize(mod),
                        },
                        .Auto, .Extern => .{ .scalar = struct_type.size(ip).* },
                    };
                },
                .anon_struct_type => |tuple| {
                    switch (strat) {
                        .sema => |sema| try sema.resolveTypeLayout(ty),
                        .lazy, .eager => {},
                    }
                    const field_count = tuple.types.len;
                    if (field_count == 0) {
                        return AbiSizeAdvanced{ .scalar = 0 };
                    }
                    return AbiSizeAdvanced{ .scalar = ty.structFieldOffset(field_count, mod) };
                },

                .union_type => |union_type| {
                    switch (strat) {
                        .sema => |sema| try sema.resolveTypeLayout(ty),
                        .lazy => if (!union_type.flagsPtr(ip).status.haveLayout()) return .{
                            .val = (try mod.intern(.{ .int = .{
                                .ty = .comptime_int_type,
                                .storage = .{ .lazy_size = ty.toIntern() },
                            } })).toValue(),
                        },
                        .eager => {},
                    }
                    const union_obj = ip.loadUnionType(union_type);
                    return AbiSizeAdvanced{ .scalar = mod.unionAbiSize(union_obj) };
                },
                .opaque_type => unreachable, // no size available
                .enum_type => |enum_type| return AbiSizeAdvanced{ .scalar = enum_type.tag_ty.toType().abiSize(mod) },

                // values, not types
                .undef,
                .runtime_value,
                .simple_value,
                .variable,
                .extern_func,
                .func,
                .int,
                .err,
                .error_union,
                .enum_literal,
                .enum_tag,
                .empty_enum_value,
                .float,
                .ptr,
                .opt,
                .aggregate,
                .un,
                // memoization, not types
                .memoized_call,
                => unreachable,
            },
        }
    }

    fn abiSizeAdvancedOptional(
        ty: Type,
        mod: *Module,
        strat: AbiAlignmentAdvancedStrat,
    ) Module.CompileError!AbiSizeAdvanced {
        const child_ty = ty.optionalChild(mod);

        if (child_ty.isNoReturn(mod)) {
            return AbiSizeAdvanced{ .scalar = 0 };
        }

        if (!(child_ty.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
            error.NeedLazy => return .{ .val = (try mod.intern(.{ .int = .{
                .ty = .comptime_int_type,
                .storage = .{ .lazy_size = ty.toIntern() },
            } })).toValue() },
            else => |e| return e,
        })) return AbiSizeAdvanced{ .scalar = 1 };

        if (ty.optionalReprIsPayload(mod)) {
            return abiSizeAdvanced(child_ty, mod, strat);
        }

        const payload_size = switch (try child_ty.abiSizeAdvanced(mod, strat)) {
            .scalar => |elem_size| elem_size,
            .val => switch (strat) {
                .sema => unreachable,
                .eager => unreachable,
                .lazy => return .{ .val = (try mod.intern(.{ .int = .{
                    .ty = .comptime_int_type,
                    .storage = .{ .lazy_size = ty.toIntern() },
                } })).toValue() },
            },
        };

        // Optional types are represented as a struct with the child type as the first
        // field and a boolean as the second. Since the child type's abi alignment is
        // guaranteed to be >= that of bool's (1 byte) the added size is exactly equal
        // to the child type's ABI alignment.
        return AbiSizeAdvanced{
            .scalar = child_ty.abiAlignment(mod).toByteUnits(0) + payload_size,
        };
    }

    fn intAbiSize(bits: u16, target: Target) u64 {
        return intAbiAlignment(bits, target).forward(@as(u16, @intCast((@as(u17, bits) + 7) / 8)));
    }

    fn intAbiAlignment(bits: u16, target: Target) Alignment {
        return Alignment.fromByteUnits(@min(
            std.math.ceilPowerOfTwoPromote(u16, @as(u16, @intCast((@as(u17, bits) + 7) / 8))),
            target.maxIntAlignment(),
        ));
    }

    pub fn bitSize(ty: Type, mod: *Module) u64 {
        return bitSizeAdvanced(ty, mod, null) catch unreachable;
    }

    /// If you pass `opt_sema`, any recursive type resolutions will happen if
    /// necessary, possibly returning a CompileError. Passing `null` instead asserts
    /// the type is fully resolved, and there will be no error, guaranteed.
    pub fn bitSizeAdvanced(
        ty: Type,
        mod: *Module,
        opt_sema: ?*Sema,
    ) Module.CompileError!u64 {
        const target = mod.getTarget();
        const ip = &mod.intern_pool;

        const strat: AbiAlignmentAdvancedStrat = if (opt_sema) |sema| .{ .sema = sema } else .eager;

        switch (ip.indexToKey(ty.toIntern())) {
            .int_type => |int_type| return int_type.bits,
            .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
                .Slice => return target.ptrBitWidth() * 2,
                else => return target.ptrBitWidth(),
            },
            .anyframe_type => return target.ptrBitWidth(),

            .array_type => |array_type| {
                const len = array_type.len + @intFromBool(array_type.sentinel != .none);
                if (len == 0) return 0;
                const elem_ty = array_type.child.toType();
                const elem_size = @max(elem_ty.abiAlignment(mod).toByteUnits(0), elem_ty.abiSize(mod));
                if (elem_size == 0) return 0;
                const elem_bit_size = try bitSizeAdvanced(elem_ty, mod, opt_sema);
                return (len - 1) * 8 * elem_size + elem_bit_size;
            },
            .vector_type => |vector_type| {
                const child_ty = vector_type.child.toType();
                const elem_bit_size = try bitSizeAdvanced(child_ty, mod, opt_sema);
                return elem_bit_size * vector_type.len;
            },
            .opt_type => {
                // Optionals and error unions are not packed so their bitsize
                // includes padding bits.
                return (try abiSizeAdvanced(ty, mod, strat)).scalar * 8;
            },

            // TODO revisit this when we have the concept of the error tag type
            .error_set_type, .inferred_error_set_type => return 16,

            .error_union_type => {
                // Optionals and error unions are not packed so their bitsize
                // includes padding bits.
                return (try abiSizeAdvanced(ty, mod, strat)).scalar * 8;
            },
            .func_type => unreachable, // represents machine code; not a pointer
            .simple_type => |t| switch (t) {
                .f16 => return 16,
                .f32 => return 32,
                .f64 => return 64,
                .f80 => return 80,
                .f128 => return 128,

                .usize,
                .isize,
                => return target.ptrBitWidth(),

                .c_char => return target.c_type_bit_size(.char),
                .c_short => return target.c_type_bit_size(.short),
                .c_ushort => return target.c_type_bit_size(.ushort),
                .c_int => return target.c_type_bit_size(.int),
                .c_uint => return target.c_type_bit_size(.uint),
                .c_long => return target.c_type_bit_size(.long),
                .c_ulong => return target.c_type_bit_size(.ulong),
                .c_longlong => return target.c_type_bit_size(.longlong),
                .c_ulonglong => return target.c_type_bit_size(.ulonglong),
                .c_longdouble => return target.c_type_bit_size(.longdouble),

                .bool => return 1,
                .void => return 0,

                // TODO revisit this when we have the concept of the error tag type
                .anyerror,
                .adhoc_inferred_error_set,
                => return 16,

                .anyopaque => unreachable,
                .type => unreachable,
                .comptime_int => unreachable,
                .comptime_float => unreachable,
                .noreturn => unreachable,
                .null => unreachable,
                .undefined => unreachable,
                .enum_literal => unreachable,
                .generic_poison => unreachable,

                .atomic_order => unreachable,
                .atomic_rmw_op => unreachable,
                .calling_convention => unreachable,
                .address_space => unreachable,
                .float_mode => unreachable,
                .reduce_op => unreachable,
                .call_modifier => unreachable,
                .prefetch_options => unreachable,
                .export_options => unreachable,
                .extern_options => unreachable,
                .type_info => unreachable,
            },
            .struct_type => |struct_type| {
                if (struct_type.layout == .Packed) {
                    if (opt_sema) |sema| try sema.resolveTypeLayout(ty);
                    return try struct_type.backingIntType(ip).*.toType().bitSizeAdvanced(mod, opt_sema);
                }
                return (try ty.abiSizeAdvanced(mod, strat)).scalar * 8;
            },

            .anon_struct_type => {
                if (opt_sema) |sema| try sema.resolveTypeFields(ty);
                return (try ty.abiSizeAdvanced(mod, strat)).scalar * 8;
            },

            .union_type => |union_type| {
                if (opt_sema) |sema| try sema.resolveTypeFields(ty);
                if (ty.containerLayout(mod) != .Packed) {
                    return (try ty.abiSizeAdvanced(mod, strat)).scalar * 8;
                }
                const union_obj = ip.loadUnionType(union_type);
                assert(union_obj.flagsPtr(ip).status.haveFieldTypes());

                var size: u64 = 0;
                for (0..union_obj.field_types.len) |field_index| {
                    const field_ty = union_obj.field_types.get(ip)[field_index];
                    size = @max(size, try bitSizeAdvanced(field_ty.toType(), mod, opt_sema));
                }
                return size;
            },
            .opaque_type => unreachable,
            .enum_type => |enum_type| return bitSizeAdvanced(enum_type.tag_ty.toType(), mod, opt_sema),

            // values, not types
            .undef,
            .runtime_value,
            .simple_value,
            .variable,
            .extern_func,
            .func,
            .int,
            .err,
            .error_union,
            .enum_literal,
            .enum_tag,
            .empty_enum_value,
            .float,
            .ptr,
            .opt,
            .aggregate,
            .un,
            // memoization, not types
            .memoized_call,
            => unreachable,
        }
    }

    /// Returns true if the type's layout is already resolved and it is safe
    /// to use `abiSize`, `abiAlignment` and `bitSize` on it.
    pub fn layoutIsResolved(ty: Type, mod: *Module) bool {
        const ip = &mod.intern_pool;
        return switch (ip.indexToKey(ty.toIntern())) {
            .struct_type => |struct_type| struct_type.haveLayout(ip),
            .union_type => |union_type| union_type.haveLayout(ip),
            .array_type => |array_type| {
                if ((array_type.len + @intFromBool(array_type.sentinel != .none)) == 0) return true;
                return array_type.child.toType().layoutIsResolved(mod);
            },
            .opt_type => |child| child.toType().layoutIsResolved(mod),
            .error_union_type => |k| k.payload_type.toType().layoutIsResolved(mod),
            else => true,
        };
    }

    pub fn isSinglePointer(ty: Type, mod: *const Module) bool {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .ptr_type => |ptr_info| ptr_info.flags.size == .One,
            else => false,
        };
    }

    /// Asserts `ty` is a pointer.
    pub fn ptrSize(ty: Type, mod: *const Module) std.builtin.Type.Pointer.Size {
        return ptrSizeOrNull(ty, mod).?;
    }

    /// Returns `null` if `ty` is not a pointer.
    pub fn ptrSizeOrNull(ty: Type, mod: *const Module) ?std.builtin.Type.Pointer.Size {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .ptr_type => |ptr_info| ptr_info.flags.size,
            else => null,
        };
    }

    pub fn isSlice(ty: Type, mod: *const Module) bool {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .ptr_type => |ptr_type| ptr_type.flags.size == .Slice,
            else => false,
        };
    }

    pub fn slicePtrFieldType(ty: Type, mod: *const Module) Type {
        return mod.intern_pool.slicePtrType(ty.toIntern()).toType();
    }

    pub fn isConstPtr(ty: Type, mod: *const Module) bool {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .ptr_type => |ptr_type| ptr_type.flags.is_const,
            else => false,
        };
    }

    pub fn isVolatilePtr(ty: Type, mod: *const Module) bool {
        return isVolatilePtrIp(ty, &mod.intern_pool);
    }

    pub fn isVolatilePtrIp(ty: Type, ip: *const InternPool) bool {
        return switch (ip.indexToKey(ty.toIntern())) {
            .ptr_type => |ptr_type| ptr_type.flags.is_volatile,
            else => false,
        };
    }

    pub fn isAllowzeroPtr(ty: Type, mod: *const Module) bool {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .ptr_type => |ptr_type| ptr_type.flags.is_allowzero,
            .opt_type => true,
            else => false,
        };
    }

    pub fn isCPtr(ty: Type, mod: *const Module) bool {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .ptr_type => |ptr_type| ptr_type.flags.size == .C,
            else => false,
        };
    }

    pub fn isPtrAtRuntime(ty: Type, mod: *const Module) bool {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
                .Slice => false,
                .One, .Many, .C => true,
            },
            .opt_type => |child| switch (mod.intern_pool.indexToKey(child)) {
                .ptr_type => |p| switch (p.flags.size) {
                    .Slice, .C => false,
                    .Many, .One => !p.flags.is_allowzero,
                },
                else => false,
            },
            else => false,
        };
    }

    /// For pointer-like optionals, returns true, otherwise returns the allowzero property
    /// of pointers.
    pub fn ptrAllowsZero(ty: Type, mod: *const Module) bool {
        if (ty.isPtrLikeOptional(mod)) {
            return true;
        }
        return ty.ptrInfo(mod).flags.is_allowzero;
    }

    /// See also `isPtrLikeOptional`.
    pub fn optionalReprIsPayload(ty: Type, mod: *const Module) bool {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .opt_type => |child_type| child_type == .anyerror_type or switch (mod.intern_pool.indexToKey(child_type)) {
                .ptr_type => |ptr_type| ptr_type.flags.size != .C and !ptr_type.flags.is_allowzero,
                .error_set_type, .inferred_error_set_type => true,
                else => false,
            },
            .ptr_type => |ptr_type| ptr_type.flags.size == .C,
            else => false,
        };
    }

    /// Returns true if the type is optional and would be lowered to a single pointer
    /// address value, using 0 for null. Note that this returns true for C pointers.
    /// This function must be kept in sync with `Sema.typePtrOrOptionalPtrTy`.
    pub fn isPtrLikeOptional(ty: Type, mod: *const Module) bool {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .ptr_type => |ptr_type| ptr_type.flags.size == .C,
            .opt_type => |child| switch (mod.intern_pool.indexToKey(child)) {
                .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
                    .Slice, .C => false,
                    .Many, .One => !ptr_type.flags.is_allowzero,
                },
                else => false,
            },
            else => false,
        };
    }

    /// For *[N]T,  returns [N]T.
    /// For *T,     returns T.
    /// For [*]T,   returns T.
    pub fn childType(ty: Type, mod: *const Module) Type {
        return childTypeIp(ty, &mod.intern_pool);
    }

    pub fn childTypeIp(ty: Type, ip: *const InternPool) Type {
        return ip.childType(ty.toIntern()).toType();
    }

    /// For *[N]T,       returns T.
    /// For ?*T,         returns T.
    /// For ?*[N]T,      returns T.
    /// For ?[*]T,       returns T.
    /// For *T,          returns T.
    /// For [*]T,        returns T.
    /// For [N]T,        returns T.
    /// For []T,         returns T.
    /// For anyframe->T, returns T.
    pub fn elemType2(ty: Type, mod: *const Module) Type {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
                .One => ptr_type.child.toType().shallowElemType(mod),
                .Many, .C, .Slice => ptr_type.child.toType(),
            },
            .anyframe_type => |child| {
                assert(child != .none);
                return child.toType();
            },
            .vector_type => |vector_type| vector_type.child.toType(),
            .array_type => |array_type| array_type.child.toType(),
            .opt_type => |child| mod.intern_pool.childType(child).toType(),
            else => unreachable,
        };
    }

    fn shallowElemType(child_ty: Type, mod: *const Module) Type {
        return switch (child_ty.zigTypeTag(mod)) {
            .Array, .Vector => child_ty.childType(mod),
            else => child_ty,
        };
    }

    /// For vectors, returns the element type. Otherwise returns self.
    pub fn scalarType(ty: Type, mod: *Module) Type {
        return switch (ty.zigTypeTag(mod)) {
            .Vector => ty.childType(mod),
            else => ty,
        };
    }

    /// Asserts that the type is an optional.
    /// Note that for C pointers this returns the type unmodified.
    pub fn optionalChild(ty: Type, mod: *const Module) Type {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .opt_type => |child| child.toType(),
            .ptr_type => |ptr_type| b: {
                assert(ptr_type.flags.size == .C);
                break :b ty;
            },
            else => unreachable,
        };
    }

    /// Returns the tag type of a union, if the type is a union and it has a tag type.
    /// Otherwise, returns `null`.
    pub fn unionTagType(ty: Type, mod: *Module) ?Type {
        const ip = &mod.intern_pool;
        return switch (ip.indexToKey(ty.toIntern())) {
            .union_type => |union_type| switch (union_type.flagsPtr(ip).runtime_tag) {
                .tagged => {
                    assert(union_type.flagsPtr(ip).status.haveFieldTypes());
                    return union_type.enum_tag_ty.toType();
                },
                else => null,
            },
            else => null,
        };
    }

    /// Same as `unionTagType` but includes safety tag.
    /// Codegen should use this version.
    pub fn unionTagTypeSafety(ty: Type, mod: *Module) ?Type {
        const ip = &mod.intern_pool;
        return switch (ip.indexToKey(ty.toIntern())) {
            .union_type => |union_type| {
                if (!union_type.hasTag(ip)) return null;
                assert(union_type.haveFieldTypes(ip));
                return union_type.enum_tag_ty.toType();
            },
            else => null,
        };
    }

    /// Asserts the type is a union; returns the tag type, even if the tag will
    /// not be stored at runtime.
    pub fn unionTagTypeHypothetical(ty: Type, mod: *Module) Type {
        const union_obj = mod.typeToUnion(ty).?;
        return union_obj.enum_tag_ty.toType();
    }

    pub fn unionFieldType(ty: Type, enum_tag: Value, mod: *Module) Type {
        const ip = &mod.intern_pool;
        const union_obj = mod.typeToUnion(ty).?;
        const index = mod.unionTagFieldIndex(union_obj, enum_tag).?;
        return union_obj.field_types.get(ip)[index].toType();
    }

    pub fn unionTagFieldIndex(ty: Type, enum_tag: Value, mod: *Module) ?u32 {
        const union_obj = mod.typeToUnion(ty).?;
        return mod.unionTagFieldIndex(union_obj, enum_tag);
    }

    pub fn unionHasAllZeroBitFieldTypes(ty: Type, mod: *Module) bool {
        const ip = &mod.intern_pool;
        const union_obj = mod.typeToUnion(ty).?;
        for (union_obj.field_types.get(ip)) |field_ty| {
            if (field_ty.toType().hasRuntimeBits(mod)) return false;
        }
        return true;
    }

    pub fn unionGetLayout(ty: Type, mod: *Module) Module.UnionLayout {
        const ip = &mod.intern_pool;
        const union_type = ip.indexToKey(ty.toIntern()).union_type;
        const union_obj = ip.loadUnionType(union_type);
        return mod.getUnionLayout(union_obj);
    }

    pub fn containerLayout(ty: Type, mod: *Module) std.builtin.Type.ContainerLayout {
        const ip = &mod.intern_pool;
        return switch (ip.indexToKey(ty.toIntern())) {
            .struct_type => |struct_type| struct_type.layout,
            .anon_struct_type => .Auto,
            .union_type => |union_type| union_type.flagsPtr(ip).layout,
            else => unreachable,
        };
    }

    /// Asserts that the type is an error union.
    pub fn errorUnionPayload(ty: Type, mod: *Module) Type {
        return mod.intern_pool.indexToKey(ty.toIntern()).error_union_type.payload_type.toType();
    }

    /// Asserts that the type is an error union.
    pub fn errorUnionSet(ty: Type, mod: *Module) Type {
        return mod.intern_pool.errorUnionSet(ty.toIntern()).toType();
    }

    /// Returns false for unresolved inferred error sets.
    pub fn errorSetIsEmpty(ty: Type, mod: *Module) bool {
        const ip = &mod.intern_pool;
        return switch (ty.toIntern()) {
            .anyerror_type, .adhoc_inferred_error_set_type => false,
            else => switch (ip.indexToKey(ty.toIntern())) {
                .error_set_type => |error_set_type| error_set_type.names.len == 0,
                .inferred_error_set_type => |i| switch (ip.funcIesResolved(i).*) {
                    .none, .anyerror_type => false,
                    else => |t| ip.indexToKey(t).error_set_type.names.len == 0,
                },
                else => unreachable,
            },
        };
    }

    /// Returns true if it is an error set that includes anyerror, false otherwise.
    /// Note that the result may be a false negative if the type did not get error set
    /// resolution prior to this call.
    pub fn isAnyError(ty: Type, mod: *Module) bool {
        const ip = &mod.intern_pool;
        return switch (ty.toIntern()) {
            .anyerror_type => true,
            .adhoc_inferred_error_set_type => false,
            else => switch (mod.intern_pool.indexToKey(ty.toIntern())) {
                .inferred_error_set_type => |i| ip.funcIesResolved(i).* == .anyerror_type,
                else => false,
            },
        };
    }

    pub fn isError(ty: Type, mod: *const Module) bool {
        return switch (ty.zigTypeTag(mod)) {
            .ErrorUnion, .ErrorSet => true,
            else => false,
        };
    }

    /// Returns whether ty, which must be an error set, includes an error `name`.
    /// Might return a false negative if `ty` is an inferred error set and not fully
    /// resolved yet.
    pub fn errorSetHasFieldIp(
        ip: *const InternPool,
        ty: InternPool.Index,
        name: InternPool.NullTerminatedString,
    ) bool {
        return switch (ty) {
            .anyerror_type => true,
            else => switch (ip.indexToKey(ty)) {
                .error_set_type => |error_set_type| error_set_type.nameIndex(ip, name) != null,
                .inferred_error_set_type => |i| switch (ip.funcIesResolved(i).*) {
                    .anyerror_type => true,
                    .none => false,
                    else => |t| ip.indexToKey(t).error_set_type.nameIndex(ip, name) != null,
                },
                else => unreachable,
            },
        };
    }

    /// Returns whether ty, which must be an error set, includes an error `name`.
    /// Might return a false negative if `ty` is an inferred error set and not fully
    /// resolved yet.
    pub fn errorSetHasField(ty: Type, name: []const u8, mod: *Module) bool {
        const ip = &mod.intern_pool;
        return switch (ty.toIntern()) {
            .anyerror_type => true,
            else => switch (ip.indexToKey(ty.toIntern())) {
                .error_set_type => |error_set_type| {
                    // If the string is not interned, then the field certainly is not present.
                    const field_name_interned = ip.getString(name).unwrap() orelse return false;
                    return error_set_type.nameIndex(ip, field_name_interned) != null;
                },
                .inferred_error_set_type => |i| switch (ip.funcIesResolved(i).*) {
                    .anyerror_type => true,
                    .none => false,
                    else => |t| {
                        // If the string is not interned, then the field certainly is not present.
                        const field_name_interned = ip.getString(name).unwrap() orelse return false;
                        return ip.indexToKey(t).error_set_type.nameIndex(ip, field_name_interned) != null;
                    },
                },
                else => unreachable,
            },
        };
    }

    /// Asserts the type is an array or vector or struct.
    pub fn arrayLen(ty: Type, mod: *const Module) u64 {
        return arrayLenIp(ty, &mod.intern_pool);
    }

    pub fn arrayLenIp(ty: Type, ip: *const InternPool) u64 {
        return switch (ip.indexToKey(ty.toIntern())) {
            .vector_type => |vector_type| vector_type.len,
            .array_type => |array_type| array_type.len,
            .struct_type => |struct_type| struct_type.field_types.len,
            .anon_struct_type => |tuple| tuple.types.len,

            else => unreachable,
        };
    }

    pub fn arrayLenIncludingSentinel(ty: Type, mod: *const Module) u64 {
        return ty.arrayLen(mod) + @intFromBool(ty.sentinel(mod) != null);
    }

    pub fn vectorLen(ty: Type, mod: *const Module) u32 {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .vector_type => |vector_type| vector_type.len,
            .anon_struct_type => |tuple| @intCast(tuple.types.len),
            else => unreachable,
        };
    }

    /// Asserts the type is an array, pointer or vector.
    pub fn sentinel(ty: Type, mod: *const Module) ?Value {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .vector_type,
            .struct_type,
            .anon_struct_type,
            => null,

            .array_type => |t| if (t.sentinel != .none) t.sentinel.toValue() else null,
            .ptr_type => |t| if (t.sentinel != .none) t.sentinel.toValue() else null,

            else => unreachable,
        };
    }

    /// Returns true if and only if the type is a fixed-width integer.
    pub fn isInt(self: Type, mod: *const Module) bool {
        return self.isSignedInt(mod) or self.isUnsignedInt(mod);
    }

    /// Returns true if and only if the type is a fixed-width, signed integer.
    pub fn isSignedInt(ty: Type, mod: *const Module) bool {
        return switch (ty.toIntern()) {
            .c_char_type => mod.getTarget().charSignedness() == .signed,
            .isize_type, .c_short_type, .c_int_type, .c_long_type, .c_longlong_type => true,
            else => switch (mod.intern_pool.indexToKey(ty.toIntern())) {
                .int_type => |int_type| int_type.signedness == .signed,
                else => false,
            },
        };
    }

    /// Returns true if and only if the type is a fixed-width, unsigned integer.
    pub fn isUnsignedInt(ty: Type, mod: *const Module) bool {
        return switch (ty.toIntern()) {
            .c_char_type => mod.getTarget().charSignedness() == .unsigned,
            .usize_type, .c_ushort_type, .c_uint_type, .c_ulong_type, .c_ulonglong_type => true,
            else => switch (mod.intern_pool.indexToKey(ty.toIntern())) {
                .int_type => |int_type| int_type.signedness == .unsigned,
                else => false,
            },
        };
    }

    /// Returns true for integers, enums, error sets, and packed structs.
    /// If this function returns true, then intInfo() can be called on the type.
    pub fn isAbiInt(ty: Type, mod: *Module) bool {
        return switch (ty.zigTypeTag(mod)) {
            .Int, .Enum, .ErrorSet => true,
            .Struct => ty.containerLayout(mod) == .Packed,
            else => false,
        };
    }

    /// Asserts the type is an integer, enum, error set, or vector of one of them.
    pub fn intInfo(starting_ty: Type, mod: *Module) InternPool.Key.IntType {
        const ip = &mod.intern_pool;
        const target = mod.getTarget();
        var ty = starting_ty;

        while (true) switch (ty.toIntern()) {
            .anyerror_type, .adhoc_inferred_error_set_type => {
                // TODO revisit this when error sets support custom int types
                return .{ .signedness = .unsigned, .bits = 16 };
            },
            .usize_type => return .{ .signedness = .unsigned, .bits = target.ptrBitWidth() },
            .isize_type => return .{ .signedness = .signed, .bits = target.ptrBitWidth() },
            .c_char_type => return .{ .signedness = mod.getTarget().charSignedness(), .bits = target.c_type_bit_size(.char) },
            .c_short_type => return .{ .signedness = .signed, .bits = target.c_type_bit_size(.short) },
            .c_ushort_type => return .{ .signedness = .unsigned, .bits = target.c_type_bit_size(.ushort) },
            .c_int_type => return .{ .signedness = .signed, .bits = target.c_type_bit_size(.int) },
            .c_uint_type => return .{ .signedness = .unsigned, .bits = target.c_type_bit_size(.uint) },
            .c_long_type => return .{ .signedness = .signed, .bits = target.c_type_bit_size(.long) },
            .c_ulong_type => return .{ .signedness = .unsigned, .bits = target.c_type_bit_size(.ulong) },
            .c_longlong_type => return .{ .signedness = .signed, .bits = target.c_type_bit_size(.longlong) },
            .c_ulonglong_type => return .{ .signedness = .unsigned, .bits = target.c_type_bit_size(.ulonglong) },
            else => switch (ip.indexToKey(ty.toIntern())) {
                .int_type => |int_type| return int_type,
                .struct_type => |t| ty = t.backingIntType(ip).*.toType(),
                .enum_type => |enum_type| ty = enum_type.tag_ty.toType(),
                .vector_type => |vector_type| ty = vector_type.child.toType(),

                // TODO revisit this when error sets support custom int types
                .error_set_type, .inferred_error_set_type => return .{ .signedness = .unsigned, .bits = 16 },

                .anon_struct_type => unreachable,

                .ptr_type => unreachable,
                .anyframe_type => unreachable,
                .array_type => unreachable,

                .opt_type => unreachable,
                .error_union_type => unreachable,
                .func_type => unreachable,
                .simple_type => unreachable, // handled via Index enum tag above

                .union_type => unreachable,
                .opaque_type => unreachable,

                // values, not types
                .undef,
                .runtime_value,
                .simple_value,
                .variable,
                .extern_func,
                .func,
                .int,
                .err,
                .error_union,
                .enum_literal,
                .enum_tag,
                .empty_enum_value,
                .float,
                .ptr,
                .opt,
                .aggregate,
                .un,
                // memoization, not types
                .memoized_call,
                => unreachable,
            },
        };
    }

    pub fn isNamedInt(ty: Type) bool {
        return switch (ty.toIntern()) {
            .usize_type,
            .isize_type,
            .c_char_type,
            .c_short_type,
            .c_ushort_type,
            .c_int_type,
            .c_uint_type,
            .c_long_type,
            .c_ulong_type,
            .c_longlong_type,
            .c_ulonglong_type,
            => true,

            else => false,
        };
    }

    /// Returns `false` for `comptime_float`.
    pub fn isRuntimeFloat(ty: Type) bool {
        return switch (ty.toIntern()) {
            .f16_type,
            .f32_type,
            .f64_type,
            .f80_type,
            .f128_type,
            .c_longdouble_type,
            => true,

            else => false,
        };
    }

    /// Returns `true` for `comptime_float`.
    pub fn isAnyFloat(ty: Type) bool {
        return switch (ty.toIntern()) {
            .f16_type,
            .f32_type,
            .f64_type,
            .f80_type,
            .f128_type,
            .c_longdouble_type,
            .comptime_float_type,
            => true,

            else => false,
        };
    }

    /// Asserts the type is a fixed-size float or comptime_float.
    /// Returns 128 for comptime_float types.
    pub fn floatBits(ty: Type, target: Target) u16 {
        return switch (ty.toIntern()) {
            .f16_type => 16,
            .f32_type => 32,
            .f64_type => 64,
            .f80_type => 80,
            .f128_type, .comptime_float_type => 128,
            .c_longdouble_type => target.c_type_bit_size(.longdouble),

            else => unreachable,
        };
    }

    /// Asserts the type is a function or a function pointer.
    pub fn fnReturnType(ty: Type, mod: *Module) Type {
        return mod.intern_pool.funcTypeReturnType(ty.toIntern()).toType();
    }

    /// Asserts the type is a function.
    pub fn fnCallingConvention(ty: Type, mod: *Module) std.builtin.CallingConvention {
        return mod.intern_pool.indexToKey(ty.toIntern()).func_type.cc;
    }

    pub fn isValidParamType(self: Type, mod: *const Module) bool {
        return switch (self.zigTypeTagOrPoison(mod) catch return true) {
            .Opaque, .NoReturn => false,
            else => true,
        };
    }

    pub fn isValidReturnType(self: Type, mod: *const Module) bool {
        return switch (self.zigTypeTagOrPoison(mod) catch return true) {
            .Opaque => false,
            else => true,
        };
    }

    /// Asserts the type is a function.
    pub fn fnIsVarArgs(ty: Type, mod: *Module) bool {
        return mod.intern_pool.indexToKey(ty.toIntern()).func_type.is_var_args;
    }

    pub fn isNumeric(ty: Type, mod: *const Module) bool {
        return switch (ty.toIntern()) {
            .f16_type,
            .f32_type,
            .f64_type,
            .f80_type,
            .f128_type,
            .c_longdouble_type,
            .comptime_int_type,
            .comptime_float_type,
            .usize_type,
            .isize_type,
            .c_char_type,
            .c_short_type,
            .c_ushort_type,
            .c_int_type,
            .c_uint_type,
            .c_long_type,
            .c_ulong_type,
            .c_longlong_type,
            .c_ulonglong_type,
            => true,

            else => switch (mod.intern_pool.indexToKey(ty.toIntern())) {
                .int_type => true,
                else => false,
            },
        };
    }

    /// During semantic analysis, instead call `Sema.typeHasOnePossibleValue` which
    /// resolves field types rather than asserting they are already resolved.
    pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
        var ty = starting_type;
        const ip = &mod.intern_pool;
        while (true) switch (ty.toIntern()) {
            .empty_struct_type => return Value.empty_struct,

            else => switch (ip.indexToKey(ty.toIntern())) {
                .int_type => |int_type| {
                    if (int_type.bits == 0) {
                        return try mod.intValue(ty, 0);
                    } else {
                        return null;
                    }
                },

                .ptr_type,
                .error_union_type,
                .func_type,
                .anyframe_type,
                .error_set_type,
                .inferred_error_set_type,
                => return null,

                inline .array_type, .vector_type => |seq_type, seq_tag| {
                    const has_sentinel = seq_tag == .array_type and seq_type.sentinel != .none;
                    if (seq_type.len + @intFromBool(has_sentinel) == 0) return (try mod.intern(.{ .aggregate = .{
                        .ty = ty.toIntern(),
                        .storage = .{ .elems = &.{} },
                    } })).toValue();
                    if (try seq_type.child.toType().onePossibleValue(mod)) |opv| {
                        return (try mod.intern(.{ .aggregate = .{
                            .ty = ty.toIntern(),
                            .storage = .{ .repeated_elem = opv.toIntern() },
                        } })).toValue();
                    }
                    return null;
                },
                .opt_type => |child| {
                    if (child == .noreturn_type) {
                        return try mod.nullValue(ty);
                    } else {
                        return null;
                    }
                },

                .simple_type => |t| switch (t) {
                    .f16,
                    .f32,
                    .f64,
                    .f80,
                    .f128,
                    .usize,
                    .isize,
                    .c_char,
                    .c_short,
                    .c_ushort,
                    .c_int,
                    .c_uint,
                    .c_long,
                    .c_ulong,
                    .c_longlong,
                    .c_ulonglong,
                    .c_longdouble,
                    .anyopaque,
                    .bool,
                    .type,
                    .anyerror,
                    .comptime_int,
                    .comptime_float,
                    .enum_literal,
                    .atomic_order,
                    .atomic_rmw_op,
                    .calling_convention,
                    .address_space,
                    .float_mode,
                    .reduce_op,
                    .call_modifier,
                    .prefetch_options,
                    .export_options,
                    .extern_options,
                    .type_info,
                    .adhoc_inferred_error_set,
                    => return null,

                    .void => return Value.void,
                    .noreturn => return Value.@"unreachable",
                    .null => return Value.null,
                    .undefined => return Value.undef,

                    .generic_poison => unreachable,
                },
                .struct_type => |struct_type| {
                    assert(struct_type.haveFieldTypes(ip));
                    if (struct_type.knownNonOpv(ip))
                        return null;
                    const field_vals = try mod.gpa.alloc(InternPool.Index, struct_type.field_types.len);
                    defer mod.gpa.free(field_vals);
                    for (field_vals, 0..) |*field_val, i_usize| {
                        const i: u32 = @intCast(i_usize);
                        if (struct_type.fieldIsComptime(ip, i)) {
                            field_val.* = struct_type.field_inits.get(ip)[i];
                            continue;
                        }
                        const field_ty = struct_type.field_types.get(ip)[i].toType();
                        if (try field_ty.onePossibleValue(mod)) |field_opv| {
                            field_val.* = try field_opv.intern(field_ty, mod);
                        } else return null;
                    }

                    // In this case the struct has no runtime-known fields and
                    // therefore has one possible value.
                    return (try mod.intern(.{ .aggregate = .{
                        .ty = ty.toIntern(),
                        .storage = .{ .elems = field_vals },
                    } })).toValue();
                },

                .anon_struct_type => |tuple| {
                    for (tuple.values.get(ip)) |val| {
                        if (val == .none) return null;
                    }
                    // In this case the struct has all comptime-known fields and
                    // therefore has one possible value.
                    // TODO: write something like getCoercedInts to avoid needing to dupe
                    const duped_values = try mod.gpa.dupe(InternPool.Index, tuple.values.get(ip));
                    defer mod.gpa.free(duped_values);
                    return (try mod.intern(.{ .aggregate = .{
                        .ty = ty.toIntern(),
                        .storage = .{ .elems = duped_values },
                    } })).toValue();
                },

                .union_type => |union_type| {
                    const union_obj = ip.loadUnionType(union_type);
                    const tag_val = (try union_obj.enum_tag_ty.toType().onePossibleValue(mod)) orelse
                        return null;
                    if (union_obj.field_names.len == 0) {
                        const only = try mod.intern(.{ .empty_enum_value = ty.toIntern() });
                        return only.toValue();
                    }
                    const only_field_ty = union_obj.field_types.get(ip)[0];
                    const val_val = (try only_field_ty.toType().onePossibleValue(mod)) orelse
                        return null;
                    const only = try mod.intern(.{ .un = .{
                        .ty = ty.toIntern(),
                        .tag = tag_val.toIntern(),
                        .val = val_val.toIntern(),
                    } });
                    return only.toValue();
                },
                .opaque_type => return null,
                .enum_type => |enum_type| switch (enum_type.tag_mode) {
                    .nonexhaustive => {
                        if (enum_type.tag_ty == .comptime_int_type) return null;

                        if (try enum_type.tag_ty.toType().onePossibleValue(mod)) |int_opv| {
                            const only = try mod.intern(.{ .enum_tag = .{
                                .ty = ty.toIntern(),
                                .int = int_opv.toIntern(),
                            } });
                            return only.toValue();
                        }

                        return null;
                    },
                    .auto, .explicit => {
                        if (enum_type.tag_ty.toType().hasRuntimeBits(mod)) return null;

                        switch (enum_type.names.len) {
                            0 => {
                                const only = try mod.intern(.{ .empty_enum_value = ty.toIntern() });
                                return only.toValue();
                            },
                            1 => {
                                if (enum_type.values.len == 0) {
                                    const only = try mod.intern(.{ .enum_tag = .{
                                        .ty = ty.toIntern(),
                                        .int = try mod.intern(.{ .int = .{
                                            .ty = enum_type.tag_ty,
                                            .storage = .{ .u64 = 0 },
                                        } }),
                                    } });
                                    return only.toValue();
                                } else {
                                    return enum_type.values.get(ip)[0].toValue();
                                }
                            },
                            else => return null,
                        }
                    },
                },

                // values, not types
                .undef,
                .runtime_value,
                .simple_value,
                .variable,
                .extern_func,
                .func,
                .int,
                .err,
                .error_union,
                .enum_literal,
                .enum_tag,
                .empty_enum_value,
                .float,
                .ptr,
                .opt,
                .aggregate,
                .un,
                // memoization, not types
                .memoized_call,
                => unreachable,
            },
        };
    }

    /// During semantic analysis, instead call `Sema.typeRequiresComptime` which
    /// resolves field types rather than asserting they are already resolved.
    /// TODO merge these implementations together with the "advanced" pattern seen
    /// elsewhere in this file.
    pub fn comptimeOnly(ty: Type, mod: *Module) bool {
        const ip = &mod.intern_pool;
        return switch (ty.toIntern()) {
            .empty_struct_type => false,

            else => switch (ip.indexToKey(ty.toIntern())) {
                .int_type => false,
                .ptr_type => |ptr_type| {
                    const child_ty = ptr_type.child.toType();
                    switch (child_ty.zigTypeTag(mod)) {
                        .Fn => return !child_ty.isFnOrHasRuntimeBits(mod),
                        .Opaque => return false,
                        else => return child_ty.comptimeOnly(mod),
                    }
                },
                .anyframe_type => |child| {
                    if (child == .none) return false;
                    return child.toType().comptimeOnly(mod);
                },
                .array_type => |array_type| array_type.child.toType().comptimeOnly(mod),
                .vector_type => |vector_type| vector_type.child.toType().comptimeOnly(mod),
                .opt_type => |child| child.toType().comptimeOnly(mod),
                .error_union_type => |error_union_type| error_union_type.payload_type.toType().comptimeOnly(mod),

                .error_set_type,
                .inferred_error_set_type,
                => false,

                // These are function bodies, not function pointers.
                .func_type => true,

                .simple_type => |t| switch (t) {
                    .f16,
                    .f32,
                    .f64,
                    .f80,
                    .f128,
                    .usize,
                    .isize,
                    .c_char,
                    .c_short,
                    .c_ushort,
                    .c_int,
                    .c_uint,
                    .c_long,
                    .c_ulong,
                    .c_longlong,
                    .c_ulonglong,
                    .c_longdouble,
                    .anyopaque,
                    .bool,
                    .void,
                    .anyerror,
                    .adhoc_inferred_error_set,
                    .noreturn,
                    .generic_poison,
                    .atomic_order,
                    .atomic_rmw_op,
                    .calling_convention,
                    .address_space,
                    .float_mode,
                    .reduce_op,
                    .call_modifier,
                    .prefetch_options,
                    .export_options,
                    .extern_options,
                    => false,

                    .type,
                    .comptime_int,
                    .comptime_float,
                    .null,
                    .undefined,
                    .enum_literal,
                    .type_info,
                    => true,
                },
                .struct_type => |struct_type| {
                    // packed structs cannot be comptime-only because they have a well-defined
                    // memory layout and every field has a well-defined bit pattern.
                    if (struct_type.layout == .Packed)
                        return false;

                    // A struct with no fields is not comptime-only.
                    return switch (struct_type.flagsPtr(ip).requires_comptime) {
                        // Return false to avoid incorrect dependency loops.
                        // This will be handled correctly once merged with
                        // `Sema.typeRequiresComptime`.
                        .wip, .unknown => false,
                        .no => false,
                        .yes => true,
                    };
                },

                .anon_struct_type => |tuple| {
                    for (tuple.types.get(ip), tuple.values.get(ip)) |field_ty, val| {
                        const have_comptime_val = val != .none;
                        if (!have_comptime_val and field_ty.toType().comptimeOnly(mod)) return true;
                    }
                    return false;
                },

                .union_type => |union_type| {
                    switch (union_type.flagsPtr(ip).requires_comptime) {
                        .wip, .unknown => {
                            // Return false to avoid incorrect dependency loops.
                            // This will be handled correctly once merged with
                            // `Sema.typeRequiresComptime`.
                            return false;
                        },
                        .no => return false,
                        .yes => return true,
                    }
                },

                .opaque_type => false,

                .enum_type => |enum_type| enum_type.tag_ty.toType().comptimeOnly(mod),

                // values, not types
                .undef,
                .runtime_value,
                .simple_value,
                .variable,
                .extern_func,
                .func,
                .int,
                .err,
                .error_union,
                .enum_literal,
                .enum_tag,
                .empty_enum_value,
                .float,
                .ptr,
                .opt,
                .aggregate,
                .un,
                // memoization, not types
                .memoized_call,
                => unreachable,
            },
        };
    }

    pub fn isVector(ty: Type, mod: *const Module) bool {
        return ty.zigTypeTag(mod) == .Vector;
    }

    pub fn isArrayOrVector(ty: Type, mod: *const Module) bool {
        return switch (ty.zigTypeTag(mod)) {
            .Array, .Vector => true,
            else => false,
        };
    }

    pub fn isIndexable(ty: Type, mod: *Module) bool {
        return switch (ty.zigTypeTag(mod)) {
            .Array, .Vector => true,
            .Pointer => switch (ty.ptrSize(mod)) {
                .Slice, .Many, .C => true,
                .One => switch (ty.childType(mod).zigTypeTag(mod)) {
                    .Array, .Vector => true,
                    .Struct => ty.childType(mod).isTuple(mod),
                    else => false,
                },
            },
            .Struct => ty.isTuple(mod),
            else => false,
        };
    }

    pub fn indexableHasLen(ty: Type, mod: *Module) bool {
        return switch (ty.zigTypeTag(mod)) {
            .Array, .Vector => true,
            .Pointer => switch (ty.ptrSize(mod)) {
                .Many, .C => false,
                .Slice => true,
                .One => switch (ty.childType(mod).zigTypeTag(mod)) {
                    .Array, .Vector => true,
                    .Struct => ty.childType(mod).isTuple(mod),
                    else => false,
                },
            },
            .Struct => ty.isTuple(mod),
            else => false,
        };
    }

    /// Returns null if the type has no namespace.
    pub fn getNamespaceIndex(ty: Type, mod: *Module) Module.Namespace.OptionalIndex {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .opaque_type => |opaque_type| opaque_type.namespace.toOptional(),
            .struct_type => |struct_type| struct_type.namespace,
            .union_type => |union_type| union_type.namespace.toOptional(),
            .enum_type => |enum_type| enum_type.namespace,

            else => .none,
        };
    }

    /// Returns null if the type has no namespace.
    pub fn getNamespace(ty: Type, mod: *Module) ?*Module.Namespace {
        return if (getNamespaceIndex(ty, mod).unwrap()) |i| mod.namespacePtr(i) else null;
    }

    // Works for vectors and vectors of integers.
    pub fn minInt(ty: Type, mod: *Module, dest_ty: Type) !Value {
        const scalar = try minIntScalar(ty.scalarType(mod), mod, dest_ty.scalarType(mod));
        return if (ty.zigTypeTag(mod) == .Vector) (try mod.intern(.{ .aggregate = .{
            .ty = dest_ty.toIntern(),
            .storage = .{ .repeated_elem = scalar.toIntern() },
        } })).toValue() else scalar;
    }

    /// Asserts that the type is an integer.
    pub fn minIntScalar(ty: Type, mod: *Module, dest_ty: Type) !Value {
        const info = ty.intInfo(mod);
        if (info.signedness == .unsigned) return mod.intValue(dest_ty, 0);
        if (info.bits == 0) return mod.intValue(dest_ty, -1);

        if (std.math.cast(u6, info.bits - 1)) |shift| {
            const n = @as(i64, std.math.minInt(i64)) >> (63 - shift);
            return mod.intValue(dest_ty, n);
        }

        var res = try std.math.big.int.Managed.init(mod.gpa);
        defer res.deinit();

        try res.setTwosCompIntLimit(.min, info.signedness, info.bits);

        return mod.intValue_big(dest_ty, res.toConst());
    }

    // Works for vectors and vectors of integers.
    /// The returned Value will have type dest_ty.
    pub fn maxInt(ty: Type, mod: *Module, dest_ty: Type) !Value {
        const scalar = try maxIntScalar(ty.scalarType(mod), mod, dest_ty.scalarType(mod));
        return if (ty.zigTypeTag(mod) == .Vector) (try mod.intern(.{ .aggregate = .{
            .ty = dest_ty.toIntern(),
            .storage = .{ .repeated_elem = scalar.toIntern() },
        } })).toValue() else scalar;
    }

    /// The returned Value will have type dest_ty.
    pub fn maxIntScalar(ty: Type, mod: *Module, dest_ty: Type) !Value {
        const info = ty.intInfo(mod);

        switch (info.bits) {
            0 => return switch (info.signedness) {
                .signed => try mod.intValue(dest_ty, -1),
                .unsigned => try mod.intValue(dest_ty, 0),
            },
            1 => return switch (info.signedness) {
                .signed => try mod.intValue(dest_ty, 0),
                .unsigned => try mod.intValue(dest_ty, 1),
            },
            else => {},
        }

        if (std.math.cast(u6, info.bits - 1)) |shift| switch (info.signedness) {
            .signed => {
                const n = @as(i64, std.math.maxInt(i64)) >> (63 - shift);
                return mod.intValue(dest_ty, n);
            },
            .unsigned => {
                const n = @as(u64, std.math.maxInt(u64)) >> (63 - shift);
                return mod.intValue(dest_ty, n);
            },
        };

        var res = try std.math.big.int.Managed.init(mod.gpa);
        defer res.deinit();

        try res.setTwosCompIntLimit(.max, info.signedness, info.bits);

        return mod.intValue_big(dest_ty, res.toConst());
    }

    /// Asserts the type is an enum or a union.
    pub fn intTagType(ty: Type, mod: *Module) Type {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .union_type => |union_type| union_type.enum_tag_ty.toType().intTagType(mod),
            .enum_type => |enum_type| enum_type.tag_ty.toType(),
            else => unreachable,
        };
    }

    pub fn isNonexhaustiveEnum(ty: Type, mod: *Module) bool {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .enum_type => |enum_type| switch (enum_type.tag_mode) {
                .nonexhaustive => true,
                .auto, .explicit => false,
            },
            else => false,
        };
    }

    // Asserts that `ty` is an error set and not `anyerror`.
    // Asserts that `ty` is resolved if it is an inferred error set.
    pub fn errorSetNames(ty: Type, mod: *Module) []const InternPool.NullTerminatedString {
        const ip = &mod.intern_pool;
        return switch (ip.indexToKey(ty.toIntern())) {
            .error_set_type => |x| x.names.get(ip),
            .inferred_error_set_type => |i| switch (ip.funcIesResolved(i).*) {
                .none => unreachable, // unresolved inferred error set
                .anyerror_type => unreachable,
                else => |t| ip.indexToKey(t).error_set_type.names.get(ip),
            },
            else => unreachable,
        };
    }

    pub fn enumFields(ty: Type, mod: *Module) []const InternPool.NullTerminatedString {
        const ip = &mod.intern_pool;
        return ip.indexToKey(ty.toIntern()).enum_type.names.get(ip);
    }

    pub fn enumFieldCount(ty: Type, mod: *Module) usize {
        return mod.intern_pool.indexToKey(ty.toIntern()).enum_type.names.len;
    }

    pub fn enumFieldName(ty: Type, field_index: usize, mod: *Module) InternPool.NullTerminatedString {
        const ip = &mod.intern_pool;
        return ip.indexToKey(ty.toIntern()).enum_type.names.get(ip)[field_index];
    }

    pub fn enumFieldIndex(ty: Type, field_name: InternPool.NullTerminatedString, mod: *Module) ?u32 {
        const ip = &mod.intern_pool;
        const enum_type = ip.indexToKey(ty.toIntern()).enum_type;
        return enum_type.nameIndex(ip, field_name);
    }

    /// Asserts `ty` is an enum. `enum_tag` can either be `enum_field_index` or
    /// an integer which represents the enum value. Returns the field index in
    /// declaration order, or `null` if `enum_tag` does not match any field.
    pub fn enumTagFieldIndex(ty: Type, enum_tag: Value, mod: *Module) ?u32 {
        const ip = &mod.intern_pool;
        const enum_type = ip.indexToKey(ty.toIntern()).enum_type;
        const int_tag = switch (ip.indexToKey(enum_tag.toIntern())) {
            .int => enum_tag.toIntern(),
            .enum_tag => |info| info.int,
            else => unreachable,
        };
        assert(ip.typeOf(int_tag) == enum_type.tag_ty);
        return enum_type.tagValueIndex(ip, int_tag);
    }

    pub fn structFieldName(ty: Type, field_index: usize, mod: *Module) InternPool.NullTerminatedString {
        const ip = &mod.intern_pool;
        return switch (ip.indexToKey(ty.toIntern())) {
            .struct_type => |struct_type| struct_type.field_names.get(ip)[field_index],
            .anon_struct_type => |anon_struct| anon_struct.names.get(ip)[field_index],
            else => unreachable,
        };
    }

    pub fn structFieldCount(ty: Type, mod: *Module) usize {
        const ip = &mod.intern_pool;
        return switch (ip.indexToKey(ty.toIntern())) {
            .struct_type => |struct_type| struct_type.field_types.len,
            .anon_struct_type => |anon_struct| anon_struct.types.len,
            else => unreachable,
        };
    }

    /// Supports structs and unions.
    pub fn structFieldType(ty: Type, index: usize, mod: *Module) Type {
        const ip = &mod.intern_pool;
        return switch (ip.indexToKey(ty.toIntern())) {
            .struct_type => |struct_type| struct_type.field_types.get(ip)[index].toType(),
            .union_type => |union_type| {
                const union_obj = ip.loadUnionType(union_type);
                return union_obj.field_types.get(ip)[index].toType();
            },
            .anon_struct_type => |anon_struct| anon_struct.types.get(ip)[index].toType(),
            else => unreachable,
        };
    }

    pub fn structFieldAlign(ty: Type, index: usize, mod: *Module) Alignment {
        const ip = &mod.intern_pool;
        switch (ip.indexToKey(ty.toIntern())) {
            .struct_type => |struct_type| {
                assert(struct_type.layout != .Packed);
                const explicit_align = struct_type.fieldAlign(ip, index);
                const field_ty = struct_type.field_types.get(ip)[index].toType();
                return mod.structFieldAlignment(explicit_align, field_ty, struct_type.layout);
            },
            .anon_struct_type => |anon_struct| {
                return anon_struct.types.get(ip)[index].toType().abiAlignment(mod);
            },
            .union_type => |union_type| {
                const union_obj = ip.loadUnionType(union_type);
                return mod.unionFieldNormalAlignment(union_obj, @intCast(index));
            },
            else => unreachable,
        }
    }

    pub fn structFieldDefaultValue(ty: Type, index: usize, mod: *Module) Value {
        const ip = &mod.intern_pool;
        switch (ip.indexToKey(ty.toIntern())) {
            .struct_type => |struct_type| {
                const val = struct_type.fieldInit(ip, index);
                // TODO: avoid using `unreachable` to indicate this.
                if (val == .none) return Value.@"unreachable";
                return val.toValue();
            },
            .anon_struct_type => |anon_struct| {
                const val = anon_struct.values.get(ip)[index];
                // TODO: avoid using `unreachable` to indicate this.
                if (val == .none) return Value.@"unreachable";
                return val.toValue();
            },
            else => unreachable,
        }
    }

    pub fn structFieldValueComptime(ty: Type, mod: *Module, index: usize) !?Value {
        const ip = &mod.intern_pool;
        switch (ip.indexToKey(ty.toIntern())) {
            .struct_type => |struct_type| {
                if (struct_type.fieldIsComptime(ip, index)) {
                    return struct_type.field_inits.get(ip)[index].toValue();
                } else {
                    return struct_type.field_types.get(ip)[index].toType().onePossibleValue(mod);
                }
            },
            .anon_struct_type => |tuple| {
                const val = tuple.values.get(ip)[index];
                if (val == .none) {
                    return tuple.types.get(ip)[index].toType().onePossibleValue(mod);
                } else {
                    return val.toValue();
                }
            },
            else => unreachable,
        }
    }

    pub fn structFieldIsComptime(ty: Type, index: usize, mod: *Module) bool {
        const ip = &mod.intern_pool;
        return switch (ip.indexToKey(ty.toIntern())) {
            .struct_type => |struct_type| struct_type.fieldIsComptime(ip, index),
            .anon_struct_type => |anon_struct| anon_struct.values.get(ip)[index] != .none,
            else => unreachable,
        };
    }

    pub fn packedStructFieldByteOffset(ty: Type, field_index: usize, mod: *Module) u32 {
        const ip = &mod.intern_pool;
        const struct_type = ip.indexToKey(ty.toIntern()).struct_type;
        assert(struct_type.layout == .Packed);
        comptime assert(Type.packed_struct_layout_version == 2);

        var bit_offset: u16 = undefined;
        var elem_size_bits: u16 = undefined;
        var running_bits: u16 = 0;
        for (struct_type.field_types.get(ip), 0..) |field_ty, i| {
            if (!field_ty.toType().hasRuntimeBits(mod)) continue;

            const field_bits: u16 = @intCast(field_ty.toType().bitSize(mod));
            if (i == field_index) {
                bit_offset = running_bits;
                elem_size_bits = field_bits;
            }
            running_bits += field_bits;
        }
        const byte_offset = bit_offset / 8;
        return byte_offset;
    }

    pub const FieldOffset = struct {
        field: usize,
        offset: u64,
    };

    /// Supports structs and unions.
    pub fn structFieldOffset(ty: Type, index: usize, mod: *Module) u64 {
        const ip = &mod.intern_pool;
        switch (ip.indexToKey(ty.toIntern())) {
            .struct_type => |struct_type| {
                assert(struct_type.haveLayout(ip));
                assert(struct_type.layout != .Packed);
                return struct_type.offsets.get(ip)[index];
            },

            .anon_struct_type => |tuple| {
                var offset: u64 = 0;
                var big_align: Alignment = .none;

                for (tuple.types.get(ip), tuple.values.get(ip), 0..) |field_ty, field_val, i| {
                    if (field_val != .none or !field_ty.toType().hasRuntimeBits(mod)) {
                        // comptime field
                        if (i == index) return offset;
                        continue;
                    }

                    const field_align = field_ty.toType().abiAlignment(mod);
                    big_align = big_align.max(field_align);
                    offset = field_align.forward(offset);
                    if (i == index) return offset;
                    offset += field_ty.toType().abiSize(mod);
                }
                offset = big_align.max(.@"1").forward(offset);
                return offset;
            },

            .union_type => |union_type| {
                if (!union_type.hasTag(ip))
                    return 0;
                const union_obj = ip.loadUnionType(union_type);
                const layout = mod.getUnionLayout(union_obj);
                if (layout.tag_align.compare(.gte, layout.payload_align)) {
                    // {Tag, Payload}
                    return layout.payload_align.forward(layout.tag_size);
                } else {
                    // {Payload, Tag}
                    return 0;
                }
            },

            else => unreachable,
        }
    }

    pub fn declSrcLoc(ty: Type, mod: *Module) Module.SrcLoc {
        return declSrcLocOrNull(ty, mod).?;
    }

    pub fn declSrcLocOrNull(ty: Type, mod: *Module) ?Module.SrcLoc {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .struct_type => |struct_type| {
                return mod.declPtr(struct_type.decl.unwrap() orelse return null).srcLoc(mod);
            },
            .union_type => |union_type| {
                return mod.declPtr(union_type.decl).srcLoc(mod);
            },
            .opaque_type => |opaque_type| mod.opaqueSrcLoc(opaque_type),
            .enum_type => |enum_type| mod.declPtr(enum_type.decl).srcLoc(mod),
            else => null,
        };
    }

    pub fn getOwnerDecl(ty: Type, mod: *Module) Module.Decl.Index {
        return ty.getOwnerDeclOrNull(mod) orelse unreachable;
    }

    pub fn getOwnerDeclOrNull(ty: Type, mod: *Module) ?Module.Decl.Index {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .struct_type => |struct_type| struct_type.decl.unwrap(),
            .union_type => |union_type| union_type.decl,
            .opaque_type => |opaque_type| opaque_type.decl,
            .enum_type => |enum_type| enum_type.decl,
            else => null,
        };
    }

    pub fn isGenericPoison(ty: Type) bool {
        return ty.toIntern() == .generic_poison_type;
    }

    pub fn isTuple(ty: Type, mod: *Module) bool {
        const ip = &mod.intern_pool;
        return switch (ip.indexToKey(ty.toIntern())) {
            .struct_type => |struct_type| {
                if (struct_type.layout == .Packed) return false;
                if (struct_type.decl == .none) return false;
                return struct_type.flagsPtr(ip).is_tuple;
            },
            .anon_struct_type => |anon_struct| anon_struct.names.len == 0,
            else => false,
        };
    }

    pub fn isAnonStruct(ty: Type, mod: *Module) bool {
        if (ty.toIntern() == .empty_struct_type) return true;
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .anon_struct_type => |anon_struct_type| anon_struct_type.names.len > 0,
            else => false,
        };
    }

    pub fn isTupleOrAnonStruct(ty: Type, mod: *Module) bool {
        const ip = &mod.intern_pool;
        return switch (ip.indexToKey(ty.toIntern())) {
            .struct_type => |struct_type| {
                if (struct_type.layout == .Packed) return false;
                if (struct_type.decl == .none) return false;
                return struct_type.flagsPtr(ip).is_tuple;
            },
            .anon_struct_type => true,
            else => false,
        };
    }

    pub fn isSimpleTuple(ty: Type, mod: *Module) bool {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .anon_struct_type => |anon_struct_type| anon_struct_type.names.len == 0,
            else => false,
        };
    }

    pub fn isSimpleTupleOrAnonStruct(ty: Type, mod: *Module) bool {
        return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
            .anon_struct_type => true,
            else => false,
        };
    }

    pub const @"u1": Type = .{ .ip_index = .u1_type };
    pub const @"u8": Type = .{ .ip_index = .u8_type };
    pub const @"u16": Type = .{ .ip_index = .u16_type };
    pub const @"u29": Type = .{ .ip_index = .u29_type };
    pub const @"u32": Type = .{ .ip_index = .u32_type };
    pub const @"u64": Type = .{ .ip_index = .u64_type };
    pub const @"u128": Type = .{ .ip_index = .u128_type };

    pub const @"i8": Type = .{ .ip_index = .i8_type };
    pub const @"i16": Type = .{ .ip_index = .i16_type };
    pub const @"i32": Type = .{ .ip_index = .i32_type };
    pub const @"i64": Type = .{ .ip_index = .i64_type };
    pub const @"i128": Type = .{ .ip_index = .i128_type };

    pub const @"f16": Type = .{ .ip_index = .f16_type };
    pub const @"f32": Type = .{ .ip_index = .f32_type };
    pub const @"f64": Type = .{ .ip_index = .f64_type };
    pub const @"f80": Type = .{ .ip_index = .f80_type };
    pub const @"f128": Type = .{ .ip_index = .f128_type };

    pub const @"bool": Type = .{ .ip_index = .bool_type };
    pub const @"usize": Type = .{ .ip_index = .usize_type };
    pub const @"isize": Type = .{ .ip_index = .isize_type };
    pub const @"comptime_int": Type = .{ .ip_index = .comptime_int_type };
    pub const @"comptime_float": Type = .{ .ip_index = .comptime_float_type };
    pub const @"void": Type = .{ .ip_index = .void_type };
    pub const @"type": Type = .{ .ip_index = .type_type };
    pub const @"anyerror": Type = .{ .ip_index = .anyerror_type };
    pub const @"anyopaque": Type = .{ .ip_index = .anyopaque_type };
    pub const @"anyframe": Type = .{ .ip_index = .anyframe_type };
    pub const @"null": Type = .{ .ip_index = .null_type };
    pub const @"undefined": Type = .{ .ip_index = .undefined_type };
    pub const @"noreturn": Type = .{ .ip_index = .noreturn_type };

    pub const @"c_char": Type = .{ .ip_index = .c_char_type };
    pub const @"c_short": Type = .{ .ip_index = .c_short_type };
    pub const @"c_ushort": Type = .{ .ip_index = .c_ushort_type };
    pub const @"c_int": Type = .{ .ip_index = .c_int_type };
    pub const @"c_uint": Type = .{ .ip_index = .c_uint_type };
    pub const @"c_long": Type = .{ .ip_index = .c_long_type };
    pub const @"c_ulong": Type = .{ .ip_index = .c_ulong_type };
    pub const @"c_longlong": Type = .{ .ip_index = .c_longlong_type };
    pub const @"c_ulonglong": Type = .{ .ip_index = .c_ulonglong_type };
    pub const @"c_longdouble": Type = .{ .ip_index = .c_longdouble_type };

    pub const slice_const_u8: Type = .{ .ip_index = .slice_const_u8_type };
    pub const manyptr_u8: Type = .{ .ip_index = .manyptr_u8_type };
    pub const single_const_pointer_to_comptime_int: Type = .{
        .ip_index = .single_const_pointer_to_comptime_int_type,
    };
    pub const slice_const_u8_sentinel_0: Type = .{ .ip_index = .slice_const_u8_sentinel_0_type };
    pub const empty_struct_literal: Type = .{ .ip_index = .empty_struct_type };

    pub const generic_poison: Type = .{ .ip_index = .generic_poison_type };

    pub const err_int = Type.u16;

    pub fn smallestUnsignedBits(max: u64) u16 {
        if (max == 0) return 0;
        const base = std.math.log2(max);
        const upper = (@as(u64, 1) << @as(u6, @intCast(base))) - 1;
        return @as(u16, @intCast(base + @intFromBool(upper < max)));
    }

    /// This is only used for comptime asserts. Bump this number when you make a change
    /// to packed struct layout to find out all the places in the codebase you need to edit!
    pub const packed_struct_layout_version = 2;
};

fn cTypeAlign(target: Target, c_type: Target.CType) Alignment {
    return Alignment.fromByteUnits(target.c_type_alignment(c_type));
}