llvm-native-core 0.1.15

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

#![allow(dead_code)]

use super::encode_sleb128;
use super::encode_uleb128;

// Re-export DW_OP_* constants for convenience
use super::dwarf_types::dwarf_ops;

// ============================================================================
// DwarfExpression — build and evaluate DWARF expressions
// ============================================================================

/// A builder and evaluator for DWARF location expressions.
///
/// `DwarfExpression` can operate in two modes:
/// - **Location description**: produces a description of where a value lives
///   (in memory, in a register, at a computed address).
/// - **Value description**: produces the value itself on the DWARF stack.
pub type DwarfExpr = DwarfExpression;

/// A builder and evaluator for DWARF location expressions.
///
/// # Example
///
/// ```ignore
/// let mut expr = DwarfExpression::new(8);
/// expr.fbreg(-8);               // DW_OP_fbreg -8
/// expr.deref();                 // DW_OP_deref
/// expr.const_u32(42);           // DW_OP_const4u 42
/// expr.plus();                  // DW_OP_plus
/// expr.stack_value();           // DW_OP_stack_value
/// let bytes = expr.finish();
/// ```
#[derive(Debug, Clone)]
pub struct DwarfExpression {
    /// Output byte stream — the raw DWARF expression bytes.
    pub output: Vec<u8>,
    /// Expression evaluation stack (for constant evaluation).
    stack: Vec<i64>,
    /// Address size in bytes (4 or 8).
    pub address_size: u8,
    /// Whether this expression describes a location (true) or a value (false).
    pub is_location: bool,
}

impl DwarfExpression {
    /// Create a new empty DWARF expression.
    ///
    /// `address_size` is the target address size (4 for 32-bit, 8 for 64-bit).
    /// Defaults to location description mode.
    pub fn new(address_size: u8) -> Self {
        Self {
            output: Vec::new(),
            stack: Vec::new(),
            address_size,
            is_location: true,
        }
    }

    /// Finish building and return the raw byte sequence.
    pub fn finish(self) -> Vec<u8> {
        self.output
    }

    /// Get a reference to the current byte sequence.
    pub fn as_bytes(&self) -> &[u8] {
        &self.output
    }

    /// Return the length of the expression in bytes.
    pub fn len(&self) -> usize {
        self.output.len()
    }

    /// Return true if the expression is empty.
    pub fn is_empty(&self) -> bool {
        self.output.is_empty()
    }

    /// Clear the expression and evaluation stack.
    pub fn clear(&mut self) {
        self.output.clear();
        self.stack.clear();
    }

    // ── Low-level op emission ─────────────────────────────────────────

    /// Emit a single-byte opcode with no operands.
    pub fn add_op(&mut self, op: u8) {
        self.output.push(op);
    }

    /// Emit an opcode followed by a u8 operand.
    pub fn add_op_u8(&mut self, op: u8, val: u8) {
        self.output.push(op);
        self.output.push(val);
    }

    /// Emit an opcode followed by a u16 operand (little-endian).
    pub fn add_op_u16(&mut self, op: u8, val: u16) {
        self.output.push(op);
        self.output.extend_from_slice(&val.to_le_bytes());
    }

    /// Emit an opcode followed by a u32 operand (little-endian).
    pub fn add_op_u32(&mut self, op: u8, val: u32) {
        self.output.push(op);
        self.output.extend_from_slice(&val.to_le_bytes());
    }

    /// Emit an opcode followed by a u64 operand (little-endian).
    pub fn add_op_u64(&mut self, op: u8, val: u64) {
        self.output.push(op);
        self.output.extend_from_slice(&val.to_le_bytes());
    }

    /// Emit an opcode followed by a SLEB128-encoded operand.
    pub fn add_op_sleb(&mut self, op: u8, val: i64) {
        self.output.push(op);
        encode_sleb128(&mut self.output, val);
    }

    /// Emit an opcode followed by a ULEB128-encoded operand.
    pub fn add_op_uleb(&mut self, op: u8, val: u64) {
        self.output.push(op);
        encode_uleb128(&mut self.output, val);
    }

    // ── Address and memory ────────────────────────────────────────────

    /// Push an absolute address: `DW_OP_addr <address>`.
    ///
    /// The address is encoded with `address_size` bytes.
    pub fn addr(&mut self, val: u64) {
        self.output.push(dwarf_ops::DW_OP_addr as u8);
        match self.address_size {
            4 => self.output.extend_from_slice(&(val as u32).to_le_bytes()),
            _ => self.output.extend_from_slice(&val.to_le_bytes()),
        }
    }

    /// Dereference the top of stack: `DW_OP_deref`.
    pub fn deref(&mut self) {
        self.output.push(dwarf_ops::DW_OP_deref as u8);
    }

    /// Dereference `size` bytes from the top of stack: `DW_OP_deref_size <size>`.
    pub fn deref_size(&mut self, size: u8) {
        self.output.push(dwarf_ops::DW_OP_deref_size as u8);
        self.output.push(size);
    }

    /// Push the address of the current object: `DW_OP_push_object_address`.
    pub fn push_object_address(&mut self) {
        self.output.push(dwarf_ops::DW_OP_push_object_address as u8);
    }

    /// Push the thread-local storage address of the top of stack: `DW_OP_form_tls_address`.
    pub fn form_tls_address(&mut self) {
        self.output.push(dwarf_ops::DW_OP_form_tls_address as u8);
    }

    /// Push the Call Frame Address (CFA): `DW_OP_call_frame_cfa`.
    pub fn call_frame_cfa(&mut self) {
        self.output.push(dwarf_ops::DW_OP_call_frame_cfa as u8);
    }

    // ── Constants ─────────────────────────────────────────────────────

    /// Push an unsigned 1-byte constant: `DW_OP_const1u <u8>`.
    pub fn const_u8(&mut self, val: u8) {
        self.add_op_u8(dwarf_ops::DW_OP_const1u as u8, val);
    }

    /// Push an unsigned 2-byte constant: `DW_OP_const2u <u16>`.
    pub fn const_u16(&mut self, val: u16) {
        self.add_op_u16(dwarf_ops::DW_OP_const2u as u8, val);
    }

    /// Push an unsigned 4-byte constant: `DW_OP_const4u <u32>`.
    pub fn const_u32(&mut self, val: u32) {
        self.add_op_u32(dwarf_ops::DW_OP_const4u as u8, val);
    }

    /// Push an unsigned 8-byte constant: `DW_OP_const8u <u64>`.
    pub fn const_u64(&mut self, val: u64) {
        self.add_op_u64(dwarf_ops::DW_OP_const8u as u8, val);
    }

