llvm-native-core 0.1.16

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
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
//! APInt — Arbitrary Precision Integers
//!
//! Clean-room implementation based on standard algorithms from computer science
//! literature (Knuth, Hacker's Delight, etc.). No LLVM source code was consulted.
//!
//! APInt represents fixed-width integer values. The bit width is fixed at
//! construction time and determines the range. All arithmetic operations are
//! wrapping (modulo 2^bit_width). Signed operations follow C99 truncation-toward-zero
//! semantics.

use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::{Add, BitAnd, BitOr, BitXor, Mul, Neg, Not, Shl, Shr, Sub};

// ---------------------------------------------------------------------------
// APInt struct
// ---------------------------------------------------------------------------

/// Arbitrary-precision integer with a fixed bit width (≥ 1).
///
/// The value is stored as a little-endian array of 64-bit words.
/// Only `ceil(bit_width / 64)` words are allocated; unused high bits
/// in the last word are guaranteed to be zero after any public operation.
#[derive(Clone)]
pub struct APInt {
    /// Bit width of this integer (≥ 1).
    bit_width: u32,
    /// Value stored as little-endian 64-bit words.
    /// For bit_width ≤ 64, a single word is used; for wider widths,
    /// additional words hold the higher-order bits.
    words: Vec<u64>,
}

// ---------------------------------------------------------------------------
// Internal helpers (free functions)
// ---------------------------------------------------------------------------

/// Number of u64 words needed for `bit_width` bits.
#[inline]
fn num_words(bit_width: u32) -> usize {
    debug_assert!(bit_width >= 1, "bit_width must be >= 1");
    ((bit_width as usize + 63) / 64).max(1)
}

/// Create a mask for the valid bits in the last word.
/// Returns `!0u64` when bit_width is a multiple of 64 (all bits valid).
#[inline]
fn last_word_mask(bit_width: u32) -> u64 {
    let bits_in_last = bit_width % 64;
    if bits_in_last == 0 {
        u64::MAX
    } else {
        (1u64 << bits_in_last) - 1
    }
}

/// Number of unused high bits in the last word.
#[inline]
fn excess_bits(bit_width: u32) -> u32 {
    let rem = bit_width % 64;
    if rem == 0 {
        0
    } else {
        64 - rem
    }
}

// ---------------------------------------------------------------------------
// Word-level arithmetic primitives
// ---------------------------------------------------------------------------

/// Add two same-length word slices with optional carry-in.
/// Returns (result_words, carry_out).
fn add_words(a: &[u64], b: &[u64]) -> (Vec<u64>, bool) {
    let n = a.len().max(b.len());
    let mut result = vec![0u64; n];
    let mut carry = false;
    for i in 0..n {
        let av = a.get(i).copied().unwrap_or(0);
        let bv = b.get(i).copied().unwrap_or(0);
        let (sum1, c1) = av.overflowing_add(bv);
        let (sum2, c2) = sum1.overflowing_add(carry as u64);
        result[i] = sum2;
        carry = c1 || c2;
    }
    (result, carry)
}

/// Subtract `b` from `a` (same-length word slices) with optional borrow-in.
/// Returns (result_words, borrow_out).
fn sub_words(a: &[u64], b: &[u64]) -> (Vec<u64>, bool) {
    let n = a.len().max(b.len());
    let mut result = vec![0u64; n];
    let mut borrow = false;
    for i in 0..n {
        let av = a.get(i).copied().unwrap_or(0);
        let bv = b.get(i).copied().unwrap_or(0);
        let (diff1, b1) = av.overflowing_sub(bv);
        let (diff2, b2) = diff1.overflowing_sub(borrow as u64);
        result[i] = diff2;
        borrow = b1 || b2;
    }
    (result, borrow)
}

/// Multiply two word slices.  The result has length `a.len() + b.len()`.
fn mul_words(a: &[u64], b: &[u64]) -> Vec<u64> {
    let n = a.len() + b.len();
    let mut result = vec![0u64; n];
    for i in 0..a.len() {
        let mut carry: u64 = 0;
        for j in 0..b.len() {
            let product =
                (a[i] as u128) * (b[j] as u128) + (result[i + j] as u128) + (carry as u128);
            result[i + j] = product as u64;
            carry = (product >> 64) as u64;
        }
        result[i + b.len()] = carry;
    }
    result
}

/// Divide `dividend` (little-endian words) by a single-word `divisor`.
/// Returns `(quotient_words, remainder)`.
fn div_rem_single(dividend: &[u64], divisor: u64) -> (Vec<u64>, u64) {
    let mut quotient = vec![0u64; dividend.len()];
    let mut remainder: u64 = 0;
    for i in (0..dividend.len()).rev() {
        let d = ((remainder as u128) << 64) | (dividend[i] as u128);
        quotient[i] = (d / divisor as u128) as u64;
        remainder = (d % divisor as u128) as u64;
    }
    (quotient, remainder)
}

/// Divide two multi-word numbers (little-endian words).
/// `n` = dividend, `d` = divisor.  Both are normalized (no leading zeros).
/// Returns `(quotient, remainder)` where quotient and remainder have the same
/// length as `n`.  Panics if divisor is zero.
fn div_rem_multi(n: &[u64], d: &[u64]) -> (Vec<u64>, Vec<u64>) {
    // Assert divisor is not zero.
    debug_assert!(!d.iter().all(|&w| w == 0), "division by zero");
    let m = n.len();
    // If divisor is single-word, use fast path.
    let d_nwords = d.iter().rposition(|&w| w != 0).map(|i| i + 1).unwrap_or(0);
    if d_nwords <= 1 {
        let divisor = if d_nwords == 0 { 0 } else { d[0] };
        if divisor == 1 {
            return (n.to_vec(), vec![0u64; m]);
        }
        let (q, r) = div_rem_single(n, divisor);
        let mut rem = vec![0u64; m];
        rem[0] = r;
        return (q, rem);
    }

    // Multi-word division using binary long division (shift-subtract).
    // This is O(n^2) but correct for all sizes.
    let mut remainder = n.to_vec();
    let mut quotient = vec![0u64; m];

    // Total significant bits of dividend and divisor.
    let n_bits = significant_bits(n);
    let d_bits = significant_bits(d);

    if n_bits < d_bits {
        return (quotient, remainder);
    }

    // We work bit-by-bit from most significant to least.
    let shift = n_bits - d_bits;
    // For each bit position from shift down to 0:
    for pos in (0..=shift).rev() {
        // Left-shift divisor by `pos` bits (logically) and compare/subtract.
        if cmp_shifted(&remainder, d, pos) != Ordering::Less {
            sub_shifted(&mut remainder, d, pos);
            // Set bit `pos` in quotient.
            let word_idx = (pos as usize) / 64;
            let bit_idx = (pos as usize) % 64;
            quotient[word_idx] |= 1u64 << bit_idx;
        }
    }

    (quotient, remainder)
}

/// Compare `a` against `b` left-shifted by `shift` bits.
fn cmp_shifted(a: &[u64], b: &[u64], shift: usize) -> Ordering {
    let word_shift = shift / 64;
    let bit_shift = (shift % 64) as u32;

    // We compare starting from the most significant possible word.
    let a_bits = significant_bits(a);
    let b_bits = significant_bits(b);
    let b_shifted_bits = b_bits + shift;

    if a_bits > b_shifted_bits {
        return Ordering::Greater;
    }
    if a_bits < b_shifted_bits {
        return Ordering::Less;
    }

    // Same bit length; compare word by word from high to low.
    let max_word = (b_shifted_bits + 63) / 64;
    for i in (0..max_word).rev() {
        let a_word = a.get(i).copied().unwrap_or(0);
        let b_word = get_shifted_word(b, i, word_shift, bit_shift);
        match a_word.cmp(&b_word) {
            Ordering::Equal => continue,
            ord => return ord,
        }
    }
    Ordering::Equal
}

/// Get the word at logical index `i` from `b` left-shifted by `(word_shift, bit_shift)`.
fn get_shifted_word(b: &[u64], i: usize, word_shift: usize, bit_shift: u32) -> u64 {
    let lo_idx = i.wrapping_sub(word_shift);
    let hi_idx = lo_idx.wrapping_sub(1);
    let lo = b.get(lo_idx).copied().unwrap_or(0);
    let hi = if lo_idx == 0 {
        0
    } else {
        b.get(hi_idx).copied().unwrap_or(0)
    };

    if bit_shift == 0 {
        lo
    } else {
        (lo << bit_shift) | (hi >> (64 - bit_shift))
    }
}

/// Subtract `b << shift` from `a` (in-place).
fn sub_shifted(a: &mut [u64], b: &[u64], shift: usize) {
    let word_shift = shift / 64;
    let bit_shift = (shift % 64) as u32;
    let mut borrow: u64 = 0;

    for i in 0..a.len() {
        let b_word = get_shifted_word(b, i, word_shift, bit_shift);
        let (diff1, b1) = a[i].overflowing_sub(b_word);
        let (diff2, b2) = diff1.overflowing_sub(borrow);
        a[i] = diff2;
        borrow = (b1 as u64) + (b2 as u64);
    }
}

/// Count significant bits (position of highest set bit + 1) in a word slice.
fn significant_bits(words: &[u64]) -> usize {
    for i in (0..words.len()).rev() {
        if words[i] != 0 {
            return i * 64 + 64 - words[i].leading_zeros() as usize;
        }
    }
    0
}

// ---------------------------------------------------------------------------
// Construction
// ---------------------------------------------------------------------------

impl APInt {
    /// Create an APInt from a u64 value.
    ///
    /// If `is_signed` is true, the u64 is interpreted as a signed 64-bit value
    /// and sign-extended to `bit_width`.  If false, it is zero-extended.
    ///
    /// # Panics
    /// Panics if `bit_width` is zero.
    pub fn new(bit_width: u32, val: u64, is_signed: bool) -> Self {
        assert!(bit_width >= 1, "APInt::new: bit_width must be >= 1, got 0");
        let nw = num_words(bit_width);
        let mut words = vec![0u64; nw];
        words[0] = val;

        if is_signed && (val >> 63) != 0 {
            // Sign-extend: fill all upper words with 1s.
            for w in words.iter_mut().skip(1) {
                *w = u64::MAX;
            }
        }

        let mut result = APInt { bit_width, words };
        result.clear_unused_bits();
        result.normalize();
        result
    }

    /// Returns the bit width of this integer.
    pub fn bit_width(&self) -> u32 {
        self.bit_width
    }

    /// Create an APInt from a single u64 (zero-extended).
    /// Create from a u64 value (zero-extended to `bit_width`).
    ///
    /// # Panics
    /// Panics if `bit_width` is zero.
    pub fn from_u64(bit_width: u32, val: u64) -> Self {
        Self::new(bit_width, val, false)
    }

    /// Create from an i64 value (sign-extended to `bit_width`).
    ///
    /// # Panics
    /// Panics if `bit_width` is zero.
    pub fn from_i64(bit_width: u32, val: i64) -> Self {
        Self::new(bit_width, val as u64, true)
    }

    /// Create an APInt representing zero.
    pub fn get_zero(bit_width: u32) -> Self {
        Self::new(bit_width, 0, false)
    }

    /// Create an APInt representing one.
    pub fn get_one(bit_width: u32) -> Self {
        Self::new(bit_width, 1, false)
    }

    /// Create an APInt with all bits set (the maximum unsigned value).
    pub fn get_all_ones(bit_width: u32) -> Self {
        assert!(bit_width >= 1, "get_all_ones: bit_width must be >= 1");
        let nw = num_words(bit_width);
        let mut words = vec![u64::MAX; nw];
        let mask = last_word_mask(bit_width);
        if let Some(last) = words.last_mut() {
            *last &= mask;
        }
        APInt { bit_width, words }
    }

    /// Create the maximum unsigned value for the given width.
    pub fn get_max_value(bit_width: u32) -> Self {
        Self::get_all_ones(bit_width)
    }

    /// Create the minimum unsigned value (zero).
    pub fn get_min_value(bit_width: u32) -> Self {
        Self::get_zero(bit_width)
    }

    /// Create the maximum signed value: `2^(bit_width-1) - 1`.
    pub fn get_signed_max_value(bit_width: u32) -> Self {
        assert!(bit_width >= 1);
        let mut result = Self::get_all_ones(bit_width);
        // Clear the sign bit.
        if let Some(w) = result.words.last_mut() {
            let sign_bit_pos = (bit_width - 1) % 64;
            *w &= !(1u64 << sign_bit_pos);
        }
        result.clear_unused_bits();
        result
    }

    /// Create the minimum signed value: `-2^(bit_width-1)`.
    pub fn get_signed_min_value(bit_width: u32) -> Self {
        assert!(bit_width >= 1);
        let nw = num_words(bit_width);
        let mut words = vec![0u64; nw];
        // Set only the sign bit.
        let sign_word = ((bit_width - 1) / 64) as usize;
        let sign_bit = (bit_width - 1) % 64;
        words[sign_word] = 1u64 << sign_bit;
        APInt { bit_width, words }
    }

