onlineasm 0.4.6

Minimal portable runtime assembler with offlineasm mnemonics
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
#![warn(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
// Lowering handlers take the shared context plus decoded operands. Bundling
// the parameters into a struct would obscure the 1:1 mapping with the
// mnemonic tables and add churn without improving safety.
#![allow(clippy::too_many_arguments)]

//! `onlineasm`: a minimal, portable runtime assembler.
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use onlineasm::{onlineasm, Assembler, JitAllocator, Target};
//!
//! let mut asm = Assembler::native();
//!
//! let (arg0, arg1) = match asm.target() {
//!     Target::X64 => (onlineasm::regs::t6, onlineasm::regs::t1),
//!     Target::AArch64 | Target::RISCV64 => (onlineasm::regs::t0, onlineasm::regs::t1),
//! };
//! onlineasm!(asm;
//!     =>add;
//!     move t0, {arg0};
//!     addq t0, {arg1};
//!     ret;
//! );
//! let code = asm.finish()?;
//! let entry = code.offset(add).ok_or("add is unbound")?;
//! let mut jit = JitAllocator::new(Default::default());
//! let span = code.allocate(&mut jit)?;
//! let f: extern "C" fn(u64, u64) -> u64 =
//!     unsafe { std::mem::transmute(span.rx().add(entry as usize)) };
//! assert_eq!(f(40, 2), 42);
//! # Ok(())
//! # }
//! ```
//!
//! ## Backward assembly
//!
//! [`BackwardAssembler`] records all calls to assembler, `onlineasm!()`
//! invocations, and then replays them in reverse order at `finish`, so
//! last emitted instruction executes first:
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use onlineasm::{onlineasm, BackwardAssembler, JitAllocator};
//!
//! let mut asm = BackwardAssembler::native_backward();
//! onlineasm!(asm;
//!     ret;
//!     addq t0, 41;
//!     move t0, 1;
//! );
//! let code = asm.finish()?;
//! let mut jit = JitAllocator::new(Default::default());
//! let span = code.allocate(&mut jit)?;
//! let f: extern "C" fn() -> u64 = unsafe { std::mem::transmute(span.rx()) };
//! assert_eq!(f(), 42);
//! # Ok(())
//! # }
//! ```
//!
//! ## Reusing an assembler
//!
//! [`Assembler::finish`] leaves the assembler ready for the next image (it
//! clears the code buffer but keeps its allocations), so a JIT that compiles
//! many small functions can build them through one assembler:
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use onlineasm::{onlineasm, Assembler, JitAllocator};
//!
//! let mut asm = Assembler::native();
//! let mut jit = JitAllocator::new(Default::default());
//! for value in [41u64, 42] {
//!     onlineasm!(asm;
//!         =>entry;
//!         move t0, {value};
//!         ret;
//!     );
//!     let code = asm.finish()?;
//!     let entry = code.offset(entry).ok_or("entry is unbound")?;
//!     let span = code.allocate(&mut jit)?;
//!     let f: extern "C" fn() -> u64 =
//!         unsafe { std::mem::transmute(span.rx().add(entry as usize)) };
//!     assert_eq!(f(), value);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! [`Assembler::reset`] discards a partially assembled image instead of
//! finalizing it. Handles from a finished or discarded image stay valid
//! through [`Finished`], but must not be used to emit further code; label and
//! virtual-patch handles from an earlier image are rejected by the next one.
//!
//! ## External symbols
//!
//! Generated code references host functions and data by [`ExternalName`]
//! and resolves them when the code is loaded:
//!
//! ```ignore
//! let helper = ExternalName::user(0, 3);
//! onlineasm!(asm;
//!     call extern {helper.clone()};
//! );
//! let code = asm.finish()?.load(&mut jit, |name| {
//!     if *name == helper { helper_fn as *const u8 } else { std::ptr::null() }
//! })?;
//! ```
//!
//! A far extern ([`Assembler::extern_far`], `extern` in the macro) is reached
//! through an address table placed after the code, so it can be anywhere,
//! and [`LoadedCode::rebind`] binds it later. A near extern
//! ([`Assembler::extern_near`], `extern near`) is a direct PC-relative
//! reference and must be within the instruction's range of the code
//! (x86-64 and RISC-V 64: +/-2 GiB; AArch64 `bl`/`b`: +/-128 MiB, `adrp`:
//! +/-4 GiB); loading fails otherwise.
//!
//! ## Patching emitted code
//!
//! A `#[patch = name]` instruction in [`onlineasm!`](crate::onlineasm) (or
//! [`Assembler::emit_patched`]) emits through a patchable site and binds its
//! [`PatchHandle`] to `name`. After [`finish`](Assembler::finish),
//! [`Finished::location`] turns the handle into a [`PatchLocation`]: either a
//! jump, retargeted with [`asmkit::repatch_jump_span`], or a 64-bit
//! immediate, rewritten with [`repatch_u64`]. Jumps and calls with an
//! absolute (non-label) target use `#[patch_abs = name]` instead, which
//! reserves a 64-bit address slot and branches to it indirectly. See
//! [`Assembler::emit_patched`] for the patchable instructions, and the `patch` example (`cargo run -p onlineasm --example
//! patch`) for all three flows.
//!
//! ## Instruction reference
//!
//! See [crate::reference].

use asmkit::{
    Arch, AsmError, CodeBuffer, CodeBufferFinalized, Environment, RelocDistance, RelocTarget, Span,
};
use offlineasm_ir::Lbl;

mod aarch64;
mod backward;
mod insn;
mod lower;
mod riscv64;
mod x86;

pub(crate) mod ir {
    pub use crate::lower::{LabelResolver, LowerError, PatchHandle};
    pub use offlineasm_ir::*;
}

pub use offlineasm_ir::regs;

#[doc = include_str!("../docs/reference.md")]
pub mod reference {}

#[allow(non_upper_case_globals, non_snake_case)]
pub mod mnem {
    include!(concat!(env!("OUT_DIR"), "/mnem.rs"));
}

