winch-codegen 49.0.2

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

use cranelift_codegen::isa::aarch64;
use cranelift_codegen::isa::aarch64::inst::emit::{enc_arith_rrr, enc_move_wide, enc_movk};
use cranelift_codegen::isa::aarch64::inst::{
    ASIMDFPModImm, FpuToIntOp, MoveWideConst, NZCV, UImm5, VecALUModOp, VecExtendOp, VecRRLongOp,
    VecRRNarrowOp, VecRRPairLongOp, VecRRRLongModOp, VecRRRLongOp, VecShiftImmOp,
};
use cranelift_codegen::{
    Final, MachBuffer, MachBufferFinalized, MachInst, MachInstEmit, MachInstEmitState, MachLabel,
    Writable,
    ir::{ExternalName, MemFlagsData, SourceLoc, TrapCode, UserExternalNameRef},
    isa::aarch64::inst::{
        self, ALUOp, ALUOp3, AMode, BitOp, BranchTarget, Cond, CondBrKind, ExtendOp,
        FPULeftShiftImm, FPUOp1, FPUOp2,
        FPUOpRI::{self, UShr32, UShr64},
        FPUOpRIMod, FPURightShiftImm, FpuRoundMode, Imm12, ImmLogic, ImmShift, Inst, IntToFpuOp,
        PairAMode, ScalarSize, VecALUOp, VecLanesOp, VecMisc2, VectorSize,
        emit::{EmitInfo, EmitState},
    },
    settings,
};
use cranelift_codegen::{PatchRegion, VCodeConstant};
use regalloc2::RegClass;
use wasmtime_core::math::{f32_cvt_to_int_bounds, f64_cvt_to_int_bounds};

impl From<OperandSize> for inst::OperandSize {
    fn from(size: OperandSize) -> Self {
        match size {
            OperandSize::S32 => Self::Size32,
            OperandSize::S64 => Self::Size64,
            s => panic!("Invalid operand size {s:?}"),
        }
    }
}

impl From<IntCmpKind> for Cond {
    fn from(value: IntCmpKind) -> Self {
        match value {
            IntCmpKind::Eq => Cond::Eq,
            IntCmpKind::Ne => Cond::Ne,
            IntCmpKind::LtS => Cond::Lt,
            IntCmpKind::LtU => Cond::Lo,
            IntCmpKind::GtS => Cond::Gt,
            IntCmpKind::GtU => Cond::Hi,
            IntCmpKind::LeS => Cond::Le,
            IntCmpKind::LeU => Cond::Ls,
            IntCmpKind::GeS => Cond::Ge,
            IntCmpKind::GeU => Cond::Hs,
        }
    }
}

impl From<FloatCmpKind> for Cond {
    fn from(value: FloatCmpKind) -> Self {
        match value {
            FloatCmpKind::Eq => Cond::Eq,
            FloatCmpKind::Ne => Cond::Ne,
            FloatCmpKind::Lt => Cond::Mi,
            FloatCmpKind::Gt => Cond::Gt,
            FloatCmpKind::Le => Cond::Ls,
            FloatCmpKind::Ge => Cond::Ge,
        }
    }
}

impl From<OperandSize> for ScalarSize {
    fn from(size: OperandSize) -> ScalarSize {
        match size {
            OperandSize::S8 => ScalarSize::Size8,
            OperandSize::S16 => ScalarSize::Size16,
            OperandSize::S32 => ScalarSize::Size32,
            OperandSize::S64 => ScalarSize::Size64,
            OperandSize::S128 => ScalarSize::Size128,
        }
    }
}

impl From<ShiftKind> for ALUOp {
    fn from(kind: ShiftKind) -> Self {
        match kind {
            ShiftKind::Shl => ALUOp::Lsl,
            ShiftKind::ShrS => ALUOp::Asr,
            ShiftKind::ShrU => ALUOp::Lsr,
            ShiftKind::Rotr => ALUOp::Extr,
            ShiftKind::Rotl => ALUOp::Extr,
        }
    }
}

/// Low level assembler implementation for Aarch64.
pub(crate) struct Assembler {
    /// The machine instruction buffer.
    buffer: MachBuffer<Inst>,
    /// Constant emission information.
    emit_info: EmitInfo,
    /// Emission state.
    emit_state: EmitState,
    /// Constant pool.
    pool: ConstantPool,
}

impl Assembler {
    /// Create a new Aarch64 assembler.
    pub fn new(shared_flags: settings::Flags, isa_flags: aarch64::settings::Flags) -> Self {
        Self {
            buffer: MachBuffer::<Inst>::new(),
            emit_state: Default::default(),
            emit_info: EmitInfo::new(shared_flags, isa_flags),
            pool: ConstantPool::new(),
        }
    }
}

impl Assembler {
    /// Return the emitted code.
    pub fn finalize(mut self, loc: Option<SourceLoc>) -> MachBufferFinalized<Final> {
        let stencil = self
            .buffer
            .finish(&self.pool.constants(), self.emit_state.ctrl_plane_mut());
        stencil.apply_base_srcloc(loc.unwrap_or_default())
    }

    fn emit(&mut self, inst: Inst) {
        self.emit_with_island(inst, Inst::worst_case_size());
    }

    fn emit_with_island(&mut self, inst: Inst, needed_space: u32) {
        if self.buffer.island_needed(needed_space) {
            let label = self.buffer.get_label();
            let jmp = Inst::Jump {
                dest: BranchTarget::Label(label),
            };
            jmp.emit(&mut self.buffer, &self.emit_info, &mut self.emit_state);
            self.buffer
                .emit_island(needed_space, self.emit_state.ctrl_plane_mut());
            self.buffer
                .bind_label(label, self.emit_state.ctrl_plane_mut());
        }
        inst.emit(&mut self.buffer, &self.emit_info, &mut self.emit_state);
    }

    /// Adds a constant to the constant pool, returning its address.
    pub fn add_constant(&mut self, constant: &[u8]) -> VCodeConstant {
        let handle = self.pool.register(constant, &mut self.buffer);
        handle
    }

    /// Store a pair of registers.
    pub fn stp(&mut self, xt1: Reg, xt2: Reg, mem: PairAMode) {
        self.emit(Inst::StoreP64 {
            rt: xt1.into(),
            rt2: xt2.into(),
            mem,
            flags: MemFlagsData::trusted(),
        });
    }

