dotscope 0.6.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
//! x86 to SSA translator.
//!
//! This module translates decoded x86 functions into SSA form, enabling
//! integration with the existing SSA optimization and codegen infrastructure.
//!
//! # Overview
//!
//! The translation pipeline:
//!
//! ```text
//! X86Function (CFG) → analyze dominance → place phi nodes → translate blocks → SsaFunction
//! ```
//!
//! # Register Versioning
//!
//! Each x86 register is tracked as a versioned SSA variable. When a register
//! is written, a new SSA variable is created. At control flow join points,
//! phi nodes merge the different versions.
//!
//! # Phi Node Placement
//!
//! Phi nodes are placed using the dominance frontier algorithm:
//! 1. Compute dominance frontiers for the CFG
//! 2. For each register defined in a block, place phi nodes at its dominance frontier
//! 3. Iterate until fixed point (phi nodes can themselves require more phi nodes)
//!
//! # Example
//!
//! ```rust,ignore
//! use dotscope::analysis::{x86_decode_all, X86Function, X86ToSsaTranslator};
//!
//! // Decode x86 code
//! let bytes = &[0x58, 0x83, 0xc0, 0x05, 0xc3]; // pop eax; add eax, 5; ret
//! let instructions = x86_decode_all(bytes, 32, 0)?;
//! let cfg = X86Function::new(&instructions, 32, 0);
//!
//! // Translate to SSA
//! let translator = X86ToSsaTranslator::new(&cfg);
//! let ssa_function = translator.translate()?;
//! ```

use crate::{
    analysis::{
        ssa::{
            CmpKind, ConstValue, DefSite, PhiNode, PhiOperand, SsaBlock, SsaFunction,
            SsaInstruction, SsaOp, SsaType, SsaVarId, SsaVariable, VariableOrigin,
        },
        x86::{
            cfg::X86Function,
            flags::{ArithmeticKind, ConditionEval, FlagState, FlagTestSource},
            types::{X86DecodedInstruction, X86Instruction, X86Memory, X86Operand, X86Register},
        },
    },
    utils::graph::NodeId,
    Error, Result,
};
use rustc_hash::{FxHashMap, FxHashSet};

/// Number of registers tracked (0-15 GPRs for x64, 16-21 segment registers).
const MAX_REGISTERS: usize = 22;

/// Tracks the current SSA variable for each x86 register.
///
/// This is the core of register versioning - each time a register is written,
/// we create a new SSA variable and update the mapping.
#[derive(Debug, Clone)]
struct RegisterState {
    /// Current SSA variable for each register (indexed by `X86Register::base_index()`).
    registers: [Option<SsaVarId>; MAX_REGISTERS],
    /// The bitness (32 or 64) - affects which registers are valid.
    bitness: u32,
}

impl RegisterState {
    /// Creates a new register state with all registers undefined.
    fn new(bitness: u32) -> Self {
        Self {
            registers: [None; MAX_REGISTERS],
            bitness,
        }
    }

    /// Gets the current SSA variable for a register.
    fn get(&self, reg: X86Register) -> Option<SsaVarId> {
        let idx = reg.base_index() as usize;
        if idx < MAX_REGISTERS {
            self.registers[idx]
        } else {
            None
        }
    }

    /// Sets the SSA variable for a register.
    fn set(&mut self, reg: X86Register, var: SsaVarId) {
        let idx = reg.base_index() as usize;
        if idx < MAX_REGISTERS {
            self.registers[idx] = Some(var);
        }
    }

    /// Returns an iterator over all defined registers and their SSA variables.
    fn defined_registers(&self) -> impl Iterator<Item = (usize, SsaVarId)> + '_ {
        self.registers
            .iter()
            .enumerate()
            .filter_map(|(idx, var)| var.map(|v| (idx, v)))
    }

    /// Returns the number of valid registers for this bitness.
    fn register_count(&self) -> usize {
        if self.bitness == 64 {
            16
        } else {
            8
        }
    }
}

/// Tracks phi nodes needed at each block for each register.
#[derive(Debug, Default)]
struct PhiPlacement {
    /// Maps block index → register index → phi node result variable.
    phis: FxHashMap<usize, FxHashMap<usize, SsaVarId>>,
}

impl PhiPlacement {
    fn new() -> Self {
        Self::default()
    }

    /// Returns the phi variable for a register at a block, if one exists.
    fn get(&self, block: usize, reg_idx: usize) -> Option<SsaVarId> {
        self.phis.get(&block).and_then(|m| m.get(&reg_idx).copied())
    }

    /// Sets the phi variable for a register at a block.
    fn set(&mut self, block: usize, reg_idx: usize, var: SsaVarId) {
        self.phis.entry(block).or_default().insert(reg_idx, var);
    }

    /// Returns true if a phi exists for the given block and register.
    fn has(&self, block: usize, reg_idx: usize) -> bool {
        self.phis
            .get(&block)
            .is_some_and(|m| m.contains_key(&reg_idx))
    }
}

/// Translates an x86 function to SSA form.
pub struct X86ToSsaTranslator<'a> {
    /// The x86 function to translate.
    func: &'a X86Function,
    /// Register state at the end of each block (for computing phi operands).
    block_exit_states: Vec<RegisterState>,
    /// Phi placement information.
    phi_placement: PhiPlacement,
    /// Blocks that define each register (for phi placement).
    reg_def_blocks: Vec<FxHashSet<usize>>,
    /// SSA variables created during translation.
    variables: Vec<SsaVariable>,
    /// Zero constant variable (lazily created).
    zero_const: Option<SsaVarId>,
}

impl<'a> X86ToSsaTranslator<'a> {
    /// Creates a new translator for the given x86 function.
    #[must_use]
    pub fn new(func: &'a X86Function) -> Self {
        let block_count = func.block_count();
        Self {
            func,
            block_exit_states: vec![RegisterState::new(func.bitness); block_count],
            phi_placement: PhiPlacement::new(),
            reg_def_blocks: vec![FxHashSet::default(); MAX_REGISTERS],
            variables: Vec::new(),
            zero_const: None,
        }
    }

    /// Translates the x86 function to SSA form.
    ///
    /// # Returns
    ///
    /// An `SsaFunction` representing the translated code, or an error if
    /// translation fails.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The function is empty
    /// - The CFG is irreducible
    /// - An unsupported instruction is encountered
    /// - A flag pattern cannot be translated
    pub fn translate(mut self) -> Result<SsaFunction> {
        if self.func.block_count() == 0 {
            return Err(Error::X86Error("Empty function".to_string()));
        }

        // Step 1: Analyze which blocks define which registers
        self.analyze_definitions();

        // Step 2: Place phi nodes using dominance frontiers
        self.place_phi_nodes();

        // Step 3: Translate blocks in dominator tree order
        let ssa_blocks = self.translate_blocks()?;

        // Step 4: Build the SSA function
        // DynCipher functions take one argument (the input value)
        let mut ssa_func = SsaFunction::new(1, 0);

        // Add blocks
        for block in ssa_blocks {
            ssa_func.add_block(block);
        }

        // Add variables
        for var in self.variables {
            ssa_func.add_variable(var);
        }

        Ok(ssa_func)
    }

    /// Analyzes which blocks define which registers.
    fn analyze_definitions(&mut self) {
        for node_id in self.func.node_ids() {
            let block_idx = node_id.index();
            if let Some(block) = self.func.block(block_idx) {
                for instr in &block.instructions {
                    if let Some(reg_idx) = get_defined_register(&instr.instruction) {
                        self.reg_def_blocks[reg_idx].insert(block_idx);
                    }
                }
            }
        }
    }

    /// Places phi nodes at dominance frontiers.
    fn place_phi_nodes(&mut self) {
        let doms = self.func.dominators();
        let block_count = self.func.block_count();
        let bitness = self.func.bitness;
        let register_count = self.block_exit_states[0].register_count();

        // For each register that is defined somewhere
        for reg_idx in 0..register_count {
            // Clone the def_blocks to avoid borrow issues
            let def_blocks: FxHashSet<usize> = self.reg_def_blocks[reg_idx].clone();
            if def_blocks.is_empty() {
                continue;
            }

            // Worklist of blocks where we might need phi nodes
            let mut worklist: Vec<usize> = def_blocks.iter().copied().collect();
            let mut phi_blocks: FxHashSet<usize> = FxHashSet::default();

            while let Some(def_block) = worklist.pop() {
                // For each block in the dominance frontier of def_block
                for block_idx in 0..block_count {
                    // Check if block_idx is in the dominance frontier of def_block
                    // DF(X) = {Y : ∃ pred of Y s.t. X dominates pred but X doesn't strictly dominate Y}
                    let node = NodeId::new(block_idx);
                    let def_node = NodeId::new(def_block);

                    let in_frontier = self.func.predecessors(node).any(|pred| {
                        doms.dominates(def_node, pred)
                            && (def_node == node || !doms.dominates(def_node, node))
                    });

                    if in_frontier && !phi_blocks.contains(&block_idx) {
                        phi_blocks.insert(block_idx);

                        // Create phi variable
                        let phi_var = self.create_variable(
                            VariableOrigin::Phi,
                            DefSite::phi(block_idx),
                            bitness,
                        );
                        self.phi_placement.set(block_idx, reg_idx, phi_var);

                        // Phi defines the register, so add to worklist
                        if !def_blocks.contains(&block_idx) {
                            worklist.push(block_idx);
                        }
                    }
                }
            }
        }
    }