    /// Push a signed 1-byte constant: `DW_OP_const1s <i8>`.
    pub fn const_i8(&mut self, val: i8) {
        self.output.push(dwarf_ops::DW_OP_const1s as u8);
        self.output.push(val as u8);
    }

    /// Push a signed 2-byte constant: `DW_OP_const2s <i16>`.
    pub fn const_i16(&mut self, val: i16) {
        self.output.push(dwarf_ops::DW_OP_const2s as u8);
        self.output.extend_from_slice(&val.to_le_bytes());
    }

    /// Push a signed 4-byte constant: `DW_OP_const4s <i32>`.
    pub fn const_i32(&mut self, val: i32) {
        self.output.push(dwarf_ops::DW_OP_const4s as u8);
        self.output.extend_from_slice(&val.to_le_bytes());
    }

    /// Push a signed 8-byte constant: `DW_OP_const8s <i64>`.
    pub fn const_i64(&mut self, val: i64) {
        self.output.push(dwarf_ops::DW_OP_const8s as u8);
        self.output.extend_from_slice(&val.to_le_bytes());
    }

    /// Push an unsigned LEB128 constant: `DW_OP_constu <ULEB128>`.
    pub fn const_uleb(&mut self, val: u64) {
        self.add_op_uleb(dwarf_ops::DW_OP_constu as u8, val);
    }

    /// Push a signed LEB128 constant: `DW_OP_consts <SLEB128>`.
    pub fn const_sleb(&mut self, val: i64) {
        self.add_op_sleb(dwarf_ops::DW_OP_consts as u8, val);
    }

    /// Push literal 0–31: `DW_OP_lit0 + n`.
    ///
    /// Panics if `n > 31`.
    pub fn lit(&mut self, n: u8) {
        assert!(n <= 31, "DW_OP_lit only supports values 0–31");
        self.output.push(dwarf_ops::DW_OP_lit0 as u8 + n);
    }

    // ── Register operations ───────────────────────────────────────────

    /// Push the contents of a register: `DW_OP_reg0 + reg` or `DW_OP_regx <ULEB128>`.
    ///
    /// Uses compact encoding for registers 0–31, extended encoding otherwise.
    pub fn reg(&mut self, reg: u16) {
        if reg <= 31 {
            self.output.push(dwarf_ops::DW_OP_reg0 as u8 + reg as u8);
        } else {
            self.add_op_uleb(dwarf_ops::DW_OP_regx as u8, reg as u64);
        }
    }

    /// Push the address of register + offset: `DW_OP_breg0 + reg` or `DW_OP_bregx`.
    ///
    /// Uses compact encoding for registers 0–31, extended encoding otherwise.
    pub fn breg(&mut self, reg: u16, offset: i64) {
        if reg <= 31 {
            self.output.push(dwarf_ops::DW_OP_breg0 as u8 + reg as u8);
        } else {
            self.output.push(dwarf_ops::DW_OP_bregx as u8);
            encode_uleb128(&mut self.output, reg as u64);
        }
        encode_sleb128(&mut self.output, offset);
    }

    /// Push the frame base register + offset: `DW_OP_fbreg <SLEB128>`.
    pub fn fbreg(&mut self, offset: i64) {
        self.add_op_sleb(dwarf_ops::DW_OP_fbreg as u8, offset);
    }

    // ── Arithmetic operations ─────────────────────────────────────────

    /// Pop two values, push their sum: `DW_OP_plus`.
    pub fn plus(&mut self) {
        self.output.push(dwarf_ops::DW_OP_plus as u8);
    }

    /// Pop two values, push (tos-1 - tos): `DW_OP_minus`.
    pub fn minus(&mut self) {
        self.output.push(dwarf_ops::DW_OP_minus as u8);
    }

    /// Pop two values, push their product: `DW_OP_mul`.
    pub fn mul(&mut self) {
        self.output.push(dwarf_ops::DW_OP_mul as u8);
    }

    /// Pop two values, push (tos-1 / tos): `DW_OP_div`.
    pub fn div(&mut self) {
        self.output.push(dwarf_ops::DW_OP_div as u8);
    }

    /// Pop two values, push (tos-1 % tos): `DW_OP_mod`.
    pub fn mod_(&mut self) {
        self.output.push(dwarf_ops::DW_OP_mod as u8);
    }

    /// Pop one value, push its absolute value: `DW_OP_abs`.
    pub fn abs(&mut self) {
        self.output.push(dwarf_ops::DW_OP_abs as u8);
    }

    /// Pop one value, push its negation: `DW_OP_neg`.
    pub fn neg(&mut self) {
        self.output.push(dwarf_ops::DW_OP_neg as u8);
    }

    /// Pop one value, push its bitwise NOT: `DW_OP_not`.
    pub fn not(&mut self) {
        self.output.push(dwarf_ops::DW_OP_not as u8);
    }

    /// Pop two values, push their bitwise AND: `DW_OP_and`.
    pub fn and(&mut self) {
        self.output.push(dwarf_ops::DW_OP_and as u8);
    }

    /// Pop two values, push their bitwise OR: `DW_OP_or`.
    pub fn or(&mut self) {
        self.output.push(dwarf_ops::DW_OP_or as u8);
    }

    /// Pop two values, push their bitwise XOR: `DW_OP_xor`.
    pub fn xor(&mut self) {
        self.output.push(dwarf_ops::DW_OP_xor as u8);
    }

    /// Pop one value, push it left-shifted by 1: `DW_OP_shl`.
    pub fn shl(&mut self) {
        self.output.push(dwarf_ops::DW_OP_shl as u8);
    }

    /// Pop one value, push it right-shifted (logical) by 1: `DW_OP_shr`.
    pub fn shr(&mut self) {
        self.output.push(dwarf_ops::DW_OP_shr as u8);
    }

    /// Pop one value, push it right-shifted (arithmetic) by 1: `DW_OP_shra`.
    pub fn shra(&mut self) {
        self.output.push(dwarf_ops::DW_OP_shra as u8);
    }

    // ── Comparison operations ─────────────────────────────────────────

    /// Pop two values, push (tos-1 == tos): `DW_OP_eq`.
    pub fn eq(&mut self) {
        self.output.push(dwarf_ops::DW_OP_eq as u8);
    }

    /// Pop two values, push (tos-1 != tos): `DW_OP_ne`.
    pub fn ne(&mut self) {
        self.output.push(dwarf_ops::DW_OP_ne as u8);
    }

    /// Pop two values, push (tos-1 < tos): `DW_OP_lt`.
    pub fn lt(&mut self) {
        self.output.push(dwarf_ops::DW_OP_lt as u8);
    }