    /// Store a register.
    pub fn str(&mut self, reg: Reg, mem: AMode, size: OperandSize, flags: MemFlagsData) {
        use OperandSize::*;
        let inst = match (reg.is_int(), size) {
            (_, S8) => Inst::Store8 {
                rd: reg.into(),
                mem,
                flags,
            },
            (_, S16) => Inst::Store16 {
                rd: reg.into(),
                mem,
                flags,
            },
            (true, S32) => Inst::Store32 {
                rd: reg.into(),
                mem,
                flags,
            },
            (false, S32) => Inst::FpuStore32 {
                rd: reg.into(),
                mem,
                flags,
            },
            (true, S64) => Inst::Store64 {
                rd: reg.into(),
                mem,
                flags,
            },
            (false, S64) => Inst::FpuStore64 {
                rd: reg.into(),
                mem,
                flags,
            },
            (_, S128) => Inst::FpuStore128 {
                rd: reg.into(),
                mem,
                flags,
            },
        };

        self.emit(inst);
    }

    /// Load a signed register.
    pub fn sload(&mut self, mem: AMode, rd: WritableReg, size: OperandSize, flags: MemFlagsData) {
        self.ldr(mem, rd, size, true, flags);
    }

    /// Load an unsigned register.
    pub fn uload(&mut self, mem: AMode, rd: WritableReg, size: OperandSize, flags: MemFlagsData) {
        self.ldr(mem, rd, size, false, flags);
    }

    /// Load address into a register.
    fn ldr(
        &mut self,
        mem: AMode,
        rd: WritableReg,
        size: OperandSize,
        signed: bool,
        flags: MemFlagsData,
    ) {
        use OperandSize::*;
        let writable_reg = rd.map(Into::into);

        let inst = match (rd.to_reg().is_int(), signed, size) {
            (_, false, S8) => Inst::ULoad8 {
                rd: writable_reg,
                mem,
                flags,
            },
            (_, true, S8) => Inst::SLoad8 {
                rd: writable_reg,
                mem,
                flags,
            },
            (_, false, S16) => Inst::ULoad16 {
                rd: writable_reg,
                mem,
                flags,
            },
            (_, true, S16) => Inst::SLoad16 {
                rd: writable_reg,
                mem,
                flags,
            },
            (true, false, S32) => Inst::ULoad32 {
                rd: writable_reg,
                mem,
                flags,
            },
            (false, _, S32) => Inst::FpuLoad32 {
                rd: writable_reg,
                mem,
                flags,
            },
            (true, true, S32) => Inst::SLoad32 {
                rd: writable_reg,
                mem,
                flags,
            },
            (true, _, S64) => Inst::ULoad64 {
                rd: writable_reg,
                mem,
                flags,
            },
            (false, _, S64) => Inst::FpuLoad64 {
                rd: writable_reg,
                mem,
                flags,
            },
            (_, _, S128) => Inst::FpuLoad128 {
                rd: writable_reg,
                mem,
                flags,
            },
        };

        self.emit(inst);
    }

    /// Load a pair of registers.
    pub fn ldp(&mut self, xt1: Reg, xt2: Reg, mem: PairAMode) {
        let writable_xt1 = Writable::from_reg(xt1.into());
        let writable_xt2 = Writable::from_reg(xt2.into());

        self.emit(Inst::LoadP64 {
            rt: writable_xt1,
            rt2: writable_xt2,
            mem,
            flags: MemFlagsData::trusted(),
        });
    }

    /// Emit a series of instructions to move an arbitrary 64-bit immediate
    /// into the destination register.
    /// The emitted instructions will depend on the destination register class.
    pub fn mov_ir(&mut self, rd: WritableReg, imm: Imm, size: OperandSize) {
        match rd.to_reg().class() {
            RegClass::Int => {
                Inst::load_constant(rd.map(Into::into), imm.unwrap_as_u64())
                    .into_iter()
                    .for_each(|i| self.emit(i));
            }
            RegClass::Float => {
                let modimm = match imm {
                    Imm::V128(_) => None,
                    _ => ASIMDFPModImm::maybe_from_u64(imm.unwrap_as_u64(), size.into()),
                };
                match modimm {
                    Some(imm) => {
                        self.emit(Inst::FpuMoveFPImm {
                            rd: rd.map(Into::into),
                            imm,
                            size: size.into(),
                        });
                    }
                    _ => {
                        let constant = self.add_constant(&imm.to_bytes());
                        let addr = AMode::Const { addr: constant };
                        self.uload(addr, rd, size, TRUSTED_FLAGS);
                    }
                }
            }
            _ => unreachable!(),
        }
    }

    /// Register to register move.
    pub fn mov_rr(&mut self, rm: Reg, rd: WritableReg, size: OperandSize) {
        let writable_rd = rd.map(Into::into);
        self.emit(Inst::Mov {
            size: size.into(),
            rd: writable_rd,
            rm: rm.into(),
        });
    }

    /// Floating point register to register move.
    pub fn fmov_rr(&mut self, rn: Reg, rd: WritableReg, size: OperandSize) {
        let writable = rd.map(Into::into);
        let inst = match size {
            OperandSize::S32 => Inst::FpuMove32 {
                rd: writable,
                rn: rn.into(),
            },
            OperandSize::S64 => Inst::FpuMove64 {
                rd: writable,
                rn: rn.into(),
            },
            OperandSize::S128 => Inst::FpuMove128 {
                rd: writable,
                rn: rn.into(),
            },
            _ => unreachable!(),
        };

        self.emit(inst);
    }

    pub fn mov_to_fpu(&mut self, rn: Reg, rd: WritableReg, size: OperandSize) {
        let writable_rd = rd.map(Into::into);
        self.emit(Inst::MovToFpu {
            size: size.into(),
            rd: writable_rd,
            rn: rn.into(),
        });
    }

    pub fn mov_from_vec(&mut self, rn: Reg, rd: WritableReg, idx: u8, size: OperandSize) {
        self.emit(Inst::MovFromVec {
            rd: rd.map(Into::into),
            rn: rn.into(),
            idx,
            size: size.into(),
        });
    }

    /// Add immediate and register.
    pub fn add_ir(&mut self, imm: Imm12, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rri(ALUOp::Add, imm, rn, rd, size);
    }

    /// Add immediate and register, setting overflow flags.
    pub fn adds_ir(&mut self, imm: Imm12, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rri(ALUOp::AddS, imm, rn, rd, size);
    }