pub use asmkit::{
    CodeLocationData, CodeLocationJump, DataLabel, ExternalName, JitAllocator, JitAllocatorOptions,
    LoadedCode, PatchableJump, ResetPolicy, UserExternalName,
};
pub use ir::{
    Disp, Extern, Fpr, Gpr, Label, LowerError, Mem, Mnemonic, Op, PatchHandle, Reach, Scratch,
    SymId, SUPPORTED_MNEMONICS,
};
/// Emits runtime assembly using offlineasm mnemonics.
///
/// ```text
/// onlineasm!(assembler; statement ...)
///
/// statement :=
///     | `.name:`                        define a local label
///     | `=>name`                         bind a fresh label to `name`
///     | `extern [near] name = {expr}`    bind an external symbol to `name`
///     | `[attr] mnemonic operand, ...`   one instruction
///
/// attr    := `#[patch = name]` | `#[patch_abs = name]` (`jmp`/`call` only)
/// operand := integer | register | `%register` | `.name` | `{expr}`
///          | `[base [+ index [* scale]] [+/- disp]]` | `extern [near] {expr}`
/// ```
///
/// Statements are `;`-separated (a trailing `;` is allowed). `integer` is a
/// decimal/`0x`/`0o`/`0b` literal, signed with a leading `-`, `register` is a
/// portable vreg (`t0`, `sp`, ...) or a bare physical name, `{expr}` splices a
/// Rust value (`VReg`, `Gpr`, `Fpr`, `Mem`, `Label`, integer). In a memory
/// operand the base and index are registers or `{expr}`, the displacement an
/// integer or `{expr}`, and the scale `1`, `2`, `4`, or `8`.
///
/// Names bound by `=>`, `extern`, and `#[patch]` are declared after the macro,
/// so they stay usable afterwards. See the crate-level documentation of
/// [onlineasm_macros] for the full rules.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use onlineasm::{onlineasm, Assembler};
///
/// let mut asm = Assembler::native();
/// onlineasm!(asm;
///     =>add;
///     move t0, 41;
///     addi t0, 1;
///     ret;
/// );
/// let code = asm.finish()?;
/// assert!(code.offset(add).is_some());
/// # Ok(())
/// # }
/// ```
pub use onlineasm_macros::onlineasm;
pub use regs::{RegInfo, RegKind, VReg};

/// Target for the assembler.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Target {
    /// x86-64.
    X64,
    /// AArch64.
    AArch64,
    /// RISC-V 64 (rv64gc).
    RISCV64,
}

#[allow(clippy::from_over_into)]
impl Into<Arch> for Target {
    fn into(self) -> Arch {
        match self {
            Self::AArch64 => Arch::AArch64,
            Self::RISCV64 => Arch::RISCV64,
            Self::X64 => Arch::X64,
        }
    }
}

impl Target {
    /// All supported targets.
    pub const ALL: [Target; 3] = [Target::X64, Target::AArch64, Target::RISCV64];

    /// Names of the callee-saved GPRs on this target under the
    /// default ABI (SystemV, AAPCS, RISCV64)
    pub const fn callee_saved_gprs(self) -> &'static [&'static str] {
        match self {
            Target::X64 => &["csr0", "csr1", "csr2", "csr3", "csr4"],
            Target::AArch64 => &[
                "csr0", "csr1", "csr2", "csr3", "csr4", "csr5", "csr6", "csr7", "csr8", "csr9",
            ],
            Target::RISCV64 => &[
                "csr0", "csr1", "csr2", "csr3", "csr4", "csr5", "csr6", "csr7", "csr8", "csr9",
                "csr10",
            ],
        }
    }

    /// Names of the callee-saved GPRs on this target under `abi`.
    pub const fn callee_saved_gprs_for(self, abi: Abi) -> &'static [&'static str] {
        match (self, abi) {
            (Target::X64, Abi::Windows) => {
                &["csr0", "csr1", "csr2", "csr3", "csr4", "csr5", "csr6"]
            }
            _ => self.callee_saved_gprs(),
        }
    }

    /// Names of the callee-saved FPRs on this target.
    pub const fn callee_saved_fprs(self) -> &'static [&'static str] {
        match self {
            Target::X64 => &[],
            Target::AArch64 => &[
                "csfr0", "csfr1", "csfr2", "csfr3", "csfr4", "csfr5", "csfr6", "csfr7",
            ],
            Target::RISCV64 => &[
                "csfr0", "csfr1", "csfr2", "csfr3", "csfr4", "csfr5", "csfr6", "csfr7",
            ],
        }
    }

    /// Names of the callee-saved FPRs on this target under `abi`.
    pub const fn callee_saved_fprs_for(self, abi: Abi) -> &'static [&'static str] {
        let _ = abi;
        self.callee_saved_fprs()
    }

    /// Returns the target matching the host architecture.
    ///
    /// # Panics
    ///
    /// Panics if host architecture is not supported.
    pub const fn native() -> Self {
        #[cfg(target_arch = "x86_64")]
        {
            Target::X64
        }
        #[cfg(target_arch = "aarch64")]
        {
            Target::AArch64
        }
        #[cfg(target_arch = "riscv64")]
        {
            Target::RISCV64
        }
        #[cfg(not(any(
            target_arch = "x86_64",
            target_arch = "aarch64",
            target_arch = "riscv64"
        )))]
        {
            panic!("onlineasm: unsupported host architecture")
        }
    }

    pub const fn arch(self) -> Arch {
        match self {
            Target::X64 => Arch::X64,
            Target::AArch64 => Arch::AArch64,
            Target::RISCV64 => Arch::RISCV64,
        }
    }

    pub const fn as_str(self) -> &'static str {
        match self {
            Target::X64 => "x86_64",
            Target::AArch64 => "aarch64",
            Target::RISCV64 => "riscv64",
        }
    }

    pub(crate) const fn info(self) -> &'static TargetInfo {
        match self {
            Target::X64 => &x86::INFO,
            Target::AArch64 => &aarch64::INFO,
            Target::RISCV64 => &riscv64::INFO,
        }
    }

    pub const fn registers(self) -> &'static [RegInfo] {
        self.info().registers
    }
}

impl std::fmt::Display for Target {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

pub(crate) type LowerFn = fn(
    &mut CodeBuffer,
    &Scratch,
    &[asmkit::Label],
    u32,
    Mnemonic,
    &[Op],
    Abi,
) -> Result<(), LowerError>;

pub(crate) type LowerPatchedFn = fn(
    &mut CodeBuffer,
    &Scratch,
    &[asmkit::Label],
    u32,
    Mnemonic,
    &[Op],
    Abi,
) -> Result<PatchHandle, LowerError>;

/// Per-target lowering hooks and register tables.
pub(crate) struct TargetInfo {
    pub(crate) scratch: Scratch,
    pub(crate) registers: &'static [RegInfo],
    pub(crate) vreg_gpr: &'static [(u16, Gpr)],
    pub(crate) vreg_fpr: &'static [(u16, Fpr)],
    pub(crate) lower: LowerFn,
    pub(crate) lower_patched: LowerPatchedFn,
}

fn lookup_gpr(table: &[(u16, Gpr)], id: u16) -> Option<Gpr> {
    table.iter().find(|&&(i, _)| i == id).map(|&(_, g)| g)
}

fn lookup_fpr(table: &[(u16, Fpr)], id: u16) -> Option<Fpr> {
    table.iter().find(|&&(i, _)| i == id).map(|&(_, v)| v)
}

#[inline]
fn reject_offlineasm_only(mnemonic: Mnemonic, ops: &[Op]) -> Result<(), LowerError> {
    let bad = |msg: &str| LowerError::BadOperand {
        mnemonic: mnemonic.as_str().to_string(),
        msg: msg.to_string(),
    };
    for op in ops {
        match op {
            Op::Sym(_) => return Err(bad("symbolic immediates are offlineasm-only")),
            Op::Mem(m) if matches!(m.disp, Disp::Sym(_)) => {
                return Err(bad("symbolic displacements are offlineasm-only"))
            }
            _ => {}
        }
    }
    Ok(())
}

/// Calling convention to use during code generation.
///
/// Call argument marshalling is not handled automatically, but the `csr` and
/// `csfr` register sets and the thread-local slot base depend on this. Only
/// x64 has more than one callee-saved set (Windows vs. SysV).
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
pub enum Abi {
    /// System V ABI (AAPCS64 on AArch64).
    #[default]
    SysV,
    /// Windows x64 ABI.
    Windows,
    /// Apple platforms: the System V callee-saved sets (AAPCS64 on AArch64),
    /// with thread-local slots in the pthread TSD (`gs` on x64,
    /// `tpidrro_el0` on AArch64).
    Darwin,
}

impl Abi {
    /// Detects the ABI to use for `target` on this host.
    pub fn detect_for(target: Target) -> Self {
        let host = if cfg!(target_arch = "x86_64") {
            Some(Target::X64)
        } else if cfg!(target_arch = "aarch64") {
            Some(Target::AArch64)
        } else if cfg!(target_arch = "riscv64") {
            Some(Target::RISCV64)
        } else {
            None
        };
        if cfg!(target_os = "windows") && host == Some(target) && target == Target::X64 {
            Abi::Windows
        } else if cfg!(target_vendor = "apple") && host == Some(target) {
            Abi::Darwin
        } else {
            Abi::SysV
        }
    }
}

/// Configuration options for [`Assembler`].
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct AssemblerOptions {
    /// Codegen environment (target plus CPU features).
    pub environment: Environment,
    /// Calling convention for the callee-saved sets.
    pub abi: Abi,
}

impl Default for AssemblerOptions {
    fn default() -> Self {
        Self {
            environment: Environment::host(),
            abi: Abi::detect_for(Target::native()),
        }
    }
}

impl AssemblerOptions {
    /// Detects the default options for `target` on this host.
    pub fn detected(target: Target) -> Self {
        Self {
            environment: Environment::new(target.into()),
            abi: Abi::detect_for(target),
        }
    }