    /// Pop two values, push (tos-1 <= tos): `DW_OP_le`.
    pub fn le(&mut self) {
        self.output.push(dwarf_ops::DW_OP_le as u8);
    }

    /// Pop two values, push (tos-1 > tos): `DW_OP_gt`.
    pub fn gt(&mut self) {
        self.output.push(dwarf_ops::DW_OP_gt as u8);
    }

    /// Pop two values, push (tos-1 >= tos): `DW_OP_ge`.
    pub fn ge(&mut self) {
        self.output.push(dwarf_ops::DW_OP_ge as u8);
    }

    // ── Stack manipulation ────────────────────────────────────────────

    /// Duplicate the top of stack: `DW_OP_dup`.
    pub fn dup(&mut self) {
        self.output.push(dwarf_ops::DW_OP_dup as u8);
    }

    /// Drop the top of stack: `DW_OP_drop`.
    pub fn drop(&mut self) {
        self.output.push(dwarf_ops::DW_OP_drop as u8);
    }

    /// Swap the top two stack elements: `DW_OP_swap`.
    pub fn swap(&mut self) {
        self.output.push(dwarf_ops::DW_OP_swap as u8);
    }

    /// Duplicate the second-from-top onto top: `DW_OP_over`.
    pub fn over(&mut self) {
        self.output.push(dwarf_ops::DW_OP_over as u8);
    }

    /// Pick the n-th stack element (0-based from top) and push it: `DW_OP_pick <u8>`.
    pub fn pick(&mut self, n: u8) {
        self.add_op_u8(dwarf_ops::DW_OP_pick as u8, n);
    }

    /// Rotate the top three stack elements: `DW_OP_rot`.
    pub fn rot(&mut self) {
        self.output.push(dwarf_ops::DW_OP_rot as u8);
    }

    // ── Control flow ──────────────────────────────────────────────────

    /// Unconditional skip: `DW_OP_skip <i16>`.
    ///
    /// `offset` is the number of bytes to skip from after the skip instruction.
    /// A negative offset skips backward.
    pub fn skip(&mut self, offset: i16) {
        self.add_op_u16(dwarf_ops::DW_OP_skip as u8, offset as u16);
    }

    /// Conditional branch: `DW_OP_bra <i16>`.
    ///
    /// Pops the top of stack; if non-zero, skips `offset` bytes.
    pub fn bra(&mut self, offset: i16) {
        self.add_op_u16(dwarf_ops::DW_OP_bra as u8, offset as u16);
    }

    /// No operation: `DW_OP_nop`.
    pub fn nop(&mut self) {
        self.output.push(dwarf_ops::DW_OP_nop as u8);
    }

    // ── Piece/composite operations ────────────────────────────────────

    /// Pop value from stack; the value occupies `size` bytes of the
    /// object: `DW_OP_piece <ULEB128>`.
    pub fn piece(&mut self, size: u64) {
        self.add_op_uleb(dwarf_ops::DW_OP_piece as u8, size);
    }

    /// Pop value; the value occupies `size` bits starting at `offset` bits
    /// into the object: `DW_OP_bit_piece <ULEB128 size> <ULEB128 offset>`.
    pub fn bit_piece(&mut self, size: u64, offset: u64) {
        self.output.push(dwarf_ops::DW_OP_bit_piece as u8);
        encode_uleb128(&mut self.output, size);
        encode_uleb128(&mut self.output, offset);
    }

    /// Mark the top of stack as a value (not a location): `DW_OP_stack_value`.
    pub fn stack_value(&mut self) {
        self.output.push(dwarf_ops::DW_OP_stack_value as u8);
        self.is_location = false;
    }

    // ── Complex operations ────────────────────────────────────────────

    /// Push the value that the location description in `expr` evaluates to
    /// in the calling frame: `DW_OP_entry_value <ULEB128 len> <expr>`.
    pub fn entry_value(&mut self, expr: &[u8]) {
        self.output.push(dwarf_ops::DW_OP_entry_value as u8);
        encode_uleb128(&mut self.output, expr.len() as u64);
        self.output.extend_from_slice(expr);
    }

    /// Push an implicit (inline) value: `DW_OP_implicit_value <ULEB128 len> <data>`.
    pub fn implicit_value(&mut self, value: &[u8]) {
        self.output.push(dwarf_ops::DW_OP_implicit_value as u8);
        encode_uleb128(&mut self.output, value.len() as u64);
        self.output.extend_from_slice(value);
    }

    /// Convert the top of stack to the given type (DWARF5):
    /// `DW_OP_convert <ULEB128 DIE offset of type>`.
    pub fn convert(&mut self, dwarf_type: u64) {
        self.output.push(dwarf_ops::DW_OP_convert as u8);
        encode_uleb128(&mut self.output, dwarf_type);
    }

    /// Reinterpret the top of stack as the given type (DWARF5):
    /// `DW_OP_reinterpret <ULEB128 DIE offset of type>`.
    pub fn reinterpret(&mut self, dwarf_type: u64) {
        self.output.push(dwarf_ops::DW_OP_reinterpret as u8);
        encode_uleb128(&mut self.output, dwarf_type);
    }

    /// Add an unsigned constant to the top of stack: `DW_OP_plus_uconst <ULEB128>`.
    pub fn plus_uconst(&mut self, val: u64) {
        self.add_op_uleb(dwarf_ops::DW_OP_plus_uconst as u8, val);
    }

    /// Push the value at an address in the `.debug_addr` section:
    /// `DW_OP_addrx <ULEB128 index>`.
    pub fn addrx(&mut self, index: u64) {
        self.add_op_uleb(dwarf_ops::DW_OP_addrx as u8, index);
    }

    /// Push a constant from the `.debug_addr` section:
    /// `DW_OP_constx <ULEB128 index>`.
    pub fn constx(&mut self, index: u64) {
        self.add_op_uleb(dwarf_ops::DW_OP_constx as u8, index);
    }

    // ── Expression evaluation (constant expressions only) ─────────────