    /// Parse a string in the given radix.
    ///
    /// Supported radices: 2, 8, 10, 16.  Radix 0 means auto-detect from prefix:
    /// - `0x` / `0X` → 16
    /// - `0b` / `0B` → 2
    /// - `0o` / `0O` → 8
    /// - otherwise → 10
    ///
    /// The result has a bit width large enough to hold the parsed value without
    /// truncation.  If the string is empty or contains invalid digits, an error
    /// is returned.
    pub fn from_string(s: &str, radix: u8) -> Result<Self, String> {
        let s = s.trim();
        if s.is_empty() {
            return Err("empty string".to_string());
        }

        // Detect radix from prefix.
        let (radix, digits) = detect_radix_and_strip(s, radix)?;

        if digits.is_empty() {
            return Err("no digits after prefix".to_string());
        }

        // Parse each digit, building up the value.
        // We'll use repeated multiplication by radix and addition.
        // Start with a reasonable initial width and grow as needed.
        let bits_per_digit = radix.ilog2().max(1);
        let initial_width = (digits.len() as u32 * bits_per_digit).max(1);
        let nw = num_words(initial_width);
        let mut result = APInt {
            bit_width: initial_width,
            words: vec![0u64; nw],
        };

        for &b in digits.as_bytes() {
            let digit = match b {
                b'0'..=b'9' => (b - b'0') as u64,
                b'a'..=b'f' => (b - b'a' + 10) as u64,
                b'A'..=b'F' => (b - b'A' + 10) as u64,
                _ => return Err(format!("invalid digit '{}' for radix {}", b as char, radix)),
            };
            if digit >= radix as u64 {
                return Err(format!(
                    "digit '{}' out of range for radix {}",
                    b as char, radix
                ));
            }

            // result = result * radix + digit
            result = mul_by_scalar(&result, radix as u64);
            result = add_scalar(&result, digit);
        }

        // Trim result to minimal bit width.
        let actual_bits = result.active_bits();
        let new_width = (actual_bits as u32).max(1);
        if new_width < result.bit_width {
            result = result.trunc(new_width);
        }

        Ok(result)
    }

    /// Create from little-endian bytes.  The bytes are interpreted as an
    /// unsigned value and zero-extended or truncated to `bit_width`.
    pub fn from_bytes_le(bytes: &[u8], bit_width: u32) -> Self {
        assert!(bit_width >= 1);
        let nw = num_words(bit_width);
        let mut words = vec![0u64; nw];
        for (i, chunk) in bytes.chunks(8).enumerate() {
            if i >= nw {
                break;
            }
            let mut val: u64 = 0;
            for (j, &b) in chunk.iter().enumerate() {
                val |= (b as u64) << (j * 8);
            }
            words[i] = val;
        }
        let mut result = APInt { bit_width, words };
        result.clear_unused_bits();
        result
    }

    /// Create from big-endian bytes.  The bytes are interpreted as an
    /// unsigned value and zero-extended or truncated to `bit_width`.
    pub fn from_bytes_be(bytes: &[u8], bit_width: u32) -> Self {
        assert!(bit_width >= 1);
        let nw = num_words(bit_width);
        let mut words = vec![0u64; nw];
        for (chunk_idx, chunk) in bytes.rchunks(8).enumerate() {
            if chunk_idx >= nw {
                break;
            }
            let mut val: u64 = 0;
            for (j, &b) in chunk.iter().rev().enumerate() {
                val |= (b as u64) << (j * 8);
            }
            // chunk_idx 0 is the least significant chunk (LE word 0).
            words[chunk_idx] = val;
        }
        let mut result = APInt { bit_width, words };
        result.clear_unused_bits();
        result
    }

    /// Zero out any bits beyond `bit_width` in the highest word.
    pub fn clear_unused_bits(&mut self) {
        if self.words.is_empty() {
            self.words.push(0);
            return;
        }
        let mask = last_word_mask(self.bit_width);
        let last = self.words.last_mut().unwrap();
        *last &= mask;
    }

    // -----------------------------------------------------------------------
    // Internal constructors / helpers
    // -----------------------------------------------------------------------

    /// Create from a vector of words without checking bit width.
    /// Used internally when the width is known to be correct.
    pub(crate) fn from_words(bit_width: u32, words: Vec<u64>) -> Self {
        let mut result = APInt { bit_width, words };
        result.normalize();
        result.clear_unused_bits();
        result
    }

    /// Remove leading (high-order) zero words beyond the minimum required
    /// by `bit_width`.  Does not change `bit_width`.
    pub(crate) fn normalize(&mut self) {
        let needed = num_words(self.bit_width);
        // Strip excess zero words from the high end.
        while self.words.len() > needed && self.words.last() == Some(&0) {
            self.words.pop();
        }
        // Ensure minimum word count is maintained.
        while self.words.len() < needed {
            self.words.push(0);
        }
    }

    /// Panic if `self.bit_width != other.bit_width`.
    fn ensure_width_compatible(&self, other: &APInt) {
        if self.bit_width != other.bit_width {
            panic!(
                "APInt bit width mismatch: {} vs {}",
                self.bit_width, other.bit_width
            );
        }
    }

    /// Get the number of significant bits (position of MSB + 1).
    pub fn get_active_bits(&self) -> usize {
        significant_bits(&self.words)
    }

    fn active_bits(&self) -> usize {
        significant_bits(&self.words)
    }
}

// ---------------------------------------------------------------------------
// Internal scalar operations (used by from_string, sqrt, etc.)
// ---------------------------------------------------------------------------

/// Multiply an APInt by a scalar u64, returning a new APInt (may grow width).
fn mul_by_scalar(a: &APInt, scalar: u64) -> APInt {
    if scalar == 0 {
        return APInt::get_zero(a.bit_width);
    }
    if scalar == 1 {
        return a.clone();
    }
    let mut result_words = vec![0u64; a.words.len() + 1];
    let mut carry: u64 = 0;
    for (i, &w) in a.words.iter().enumerate() {
        let product = (w as u128) * (scalar as u128) + (carry as u128);
        result_words[i] = product as u64;
        carry = (product >> 64) as u64;
    }
    result_words[a.words.len()] = carry;
    let new_width = if carry != 0 {
        a.bit_width + 64
    } else {
        a.bit_width
    };
    let mut result = APInt {
        bit_width: new_width,
        words: result_words,
    };
    result.normalize();
    result
}

/// Add a scalar u64 to an APInt, returning a new APInt (may grow width).
fn add_scalar(a: &APInt, scalar: u64) -> APInt {
    if scalar == 0 {
        return a.clone();
    }
    let mut result_words = a.words.clone();
    let mut carry = scalar as u128;
    for w in result_words.iter_mut() {
        let sum = (*w as u128) + carry;
        *w = sum as u64;
        carry = sum >> 64;
        if carry == 0 {
            break;
        }
    }
    if carry != 0 {
        result_words.push(carry as u64);
    }
    let new_width = (result_words.len() * 64) as u32;
    let mut result = APInt {
        bit_width: new_width.max(a.bit_width),
        words: result_words,
    };
    result.normalize();
    result
}

/// Detect radix from string prefix and strip it.
/// Returns `(radix, remaining_digits)`.
fn detect_radix_and_strip<'a>(s: &'a str, radix: u8) -> Result<(u8, &'a str), String> {
    let lower = s.to_ascii_lowercase();
    if radix == 0 {
        // Auto-detect.
        if let Some(rest) = lower.strip_prefix("0x") {
            if rest.is_empty() {
                return Err("no digits after 0x".to_string());
            }
            return Ok((16, &s[2..]));
        }
        if let Some(rest) = lower.strip_prefix("0b") {
            if rest.is_empty() {
                return Err("no digits after 0b".to_string());
            }
            return Ok((2, &s[2..]));
        }
        if let Some(rest) = lower.strip_prefix("0o") {
            if rest.is_empty() {
                return Err("no digits after 0o".to_string());
            }
            return Ok((8, &s[2..]));
        }
        Ok((10, s))
    } else {
        // Strip known prefix regardless.
        if radix == 16 {
            if lower.strip_prefix("0x").is_some() {
                return Ok((16, &s[2..]));
            }
        }
        if radix == 2 {
            if lower.strip_prefix("0b").is_some() {
                return Ok((2, &s[2..]));
            }
        }
        if radix == 8 {
            if lower.strip_prefix("0o").is_some() {
                return Ok((8, &s[2..]));
            }
        }
        if radix != 2 && radix != 8 && radix != 10 && radix != 16 {
            return Err(format!("unsupported radix: {}", radix));
        }
        Ok((radix, s))
    }
}

// ---------------------------------------------------------------------------
// Arithmetic operations
// ---------------------------------------------------------------------------

impl APInt {
    /// Wrapping addition (modulo 2^bit_width).
    pub fn add(&self, other: &APInt) -> APInt {
        self.ensure_width_compatible(other);
        let (words, _carry) = add_words(&self.words, &other.words);
        APInt::from_words(self.bit_width, words)
    }

    /// Wrapping subtraction (modulo 2^bit_width).
    pub fn sub(&self, other: &APInt) -> APInt {
        self.ensure_width_compatible(other);
        let (words, _borrow) = sub_words(&self.words, &other.words);
        APInt::from_words(self.bit_width, words)
    }

    /// Wrapping multiplication (modulo 2^bit_width).
    pub fn mul(&self, other: &APInt) -> APInt {
        self.ensure_width_compatible(other);
        let full = mul_words(&self.words, &other.words);
        let nw = self.words.len();
        let truncated: Vec<u64> = full.into_iter().take(nw).collect();
        APInt::from_words(self.bit_width, truncated)
    }

    /// Unsigned division.  Panics on division by zero.
    pub fn udiv(&self, other: &APInt) -> APInt {
        self.ensure_width_compatible(other);
        if other.is_zero() {
            panic!("APInt::udiv: division by zero");
        }
        let (q, _r) = div_rem_multi(&self.words, &other.words);
        // q is already sized to self.words.len().
        let q: Vec<u64> = q.into_iter().take(self.words.len()).collect();
        APInt::from_words(self.bit_width, q)
    }

    /// Unsigned remainder.  Panics on division by zero.
    pub fn urem(&self, other: &APInt) -> APInt {
        self.ensure_width_compatible(other);
        if other.is_zero() {
            panic!("APInt::urem: division by zero");
        }
        let (_q, r) = div_rem_multi(&self.words, &other.words);
        let r: Vec<u64> = r.into_iter().take(self.words.len()).collect();
        APInt::from_words(self.bit_width, r)
    }

    /// Signed division (C99: truncates toward zero).
    /// Panics on division by zero.
    pub fn sdiv(&self, other: &APInt) -> APInt {
        self.ensure_width_compatible(other);
        if other.is_zero() {
            panic!("APInt::sdiv: division by zero");
        }
        let a_neg = self.is_negative();
        let b_neg = other.is_negative();
        let a_abs = if a_neg { self.negate() } else { self.clone() };
        let b_abs = if b_neg { other.negate() } else { other.clone() };
        let q = a_abs.udiv(&b_abs);
        if a_neg ^ b_neg {
            q.negate()
        } else {
            q
        }
    }

    /// Signed remainder (C99: `a % b` has the same sign as `a`).
    /// Panics on division by zero.
    pub fn srem(&self, other: &APInt) -> APInt {
        self.ensure_width_compatible(other);
        if other.is_zero() {
            panic!("APInt::srem: division by zero");
        }
        let a_neg = self.is_negative();
        let b_neg = other.is_negative();
        let a_abs = if a_neg { self.negate() } else { self.clone() };
        let b_abs = if b_neg { other.negate() } else { other.clone() };
        let r = a_abs.urem(&b_abs);
        if a_neg {
            r.negate()
        } else {
            r
        }
    }

    /// Two's complement negation.
    pub fn negate(&self) -> APInt {
        // -x = ~x + 1
        let one = APInt::from_u64(self.bit_width, 1);
        APInt::add(&self.not(), &one)
    }

    /// Unsigned addition with overflow flag.
    /// Returns `(result, overflow)` where overflow is `true` if the result
    /// exceeds bit_width bits.
    pub fn add_overflow(&self, other: &APInt) -> (APInt, bool) {
        self.ensure_width_compatible(other);
        let (words, carry) = add_words(&self.words, &other.words);

        let mut overflow = carry;
        if !overflow {
            // Within-word overflow: check if any bit beyond bit_width is set.
            let excess = excess_bits(self.bit_width);
            if excess > 0 {
                let last = words.last().copied().unwrap_or(0);
                overflow = (last >> (64 - excess)) != 0;
            }
        }

        let result = APInt::from_words(self.bit_width, words);
        (result, overflow)
    }