    /// Overrides the environment.
    ///
    /// # Panics
    ///
    /// Panics for architectures other than x64, AArch64, and RISC-V 64.
    pub fn with_environment(mut self, env: Environment) -> Self {
        if !matches!(env.arch(), Arch::AArch64 | Arch::RISCV64 | Arch::X64) {
            todo!("unsupported architecture")
        }
        self.environment = env;
        self
    }

    /// Toggles position-independent code generation. With PIC on, every extern is reached through
    /// the address table, as if declared [`Reach::Far`]. offlineasm's `PIC`
    /// setting does the same.
    pub fn with_pic(mut self, pic: bool) -> Self {
        self.environment.set_pic(pic);
        self
    }

    /// Overrides the ABI.
    pub fn with_abi(mut self, abi: Abi) -> Self {
        self.abi = abi;
        self
    }

    /// Returns the target the environment encodes.
    pub fn target(&self) -> Target {
        match self.environment.arch() {
            Arch::AArch64 => Target::AArch64,
            Arch::RISCV64 => Target::RISCV64,
            Arch::X64 => Target::X64,
            _ => unreachable!(),
        }
    }
}

pub use asmkit;

/// Runtime assembler for onlineasm.
///
/// A wrapper over [`asmkit::CodeBuffer`] plus the data needed for emission.
///
/// `BACKWARD` selects the emission direction at compile time.
///
/// NOTE: instruction documentation cannot be generated automatically, and to save time
/// most of the comments on scratches and instruction behaviour
/// are pasted from [`mod@reference`]. This process is manual at the moment, and
/// they could be outdated, consult reference if you want most up to date information.
pub struct Assembler<const BACKWARD: bool = false> {
    info: &'static TargetInfo,
    target: Target,
    buf: CodeBuffer,
    ctx: Scratch,
    labels: Vec<asmkit::Label>,
    /// Handle number of `labels[0]`. It only grows across [`reset`](Self::reset)
    /// so handles from a previous image cannot name a label in a later one.
    label_base: u32,
    externs: Vec<(ExternalName, Extern)>,
    abi: Abi,
    tape: backward::ReverseTape,
}

/// An [`Assembler`] that lowers each call in program order.
pub type ForwardAssembler = Assembler<false>;

/// An [`Assembler`] that replays recorded calls in reverse at
/// [`finish`](Assembler::finish), so the last emitted instruction executes
/// first.
///
/// Labels and patch handles created during emission are *virtual*, and are not
/// accessible until `finish` is called. You cannot use `code_buffer` of such assembler
/// *during* emission.
pub type BackwardAssembler = Assembler<true>;

impl<const BACKWARD: bool> Assembler<BACKWARD> {
    fn with_options_inner(options: AssemblerOptions) -> Self {
        let target = options.target();
        let info = target.info();
        Self {
            info,
            target,
            buf: CodeBuffer::new(options.environment),
            ctx: info.scratch,
            labels: Vec::new(),
            label_base: 0,
            externs: Vec::new(),
            abi: options.abi,
            tape: backward::ReverseTape::new(),
        }
    }

    /// Returns true if this assembler is backwards.
    pub const fn is_backward(&self) -> bool {
        BACKWARD
    }

    /// Declares external symbol `name`, reached as `reach`, and returns the
    /// operand naming it. Declaring the same name and reach again returns the
    /// same handle. Under [PIC](AssemblerOptions::with_pic) every extern is
    /// [`Reach::Far`], no matter what `reach` says.
    ///
    /// An [`Extern`] is a `jmp`/`call` target or the source of
    /// `move`/`leap`/`globaladdr`/`la` (its address). The code then has to
    /// be loaded with [`Finished::load`].
    pub fn extern_name(&mut self, name: impl Into<ExternalName>, reach: Reach) -> Extern {
        let name = name.into();
        let reach = if self.pic() { Reach::Far } else { reach };
        if let Some((_, ext)) = self
            .externs
            .iter()
            .find(|(n, e)| *n == name && e.reach == reach)
        {
            return *ext;
        }
        let distance = match reach {
            Reach::Near => RelocDistance::Near,
            Reach::Far => RelocDistance::Far,
        };
        let sym = self.buf.add_symbol(name.clone(), distance);
        let ext = Extern {
            id: ir::ExternId(sym.id()),
            reach,
        };
        self.externs.push((name, ext));
        ext
    }

    /// [`Assembler::extern_name`] with [`Reach::Far`].
    pub fn extern_far(&mut self, name: impl Into<ExternalName>) -> Extern {
        self.extern_name(name, Reach::Far)
    }

    /// [`Assembler::extern_name`] with [`Reach::Near`].
    pub fn extern_near(&mut self, name: impl Into<ExternalName>) -> Extern {
        self.extern_name(name, Reach::Near)
    }

    /// Returns the underlying code buffer.
    ///
    /// On a [`BackwardAssembler`] this holds only declarations (externs)
    /// until [`finish`](Assembler::finish) replays the recorded tape.
    pub fn code_buffer(&self) -> &CodeBuffer {
        &self.buf
    }

    /// Returns the assembler's environment.
    pub fn environment(&self) -> &Environment {
        self.code_buffer().env()
    }