    /// Translates all blocks to SSA form.
    fn translate_blocks(&mut self) -> Result<Vec<SsaBlock>> {
        let block_count = self.func.block_count();
        let mut ssa_blocks = Vec::with_capacity(block_count);

        // Initialize argument variable (first pop loads the argument)
        let arg_var = self.create_variable(
            VariableOrigin::Argument(0),
            DefSite::entry(),
            self.func.bitness,
        );

        // Process blocks in order
        for block_idx in 0..block_count {
            let ssa_block = self.translate_block(block_idx, arg_var)?;
            ssa_blocks.push(ssa_block);
        }

        // Fill in phi operands now that we know exit states
        self.fill_phi_operands(&mut ssa_blocks);

        Ok(ssa_blocks)
    }

    /// Translates a single block to SSA form.
    fn translate_block(&mut self, block_idx: usize, arg_var: SsaVarId) -> Result<SsaBlock> {
        let mut ssa_block = SsaBlock::new(block_idx);

        // Initialize register state from predecessors
        let mut reg_state = self.compute_entry_state(block_idx);

        // Initialize segment registers with constant 0 for the entry block
        // (segment registers are constant selectors in user-mode code)
        if block_idx == 0 {
            let seg_regs = [
                X86Register::Es,
                X86Register::Cs,
                X86Register::Ss,
                X86Register::Ds,
                X86Register::Fs,
                X86Register::Gs,
            ];
            for seg in seg_regs {
                if reg_state.get(seg).is_none() {
                    let seg_var = self.create_variable(
                        VariableOrigin::Stack(0),
                        DefSite::entry(),
                        self.func.bitness,
                    );
                    reg_state.set(seg, seg_var);
                }
            }
        }

        // Add phi nodes for this block
        if let Some(block_phis) = self.phi_placement.phis.get(&block_idx) {
            for (&reg_idx, &phi_var) in block_phis {
                let origin = VariableOrigin::Phi;
                let phi = PhiNode::new(phi_var, origin);
                ssa_block.add_phi(phi);

                // Phi defines this register at block entry
                if let Some(reg) = index_to_register(reg_idx, self.func.bitness) {
                    reg_state.set(reg, phi_var);
                }
            }
        }

        // Track flags for CMP/TEST + Jcc fusion
        let mut flags = FlagState::new();

        // Track if we've seen the first POP (which loads the argument)
        let mut first_pop = true;

        // Translate each instruction
        let block = self
            .func
            .block(block_idx)
            .ok_or_else(|| Error::X86Error(format!("Block {block_idx} not found")))?;

        for decoded in &block.instructions {
            let instrs = self.translate_instruction(
                decoded,
                &mut reg_state,
                &mut flags,
                arg_var,
                &mut first_pop,
                block_idx,
            )?;

            for instr in instrs {
                ssa_block.add_instruction(instr);
            }
        }

        // Save exit state for phi operand computation
        self.block_exit_states[block_idx] = reg_state;

        Ok(ssa_block)
    }

    /// Computes the register state at block entry from phi nodes and predecessors.
    fn compute_entry_state(&self, block_idx: usize) -> RegisterState {
        let mut state = RegisterState::new(self.func.bitness);

        // If this block has phi nodes, use them
        if let Some(block_phis) = self.phi_placement.phis.get(&block_idx) {
            for (&reg_idx, &phi_var) in block_phis {
                if let Some(reg) = index_to_register(reg_idx, self.func.bitness) {
                    state.set(reg, phi_var);
                }
            }
        }

        // For entry block, registers start undefined (will be set by instructions)
        if block_idx == 0 {
            return state;
        }

        // For non-entry blocks without phis, try to get value from single predecessor
        let node = NodeId::new(block_idx);
        let preds: Vec<_> = self.func.predecessors(node).collect();

        if preds.len() == 1 {
            let pred_idx = preds[0].index();
            // Copy predecessor's exit state for registers without phi nodes
            for reg_idx in 0..state.register_count() {
                if !self.phi_placement.has(block_idx, reg_idx) {
                    if let Some(var) = self.block_exit_states[pred_idx].registers[reg_idx] {
                        state.registers[reg_idx] = Some(var);
                    }
                }
            }
        }

        state
    }

    /// Fills in phi operands after all blocks have been translated.
    fn fill_phi_operands(&self, ssa_blocks: &mut [SsaBlock]) {
        for (block_idx, ssa_block) in ssa_blocks.iter_mut().enumerate() {
            let node = NodeId::new(block_idx);

            for phi in ssa_block.phi_nodes_mut() {
                // Find which register this phi is for
                let phi_var = phi.result();
                let reg_idx = self.find_phi_register(block_idx, phi_var);

                if let Some(reg_idx) = reg_idx {
                    // Add operand from each predecessor
                    for pred in self.func.predecessors(node) {
                        let pred_idx = pred.index();
                        if let Some(var) = self.block_exit_states[pred_idx].registers[reg_idx] {
                            phi.add_operand(PhiOperand::new(var, pred_idx));
                        }
                    }
                }
            }
        }
    }

    /// Finds which register index a phi variable is for.
    fn find_phi_register(&self, block_idx: usize, phi_var: SsaVarId) -> Option<usize> {
        if let Some(block_phis) = self.phi_placement.phis.get(&block_idx) {
            for (&reg_idx, &var) in block_phis {
                if var == phi_var {
                    return Some(reg_idx);
                }
            }
        }
        None
    }