    /// Evaluate a constant expression that contains no register reads,
    /// no memory accesses, and no control flow.
    ///
    /// Returns `None` if the expression cannot be evaluated as a constant
    /// (contains unsupported operations, register references, etc.).
    ///
    /// # Supported operations
    ///
    /// - Constants: `DW_OP_const1u/s`, `DW_OP_const2u/s`, `DW_OP_const4u/s`,
    ///   `DW_OP_const8u/s`, `DW_OP_constu`, `DW_OP_consts`, `DW_OP_lit0..31`
    /// - Arithmetic: `DW_OP_plus`, `DW_OP_minus`, `DW_OP_mul`, `DW_OP_div`,
    ///   `DW_OP_mod`, `DW_OP_neg`, `DW_OP_abs`, `DW_OP_not`, `DW_OP_and`,
    ///   `DW_OP_or`, `DW_OP_xor`
    /// - Stack: `DW_OP_dup`, `DW_OP_drop`, `DW_OP_swap`, `DW_OP_over`,
    ///   `DW_OP_pick`, `DW_OP_rot`
    /// - Comparison: all comparison ops
    pub fn evaluate_const(&self) -> Option<i64> {
        if self.output.is_empty() {
            return None;
        }

        let mut stack: Vec<i64> = Vec::new();
        let mut pos = 0;
        let data = &self.output;

        while pos < data.len() {
            let op = data[pos];
            pos += 1;

            match op {
                // ── Literals ──────────────────────────────────────
                o if o >= dwarf_ops::DW_OP_lit0 && o <= dwarf_ops::DW_OP_lit0 + 31 => {
                    stack.push((o - dwarf_ops::DW_OP_lit0) as i64);
                }

                // ── Constants unsigned ────────────────────────────
                dwarf_ops::DW_OP_const1u => {
                    if pos >= data.len() {
                        return None;
                    }
                    stack.push(data[pos] as i64);
                    pos += 1;
                }
                dwarf_ops::DW_OP_const2u => {
                    if pos + 2 > data.len() {
                        return None;
                    }
                    let v = u16::from_le_bytes(data[pos..pos + 2].try_into().ok()?);
                    stack.push(v as i64);
                    pos += 2;
                }
                dwarf_ops::DW_OP_const4u => {
                    if pos + 4 > data.len() {
                        return None;
                    }
                    let v = u32::from_le_bytes(data[pos..pos + 4].try_into().ok()?);
                    stack.push(v as i64);
                    pos += 4;
                }
                dwarf_ops::DW_OP_const8u => {
                    if pos + 8 > data.len() {
                        return None;
                    }
                    let v = u64::from_le_bytes(data[pos..pos + 8].try_into().ok()?);
                    stack.push(v as i64);
                    pos += 8;
                }

                // ── Constants signed ──────────────────────────────
                dwarf_ops::DW_OP_const1s => {
                    if pos >= data.len() {
                        return None;
                    }
                    stack.push(data[pos] as i8 as i64);
                    pos += 1;
                }
                dwarf_ops::DW_OP_const2s => {
                    if pos + 2 > data.len() {
                        return None;
                    }
                    let v = i16::from_le_bytes(data[pos..pos + 2].try_into().ok()?);
                    stack.push(v as i64);
                    pos += 2;
                }
                dwarf_ops::DW_OP_const4s => {
                    if pos + 4 > data.len() {
                        return None;
                    }
                    let v = i32::from_le_bytes(data[pos..pos + 4].try_into().ok()?);
                    stack.push(v as i64);
                    pos += 4;
                }
                dwarf_ops::DW_OP_const8s => {
                    if pos + 8 > data.len() {
                        return None;
                    }
                    let v = i64::from_le_bytes(data[pos..pos + 8].try_into().ok()?);
                    stack.push(v);
                    pos += 8;
                }

                // ── LEB128 constants ──────────────────────────────
                dwarf_ops::DW_OP_constu => {
                    let (v, advance) = try_decode_uleb128(&data[pos..])?;
                    stack.push(v as i64);
                    pos += advance;
                }
                dwarf_ops::DW_OP_consts => {
                    let (v, advance) = try_decode_sleb128(&data[pos..])?;
                    stack.push(v);
                    pos += advance;
                }

                // ── Arithmetic ────────────────────────────────────
                dwarf_ops::DW_OP_plus => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    stack.push(a.wrapping_add(b));
                }
                dwarf_ops::DW_OP_minus => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    stack.push(a.wrapping_sub(b));
                }
                dwarf_ops::DW_OP_mul => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    stack.push(a.wrapping_mul(b));
                }
                dwarf_ops::DW_OP_div => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    if b == 0 {
                        return None;
                    }
                    stack.push(a.wrapping_div(b));
                }
                dwarf_ops::DW_OP_mod => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    if b == 0 {
                        return None;
                    }
                    stack.push(a.wrapping_rem(b));
                }
                dwarf_ops::DW_OP_neg => {
                    let a = stack.pop()?;
                    stack.push(-a);
                }
                dwarf_ops::DW_OP_abs => {
                    let a = stack.pop()?;
                    stack.push(a.abs());
                }
                dwarf_ops::DW_OP_not => {
                    let a = stack.pop()?;
                    stack.push(!a);
                }
                dwarf_ops::DW_OP_and => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    stack.push(a & b);
                }
                dwarf_ops::DW_OP_or => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    stack.push(a | b);
                }
                dwarf_ops::DW_OP_xor => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    stack.push(a ^ b);
                }
                dwarf_ops::DW_OP_shl => {
                    let a = stack.pop()?;
                    stack.push(a << 1);
                }
                dwarf_ops::DW_OP_shr => {
                    let a = stack.pop()?;
                    stack.push((a as u64 >> 1) as i64);
                }
                dwarf_ops::DW_OP_shra => {
                    let a = stack.pop()?;
                    stack.push(a >> 1);
                }

                // ── Comparison ────────────────────────────────────
                dwarf_ops::DW_OP_eq => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    stack.push(if a == b { 1 } else { 0 });
                }
                dwarf_ops::DW_OP_ne => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    stack.push(if a != b { 1 } else { 0 });
                }
                dwarf_ops::DW_OP_lt => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    stack.push(if a < b { 1 } else { 0 });
                }
                dwarf_ops::DW_OP_le => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    stack.push(if a <= b { 1 } else { 0 });
                }
                dwarf_ops::DW_OP_gt => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    stack.push(if a > b { 1 } else { 0 });
                }
                dwarf_ops::DW_OP_ge => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    stack.push(if a >= b { 1 } else { 0 });
                }

                // ── Stack ops ─────────────────────────────────────
                dwarf_ops::DW_OP_dup => {
                    let a = *stack.last()?;
                    stack.push(a);
                }
                dwarf_ops::DW_OP_drop => {
                    stack.pop()?;
                }
                dwarf_ops::DW_OP_swap => {
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    stack.push(b);
                    stack.push(a);
                }
                dwarf_ops::DW_OP_over => {
                    if stack.len() < 2 {
                        return None;
                    }
                    let a = stack[stack.len() - 2];
                    stack.push(a);
                }
                dwarf_ops::DW_OP_pick => {
                    if pos >= data.len() {
                        return None;
                    }
                    let n = data[pos] as usize;
                    pos += 1;
                    if stack.len() <= n {
                        return None;
                    }
                    let v = stack[stack.len() - 1 - n];
                    stack.push(v);
                }
                dwarf_ops::DW_OP_rot => {
                    let c = stack.pop()?;
                    let b = stack.pop()?;
                    let a = stack.pop()?;
                    stack.push(b);
                    stack.push(c);
                    stack.push(a);
                }

                // ── Unsupported in constant evaluation ────────────
                dwarf_ops::DW_OP_nop => {
                    // No operation, skip
                }

                // Anything else (registers, memory, address, etc.) is not constant
                _ => return None,
            }
        }

        // Return top of stack if there's exactly one value
        if stack.len() == 1 {
            Some(stack[0])
        } else {
            None
        }
    }

    /// Check if this expression is a simple register location.
    ///
    /// A register location is either:
    /// - `DW_OP_reg0..DW_OP_reg31` (single-byte opcode)
    /// - `DW_OP_regx <ULEB128 register>` (extended register)
    ///
    /// Returns `Some(register_number)` if it is a simple register location,
    /// `None` otherwise.
    pub fn is_register_location(&self) -> Option<u16> {
        if self.output.is_empty() {
            return None;
        }
        let op = self.output[0];
        if op >= dwarf_ops::DW_OP_reg0 && op <= dwarf_ops::DW_OP_reg0 + 31 {
            return Some((op - dwarf_ops::DW_OP_reg0) as u16);
        }
        if op == dwarf_ops::DW_OP_regx {
            if self.output.len() < 2 {
                return None;
            }
            let (reg, _) = try_decode_uleb128(&self.output[1..])?;
            return Some(reg as u16);
        }
        None
    }

    /// Check if this expression describes a frame-base-relative location.
    ///
    /// A typical frame-relative location is:
    /// - `DW_OP_fbreg <SLEB128 offset>` — location at frame_base + offset
    /// - Optionally followed by `DW_OP_deref` — value at that address
    ///
    /// Returns `Some((offset, size))` if the expression is a simple
    /// frame-relative location, where `size` is the dereference size
    /// (0 if the expression is the address itself).
    pub fn is_frame_relative(&self) -> Option<(i64, u64)> {
        if self.output.is_empty() {
            return None;
        }
        if self.output[0] != dwarf_ops::DW_OP_fbreg {
            return None;
        }
        let (offset, advance) = try_decode_sleb128(&self.output[1..])?;
        let after_fbreg = 1 + advance;

        // Check if followed by DW_OP_deref or DW_OP_deref_size
        if after_fbreg < self.output.len() {
            let next_op = self.output[after_fbreg];
            if next_op == dwarf_ops::DW_OP_deref {
                return Some((offset, 0)); // size 0 indicates unknown/implicit
            }
            if next_op == dwarf_ops::DW_OP_deref_size && after_fbreg + 1 < self.output.len() {
                let size = self.output[after_fbreg + 1] as u64;
                return Some((offset, size));
            }
        }

        // Just the address (fbreg without deref)
        Some((offset, 0))
    }
}