    /// Returns the assembler's ABI.
    pub const fn abi(&self) -> Abi {
        self.abi
    }

    /// Reports whether the assembler generates position-independent code
    /// ([`AssemblerOptions::with_pic`]).
    pub fn pic(&self) -> bool {
        self.environment().pic()
    }

    /// Returns the assembler's target.
    pub fn target(&self) -> Target {
        self.target
    }

    /// Returns the expansion scratch registers (`gpr`, `gpr2`, `fpr`).
    pub fn scratch(&self) -> Scratch {
        self.ctx
    }

    /// Resolves a portable GPR vreg to its physical register, or `None` when
    /// this target does not have it.
    pub fn try_vreg_gpr(&self, vreg: VReg) -> Option<Gpr> {
        (vreg.kind() == RegKind::Gpr)
            .then(|| lookup_gpr(self.info.vreg_gpr, vreg.id()))
            .flatten()
    }

    /// Resolves a portable FPR vreg to its physical register, or `None` when
    /// this target lacks it.
    pub fn try_vreg_fpr(&self, vreg: VReg) -> Option<Fpr> {
        (vreg.kind() == RegKind::Fpr)
            .then(|| lookup_fpr(self.info.vreg_fpr, vreg.id()))
            .flatten()
    }

    /// Resolves a portable GPR vreg to its physical register.
    ///
    /// # Panics
    ///
    /// Panics when the vreg is not a GPR or the target backend lacks it.
    #[allow(clippy::panic)]
    pub fn vreg_gpr(&self, vreg: VReg) -> Gpr {
        self.try_vreg_gpr(vreg).unwrap_or_else(|| {
            panic!(
                "onlineasm: cannot use register `{}` on {}",
                vreg.name(),
                self.target
            )
        })
    }

    /// Resolves a portable FPR vreg to its physical register.
    ///
    /// # Panics
    ///
    /// Panics when the vreg is not an FPR or the target backend lacks it.
    #[allow(clippy::panic)]
    pub fn vreg_fpr(&self, vreg: VReg) -> Fpr {
        self.try_vreg_fpr(vreg).unwrap_or_else(|| {
            panic!(
                "onlineasm: cannot use register `{}` on {}",
                vreg.name(),
                self.target
            )
        })
    }

    /// Creates a new label.
    ///
    /// On a [`BackwardAssembler`] the label is virtual until
    /// [`finish`](Assembler::finish) maps it onto the replayed code.
    pub fn label(&mut self) -> Label {
        if BACKWARD {
            self.tape.next_virtual()
        } else {
            self.label_forward()
        }
    }

    fn label_forward(&mut self) -> Label {
        let l = self.buf.get_label();
        self.labels.push(l);
        Label(self.label_base.saturating_add(self.labels.len() as u32 - 1))
    }

    #[allow(clippy::panic)]
    fn asm_label(&self, label: Label) -> asmkit::Label {
        match label
            .0
            .checked_sub(self.label_base)
            .and_then(|i| self.labels.get(i as usize))
        {
            Some(&l) => l,
            None => panic!("onlineasm: label handle does not belong to this assembler"),
        }
    }

    /// Binds a label at the current position.
    ///
    /// # Panics
    ///
    /// Panics if `label` belongs to another assembler.
    pub fn bind(&mut self, label: Label) {
        if BACKWARD {
            self.tape.push_bind(label);
        } else {
            self.bind_forward(label);
        }
    }

    fn bind_forward(&mut self, label: Label) {
        let l = self.asm_label(label);
        self.buf.bind_label(l);
    }

    /// Loads the address of `label` into `dst`, for a label within ±1 MiB of
    /// this instruction.
    ///
    /// On AArch64 this is a single `adr` with an in-buffer fixup, where
    /// `move dst, label` emits `adrp` + `add` with load-time relocations. The
    /// fixup is PC-relative, so the result is right at any load base. A
    /// label out of range makes [`finish`](Assembler::finish) fail instead
    /// of producing a wrong address. Other targets, and a
    /// [`BackwardAssembler`], emit `move dst, label`.
    ///
    /// # Panics
    ///
    /// Panics if `label` belongs to another assembler.
    pub fn label_address_near(&mut self, dst: impl IntoOperand, label: Label) {
        let dst = dst.into_operand(self);
        if let (false, Target::AArch64, Op::Gpr(g)) = (BACKWARD, self.target, &dst) {
            let l = self.asm_label(label);
            let at = self.buf.cur_offset();
            self.buf
                .use_label_at_offset(at, l, asmkit::LabelUse::A64Adr21);
            // `adr xd, #0`; the fixup fills in immlo and immhi.
            self.buf.put4(0x1000_0000 | u32::from(g.0));
            return;
        }
        self.emit_checked(Mnemonic::Move, &[dst, Op::Label(Lbl::Bound(label))]);
    }

    /// Returns the current byte offset of a label, or `u32::MAX` when it is
    /// not bound yet. On x86-64 this is best effort: [`Assembler::finish`]
    /// shrinks jumps to rel8 where they reach, which moves the code after
    /// them. Finalized offsets are available through [`Finished::offset`].
    ///
    /// On a [`BackwardAssembler`] this always reports `u32::MAX`: offsets do
    /// not exist until [`finish`](Assembler::finish) replays the tape.
    ///
    /// # Panics
    ///
    /// Panics if `label` belongs to another assembler.
    #[allow(clippy::panic)]
    pub fn offset(&self, label: Label) -> u32 {
        if BACKWARD {
            if self.tape.is_virtual(label) {
                u32::MAX
            } else {
                panic!("onlineasm: label handle does not belong to this assembler");
            }
        } else {
            self.buf.label_offset(self.asm_label(label))
        }
    }

    /// Pads with architecture `nop`s until the next emitted instruction is
    /// aligned to `alignment` bytes (a power of two).
    ///
    /// # Panics
    ///
    /// Panics when `alignment` is not a power of two.
    pub fn align(&mut self, alignment: u32) {
        assert!(
            alignment.is_power_of_two(),
            "onlineasm: alignment {alignment} is not a power of two"
        );
        if BACKWARD {
            self.tape.push_align(alignment);
        } else {
            self.align_forward(alignment);
        }
    }

    fn align_forward(&mut self, alignment: u32) {
        if self.target == Target::X64 {
            self.buf.align_to(alignment);
            return;
        }
        while self.buf.cur_offset() & (alignment - 1) != 0 {
            let before = self.buf.cur_offset();
            if self.emit_forward(Mnemonic::Nop, &[]).is_err() {
                unreachable!("the built-in `nop` lowering cannot fail");
            }
            assert!(
                self.buf.cur_offset() > before,
                "onlineasm: `nop` did not advance the buffer (buffer error: {:?})",
                self.buf.error()
            );
        }
    }