    /// Translates a single x86 instruction to SSA operations.
    #[allow(clippy::too_many_arguments)]
    fn translate_instruction(
        &mut self,
        decoded: &X86DecodedInstruction,
        reg_state: &mut RegisterState,
        flags: &mut FlagState,
        arg_var: SsaVarId,
        first_pop: &mut bool,
        block_idx: usize,
    ) -> Result<Vec<SsaInstruction>> {
        let mut result = Vec::new();

        match &decoded.instruction {
            // Data movement
            X86Instruction::Mov { dst, src } => {
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                self.set_operand_value(dst, src_var, reg_state, &mut result, block_idx)?;
                flags.clear(); // MOV doesn't set flags
            }

            X86Instruction::Movzx { dst, src } | X86Instruction::Movsx { dst, src } => {
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                // For SSA purposes, we treat zero/sign extension as a simple move
                // The type system will handle the extension semantics
                self.set_operand_value(dst, src_var, reg_state, &mut result, block_idx)?;
                flags.clear();
            }

            X86Instruction::Lea { dst, src } => {
                // LEA computes an address without dereferencing
                let addr_var =
                    self.compute_memory_address(src, reg_state, &mut result, block_idx)?;
                reg_state.set(*dst, addr_var);
                flags.clear();
            }

            X86Instruction::Push { .. } => {
                // In our simplified model, we don't track stack explicitly
                // PUSH is used in prologues which we skip
                flags.clear();
            }

            X86Instruction::Pop { dst } => {
                // First POP in DynCipher code loads the argument
                if *first_pop {
                    *first_pop = false;
                    reg_state.set(*dst, arg_var);
                } else {
                    // Subsequent POPs restore saved registers (prologue handling)
                    // We create an undefined value
                    let var = self.create_variable(
                        VariableOrigin::Stack(0),
                        DefSite::instruction(block_idx, result.len()),
                        self.func.bitness,
                    );
                    reg_state.set(*dst, var);
                }
                flags.clear();
            }

            X86Instruction::Xchg { dst, src } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                self.set_operand_value(dst, src_var, reg_state, &mut result, block_idx)?;
                self.set_operand_value(src, dst_var, reg_state, &mut result, block_idx)?;
                flags.clear();
            }

            // Arithmetic
            X86Instruction::Add { dst, src } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Add {
                    dest: res_var,
                    left: dst_var,
                    right: src_var,
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                flags.set_arithmetic(res_var, dst_var, src_var, ArithmeticKind::Add);
                // CF = (result < left) unsigned — unsigned overflow detection
                let cf = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Clt {
                    dest: cf,
                    left: res_var,
                    right: dst_var,
                    unsigned: true,
                }));
                flags.set_carry(cf);
            }

            X86Instruction::Sub { dst, src } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Sub {
                    dest: res_var,
                    left: dst_var,
                    right: src_var,
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                flags.set_arithmetic(res_var, dst_var, src_var, ArithmeticKind::Sub);
                // CF = (left < right) unsigned — borrow detection
                let cf = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Clt {
                    dest: cf,
                    left: dst_var,
                    right: src_var,
                    unsigned: true,
                }));
                flags.set_carry(cf);
            }

            X86Instruction::Imul { dst, src, src2 } => {
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                let multiplier = if let Some(s2) = src2 {
                    self.get_operand_value(s2, reg_state, &mut result, block_idx)?
                } else {
                    // Two-operand form: dst = dst * src
                    Self::get_register_value(*dst, reg_state)?
                };
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Mul {
                    dest: res_var,
                    left: src_var,
                    right: multiplier,
                }));
                reg_state.set(*dst, res_var);
                flags.set_arithmetic(res_var, src_var, multiplier, ArithmeticKind::Other);
            }

            X86Instruction::Mul { src } => {
                // MUL: EDX:EAX = EAX * src (unsigned)
                // For simplicity, we only track EAX result
                let eax = Self::get_register_value(X86Register::Eax, reg_state)?;
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Mul {
                    dest: res_var,
                    left: eax,
                    right: src_var,
                }));
                reg_state.set(X86Register::Eax, res_var);
                flags.set_arithmetic(res_var, eax, src_var, ArithmeticKind::Other);
            }

            X86Instruction::Neg { dst } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Neg {
                    dest: res_var,
                    operand: dst_var,
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                flags.set_arithmetic_unary(res_var);
                // NEG sets CF = (operand != 0)
                let zero = self.get_constant(0, &mut result, block_idx);
                let cf = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Ceq {
                    dest: cf,
                    left: dst_var,
                    right: zero,
                }));
                // Ceq gives 1 if equal, but CF = (operand != 0), so we need NOT of Ceq
                // CF = 1 - Ceq(operand, 0)  or equivalently CF = Cgt(operand, 0, unsigned)
                // Actually simpler: Ceq gives us (operand == 0), we need (operand != 0)
                // We can XOR with 1 to flip it
                let one = self.get_constant(1, &mut result, block_idx);
                let neg_cf = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Xor {
                    dest: neg_cf,
                    left: cf,
                    right: one,
                }));
                flags.set_carry(neg_cf);
            }

            X86Instruction::Inc { dst } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let one = self.get_constant(1, &mut result, block_idx);
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Add {
                    dest: res_var,
                    left: dst_var,
                    right: one,
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                // INC sets ZF/SF/OF but does NOT modify CF
                flags.set_arithmetic(res_var, dst_var, one, ArithmeticKind::Add);
            }

            X86Instruction::Dec { dst } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let one = self.get_constant(1, &mut result, block_idx);
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Sub {
                    dest: res_var,
                    left: dst_var,
                    right: one,
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                // DEC sets ZF/SF/OF but does NOT modify CF
                flags.set_arithmetic(res_var, dst_var, one, ArithmeticKind::Sub);
            }

            // Add with carry: dest = dst + src + CF
            X86Instruction::Adc { dst, src } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                // Get current carry flag (default to 0 if unknown)
                let cf_var = flags
                    .carry()
                    .unwrap_or_else(|| self.get_constant(0, &mut result, block_idx));
                // temp = dst + src
                let temp_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Add {
                    dest: temp_var,
                    left: dst_var,
                    right: src_var,
                }));
                // result = temp + CF
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Add {
                    dest: res_var,
                    left: temp_var,
                    right: cf_var,
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                flags.set_arithmetic(res_var, dst_var, src_var, ArithmeticKind::Add);
                // CF = (temp < dst) | (result < temp) — carry from either addition
                let cf1 = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Clt {
                    dest: cf1,
                    left: temp_var,
                    right: dst_var,
                    unsigned: true,
                }));
                let cf2 = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Clt {
                    dest: cf2,
                    left: res_var,
                    right: temp_var,
                    unsigned: true,
                }));
                let new_cf = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Or {
                    dest: new_cf,
                    left: cf1,
                    right: cf2,
                }));
                flags.set_carry(new_cf);
            }

            // Subtract with borrow: dest = dst - src - CF
            X86Instruction::Sbb { dst, src } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                // Get current carry flag (default to 0 if unknown)
                let cf_var = flags
                    .carry()
                    .unwrap_or_else(|| self.get_constant(0, &mut result, block_idx));
                // temp = dst - src
                let temp_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Sub {
                    dest: temp_var,
                    left: dst_var,
                    right: src_var,
                }));
                // result = temp - CF
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Sub {
                    dest: res_var,
                    left: temp_var,
                    right: cf_var,
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                flags.set_arithmetic(res_var, dst_var, src_var, ArithmeticKind::Sub);
                // CF = (dst < src) | (temp < CF) — borrow from either subtraction
                let cf1 = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Clt {
                    dest: cf1,
                    left: dst_var,
                    right: src_var,
                    unsigned: true,
                }));
                let cf2 = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Clt {
                    dest: cf2,
                    left: temp_var,
                    right: cf_var,
                    unsigned: true,
                }));
                let new_cf = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Or {
                    dest: new_cf,
                    left: cf1,
                    right: cf2,
                }));
                flags.set_carry(new_cf);
            }

            // Unsigned division: EDX:EAX / src
            X86Instruction::Div { src } => {
                let eax = Self::get_register_value(X86Register::Eax, reg_state)?;
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                // Quotient → EAX
                let quot_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Div {
                    dest: quot_var,
                    left: eax,
                    right: src_var,
                    unsigned: true,
                }));
                reg_state.set(X86Register::Eax, quot_var);
                // Remainder → EDX
                let rem_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Rem {
                    dest: rem_var,
                    left: eax,
                    right: src_var,
                    unsigned: true,
                }));
                reg_state.set(X86Register::Edx, rem_var);
                flags.set_arithmetic(quot_var, eax, src_var, ArithmeticKind::Other);
            }

            // Signed division: EDX:EAX / src
            X86Instruction::Idiv { src } => {
                let eax = Self::get_register_value(X86Register::Eax, reg_state)?;
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                // Quotient → EAX
                let quot_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Div {
                    dest: quot_var,
                    left: eax,
                    right: src_var,
                    unsigned: false,
                }));
                reg_state.set(X86Register::Eax, quot_var);
                // Remainder → EDX
                let rem_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Rem {
                    dest: rem_var,
                    left: eax,
                    right: src_var,
                    unsigned: false,
                }));
                reg_state.set(X86Register::Edx, rem_var);
                flags.set_arithmetic(quot_var, eax, src_var, ArithmeticKind::Other);
            }

            // Byte swap: reverse byte order using shifts and masks
            X86Instruction::Bswap { dst } => {
                let val = Self::get_register_value(*dst, reg_state)?;
                // bswap(x) = ((x >> 24) & 0xFF) | ((x >> 8) & 0xFF00)
                //          | ((x << 8) & 0xFF0000) | ((x << 24) & 0xFF000000)
                // For simplicity, emit as a chain of shift/mask/or operations
                let c8 = self.get_constant(8, &mut result, block_idx);
                let c24 = self.get_constant(24, &mut result, block_idx);
                let mask_ff = self.get_constant(0xFF, &mut result, block_idx);
                let mask_ff00 = self.get_constant(0xFF00, &mut result, block_idx);
                let mask_ff0000 = self.get_constant(0x00FF_0000, &mut result, block_idx);
                let mask_ff000000 =
                    self.get_constant(i64::from(0xFF00_0000_u32 as i32), &mut result, block_idx);

                // byte0 = (val >> 24) & 0xFF
                let shr24 = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Shr {
                    dest: shr24,
                    value: val,
                    amount: c24,
                    unsigned: true,
                }));
                let byte0 = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::And {
                    dest: byte0,
                    left: shr24,
                    right: mask_ff,
                }));

                // byte1 = (val >> 8) & 0xFF00
                let shr8 = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Shr {
                    dest: shr8,
                    value: val,
                    amount: c8,
                    unsigned: true,
                }));
                let byte1 = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::And {
                    dest: byte1,
                    left: shr8,
                    right: mask_ff00,
                }));

                // byte2 = (val << 8) & 0xFF0000
                let shl8 = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Shl {
                    dest: shl8,
                    value: val,
                    amount: c8,
                }));
                let byte2 = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::And {
                    dest: byte2,
                    left: shl8,
                    right: mask_ff0000,
                }));

                // byte3 = (val << 24) & 0xFF000000
                let shl24 = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Shl {
                    dest: shl24,
                    value: val,
                    amount: c24,
                }));
                let byte3 = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::And {
                    dest: byte3,
                    left: shl24,
                    right: mask_ff000000,
                }));

                // Combine: result = byte0 | byte1 | byte2 | byte3
                let or01 = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Or {
                    dest: or01,
                    left: byte0,
                    right: byte1,
                }));
                let or012 = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Or {
                    dest: or012,
                    left: or01,
                    right: byte2,
                }));
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Or {
                    dest: res_var,
                    left: or012,
                    right: byte3,
                }));

                reg_state.set(*dst, res_var);
                flags.clear();
            }

            // Conditional move: dst = condition ? src : dst
            X86Instruction::Cmovcc {
                condition,
                dst,
                src,
            } => {
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                let dst_var = Self::get_register_value(*dst, reg_state)?;

                // Evaluate condition to get a 0/1 value
                let cond_var =
                    self.evaluate_condition(*condition, flags, &mut result, block_idx)?;

                // Implement conditional move as: result = dst ^ (cond_mask & (src ^ dst))
                // where cond_mask = 0 - cond (produces 0 or 0xFFFFFFFF)
                let neg_cond = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Neg {
                    dest: neg_cond,
                    operand: cond_var,
                }));
                let xor_diff = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Xor {
                    dest: xor_diff,
                    left: src_var,
                    right: dst_var,
                }));
                let masked = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::And {
                    dest: masked,
                    left: xor_diff,
                    right: neg_cond,
                }));
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Xor {
                    dest: res_var,
                    left: dst_var,
                    right: masked,
                }));
                reg_state.set(*dst, res_var);
                // Cmovcc doesn't modify flags
            }

            // Set byte on condition: dst = condition ? 1 : 0
            X86Instruction::Setcc { condition, dst } => {
                let cond_var =
                    self.evaluate_condition(*condition, flags, &mut result, block_idx)?;
                self.set_operand_value(dst, cond_var, reg_state, &mut result, block_idx)?;
                // Setcc doesn't modify flags
            }

            // Bit scan forward/reverse
            X86Instruction::Bsf { dst, src } | X86Instruction::Bsr { dst, src } => {
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                // Approximate: result is the source value (placeholder)
                reg_state.set(*dst, src_var);
                flags.clear();
            }

            // Bit test: sets CF based on the tested bit
            X86Instruction::Bt { src, bit } => {
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                let bit_var = self.get_operand_value(bit, reg_state, &mut result, block_idx)?;
                // BT only sets flags (specifically CF), doesn't modify operands
                flags.set_test(src_var, bit_var);
            }

            // Exchange and add: temp = dst; dst = dst + src; src = temp
            X86Instruction::Xadd { dst, src } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Add {
                    dest: res_var,
                    left: dst_var,
                    right: src_var,
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                self.set_operand_value(src, dst_var, reg_state, &mut result, block_idx)?;
                flags.set_arithmetic(res_var, dst_var, src_var, ArithmeticKind::Add);
                // XADD sets CF like ADD: CF = (result < left) unsigned
                let cf = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Clt {
                    dest: cf,
                    left: res_var,
                    right: dst_var,
                    unsigned: true,
                }));
                flags.set_carry(cf);
            }

            // Bitwise
            X86Instruction::And { dst, src } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::And {
                    dest: res_var,
                    left: dst_var,
                    right: src_var,
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                flags.set_arithmetic(res_var, dst_var, src_var, ArithmeticKind::LogicalOp);
                // AND always clears CF
                let zero_cf = self.get_constant(0, &mut result, block_idx);
                flags.clear_carry(zero_cf);
            }

            X86Instruction::Or { dst, src } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Or {
                    dest: res_var,
                    left: dst_var,
                    right: src_var,
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                flags.set_arithmetic(res_var, dst_var, src_var, ArithmeticKind::LogicalOp);
                // OR always clears CF
                let zero_cf = self.get_constant(0, &mut result, block_idx);
                flags.clear_carry(zero_cf);
            }

            X86Instruction::Xor { dst, src } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let src_var = self.get_operand_value(src, reg_state, &mut result, block_idx)?;
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Xor {
                    dest: res_var,
                    left: dst_var,
                    right: src_var,
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                flags.set_arithmetic(res_var, dst_var, src_var, ArithmeticKind::LogicalOp);
                // XOR always clears CF
                let zero_cf = self.get_constant(0, &mut result, block_idx);
                flags.clear_carry(zero_cf);
            }

            X86Instruction::Not { dst } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Not {
                    dest: res_var,
                    operand: dst_var,
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                // NOT doesn't affect flags (except in some specific cases)
            }

            X86Instruction::Shl { dst, count } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let count_var = self.get_operand_value(count, reg_state, &mut result, block_idx)?;
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Shl {
                    dest: res_var,
                    value: dst_var,
                    amount: count_var,
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                flags.set_arithmetic(res_var, dst_var, count_var, ArithmeticKind::Other);
            }

            X86Instruction::Shr { dst, count } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let count_var = self.get_operand_value(count, reg_state, &mut result, block_idx)?;
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Shr {
                    dest: res_var,
                    value: dst_var,
                    amount: count_var,
                    unsigned: true,
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                flags.set_arithmetic(res_var, dst_var, count_var, ArithmeticKind::Other);
            }

            X86Instruction::Sar { dst, count } => {
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let count_var = self.get_operand_value(count, reg_state, &mut result, block_idx)?;
                let res_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Shr {
                    dest: res_var,
                    value: dst_var,
                    amount: count_var,
                    unsigned: false, // SAR is signed shift right
                }));
                self.set_operand_value(dst, res_var, reg_state, &mut result, block_idx)?;
                flags.set_arithmetic(res_var, dst_var, count_var, ArithmeticKind::Other);
            }

            X86Instruction::Rol { dst, count } | X86Instruction::Ror { dst, count } => {
                // Rotates are complex to express in SSA
                // For now, treat as unsupported or approximate
                let dst_var = self.get_operand_value(dst, reg_state, &mut result, block_idx)?;
                let _count_var =
                    self.get_operand_value(count, reg_state, &mut result, block_idx)?;
                // Keep the value unchanged (this is an approximation)
                self.set_operand_value(dst, dst_var, reg_state, &mut result, block_idx)?;
                flags.clear();
            }

            // Comparison
            X86Instruction::Cmp { left, right } => {
                let left_var = self.get_operand_value(left, reg_state, &mut result, block_idx)?;
                let right_var = self.get_operand_value(right, reg_state, &mut result, block_idx)?;
                flags.set_compare(left_var, right_var);
                // CMP sets CF = (left < right) unsigned (same as SUB)
                let cf = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                result.push(SsaInstruction::synthetic(SsaOp::Clt {
                    dest: cf,
                    left: left_var,
                    right: right_var,
                    unsigned: true,
                }));
                flags.set_carry(cf);
            }

            X86Instruction::Test { left, right } => {
                let left_var = self.get_operand_value(left, reg_state, &mut result, block_idx)?;
                let right_var = self.get_operand_value(right, reg_state, &mut result, block_idx)?;
                flags.set_test(left_var, right_var);
                // TEST always clears CF
                let zero_cf = self.get_constant(0, &mut result, block_idx);
                flags.clear_carry(zero_cf);
            }

            // Control flow
            X86Instruction::Jmp { target } => {
                let target_block = self.find_block_for_address(*target)?;
                result.push(SsaInstruction::synthetic(SsaOp::Jump {
                    target: target_block,
                }));
            }

            X86Instruction::Jcc { condition, target } => {
                let target_block = self.find_block_for_address(*target)?;
                let fallthrough_block = block_idx + 1; // Assumes sequential layout

                // Get comparison operands from flags
                if let Some((cmp, left, right, unsigned)) = flags.get_branch_operands(*condition) {
                    // Handle TEST special case
                    if matches!(
                        flags.producer(),
                        Some(crate::analysis::x86::flags::FlagProducer::Test { .. })
                    ) {
                        // For TEST + JE/JNE, we need to compare (left & right) with 0
                        let and_result = self.create_variable(
                            VariableOrigin::Stack(0),
                            DefSite::instruction(block_idx, result.len()),
                            self.func.bitness,
                        );
                        result.push(SsaInstruction::synthetic(SsaOp::And {
                            dest: and_result,
                            left,
                            right,
                        }));
                        let zero = self.get_zero_constant(&mut result, block_idx);
                        result.push(SsaInstruction::synthetic(SsaOp::BranchCmp {
                            left: and_result,
                            right: zero,
                            cmp,
                            unsigned: false,
                            true_target: target_block,
                            false_target: fallthrough_block,
                        }));
                    } else {
                        result.push(SsaInstruction::synthetic(SsaOp::BranchCmp {
                            left,
                            right,
                            cmp,
                            unsigned,
                            true_target: target_block,
                            false_target: fallthrough_block,
                        }));
                    }
                } else {
                    // Fall back to evaluate_condition for S/NS/O/NO/P/NP conditions
                    let cond_var =
                        self.evaluate_condition(*condition, flags, &mut result, block_idx)?;
                    let zero = self.get_zero_constant(&mut result, block_idx);
                    result.push(SsaInstruction::synthetic(SsaOp::BranchCmp {
                        left: cond_var,
                        right: zero,
                        cmp: CmpKind::Ne,
                        unsigned: false,
                        true_target: target_block,
                        false_target: fallthrough_block,
                    }));
                }
            }

            X86Instruction::Ret => {
                // Return the value in EAX/RAX
                let ret_reg = if self.func.bitness == 64 {
                    X86Register::Rax
                } else {
                    X86Register::Eax
                };
                let ret_val = reg_state.get(ret_reg);
                result.push(SsaInstruction::synthetic(SsaOp::Return { value: ret_val }));
            }

            X86Instruction::Call { target: _ } => {
                // Calls are not supported in DynCipher stubs
                return Err(Error::X86Error(format!(
                    "Unsupported CALL instruction at 0x{:x}",
                    decoded.offset
                )));
            }

            // Miscellaneous
            X86Instruction::Nop => {
                // No operation
            }

            X86Instruction::Cdq => {
                // Sign-extend EAX into EDX:EAX
                // In SSA, we just track that EDX becomes a function of EAX
                let eax = Self::get_register_value(X86Register::Eax, reg_state)?;
                // EDX gets sign bits of EAX (all 0s or all 1s)
                // For simplicity, create a new variable
                let edx_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, result.len()),
                    self.func.bitness,
                );
                // EDX = EAX >> 31 (arithmetic)
                let thirty_one = self.get_constant(31, &mut result, block_idx);
                result.push(SsaInstruction::synthetic(SsaOp::Shr {
                    dest: edx_var,
                    value: eax,
                    amount: thirty_one,
                    unsigned: false,
                }));
                reg_state.set(X86Register::Edx, edx_var);
            }

            X86Instruction::Cwde => {
                // Sign-extend AX into EAX
                // In SSA, this is effectively a no-op since we track 32-bit values
                flags.clear();
            }

            X86Instruction::Unsupported { offset, mnemonic } => {
                return Err(Error::X86Error(format!(
                    "Unsupported instruction '{mnemonic}' at 0x{offset:x}"
                )));
            }
        }

        Ok(result)
    }

    /// Gets the SSA variable for an operand value.
    fn get_operand_value(
        &mut self,
        operand: &X86Operand,
        reg_state: &RegisterState,
        instrs: &mut Vec<SsaInstruction>,
        block_idx: usize,
    ) -> Result<SsaVarId> {
        match operand {
            X86Operand::Register(reg) => Self::get_register_value(*reg, reg_state),
            X86Operand::Immediate(val) => Ok(self.get_constant(*val, instrs, block_idx)),
            X86Operand::Memory(mem) => self.load_from_memory(mem, reg_state, instrs, block_idx),
        }
    }

    /// Gets the SSA variable for a register.
    fn get_register_value(reg: X86Register, reg_state: &RegisterState) -> Result<SsaVarId> {
        reg_state
            .get(reg)
            .ok_or_else(|| Error::X86Error(format!("Register {reg:?} not defined")))
    }

    /// Sets the value of an operand.
    fn set_operand_value(
        &mut self,
        operand: &X86Operand,
        value: SsaVarId,
        reg_state: &mut RegisterState,
        instrs: &mut Vec<SsaInstruction>,
        block_idx: usize,
    ) -> Result<()> {
        match operand {
            X86Operand::Register(reg) => {
                reg_state.set(*reg, value);
                Ok(())
            }
            X86Operand::Memory(mem) => {
                self.store_to_memory(mem, value, reg_state, instrs, block_idx)
            }
            X86Operand::Immediate(_) => Err(Error::X86Error(
                "Cannot store to immediate operand".to_string(),
            )),
        }
    }

    /// Loads a value from memory.
    fn load_from_memory(
        &mut self,
        mem: &X86Memory,
        reg_state: &RegisterState,
        instrs: &mut Vec<SsaInstruction>,
        block_idx: usize,
    ) -> Result<SsaVarId> {
        let addr = self.compute_memory_address(mem, reg_state, instrs, block_idx)?;
        let result = self.create_variable(
            VariableOrigin::Stack(0),
            DefSite::instruction(block_idx, instrs.len()),
            self.func.bitness,
        );

        let value_type = match mem.size {
            1 => SsaType::I8,
            2 => SsaType::I16,
            8 => SsaType::I64,
            _ => SsaType::I32,
        };

        instrs.push(SsaInstruction::synthetic(SsaOp::LoadIndirect {
            dest: result,
            addr,
            value_type,
        }));

        Ok(result)
    }

    /// Stores a value to memory.
    fn store_to_memory(
        &mut self,
        mem: &X86Memory,
        value: SsaVarId,
        reg_state: &RegisterState,
        instrs: &mut Vec<SsaInstruction>,
        block_idx: usize,
    ) -> Result<()> {
        let addr = self.compute_memory_address(mem, reg_state, instrs, block_idx)?;

        let value_type = match mem.size {
            1 => SsaType::I8,
            2 => SsaType::I16,
            8 => SsaType::I64,
            _ => SsaType::I32,
        };

        instrs.push(SsaInstruction::synthetic(SsaOp::StoreIndirect {
            addr,
            value,
            value_type,
        }));

        Ok(())
    }

    /// Evaluates an x86 condition code into a 0/1 SSA variable.
    ///
    /// This is used by Cmovcc and Setcc to produce a value based on the
    /// current flag state. It emits the necessary comparison instructions
    /// and returns an SSA variable holding 0 (false) or 1 (true).
    fn evaluate_condition(
        &mut self,
        condition: crate::analysis::x86::types::X86Condition,
        flags: &FlagState,
        instrs: &mut Vec<SsaInstruction>,
        block_idx: usize,
    ) -> Result<SsaVarId> {
        let eval = flags.get_condition_operands(condition).ok_or_else(|| {
            Error::X86Error(format!(
                "Cannot evaluate condition {condition:?}: flags unknown or unsupported"
            ))
        })?;

        match eval {
            ConditionEval::Compare {
                cmp,
                left,
                right,
                unsigned,
            } => self.emit_comparison(cmp, left, right, unsigned, instrs, block_idx),
            ConditionEval::Test { cmp, left, right } => {
                // Compute AND first, then compare to zero
                let and_result = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::And {
                    dest: and_result,
                    left,
                    right,
                }));
                let zero = self.get_zero_constant(instrs, block_idx);
                self.emit_comparison(cmp, and_result, zero, false, instrs, block_idx)
            }
            ConditionEval::ZeroTest { cmp, result } => {
                let zero = self.get_zero_constant(instrs, block_idx);
                self.emit_comparison(cmp, result, zero, false, instrs, block_idx)
            }
            ConditionEval::SignFlag { source, negated } => {
                self.emit_sign_flag(source, negated, instrs, block_idx)
            }
            ConditionEval::OverflowFlag {
                left,
                right,
                result,
                kind,
                negated,
            } => self.emit_overflow_flag(left, right, result, kind, negated, instrs, block_idx),
            ConditionEval::ParityFlag { source, negated } => {
                self.emit_parity_flag(source, negated, instrs, block_idx)
            }
        }
    }

    /// Emits a comparison SSA operation (Ceq/Clt/Cgt) and returns the result variable.
    fn emit_comparison(
        &mut self,
        cmp: crate::analysis::ssa::CmpKind,
        left: SsaVarId,
        right: SsaVarId,
        unsigned: bool,
        instrs: &mut Vec<SsaInstruction>,
        block_idx: usize,
    ) -> Result<SsaVarId> {
        use crate::analysis::ssa::CmpKind;

        let result = self.create_variable(
            VariableOrigin::Stack(0),
            DefSite::instruction(block_idx, instrs.len()),
            self.func.bitness,
        );

        match cmp {
            CmpKind::Eq => {
                instrs.push(SsaInstruction::synthetic(SsaOp::Ceq {
                    dest: result,
                    left,
                    right,
                }));
            }
            CmpKind::Ne => {
                // Ne = !Eq: compute Ceq then XOR with 1
                let eq_result = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::Ceq {
                    dest: eq_result,
                    left,
                    right,
                }));
                let one = self.get_constant(1, instrs, block_idx);
                instrs.push(SsaInstruction::synthetic(SsaOp::Xor {
                    dest: result,
                    left: eq_result,
                    right: one,
                }));
            }
            CmpKind::Lt => {
                instrs.push(SsaInstruction::synthetic(SsaOp::Clt {
                    dest: result,
                    left,
                    right,
                    unsigned,
                }));
            }
            CmpKind::Gt => {
                instrs.push(SsaInstruction::synthetic(SsaOp::Cgt {
                    dest: result,
                    left,
                    right,
                    unsigned,
                }));
            }
            CmpKind::Le => {
                // Le = !Gt: compute Cgt then XOR with 1
                let gt_result = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::Cgt {
                    dest: gt_result,
                    left,
                    right,
                    unsigned,
                }));
                let one = self.get_constant(1, instrs, block_idx);
                instrs.push(SsaInstruction::synthetic(SsaOp::Xor {
                    dest: result,
                    left: gt_result,
                    right: one,
                }));
            }
            CmpKind::Ge => {
                // Ge = !Lt: compute Clt then XOR with 1
                let lt_result = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::Clt {
                    dest: lt_result,
                    left,
                    right,
                    unsigned,
                }));
                let one = self.get_constant(1, instrs, block_idx);
                instrs.push(SsaInstruction::synthetic(SsaOp::Xor {
                    dest: result,
                    left: lt_result,
                    right: one,
                }));
            }
        }

        Ok(result)
    }

    /// Resolves a `FlagTestSource` to an SSA variable, emitting Sub or And if needed.
    fn resolve_flag_test_source(
        &mut self,
        source: FlagTestSource,
        instrs: &mut Vec<SsaInstruction>,
        block_idx: usize,
    ) -> SsaVarId {
        match source {
            FlagTestSource::Direct(var) => var,
            FlagTestSource::Subtract { left, right } => {
                let result = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::Sub {
                    dest: result,
                    left,
                    right,
                }));
                result
            }
            FlagTestSource::BitwiseAnd { left, right } => {
                let result = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::And {
                    dest: result,
                    left,
                    right,
                }));
                result
            }
        }
    }

    /// Emits SSA instructions to compute the sign flag (SF) as a 0/1 value.
    ///
    /// SF = MSB of the value. Extracts it via `(value >> (bitwidth-1)) & 1`.
    fn emit_sign_flag(
        &mut self,
        source: FlagTestSource,
        negated: bool,
        instrs: &mut Vec<SsaInstruction>,
        block_idx: usize,
    ) -> Result<SsaVarId> {
        let value = self.resolve_flag_test_source(source, instrs, block_idx);
        let shift_amount = if self.func.bitness == 64 { 63 } else { 31 };
        let shift_const = self.get_constant(shift_amount, instrs, block_idx);

        // sign_shifted = value >> (bitwidth-1), unsigned shift
        let sign_shifted = self.create_variable(
            VariableOrigin::Stack(0),
            DefSite::instruction(block_idx, instrs.len()),
            self.func.bitness,
        );
        instrs.push(SsaInstruction::synthetic(SsaOp::Shr {
            dest: sign_shifted,
            value,
            amount: shift_const,
            unsigned: true,
        }));

        // sign_bit = sign_shifted & 1
        let one = self.get_constant(1, instrs, block_idx);
        let sign_bit = self.create_variable(
            VariableOrigin::Stack(0),
            DefSite::instruction(block_idx, instrs.len()),
            self.func.bitness,
        );
        instrs.push(SsaInstruction::synthetic(SsaOp::And {
            dest: sign_bit,
            left: sign_shifted,
            right: one,
        }));

        if negated {
            // NS: return !SF = sign_bit ^ 1
            let result = self.create_variable(
                VariableOrigin::Stack(0),
                DefSite::instruction(block_idx, instrs.len()),
                self.func.bitness,
            );
            let one2 = self.get_constant(1, instrs, block_idx);
            instrs.push(SsaInstruction::synthetic(SsaOp::Xor {
                dest: result,
                left: sign_bit,
                right: one2,
            }));
            Ok(result)
        } else {
            Ok(sign_bit)
        }
    }

    /// Emits SSA instructions to compute the overflow flag (OF) as a 0/1 value.
    ///
    /// The computation depends on the arithmetic operation that set the flags:
    /// - `LogicalOp`: OF is always 0 (TEST, AND, OR, XOR clear OF)
    /// - `Sub`/CMP: OF = ((left ^ right) & (left ^ result)) >> MSB
    /// - `Add`: OF = ((left ^ result) & (right ^ result)) >> MSB
    /// - `Neg`: OF = (result == INT_MIN)
    /// - `Other`: OF approximated as 0
    #[allow(clippy::too_many_arguments)]
    fn emit_overflow_flag(
        &mut self,
        left: SsaVarId,
        right: SsaVarId,
        result: Option<SsaVarId>,
        kind: ArithmeticKind,
        negated: bool,
        instrs: &mut Vec<SsaInstruction>,
        block_idx: usize,
    ) -> Result<SsaVarId> {
        let of = match kind {
            ArithmeticKind::LogicalOp | ArithmeticKind::Other => {
                // OF = 0 for logical operations and undefined/complex operations
                self.get_constant(0, instrs, block_idx)
            }
            ArithmeticKind::Sub => {
                // For CMP (result=None): compute sub_result = left - right
                // For SUB (result=Some): use existing result
                let sub_result = if let Some(r) = result {
                    r
                } else {
                    let r = self.create_variable(
                        VariableOrigin::Stack(0),
                        DefSite::instruction(block_idx, instrs.len()),
                        self.func.bitness,
                    );
                    instrs.push(SsaInstruction::synthetic(SsaOp::Sub {
                        dest: r,
                        left,
                        right,
                    }));
                    r
                };

                // OF = ((left ^ right) & (left ^ result)) >> (bitwidth-1)
                let xor_lr = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::Xor {
                    dest: xor_lr,
                    left,
                    right,
                }));

                let xor_ls = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::Xor {
                    dest: xor_ls,
                    left,
                    right: sub_result,
                }));

                let and_both = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::And {
                    dest: and_both,
                    left: xor_lr,
                    right: xor_ls,
                }));

                let shift_amount = if self.func.bitness == 64 { 63 } else { 31 };
                let shift_const = self.get_constant(shift_amount, instrs, block_idx);
                let shifted = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::Shr {
                    dest: shifted,
                    value: and_both,
                    amount: shift_const,
                    unsigned: true,
                }));

                let one = self.get_constant(1, instrs, block_idx);
                let of_bit = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::And {
                    dest: of_bit,
                    left: shifted,
                    right: one,
                }));
                of_bit
            }
            ArithmeticKind::Add => {
                // OF = ((left ^ result) & (right ^ result)) >> (bitwidth-1)
                let add_result = result.unwrap_or(left); // Should always have result for Add

                let xor_lr = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::Xor {
                    dest: xor_lr,
                    left,
                    right: add_result,
                }));

                let xor_rr = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::Xor {
                    dest: xor_rr,
                    left: right,
                    right: add_result,
                }));

                let and_both = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::And {
                    dest: and_both,
                    left: xor_lr,
                    right: xor_rr,
                }));

                let shift_amount = if self.func.bitness == 64 { 63 } else { 31 };
                let shift_const = self.get_constant(shift_amount, instrs, block_idx);
                let shifted = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::Shr {
                    dest: shifted,
                    value: and_both,
                    amount: shift_const,
                    unsigned: true,
                }));

                let one = self.get_constant(1, instrs, block_idx);
                let of_bit = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::And {
                    dest: of_bit,
                    left: shifted,
                    right: one,
                }));
                of_bit
            }
            ArithmeticKind::Neg => {
                // OF = (result == INT_MIN)
                let neg_result = result.unwrap_or(left);
                let int_min = if self.func.bitness == 64 {
                    self.get_constant(i64::MIN, instrs, block_idx)
                } else {
                    self.get_constant(i64::from(i32::MIN), instrs, block_idx)
                };
                let of_bit = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::Ceq {
                    dest: of_bit,
                    left: neg_result,
                    right: int_min,
                }));
                of_bit
            }
        };

        if negated {
            // NO: return !OF = of ^ 1
            let result_var = self.create_variable(
                VariableOrigin::Stack(0),
                DefSite::instruction(block_idx, instrs.len()),
                self.func.bitness,
            );
            let one = self.get_constant(1, instrs, block_idx);
            instrs.push(SsaInstruction::synthetic(SsaOp::Xor {
                dest: result_var,
                left: of,
                right: one,
            }));
            Ok(result_var)
        } else {
            Ok(of)
        }
    }

    /// Emits SSA instructions to compute the parity flag (PF) as a 0/1 value.
    ///
    /// PF = 1 when the low byte of the value has even parity (even number of 1-bits).
    /// Computed by XOR-folding the low byte down to a single bit.
    fn emit_parity_flag(
        &mut self,
        source: FlagTestSource,
        negated: bool,
        instrs: &mut Vec<SsaInstruction>,
        block_idx: usize,
    ) -> Result<SsaVarId> {
        let value = self.resolve_flag_test_source(source, instrs, block_idx);

        // b = value & 0xFF (isolate low byte)
        let mask_ff = self.get_constant(0xFF, instrs, block_idx);
        let b = self.create_variable(
            VariableOrigin::Stack(0),
            DefSite::instruction(block_idx, instrs.len()),
            self.func.bitness,
        );
        instrs.push(SsaInstruction::synthetic(SsaOp::And {
            dest: b,
            left: value,
            right: mask_ff,
        }));

        // b ^= b >> 4
        let c4 = self.get_constant(4, instrs, block_idx);
        let shr4 = self.create_variable(
            VariableOrigin::Stack(0),
            DefSite::instruction(block_idx, instrs.len()),
            self.func.bitness,
        );
        instrs.push(SsaInstruction::synthetic(SsaOp::Shr {
            dest: shr4,
            value: b,
            amount: c4,
            unsigned: true,
        }));
        let b1 = self.create_variable(
            VariableOrigin::Stack(0),
            DefSite::instruction(block_idx, instrs.len()),
            self.func.bitness,
        );
        instrs.push(SsaInstruction::synthetic(SsaOp::Xor {
            dest: b1,
            left: b,
            right: shr4,
        }));

        // b ^= b >> 2
        let c2 = self.get_constant(2, instrs, block_idx);
        let shr2 = self.create_variable(
            VariableOrigin::Stack(0),
            DefSite::instruction(block_idx, instrs.len()),
            self.func.bitness,
        );
        instrs.push(SsaInstruction::synthetic(SsaOp::Shr {
            dest: shr2,
            value: b1,
            amount: c2,
            unsigned: true,
        }));
        let b2 = self.create_variable(
            VariableOrigin::Stack(0),
            DefSite::instruction(block_idx, instrs.len()),
            self.func.bitness,
        );
        instrs.push(SsaInstruction::synthetic(SsaOp::Xor {
            dest: b2,
            left: b1,
            right: shr2,
        }));

        // b ^= b >> 1
        let c1 = self.get_constant(1, instrs, block_idx);
        let shr1 = self.create_variable(
            VariableOrigin::Stack(0),
            DefSite::instruction(block_idx, instrs.len()),
            self.func.bitness,
        );
        instrs.push(SsaInstruction::synthetic(SsaOp::Shr {
            dest: shr1,
            value: b2,
            amount: c1,
            unsigned: true,
        }));
        let b3 = self.create_variable(
            VariableOrigin::Stack(0),
            DefSite::instruction(block_idx, instrs.len()),
            self.func.bitness,
        );
        instrs.push(SsaInstruction::synthetic(SsaOp::Xor {
            dest: b3,
            left: b2,
            right: shr1,
        }));

        // odd_parity = b3 & 1
        let one = self.get_constant(1, instrs, block_idx);
        let odd_parity = self.create_variable(
            VariableOrigin::Stack(0),
            DefSite::instruction(block_idx, instrs.len()),
            self.func.bitness,
        );
        instrs.push(SsaInstruction::synthetic(SsaOp::And {
            dest: odd_parity,
            left: b3,
            right: one,
        }));

        if negated {
            // NP (PF=0): return odd_parity (1 when odd number of bits)
            Ok(odd_parity)
        } else {
            // P (PF=1): return !odd_parity (1 when even number of bits)
            let result = self.create_variable(
                VariableOrigin::Stack(0),
                DefSite::instruction(block_idx, instrs.len()),
                self.func.bitness,
            );
            let one2 = self.get_constant(1, instrs, block_idx);
            instrs.push(SsaInstruction::synthetic(SsaOp::Xor {
                dest: result,
                left: odd_parity,
                right: one2,
            }));
            Ok(result)
        }
    }

    /// Computes the effective address for a memory operand.
    fn compute_memory_address(
        &mut self,
        mem: &X86Memory,
        reg_state: &RegisterState,
        instrs: &mut Vec<SsaInstruction>,
        block_idx: usize,
    ) -> Result<SsaVarId> {
        // Start with base or 0
        let mut addr = if let Some(base) = mem.base {
            Self::get_register_value(base, reg_state)?
        } else {
            self.get_zero_constant(instrs, block_idx)
        };

        // Add index * scale
        if let Some(index) = mem.index {
            let index_val = Self::get_register_value(index, reg_state)?;

            // Multiply by scale if not 1
            let scaled = if mem.scale == 1 {
                index_val
            } else {
                let scale_const = self.get_constant(i64::from(mem.scale), instrs, block_idx);
                let scaled_var = self.create_variable(
                    VariableOrigin::Stack(0),
                    DefSite::instruction(block_idx, instrs.len()),
                    self.func.bitness,
                );
                instrs.push(SsaInstruction::synthetic(SsaOp::Mul {
                    dest: scaled_var,
                    left: index_val,
                    right: scale_const,
                }));
                scaled_var
            };

            // Add to address
            let new_addr = self.create_variable(
                VariableOrigin::Stack(0),
                DefSite::instruction(block_idx, instrs.len()),
                self.func.bitness,
            );
            instrs.push(SsaInstruction::synthetic(SsaOp::Add {
                dest: new_addr,
                left: addr,
                right: scaled,
            }));
            addr = new_addr;
        }

        // Add displacement
        if mem.displacement != 0 {
            let disp_const = self.get_constant(mem.displacement, instrs, block_idx);
            let new_addr = self.create_variable(
                VariableOrigin::Stack(0),
                DefSite::instruction(block_idx, instrs.len()),
                self.func.bitness,
            );
            instrs.push(SsaInstruction::synthetic(SsaOp::Add {
                dest: new_addr,
                left: addr,
                right: disp_const,
            }));
            addr = new_addr;
        }

        Ok(addr)
    }

    /// Gets or creates an SSA variable for a constant value.
    fn get_constant(
        &mut self,
        value: i64,
        instrs: &mut Vec<SsaInstruction>,
        block_idx: usize,
    ) -> SsaVarId {
        let var = self.create_variable(
            VariableOrigin::Stack(0),
            DefSite::instruction(block_idx, instrs.len()),
            self.func.bitness,
        );

        let const_value = if self.func.bitness == 64 {
            ConstValue::I64(value)
        } else {
            // Safe: x86 32-bit constant intentionally truncated to i32
            #[allow(clippy::cast_possible_truncation)]
            let truncated = value as i32;
            ConstValue::I32(truncated)
        };

        instrs.push(SsaInstruction::synthetic(SsaOp::Const {
            dest: var,
            value: const_value,
        }));

        var
    }

    /// Gets or creates a zero constant.
    fn get_zero_constant(
        &mut self,
        instrs: &mut Vec<SsaInstruction>,
        block_idx: usize,
    ) -> SsaVarId {
        if let Some(zero) = self.zero_const {
            return zero;
        }

        let zero = self.get_constant(0, instrs, block_idx);
        self.zero_const = Some(zero);
        zero
    }

    /// Creates a new SSA variable.
    fn create_variable(
        &mut self,
        origin: VariableOrigin,
        def_site: DefSite,
        bitness: u32,
    ) -> SsaVarId {
        let var_type = if bitness == 64 {
            SsaType::I64
        } else {
            SsaType::I32
        };
        let var = SsaVariable::new_typed(origin, 0, def_site, var_type);
        let id = var.id();
        self.variables.push(var);
        id
    }

    /// Finds the block index for a given address.
    fn find_block_for_address(&self, addr: u64) -> Result<usize> {
        let offset = addr - self.func.base_address;

        for node_id in self.func.node_ids() {
            let idx = node_id.index();
            if let Some(block) = self.func.block(idx) {
                if block.start_offset == offset {
                    return Ok(idx);
                }
            }
        }

        Err(Error::X86Error(format!(
            "No block found for address 0x{addr:x}"
        )))
    }
}