    /// Unsigned multiplication with overflow flag.
    /// Overflow if any non-zero bits exist beyond bit_width in the full product.
    pub fn mul_overflow(&self, other: &APInt) -> (APInt, bool) {
        self.ensure_width_compatible(other);
        let full = mul_words(&self.words, &other.words);
        let nw = self.words.len();
        let truncated: Vec<u64> = full.iter().take(nw).copied().collect();
        let result = APInt::from_words(self.bit_width, truncated);

        // Check if upper words are all zeros.
        let mut overflow = full[nw..].iter().any(|&w| w != 0);
        // Also check within-word overflow for non-multiple-of-64 widths.
        if !overflow {
            let rem = self.bit_width % 64;
            if rem != 0 {
                let last = full.get(nw - 1).copied().unwrap_or(0);
                overflow = (last >> rem) != 0;
            }
        }
        (result, overflow)
    }

    /// Signed subtraction with overflow flag.
    pub fn ssub_overflow(&self, other: &APInt) -> (APInt, bool) {
        self.ensure_width_compatible(other);
        let (words, _borrow) = sub_words(&self.words, &other.words);
        let result = APInt::from_words(self.bit_width, words);

        let a_sign = self.is_negative();
        let b_sign = other.is_negative();
        let r_sign = result.is_negative();
        // Signed overflow on sub when operands have different signs
        // and result sign differs from `a`'s sign.
        let overflow = (a_sign != b_sign) && (a_sign != r_sign);
        (result, overflow)
    }

    /// Signed addition with overflow flag.
    pub fn sadd_overflow(&self, other: &APInt) -> (APInt, bool) {
        self.ensure_width_compatible(other);
        let (words, _carry) = add_words(&self.words, &other.words);
        let result = APInt::from_words(self.bit_width, words);

        let a_sign = self.is_negative();
        let b_sign = other.is_negative();
        let r_sign = result.is_negative();
        // Signed overflow when operands have same sign and result sign differs.
        let overflow = (a_sign == b_sign) && (a_sign != r_sign);
        (result, overflow)
    }

    /// Signed multiplication with overflow flag.
    pub fn smul_overflow(&self, other: &APInt) -> (APInt, bool) {
        self.ensure_width_compatible(other);
        let full_words = mul_words(&self.words, &other.words);
        let nw = self.words.len();
        let truncated: Vec<u64> = full_words.iter().take(nw).copied().collect();
        let result = APInt::from_words(self.bit_width, truncated);

        let double_width = self.bit_width * 2;
        // Sign-extend result to double width.
        let sign = result.is_negative();
        let double_nw = num_words(double_width);
        let mut sext_words = vec![0u64; double_nw];
        sext_words[..result.words.len()].copy_from_slice(&result.words);
        if sign {
            for w in sext_words[result.words.len()..].iter_mut() {
                *w = u64::MAX;
            }
        }
        let mut sext_result = APInt {
            bit_width: double_width,
            words: sext_words,
        };
        sext_result.clear_unused_bits();

        let full = APInt {
            bit_width: double_width,
            words: full_words,
        };

        let overflow = sext_result != full;
        (result, overflow)
    }
}

// ---------------------------------------------------------------------------
// Bitwise operations
// ---------------------------------------------------------------------------

impl APInt {
    /// Bitwise AND.
    pub fn and(&self, other: &APInt) -> APInt {
        self.ensure_width_compatible(other);
        let words: Vec<u64> = self
            .words
            .iter()
            .zip(other.words.iter())
            .map(|(a, b)| a & b)
            .collect();
        APInt::from_words(self.bit_width, words)
    }

    /// Bitwise OR.
    pub fn or(&self, other: &APInt) -> APInt {
        self.ensure_width_compatible(other);
        let words: Vec<u64> = self
            .words
            .iter()
            .zip(other.words.iter())
            .map(|(a, b)| a | b)
            .collect();
        APInt::from_words(self.bit_width, words)
    }

    /// Bitwise XOR.
    pub fn xor(&self, other: &APInt) -> APInt {
        self.ensure_width_compatible(other);
        let words: Vec<u64> = self
            .words
            .iter()
            .zip(other.words.iter())
            .map(|(a, b)| a ^ b)
            .collect();
        APInt::from_words(self.bit_width, words)
    }

    /// Bitwise NOT (one's complement).
    pub fn not(&self) -> APInt {
        let words: Vec<u64> = self.words.iter().map(|w| !w).collect();
        APInt::from_words(self.bit_width, words)
    }

    /// Logical left shift by `shift` bits.
    pub fn shl(&self, shift: u32) -> APInt {
        if shift == 0 {
            return self.clone();
        }
        let nw = self.words.len();
        let word_shift = (shift / 64) as usize;
        let bit_shift = (shift % 64) as u32;

        let mut words = vec![0u64; nw];

        if word_shift >= nw {
            // Shifted all bits out — result is zero.
            return APInt::get_zero(self.bit_width);
        }

        if bit_shift == 0 {
            for i in (0..nw - word_shift).rev() {
                words[i + word_shift] = self.words[i];
            }
        } else {
            let inv_shift = 64 - bit_shift;
            for i in (0..nw - word_shift).rev() {
                let lo = self.words[i] << bit_shift;
                let hi = if i > 0 {
                    self.words[i - 1] >> inv_shift
                } else {
                    0
                };
                words[i + word_shift] = lo | hi;
            }
        }

        APInt::from_words(self.bit_width, words)
    }

    /// Logical right shift by `shift` bits (zero-fill).
    pub fn lshr(&self, shift: u32) -> APInt {
        if shift == 0 {
            return self.clone();
        }
        let nw = self.words.len();
        let word_shift = (shift / 64) as usize;
        let bit_shift = (shift % 64) as u32;

        let mut words = vec![0u64; nw];

        if word_shift >= nw {
            return APInt::get_zero(self.bit_width);
        }

        if bit_shift == 0 {
            for i in word_shift..nw {
                words[i - word_shift] = self.words[i];
            }
        } else {
            let inv_shift = 64 - bit_shift;
            for i in word_shift..nw {
                let lo = self.words[i] >> bit_shift;
                let hi = if i + 1 < nw {
                    self.words[i + 1] << inv_shift
                } else {
                    0
                };
                words[i - word_shift] = lo | hi;
            }
        }

        APInt::from_words(self.bit_width, words)
    }

    /// Arithmetic right shift (sign-extending).
    pub fn ashr(&self, shift: u32) -> APInt {
        if shift == 0 {
            return self.clone();
        }
        if shift >= self.bit_width {
            // All bits shifted out; result is all sign bits.
            if self.is_negative() {
                return APInt::get_all_ones(self.bit_width);
            } else {
                return APInt::get_zero(self.bit_width);
            }
        }
        let mut result = self.lshr(shift);
        if self.is_negative() {
            // Set the top `shift` bits to 1 (sign extension).
            let fill_width = self.bit_width - shift;
            let mask = APInt::get_all_ones(self.bit_width).shl(fill_width);
            result = result.or(&mask);
        }
        result
    }

    /// Rotate left by `rotate` bits.
    pub fn rotl(&self, rotate: u32) -> APInt {
        let rotate = rotate % self.bit_width;
        if rotate == 0 {
            return self.clone();
        }
        let left = self.shl(rotate);
        let right = self.lshr(self.bit_width - rotate);
        left.or(&right)
    }

    /// Rotate right by `rotate` bits.
    pub fn rotr(&self, rotate: u32) -> APInt {
        let rotate = rotate % self.bit_width;
        if rotate == 0 {
            return self.clone();
        }
        let right = self.lshr(rotate);
        let left = self.shl(self.bit_width - rotate);
        right.or(&left)
    }

    /// Truncate to a smaller bit width.
    ///
    /// # Panics
    /// Panics if `width > self.bit_width`.
    pub fn trunc(&self, width: u32) -> APInt {
        assert!(
            width <= self.bit_width,
            "APInt::trunc: new width {} exceeds current width {}",
            width,
            self.bit_width
        );
        if width == self.bit_width {
            return self.clone();
        }
        let nw = num_words(width);
        let words: Vec<u64> = self.words.iter().take(nw).copied().collect();
        APInt::from_words(width, words)
    }

    /// Sign-extend to a wider bit width.
    ///
    /// # Panics
    /// Panics if `width < self.bit_width`.
    pub fn sext(&self, width: u32) -> APInt {
        assert!(
            width >= self.bit_width,
            "APInt::sext: width must be >= current width"
        );
        if width == self.bit_width {
            return self.clone();
        }
        let nw = num_words(width);
        let mut words = vec![0u64; nw];
        words[..self.words.len()].copy_from_slice(&self.words);
        if self.is_negative() {
            // Fill all bits from self.bit_width to width-1 with 1s.
            let fill_all = APInt::get_all_ones(width);
            let mask = fill_all.shl(self.bit_width);
            let mut result = APInt {
                bit_width: width,
                words,
            };
            result = result.or(&mask);
            result.clear_unused_bits();
            result
        } else {
            APInt::from_words(width, words)
        }
    }

    /// Zero-extend to a wider bit width.
    ///
    /// # Panics
    /// Panics if `width < self.bit_width`.
    pub fn zext(&self, width: u32) -> APInt {
        assert!(
            width >= self.bit_width,
            "APInt::zext: width must be >= current width"
        );
        if width == self.bit_width {
            return self.clone();
        }
        let nw = num_words(width);
        let mut words = vec![0u64; nw];
        words[..self.words.len()].copy_from_slice(&self.words);
        APInt::from_words(width, words)
    }

    /// Extract a contiguous bit field as a new APInt.
    ///
    /// `lo_bit` is the least-significant bit of the field.
    /// `num_bits` is the number of bits to extract.
    ///
    /// # Panics
    /// Panics if `lo_bit + num_bits > self.bit_width`.
    pub fn extract_bits(&self, lo_bit: u32, num_bits: u32) -> APInt {
        assert!(
            lo_bit + num_bits <= self.bit_width,
            "APInt::extract_bits: range [{}, {}) exceeds bit_width {}",
            lo_bit,
            lo_bit + num_bits,
            self.bit_width
        );
        if num_bits == 0 {
            return APInt::get_zero(1);
        }
        // Shift right to align lo_bit with bit 0, then truncate.
        let shifted = self.lshr(lo_bit);
        shifted.trunc(num_bits)
    }
}

// ---------------------------------------------------------------------------
// Comparison methods
// ---------------------------------------------------------------------------

impl APInt {
    /// Equality comparison.
    pub fn eq(&self, other: &APInt) -> bool {
        self.bit_width == other.bit_width && self.words == other.words
    }

    /// Inequality comparison.
    pub fn ne(&self, other: &APInt) -> bool {
        !self.eq(other)
    }

    /// Unsigned less-than.
    pub fn ult(&self, other: &APInt) -> bool {
        self.ensure_width_compatible(other);
        unsigned_cmp(&self.words, &other.words) == Ordering::Less
    }

    /// Unsigned greater-than.
    pub fn ugt(&self, other: &APInt) -> bool {
        self.ensure_width_compatible(other);
        unsigned_cmp(&self.words, &other.words) == Ordering::Greater
    }

    /// Unsigned less-than-or-equal.
    pub fn ule(&self, other: &APInt) -> bool {
        self.ensure_width_compatible(other);
        matches!(
            unsigned_cmp(&self.words, &other.words),
            Ordering::Less | Ordering::Equal
        )
    }

    /// Unsigned greater-than-or-equal.
    pub fn uge(&self, other: &APInt) -> bool {
        self.ensure_width_compatible(other);
        matches!(
            unsigned_cmp(&self.words, &other.words),
            Ordering::Greater | Ordering::Equal
        )
    }

    /// Signed less-than.
    pub fn slt(&self, other: &APInt) -> bool {
        self.ensure_width_compatible(other);
        signed_cmp(&self.words, self.bit_width, &other.words, other.bit_width) == Ordering::Less
    }

    /// Signed greater-than.
    pub fn sgt(&self, other: &APInt) -> bool {
        self.ensure_width_compatible(other);
        signed_cmp(&self.words, self.bit_width, &other.words, other.bit_width) == Ordering::Greater
    }

    /// Signed less-than-or-equal.
    pub fn sle(&self, other: &APInt) -> bool {
        self.ensure_width_compatible(other);
        matches!(
            signed_cmp(&self.words, self.bit_width, &other.words, other.bit_width),
            Ordering::Less | Ordering::Equal
        )
    }

    /// Signed greater-than-or-equal.
    pub fn sge(&self, other: &APInt) -> bool {
        self.ensure_width_compatible(other);
        matches!(
            signed_cmp(&self.words, self.bit_width, &other.words, other.bit_width),
            Ordering::Greater | Ordering::Equal
        )
    }

    /// Returns `true` if the value is zero.
    pub fn is_zero(&self) -> bool {
        self.words.iter().all(|&w| w == 0)
    }

    /// Returns `true` if the value is one.
    pub fn is_one(&self) -> bool {
        self.words.first() == Some(&1) && self.words[1..].iter().all(|&w| w == 0)
    }

    /// Returns `true` if all bits are set (unsigned max).
    pub fn is_all_ones(&self) -> bool {
        let mask = last_word_mask(self.bit_width);
        let last = self.words.last().copied().unwrap_or(0);
        if last != mask {
            return false;
        }
        self.words[..self.words.len() - 1]
            .iter()
            .all(|&w| w == u64::MAX)
    }