    /// Embeds `data` in the image and returns the label naming it.
    ///
    /// The payload is placed in a constant island at the end of the finalized
    /// image (8-byte aligned for payloads up to 8 bytes, 16-byte otherwise),
    /// so the label is usable from code emitted before or after this call.
    /// Load it directly with a label-addressed memory operand
    /// (`loadq dst, {asm.mem_label(label)}`) or take its address with
    /// `leap reg, {label}`.
    ///
    /// # Panics
    ///
    /// Panics when the buffer already failed.
    pub fn embed_data(&mut self, data: &[u8]) -> Label {
        if BACKWARD {
            self.tape.push_embed(data)
        } else {
            self.embed_data_forward(data)
        }
    }

    /// [`Assembler::embed_data`] for one 64-bit word, written in native
    /// (little-endian on every supported target) byte order.
    pub fn embed_u64(&mut self, bits: u64) -> Label {
        self.embed_data(&bits.to_ne_bytes())
    }

    fn embed_data_forward(&mut self, data: &[u8]) -> Label {
        let constant = self.buf.add_constant(data.to_vec());
        self.labels.push(self.buf.get_label_for_constant(constant));
        Label(
            self.label_base
                .saturating_add(self.labels.len() as u32 - 1),
        )
    }

    /// Writes `bytes` at the current position as raw data.
    ///
    /// Unlike [`Assembler::embed_data`], this does not create or move a label
    /// and does not deduplicate. Use it to fill a block reserved by
    /// [`Assembler::bind_data`] where the pool must sit (typically the end of
    /// the image), after all referencing code has been emitted.
    pub fn emit_data(&mut self, bytes: &[u8]) {
        if BACKWARD {
            self.tape.push_data(None, 1, bytes);
        } else {
            self.emit_data_forward(bytes);
        }
    }

    /// Writes `v` as 4 little-endian bytes at the current position.
    pub fn emit_u32(&mut self, v: u32) {
        self.emit_data(&v.to_le_bytes());
    }

    /// Writes `v` as 8 little-endian bytes at the current position.
    pub fn emit_u64(&mut self, v: u64) {
        self.emit_data(&v.to_le_bytes());
    }

    /// Pads to `alignment` for a following data block.
    ///
    /// This is [`Assembler::align`] without the instruction-alignment
    /// contract: the padding bytes are not executed.
    ///
    /// # Panics
    ///
    /// Panics when `alignment` is not a power of two.
    pub fn align_data(&mut self, alignment: u32) {
        assert!(
            alignment.is_power_of_two(),
            "onlineasm: alignment {alignment} is not a power of two"
        );
        if BACKWARD {
            if alignment > 1 {
                self.tape.push_data(None, alignment, &[]);
            }
        } else {
            self.align_data_forward(alignment);
        }
    }

    /// Aligns, binds `label`, and writes `bytes` as raw data.
    ///
    /// This is the "create the label first, fill the island later" form: call
    /// [`Assembler::label`] while emitting code, reference the label with
    /// [`Assembler::mem_label`], then bind and fill it here after the code.
    pub fn bind_data(&mut self, label: Label, alignment: u32, bytes: &[u8]) {
        if BACKWARD {
            self.tape.push_data(Some(label), alignment, bytes);
        } else {
            self.align_data_forward(alignment);
            self.bind_forward(label);
            self.emit_data_forward(bytes);
        }
    }

    fn emit_data_forward(&mut self, bytes: &[u8]) {
        for &byte in bytes {
            self.buf.put1(byte);
        }
    }

    fn align_data_forward(&mut self, alignment: u32) {
        if alignment > 1 {
            self.buf.align_to(alignment);
        }
    }

    /// Converts `v` into an assembler operand.
    pub fn op(&self, v: impl IntoOperand) -> Op {
        v.into_operand(self)
    }

    /// Builds a `[base + disp]` memory operand (resolving a portable base).
    ///
    /// When `base` is a [`Label`] and `disp` is zero, this builds the
    /// PC-relative label-addressed form instead (see [`Assembler::mem_label`]).
    ///
    /// # Panics
    ///
    /// Panics when `base` does not resolve to a general-purpose register or a
    /// label, or when a label is combined with a non-zero displacement.
    pub fn mem(&self, base: impl IntoOperand, disp: i32) -> Mem {
        match self.op(base) {
            Op::Label(l) => {
                assert!(
                    disp == 0,
                    "onlineasm: a label-addressed memory operand has no displacement"
                );
                Mem::absolute(self.label_disp(l, false))
            }
            Op::Gpr(g) => Mem {
                base: Some(g),
                index: None,
                disp: Disp::Const(disp),
            },
            other => panic!("onlineasm: expected a register operand, got {other:?}"),
        }
    }

    /// Builds the PC-relative memory at `label`'s address (`[label]`):
    /// `[rip + label]` on x86-64, an `ldr` literal on AArch64.
    ///
    /// Reference its contents with any load/store mnemonic, for example
    /// `loadq dst, {mem}`. Use [`Assembler::mem_label_far`] when the label may
    /// be out of the literal range on AArch64.
    pub fn mem_label(&self, label: Label) -> Mem {
        Mem::absolute(self.label_disp(Lbl::Bound(label), false))
    }

    /// Like [`Assembler::mem_label`], but asks for the AArch64 page-pair
    /// (`adrp` + `ldr`/`str` low-12) form, which reaches ±4 GiB.
    pub fn mem_label_far(&self, label: Label) -> Mem {
        Mem::absolute(self.label_disp(Lbl::Bound(label), true))
    }

    fn label_disp(&self, l: Lbl, far: bool) -> Disp {
        let Lbl::Bound(label) = l else {
            panic!("onlineasm: a label-addressed memory operand needs a bound label")
        };
        if far {
            Disp::LabelFar(label)
        } else {
            Disp::Label(label)
        }
    }

    /// Builds a `[base + index*scale + disp]` memory operand.
    ///
    /// # Panics
    ///
    /// Panics when `base`/`index` do not resolve to general-purpose
    /// registers, or when `scale` is not 1, 2, 4, or 8.
    pub fn mem_indexed(
        &self,
        base: impl IntoOperand,
        index: impl IntoOperand,
        scale: u8,
        disp: i32,
    ) -> Mem {
        assert!(
            matches!(scale, 1 | 2 | 4 | 8),
            "scale must be 1, 2, 4, or 8"
        );
        Mem {
            base: Some(self.gpr_operand(base)),
            index: Some((self.gpr_operand(index), scale)),
            disp: Disp::Const(disp),
        }
    }

    #[allow(clippy::panic)]
    fn gpr_operand(&self, v: impl IntoOperand) -> Gpr {
        match v.into_operand(self) {
            Op::Gpr(g) => g,
            other => panic!("onlineasm: expected a register operand, got {other:?}"),
        }
    }

    /// Emits one onlineasm mnemonic.
    ///
    /// # Errors
    ///
    /// Returns an error if the mnemonic is offlineasm-only or lowering fails.
    pub fn emit(&mut self, mnemonic: Mnemonic, ops: &[Op]) -> Result<(), LowerError> {
        if BACKWARD {
            reject_offlineasm_only(mnemonic, ops)?;
            self.tape.push_emit(mnemonic, ops);
            Ok(())
        } else {
            self.emit_forward(mnemonic, ops)
        }
    }