/// Returns the register index defined by an instruction, if any.
fn get_defined_register(instr: &X86Instruction) -> Option<usize> {
    match instr {
        X86Instruction::Mov { dst, .. }
        | X86Instruction::Movzx { dst, .. }
        | X86Instruction::Movsx { dst, .. }
        | X86Instruction::Add { dst, .. }
        | X86Instruction::Sub { dst, .. }
        | X86Instruction::And { dst, .. }
        | X86Instruction::Or { dst, .. }
        | X86Instruction::Xor { dst, .. }
        | X86Instruction::Not { dst }
        | X86Instruction::Neg { dst }
        | X86Instruction::Inc { dst }
        | X86Instruction::Dec { dst }
        | X86Instruction::Shl { dst, .. }
        | X86Instruction::Shr { dst, .. }
        | X86Instruction::Sar { dst, .. }
        | X86Instruction::Rol { dst, .. }
        | X86Instruction::Ror { dst, .. }
        | X86Instruction::Adc { dst, .. }
        | X86Instruction::Sbb { dst, .. }
        | X86Instruction::Setcc { dst, .. }
        | X86Instruction::Xadd { dst, .. } => {
            if let X86Operand::Register(reg) = dst {
                Some(reg.base_index() as usize)
            } else {
                None
            }
        }
        X86Instruction::Lea { dst, .. }
        | X86Instruction::Imul { dst, .. }
        | X86Instruction::Bswap { dst }
        | X86Instruction::Cmovcc { dst, .. }
        | X86Instruction::Bsf { dst, .. }
        | X86Instruction::Bsr { dst, .. } => Some(dst.base_index() as usize),
        X86Instruction::Pop { dst } => Some(dst.base_index() as usize),
        X86Instruction::Mul { .. }
        | X86Instruction::Div { .. }
        | X86Instruction::Idiv { .. }
        | X86Instruction::Cdq => {
            // These define EAX/EDX
            Some(0) // EAX
        }
        X86Instruction::Xchg { dst, src } => {
            // Both operands are modified
            if let X86Operand::Register(reg) = dst {
                Some(reg.base_index() as usize)
            } else if let X86Operand::Register(reg) = src {
                Some(reg.base_index() as usize)
            } else {
                None
            }
        }
        _ => None,
    }
}