    /// Add with three registers.
    pub fn add_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rrr_extend(ALUOp::Add, rm, rn, rd, size, ExtendOp::UXTX);
    }

    /// Add with three registers and explicit extend operation.
    pub fn add_rrr_with_extend(
        &mut self,
        rm: Reg,
        rn: Reg,
        rd: WritableReg,
        size: OperandSize,
        extendop: ExtendOp,
    ) {
        self.alu_rrr_extend(ALUOp::Add, rm, rn, rd, size, extendop);
    }

    /// Add with three registers, setting overflow flags.
    pub fn adds_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rrr_extend(ALUOp::AddS, rm, rn, rd, size, ExtendOp::UXTX);
    }

    /// Add with carry, three registers.
    pub fn adc_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rrr(ALUOp::Adc, rm, rn, rd, size);
    }

    /// Vector extend: widen the low or high half's lanes to `lane_size`.
    pub fn vec_extend(
        &mut self,
        t: VecExtendOp,
        rn: Reg,
        rd: WritableReg,
        high_half: bool,
        lane_size: ScalarSize,
    ) {
        self.emit(Inst::VecExtend {
            t,
            rd: rd.map(Into::into),
            rn: rn.into(),
            high_half,
            lane_size,
        });
    }

    /// Vector narrow: saturate `rn`'s lanes to `lane_size` into the low or
    /// high half of `rd`; the high-half form preserves `rd`'s other lanes.
    pub fn vec_narrow(
        &mut self,
        op: VecRRNarrowOp,
        rn: Reg,
        rd: WritableReg,
        high_half: bool,
        lane_size: ScalarSize,
    ) {
        if high_half {
            self.emit(Inst::VecRRNarrowHigh {
                op,
                rd: rd.map(Into::into),
                ri: rd.to_reg().into(),
                rn: rn.into(),
                lane_size,
            });
        } else {
            self.emit(Inst::VecRRNarrowLow {
                op,
                rd: rd.map(Into::into),
                rn: rn.into(),
                lane_size,
            });
        }
    }
    /// Duplicate a general-purpose register's value into every lane of a
    /// vector register.
    pub fn vec_dup(&mut self, rn: Reg, rd: WritableReg, size: VectorSize) {
        self.emit(Inst::VecDup {
            rd: rd.map(Into::into),
            rn: rn.into(),
            size,
        });
    }

    /// Signed move from a vector element to a GPR.
    pub fn mov_from_vec_signed(
        &mut self,
        rn: Reg,
        rd: WritableReg,
        idx: u8,
        size: VectorSize,
        scalar_size: OperandSize,
    ) {
        self.emit(Inst::MovFromVecSigned {
            rd: rd.map(Into::into),
            rn: rn.into(),
            idx,
            size,
            scalar_size: scalar_size.into(),
        });
    }

    /// Move from a vector element to a scalar float register.
    pub fn fpu_move_from_vec(&mut self, rn: Reg, rd: WritableReg, idx: u8, size: VectorSize) {
        self.emit(Inst::FpuMoveFromVec {
            rd: rd.map(Into::into),
            rn: rn.into(),
            idx,
            size,
        });
    }

    /// Move a GPR into a vector element, preserving the other lanes.
    pub fn mov_to_vec(&mut self, rn: Reg, rd: WritableReg, idx: u8, size: VectorSize) {
        self.emit(Inst::MovToVec {
            rd: rd.map(Into::into),
            ri: rd.to_reg().into(),
            rn: rn.into(),
            idx,
            size,
        });
    }

    /// Move a vector element into a vector element, preserving the other
    /// lanes.
    pub fn vec_mov_element(
        &mut self,
        rn: Reg,
        rd: WritableReg,
        dest_idx: u8,
        src_idx: u8,
        size: VectorSize,
    ) {
        self.emit(Inst::VecMovElement {
            rd: rd.map(Into::into),
            ri: rd.to_reg().into(),
            rn: rn.into(),
            dest_idx,
            src_idx,
            size,
        });
    }

    /// Duplicate one lane of a vector register into every lane of a vector
    /// register.
    pub fn vec_dup_elem(&mut self, rn: Reg, rd: WritableReg, size: VectorSize, lane: u8) {
        self.emit(Inst::VecDupFromFpu {
            rd: rd.map(Into::into),
            rn: rn.into(),
            size,
            lane,
        });
    }

    /// Vector widening multiply: multiply the low or high halves of `rn` and
    /// `rm` into lanes of twice the source lane width.
    pub fn vec_rrr_long(
        &mut self,
        alu_op: VecRRRLongOp,
        rn: Reg,
        rm: Reg,
        rd: WritableReg,
        high_half: bool,
    ) {
        self.emit(Inst::VecRRRLong {
            alu_op,
            rd: rd.map(Into::into),
            rn: rn.into(),
            rm: rm.into(),
            high_half,
        });
    }

    /// Vector widening multiply accumulate: multiply the low or high halves of
    /// `rn` and `rm`, adding the result to lanes of twice the source lane width.
    pub fn vec_rrrr_long(
        &mut self,
        alu_op: VecRRRLongModOp,
        rn: Reg,
        rm: Reg,
        rd: WritableReg,
        high_half: bool,
    ) {
        self.emit(Inst::VecRRRLongMod {
            alu_op,
            rd: rd.map(Into::into),
            ri: rd.to_reg().into(),
            rn: rn.into(),
            rm: rm.into(),
            high_half,
        });
    }

    /// Vector pairwise widening add: sum adjacent lane pairs of `rn` into
    /// lanes of twice the source lane width.
    pub fn vec_rr_pair_long(&mut self, op: VecRRPairLongOp, rn: Reg, rd: WritableReg) {
        self.emit(Inst::VecRRPairLong {
            op,
            rd: rd.map(Into::into),
            rn: rn.into(),
        });
    }

    /// Vector lengthening operation: widen the low or high half's lanes.
    pub fn vec_rr_long(&mut self, op: VecRRLongOp, rn: Reg, rd: WritableReg, high_half: bool) {
        self.emit(Inst::VecRRLong {
            op,
            rd: rd.map(Into::into),
            rn: rn.into(),
            high_half,
        });
    }

    /// Vector three-register ALU operation whose destination is also an input
    pub fn vec_rrr_mod(
        &mut self,
        alu_op: VecALUModOp,
        rn: Reg,
        rm: Reg,
        rd: WritableReg,
        size: VectorSize,
    ) {
        self.emit(Inst::VecRRRMod {
            alu_op,
            rd: rd.map(Into::into),
            ri: rd.to_reg().into(),
            rn: rn.into(),
            rm: rm.into(),
            size,
        });
    }

    /// Vector two register miscellaneous instruction.
    pub fn vec_misc(&mut self, op: VecMisc2, rn: Reg, rd: WritableReg, size: VectorSize) {
        self.emit(Inst::VecMisc {
            op,
            rd: rd.map(Into::into),
            rn: rn.into(),
            size,
        });
    }

    /// Vector table lookup: index `rn`'s bytes by `rm`, zeroing out of range
    /// lanes.
    pub fn vec_tbl(&mut self, rn: Reg, rm: Reg, rd: WritableReg) {
        self.emit(Inst::VecTbl {
            rd: rd.map(Into::into),
            rn: rn.into(),
            rm: rm.into(),
        });
    }

    /// Vector table lookup, leaving out of range lanes of `rd` unmodified.
    pub fn vec_tbl_ext(&mut self, rn: Reg, rm: Reg, rd: WritableReg) {
        self.emit(Inst::VecTblExt {
            rd: rd.map(Into::into),
            ri: rd.to_reg().into(),
            rn: rn.into(),
            rm: rm.into(),
        });
    }

    /// Vector shift by immediate.
    pub fn vec_shift_imm(
        &mut self,
        op: VecShiftImmOp,
        imm: u8,
        rn: Reg,
        rd: WritableReg,
        size: VectorSize,
    ) {
        self.emit(Inst::VecShiftImm {
            op,
            rd: rd.map(Into::into),
            rn: rn.into(),
            size,
            imm,
        });
    }

    /// Extract a vector from a pair of vectors, starting at byte `imm4`.
    pub fn vec_extract(&mut self, rn: Reg, rm: Reg, rd: WritableReg, imm4: u8) {
        self.emit(Inst::VecExtract {
            rd: rd.map(Into::into),
            rn: rn.into(),
            rm: rm.into(),
            imm4,
        });
    }

    /// Load a 128-bit constant into a vector register.
    pub fn vec_load_const(&mut self, constant: &[u8; 16], rd: WritableReg) {
        let handle = self.add_constant(constant);
        self.uload(
            AMode::Const { addr: handle },
            rd,
            OperandSize::S128,
            TRUSTED_FLAGS,
        );
    }

    /// Vector reduction across lanes
    pub fn vec_lanes(&mut self, op: VecLanesOp, rn: Reg, rd: WritableReg, size: VectorSize) {
        self.emit(Inst::VecLanes {
            op,
            rd: rd.map(Into::into),
            rn: rn.into(),
            size,
        });
    }

    /// Load a scalar and replicate it into all vector lanes.
    pub fn vec_load_replicate(
        &mut self,
        rn: Reg,
        rd: WritableReg,
        size: VectorSize,
        flags: MemFlagsData,
    ) {
        self.emit(Inst::VecLoadReplicate {
            rd: rd.map(Into::into),
            rn: rn.into(),
            size,
            flags,
        });
    }

    /// Vector ALU op
    pub fn vec_rrr(
        &mut self,
        alu_op: VecALUOp,
        rn: Reg,
        rm: Reg,
        rd: WritableReg,
        size: VectorSize,
    ) {
        self.emit(Inst::VecRRR {
            alu_op,
            rd: rd.map(Into::into),
            rn: rn.into(),
            rm: rm.into(),
            size,
        });
    }

    /// Add across Vector.
    pub fn addv(&mut self, rn: Reg, rd: WritableReg, size: VectorSize) {
        self.emit(Inst::VecLanes {
            op: VecLanesOp::Addv,
            rd: rd.map(Into::into),
            rn: rn.into(),
            size,
        });
    }

    /// Subtract immediate and register.
    pub fn sub_ir(&mut self, imm: Imm12, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rri(ALUOp::Sub, imm, rn, rd, size);
    }

    /// Subtract immediate and register, setting flags.
    pub fn subs_ir(&mut self, imm: Imm12, rn: Reg, size: OperandSize) {
        self.alu_rri(ALUOp::SubS, imm, rn, writable!(regs::zero()), size);
    }

    /// Subtract with three registers.
    pub fn sub_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rrr_extend(ALUOp::Sub, rm, rn, rd, size, ExtendOp::UXTX);
    }

    /// Negate a general-purpose register.
    pub fn neg_rr(&mut self, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rrr(ALUOp::Sub, rn, zero(), rd, size);
    }

    /// Subtract with three registers, setting flags.
    pub fn subs_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rrr_extend(ALUOp::SubS, rm, rn, rd, size, ExtendOp::UXTX);
    }

    /// Subtract with carry, three registers.
    pub fn sbc_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rrr(ALUOp::Sbc, rm, rn, rd, size);
    }

    /// Multiply with three registers.
    pub fn mul_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rrrr(ALUOp3::MAdd, rm, rn, rd, regs::zero(), size);
    }

    /// Unsigned multiply, writing the high 64 bits of the 128-bit result.
    pub fn umulh_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg) {
        self.alu_rrr(ALUOp::UMulH, rm, rn, rd, OperandSize::S64);
    }

    /// Signed multiply, writing the high 64 bits of the 128-bit result.
    pub fn smulh_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg) {
        self.alu_rrr(ALUOp::SMulH, rm, rn, rd, OperandSize::S64);
    }

    /// Signed/unsigned division with three registers.
    pub fn div_rrr(
        &mut self,
        divisor: Reg,
        dividend: Reg,
        dest: Writable<Reg>,
        kind: DivKind,
        size: OperandSize,
    ) {
        // Check for division by 0.
        self.trapz(divisor, TrapCode::INTEGER_DIVISION_BY_ZERO, size);

        // check for overflow
        if kind == DivKind::Signed {
            // Check for divisor overflow.
            self.alu_rri(
                ALUOp::AddS,
                Imm12::maybe_from_u64(1).expect("1 to fit in 12 bits"),
                divisor,
                writable!(zero()),
                size,
            );

            // Check if the dividend is 1.
            self.emit(Inst::CCmpImm {
                size: size.into(),
                rn: dividend.into(),
                imm: UImm5::maybe_from_u8(1).expect("1 fits in 5 bits"),
                nzcv: NZCV::new(false, false, false, false),
                cond: Cond::Eq,
            });

            // Finally, trap if the previous operation overflowed.
            self.trapif(Cond::Vs, TrapCode::INTEGER_OVERFLOW);
        }

        // `cranelift-codegen` doesn't support emitting sdiv for anything but I64,
        // we therefore sign-extend the operand.
        // see: https://github.com/bytecodealliance/wasmtime/issues/9766
        let size = if size == OperandSize::S32 && kind == DivKind::Signed {
            self.extend(
                divisor,
                writable!(divisor),
                ExtendKind::Signed(Extend::<Signed>::I64Extend32),
            );
            self.extend(
                dividend,
                writable!(dividend),
                ExtendKind::Signed(Extend::<Signed>::I64Extend32),
            );
            OperandSize::S64
        } else {
            size
        };

        let op = match kind {
            DivKind::Signed => ALUOp::SDiv,
            DivKind::Unsigned => ALUOp::UDiv,
        };

        self.alu_rrr(op, divisor, dividend, dest.map(Into::into), size);
    }

    /// Signed/unsigned remainder operation with three registers.
    pub fn rem_rrr(
        &mut self,
        divisor: Reg,
        dividend: Reg,
        dest: Writable<Reg>,
        scratch: WritableReg,
        kind: RemKind,
        size: OperandSize,
    ) {
        // Check for division by 0
        self.trapz(divisor, TrapCode::INTEGER_DIVISION_BY_ZERO, size);

        // `cranelift-codegen` doesn't support emitting sdiv for anything but I64,
        // we therefore sign-extend the operand.
        // see: https://github.com/bytecodealliance/wasmtime/issues/9766
        let size = if size == OperandSize::S32 && kind.is_signed() {
            self.extend(
                divisor,
                writable!(divisor),
                ExtendKind::Signed(Extend::<Signed>::I64Extend32),
            );
            self.extend(
                dividend,
                writable!(dividend),
                ExtendKind::Signed(Extend::<Signed>::I64Extend32),
            );
            OperandSize::S64
        } else {
            size
        };

        let op = match kind {
            RemKind::Signed => ALUOp::SDiv,
            RemKind::Unsigned => ALUOp::UDiv,
        };

        self.alu_rrr(op, divisor, dividend, scratch, size);

        self.alu_rrrr(
            ALUOp3::MSub,
            scratch.to_reg(),
            divisor,
            dest.map(Into::into),
            dividend,
            size,
        );
    }

    /// And with three registers.
    pub fn and_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rrr(ALUOp::And, rm, rn, rd, size);
    }

    /// And immediate and register.
    pub fn and_ir(&mut self, imm: ImmLogic, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rri_logic(ALUOp::And, imm, rn, rd, size);
    }

    /// Or with three registers.
    pub fn or_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rrr(ALUOp::Orr, rm, rn, rd, size);
    }

    /// Or immediate and register.
    pub fn or_ir(&mut self, imm: ImmLogic, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rri_logic(ALUOp::Orr, imm, rn, rd, size);
    }

    /// Xor with three registers.
    pub fn xor_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rrr(ALUOp::Eor, rm, rn, rd, size);
    }

    /// Xor immediate and register.
    pub fn xor_ir(&mut self, imm: ImmLogic, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.alu_rri_logic(ALUOp::Eor, imm, rn, rd, size);
    }

    /// Shift with three registers.
    pub fn shift_rrr(
        &mut self,
        rm: Reg,
        rn: Reg,
        rd: WritableReg,
        kind: ShiftKind,
        size: OperandSize,
    ) {
        let shift_op: ALUOp = kind.into();
        // In the case of rotate left, we negate the register containing the
        // shift value.
        if kind == ShiftKind::Rotl {
            self.alu_rrr(ALUOp::Sub, rm, regs::zero(), writable!(rm), size);
            self.alu_rrr(shift_op, rm, rn, rd, size);
        } else {
            self.alu_rrr(shift_op, rm, rn, rd, size);
        }
    }

    /// Shift immediate and register.
    pub fn shift_ir(
        &mut self,
        imm: ImmShift,
        rn: Reg,
        rd: WritableReg,
        kind: ShiftKind,
        size: OperandSize,
    ) {
        let shift_op: ALUOp = kind.into();
        // In the case of rotate left, we emit rotate right with type_size -
        // value.
        if kind == ShiftKind::Rotl {
            let value_size = size.num_bits();
            let mut imm_val = value_size.wrapping_sub(imm.value());
            imm_val &= value_size - 1;
            let negated_imm = ImmShift::maybe_from_u64(imm_val as u64).unwrap();

            self.alu_rri_shift(shift_op, negated_imm, rn, rd, size);
        } else {
            self.alu_rri_shift(shift_op, imm, rn, rd, size);
        }
    }

    /// Count Leading Zeros.
    pub fn clz(&mut self, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.bit_rr(BitOp::Clz, rn, rd, size);
    }

    /// Reverse Bits reverses the bit order in a register.
    pub fn rbit(&mut self, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.bit_rr(BitOp::RBit, rn, rd, size);
    }

    /// Float add with three registers.
    pub fn fadd_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.fpu_rrr(FPUOp2::Add, rm, rn, rd, size);
    }

    /// Float sub with three registers.
    pub fn fsub_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.fpu_rrr(FPUOp2::Sub, rm, rn, rd, size);
    }

    /// Float multiply with three registers.
    pub fn fmul_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.fpu_rrr(FPUOp2::Mul, rm, rn, rd, size);
    }

    /// Float division with three registers.
    pub fn fdiv_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.fpu_rrr(FPUOp2::Div, rm, rn, rd, size);
    }

    /// Float max with three registers.
    pub fn fmax_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.fpu_rrr(FPUOp2::Max, rm, rn, rd, size);
    }

    /// Float min with three registers.
    pub fn fmin_rrr(&mut self, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.fpu_rrr(FPUOp2::Min, rm, rn, rd, size);
    }

    /// Float neg with two registers.
    pub fn fneg_rr(&mut self, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.fpu_rr(FPUOp1::Neg, rn, rd, size);
    }

    /// Float abs with two registers.
    pub fn fabs_rr(&mut self, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.fpu_rr(FPUOp1::Abs, rn, rd, size);
    }

    /// Float sqrt with two registers.
    pub fn fsqrt_rr(&mut self, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.fpu_rr(FPUOp1::Sqrt, rn, rd, size);
    }

    /// Float round (ceil, trunc, floor) with two registers.
    pub fn fround_rr(&mut self, rn: Reg, rd: WritableReg, mode: RoundingMode, size: OperandSize) {
        let fpu_mode = match (mode, size) {
            (RoundingMode::Nearest, OperandSize::S32) => FpuRoundMode::Nearest32,
            (RoundingMode::Up, OperandSize::S32) => FpuRoundMode::Plus32,
            (RoundingMode::Down, OperandSize::S32) => FpuRoundMode::Minus32,
            (RoundingMode::Zero, OperandSize::S32) => FpuRoundMode::Zero32,
            (RoundingMode::Nearest, OperandSize::S64) => FpuRoundMode::Nearest64,
            (RoundingMode::Up, OperandSize::S64) => FpuRoundMode::Plus64,
            (RoundingMode::Down, OperandSize::S64) => FpuRoundMode::Minus64,
            (RoundingMode::Zero, OperandSize::S64) => FpuRoundMode::Zero64,
            (m, o) => panic!("Invalid rounding mode or operand size {m:?}, {o:?}"),
        };
        self.fpu_round(fpu_mode, rn, rd)
    }

    /// Float unsigned shift right with two registers and an immediate.
    pub fn fushr_rri(&mut self, rn: Reg, rd: WritableReg, amount: u8, size: OperandSize) {
        let imm = FPURightShiftImm {
            amount,
            lane_size_in_bits: size.num_bits(),
        };
        let ushr = match size {
            OperandSize::S32 => UShr32(imm),
            OperandSize::S64 => UShr64(imm),
            _ => unreachable!(),
        };
        self.fpu_rri(ushr, rn, rd)
    }

    /// Float unsigned shift left and insert with three registers
    /// and an immediate.
    pub fn fsli_rri_mod(
        &mut self,
        ri: Reg,
        rn: Reg,
        rd: WritableReg,
        amount: u8,
        size: OperandSize,
    ) {
        let imm = FPULeftShiftImm {
            amount,
            lane_size_in_bits: size.num_bits(),
        };
        let sli = match size {
            OperandSize::S32 => FPUOpRIMod::Sli32(imm),
            OperandSize::S64 => FPUOpRIMod::Sli64(imm),
            _ => unreachable!(),
        };
        self.fpu_rri_mod(sli, ri, rn, rd)
    }

    /// Float compare.
    pub fn fcmp(&mut self, rn: Reg, rm: Reg, size: OperandSize) {
        self.emit(Inst::FpuCmp {
            size: size.into(),
            rn: rn.into(),
            rm: rm.into(),
        })
    }

    /// Convert an signed integer to a float.
    pub fn cvt_sint_to_float(
        &mut self,
        rn: Reg,
        rd: WritableReg,
        src_size: OperandSize,
        dst_size: OperandSize,
    ) {
        let op = match (src_size, dst_size) {
            (OperandSize::S32, OperandSize::S32) => IntToFpuOp::I32ToF32,
            (OperandSize::S64, OperandSize::S32) => IntToFpuOp::I64ToF32,
            (OperandSize::S32, OperandSize::S64) => IntToFpuOp::I32ToF64,
            (OperandSize::S64, OperandSize::S64) => IntToFpuOp::I64ToF64,
            _ => unreachable!(),
        };

        self.emit(Inst::IntToFpu {
            op,
            rd: rd.map(Into::into),
            rn: rn.into(),
        });
    }

    /// Convert an unsigned integer to a float.
    pub fn cvt_uint_to_float(
        &mut self,
        rn: Reg,
        rd: WritableReg,
        src_size: OperandSize,
        dst_size: OperandSize,
    ) {
        let op = match (src_size, dst_size) {
            (OperandSize::S32, OperandSize::S32) => IntToFpuOp::U32ToF32,
            (OperandSize::S64, OperandSize::S32) => IntToFpuOp::U64ToF32,
            (OperandSize::S32, OperandSize::S64) => IntToFpuOp::U32ToF64,
            (OperandSize::S64, OperandSize::S64) => IntToFpuOp::U64ToF64,
            _ => unreachable!(),
        };

        self.emit(Inst::IntToFpu {
            op,
            rd: rd.map(Into::into),
            rn: rn.into(),
        });
    }

    /// Change precision of float.
    pub fn cvt_float_to_float(
        &mut self,
        rn: Reg,
        rd: WritableReg,
        src_size: OperandSize,
        dst_size: OperandSize,
    ) {
        let (fpu_op, size) = match (src_size, dst_size) {
            (OperandSize::S32, OperandSize::S64) => (FPUOp1::Cvt32To64, ScalarSize::Size32),
            (OperandSize::S64, OperandSize::S32) => (FPUOp1::Cvt64To32, ScalarSize::Size64),
            _ => unimplemented!(),
        };
        self.emit(Inst::FpuRR {
            fpu_op,
            size,
            rd: rd.map(Into::into),
            rn: rn.into(),
        });
    }

    /// Return instruction.
    pub fn ret(&mut self) {
        self.emit(Inst::Ret {});
    }

    /// An unconditional branch.
    pub fn jmp(&mut self, target: MachLabel) {
        self.emit(Inst::Jump {
            dest: BranchTarget::Label(target),
        });
    }

    /// A conditional branch.
    pub fn jmp_if(&mut self, kind: Cond, taken: MachLabel) {
        self.emit(Inst::CondBr {
            taken: BranchTarget::Label(taken),
            not_taken: BranchTarget::ResolvedOffset(4),
            kind: CondBrKind::Cond(kind),
        });
    }

    /// Emits a jump table sequence.
    pub fn jmp_table(
        &mut self,
        targets: &[MachLabel],
        default: MachLabel,
        index: Reg,
        tmp1: Reg,
        tmp2: Reg,
    ) {
        self.emit_with_island(
            Inst::JTSequence {
                default,
                targets: Box::new(targets.to_vec()),
                ridx: index.into(),
                rtmp1: Writable::from_reg(tmp1.into()),
                rtmp2: Writable::from_reg(tmp2.into()),
            },
            // number of bytes needed for the jumptable sequence:
            // 4 bytes per instruction, with 8 instructions base + the size of
            // the jumptable more.
            (4 * (8 + targets.len())).try_into().unwrap(),
        );
    }

    /// Conditional Set sets the destination register to 1 if the condition
    /// is true, and otherwise sets it to 0.
    pub fn cset(&mut self, rd: WritableReg, cond: Cond) {
        self.emit(Inst::CSet {
            rd: rd.map(Into::into),
            cond,
        });
    }

    /// If the condition is true, `csel` writes rn to rd. If the
    /// condition is false, it writes rm to rd
    pub fn csel(&mut self, rn: Reg, rm: Reg, rd: WritableReg, cond: Cond) {
        self.emit(Inst::CSel {
            rd: rd.map(Into::into),
            rn: rn.into(),
            rm: rm.into(),
            cond,
        });
    }

    /// If the condition is true, `csel` writes rn to rd. If the
    /// condition is false, it writes rm to rd
    pub fn fpu_csel(&mut self, rn: Reg, rm: Reg, rd: WritableReg, cond: Cond, size: OperandSize) {
        match size {
            OperandSize::S32 => {
                self.emit(Inst::FpuCSel32 {
                    rd: rd.map(Into::into),
                    rn: rn.into(),
                    rm: rm.into(),
                    cond,
                });
            }
            OperandSize::S64 => {
                self.emit(Inst::FpuCSel64 {
                    rd: rd.map(Into::into),
                    rn: rn.into(),
                    rm: rm.into(),
                    cond,
                });
            }
            OperandSize::S128 => {
                self.emit(Inst::VecCSel {
                    rd: rd.map(Into::into),
                    rn: rn.into(),
                    rm: rm.into(),
                    cond,
                });
            }
            _ => todo!(),
        }
    }

    /// Population count per byte.
    pub fn cnt(&mut self, rd: WritableReg) {
        self.emit(Inst::VecMisc {
            op: VecMisc2::Cnt,
            rd: rd.map(Into::into),
            rn: rd.to_reg().into(),
            size: VectorSize::Size8x8,
        });
    }

    pub fn extend(&mut self, rn: Reg, rd: WritableReg, kind: ExtendKind) {
        self.emit(Inst::Extend {
            rd: rd.map(Into::into),
            rn: rn.into(),
            signed: kind.signed(),
            from_bits: kind.from_bits(),
            to_bits: kind.to_bits(),
        })
    }

    /// Bitwise AND (shifted register), setting flags.
    pub fn ands_rr(&mut self, rn: Reg, rm: Reg, size: OperandSize) {
        self.alu_rrr(ALUOp::AndS, rm, rn, writable!(regs::zero()), size);
    }

    /// Permanently Undefined.
    pub fn udf(&mut self, code: TrapCode) {
        self.emit(Inst::Udf { trap_code: code });
    }

    /// Conditional trap.
    pub fn trapif(&mut self, cc: Cond, code: TrapCode) {
        self.emit(Inst::TrapIf {
            kind: CondBrKind::Cond(cc),
            trap_code: code,
        });
    }

    /// Trap if `rn` is zero.
    pub fn trapz(&mut self, rn: Reg, code: TrapCode, size: OperandSize) {
        self.emit(Inst::TrapIf {
            kind: CondBrKind::Zero(rn.into(), size.into()),
            trap_code: code,
        });
    }

    // Helpers for ALU operations.

    fn alu_rri(&mut self, op: ALUOp, imm: Imm12, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.emit(Inst::AluRRImm12 {
            alu_op: op,
            size: size.into(),
            rd: rd.map(Into::into),
            rn: rn.into(),
            imm12: imm,
        });
    }

    fn alu_rri_logic(
        &mut self,
        op: ALUOp,
        imm: ImmLogic,
        rn: Reg,
        rd: WritableReg,
        size: OperandSize,
    ) {
        self.emit(Inst::AluRRImmLogic {
            alu_op: op,
            size: size.into(),
            rd: rd.map(Into::into),
            rn: rn.into(),
            imml: imm,
        });
    }

    fn alu_rri_shift(
        &mut self,
        op: ALUOp,
        imm: ImmShift,
        rn: Reg,
        rd: WritableReg,
        size: OperandSize,
    ) {
        self.emit(Inst::AluRRImmShift {
            alu_op: op,
            size: size.into(),
            rd: rd.map(Into::into),
            rn: rn.into(),
            immshift: imm,
        });
    }

    fn alu_rrr(&mut self, op: ALUOp, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.emit(Inst::AluRRR {
            alu_op: op,
            size: size.into(),
            rd: rd.map(Into::into),
            rn: rn.into(),
            rm: rm.into(),
        });
    }

    fn alu_rrr_extend(
        &mut self,
        op: ALUOp,
        rm: Reg,
        rn: Reg,
        rd: WritableReg,
        size: OperandSize,
        extendop: ExtendOp,
    ) {
        self.emit(Inst::AluRRRExtend {
            alu_op: op,
            size: size.into(),
            rd: rd.map(Into::into),
            rn: rn.into(),
            rm: rm.into(),
            extendop,
        });
    }

    fn alu_rrrr(
        &mut self,
        op: ALUOp3,
        rm: Reg,
        rn: Reg,
        rd: WritableReg,
        ra: Reg,
        size: OperandSize,
    ) {
        self.emit(Inst::AluRRRR {
            alu_op: op,
            size: size.into(),
            rd: rd.map(Into::into),
            rn: rn.into(),
            rm: rm.into(),
            ra: ra.into(),
        });
    }

    fn fpu_rrr(&mut self, op: FPUOp2, rm: Reg, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.emit(Inst::FpuRRR {
            fpu_op: op,
            size: size.into(),
            rd: rd.map(Into::into),
            rn: rn.into(),
            rm: rm.into(),
        });
    }

    fn fpu_rri(&mut self, op: FPUOpRI, rn: Reg, rd: WritableReg) {
        self.emit(Inst::FpuRRI {
            fpu_op: op,
            rd: rd.map(Into::into),
            rn: rn.into(),
        });
    }

    fn fpu_rri_mod(&mut self, op: FPUOpRIMod, ri: Reg, rn: Reg, rd: WritableReg) {
        self.emit(Inst::FpuRRIMod {
            fpu_op: op,
            rd: rd.map(Into::into),
            ri: ri.into(),
            rn: rn.into(),
        });
    }

    fn fpu_rr(&mut self, op: FPUOp1, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.emit(Inst::FpuRR {
            fpu_op: op,
            size: size.into(),
            rd: rd.map(Into::into),
            rn: rn.into(),
        });
    }

    fn fpu_round(&mut self, op: FpuRoundMode, rn: Reg, rd: WritableReg) {
        self.emit(Inst::FpuRound {
            op,
            rd: rd.map(Into::into),
            rn: rn.into(),
        });
    }

    fn bit_rr(&mut self, op: BitOp, rn: Reg, rd: WritableReg, size: OperandSize) {
        self.emit(Inst::BitRR {
            op,
            size: size.into(),
            rd: rd.map(Into::into),
            rn: rn.into(),
        });
    }

    /// Get a label from the underlying machine code buffer.
    pub fn get_label(&mut self) -> MachLabel {
        self.buffer.get_label()
    }

    /// Get a mutable reference to underlying
    /// machine buffer.
    pub fn buffer_mut(&mut self) -> &mut MachBuffer<Inst> {
        &mut self.buffer
    }

    /// Get a reference to the underlying machine buffer.
    pub fn buffer(&self) -> &MachBuffer<Inst> {
        &self.buffer
    }

    /// Emit a direct call to a function defined locally and
    /// referenced to by `name`.
    pub fn call_with_name(&mut self, name: UserExternalNameRef, call_conv: CallingConvention) {
        self.emit(Inst::Call {
            info: Box::new(cranelift_codegen::CallInfo::empty(
                ExternalName::user(name),
                call_conv.into(),
            )),
        })
    }

    /// Emit an indirect call to a function whose address is
    /// stored the `callee` register.
    pub fn call_with_reg(&mut self, callee: Reg, call_conv: CallingConvention) {
        self.emit(Inst::CallInd {
            info: Box::new(cranelift_codegen::CallInfo::empty(
                callee.into(),
                call_conv.into(),
            )),
        })
    }

    /// Load the min value for an integer of size out_size, as a floating-point
    /// of size `in-size`, into register `rd`.
    fn min_fp_value(
        &mut self,
        signed: bool,
        in_size: OperandSize,
        out_size: OperandSize,
        rd: Writable<Reg>,
    ) {
        match in_size {
            OperandSize::S32 => {
                let (min, _) = f32_cvt_to_int_bounds(signed, out_size.num_bits().into());
                self.mov_ir(rd, Imm::f32(min.to_bits()), in_size);
            }
            OperandSize::S64 => {
                let (min, _) = f64_cvt_to_int_bounds(signed, out_size.num_bits().into());
                self.mov_ir(rd, Imm::f64(min.to_bits()), in_size);
            }
            s => unreachable!("unsupported floating-point size: {}bit", s.num_bits()),
        };
    }

    /// Load the max value for an integer of size out_size, as a floating-point
    /// of size `in_size`, into register `rd`.
    fn max_fp_value(
        &mut self,
        signed: bool,
        in_size: OperandSize,
        out_size: OperandSize,
        rd: Writable<Reg>,
    ) {
        match in_size {
            OperandSize::S32 => {
                let (_, max) = f32_cvt_to_int_bounds(signed, out_size.num_bits().into());
                self.mov_ir(rd, Imm::f32(max.to_bits()), in_size);
            }
            OperandSize::S64 => {
                let (_, max) = f64_cvt_to_int_bounds(signed, out_size.num_bits().into());
                self.mov_ir(rd, Imm::f64(max.to_bits()), in_size);
            }
            s => unreachable!("unsupported floating-point size: {}bit", s.num_bits()),
        };
    }

    /// Emit instructions to check if the value in `rn` is NaN.
    fn check_nan(&mut self, rn: Reg, size: OperandSize) {
        self.fcmp(rn, rn, size);
        self.trapif(Cond::Vs, TrapCode::BAD_CONVERSION_TO_INTEGER);
    }

    /// Convert the floating point of size `src_size` stored in `src`, into a integer of size
    /// `dst_size`, storing the result in `dst`.
    pub fn fpu_to_int(
        &mut self,
        dst: Writable<Reg>,
        src: Reg,
        tmp_reg: WritableReg,
        src_size: OperandSize,
        dst_size: OperandSize,
        kind: TruncKind,
        signed: bool,
    ) {
        if kind.is_unchecked() {
            // Confusingly, when `kind` is `Unchecked` is when we actually need to perform the checks:
            // - check if fp is NaN
            // - check bounds
            self.check_nan(src, src_size);

            self.min_fp_value(signed, src_size, dst_size, tmp_reg);
            self.fcmp(src, tmp_reg.to_reg(), src_size);
            self.trapif(Cond::Le, TrapCode::INTEGER_OVERFLOW);

            self.max_fp_value(signed, src_size, dst_size, tmp_reg);
            self.fcmp(src, tmp_reg.to_reg(), src_size);
            self.trapif(Cond::Ge, TrapCode::INTEGER_OVERFLOW);
        }

        self.cvt_fpu_to_int(dst, src, src_size, dst_size, signed)
    }

    /// Select and emit the appropriate `fcvt*` instruction
    pub fn cvt_fpu_to_int(
        &mut self,
        dst: Writable<Reg>,
        src: Reg,
        src_size: OperandSize,
        dst_size: OperandSize,
        signed: bool,
    ) {
        let op = match (src_size, dst_size, signed) {
            (OperandSize::S32, OperandSize::S32, false) => FpuToIntOp::F32ToU32,
            (OperandSize::S32, OperandSize::S32, true) => FpuToIntOp::F32ToI32,
            (OperandSize::S32, OperandSize::S64, false) => FpuToIntOp::F32ToU64,
            (OperandSize::S32, OperandSize::S64, true) => FpuToIntOp::F32ToI64,
            (OperandSize::S64, OperandSize::S32, false) => FpuToIntOp::F64ToU32,
            (OperandSize::S64, OperandSize::S32, true) => FpuToIntOp::F64ToI32,
            (OperandSize::S64, OperandSize::S64, false) => FpuToIntOp::F64ToU64,
            (OperandSize::S64, OperandSize::S64, true) => FpuToIntOp::F64ToI64,
            (fsize, int_size, signed) => unimplemented!(
                "unsupported conversion: f{} to {}{}",
                fsize.num_bits(),
                if signed { "i" } else { "u" },
                int_size.num_bits(),
            ),
        };

        self.emit(Inst::FpuToInt {
            op,
            rd: dst.map(Into::into),
            rn: src.into(),
        });
    }
}