    fn emit_forward(&mut self, mnemonic: Mnemonic, ops: &[Op]) -> Result<(), LowerError> {
        reject_offlineasm_only(mnemonic, ops)?;
        (self.info.lower)(
            &mut self.buf,
            &self.ctx,
            &self.labels,
            self.label_base,
            mnemonic,
            ops,
            self.abi,
        )
    }

    #[allow(clippy::panic)]
    fn emit_checked(&mut self, mnemonic: Mnemonic, ops: &[Op]) {
        if let Err(e) = self.emit(mnemonic, ops) {
            panic!("onlineasm: lowering `{mnemonic}` failed: {e}");
        }
    }

    /// Emits one onlineasm mnemonic through a patchable site and returns its
    /// patch handle.
    ///
    /// The macro form is `#[patch = name]` on the instruction. Patchable
    /// instructions and the handle each yields:
    ///
    /// * `jmp`/`call` with a label target: a [`PatchHandle::Jump`], retargeted
    ///   with [`asmkit::repatch_jump_span`] or [`asmkit::repatch_jump_span_mt_safe`]. Register, memory, absolute, and
    ///   external targets are not patchable (absolute ones use
    ///   `#[patch_abs = name]` instead; see below).
    /// * `move` with a register destination and an immediate source: a
    ///   [`PatchHandle::Data`], rewritten with [`repatch_u64`].
    /// * Conditional branches (integer `bqeq`/`bieq`/..., test `btqz`/...,
    ///   flag `bo`/`bs`/`bz`/`bnz`, arithmetic `baddqo`/..., float
    ///   `bdeq`/...): a [`PatchHandle::Jump`]. Float conditions that expand to
    ///   several branches are not patchable (which ones depends on the
    ///   target), and neither is the overflow-of-`or` arithmetic branch
    ///   (`borio`/`borqo`), which emits no branch at all.
    ///
    /// An external symbol is never a patch site, whatever the mnemonic.
    /// Anything else fails with [`LowerError::NotPatchable`].
    ///
    /// `#[patch_abs = name]` (macro only) applies to `jmp`/`call` with an
    /// integer or `{expr}` target. It emits a patchable `move` of the target
    /// into the expansion scratch GPR followed by an indirect jump/call
    /// through it, and binds the `move`'s [`PatchHandle::Data`]: fill it with
    /// the callee's absolute address via [`repatch_u64`]. The scratch GPR
    /// (`r11`/`x16`/`x31`) is clobbered, as for any expansion using it.
    ///
    /// On a [`BackwardAssembler`] the call is recorded and the returned
    /// handle is virtual until [`finish`](Assembler::finish) replays the
    /// tape, resolve it with [`Finished::location`] afterwards.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use onlineasm::{onlineasm, Assembler, JitAllocator, PatchLocation};
    ///
    /// let mut asm = Assembler::native();
    /// onlineasm!(asm;
    ///     #[patch = slot] move t0, 0;
    ///     ret;
    /// );
    /// let code = asm.finish()?;
    /// let location = code.location(slot).ok_or("slot is unbound")?;
    ///
    /// let mut jit = JitAllocator::new(Default::default());
    /// let mut span = code.allocate(&mut jit)?;
    /// // SAFETY: `span` holds `code`, and nothing executes the patched
    /// // instruction while it is rewritten.
    /// unsafe { onlineasm::repatch_u64(&mut jit, &mut span, &location, 42)? };
    /// let f: extern "C" fn() -> u64 = unsafe { std::mem::transmute(span.rx()) };
    /// assert_eq!(f(), 42);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the mnemonic is offlineasm-only, lowering fails,
    /// or the mnemonic (or its operand shape) is not patchable. On a
    /// [`BackwardAssembler`], lowering failures surface at
    /// [`finish`](Assembler::finish) instead.
    pub fn emit_patched(
        &mut self,
        mnemonic: Mnemonic,
        ops: &[Op],
    ) -> Result<PatchHandle, LowerError> {
        if BACKWARD {
            reject_offlineasm_only(mnemonic, ops)?;
            Ok(self.tape.push_emit_patched(mnemonic, ops))
        } else {
            self.emit_forward_patched(mnemonic, ops)
        }
    }

    fn emit_forward_patched(
        &mut self,
        mnemonic: Mnemonic,
        ops: &[Op],
    ) -> Result<PatchHandle, LowerError> {
        reject_offlineasm_only(mnemonic, ops)?;
        (self.info.lower_patched)(
            &mut self.buf,
            &self.ctx,
            &self.labels,
            self.label_base,
            mnemonic,
            ops,
            self.abi,
        )
    }

    /// Finalizes the buffer, reporting offsets for `labels` in order.
    /// `virtual_patches` resolves backward handles in [`Finished::location`].
    ///
    /// `label_base` and `patch_base` are the first handle numbers of this
    /// image, so [`Finished`] can reject handles from an earlier image.
    fn finalize(
        &mut self,
        labels: &[asmkit::Label],
        label_base: u32,
        patch_base: u32,
        virtual_patches: Vec<PatchHandle>,
    ) -> Result<Finished, AsmError> {
        self.buf.emit_island(u32::MAX)?;
        // `finish_owned` moves the recordings out instead of cloning them.
        let inner = self.buf.finish_owned()?;
        let offsets: Vec<u32> = labels.iter().map(|l| inner.label_offset(*l)).collect();
        // Reset the (now empty) buffer so the next image starts clean.
        self.buf.clear();
        Ok(Finished {
            // The finalized image is several kilobytes because of its inline
            // `SmallVec`s; keep it behind a pointer so moving `Finished` out
            // of `finish()` does not copy it.
            inner: Box::new(inner),
            offsets,
            label_base,
            patch_base,
            linked: false,
            virtual_patches,
        })
    }

    /// Discards the code assembled so far and resets the assembler for the
    /// next image, retaining buffer capacity.
    ///
    /// [`finish`](Assembler::finish) already does this on success; call
    /// `reset` to throw away a partially assembled image instead.
    ///
    /// Handles from the discarded image must not be used again. Label and
    /// virtual-patch handles are rejected because handle numbers only grow
    /// across resets; raw [`PatchHandle::Jump`]/[`PatchHandle::Data`] handles
    /// from [`emit_patched`](Assembler::emit_patched) carry asmkit offsets and
    /// must not be carried across a reset either.
    pub fn reset(&mut self) {
        self.label_base = self.label_base.saturating_add(self.labels.len() as u32);
        self.buf.clear();
        self.labels.clear();
        self.externs.clear();
        self.tape.reset();
    }
}

impl Assembler<false> {
    /// Creates an assembler for `target`.
    ///
    /// This constructor is only available on [`ForwardAssembler`], so a bare
    /// `Assembler::new(..)` keeps meaning forward. Backward assembly starts
    /// from [`BackwardAssembler::new_backward`].
    pub fn new(target: Target) -> Self {
        Self::with_options(AssemblerOptions::detected(target))
    }

    /// Creates an assembler for `target` with explicit [`AssemblerOptions`].
    pub fn with_options(options: AssemblerOptions) -> Self {
        Self::with_options_inner(options)
    }