/// Converts a register index back to a register.
fn index_to_register(index: usize, bitness: u32) -> Option<X86Register> {
    // Segment registers are the same regardless of bitness
    match index {
        16 => return Some(X86Register::Es),
        17 => return Some(X86Register::Cs),
        18 => return Some(X86Register::Ss),
        19 => return Some(X86Register::Ds),
        20 => return Some(X86Register::Fs),
        21 => return Some(X86Register::Gs),
        _ => {}
    }

    if bitness == 64 {
        match index {
            0 => Some(X86Register::Rax),
            1 => Some(X86Register::Rcx),
            2 => Some(X86Register::Rdx),
            3 => Some(X86Register::Rbx),
            4 => Some(X86Register::Rsp),
            5 => Some(X86Register::Rbp),
            6 => Some(X86Register::Rsi),
            7 => Some(X86Register::Rdi),
            8 => Some(X86Register::R8),
            9 => Some(X86Register::R9),
            10 => Some(X86Register::R10),
            11 => Some(X86Register::R11),
            12 => Some(X86Register::R12),
            13 => Some(X86Register::R13),
            14 => Some(X86Register::R14),
            15 => Some(X86Register::R15),
            _ => None,
        }
    } else {
        match index {
            0 => Some(X86Register::Eax),
            1 => Some(X86Register::Ecx),
            2 => Some(X86Register::Edx),
            3 => Some(X86Register::Ebx),
            4 => Some(X86Register::Esp),
            5 => Some(X86Register::Ebp),
            6 => Some(X86Register::Esi),
            7 => Some(X86Register::Edi),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analysis::x86::decoder::x86_decode_all;

    #[test]
    fn test_translate_linear_code() {
        // pop eax; add eax, 5; ret
        let bytes = [0x58, 0x83, 0xc0, 0x05, 0xc3];
        let instructions = x86_decode_all(&bytes, 32, 0x1000).unwrap();
        let cfg = X86Function::new(&instructions, 32, 0x1000);

        let translator = X86ToSsaTranslator::new(&cfg);
        let ssa = translator.translate().unwrap();

        // Should have one block
        assert_eq!(ssa.block_count(), 1);

        // Should have instructions
        let block = ssa.block(0).unwrap();
        assert!(!block.instructions().is_empty());

        // Should end with return
        let last_instr = block.instructions().last().unwrap();
        assert!(matches!(last_instr.op(), SsaOp::Return { .. }));
    }

    #[test]
    fn test_translate_with_constant() {
        // mov eax, 0x12345678; ret
        let bytes = [0xb8, 0x78, 0x56, 0x34, 0x12, 0xc3];
        let instructions = x86_decode_all(&bytes, 32, 0x1000).unwrap();
        let cfg = X86Function::new(&instructions, 32, 0x1000);

        let translator = X86ToSsaTranslator::new(&cfg);
        let ssa = translator.translate().unwrap();

        assert_eq!(ssa.block_count(), 1);
    }

    #[test]
    fn test_translate_arithmetic() {
        // pop eax; xor eax, 0x1234; add eax, 5; sub eax, 2; ret
        let bytes = [
            0x58, // pop eax
            0x35, 0x34, 0x12, 0x00, 0x00, // xor eax, 0x1234
            0x83, 0xc0, 0x05, // add eax, 5
            0x83, 0xe8, 0x02, // sub eax, 2
            0xc3, // ret
        ];
        let instructions = x86_decode_all(&bytes, 32, 0x1000).unwrap();
        let cfg = X86Function::new(&instructions, 32, 0x1000);

        let translator = X86ToSsaTranslator::new(&cfg);
        let ssa = translator.translate().unwrap();

        // Should have one block with multiple operations
        let block = ssa.block(0).unwrap();
        let ops: Vec<_> = block.instructions().iter().map(|i| i.op()).collect();

        // Should have Xor, Add, Sub operations
        assert!(ops.iter().any(|op| matches!(op, SsaOp::Xor { .. })));
        assert!(ops.iter().any(|op| matches!(op, SsaOp::Add { .. })));
        assert!(ops.iter().any(|op| matches!(op, SsaOp::Sub { .. })));
    }

    #[test]
    fn test_translate_conditional() {
        // pop eax; cmp eax, 10; jl add_block; jmp skip
        // add_block: add eax, 5
        // skip: ret
        let bytes = [
            0x58, // pop eax
            0x83, 0xf8, 0x0a, // cmp eax, 10
            0x7c, 0x02, // jl +2 (to add)
            0xeb, 0x03, // jmp +3 (to ret)
            0x83, 0xc0, 0x05, // add eax, 5
            0xc3, // ret
        ];
        let instructions = x86_decode_all(&bytes, 32, 0x1000).unwrap();
        let cfg = X86Function::new(&instructions, 32, 0x1000);

        let translator = X86ToSsaTranslator::new(&cfg);
        let ssa = translator.translate().unwrap();

        // Should have multiple blocks
        assert!(ssa.block_count() > 1);

        // First block should have a BranchCmp
        let first_block = ssa.block(0).unwrap();
        let has_branch = first_block
            .instructions()
            .iter()
            .any(|i| matches!(i.op(), SsaOp::BranchCmp { .. }));
        assert!(has_branch);
    }

    #[test]
    fn test_register_state() {
        let mut state = RegisterState::new(32);

        let v1 = SsaVarId::new();
        state.set(X86Register::Eax, v1);
        assert_eq!(state.get(X86Register::Eax), Some(v1));

        // Different size registers map to same base
        assert_eq!(state.get(X86Register::Al), Some(v1));
        assert_eq!(state.get(X86Register::Ax), Some(v1));
    }

    #[test]
    fn test_empty_function() {
        let cfg = X86Function::new(&[], 32, 0);
        let translator = X86ToSsaTranslator::new(&cfg);
        let result = translator.translate();
        assert!(result.is_err());
    }

    #[test]
    fn test_translate_js_after_cmp() {
        // pop eax; cmp eax, 0; js +2; nop; nop; nop; ret
        // JS (0x78) jumps if SF=1 (result is negative)
        let bytes = [
            0x58, // pop eax
            0x83, 0xf8, 0x00, // cmp eax, 0
            0x78, 0x03, // js +3 (skip 3 nops to ret)
            0x90, // nop
            0x90, // nop
            0x90, // nop
            0xc3, // ret
        ];
        let instructions = x86_decode_all(&bytes, 32, 0x1000).unwrap();
        let cfg = X86Function::new(&instructions, 32, 0x1000);

        let translator = X86ToSsaTranslator::new(&cfg);
        let ssa = translator.translate().unwrap();

        // Should compile and produce multiple blocks with BranchCmp
        assert!(ssa.block_count() > 1);
        let first_block = ssa.block(0).unwrap();
        let has_branch = first_block
            .instructions()
            .iter()
            .any(|i| matches!(i.op(), SsaOp::BranchCmp { .. }));
        assert!(has_branch);
    }

    #[test]
    fn test_translate_jns_after_test() {
        // pop eax; test eax, eax; jns +3; nop; nop; nop; ret
        // JNS (0x79) jumps if SF=0 (non-negative)
        let bytes = [
            0x58, // pop eax
            0x85, 0xc0, // test eax, eax
            0x79, 0x03, // jns +3
            0x90, // nop
            0x90, // nop
            0x90, // nop
            0xc3, // ret
        ];
        let instructions = x86_decode_all(&bytes, 32, 0x1000).unwrap();
        let cfg = X86Function::new(&instructions, 32, 0x1000);

        let translator = X86ToSsaTranslator::new(&cfg);
        let ssa = translator.translate().unwrap();

        assert!(ssa.block_count() > 1);
        let first_block = ssa.block(0).unwrap();
        let has_branch = first_block
            .instructions()
            .iter()
            .any(|i| matches!(i.op(), SsaOp::BranchCmp { .. }));
        assert!(has_branch);
    }

    #[test]
    fn test_translate_jo_after_cmp() {
        // pop eax; cmp eax, 0x7FFFFFFF; jo +3; nop; nop; nop; ret
        // JO (0x70) jumps if OF=1 (signed overflow)
        let bytes = [
            0x58, // pop eax
            0x3d, 0xff, 0xff, 0xff, 0x7f, // cmp eax, 0x7FFFFFFF
            0x70, 0x03, // jo +3
            0x90, // nop
            0x90, // nop
            0x90, // nop
            0xc3, // ret
        ];
        let instructions = x86_decode_all(&bytes, 32, 0x1000).unwrap();
        let cfg = X86Function::new(&instructions, 32, 0x1000);

        let translator = X86ToSsaTranslator::new(&cfg);
        let ssa = translator.translate().unwrap();

        assert!(ssa.block_count() > 1);
        let first_block = ssa.block(0).unwrap();
        let has_branch = first_block
            .instructions()
            .iter()
            .any(|i| matches!(i.op(), SsaOp::BranchCmp { .. }));
        assert!(has_branch);
    }

    #[test]
    fn test_translate_jno_after_test() {
        // pop eax; test eax, eax; jno +3; nop; nop; nop; ret
        // JNO (0x71) jumps if OF=0 — always taken after TEST (TEST clears OF)
        let bytes = [
            0x58, // pop eax
            0x85, 0xc0, // test eax, eax
            0x71, 0x03, // jno +3
            0x90, // nop
            0x90, // nop
            0x90, // nop
            0xc3, // ret
        ];
        let instructions = x86_decode_all(&bytes, 32, 0x1000).unwrap();
        let cfg = X86Function::new(&instructions, 32, 0x1000);

        let translator = X86ToSsaTranslator::new(&cfg);
        let ssa = translator.translate().unwrap();

        assert!(ssa.block_count() > 1);
    }

    #[test]
    fn test_translate_jp_after_cmp() {
        // pop eax; cmp eax, 0; jp +3; nop; nop; nop; ret
        // JP (0x7A) jumps if PF=1 (even parity of low byte)
        let bytes = [
            0x58, // pop eax
            0x83, 0xf8, 0x00, // cmp eax, 0
            0x7a, 0x03, // jp +3
            0x90, // nop
            0x90, // nop
            0x90, // nop
            0xc3, // ret
        ];
        let instructions = x86_decode_all(&bytes, 32, 0x1000).unwrap();
        let cfg = X86Function::new(&instructions, 32, 0x1000);

        let translator = X86ToSsaTranslator::new(&cfg);
        let ssa = translator.translate().unwrap();

        assert!(ssa.block_count() > 1);
        let first_block = ssa.block(0).unwrap();
        let has_branch = first_block
            .instructions()
            .iter()
            .any(|i| matches!(i.op(), SsaOp::BranchCmp { .. }));
        assert!(has_branch);
    }

    #[test]
    fn test_translate_jnp_after_test() {
        // pop eax; test eax, eax; jnp +3; nop; nop; nop; ret
        // JNP (0x7B) jumps if PF=0 (odd parity)
        let bytes = [
            0x58, // pop eax
            0x85, 0xc0, // test eax, eax
            0x7b, 0x03, // jnp +3
            0x90, // nop
            0x90, // nop
            0x90, // nop
            0xc3, // ret
        ];
        let instructions = x86_decode_all(&bytes, 32, 0x1000).unwrap();
        let cfg = X86Function::new(&instructions, 32, 0x1000);

        let translator = X86ToSsaTranslator::new(&cfg);
        let ssa = translator.translate().unwrap();

        assert!(ssa.block_count() > 1);
    }

    #[test]
    fn test_translate_js_after_sub() {
        // pop eax; sub eax, 1; js +3; nop; nop; nop; ret
        // JS after SUB: jump if result is negative
        let bytes = [
            0x58, // pop eax
            0x83, 0xe8, 0x01, // sub eax, 1
            0x78, 0x03, // js +3
            0x90, // nop
            0x90, // nop
            0x90, // nop
            0xc3, // ret
        ];
        let instructions = x86_decode_all(&bytes, 32, 0x1000).unwrap();
        let cfg = X86Function::new(&instructions, 32, 0x1000);

        let translator = X86ToSsaTranslator::new(&cfg);
        let ssa = translator.translate().unwrap();

        assert!(ssa.block_count() > 1);
    }

    #[test]
    fn test_translate_jo_after_add() {
        // pop eax; add eax, 0x7FFFFFFF; jo +3; nop; nop; nop; ret
        // JO after ADD: signed overflow detection
        let bytes = [
            0x58, // pop eax
            0x05, 0xff, 0xff, 0xff, 0x7f, // add eax, 0x7FFFFFFF
            0x70, 0x03, // jo +3
            0x90, // nop
            0x90, // nop
            0x90, // nop
            0xc3, // ret
        ];
        let instructions = x86_decode_all(&bytes, 32, 0x1000).unwrap();
        let cfg = X86Function::new(&instructions, 32, 0x1000);

        let translator = X86ToSsaTranslator::new(&cfg);
        let ssa = translator.translate().unwrap();

        assert!(ssa.block_count() > 1);
    }

    #[test]
    fn test_translate_cmovs_after_cmp() {
        // pop eax; pop ecx; cmp eax, 0; cmovs eax, ecx; ret
        // CMOVS: conditional move if sign flag is set
        let bytes = [
            0x58, // pop eax
            0x59, // pop ecx
            0x83, 0xf8, 0x00, // cmp eax, 0
            0x0f, 0x48, 0xc1, // cmovs eax, ecx
            0xc3, // ret
        ];
        let instructions = x86_decode_all(&bytes, 32, 0x1000).unwrap();
        let cfg = X86Function::new(&instructions, 32, 0x1000);

        let translator = X86ToSsaTranslator::new(&cfg);
        let ssa = translator.translate().unwrap();

        // Should have one block with return
        let block = ssa.block(0).unwrap();
        let last = block.instructions().last().unwrap();
        assert!(matches!(last.op(), SsaOp::Return { .. }));
    }

    #[test]
    fn test_translate_seto_after_cmp() {
        // pop eax; cmp eax, 0x7FFFFFFF; seto al; ret
        // SETO: set byte if overflow
        let bytes = [
            0x58, // pop eax
            0x3d, 0xff, 0xff, 0xff, 0x7f, // cmp eax, 0x7FFFFFFF
            0x0f, 0x90, 0xc0, // seto al
            0xc3, // ret
        ];
        let instructions = x86_decode_all(&bytes, 32, 0x1000).unwrap();
        let cfg = X86Function::new(&instructions, 32, 0x1000);

        let translator = X86ToSsaTranslator::new(&cfg);
        let ssa = translator.translate().unwrap();

        // Should have one block with return
        let block = ssa.block(0).unwrap();
        let last = block.instructions().last().unwrap();
        assert!(matches!(last.op(), SsaOp::Return { .. }));
    }
}