// ============================================================================
// Helper functions
// ============================================================================

/// Try to decode a ULEB128 value from a byte slice.
///
/// Returns `Some((value, bytes_consumed))` on success, `None` if the encoding
/// is incomplete or invalid.
fn try_decode_uleb128(data: &[u8]) -> Option<(u64, usize)> {
    let mut result: u64 = 0;
    let mut shift = 0;
    for (i, &byte) in data.iter().enumerate() {
        if i >= 10 {
            // ULEB128 should not exceed 10 bytes for u64
            return None;
        }
        result |= ((byte & 0x7F) as u64) << shift;
        if byte & 0x80 == 0 {
            return Some((result, i + 1));
        }
        shift += 7;
    }
    None
}

/// Try to decode a SLEB128 value from a byte slice.
fn try_decode_sleb128(data: &[u8]) -> Option<(i64, usize)> {
    let mut result: i64 = 0;
    let mut shift = 0;
    for (i, &byte) in data.iter().enumerate() {
        if i >= 10 {
            return None;
        }
        result |= ((byte & 0x7F) as i64) << shift;
        shift += 7;
        if byte & 0x80 == 0 {
            // Sign extend if the high bit of the last byte is set
            if shift < 64 && (byte & 0x40) != 0 {
                result |= (-1i64) << shift;
            }
            return Some((result, i + 1));
        }
    }
    None
}

/// Create a simple register location expression: `DW_OP_reg<n>` or `DW_OP_regx`.
///
/// This produces a minimal DWARF expression that says "the value is in register N".
pub fn make_reg_expr(reg: u16) -> Vec<u8> {
    let mut expr = DwarfExpression::new(8);
    expr.reg(reg);
    expr.finish()
}

/// Create a frame-base-relative location expression: `DW_OP_fbreg <offset>`.
///
/// This produces a DWARF expression that says "the value is at frame_base + offset".
pub fn make_fbreg_expr(offset: i64) -> Vec<u8> {
    let mut expr = DwarfExpression::new(8);
    expr.fbreg(offset);
    expr.finish()
}

/// Create a frame-base-relative dereferenced expression:
/// `DW_OP_fbreg <offset>; DW_OP_deref`.
pub fn make_fbreg_deref_expr(offset: i64) -> Vec<u8> {
    let mut expr = DwarfExpression::new(8);
    expr.fbreg(offset);
    expr.deref();
    expr.finish()
}

/// Create an expression that pushes a stack value:
/// `DW_OP_lit<n>` or `DW_OP_const<N>` + `DW_OP_stack_value`.
pub fn make_const_expr(value: i64) -> Vec<u8> {
    let mut expr = DwarfExpression::new(8);
    if value >= 0 && value <= 31 {
        expr.lit(value as u8);
    } else if value >= 0 && value <= 255 {
        expr.const_u8(value as u8);
    } else if value >= -128 && value <= 127 {
        expr.const_i8(value as i8);
    } else if value >= 0 && value <= 65535 {
        expr.const_u16(value as u16);
    } else {
        expr.const_sleb(value);
    }
    expr.stack_value();
    expr.finish()
}