    /// Creates an assembler for the host architecture.
    pub fn native() -> Self {
        Self::new(Target::native())
    }

    /// Finalizes the code buffer.
    ///
    /// On success the assembler is reset ([`reset`](Assembler::reset)) and can
    /// assemble another image without reallocating its buffer. Label and patch
    /// handles from this image stay valid through [`Finished`], but must not be
    /// used to emit further code.
    ///
    /// # Errors
    ///
    /// Returns an error if finalization fails. The assembler is reset either
    /// way.
    pub fn finish(&mut self) -> Result<Finished, AsmError> {
        let labels = std::mem::take(&mut self.labels);
        let res = self.finalize(&labels, self.label_base, 0, Vec::new());
        // Put the label allocation back so `reset` can keep it for reuse.
        self.labels = labels;
        self.reset();
        res
    }
}

impl Assembler<true> {
    /// Creates a backward assembler for `target`.
    ///
    /// Calls on the returned assembler record onto a tape that
    /// [`finish`](Assembler::finish) replays in reverse.
    pub fn new_backward(target: Target) -> Self {
        Self::with_options_backward(AssemblerOptions::detected(target))
    }

    /// Creates a backward assembler for `target` with explicit
    /// [`AssemblerOptions`].
    pub fn with_options_backward(options: AssemblerOptions) -> Self {
        Self::with_options_inner(options)
    }

    /// Creates a backward assembler for the host architecture.
    pub fn native_backward() -> Self {
        Self::new_backward(Target::native())
    }

    /// Replays the recorded calls in reverse and finalizes the code buffer.
    ///
    /// The last-recorded call is lowered first, so it executes first.
    /// Virtual labels created while recording resolve onto the replayed code,
    /// and [`Finished::offset`] has them afterwards.
    ///
    /// On success the assembler is reset ([`reset`](Assembler::reset)) and can
    /// record another image. Handles from this image stay valid through
    /// [`Finished`], but must not be used to record further code.
    ///
    /// # Errors
    ///
    /// Returns [`BackwardFinishError::Lower`] when a recorded call fails to
    /// lower, or [`BackwardFinishError::Finalize`] when finalization fails. The
    /// assembler is reset either way.
    ///
    /// # Panics
    ///
    /// Panics if a recorded operand names a label from another assembler.
    pub fn finish(&mut self) -> Result<Finished, BackwardFinishError> {
        let res = self.replay();
        self.reset();
        res
    }

    fn replay(&mut self) -> Result<Finished, BackwardFinishError> {
        let virtual_count = self.tape.virtual_count();
        let patch_count = self.tape.patch_count();
        let virtual_base = self.tape.virtual_base();
        let patch_base = self.tape.patch_base();
        let mut items = self.tape.take();
        // Embedded constants always land in the island, wherever the call
        // sits on the tape, so declare them first.
        let mut embedded: Vec<Option<&[u8]>> = vec![None; virtual_count as usize];
        for item in &items {
            if let backward::TapeItem::Embed { data, label } = item {
                if let Some(index) = label
                    .0
                    .checked_sub(virtual_base)
                    .and_then(|i| usize::try_from(i).ok())
                {
                    embedded[index] = Some(data);
                }
            }
        }
        let mut real: Vec<Label> = Vec::with_capacity(virtual_count as usize);
        for payload in embedded {
            match payload {
                Some(data) => real.push(self.embed_data_forward(data)),
                None => real.push(self.label_forward()),
            }
        }

        let mut patches: Vec<PatchHandle> = Vec::with_capacity(patch_count as usize);
        let items_len = items.len();
        for (position, item) in items.iter_mut().rev().enumerate() {
            let index = items_len - 1 - position;
            match item {
                backward::TapeItem::Emit { mnemonic, ops } => {
                    backward::remap_ops(ops, &real, virtual_base);
                    self.emit_forward(*mnemonic, ops)
                        .map_err(|source| BackwardFinishError::Lower { index, source })?;
                }
                backward::TapeItem::EmitPatched { mnemonic, ops } => {
                    backward::remap_ops(ops, &real, virtual_base);
                    let handle = self
                        .emit_forward_patched(*mnemonic, ops)
                        .map_err(|source| BackwardFinishError::Lower { index, source })?;
                    patches.push(handle);
                }
                backward::TapeItem::Bind(v) => {
                    self.bind_forward(backward::remap_label(*v, &real, virtual_base));
                }
                backward::TapeItem::Align(alignment) => self.align_forward(*alignment),
                backward::TapeItem::Embed { .. } => {}
                backward::TapeItem::Data { data, label, align } => {
                    self.align_data_forward(*align);
                    if let Some(v) = label {
                        self.bind_forward(backward::remap_label(*v, &real, virtual_base));
                    }
                    self.emit_data_forward(data);
                }
            }
        }
        patches.reverse();
        let labels: Vec<asmkit::Label> = real.iter().map(|r| self.asm_label(*r)).collect();
        self.finalize(&labels, virtual_base, patch_base, patches)
            .map_err(BackwardFinishError::Finalize)
    }
}

impl Default for Assembler<false> {
    fn default() -> Self {
        Self::native()
    }
}

/// Failure to replay a backward assembler's tape at
/// [`finish`](Assembler::finish).
#[derive(Debug)]
pub enum BackwardFinishError {
    /// Replaying the recorded call at tape position `index` failed to lower.
    Lower { index: usize, source: LowerError },
    /// Finalization failed after a successful replay.
    Finalize(AsmError),
}

impl std::fmt::Display for BackwardFinishError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Lower { index, source } => {
                write!(f, "replaying recorded call {index} failed: {source}")
            }
            Self::Finalize(e) => write!(f, "finalization failed: {e}"),
        }
    }
}

impl std::error::Error for BackwardFinishError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Lower { source, .. } => Some(source),
            Self::Finalize(e) => Some(e),
        }
    }
}

/// A finalized machine-code image plus the offsets of the labels.
pub struct Finished {
    inner: Box<CodeBufferFinalized>,
    offsets: Vec<u32>,
    /// First label handle of this image (see [`Assembler::reset`]).
    label_base: u32,
    /// First virtual patch handle of this image.
    patch_base: u32,
    linked: bool,
    virtual_patches: Vec<PatchHandle>,
}

/// Where a [`PatchHandle`] is in a [`Finished`] image.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PatchLocation {
    /// A jump or call (`#[patch]` on `jmp`/`call`/branches), retargeted with
    /// [`asmkit::repatch_jump_span`] to an absolute address. The new target
    /// must be within the jump's range, anything further fails with [`AsmError::TooLarge`]. To patch
    /// before allocating, apply [`asmkit::repatch_jump`] to a copy of
    /// [`Finished::data`] with a [`Finished::offset`] target instead.
    Jump(CodeLocationJump),
    /// A 64-bit immediate (`#[patch]` on `move`, or the address slot of
    /// `#[patch_abs]` on `jmp`/`call`), rewritten with [`repatch_u64`]. To
    /// patch before allocating, apply [`asmkit::repatch_value`] to a copy of
    /// [`Finished::data`], and read the current value back with
    /// [`asmkit::read_value`].
    Data(CodeLocationData),
}