    /// Returns `true` if the sign bit (bit `bit_width - 1`) is set.
    pub fn is_negative(&self) -> bool {
        if self.bit_width == 1 {
            return self.words[0] & 1 != 0;
        }
        let word = (self.bit_width - 1) / 64;
        let bit = (self.bit_width - 1) % 64;
        self.words
            .get(word as usize)
            .map(|w| (w >> bit) & 1 != 0)
            .unwrap_or(false)
    }

    /// Returns `true` if the value is non-negative (sign bit is zero).
    pub fn is_non_negative(&self) -> bool {
        !self.is_negative()
    }

    /// Returns `true` if the value is strictly positive (> 0).
    pub fn is_strictly_positive(&self) -> bool {
        !self.is_zero() && self.is_non_negative()
    }

    /// Returns `true` if the value is a power of two.
    pub fn is_power_of_2(&self) -> bool {
        if self.is_zero() {
            return false;
        }
        // Count population; must be exactly 1.
        // But special case: for signed min (only sign bit set), that's not
        // a power of two in the usual sense (since 2^N for N = bit_width-1
        // equals the unsigned value of the sign bit).  Power-of-2 test is
        // usually unsigned.
        self.count_population() == 1
    }

    /// Returns `true` if the value fits in a signed integer of `n` bits.
    pub fn is_signed_int_n(&self, n: u32) -> bool {
        if n == 0 {
            return self.is_zero();
        }
        if n >= self.bit_width {
            return true;
        }
        // After arithmetic right shift by (n-1), any remaining bits beyond n
        // should be equal to the sign bit at position n-1.
        let shifted = self.ashr(n - 1);
        shifted.is_zero() || shifted.is_all_ones()
    }

    /// Returns `true` if the value fits in an unsigned integer of `n` bits.
    pub fn is_int_n(&self, n: u32) -> bool {
        if n == 0 {
            return self.is_zero();
        }
        if n >= self.bit_width {
            return true;
        }
        // Bits beyond n-1 should be zero.
        let shifted = self.lshr(n);
        shifted.is_zero()
    }
}

/// Unsigned comparison of two word slices.
fn unsigned_cmp(a: &[u64], b: &[u64]) -> Ordering {
    let len = a.len().max(b.len());
    for i in (0..len).rev() {
        let aw = a.get(i).copied().unwrap_or(0);
        let bw = b.get(i).copied().unwrap_or(0);
        match aw.cmp(&bw) {
            Ordering::Equal => continue,
            ord => return ord,
        }
    }
    Ordering::Equal
}

/// Signed comparison of two word slices with given bit widths.
fn signed_cmp(a: &[u64], aw: u32, b: &[u64], bw: u32) -> Ordering {
    let a_neg = is_negative_words(a, aw);
    let b_neg = is_negative_words(b, bw);
    if a_neg != b_neg {
        return if a_neg {
            Ordering::Less
        } else {
            Ordering::Greater
        };
    }
    // Same sign; compare unsigned.
    unsigned_cmp(a, b)
}

/// Check if the sign bit is set in a word slice of given width.
fn is_negative_words(words: &[u64], bit_width: u32) -> bool {
    if bit_width == 0 {
        return false;
    }
    let word = ((bit_width - 1) / 64) as usize;
    let bit = (bit_width - 1) % 64;
    words
        .get(word)
        .map(|w| (w >> bit) & 1 != 0)
        .unwrap_or(false)
}

// ---------------------------------------------------------------------------
// Conversion
// ---------------------------------------------------------------------------

impl APInt {
    /// Truncate to a u64 (returns `None` if any high bits beyond 64 are set).
    pub fn to_u64(&self) -> Option<u64> {
        // Check that bits beyond 63 are zero.
        if self.words.len() > 1 && self.words[1..].iter().any(|&w| w != 0) {
            return None;
        }
        if self.bit_width > 64 && self.words.len() >= 2 && self.words[1] != 0 {
            return None;
        }
        // Also check if the 64th bit (if bit_width > 64) is set in word 0.
        // Wait, word 0 is bits 0..63. If bit_width > 64, all of word 0 is used.
        // If bit_width <= 64, the mask handles it.
        Some(self.words.first().copied().unwrap_or(0))
    }

    /// Truncate to an i64 (returns `None` if value does not fit in 64-bit signed).
    pub fn to_i64(&self) -> Option<i64> {
        if self.bit_width <= 64 {
            let val = self.words.first().copied().unwrap_or(0);
            if self.bit_width < 64 {
                // Sign-extend val from bit_width to 64 bits.
                let shift = 64 - self.bit_width;
                Some(((val << shift) as i64) >> shift)
            } else {
                Some(val as i64)
            }
        } else {
            // Need to check that all bits beyond the low 64 sign-extend correctly.
            let low = self.words[0];
            let sign_bit_64 = (low >> 63) & 1;
            // All higher words must equal the sign extension.
            let fill = if sign_bit_64 != 0 { u64::MAX } else { 0 };
            for &w in &self.words[1..] {
                if w != fill {
                    return None;
                }
            }
            // Also check bits in word 1 if bit_width isn't a multiple of 64.
            // Actually, the check above is sufficient since clear_unused_bits ensures
            // unused bits are zero, and fill check covers all higher words.
            Some(low as i64)
        }
    }

    /// Convert to a string in the given radix.
    ///
    /// If `signed` is true, the value is interpreted as a signed integer
    /// (negative values prefixed with `-`).  Otherwise, it is printed as unsigned.
    pub fn to_string(&self, radix: u8, signed: bool) -> String {
        if radix != 2 && radix != 8 && radix != 10 && radix != 16 {
            panic!("APInt::to_string: unsupported radix {}", radix);
        }
        if signed && self.is_negative() {
            let neg = self.negate();
            format!("-{}", neg.to_string(radix, false))
        } else {
            to_string_unsigned(&self.words, radix)
        }
    }

    /// Convert to little-endian bytes.
    pub fn to_bytes_le(&self) -> Vec<u8> {
        let byte_len = ((self.bit_width + 7) / 8) as usize;
        let mut bytes = vec![0u8; byte_len];
        for (i, &w) in self.words.iter().enumerate() {
            let base = i * 8;
            if base >= byte_len {
                break;
            }
            for j in 0..8 {
                let idx = base + j;
                if idx >= byte_len {
                    break;
                }
                bytes[idx] = (w >> (j * 8)) as u8;
            }
        }
        bytes
    }

    /// Convert to big-endian bytes.
    pub fn to_bytes_be(&self) -> Vec<u8> {
        let byte_len = ((self.bit_width + 7) / 8) as usize;
        let mut bytes = vec![0u8; byte_len];
        for (i, &w) in self.words.iter().enumerate() {
            for j in 0..8 {
                let byte_idx = i * 8 + j;
                if byte_idx >= byte_len {
                    break;
                }
                let be_idx = byte_len - 1 - byte_idx;
                bytes[be_idx] = (w >> (j * 8)) as u8;
            }
        }
        bytes
    }

    /// Return the value as a u64, saturated to `limit`.
    /// If the value is > `limit`, return `limit`.
    pub fn get_limited_value(&self, limit: u64) -> u64 {
        // If we can fit in u64, compare; otherwise we're definitely > limit.
        if let Some(val) = self.to_u64() {
            val.min(limit)
        } else if limit == u64::MAX {
            limit
        } else {
            // Value > u64::MAX > limit (since limit < u64::MAX)
            limit
        }
    }
}

/// Convert an unsigned word slice to a string in the given radix.
fn to_string_unsigned(words: &[u64], radix: u8) -> String {
    if words.iter().all(|&w| w == 0) {
        return "0".to_string();
    }

    // Repeatedly divide by radix, collecting remainders.
    let mut digits: Vec<u8> = Vec::new();
    let mut current = words.to_vec();

    while !current.iter().all(|&w| w == 0) {
        let (_quotient, rem) = div_rem_single(&current, radix as u64);
        digits.push(rem as u8);
        let (q, _) = div_rem_single(&current, radix as u64);
        current = q;
        // Trim leading zeros.
        while current.len() > 1 && current.last() == Some(&0) {
            current.pop();
        }
    }

    digits.reverse();
    let chars: String = digits
        .into_iter()
        .map(|d| {
            if d < 10 {
                (b'0' + d) as char
            } else {
                (b'a' + (d - 10)) as char
            }
        })
        .collect();
    chars
}

// ---------------------------------------------------------------------------
// Bit-level access
// ---------------------------------------------------------------------------

impl APInt {
    /// Get the value of a single bit.
    ///
    /// # Panics
    /// Panics if `bit >= self.bit_width`.
    pub fn get_bit(&self, bit: u32) -> bool {
        assert!(
            bit < self.bit_width,
            "get_bit: bit {} out of range (width {})",
            bit,
            self.bit_width
        );
        let word = (bit / 64) as usize;
        let bit_in_word = bit % 64;
        (self.words[word] >> bit_in_word) & 1 != 0
    }

    /// Set a single bit to 1.
    ///
    /// # Panics
    /// Panics if `bit >= self.bit_width`.
    pub fn set_bit(&mut self, bit: u32) {
        assert!(
            bit < self.bit_width,
            "set_bit: bit {} out of range (width {})",
            bit,
            self.bit_width
        );
        let word = (bit / 64) as usize;
        let bit_in_word = bit % 64;
        // Ensure words vector is large enough.
        if word >= self.words.len() {
            self.words.resize(word + 1, 0);
        }
        self.words[word] |= 1u64 << bit_in_word;
    }

    /// Clear a single bit to 0.
    ///
    /// # Panics
    /// Panics if `bit >= self.bit_width`.
    pub fn clear_bit(&mut self, bit: u32) {
        assert!(
            bit < self.bit_width,
            "clear_bit: bit {} out of range (width {})",
            bit,
            self.bit_width
        );
        let word = (bit / 64) as usize;
        let bit_in_word = bit % 64;
        if word < self.words.len() {
            self.words[word] &= !(1u64 << bit_in_word);
        }
    }

    /// Return the number of 64-bit words used.
    pub fn get_num_words(&self) -> usize {
        self.words.len()
    }

    /// Return a reference to the raw word data.
    pub fn get_raw_data(&self) -> &[u64] {
        &self.words
    }

    /// Count leading zeros (before the most significant set bit).
    pub fn count_leading_zeros(&self) -> u32 {
        let mut count = 0u32;
        for i in (0..self.words.len()).rev() {
            let w = self.words[i];
            if w == 0 {
                count += 64;
            } else {
                count += w.leading_zeros();
                break;
            }
        }
        // Subtract excess bits in the last word.
        let excess = excess_bits(self.bit_width);
        if count >= excess {
            count - excess
        } else {
            0
        }
    }

    /// Count trailing zeros (before the least significant set bit).
    pub fn count_trailing_zeros(&self) -> u32 {
        let mut count = 0u32;
        for &w in &self.words {
            if w == 0 {
                count += 64;
            } else {
                count += w.trailing_zeros();
                break;
            }
        }
        count.min(self.bit_width)
    }

    /// Count the number of set bits (population count / Hamming weight).
    pub fn count_population(&self) -> u32 {
        self.words.iter().map(|&w| w.count_ones()).sum()
    }

    /// Return the low `num_bits` as a new APInt.
    pub fn get_lo_bits(&self, num_bits: u32) -> APInt {
        assert!(num_bits <= self.bit_width);
        if num_bits == 0 {
            return APInt::get_zero(1);
        }
        self.trunc(num_bits)
    }

    /// Return the high `num_bits` as a new APInt.
    pub fn get_hi_bits(&self, num_bits: u32) -> APInt {
        assert!(num_bits <= self.bit_width);
        if num_bits == 0 {
            return APInt::get_zero(1);
        }
        let shift = self.bit_width - num_bits;
        let shifted = self.lshr(shift);
        shifted.trunc(num_bits)
    }
}

// ---------------------------------------------------------------------------
// Advanced operations
// ---------------------------------------------------------------------------

impl APInt {
    /// Greatest common divisor (Euclidean algorithm).
    pub fn gcd(&self, other: &APInt) -> APInt {
        self.ensure_width_compatible(other);
        let mut a = self.clone();
        let mut b = other.clone();
        if a.is_zero() {
            return b;
        }
        if b.is_zero() {
            return a;
        }
        // Ensure a >= b (unsigned).
        if a.ult(&b) {
            std::mem::swap(&mut a, &mut b);
        }
        while !b.is_zero() {
            let r = a.urem(&b);
            a = b;
            b = r;
        }
        a
    }

    /// Least common multiple.
    /// lcm(a, b) = a / gcd(a, b) * b (handles zero correctly).
    pub fn lcm(&self, other: &APInt) -> APInt {
        self.ensure_width_compatible(other);
        if self.is_zero() || other.is_zero() {
            return APInt::get_zero(self.bit_width);
        }
        let g = self.gcd(other);
        // (a / g) * b
        let a_div_g = self.udiv(&g);
        APInt::mul(&a_div_g, other)
    }