// ============================================================================
// Tests
// ============================================================================

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

    // ── Basic creation tests ──────────────────────────────────────────

    #[test]
    fn test_new_expression() {
        let expr = DwarfExpression::new(8);
        assert!(expr.output.is_empty());
        assert_eq!(expr.address_size, 8);
        assert!(expr.is_location);
        assert!(expr.is_empty());
        assert_eq!(expr.len(), 0);
    }

    #[test]
    fn test_new_expression_32bit() {
        let expr = DwarfExpression::new(4);
        assert_eq!(expr.address_size, 4);
    }

    #[test]
    fn test_finish_and_clear() {
        let mut expr = DwarfExpression::new(8);
        expr.nop();
        assert_eq!(expr.len(), 1);
        let bytes = expr.clone().finish();
        assert_eq!(bytes.len(), 1);
        expr.clear();
        assert!(expr.is_empty());
    }

    // ── Opcode emission tests ─────────────────────────────────────────

    #[test]
    fn test_add_op() {
        let mut expr = DwarfExpression::new(8);
        expr.add_op(0x50);
        assert_eq!(expr.output, vec![0x50]);
    }

    #[test]
    fn test_add_op_u8() {
        let mut expr = DwarfExpression::new(8);
        expr.add_op_u8(0x08, 42);
        assert_eq!(expr.output, vec![0x08, 42]);
    }

    #[test]
    fn test_add_op_u16() {
        let mut expr = DwarfExpression::new(8);
        expr.add_op_u16(0x02, 0x1234);
        assert_eq!(expr.output.len(), 3);
        assert_eq!(expr.output[0], 0x02);
    }

    #[test]
    fn test_add_op_u32() {
        let mut expr = DwarfExpression::new(8);
        expr.add_op_u32(0x03, 0xDEADBEEF);
        assert_eq!(expr.output.len(), 5);
        assert_eq!(expr.output[0], 0x03);
    }

    #[test]
    fn test_add_op_u64() {
        let mut expr = DwarfExpression::new(8);
        expr.add_op_u64(0x04, 0x1234567890ABCDEF);
        assert_eq!(expr.output.len(), 9);
        assert_eq!(expr.output[0], 0x04);
    }

    // ── Address tests ─────────────────────────────────────────────────

    #[test]
    fn test_addr_64bit() {
        let mut expr = DwarfExpression::new(8);
        expr.addr(0x400000);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_addr as u8);
        assert_eq!(expr.output.len(), 9); // op + 8 bytes
        let addr = u64::from_le_bytes(expr.output[1..9].try_into().unwrap());
        assert_eq!(addr, 0x400000);
    }

    #[test]
    fn test_addr_32bit() {
        let mut expr = DwarfExpression::new(4);
        expr.addr(0x4000);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_addr as u8);
        assert_eq!(expr.output.len(), 5); // op + 4 bytes
    }

    #[test]
    fn test_deref() {
        let mut expr = DwarfExpression::new(8);
        expr.deref();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_deref as u8);
    }

    #[test]
    fn test_deref_size() {
        let mut expr = DwarfExpression::new(8);
        expr.deref_size(8);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_deref_size as u8);
        assert_eq!(expr.output[1], 8);
    }

    #[test]
    fn test_push_object_address() {
        let mut expr = DwarfExpression::new(8);
        expr.push_object_address();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_push_object_address as u8);
    }

    #[test]
    fn test_form_tls_address() {
        let mut expr = DwarfExpression::new(8);
        expr.form_tls_address();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_form_tls_address as u8);
    }

    #[test]
    fn test_call_frame_cfa() {
        let mut expr = DwarfExpression::new(8);
        expr.call_frame_cfa();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_call_frame_cfa as u8);
    }

    // ── Constant tests ────────────────────────────────────────────────

    #[test]
    fn test_const_u8() {
        let mut expr = DwarfExpression::new(8);
        expr.const_u8(42);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_const1u as u8);
        assert_eq!(expr.output[1], 42);
    }

    #[test]
    fn test_const_u16() {
        let mut expr = DwarfExpression::new(8);
        expr.const_u16(0x1234);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_const2u as u8);
    }

    #[test]
    fn test_const_u32() {
        let mut expr = DwarfExpression::new(8);
        expr.const_u32(0xDEADBEEF);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_const4u as u8);
    }

    #[test]
    fn test_const_u64() {
        let mut expr = DwarfExpression::new(8);
        expr.const_u64(0xFFFFFFFF);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_const8u as u8);
    }

    #[test]
    fn test_const_i8() {
        let mut expr = DwarfExpression::new(8);
        expr.const_i8(-42);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_const1s as u8);
        assert_eq!(expr.output[1] as i8, -42);
    }

    #[test]
    fn test_const_uleb() {
        let mut expr = DwarfExpression::new(8);
        expr.const_uleb(127);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_constu as u8);
        assert_eq!(expr.output[1], 127);
    }

    #[test]
    fn test_const_sleb() {
        let mut expr = DwarfExpression::new(8);
        expr.const_sleb(-1);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_consts as u8);
        assert_eq!(expr.output[1], 0x7F);
    }

    #[test]
    fn test_lit() {
        for n in 0..=31 {
            let mut expr = DwarfExpression::new(8);
            expr.lit(n);
            assert_eq!(expr.output[0], dwarf_ops::DW_OP_lit0 as u8 + n);
        }
    }

    #[test]
    #[should_panic]
    fn test_lit_too_large() {
        let mut expr = DwarfExpression::new(8);
        expr.lit(32);
    }

    // ── Register tests ────────────────────────────────────────────────

    #[test]
    fn test_reg_compact() {
        let mut expr = DwarfExpression::new(8);
        expr.reg(5);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_reg0 as u8 + 5);
    }

    #[test]
    fn test_reg_extended() {
        let mut expr = DwarfExpression::new(8);
        expr.reg(32);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_regx as u8);
    }

    #[test]
    fn test_breg_compact() {
        let mut expr = DwarfExpression::new(8);
        expr.breg(7, -8);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_breg0 as u8 + 7);
    }

    #[test]
    fn test_breg_extended() {
        let mut expr = DwarfExpression::new(8);
        expr.breg(64, 0);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_bregx as u8);
    }

    #[test]
    fn test_fbreg() {
        let mut expr = DwarfExpression::new(8);
        expr.fbreg(-16);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_fbreg as u8);
    }

    // ── Arithmetic tests ──────────────────────────────────────────────

    #[test]
    fn test_plus() {
        let mut expr = DwarfExpression::new(8);
        expr.plus();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_plus as u8);
    }

    #[test]
    fn test_minus() {
        let mut expr = DwarfExpression::new(8);
        expr.minus();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_minus as u8);
    }

    #[test]
    fn test_mul() {
        let mut expr = DwarfExpression::new(8);
        expr.mul();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_mul as u8);
    }

    #[test]
    fn test_div() {
        let mut expr = DwarfExpression::new(8);
        expr.div();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_div as u8);
    }

    #[test]
    fn test_mod() {
        let mut expr = DwarfExpression::new(8);
        expr.mod_();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_mod as u8);
    }

    #[test]
    fn test_neg_abs_not() {
        let mut expr = DwarfExpression::new(8);
        expr.neg();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_neg as u8);

        let mut expr = DwarfExpression::new(8);
        expr.abs();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_abs as u8);

        let mut expr = DwarfExpression::new(8);
        expr.not();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_not as u8);
    }

    #[test]
    fn test_bitwise() {
        let mut expr = DwarfExpression::new(8);
        expr.and();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_and as u8);

        let mut expr = DwarfExpression::new(8);
        expr.or();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_or as u8);

        let mut expr = DwarfExpression::new(8);
        expr.xor();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_xor as u8);
    }

    #[test]
    fn test_shifts() {
        let mut expr = DwarfExpression::new(8);
        expr.shl();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_shl as u8);

        let mut expr = DwarfExpression::new(8);
        expr.shr();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_shr as u8);

        let mut expr = DwarfExpression::new(8);
        expr.shra();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_shra as u8);
    }

    // ── Comparison tests ──────────────────────────────────────────────

    #[test]
    fn test_comparisons() {
        let mut expr = DwarfExpression::new(8);
        expr.eq();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_eq as u8);

        let mut expr = DwarfExpression::new(8);
        expr.ne();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_ne as u8);

        let mut expr = DwarfExpression::new(8);
        expr.lt();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_lt as u8);

        let mut expr = DwarfExpression::new(8);
        expr.le();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_le as u8);

        let mut expr = DwarfExpression::new(8);
        expr.gt();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_gt as u8);

        let mut expr = DwarfExpression::new(8);
        expr.ge();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_ge as u8);
    }

    // ── Stack manipulation tests ──────────────────────────────────────

    #[test]
    fn test_stack_ops() {
        let mut expr = DwarfExpression::new(8);
        expr.dup();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_dup as u8);

        let mut expr = DwarfExpression::new(8);
        expr.drop();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_drop as u8);

        let mut expr = DwarfExpression::new(8);
        expr.swap();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_swap as u8);

        let mut expr = DwarfExpression::new(8);
        expr.over();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_over as u8);

        let mut expr = DwarfExpression::new(8);
        expr.pick(3);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_pick as u8);
        assert_eq!(expr.output[1], 3);

        let mut expr = DwarfExpression::new(8);
        expr.rot();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_rot as u8);
    }

    // ── Control flow tests ────────────────────────────────────────────

    #[test]
    fn test_skip() {
        let mut expr = DwarfExpression::new(8);
        expr.skip(10);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_skip as u8);
    }

    #[test]
    fn test_bra() {
        let mut expr = DwarfExpression::new(8);
        expr.bra(-5);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_bra as u8);
    }

    #[test]
    fn test_nop() {
        let mut expr = DwarfExpression::new(8);
        expr.nop();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_nop as u8);
    }

    // ── Piece tests ───────────────────────────────────────────────────

    #[test]
    fn test_piece() {
        let mut expr = DwarfExpression::new(8);
        expr.piece(8);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_piece as u8);
    }

    #[test]
    fn test_bit_piece() {
        let mut expr = DwarfExpression::new(8);
        expr.bit_piece(32, 0);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_bit_piece as u8);
    }

    #[test]
    fn test_stack_value() {
        let mut expr = DwarfExpression::new(8);
        expr.stack_value();
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_stack_value as u8);
        assert!(!expr.is_location);
    }

    // ── Complex operations ────────────────────────────────────────────

    #[test]
    fn test_entry_value() {
        let mut expr = DwarfExpression::new(8);
        expr.entry_value(&[0x50, 0x30]); // DW_OP_reg0, DW_OP_lit0
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_entry_value as u8);
    }

    #[test]
    fn test_implicit_value() {
        let mut expr = DwarfExpression::new(8);
        expr.implicit_value(&[0x42, 0x00, 0x00, 0x00]);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_implicit_value as u8);
    }

    #[test]
    fn test_convert() {
        let mut expr = DwarfExpression::new(8);
        expr.convert(0x100);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_convert as u8);
    }

    #[test]
    fn test_reinterpret() {
        let mut expr = DwarfExpression::new(8);
        expr.reinterpret(0x200);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_reinterpret as u8);
    }

    #[test]
    fn test_plus_uconst() {
        let mut expr = DwarfExpression::new(8);
        expr.plus_uconst(16);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_plus_uconst as u8);
    }

    #[test]
    fn test_addrx() {
        let mut expr = DwarfExpression::new(8);
        expr.addrx(3);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_addrx as u8);
    }

    #[test]
    fn test_constx() {
        let mut expr = DwarfExpression::new(8);
        expr.constx(1);
        assert_eq!(expr.output[0], dwarf_ops::DW_OP_constx as u8);
    }

    // ── Constant evaluation tests ─────────────────────────────────────

    #[test]
    fn test_evaluate_const_lit() {
        let mut expr = DwarfExpression::new(8);
        expr.lit(5);
        let result = expr.evaluate_const();
        assert_eq!(result, Some(5));
    }

    #[test]
    fn test_evaluate_const_constu() {
        let mut expr = DwarfExpression::new(8);
        expr.const_uleb(100);
        let result = expr.evaluate_const();
        assert_eq!(result, Some(100));
    }

    #[test]
    fn test_evaluate_const_plus() {
        let mut expr = DwarfExpression::new(8);
        expr.lit(3);
        expr.lit(4);
        expr.plus();
        let result = expr.evaluate_const();
        assert_eq!(result, Some(7));
    }

    #[test]
    fn test_evaluate_const_complex() {
        let mut expr = DwarfExpression::new(8);
        expr.lit(10); // push 10
        expr.lit(3); // push 3
        expr.mul(); // 10 * 3 = 30
        expr.lit(5); // push 5
        expr.plus(); // 30 + 5 = 35
        let result = expr.evaluate_const();
        assert_eq!(result, Some(35));
    }

    #[test]
    fn test_evaluate_const_stack_ops() {
        let mut expr = DwarfExpression::new(8);
        expr.lit(10);
        expr.dup(); // 10, 10
        expr.plus(); // 20
        let result = expr.evaluate_const();
        assert_eq!(result, Some(20));
    }

    #[test]
    fn test_evaluate_const_drop() {
        let mut expr = DwarfExpression::new(8);
        expr.lit(1);
        expr.lit(2);
        expr.drop(); // drop 2, leave 1
        let result = expr.evaluate_const();
        assert_eq!(result, Some(1));
    }

    #[test]
    fn test_evaluate_const_comparison_eq() {
        let mut expr = DwarfExpression::new(8);
        expr.lit(5);
        expr.lit(5);
        expr.eq();
        let result = expr.evaluate_const();
        assert_eq!(result, Some(1));
    }

    #[test]
    fn test_evaluate_const_comparison_lt() {
        let mut expr = DwarfExpression::new(8);
        expr.lit(3);
        expr.lit(7);
        expr.lt();
        let result = expr.evaluate_const();
        assert_eq!(result, Some(1));
    }

    #[test]
    fn test_evaluate_const_neg() {
        let mut expr = DwarfExpression::new(8);
        expr.const_u8(42);
        expr.neg();
        let result = expr.evaluate_const();
        assert_eq!(result, Some(-42));
    }

    #[test]
    fn test_evaluate_const_abs() {
        let mut expr = DwarfExpression::new(8);
        expr.const_sleb(-15);
        expr.abs();
        let result = expr.evaluate_const();
        assert_eq!(result, Some(15));
    }

    #[test]
    fn test_evaluate_const_empty() {
        let expr = DwarfExpression::new(8);
        assert_eq!(expr.evaluate_const(), None);
    }

    #[test]
    fn test_evaluate_const_unsupported_op() {
        let mut expr = DwarfExpression::new(8);
        expr.reg(0); // register read not supported in const eval
        let result = expr.evaluate_const();
        assert_eq!(result, None);
    }

    #[test]
    fn test_evaluate_const_div_by_zero() {
        let mut expr = DwarfExpression::new(8);
        expr.lit(10);
        expr.lit(0);
        expr.div();
        let result = expr.evaluate_const();
        assert_eq!(result, None);
    }

    // ── Register location detection ───────────────────────────────────

    #[test]
    fn test_is_register_location_compact() {
        let expr_bytes = make_reg_expr(5);
        let expr = DwarfExpression {
            output: expr_bytes,
            stack: Vec::new(),
            address_size: 8,
            is_location: true,
        };
        assert_eq!(expr.is_register_location(), Some(5));
    }

    #[test]
    fn test_is_register_location_extended() {
        let expr_bytes = make_reg_expr(32);
        let expr = DwarfExpression {
            output: expr_bytes,
            stack: Vec::new(),
            address_size: 8,
            is_location: true,
        };
        assert_eq!(expr.is_register_location(), Some(32));
    }

    #[test]
    fn test_is_register_location_none() {
        let mut expr = DwarfExpression::new(8);
        expr.fbreg(-8);
        assert_eq!(expr.is_register_location(), None);
    }

    #[test]
    fn test_is_register_location_empty() {
        let expr = DwarfExpression::new(8);
        assert_eq!(expr.is_register_location(), None);
    }

    // ── Frame-relative detection ──────────────────────────────────────

    #[test]
    fn test_is_frame_relative_fbreg_only() {
        let expr_bytes = make_fbreg_expr(-8);
        let expr = DwarfExpression {
            output: expr_bytes,
            stack: Vec::new(),
            address_size: 8,
            is_location: true,
        };
        let result = expr.is_frame_relative();
        assert!(result.is_some());
        assert_eq!(result.unwrap().0, -8);
    }

    #[test]
    fn test_is_frame_relative_fbreg_deref() {
        let expr_bytes = make_fbreg_deref_expr(-16);
        let expr = DwarfExpression {
            output: expr_bytes,
            stack: Vec::new(),
            address_size: 8,
            is_location: true,
        };
        let result = expr.is_frame_relative();
        assert!(result.is_some());
        assert_eq!(result.unwrap().0, -16);
    }

    #[test]
    fn test_is_frame_relative_none() {
        let mut expr = DwarfExpression::new(8);
        expr.reg(3);
        assert_eq!(expr.is_frame_relative(), None);
    }

    // ── make_* helpers ────────────────────────────────────────────────

    #[test]
    fn test_make_reg_expr_compact() {
        let bytes = make_reg_expr(10);
        assert_eq!(bytes.len(), 1);
        assert_eq!(bytes[0], dwarf_ops::DW_OP_reg0 as u8 + 10);
    }

    #[test]
    fn test_make_reg_expr_extended() {
        let bytes = make_reg_expr(32);
        assert!(bytes.len() > 1);
        assert_eq!(bytes[0], dwarf_ops::DW_OP_regx as u8);
    }

    #[test]
    fn test_make_fbreg_expr() {
        let bytes = make_fbreg_expr(-8);
        assert_eq!(bytes[0], dwarf_ops::DW_OP_fbreg as u8);
    }

    #[test]
    fn test_make_fbreg_deref_expr() {
        let bytes = make_fbreg_deref_expr(-16);
        assert_eq!(bytes[0], dwarf_ops::DW_OP_fbreg as u8);
        assert_eq!(bytes.last(), Some(&(dwarf_ops::DW_OP_deref as u8)));
    }

    #[test]
    fn test_make_const_expr_lit() {
        let bytes = make_const_expr(5);
        assert_eq!(bytes[0], dwarf_ops::DW_OP_lit0 as u8 + 5);
        assert_eq!(bytes.last(), Some(&(dwarf_ops::DW_OP_stack_value as u8)));
    }

    #[test]
    fn test_make_const_expr_large() {
        let bytes = make_const_expr(1000);
        // 1000 fits in u16, so DW_OP_const2u
        assert_eq!(bytes[0], dwarf_ops::DW_OP_const2u as u8);
        assert_eq!(bytes.last(), Some(&(dwarf_ops::DW_OP_stack_value as u8)));
    }

    // ── LEB128 decoder tests ──────────────────────────────────────────

    #[test]
    fn test_try_decode_uleb128_small() {
        let data = vec![42u8];
        let (val, len) = try_decode_uleb128(&data).unwrap();
        assert_eq!(val, 42);
        assert_eq!(len, 1);
    }

    #[test]
    fn test_try_decode_uleb128_multi() {
        // 624485 = 0x98765 → ULEB128: 0xE5, 0x8E, 0x26
        let data = vec![0xE5, 0x8E, 0x26];
        let (val, len) = try_decode_uleb128(&data).unwrap();
        assert_eq!(val, 624485);
        assert_eq!(len, 3);
    }

    #[test]
    fn test_try_decode_uleb128_zero() {
        let data = vec![0u8];
        let (val, _) = try_decode_uleb128(&data).unwrap();
        assert_eq!(val, 0);
    }

    #[test]
    fn test_try_decode_sleb128_positive() {
        let data = vec![42u8];
        let (val, _) = try_decode_sleb128(&data).unwrap();
        assert_eq!(val, 42);
    }

    #[test]
    fn test_try_decode_sleb128_negative() {
        let data = vec![0x7Fu8];
        let (val, _) = try_decode_sleb128(&data).unwrap();
        assert_eq!(val, -1);
    }
}