impl Finished {
    /// Returns the machine-code bytes.
    pub fn data(&self) -> &[u8] {
        self.inner.data()
    }

    /// Returns the final byte offset of a label, or `None` when it was never
    /// bound or belongs to another image.
    pub fn offset(&self, label: Label) -> Option<u32> {
        let index = label.0.checked_sub(self.label_base)? as usize;
        match self.offsets.get(index) {
            Some(&off) if off != u32::MAX => Some(off),
            _ => None,
        }
    }

    /// Returns where a [`PatchHandle`] returned while assembling
    /// (`#[patch = h]` or [`Assembler::emit_patched`]) is in this image.
    ///
    /// Returns `None` for a linked image ([`Finished::link`] drops every
    /// handle), or for a backward-assembler handle this image does not know.
    /// A forward handle from another image is not detected: it maps to a
    /// meaningless offset, so only pass handles this image's assembler
    /// returned.
    pub fn location(&self, handle: PatchHandle) -> Option<PatchLocation> {
        if self.linked {
            return None;
        }
        let real = match handle {
            PatchHandle::Virtual(id) => {
                let index = id.checked_sub(self.patch_base)? as usize;
                *self.virtual_patches.get(index)?
            }
            real => real,
        };
        Some(match real {
            PatchHandle::Jump(jump) => PatchLocation::Jump(self.inner.location_of(jump)),
            PatchHandle::Data(data) => PatchLocation::Data(self.inner.location_of(data)),
            PatchHandle::Virtual(_) => {
                unreachable!("onlineasm: resolved patch handle is never virtual")
            }
        })
    }

    /// Loads the image into executable memory.
    ///
    /// # Errors
    ///
    /// Returns an error if the image references externs (load it with
    /// [`Finished::load`] instead) or the JIT allocation fails.
    pub fn allocate(&self, jit: &mut JitAllocator) -> Result<Span, AsmError> {
        if self.has_externs() {
            return Err(AsmError::InvalidState);
        }
        self.inner.allocate(jit)
    }

    /// Reports whether the image references external symbols.
    pub fn has_externs(&self) -> bool {
        self.inner
            .relocs()
            .iter()
            .any(|r| matches!(r.target, RelocTarget::Sym(_)))
    }

    /// Loads the image into executable memory, resolving each external
    /// symbol through `resolve`. Far externs get a slot in an address table
    /// placed after the code, which [`LoadedCode::rebind`] can repoint.
    ///
    /// # Errors
    ///
    /// Returns an error if `resolve` returns null for a name, a near extern
    /// is out of its instruction's range, or the JIT allocation fails.
    pub fn load(
        &self,
        jit: &mut JitAllocator,
        resolve: impl Fn(&ExternalName) -> *const u8,
    ) -> Result<LoadedCode, AsmError> {
        self.inner.load(jit, resolve)
    }

    /// Links finalized images into one. Label and patch handles from the
    /// individual images are not preserved (their offsets move).
    ///
    /// # Errors
    ///
    /// Returns an error if `images` is empty or linking fails.
    pub fn link(images: impl IntoIterator<Item = Finished>) -> Result<Finished, AsmError> {
        let mut linker = asmkit::Linker::new();
        let mut any = false;
        for image in images {
            linker.add_buffer(*image.inner);
            any = true;
        }
        if !any {
            return Err(AsmError::NoCodeGenerated);
        }
        Ok(Finished {
            inner: Box::new(linker.link()?),
            offsets: Vec::new(),
            label_base: 0,
            patch_base: 0,
            linked: true,
            virtual_patches: Vec::new(),
        })
    }

    /// Returns the underlying asmkit image.
    pub fn inner(&self) -> &CodeBufferFinalized {
        &self.inner
    }
}

/// Writes `value` into the immediate at `location` in loaded code.
///
/// `location` is the [`PatchLocation::Data`] of a `#[patch]`ed `move` or a
/// `#[patch_abs]` address slot (see [`Assembler::emit_patched`]).
///
/// # Errors
///
/// Returns an error if `location` is a jump, or `value` does not fit the
/// immediate.
///
/// # Safety
///
/// `span` must hold the image `location` came from, and no thread may run
/// the patched instruction while it is rewritten.
pub unsafe fn repatch_u64(
    jit: &mut JitAllocator,
    span: &mut Span,
    location: &PatchLocation,
    value: u64,
) -> Result<(), AsmError> {
    let PatchLocation::Data(data) = *location else {
        return Err(AsmError::InvalidArgument);
    };
    // SAFETY: forwarded from the caller.
    unsafe { asmkit::repatch_value_span(jit, span, data, value) }
}

/// Converts a Rust value into an assembler operand.
pub trait IntoOperand {
    /// Converts `self` into an operand, resolving vregs against `asm`.
    fn into_operand<const BACKWARD: bool>(self, asm: &Assembler<BACKWARD>) -> Op;
}

impl IntoOperand for Op {
    fn into_operand<const BACKWARD: bool>(self, _asm: &Assembler<BACKWARD>) -> Op {
        self
    }
}

macro_rules! imm_operand {
    ($($t:ty),* $(,)?) => {
        $(impl IntoOperand for $t {
            fn into_operand<const BACKWARD: bool>(self, _asm: &Assembler<BACKWARD>) -> Op {
                Op::Imm(self as i64)
            }
        })*
    };
}
imm_operand!(i8, i16, i32, i64, u8, u16, u32, u64, isize, usize);

impl IntoOperand for Gpr {
    fn into_operand<const BACKWARD: bool>(self, _asm: &Assembler<BACKWARD>) -> Op {
        Op::Gpr(self)
    }
}

impl IntoOperand for Fpr {
    fn into_operand<const BACKWARD: bool>(self, _asm: &Assembler<BACKWARD>) -> Op {
        Op::Fpr(self)
    }
}

impl IntoOperand for Mem {
    fn into_operand<const BACKWARD: bool>(self, _asm: &Assembler<BACKWARD>) -> Op {
        Op::Mem(self)
    }
}

impl IntoOperand for Extern {
    fn into_operand<const BACKWARD: bool>(self, _asm: &Assembler<BACKWARD>) -> Op {
        Op::Extern(self)
    }
}

impl IntoOperand for Label {
    fn into_operand<const BACKWARD: bool>(self, _asm: &Assembler<BACKWARD>) -> Op {
        Op::Label(Lbl::Bound(self))
    }
}

impl IntoOperand for VReg {
    fn into_operand<const BACKWARD: bool>(self, asm: &Assembler<BACKWARD>) -> Op {
        match self.kind() {
            RegKind::Gpr => Op::Gpr(asm.vreg_gpr(self)),
            RegKind::Fpr => Op::Fpr(asm.vreg_fpr(self)),
        }
    }
}

impl<T: IntoOperand + Copy> IntoOperand for &T {
    fn into_operand<const BACKWARD: bool>(self, asm: &Assembler<BACKWARD>) -> Op {
        (*self).into_operand(asm)
    }
}