    /// Integer square root (floor).
    /// Uses Newton's method with division-based convergence check to avoid
    /// overflow from wrapping multiplication.
    pub fn sqrt(&self) -> APInt {
        if self.is_zero() {
            return self.clone();
        }
        // Initial guess: 2^(bit_len/2).
        let bit_len = self.active_bits() as u32;
        let mut x = APInt::from_u64(self.bit_width, 1).shl((bit_len + 1) / 2);

        // Newton iteration: x_{n+1} = (x_n + self/x_n) / 2
        loop {
            let q = self.udiv(&x);
            let x_next = APInt::add(&x, &q).lshr(1);
            if x_next.uge(&x) {
                break;
            }
            x = x_next;
        }
        // Adjust downward using x > self/x instead of x*x > self
        // to avoid wrapping multiplication.
        let one = APInt::from_u64(self.bit_width, 1);
        while x.ugt(&self.udiv(&x)) {
            x = APInt::sub(&x, &one);
        }
        x
    }

    /// Absolute value.
    pub fn abs(&self) -> APInt {
        if self.is_negative() {
            self.negate()
        } else {
            self.clone()
        }
    }

    /// Unsigned minimum.
    pub fn umin(&self, other: &APInt) -> APInt {
        if self.ult(other) {
            self.clone()
        } else {
            other.clone()
        }
    }

    /// Unsigned maximum.
    pub fn umax(&self, other: &APInt) -> APInt {
        if self.ugt(other) {
            self.clone()
        } else {
            other.clone()
        }
    }

    /// Signed minimum.
    pub fn smin(&self, other: &APInt) -> APInt {
        if self.slt(other) {
            self.clone()
        } else {
            other.clone()
        }
    }

    /// Signed maximum.
    pub fn smax(&self, other: &APInt) -> APInt {
        if self.sgt(other) {
            self.clone()
        } else {
            other.clone()
        }
    }
}

// ---------------------------------------------------------------------------
// Operator overloads
// ---------------------------------------------------------------------------

impl PartialEq for APInt {
    fn eq(&self, other: &APInt) -> bool {
        self.eq(other)
    }
}

impl Eq for APInt {}

impl Hash for APInt {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.bit_width.hash(state);
        for &w in &self.words {
            w.hash(state);
        }
    }
}

impl PartialOrd for APInt {
    fn partial_cmp(&self, other: &APInt) -> Option<Ordering> {
        if self.bit_width != other.bit_width {
            return None;
        }
        Some(unsigned_cmp(&self.words, &other.words))
    }
}

impl<'a, 'b> Add<&'b APInt> for &'a APInt {
    type Output = APInt;
    fn add(self, rhs: &'b APInt) -> APInt {
        APInt::add(self, rhs)
    }
}

impl<'a, 'b> Sub<&'b APInt> for &'a APInt {
    type Output = APInt;
    fn sub(self, rhs: &'b APInt) -> APInt {
        APInt::sub(self, rhs)
    }
}

impl<'a, 'b> Mul<&'b APInt> for &'a APInt {
    type Output = APInt;
    fn mul(self, rhs: &'b APInt) -> APInt {
        APInt::mul(self, rhs)
    }
}

impl<'a, 'b> BitAnd<&'b APInt> for &'a APInt {
    type Output = APInt;
    fn bitand(self, rhs: &'b APInt) -> APInt {
        APInt::and(self, rhs)
    }
}

impl<'a, 'b> BitOr<&'b APInt> for &'a APInt {
    type Output = APInt;
    fn bitor(self, rhs: &'b APInt) -> APInt {
        APInt::or(self, rhs)
    }
}

impl<'a, 'b> BitXor<&'b APInt> for &'a APInt {
    type Output = APInt;
    fn bitxor(self, rhs: &'b APInt) -> APInt {
        APInt::xor(self, rhs)
    }
}

impl<'a> Shl<u32> for &'a APInt {
    type Output = APInt;
    fn shl(self, shift: u32) -> APInt {
        APInt::shl(self, shift)
    }
}

impl<'a> Shr<u32> for &'a APInt {
    type Output = APInt;
    fn shr(self, shift: u32) -> APInt {
        APInt::lshr(self, shift)
    }
}

impl Not for APInt {
    type Output = APInt;
    fn not(self) -> APInt {
        APInt::not(&self)
    }
}

impl<'a> Not for &'a APInt {
    type Output = APInt;
    fn not(self) -> APInt {
        APInt::not(self)
    }
}

impl<'a> Neg for &'a APInt {
    type Output = APInt;
    fn neg(self) -> APInt {
        APInt::negate(self)
    }
}

impl fmt::Display for APInt {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_string(10, false))
    }
}