/// Captures the region in a MachBuffer where an add-with-immediate instruction would be emitted,
/// but the immediate is not yet known.
pub(crate) struct PatchableAddToReg {
    /// The region to be patched in the [`MachBuffer`]. It contains
    /// space for 3 32-bit instructions, i.e. it's 12 bytes long.
    region: PatchRegion,

    // The destination register for the add instruction.
    reg: Writable<Reg>,

    // The temporary register used to hold the immediate value.
    tmp: Writable<Reg>,
}

impl PatchableAddToReg {
    /// Create a new [`PatchableAddToReg`] by capturing a region in the output
    /// buffer containing an instruction sequence that loads an immediate into a
    /// register `tmp`, then adds it to a register `reg`. The [`MachBuffer`]
    /// will have that instruction sequence written to the region, though the
    /// immediate loaded into `tmp` will be `0` until the `::finalize` method is
    /// called.
    pub(crate) fn new(reg: Writable<Reg>, tmp: Writable<Reg>, buf: &mut MachBuffer<Inst>) -> Self {
        let insns = Self::add_immediate_instruction_sequence(reg, tmp, 0);
        let open = buf.start_patchable();
        buf.put_data(&insns);
        let region = buf.end_patchable(open);

        Self { region, reg, tmp }
    }

    fn add_immediate_instruction_sequence(
        reg: Writable<Reg>,
        tmp: Writable<Reg>,
        imm: i32,
    ) -> [u8; 12] {
        let imm_hi = imm as u64 & 0xffff_0000;
        let imm_hi = MoveWideConst::maybe_from_u64(imm_hi).unwrap();

        let imm_lo = imm as u64 & 0x0000_ffff;
        let imm_lo = MoveWideConst::maybe_from_u64(imm_lo).unwrap();

        let size = OperandSize::S64.into();

        let tmp = tmp.map(Into::into);
        let rd = reg.map(Into::into);

        // This is "movz to bits 16-31 of 64 bit reg tmp and zero the rest"
        let mov_insn = enc_move_wide(inst::MoveWideOp::MovZ, tmp, imm_hi, size);

        // This is "movk to bits 0-15 of 64 bit reg tmp"
        let movk_insn = enc_movk(tmp, imm_lo, size);

        // This is "add tmp to rd". The opcodes are somewhat buried in the
        // instruction encoder so we just repeat them here.
        let add_bits_31_21: u32 = 0b00001011_000 | (size.sf_bit() << 10);
        let add_bits_15_10: u32 = 0;
        let add_insn = enc_arith_rrr(
            add_bits_31_21,
            add_bits_15_10,
            rd,
            rd.to_reg(),
            tmp.to_reg(),
        );

        let mut buf = [0u8; 12];
        buf[0..4].copy_from_slice(&mov_insn.to_le_bytes());
        buf[4..8].copy_from_slice(&movk_insn.to_le_bytes());
        buf[8..12].copy_from_slice(&add_insn.to_le_bytes());
        buf
    }

    /// Patch the [`MachBuffer`] with the known constant to be added to the register. The final
    /// value is passed in as an i32, but the instruction encoding is fixed when
    /// [`PatchableAddToReg::new`] is called.
    pub(crate) fn finalize(self, val: i32, buffer: &mut MachBuffer<Inst>) {
        let insns = Self::add_immediate_instruction_sequence(self.reg, self.tmp, val);
        let slice = self.region.patch(buffer);
        assert_eq!(slice.len(), insns.len());
        slice.copy_from_slice(&insns);
    }
}