impl fmt::Debug for APInt {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "APInt({}b, 0x{})",
            self.bit_width,
            self.to_string(16, false)
        )
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // =======================================================================
    // Construction tests
    // =======================================================================

    #[test]
    #[should_panic(expected = "bit_width must be >= 1")]
    fn test_new_zero_width_panics() {
        APInt::new(0, 0, false);
    }

    #[test]
    fn test_new_1bit() {
        let a = APInt::new(1, 0, false);
        assert_eq!(a.to_u64(), Some(0));
        let b = APInt::new(1, 1, false);
        assert_eq!(b.to_u64(), Some(1));
    }

    #[test]
    fn test_from_u64() {
        let a = APInt::from_u64(64, 0xDEADBEEF);
        assert_eq!(a.to_u64(), Some(0xDEADBEEF));

        let b = APInt::from_u64(128, 0xFFFFFFFFFFFFFFFF);
        assert_eq!(b.to_u64(), Some(0xFFFFFFFFFFFFFFFF));
        // Upper word should be zero.
        assert_eq!(b.words.len(), 2);
        assert_eq!(b.words[1], 0);
    }

    #[test]
    fn test_from_i64_positive() {
        let a = APInt::from_i64(128, 42);
        assert_eq!(a.to_i64(), Some(42));
        assert_eq!(a.words.len(), 2);
        assert_eq!(a.words[1], 0);
    }

    #[test]
    fn test_from_i64_negative() {
        let a = APInt::from_i64(128, -1);
        assert_eq!(a.to_i64(), Some(-1));
        assert!(a.is_negative());
        // Should be sign-extended: all 128 bits are 1.
        assert_eq!(a.words[0], u64::MAX);
        assert_eq!(a.words[1], u64::MAX);
    }

    #[test]
    fn test_get_zero() {
        let z = APInt::get_zero(256);
        assert!(z.is_zero());
        assert_eq!(z.words.len(), 4);
        assert!(z.words.iter().all(|&w| w == 0));
    }

    #[test]
    fn test_get_one() {
        let o = APInt::get_one(65);
        assert!(o.is_one());
        assert_eq!(o.words[0], 1);
        assert_eq!(o.words[1], 0);
    }

    #[test]
    fn test_get_all_ones() {
        let a = APInt::get_all_ones(65);
        assert!(a.is_all_ones());
        assert_eq!(a.words[0], u64::MAX);
        assert_eq!(a.words[1], 1); // only one bit in second word
    }

    #[test]
    fn test_get_signed_max_value() {
        // 8-bit signed max = 127
        let a = APInt::get_signed_max_value(8);
        assert_eq!(a.to_u64(), Some(127));
        assert!(!a.is_negative());

        // 64-bit signed max
        let b = APInt::get_signed_max_value(64);
        assert_eq!(b.to_u64(), Some(i64::MAX as u64));
    }

    #[test]
    fn test_get_signed_min_value() {
        // 8-bit signed min = -128
        let a = APInt::get_signed_min_value(8);
        assert!(a.is_negative());
        assert_eq!(a.to_i64(), Some(-128));

        // 64-bit signed min
        let b = APInt::get_signed_min_value(64);
        assert_eq!(b.to_i64(), Some(i64::MIN));
    }

    // =======================================================================
    // String parsing tests
    // =======================================================================

    #[test]
    fn test_from_string_decimal() {
        let a = APInt::from_string("12345", 10).unwrap();
        assert_eq!(a.to_string(10, false), "12345");
    }

    #[test]
    fn test_from_string_hex_prefix() {
        let a = APInt::from_string("0xFF", 0).unwrap();
        assert_eq!(a.to_u64(), Some(255));
        assert_eq!(a.to_string(16, false), "ff");

        let b = APInt::from_string("0xDEAD", 0).unwrap();
        assert_eq!(b.to_u64(), Some(0xDEAD));
    }

    #[test]
    fn test_from_string_binary_prefix() {
        let a = APInt::from_string("0b1010", 0).unwrap();
        assert_eq!(a.to_u64(), Some(10));

        let b = APInt::from_string("0b11111111", 0).unwrap();
        assert_eq!(b.to_u64(), Some(255));
    }

    #[test]
    fn test_from_string_octal_prefix() {
        let a = APInt::from_string("0o77", 0).unwrap();
        assert_eq!(a.to_u64(), Some(63));
    }

    #[test]
    fn test_from_string_explicit_radix() {
        let a = APInt::from_string("1010", 2).unwrap();
        assert_eq!(a.to_u64(), Some(10));

        let b = APInt::from_string("77", 8).unwrap();
        assert_eq!(b.to_u64(), Some(63));

        let c = APInt::from_string("FF", 16).unwrap();
        assert_eq!(c.to_u64(), Some(255));
    }

    #[test]
    fn test_from_string_large_hex() {
        let a = APInt::from_string("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0).unwrap();
        // 128-bit all-ones.
        assert_eq!(a.words.len(), 2);
        assert_eq!(a.words[0], u64::MAX);
        assert_eq!(a.words[1], u64::MAX);
    }

    #[test]
    fn test_from_string_empty() {
        assert!(APInt::from_string("", 10).is_err());
    }

    #[test]
    fn test_from_string_invalid_digit() {
        assert!(APInt::from_string("12G", 16).is_err());
        assert!(APInt::from_string("102", 2).is_err());
    }

    // =======================================================================
    // Bytes conversion tests
    // =======================================================================

    #[test]
    fn test_from_bytes_le() {
        let a = APInt::from_bytes_le(&[0x78, 0x56, 0x34, 0x12], 32);
        assert_eq!(a.to_u64(), Some(0x12345678));
    }

    #[test]
    fn test_from_bytes_be() {
        let a = APInt::from_bytes_be(&[0x12, 0x34, 0x56, 0x78], 32);
        assert_eq!(a.to_u64(), Some(0x12345678));
    }

    #[test]
    fn test_to_bytes_le_roundtrip() {
        let original = APInt::from_u64(64, 0xDEADBEEFCAFEBABE);
        let bytes = original.to_bytes_le();
        let roundtrip = APInt::from_bytes_le(&bytes, 64);
        assert_eq!(original, roundtrip);
    }

    #[test]
    fn test_to_bytes_be_roundtrip() {
        let original = APInt::from_u64(64, 0xDEADBEEFCAFEBABE);
        let bytes = original.to_bytes_be();
        let roundtrip = APInt::from_bytes_be(&bytes, 64);
        assert_eq!(original, roundtrip);
    }

    // =======================================================================
    // Arithmetic tests
    // =======================================================================

    #[test]
    fn test_add_basic() {
        let a = APInt::from_u64(64, 100);
        let b = APInt::from_u64(64, 200);
        assert_eq!(a.add(&b).to_u64(), Some(300));
    }

    #[test]
    fn test_add_wrapping() {
        let a = APInt::from_u64(8, 250);
        let b = APInt::from_u64(8, 10);
        // 250 + 10 = 260, wraps to 260 % 256 = 4
        assert_eq!(a.add(&b).to_u64(), Some(4));
    }

    #[test]
    fn test_sub_basic() {
        let a = APInt::from_u64(64, 500);
        let b = APInt::from_u64(64, 200);
        assert_eq!(a.sub(&b).to_u64(), Some(300));
    }

    #[test]
    fn test_sub_wrapping() {
        let a = APInt::from_u64(8, 5);
        let b = APInt::from_u64(8, 10);
        // 5 - 10 = -5 ≡ 251 (mod 256)
        assert_eq!(a.sub(&b).to_u64(), Some(251));
    }

    #[test]
    fn test_mul_basic() {
        let a = APInt::from_u64(64, 7);
        let b = APInt::from_u64(64, 9);
        assert_eq!(a.mul(&b).to_u64(), Some(63));
    }

    #[test]
    fn test_mul_wrapping() {
        let a = APInt::from_u64(8, 16);
        let b = APInt::from_u64(8, 16);
        // 16 * 16 = 256, wraps to 0
        assert_eq!(a.mul(&b).to_u64(), Some(0));
    }

    #[test]
    fn test_mul_65bit() {
        let a = APInt::from_u64(65, 3);
        let b = APInt::from_u64(65, 5);
        assert_eq!(a.mul(&b).to_u64(), Some(15));
    }

    #[test]
    fn test_udiv_basic() {
        let a = APInt::from_u64(64, 100);
        let b = APInt::from_u64(64, 7);
        assert_eq!(a.udiv(&b).to_u64(), Some(14));
    }

    #[test]
    #[should_panic(expected = "division by zero")]
    fn test_udiv_by_zero() {
        let a = APInt::from_u64(64, 100);
        let b = APInt::get_zero(64);
        a.udiv(&b);
    }

    #[test]
    fn test_urem_basic() {
        let a = APInt::from_u64(64, 100);
        let b = APInt::from_u64(64, 7);
        assert_eq!(a.urem(&b).to_u64(), Some(2));
    }

    #[test]
    fn test_sdiv_positive() {
        let a = APInt::from_i64(64, 100);
        let b = APInt::from_i64(64, 7);
        assert_eq!(a.sdiv(&b).to_i64(), Some(14));
    }

    #[test]
    fn test_sdiv_negative_dividend() {
        // C99: -100 / 7 = -14 (truncate toward zero)
        let a = APInt::from_i64(64, -100);
        let b = APInt::from_i64(64, 7);
        assert_eq!(a.sdiv(&b).to_i64(), Some(-14));
    }

    #[test]
    fn test_sdiv_negative_divisor() {
        // 100 / -7 = -14
        let a = APInt::from_i64(64, 100);
        let b = APInt::from_i64(64, -7);
        assert_eq!(a.sdiv(&b).to_i64(), Some(-14));
    }

    #[test]
    fn test_sdiv_both_negative() {
        // -100 / -7 = 14
        let a = APInt::from_i64(64, -100);
        let b = APInt::from_i64(64, -7);
        assert_eq!(a.sdiv(&b).to_i64(), Some(14));
    }

    #[test]
    fn test_srem_c99() {
        // C99: -100 % 7 = -2 (remainder has sign of dividend)
        let a = APInt::from_i64(64, -100);
        let b = APInt::from_i64(64, 7);
        assert_eq!(a.srem(&b).to_i64(), Some(-2));
    }

    #[test]
    fn test_negate() {
        let a = APInt::from_i64(64, 42);
        let n = a.negate();
        assert_eq!(n.to_i64(), Some(-42));
    }

    #[test]
    fn test_negate_zero() {
        let a = APInt::get_zero(64);
        let n = a.negate();
        assert!(n.is_zero());
    }

    #[test]
    fn test_negate_min_value() {
        // Negating signed min gives signed min (wrapping).
        let a = APInt::get_signed_min_value(64); // -2^63
        let n = a.negate();
        // In two's complement, negating the minimum gives itself.
        assert_eq!(n, a);
    }

    // =======================================================================
    // Overflow tests
    // =======================================================================

    #[test]
    fn test_add_overflow_no() {
        let a = APInt::from_u64(64, 100);
        let b = APInt::from_u64(64, 200);
        let (result, overflow) = a.add_overflow(&b);
        assert_eq!(result.to_u64(), Some(300));
        assert!(!overflow);
    }

    #[test]
    fn test_add_overflow_yes() {
        let a = APInt::from_u64(8, 200);
        let b = APInt::from_u64(8, 100);
        let (_result, overflow) = a.add_overflow(&b);
        // 200 + 100 = 300 > 255, overflow.
        assert!(overflow);
    }

    #[test]
    fn test_mul_overflow_no() {
        let a = APInt::from_u64(64, 100);
        let b = APInt::from_u64(64, 200);
        let (_result, overflow) = a.mul_overflow(&b);
        assert!(!overflow);
    }

    #[test]
    fn test_mul_overflow_yes() {
        let a = APInt::from_u64(8, 16);
        let b = APInt::from_u64(8, 16);
        let (_result, overflow) = a.mul_overflow(&b);
        assert!(overflow);
    }

    #[test]
    fn test_sadd_overflow_no() {
        let a = APInt::from_i64(64, 100);
        let b = APInt::from_i64(64, 200);
        let (_result, overflow) = a.sadd_overflow(&b);
        assert!(!overflow);
    }

    #[test]
    fn test_sadd_overflow_pos() {
        let a = APInt::get_signed_max_value(64); // i64::MAX
        let b = APInt::from_i64(64, 1);
        let (_result, overflow) = a.sadd_overflow(&b);
        assert!(overflow);
    }

    #[test]
    fn test_sadd_overflow_neg() {
        let a = APInt::get_signed_min_value(64); // i64::MIN
        let b = APInt::from_i64(64, -1);
        let (_result, overflow) = a.sadd_overflow(&b);
        assert!(overflow);
    }

    #[test]
    fn test_ssub_overflow_no() {
        let a = APInt::from_i64(64, 100);
        let b = APInt::from_i64(64, 50);
        let (_result, overflow) = a.ssub_overflow(&b);
        assert!(!overflow);
    }

    #[test]
    fn test_ssub_overflow_yes() {
        let a = APInt::get_signed_max_value(64); // i64::MAX
        let b = APInt::from_i64(64, -1);
        let (_result, overflow) = a.ssub_overflow(&b);
        // i64::MAX - (-1) = i64::MAX + 1 overflows
        assert!(overflow);
    }

    #[test]
    fn test_smul_overflow_no() {
        let a = APInt::from_i64(64, 100);
        let b = APInt::from_i64(64, 200);
        let (_result, overflow) = a.smul_overflow(&b);
        assert!(!overflow);
    }

    #[test]
    fn test_smul_overflow_yes() {
        let a = APInt::get_signed_max_value(64); // i64::MAX
        let b = APInt::from_i64(64, 2);
        let (_result, overflow) = a.smul_overflow(&b);
        assert!(overflow);
    }

    // =======================================================================
    // Bitwise tests
    // =======================================================================

    #[test]
    fn test_and() {
        let a = APInt::from_u64(64, 0xFF00);
        let b = APInt::from_u64(64, 0x0FF0);
        assert_eq!(a.and(&b).to_u64(), Some(0x0F00));
    }

    #[test]
    fn test_or() {
        let a = APInt::from_u64(64, 0xFF00);
        let b = APInt::from_u64(64, 0x0FF0);
        assert_eq!(a.or(&b).to_u64(), Some(0xFFF0));
    }

    #[test]
    fn test_xor() {
        let a = APInt::from_u64(64, 0xFF00);
        let b = APInt::from_u64(64, 0x0FF0);
        assert_eq!(a.xor(&b).to_u64(), Some(0xF0F0));
    }

    #[test]
    fn test_not() {
        let a = APInt::from_u64(8, 0x0F);
        // ~0x0F in 8 bits = 0xF0
        assert_eq!(a.not().to_u64(), Some(0xF0));
    }

    #[test]
    fn test_shl_basic() {
        let a = APInt::from_u64(64, 1);
        assert_eq!(a.shl(10).to_u64(), Some(1024));
    }

    #[test]
    fn test_shl_wrapping() {
        let a = APInt::from_u64(8, 0x01);
        assert_eq!(a.shl(8).to_u64(), Some(0)); // shifted all out
        assert_eq!(a.shl(9).to_u64(), Some(0));
    }

    #[test]
    fn test_shl_65bit() {
        let a = APInt::from_u64(65, 1);
        let s = a.shl(64);
        assert_eq!(s.words[0], 0);
        assert_eq!(s.words[1], 1);
    }

    #[test]
    fn test_lshr_basic() {
        let a = APInt::from_u64(64, 0x8000_0000_0000_0000);
        assert_eq!(a.lshr(63).to_u64(), Some(1));
    }

    #[test]
    fn test_lshr_zero_fill() {
        let a = APInt::from_u64(64, 0xFFFF_FFFF_FFFF_FFFF);
        assert_eq!(a.lshr(4).to_u64(), Some(0x0FFF_FFFF_FFFF_FFFF));
    }

    #[test]
    fn test_ashr_sign_extend() {
        // 8-bit: 0x80 = -128 (signed)
        let a = APInt::from_i64(8, -128);
        let s = a.ashr(1);
        // -128 >> 1 = -64 = 0xC0
        assert_eq!(s.to_i64(), Some(-64));

        let s2 = a.ashr(4);
        // -128 >> 4 = -8 = 0xF8
        assert_eq!(s2.to_i64(), Some(-8));
    }

    #[test]
    fn test_ashr_positive() {
        let a = APInt::from_u64(8, 0x40); // 64
        assert_eq!(a.ashr(1).to_u64(), Some(32));
        assert_eq!(a.ashr(6).to_u64(), Some(1));
        assert_eq!(a.ashr(7).to_u64(), Some(0));
    }

    #[test]
    fn test_rotl() {
        // 8-bit: 0b10000001 (129)
        let a = APInt::from_u64(8, 0x81);
        assert_eq!(a.rotl(1).to_u64(), Some(0x03)); // 0b00000011
        assert_eq!(a.rotl(2).to_u64(), Some(0x06)); // 0b00000110
    }

    #[test]
    fn test_rotr() {
        let a = APInt::from_u64(8, 0x81);
        assert_eq!(a.rotr(1).to_u64(), Some(0xC0)); // 0b11000000
        assert_eq!(a.rotr(2).to_u64(), Some(0x60)); // 0b01100000
    }

    #[test]
    fn test_trunc() {
        let a = APInt::from_u64(64, 0x123456789ABCDEF0);
        let t = a.trunc(32);
        assert_eq!(t.bit_width, 32);
        assert_eq!(t.to_u64(), Some(0x9ABCDEF0));
    }

    #[test]
    fn test_sext() {
        // 8-bit: 0xFF = -1
        let a = APInt::from_i64(8, -1);
        let s = a.sext(64);
        assert_eq!(s.bit_width, 64);
        assert_eq!(s.to_i64(), Some(-1));
    }

    #[test]
    fn test_zext() {
        let a = APInt::from_u64(8, 0xFF);
        let z = a.zext(64);
        assert_eq!(z.bit_width, 64);
        assert_eq!(z.to_u64(), Some(0xFF));
    }

    #[test]
    fn test_extract_bits() {
        // 64-bit: 0x123456789ABCDEF0
        let a = APInt::from_u64(64, 0x123456789ABCDEF0);
        let e = a.extract_bits(4, 8);
        // Bits [4..12) of ...DEF0: F0 = 1111_0000, bits 4..11 = 1111_1111? No.
        // Let's compute: 0x...DEF0 → bits 4..11: 0xEF = 239? Actually:
        // ...DEF0 in binary: ...1101_1110_1111_0000
        // bit 0 is LSB (0), bit 4..11: starting from bit 4: 1111_111? No...
        // 0x...DEF0 byte view: F0 = 11110000, EF = 11101111, DE = 11011110
        // bits [4..12): bits 4,5,6,7,8,9,10,11 = 1111 1110?
        // Let me just check that extract_bits returns correct width.
        assert_eq!(e.bit_width, 8);
        // The value should be (a >> 4) & 0xFF = 0x...DEF0 >> 4 = 0x...DEF = 0xEF = 239
        assert_eq!(e.to_u64(), Some(0xEF));
    }

    #[test]
    fn test_extract_bits_boundary() {
        let a = APInt::from_u64(65, u64::MAX);
        let e = a.extract_bits(60, 5);
        assert_eq!(e.bit_width, 5);
        // a has bits [0..63] = 1, bit 64 = 0
        // bits 60..64: 4 bits of 1 from word 0, 1 bit of 0 from word 1
        assert_eq!(e.to_u64(), Some(0x0F)); // lower 4 bits = 1, upper 1 bit = 0 → 0b01111 = 15
    }

    // =======================================================================
    // Comparison tests
    // =======================================================================

    #[test]
    fn test_eq() {
        let a = APInt::from_u64(64, 42);
        let b = APInt::from_u64(64, 42);
        let c = APInt::from_u64(64, 99);
        assert!(a.eq(&b));
        assert!(a.ne(&c));
    }

    #[test]
    fn test_ult() {
        let a = APInt::from_u64(64, 100);
        let b = APInt::from_u64(64, 200);
        assert!(a.ult(&b));
        assert!(!b.ult(&a));
    }

    #[test]
    fn test_ule() {
        let a = APInt::from_u64(64, 100);
        let b = APInt::from_u64(64, 100);
        assert!(a.ule(&b));
        assert!(b.ule(&a));
    }

    #[test]
    fn test_slt_positive() {
        let a = APInt::from_i64(64, 100);
        let b = APInt::from_i64(64, 200);
        assert!(a.slt(&b));
    }

    #[test]
    fn test_slt_negative() {
        let a = APInt::from_i64(64, -100);
        let b = APInt::from_i64(64, 50);
        assert!(a.slt(&b));
    }

    #[test]
    fn test_slt_both_negative() {
        let a = APInt::from_i64(64, -200);
        let b = APInt::from_i64(64, -100);
        assert!(a.slt(&b));
    }

    #[test]
    fn test_is_negative() {
        let a = APInt::from_i64(64, -1);
        assert!(a.is_negative());
        let b = APInt::from_u64(64, 1);
        assert!(!b.is_negative());
    }

    #[test]
    fn test_is_power_of_2() {
        assert!(APInt::from_u64(64, 1).is_power_of_2());
        assert!(APInt::from_u64(64, 2).is_power_of_2());
        assert!(APInt::from_u64(64, 1024).is_power_of_2());
        assert!(!APInt::from_u64(64, 0).is_power_of_2());
        assert!(!APInt::from_u64(64, 3).is_power_of_2());
        assert!(!APInt::from_u64(64, 1023).is_power_of_2());
    }

    #[test]
    fn test_is_signed_int_n() {
        let a = APInt::from_i64(64, 127);
        assert!(a.is_signed_int_n(8)); // fits in 8-bit signed
        let b = APInt::from_i64(64, 128);
        assert!(!b.is_signed_int_n(8)); // doesn't fit in 8-bit signed
        let c = APInt::from_i64(64, -128);
        assert!(c.is_signed_int_n(8));
        let d = APInt::from_i64(64, -129);
        assert!(!d.is_signed_int_n(8));
    }

    #[test]
    fn test_is_int_n() {
        let a = APInt::from_u64(64, 255);
        assert!(a.is_int_n(8)); // fits in 8-bit unsigned
        let b = APInt::from_u64(64, 256);
        assert!(!b.is_int_n(8));
    }

    // =======================================================================
    // Conversion tests
    // =======================================================================

    #[test]
    fn test_to_u64_exact() {
        assert_eq!(APInt::from_u64(32, 42).to_u64(), Some(42));
    }

    #[test]
    fn test_to_u64_none() {
        // Value too large for u64.
        let a = APInt::from_u64(128, 1).shl(65);
        assert_eq!(a.to_u64(), None);
    }

    #[test]
    fn test_to_i64_positive() {
        assert_eq!(APInt::from_i64(64, 42).to_i64(), Some(42));
    }

    #[test]
    fn test_to_i64_negative() {
        assert_eq!(APInt::from_i64(64, -42).to_i64(), Some(-42));
    }

    #[test]
    fn test_to_i64_narrow() {
        // 8-bit signed value, sign-extended to i64.
        let a = APInt::from_i64(8, -1);
        assert_eq!(a.to_i64(), Some(-1));
        let b = APInt::from_i64(8, 127);
        assert_eq!(b.to_i64(), Some(127));
    }

    #[test]
    fn test_get_limited_value() {
        let a = APInt::from_u64(64, 50);
        assert_eq!(a.get_limited_value(100), 50);
        assert_eq!(a.get_limited_value(40), 40); // saturated
    }

    // =======================================================================
    // Bit-level access tests
    // =======================================================================

    #[test]
    fn test_get_bit() {
        let a = APInt::from_u64(64, 0b1010);
        assert!(a.get_bit(1));
        assert!(!a.get_bit(0));
        assert!(a.get_bit(3));
        assert!(!a.get_bit(2));
    }

    #[test]
    fn test_set_bit() {
        let mut a = APInt::from_u64(64, 0);
        a.set_bit(5);
        assert_eq!(a.to_u64(), Some(32));
        a.set_bit(0);
        assert_eq!(a.to_u64(), Some(33));
    }

    #[test]
    fn test_clear_bit() {
        let mut a = APInt::from_u64(64, 0xFF);
        a.clear_bit(0);
        assert_eq!(a.to_u64(), Some(0xFE));
        a.clear_bit(7);
        assert_eq!(a.to_u64(), Some(0x7E));
    }

    #[test]
    fn test_count_leading_zeros() {
        assert_eq!(APInt::from_u64(64, 1).count_leading_zeros(), 63);
        assert_eq!(APInt::from_u64(64, 0).count_leading_zeros(), 64);
        assert_eq!(APInt::from_u64(8, 0x0F).count_leading_zeros(), 4);
    }

    #[test]
    fn test_count_trailing_zeros() {
        assert_eq!(APInt::from_u64(64, 8).count_trailing_zeros(), 3);
        assert_eq!(APInt::from_u64(64, 0).count_trailing_zeros(), 64);
        // For 8-bit, count trailing zeros caps at bit_width.
        assert_eq!(APInt::from_u64(8, 0).count_trailing_zeros(), 8);
    }

    #[test]
    fn test_count_population() {
        assert_eq!(APInt::from_u64(64, 0).count_population(), 0);
        assert_eq!(APInt::from_u64(64, 0xFF).count_population(), 8);
        assert_eq!(APInt::from_u64(64, u64::MAX).count_population(), 64);
    }

    #[test]
    fn test_get_lo_bits() {
        let a = APInt::from_u64(64, 0xDEADBEEF);
        assert_eq!(a.get_lo_bits(16).to_u64(), Some(0xBEEF));
    }

    #[test]
    fn test_get_hi_bits() {
        // 64-bit value: high 16 bits at positions 48-63.
        let a = APInt::from_u64(64, 0xDEAD000000000000);
        assert_eq!(a.get_hi_bits(16).to_u64(), Some(0xDEAD));
    }

    // =======================================================================
    // Advanced operation tests
    // =======================================================================

    #[test]
    fn test_gcd() {
        let a = APInt::from_u64(64, 48);
        let b = APInt::from_u64(64, 18);
        assert_eq!(a.gcd(&b).to_u64(), Some(6));
    }

    #[test]
    fn test_gcd_zero() {
        let a = APInt::from_u64(64, 0);
        let b = APInt::from_u64(64, 18);
        assert_eq!(a.gcd(&b).to_u64(), Some(18));
        assert_eq!(b.gcd(&a).to_u64(), Some(18));
    }

    #[test]
    fn test_gcd_coprime() {
        let a = APInt::from_u64(64, 17);
        let b = APInt::from_u64(64, 13);
        assert_eq!(a.gcd(&b).to_u64(), Some(1));
    }

    #[test]
    fn test_gcd_large() {
        let a = APInt::from_u64(128, 1071);
        let b = APInt::from_u64(128, 462);
        assert_eq!(a.gcd(&b).to_u64(), Some(21));
    }

    #[test]
    fn test_lcm() {
        let a = APInt::from_u64(64, 12);
        let b = APInt::from_u64(64, 18);
        assert_eq!(a.lcm(&b).to_u64(), Some(36));
    }

    #[test]
    fn test_lcm_zero() {
        let a = APInt::from_u64(64, 0);
        let b = APInt::from_u64(64, 18);
        assert_eq!(a.lcm(&b).to_u64(), Some(0));
    }

    #[test]
    fn test_sqrt_perfect_square() {
        assert_eq!(APInt::from_u64(64, 0).sqrt().to_u64(), Some(0));
        assert_eq!(APInt::from_u64(64, 1).sqrt().to_u64(), Some(1));
        assert_eq!(APInt::from_u64(64, 4).sqrt().to_u64(), Some(2));
        assert_eq!(APInt::from_u64(64, 9).sqrt().to_u64(), Some(3));
        assert_eq!(APInt::from_u64(64, 100).sqrt().to_u64(), Some(10));
        assert_eq!(APInt::from_u64(64, 10000).sqrt().to_u64(), Some(100));
    }

    #[test]
    fn test_sqrt_floor() {
        assert_eq!(APInt::from_u64(64, 2).sqrt().to_u64(), Some(1));
        assert_eq!(APInt::from_u64(64, 3).sqrt().to_u64(), Some(1));
        assert_eq!(APInt::from_u64(64, 99).sqrt().to_u64(), Some(9));
        assert_eq!(APInt::from_u64(64, 120).sqrt().to_u64(), Some(10));
    }

    #[test]
    fn test_sqrt_large() {
        // sqrt(2^64 - 1) = 2^32 - 1 = 0xFFFFFFFF
        let a = APInt::from_u64(64, u64::MAX);
        let s = a.sqrt();
        // s^2 <= a
        assert!(APInt::mul(&s, &s).ule(&a));
        // (s+1)^2 > a (may overflow, so check via division)
        let s1 = APInt::add(&s, &APInt::from_u64(64, 1));
        assert!(s1.ugt(&a.udiv(&s1)));
    }

    #[test]
    fn test_sqrt_128bit() {
        // sqrt(2^64 - 1) for a 128-bit value.
        let a = APInt::from_u64(128, u64::MAX);
        let s = a.sqrt();
        // s^2 <= a (use APInt::mul to avoid method resolution issues)
        assert!(APInt::mul(&s, &s).ule(&a));
        let s1 = APInt::add(&s, &APInt::from_u64(128, 1));
        assert!(s1.ugt(&a.udiv(&s1)));
    }

    #[test]
    fn test_abs_positive() {
        let a = APInt::from_i64(64, 42);
        assert_eq!(a.abs().to_i64(), Some(42));
    }

    #[test]
    fn test_abs_negative() {
        let a = APInt::from_i64(64, -42);
        assert_eq!(a.abs().to_i64(), Some(42));
    }

    #[test]
    fn test_umin_umax() {
        let a = APInt::from_u64(64, 10);
        let b = APInt::from_u64(64, 20);
        assert_eq!(a.umin(&b).to_u64(), Some(10));
        assert_eq!(a.umax(&b).to_u64(), Some(20));
    }

    #[test]
    fn test_smin_smax() {
        let a = APInt::from_i64(64, -10);
        let b = APInt::from_i64(64, 20);
        assert_eq!(a.smin(&b).to_i64(), Some(-10));
        assert_eq!(a.smax(&b).to_i64(), Some(20));
    }

    // =======================================================================
    // Operator overload tests
    // =======================================================================

    #[test]
    fn test_operator_add() {
        let a = APInt::from_u64(64, 10);
        let b = APInt::from_u64(64, 20);
        assert_eq!((&a + &b).to_u64(), Some(30));
    }

    #[test]
    fn test_operator_sub() {
        let a = APInt::from_u64(64, 100);
        let b = APInt::from_u64(64, 30);
        assert_eq!((&a - &b).to_u64(), Some(70));
    }

    #[test]
    fn test_operator_mul() {
        let a = APInt::from_u64(64, 6);
        let b = APInt::from_u64(64, 7);
        assert_eq!((&a * &b).to_u64(), Some(42));
    }

    #[test]
    fn test_operator_bitand() {
        let a = APInt::from_u64(64, 0xFF00);
        let b = APInt::from_u64(64, 0x0FF0);
        assert_eq!((&a & &b).to_u64(), Some(0x0F00));
    }

    #[test]
    fn test_operator_bitor() {
        let a = APInt::from_u64(64, 0xFF00);
        let b = APInt::from_u64(64, 0x0FF0);
        assert_eq!((&a | &b).to_u64(), Some(0xFFF0));
    }

    #[test]
    fn test_operator_bitxor() {
        let a = APInt::from_u64(64, 0xFF00);
        let b = APInt::from_u64(64, 0x0FF0);
        assert_eq!((&a ^ &b).to_u64(), Some(0xF0F0));
    }

    #[test]
    fn test_operator_not() {
        let a = APInt::from_u64(8, 0x0F);
        assert_eq!((!a).to_u64(), Some(0xF0));
    }

    #[test]
    fn test_operator_neg() {
        let a = APInt::from_i64(64, 42);
        assert_eq!((-&a).to_i64(), Some(-42));
    }

    #[test]
    fn test_operator_shl() {
        let a = APInt::from_u64(64, 1);
        assert_eq!((&a << 10).to_u64(), Some(1024));
    }

    #[test]
    fn test_operator_shr() {
        let a = APInt::from_u64(64, 1024);
        assert_eq!((&a >> 10).to_u64(), Some(1));
    }

    #[test]
    fn test_partial_ord() {
        let a = APInt::from_u64(64, 10);
        let b = APInt::from_u64(64, 20);
        assert!(a < b);
        assert!(b > a);
        assert!(a <= b);
        assert!(b >= a);
    }

    #[test]
    fn test_partial_ord_different_widths() {
        let a = APInt::from_u64(64, 10);
        let b = APInt::from_u64(32, 20);
        assert!(a.partial_cmp(&b).is_none());
    }

    #[test]
    fn test_display() {
        let a = APInt::from_u64(64, 12345);
        assert_eq!(format!("{}", a), "12345");
    }

    #[test]
    fn test_debug() {
        let a = APInt::from_u64(64, 255);
        let s = format!("{:?}", a);
        assert!(s.contains("64b"));
        assert!(s.contains("ff"));
    }

    #[test]
    fn test_clone() {
        let a = APInt::from_u64(64, 42);
        let b = a.clone();
        assert_eq!(a, b);
        // Ensure deep copy.
        // (We can't mutate through shared reference, but clone creates independent data.)
    }

    #[test]
    fn test_hash() {
        use std::collections::hash_map::DefaultHasher;
        let a = APInt::from_u64(64, 42);
        let b = APInt::from_u64(64, 42);
        let c = APInt::from_u64(64, 99);
        let mut ha = DefaultHasher::new();
        let mut hb = DefaultHasher::new();
        let mut hc = DefaultHasher::new();
        a.hash(&mut ha);
        b.hash(&mut hb);
        c.hash(&mut hc);
        assert_eq!(ha.finish(), hb.finish());
        assert_ne!(ha.finish(), hc.finish());
    }

    // =======================================================================
    // Edge case tests
    // =======================================================================

    #[test]
    fn test_1bit_values() {
        let zero = APInt::new(1, 0, false);
        let one = APInt::new(1, 1, false);
        assert!(zero.is_zero());
        assert!(one.is_one());
        // 1-bit: bit 0 is also the sign bit.
        // In 1-bit, 1 represents both unsigned 1 and signed -1.
        assert!(one.is_negative()); // sign bit IS the only bit
        assert_eq!(zero.add(&one).to_u64(), Some(1));
        assert_eq!(one.add(&one).to_u64(), Some(0)); // 1+1 = 0 (mod 2)
        assert_eq!(one.negate().to_u64(), Some(1)); // -1 ≡ 1 (mod 2)
    }

    #[test]
    fn test_33bit() {
        // 1 << 32 = bit 32 set (in word 0 for 33-bit width, which fits in 1 word).
        let a = APInt::from_u64(33, 1).shl(32);
        assert_eq!(a.words.len(), 1);
        assert_eq!(a.words[0], 1u64 << 32);
        // Verify clear_unused_bits doesn't destroy.
        let b = APInt::from_u64(33, u64::MAX);
        // 33 bits: word 0 uses all 33 bits, the rest (bits 33..63) should be zero.
        assert_eq!(b.words[0] & ((1u64 << 33) - 1), (1u64 << 33) - 1);
        assert_eq!(b.words[0] >> 33, 0); // upper bits zero
    }

    #[test]
    fn test_128bit_add() {
        let a = APInt::from_u64(128, u64::MAX);
        let b = APInt::from_u64(128, 1);
        let sum = a.add(&b);
        // Low word wraps to 0, carry into high word.
        assert_eq!(sum.words[0], 0);
        assert_eq!(sum.words[1], 1);
    }

    #[test]
    fn test_128bit_mul() {
        // (2^64 - 1) * 2 = 2^65 - 2
        let a = APInt::from_u64(128, u64::MAX);
        let b = APInt::from_u64(128, 2);
        let prod = a.mul(&b);
        assert_eq!(prod.words[0], u64::MAX - 1); // 0xFFFFFFFFFFFFFFFE
        assert_eq!(prod.words[1], 1);
    }

    #[test]
    fn test_256bit_ops() {
        let a = APInt::get_all_ones(256);
        let b = APInt::from_u64(256, 1);
        let sum = a.add(&b);
        assert!(sum.is_zero()); // all ones + 1 = 0 (wrapping)

        let zero = APInt::get_zero(256);
        let all_ones = APInt::get_all_ones(256);
        assert!(all_ones.and(&zero).is_zero());
        assert!(all_ones.or(&zero).is_all_ones());
    }

    #[test]
    fn test_1024bit_basic() {
        let a = APInt::from_u64(1024, 42);
        assert_eq!(a.to_u64(), Some(42));
        let shifted = a.shl(1000);
        assert_eq!(
            shifted.count_leading_zeros(),
            1024 - 1000 - 6 /* for 42 */
        );
    }

    #[test]
    fn test_mul_overflow_65bit() {
        let a = APInt::from_u64(65, 1u64 << 63);
        let b = APInt::from_u64(65, 2);
        let (_result, overflow) = a.mul_overflow(&b);
        // (2^63) * 2 = 2^64, which fits in 65 bits with no overflow.
        assert!(!overflow);
    }

    #[test]
    fn test_sdiv_special_cases() {
        // i64::MIN / -1 overflows (since -i64::MIN > i64::MAX).
        let a = APInt::get_signed_min_value(64);
        let b = APInt::from_i64(64, -1);
        // In wrapping arithmetic, the result of sdiv is the wrapped value.
        // i64::MIN / -1 = i64::MIN (since the true quotient 2^63 overflows).
        let q = a.sdiv(&b);
        assert_eq!(q.to_i64(), Some(i64::MIN));
    }

    #[test]
    fn test_rotr_full_width() {
        let a = APInt::from_u64(8, 0x81);
        assert_eq!(a.rotr(8).to_u64(), Some(0x81)); // full rotation
        assert_eq!(a.rotl(8).to_u64(), Some(0x81)); // full rotation
    }

    #[test]
    fn test_sqrt_one() {
        assert_eq!(APInt::from_u64(8, 1).sqrt().to_u64(), Some(1));
    }

    #[test]
    fn test_sqrt_max_u64() {
        let a = APInt::from_u64(64, u64::MAX);
        let s = a.sqrt();
        // sqrt(2^64 - 1) ≈ 2^32.
        let expected = 0xFFFF_FFFFu64; // floor(sqrt(2^64-1))
        assert_eq!(s.to_u64(), Some(expected));
    }

    // =======================================================================
    // get_raw_data / get_num_words tests
    // =======================================================================

    #[test]
    fn test_get_num_words() {
        assert_eq!(APInt::from_u64(1, 1).get_num_words(), 1);
        assert_eq!(APInt::from_u64(64, 1).get_num_words(), 1);
        assert_eq!(APInt::from_u64(65, 1).get_num_words(), 2);
        assert_eq!(APInt::from_u64(128, 1).get_num_words(), 2);
        assert_eq!(APInt::from_u64(129, 1).get_num_words(), 3);
    }

    #[test]
    fn test_get_raw_data() {
        let a = APInt::from_u64(128, 0xDEADBEEF);
        let raw = a.get_raw_data();
        assert_eq!(raw[0], 0xDEADBEEF);
        assert_eq!(raw[1], 0);
    }

    // =======================================================================
    // Edge cases for clear_unused_bits / normalize
    // =======================================================================

    #[test]
    fn test_clear_unused_bits_65bit() {
        let mut a = APInt {
            bit_width: 65,
            words: vec![u64::MAX, u64::MAX],
        };
        a.clear_unused_bits();
        // Only bit 0 of word 1 should survive.
        assert_eq!(a.words[0], u64::MAX);
        assert_eq!(a.words[1], 1);
    }

    #[test]
    fn test_clear_unused_bits_64bit() {
        let mut a = APInt {
            bit_width: 64,
            words: vec![u64::MAX],
        };
        a.clear_unused_bits();
        // All 64 bits used.
        assert_eq!(a.words[0], u64::MAX);
    }

    #[test]
    fn test_normalize_leading_zeros() {
        // bit_width=128 requires 2 words.  normalize should keep 2 words
        // even when the upper word is zero.
        let mut a = APInt {
            bit_width: 128,
            words: vec![42, 0, 0],
        };
        a.normalize();
        // Excess zero words beyond minimum are removed; minimum (2) is kept.
        assert_eq!(a.words.len(), 2);
        assert_eq!(a.words[0], 42);
        assert_eq!(a.words[1], 0);
    }

    #[test]
    fn test_normalize_keeps_nonzero() {
        let mut a = APInt {
            bit_width: 128,
            words: vec![42, 1],
        };
        a.normalize();
        assert_eq!(a.words.len(), 2);
    }

    #[test]
    fn test_ensure_width_compatible_panics() {
        let a = APInt::from_u64(64, 5);
        let b = APInt::from_u64(32, 5);
        // This should panic; we test by checking that it does not silently succeed.
        let result = std::panic::catch_unwind(|| {
            a.add(&b);
        });
        assert!(result.is_err());
    }

    // =======================================================================
    // is_strictly_positive tests
    // =======================================================================

    #[test]
    fn test_is_strictly_positive() {
        assert!(APInt::from_u64(64, 1).is_strictly_positive());
        assert!(APInt::from_u64(64, 42).is_strictly_positive());
        assert!(!APInt::from_u64(64, 0).is_strictly_positive());
        assert!(!APInt::from_i64(64, -1).is_strictly_positive());
    }

    // =======================================================================
    // Round-trip and consistency tests
    // =======================================================================

    #[test]
    fn test_add_sub_identity() {
        let a = APInt::from_u64(64, 12345);
        let b = APInt::from_u64(64, 6789);
        let sum = a.add(&b);
        let diff = sum.sub(&b);
        assert_eq!(a, diff);
    }

    #[test]
    fn test_mul_div_identity() {
        let a = APInt::from_u64(64, 12345);
        let b = APInt::from_u64(64, 73);
        let prod = a.mul(&b);
        let quot = prod.udiv(&b);
        assert_eq!(a, quot);
    }

    #[test]
    fn test_shl_lshr_identity() {
        // shl + lshr is identity only when top bits are not shifted out.
        let a = APInt::from_u64(64, 0x000056789ABCDEF0);
        assert_eq!(a.shl(16).lshr(16), a);
    }

    #[test]
    fn test_trunc_sext_identity() {
        // Truncating to smaller width then sign-extending back may not be identity
        // if the value was too large. But for fitting values it should work.
        let a = APInt::from_i64(64, 42);
        let t = a.trunc(16);
        let s = t.sext(64);
        assert_eq!(a, s);
    }

    #[test]
    fn test_trunc_zext_identity() {
        let a = APInt::from_u64(64, 0xABCD);
        let t = a.trunc(16);
        let z = t.zext(64);
        assert_eq!(a, z);
    }

    #[test]
    fn test_negate_twice() {
        let a = APInt::from_i64(64, 42);
        assert_eq!(a.negate().negate(), a);
        // Also for min value (where negate wraps).
        let min = APInt::get_signed_min_value(64);
        assert_eq!(min.negate().negate(), min);
    }

    #[test]
    fn test_bitwise_not_twice() {
        let a = APInt::from_u64(64, 0xDEADBEEF);
        assert_eq!(APInt::not(&APInt::not(&a)), a);
    }

    // =======================================================================
    // Display test for negative values
    // =======================================================================

    #[test]
    fn test_display_negative() {
        let a = APInt::from_i64(64, -42);
        // Display prints unsigned, so this would be 2^64 - 42.
        let s = format!("{}", a);
        assert!(!s.starts_with('-'));
        assert!(s.parse::<u128>().unwrap() > 0);
    }

    // =======================================================================
    // from_string radix auto-detect
    // =======================================================================

    #[test]
    fn test_from_string_auto_radix_decimal() {
        let a = APInt::from_string("42", 0).unwrap();
        assert_eq!(a.to_u64(), Some(42));
    }

    #[test]
    fn test_from_string_auto_radix_hex() {
        let a = APInt::from_string("0x2A", 0).unwrap();
        assert_eq!(a.to_u64(), Some(42));
    }

    #[test]
    fn test_from_string_auto_radix_binary() {
        let a = APInt::from_string("0b101010", 0).unwrap();
        assert_eq!(a.to_u64(), Some(42));
    }

    #[test]
    fn test_from_string_radix_16_explicit() {
        let a = APInt::from_string("0xFF", 16).unwrap();
        assert_eq!(a.to_u64(), Some(255));
    }

    #[test]
    fn test_to_string_radices() {
        let a = APInt::from_u64(64, 42);
        assert_eq!(a.to_string(2, false), "101010");
        assert_eq!(a.to_string(8, false), "52");
        assert_eq!(a.to_string(10, false), "42");
        assert_eq!(a.to_string(16, false), "2a");
    }

    #[test]
    fn test_to_string_signed() {
        let a = APInt::from_i64(64, -42);
        assert_eq!(a.to_string(10, true), "-42");
    }

    // =======================================================================
    // from_string leading zeros and whitespace
    // =======================================================================

    #[test]
    fn test_from_string_leading_zeros() {
        let a = APInt::from_string("00042", 10).unwrap();
        assert_eq!(a.to_u64(), Some(42));
    }

    // =======================================================================
    // Large division test
    // =======================================================================

    #[test]
    fn test_udiv_128bit() {
        // (2^128 - 1) / 3
        let a = APInt::get_all_ones(128);
        let b = APInt::from_u64(128, 3);
        let q = a.udiv(&b);
        // (2^128-1)/3 = 0x5555...5555 (128 bits of alternating 0/1).
        // In words: [0x5555555555555555, 0x5555555555555555]
        let mut expected_words = vec![0x5555555555555555u64; 2];
        expected_words[1] &= last_word_mask(128); // 128 is multiple of 64, so full mask.
        let expected = APInt {
            bit_width: 128,
            words: expected_words,
        };
        assert_eq!(q, expected);
    }

    #[test]
    fn test_urem_128bit() {
        let a = APInt::get_all_ones(128);
        let b = APInt::from_u64(128, 3);
        let r = a.urem(&b);
        // (2^128 - 1) % 3 = 0 (since 2^128 ≡ 1 mod 3, so 2^128-1 ≡ 0 mod 3)
        assert!(r.is_zero());
    }

    // =======================================================================
    // test mul_overflow with 1-bit edge case
    // =======================================================================

    #[test]
    fn test_mul_overflow_1bit() {
        let a = APInt::new(1, 1, false);
        let b = APInt::new(1, 1, false);
        let (_result, overflow) = a.mul_overflow(&b);
        // 1 * 1 = 1, no overflow.
        assert!(!overflow);
    }

    #[test]
    fn test_smul_overflow_32bit() {
        let a = APInt::from_i64(32, i32::MAX as i64);
        let b = APInt::from_i64(32, 2);
        let (_result, overflow) = a.smul_overflow(&b);
        assert!(overflow);
    }
}