vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
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
//! Lifting of 32-bit MIPS (MIPS32 release 2, little-endian). A transfer
//! runs the instruction after it, its delay slot, before control leaves;
//! the two are lifted together, the slot first. Floating-point
//! instructions are not modelled.

pub mod decode;
mod formats;
mod starts;
mod steps;
mod tables;
pub mod text;

pub(super) use formats::count_format;
pub(crate) use formats::count_from_block_format;
pub(super) use formats::split_shared_calls;
pub(crate) use starts::{direct_transfers, function_starts};
pub(super) use steps::{decode, decode_big};
pub(crate) use tables::{fold_fixed_entries, fold_table_slots};

use decode::{Alu, Branch, FloatFormat, FloatOp, FloatTest, Instruction, Op, Rounding};

use super::Machine;
use super::calls::bare;
use super::constants::{Known, Rules};
use steps::written_register;
use vlk_arch::arch::mips32::{F0, FLAG0, FP, GP, HI, LO, RA, SP, THREAD, slot};
use vlk_ir::ir::{BinOp, Cond, Expr, MachineInstruction, Operation, RegRef, Stmt};
use vlk_types::types::{CallKind, Convention, Precision};

const WORD: u64 = 0xffff_ffff;
/// The registers that hold a branch's operands while its delay slot,
/// which may write the registers they were read from, runs.
const HELD: [u16; 2] = [vlk_ir::ir::TEMP_BASE + 0x62, vlk_ir::ir::TEMP_BASE + 0x63];
/// The register that holds the address of one half of an unaligned access.
const HALF_ADDRESS: u16 = vlk_ir::ir::TEMP_BASE + 0x64;

/// One step of the code: an instruction, and with it what the encoding
/// ties to it.
pub(super) struct Step {
    instruction: Instruction,
    /// The delay slot of a transfer, lifted before the transfer leaves.
    slot: Option<Instruction>,
    /// For the delay slot of a branch that skips it when not taken: where
    /// the branch goes once the slot has run.
    then: Option<u64>,
    /// The other half of an unaligned word access, already matched.
    unaligned: bool,
    /// The pairs of float registers, a bit each, that the code uses for
    /// more than a single in the even register.
    shared_pairs: u16,
}

pub(super) struct Lifter<'a> {
    out: super::Emitter,
    image: &'a vlk_loader::loader::Image,
    /// The function's start, which t9 holds on entry to position-
    /// independent code.
    start: u64,
    /// Whether the image stores the most significant byte of a word first.
    big: bool,
    /// The step's `shared_pairs`.
    shared_pairs: u16,
    /// What the block has left in the low two bits of the float control
    /// register, which say how a conversion rounds.
    control: Control,
    /// The low two bits a register is known to hold where its whole value
    /// is not, as after `ori` with 3.
    ends: [Option<u8>; 32],
}

fn low(value: Expr) -> Expr {
    Expr::bin(BinOp::And, value, Expr::constant(WORD))
}

fn apply(op: Operation, args: Vec<Expr>) -> Expr {
    Expr::Apply { op, args }
}

fn precision(double: bool) -> Precision {
    if double {
        Precision::Double
    } else {
        Precision::Single
    }
}

/// The slot of the pair a float register is half of.
fn pair(register: i64) -> u16 {
    F0 + (register & 31) as u16 / 2
}

/// A float register's value: a double is the whole pair, a single the
/// half the register is.
fn read_float(register: i64, p: Precision) -> Expr {
    let whole = Expr::reg(pair(register), 64);
    match p {
        Precision::Double => whole,
        Precision::Single if register & 1 == 1 => Expr::bin(BinOp::Shr, whole, Expr::constant(32)),
        Precision::Single => low(whole),
    }
}

/// What a block has done to the rounding bits of the float control
/// register.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Control {
    Unwritten,
    /// Written with these two bits: 0 to the nearest, 1 toward zero, 2 up,
    /// 3 down.
    Rounds(u8),
    Unknown,
}

/// The least double, or single, whose conversion to a word is defined
/// under `rounding`, as its bits, and whether that value itself is.
fn lowest_word(p: Precision, rounding: vlk_ir::ir::Rounding) -> (u64, bool) {
    use vlk_ir::ir::Rounding::{Down, NearestAway, NearestEven, TowardZero, Up};
    let least = -2_147_483_648.0_f64;
    match p {
        // No single near this value has a fraction.
        Precision::Single => (u64::from((least as f32).to_bits()), true),
        Precision::Double => match rounding {
            Down => (least.to_bits(), true),
            // A tie goes to the even word, which is this one.
            NearestEven => ((least - 0.5).to_bits(), true),
            NearestAway => ((least - 0.5).to_bits(), false),
            TowardZero | Up => ((least - 1.0).to_bits(), false),
        },
    }
}

fn sign_extend(value: Expr) -> Expr {
    Expr::SignExtend {
        value: Box::new(value),
        width: 4,
    }
}

impl<'a> Lifter<'a> {
    pub(super) fn new(image: &'a vlk_loader::loader::Image, start: u64) -> Self {
        Self {
            out: super::Emitter::default(),
            image,
            start,
            big: image.byte_order() == Some(object::Endianness::Big),
            shared_pairs: u16::MAX,
            control: Control::Unwritten,
            ends: [None; 32],
        }
    }

    /// A register's value: 32 bits, except the stack and frame pointers,
    /// which the stack analysis follows at full width.
    fn read(&self, register: u8) -> Expr {
        match slot(register) {
            None => Expr::constant(0),
            Some(index @ (SP | FP)) => Expr::reg(index, 64),
            Some(index) => Expr::reg(index, 32),
        }
    }

    fn assign_slot(&mut self, index: u16, value: Expr) {
        self.out.stmts.push(Stmt::Assign {
            dest: RegRef { index, width: 64 },
            value,
            at: None,
        });
    }

    fn write(&mut self, register: u8, value: Expr) {
        self.ends[usize::from(register & 31)] = None;
        let Some(index) = slot(register) else {
            return;
        };
        // An address in the frame keeps its full width.
        let frame = matches!(index, SP | FP)
            && match &value {
                Expr::Reg {
                    index: SP | FP,
                    width: 64,
                } => true,
                Expr::Bin { lhs, .. } => matches!(
                    lhs.as_ref(),
                    Expr::Reg {
                        index: SP | FP,
                        width: 64
                    }
                ),
                _ => false,
            };
        let value = if frame { value } else { low(value) };
        self.assign_slot(index, value);
    }

    /// `base + offset`: at full width from the stack or frame pointer,
    /// else wrapped to 32 bits.
    fn address(&self, base: u8, offset: i64) -> Expr {
        match slot(base) {
            Some(SP | FP) => Expr::bin(BinOp::Add, self.read(base), Expr::constant(offset as u64)),
            _ if offset < 0 => low(Expr::bin(
                BinOp::Sub,
                self.read(base),
                Expr::constant(offset.unsigned_abs()),
            )),
            _ => low(Expr::bin(
                BinOp::Add,
                self.read(base),
                Expr::constant(offset as u64),
            )),
        }
    }

    fn unsupported(&mut self, instruction: &Instruction, pc: u64, writes: Option<Vec<u16>>) {
        self.out.stmts.push(Stmt::Unsupported {
            at: None,
            text: format!("{} at 0x{pc:x}", text::text(instruction, pc)),
            writes,
        });
    }

    /// The low two bits `register` is known to hold.
    fn ends(&self, register: u8) -> Option<u8> {
        if register == 0 {
            return Some(0);
        }
        self.ends[usize::from(register)]
    }

    fn forget(&mut self) {
        self.control = Control::Unwritten;
        self.ends = [None; 32];
    }

    fn alu(op: Alu, a: Expr, b: Expr) -> Expr {
        match op {
            Alu::Add => Expr::bin(BinOp::Add, a, b),
            Alu::Sub => Expr::bin(BinOp::Sub, a, b),
            Alu::And => Expr::bin(BinOp::And, a, b),
            Alu::Or => Expr::bin(BinOp::Or, a, b),
            Alu::Xor => Expr::bin(BinOp::Xor, a, b),
            Alu::Nor => Expr::bin(BinOp::Xor, Expr::bin(BinOp::Or, a, b), Expr::constant(WORD)),
            Alu::Less => Expr::truth(Cond::Lt, a, b),
            // Below zero's other side, or below one: a test for zero.
            Alu::LessUnsigned if a == Expr::constant(0) => Expr::truth(Cond::Ne, b, a),
            Alu::LessUnsigned if b == Expr::constant(1) => {
                Expr::truth(Cond::Eq, a, Expr::constant(0))
            }
            Alu::LessUnsigned => Expr::truth(Cond::Cc, a, b),
            Alu::ShiftLeft => Expr::bin(BinOp::Shl, a, b),
            Alu::ShiftRight => Expr::bin(BinOp::Shr, a, b),
            Alu::ShiftRightArithmetic => Expr::bin(BinOp::Sar, a, b),
            Alu::Rotate => super::rotate(a, b, 32, true),
        }
    }

    /// The 64-bit product of two registers.
    fn product(&self, rs: u8, rt: u8, signed: bool) -> Expr {
        let operand = |register: u8| {
            let value = self.read(register);
            if signed { sign_extend(value) } else { value }
        };
        Expr::bin(BinOp::Mul, operand(rs), operand(rt))
    }

    fn set_wide(&mut self, value: Expr) {
        // The value is read twice: hold it so that it is computed once.
        self.assign_slot(vlk_ir::ir::EXCHANGE, value);
        let held = Expr::reg(vlk_ir::ir::EXCHANGE, 64);
        self.assign_slot(LO, low(held.clone()));
        self.assign_slot(HI, Expr::bin(BinOp::Shr, held, Expr::constant(32)));
    }

    fn wide(&self) -> Expr {
        Expr::bin(
            BinOp::Or,
            Expr::bin(BinOp::Shl, Expr::reg(HI, 32), Expr::constant(32)),
            Expr::reg(LO, 32),
        )
    }

    /// A call that returns past the delay slot.
    fn call(&mut self, target: Option<u64>, through: Option<Expr>) {
        self.forget();
        match (target, through) {
            (Some(target), _) => {
                self.out
                    .stmts
                    .push(bare(CallKind::Invoke, self.image, Some(target)));
            }
            (None, Some(through)) => {
                self.out.stmts.push(super::call_through_as(
                    CallKind::Invoke,
                    self.image,
                    through,
                    Convention::O32,
                ));
            }
            (None, None) => {}
        }
    }

    /// One half of an unaligned word access alone: the bytes of the aligned
    /// word from its start to the address, or from the address to its end,
    /// go to or come from the high or the low end of register `rt`. The
    /// address is held: the destination may be its base.
    fn half_word(&mut self, op: Op, rs: u8, rt: u8, imm: i64) {
        self.assign_slot(HALF_ADDRESS, self.address(rs, imm));
        let address = Expr::reg(HALF_ADDRESS, 32);
        let aligned = Expr::bin(BinOp::And, address.clone(), Expr::constant(WORD & !3));
        let word = Expr::Load {
            addr: Box::new(aligned.clone()),
            width: 4,
            signed: false,
        };
        // Eight times the address's place in its word, and what
        // is left of 24.
        // On a big-endian processor the word's first byte is its
        // most significant, so the places count from the other end.
        let within = Expr::bin(BinOp::And, address, Expr::constant(3));
        let within = if self.big {
            Expr::bin(BinOp::Xor, within, Expr::constant(3))
        } else {
            within
        };
        let place = Expr::bin(BinOp::Shl, within, Expr::constant(3));
        let rest = Expr::bin(BinOp::Sub, Expr::constant(24), place.clone());
        let register = self.read(rt);
        let shifted = |op: BinOp, value: Expr, by: Expr| low(Expr::bin(op, value, by));
        // The bits that keep what was there: all but those the
        // shift of a full word reaches.
        let kept = |op: BinOp, by: Expr| {
            Expr::bin(
                BinOp::Xor,
                shifted(op, Expr::constant(WORD), by),
                Expr::constant(WORD),
            )
        };
        let (kept, moved) = match op {
            // The register keeps its low bytes.
            Op::LoadLeft => (
                kept(BinOp::Shl, rest.clone()),
                shifted(BinOp::Shl, word.clone(), rest),
            ),
            // The register keeps its high bytes.
            Op::LoadRight => (
                kept(BinOp::Shr, place.clone()),
                shifted(BinOp::Shr, word.clone(), place),
            ),
            // The word keeps its high bytes.
            Op::StoreLeft => (
                kept(BinOp::Shr, rest.clone()),
                shifted(BinOp::Shr, register.clone(), rest),
            ),
            // The word keeps its low bytes.
            _ => (
                kept(BinOp::Shl, place.clone()),
                shifted(BinOp::Shl, register.clone(), place),
            ),
        };
        let old = if matches!(op, Op::LoadLeft | Op::LoadRight) {
            register
        } else {
            word
        };
        let value = Expr::bin(BinOp::Or, Expr::bin(BinOp::And, old, kept), moved);
        if matches!(op, Op::LoadLeft | Op::LoadRight) {
            self.write(rt, value);
        } else {
            self.out.stmts.push(Stmt::Store {
                addr: aligned,
                value,
                width: 4,
                at: None,
            });
        }
    }

    /// An instruction that is no transfer.
    fn plain(&mut self, instruction: &Instruction, pc: u64, unaligned: bool) {
        let Instruction {
            op,
            rs,
            rt,
            rd,
            imm,
            ..
        } = *instruction;
        match op {
            Op::Register(alu) => {
                let shift = matches!(
                    alu,
                    Alu::ShiftLeft | Alu::ShiftRight | Alu::ShiftRightArithmetic | Alu::Rotate
                );
                let value = if shift {
                    let count = Expr::bin(BinOp::And, self.read(rs), Expr::constant(31));
                    Self::alu(alu, self.read(rt), count)
                } else {
                    Self::alu(alu, self.read(rs), self.read(rt))
                };
                self.write(rd, value);
                if matches!(alu, Alu::Add | Alu::Or) && rt == 0 {
                    self.ends[usize::from(rd)] = self.ends(rs).filter(|_| rd != 0);
                }
            }
            Op::Immediate(alu) => {
                let ends = self.ends(rs);
                let set = (imm & 3) as u8;
                let ends = match alu {
                    Alu::Or if set == 3 => Some(3),
                    Alu::And if set == 0 => Some(0),
                    Alu::Or => ends.map(|ends| ends | set),
                    Alu::And => ends.map(|ends| ends & set),
                    Alu::Xor => ends.map(|ends| ends ^ set),
                    Alu::Add => ends.map(|ends| (ends + set) & 3),
                    _ => None,
                }
                .filter(|_| rt != 0);
                let frame = matches!(slot(rs), Some(SP | FP)) && alu == Alu::Add;
                let operand = if frame {
                    Expr::constant(imm as u64)
                } else {
                    Expr::constant(u64::from(imm as u32))
                };
                let value = match alu {
                    // A negative amount reads as a subtraction.
                    _ if alu == Alu::Add && !frame && rs != 0 && imm < 0 => Expr::bin(
                        BinOp::Sub,
                        self.read(rs),
                        Expr::constant(imm.unsigned_abs()),
                    ),
                    _ => Self::alu(alu, self.read(rs), operand),
                };
                self.write(rt, value);
                self.ends[usize::from(rt)] = ends;
            }
            Op::Shift(alu) => {
                let value = Self::alu(alu, self.read(rt), Expr::constant(imm as u64));
                self.write(rd, value);
            }
            Op::Lui => {
                self.write(rt, Expr::constant(imm as u64));
                self.ends[usize::from(rt)] = (rt != 0).then_some(0);
            }
            Op::Multiply { signed } => {
                let product = self.product(rs, rt, signed);
                self.set_wide(product);
            }
            Op::MultiplyAdd { signed, subtract } => {
                let product = self.product(rs, rt, signed);
                let op = if subtract { BinOp::Sub } else { BinOp::Add };
                let value = Expr::bin(op, self.wide(), product);
                self.set_wide(value);
            }
            Op::Divide { signed } => {
                let (quotient, remainder) = if signed {
                    (BinOp::DivS, BinOp::ModS)
                } else {
                    (BinOp::DivU, BinOp::ModU)
                };
                let (a, b) = (self.read(rs), self.read(rt));
                self.assign_slot(LO, low(Expr::bin(quotient, a.clone(), b.clone())));
                self.assign_slot(HI, low(Expr::bin(remainder, a, b)));
            }
            Op::MultiplyLow => {
                let value = Expr::bin(BinOp::Mul, self.read(rs), self.read(rt));
                self.write(rd, value);
            }
            Op::MoveFromHi => self.write(rd, Expr::reg(HI, 32)),
            Op::MoveFromLo => self.write(rd, Expr::reg(LO, 32)),
            Op::MoveToHi => {
                let value = self.read(rs);
                self.assign_slot(HI, low(value));
            }
            Op::MoveToLo => {
                let value = self.read(rs);
                self.assign_slot(LO, low(value));
            }
            Op::MoveIfZero | Op::MoveIfNotZero => {
                let cond = if op == Op::MoveIfZero {
                    Cond::Eq
                } else {
                    Cond::Ne
                };
                let value = Expr::Select {
                    cond,
                    lhs: Box::new(self.read(rt)),
                    rhs: Box::new(Expr::constant(0)),
                    then: Box::new(self.read(rs)),
                    els: Box::new(self.read(rd)),
                };
                self.write(rd, value);
            }
            Op::CountLeadingZeros | Op::CountLeadingOnes => {
                let value = if op == Op::CountLeadingOnes {
                    Expr::bin(BinOp::Xor, self.read(rs), Expr::constant(WORD))
                } else {
                    self.read(rs)
                };
                self.write(
                    rd,
                    Expr::apply(Operation::CountLeadingZeros(32), vec![value]),
                );
            }
            Op::Extract => {
                let mask = (1u64 << (u32::from(rd) + 1)) - 1;
                let value = Expr::bin(
                    BinOp::And,
                    Expr::bin(BinOp::Shr, self.read(rs), Expr::constant(imm as u64)),
                    Expr::constant(mask),
                );
                self.write(rt, value);
            }
            Op::Insert => {
                let size = u32::from(rd) + 1 - imm as u32;
                let mask = ((1u64 << size) - 1) << imm;
                let value = Expr::bin(
                    BinOp::Or,
                    Expr::bin(BinOp::And, self.read(rt), Expr::constant(WORD & !mask)),
                    Expr::bin(
                        BinOp::And,
                        Expr::bin(BinOp::Shl, self.read(rs), Expr::constant(imm as u64)),
                        Expr::constant(mask),
                    ),
                );
                self.write(rt, value);
            }
            Op::SignExtendByte | Op::SignExtendHalf => {
                let value = Expr::SignExtend {
                    value: Box::new(self.read(rt)),
                    width: if op == Op::SignExtendByte { 1 } else { 2 },
                };
                self.write(rd, value);
            }
            Op::SwapBytesInHalves => {
                let value = self.read(rt);
                let swapped = Expr::bin(
                    BinOp::Or,
                    Expr::bin(
                        BinOp::Shl,
                        Expr::bin(BinOp::And, value.clone(), Expr::constant(0x00ff_00ff)),
                        Expr::constant(8),
                    ),
                    Expr::bin(
                        BinOp::And,
                        Expr::bin(BinOp::Shr, value, Expr::constant(8)),
                        Expr::constant(0x00ff_00ff),
                    ),
                );
                self.write(rd, swapped);
            }
            Op::Load { bytes, signed } => {
                let address = self.address(rs, imm);
                self.write(
                    rt,
                    Expr::Load {
                        addr: Box::new(address),
                        width: bytes,
                        signed,
                    },
                );
            }
            Op::Store { bytes } => {
                let value = self.read(rt);
                self.out.stmts.push(Stmt::Store {
                    addr: self.address(rs, imm),
                    value: match slot(rt) {
                        Some(index @ (SP | FP)) => Expr::reg(index, 32),
                        _ => value,
                    },
                    width: bytes,
                    at: None,
                });
            }
            // The two halves of an unaligned word, matched as a pair by
            // the decoder: the right half names the word's address.
            Op::LoadRight if unaligned => {
                let value = Expr::Load {
                    addr: Box::new(self.address(rs, imm)),
                    width: 4,
                    signed: false,
                };
                self.write(rt, value);
            }
            Op::StoreRight if unaligned => {
                self.out.stmts.push(Stmt::Store {
                    addr: self.address(rs, imm),
                    value: self.read(rt),
                    width: 4,
                    at: None,
                });
            }
            Op::LoadLeft | Op::LoadRight | Op::StoreLeft | Op::StoreRight => {
                self.half_word(op, rs, rt, imm);
            }
            Op::LoadLinked | Op::StoreConditional => {
                let output = RegRef {
                    index: vlk_ir::ir::TEMP_BASE + 0x60,
                    width: 64,
                };
                let load = op == Op::LoadLinked;
                let mut inputs = vec![self.address(rs, imm)];
                if !load {
                    inputs.push(self.read(rt));
                }
                self.out.stmts.push(Stmt::Machine {
                    at: None,
                    instruction: MachineInstruction::ArmExclusive {
                        load,
                        width: 4,
                        pair: false,
                        ordered: false,
                    },
                    inputs,
                    outputs: vec![output],
                });
                // A load gives the word; a store gives one when it took
                // place, where the monitor's status is zero.
                let value = if load {
                    Expr::reg(output.index, 64)
                } else {
                    Expr::truth(Cond::Eq, Expr::reg(output.index, 64), Expr::constant(0))
                };
                self.write(rt, value);
            }
            Op::Syscall => {
                self.forget();
                self.out.stmts.push(Stmt::Call {
                    kind: CallKind::Syscall,
                    target: None,
                    through: None,
                    convention: Convention::SyscallMips,
                    args: None,
                    floats_named: true,
                    abi: None,
                    clobbers: None,
                    outputs: vlk_ir::ir::fallback_call_outputs(Convention::SyscallMips, None),
                    via: None,
                    at: None,
                });
            }
            Op::ReadHardware => self.write(rt, Expr::reg(THREAD, 32)),
            // A barrier has no effect on one thread; a conditional trap
            // guards a case, as a division by zero, the IR leaves undefined.
            Op::Sync | Op::Trap { .. } => {}
            Op::Other => self.unsupported(instruction, pc, None),
            Op::Break
            | Op::Jump { .. }
            | Op::JumpRegister { .. }
            | Op::Branch { .. }
            | Op::FloatBranch { .. } => {}
            _ => self.float(instruction, pc),
        }
    }

    fn write_float(&mut self, register: i64, p: Precision, value: Expr) {
        let whole = Expr::reg(pair(register), 64);
        // A single leaves the other half of its pair as it was. Where the
        // code keeps nothing in that half, the pair holds the single alone.
        let alone = self.shared_pairs >> ((register & 31) / 2) & 1 == 0;
        let value = match p {
            Precision::Double => value,
            Precision::Single if alone => value,
            Precision::Single if register & 1 == 1 => Expr::bin(
                BinOp::Or,
                low(whole),
                Expr::bin(BinOp::Shl, value, Expr::constant(32)),
            ),
            Precision::Single => Expr::bin(
                BinOp::Or,
                Expr::bin(BinOp::And, whole, Expr::constant(!WORD)),
                value,
            ),
        };
        self.assign_slot(pair(register), value);
    }

    fn flag(flag: u8) -> Expr {
        Expr::reg(FLAG0 + u16::from(flag & 7), 64)
    }

    /// An instruction of the float coprocessor that is no branch.
    fn float(&mut self, instruction: &Instruction, pc: u64) {
        let Instruction {
            op,
            rs,
            rt,
            rd,
            imm,
            ..
        } = *instruction;
        let (ft, fs, fd) = (i64::from(rt), i64::from(rd), imm);
        match op {
            Op::FloatArithmetic { op, double } => {
                let p = precision(double);
                let a = read_float(fs, p);
                let b = read_float(ft, p);
                let value = match op {
                    FloatOp::Add => apply(Operation::FloatAdd(p), vec![a, b]),
                    FloatOp::Sub => apply(Operation::FloatSub(p), vec![a, b]),
                    FloatOp::Mul => apply(Operation::FloatMul(p), vec![a, b]),
                    FloatOp::Div => apply(Operation::FloatDiv(p), vec![a, b]),
                    FloatOp::Sqrt => apply(Operation::FloatSqrt(p), vec![a]),
                    FloatOp::Abs => apply(Operation::FloatAbs(p), vec![a]),
                    FloatOp::Negate => apply(Operation::FloatNegate(p), vec![a]),
                    FloatOp::Move => a,
                };
                self.write_float(fd, p, value);
            }
            Op::FloatMultiplyAdd {
                subtract,
                negate,
                double,
            } => {
                let p = precision(double);
                let product = apply(
                    Operation::FloatMul(p),
                    vec![read_float(fs, p), read_float(ft, p)],
                );
                let addend = read_float(i64::from(rs), p);
                let sum = if subtract {
                    apply(Operation::FloatSub(p), vec![product, addend])
                } else {
                    apply(Operation::FloatAdd(p), vec![product, addend])
                };
                let value = if negate {
                    apply(Operation::FloatNegate(p), vec![sum])
                } else {
                    sum
                };
                self.write_float(fd, p, value);
            }
            Op::FloatConvert { from, double } => {
                let to = precision(double);
                let value = match from {
                    FloatFormat::Word => apply(
                        Operation::IntToFloat {
                            signed: true,
                            bits: 32,
                            to,
                        },
                        vec![read_float(fs, Precision::Single)],
                    ),
                    FloatFormat::Single | FloatFormat::Double => {
                        let from = precision(from == FloatFormat::Double);
                        apply(
                            Operation::FloatConvert { from, to },
                            vec![read_float(fs, from)],
                        )
                    }
                };
                self.write_float(fd, to, value);
            }
            // After a write of the control register whose low bits are
            // not known the rounding is not known here.
            Op::FloatToWord {
                rounding: Rounding::Current,
                ..
            } if self.control == Control::Unknown => {
                self.unsupported(instruction, pc, Some(vec![pair(fd)]));
            }
            Op::FloatToWord { rounding, double } => {
                let from = precision(double);
                let rounding = match (rounding, self.control) {
                    (Rounding::Zero, _) | (Rounding::Current, Control::Rounds(1)) => {
                        vlk_ir::ir::Rounding::TowardZero
                    }
                    (Rounding::Up, _) | (Rounding::Current, Control::Rounds(2)) => {
                        vlk_ir::ir::Rounding::Up
                    }
                    (Rounding::Down, _) | (Rounding::Current, Control::Rounds(3)) => {
                        vlk_ir::ir::Rounding::Down
                    }
                    // A control register the block has not written is
                    // taken to hold its default.
                    (Rounding::Nearest | Rounding::Current, _) => vlk_ir::ir::Rounding::NearestEven,
                };
                let source = read_float(fs, from);
                let converted = apply(
                    Operation::FloatToInt {
                        signed: true,
                        bits: 32,
                        from,
                        saturating: true,
                        rounding,
                    },
                    vec![source.clone()],
                );
                // A NaN and a value below the least word give the highest
                // word, as one above it does.
                let (least, inclusive) = lowest_word(from, rounding);
                let below = if inclusive {
                    apply(
                        Operation::FloatLess(from),
                        vec![source.clone(), Expr::constant(least)],
                    )
                } else {
                    apply(
                        Operation::FloatLessEqual(from),
                        vec![source.clone(), Expr::constant(least)],
                    )
                };
                let invalid = Expr::bin(
                    BinOp::Or,
                    apply(
                        Operation::FloatUnordered(from),
                        vec![source.clone(), source],
                    ),
                    below,
                );
                let value = Expr::Select {
                    cond: Cond::Ne,
                    lhs: Box::new(invalid),
                    rhs: Box::new(Expr::constant(0)),
                    then: Box::new(Expr::constant(0x7fff_ffff)),
                    els: Box::new(low(converted)),
                };
                self.write_float(fd, Precision::Single, value);
            }
            Op::FloatCompare {
                condition,
                double,
                flag,
            } => {
                let p = precision(double);
                let operands = || vec![read_float(fs, p), read_float(ft, p)];
                let mut terms = Vec::new();
                if condition & 6 == 6 {
                    terms.push(apply(Operation::FloatLessEqual(p), operands()));
                } else if condition & 4 != 0 {
                    terms.push(apply(Operation::FloatLess(p), operands()));
                } else if condition & 2 != 0 {
                    terms.push(apply(Operation::FloatEqual(p), operands()));
                }
                if condition & 1 != 0 {
                    terms.push(apply(Operation::FloatUnordered(p), operands()));
                }
                let value = terms
                    .into_iter()
                    .reduce(|a, b| Expr::bin(BinOp::Or, a, b))
                    .unwrap_or(Expr::constant(0));
                self.assign_slot(FLAG0 + u16::from(flag & 7), value);
            }
            Op::FloatSelect { test, double } => {
                let p = precision(double);
                let (cond, lhs) = match test {
                    FloatTest::Zero => (Cond::Eq, self.read(rt)),
                    FloatTest::NotZero => (Cond::Ne, self.read(rt)),
                    FloatTest::Flag { set: true, flag } => (Cond::Ne, Self::flag(flag)),
                    FloatTest::Flag { set: false, flag } => (Cond::Eq, Self::flag(flag)),
                };
                let value = Expr::Select {
                    cond,
                    lhs: Box::new(lhs),
                    rhs: Box::new(Expr::constant(0)),
                    then: Box::new(read_float(fs, p)),
                    els: Box::new(read_float(fd, p)),
                };
                self.write_float(fd, p, value);
            }
            Op::SelectOnFlag { set, flag } => {
                let value = Expr::Select {
                    cond: if set { Cond::Ne } else { Cond::Eq },
                    lhs: Box::new(Self::flag(flag)),
                    rhs: Box::new(Expr::constant(0)),
                    then: Box::new(self.read(rs)),
                    els: Box::new(self.read(rd)),
                };
                self.write(rd, value);
            }
            Op::FloatTransfer {
                to_float: false,
                high,
            } => {
                let value = read_float(fs | i64::from(high), Precision::Single);
                self.write(rt, value);
            }
            Op::FloatTransfer {
                to_float: true,
                high,
            } => {
                let value = self.read(rt);
                self.write_float(fs | i64::from(high), Precision::Single, value);
            }
            Op::FloatControl { write } => {
                let output = RegRef {
                    index: vlk_ir::ir::TEMP_BASE + 0x60,
                    width: 64,
                };
                let (inputs, outputs) = if write {
                    // Register 31 holds the rounding in its low two bits.
                    // Others share those bits or hold none of them.
                    self.control = match self.ends(rt) {
                        Some(ends) if rd == 31 => Control::Rounds(ends),
                        _ => Control::Unknown,
                    };
                    (vec![self.read(rt)], Vec::new())
                } else {
                    (Vec::new(), vec![output])
                };
                self.out.stmts.push(Stmt::Machine {
                    at: None,
                    instruction: MachineInstruction::MipsFloatControl {
                        register: rd,
                        write,
                    },
                    inputs,
                    outputs,
                });
                if !write {
                    self.write(rt, Expr::reg(output.index, 64));
                }
            }
            Op::FloatLoad { double } => {
                let value = Expr::Load {
                    addr: Box::new(self.address(rs, imm)),
                    width: if double { 8 } else { 4 },
                    signed: false,
                };
                self.write_float(ft, precision(double), value);
            }
            Op::FloatStore { double } => {
                self.out.stmts.push(Stmt::Store {
                    addr: self.address(rs, imm),
                    value: read_float(ft, precision(double)),
                    width: if double { 8 } else { 4 },
                    at: None,
                });
            }
            Op::FloatLoadIndexed { double } => {
                let addr = low(Expr::bin(BinOp::Add, self.read(rs), self.read(rt)));
                let value = Expr::Load {
                    addr: Box::new(addr),
                    width: if double { 8 } else { 4 },
                    signed: false,
                };
                self.write_float(fd, precision(double), value);
            }
            Op::FloatStoreIndexed { double } => {
                let addr = low(Expr::bin(BinOp::Add, self.read(rs), self.read(rt)));
                self.out.stmts.push(Stmt::Store {
                    addr,
                    value: read_float(fs, precision(double)),
                    width: if double { 8 } else { 4 },
                    at: None,
                });
            }
            _ => {}
        }
    }

    /// The operands of a branch, held aside when the delay slot writes
    /// the registers they are read from.
    fn held(
        &mut self,
        operands: [(u8, Expr); 2],
        slot_instruction: Option<&Instruction>,
    ) -> [Expr; 2] {
        let written = slot_instruction.map(written_register);
        let mut index = 0;
        operands.map(|(register, value)| {
            let place = HELD[index];
            index += 1;
            if register != 0 && written == Some(Some(register)) {
                // A branch compares 32-bit values.
                self.assign_slot(place, low(value));
                Expr::reg(place, 32)
            } else {
                value
            }
        })
    }

    /// The delay slot of the transfer at `pc`, where the step has one.
    fn delay_slot(&mut self, step: &Step, pc: u64) {
        if let Some(slot_instruction) = &step.slot {
            self.plain(slot_instruction, pc.wrapping_add(4), false);
        }
    }

    /// A jump to a function through `through`: a call that does not return
    /// here.
    fn tail_call(&mut self, through: Expr) {
        self.out.stmts.push(super::call_through_as(
            CallKind::Tail,
            self.image,
            through,
            Convention::O32,
        ));
        self.out.stmts.push(Stmt::Ret {
            value: Expr::reg(vlk_arch::arch::RETURN, 32),
            at: None,
        });
    }

    /// A conditional branch on general registers. Returns whether it ends
    /// the block.
    fn branch(&mut self, step: &Step, pc: u64) -> bool {
        let instruction = &step.instruction;
        let Op::Branch { test, likely, link } = instruction.op else {
            unreachable!("a branch")
        };
        let Instruction { rs, rt, .. } = *instruction;
        let Some(target) = text::target(instruction, pc) else {
            return true;
        };
        let (cond, rhs) = match test {
            Branch::Equal => (Cond::Eq, self.read(rt)),
            Branch::NotEqual => (Cond::Ne, self.read(rt)),
            Branch::LessEqualZero => (Cond::Le, Expr::constant(0)),
            Branch::GreaterZero => (Cond::Gt, Expr::constant(0)),
            Branch::LessZero => (Cond::Lt, Expr::constant(0)),
            Branch::GreaterEqualZero => (Cond::Ge, Expr::constant(0)),
        };
        let compared = match test {
            Branch::Equal | Branch::NotEqual => rt,
            _ => 0,
        };
        let always =
            matches!(test, Branch::Equal | Branch::GreaterEqualZero) && rs == 0 && compared == 0;
        if link {
            self.write(31, Expr::constant(pc.wrapping_add(8)));
        }
        if likely {
            // The slot runs only when the branch is taken: leave
            // for the instruction past it otherwise. The slot is
            // the next step, which then goes to the target.
            self.out.stmts.push(Stmt::Brif {
                cond: cond.invert(),
                lhs: self.read(rs),
                rhs,
                target: pc.wrapping_add(8),
                at: None,
            });
            return true;
        }
        let [lhs, rhs] = self.held([(rs, self.read(rs)), (compared, rhs)], step.slot.as_ref());
        self.delay_slot(step, pc);
        if always && link {
            self.call(Some(target), None);
            return false;
        }
        self.out.stmts.push(if always {
            Stmt::Br {
                target: Some(target),
                at: None,
            }
        } else {
            Stmt::Brif {
                cond,
                lhs,
                rhs,
                target,
                at: None,
            }
        });
        true
    }

    /// A branch on a float condition flag being `set`.
    fn float_branch(&mut self, step: &Step, pc: u64) {
        let Op::FloatBranch { set, likely, flag } = step.instruction.op else {
            unreachable!("a float branch")
        };
        let Some(target) = text::target(&step.instruction, pc) else {
            return;
        };
        if likely {
            self.out.stmts.push(Stmt::Brif {
                cond: if set { Cond::Eq } else { Cond::Ne },
                lhs: Self::flag(flag),
                rhs: Expr::constant(0),
                target: pc.wrapping_add(8),
                at: None,
            });
            return;
        }
        // A comparison in the delay slot sets the flag after
        // the branch has read it.
        let compares = step
            .slot
            .as_ref()
            .is_some_and(|slot| matches!(slot.op, Op::FloatCompare { .. }));
        let lhs = if compares {
            self.assign_slot(HELD[0], Self::flag(flag));
            Expr::reg(HELD[0], 64)
        } else {
            Self::flag(flag)
        };
        self.delay_slot(step, pc);
        self.out.stmts.push(Stmt::Brif {
            cond: if set { Cond::Ne } else { Cond::Eq },
            lhs,
            rhs: Expr::constant(0),
            target,
            at: None,
        });
    }

    /// A jump or call to the address the instruction names. Returns
    /// whether it ends the block.
    fn jump(&mut self, step: &Step, pc: u64, link: bool) -> bool {
        let target = text::target(&step.instruction, pc);
        if link {
            self.write(31, Expr::constant(pc.wrapping_add(8)));
        }
        self.delay_slot(step, pc);
        // In an object file, a symbol another module defines is
        // reached through the entry that stands for it.
        let outside = self.image.outside_calls.get(&pc).map(|slot| Expr::Load {
            addr: Box::new(Expr::constant(*slot)),
            width: 4,
            signed: false,
        });
        match (link, outside) {
            (true, Some(through)) => {
                self.call(None, Some(through));
                false
            }
            (true, None) => {
                self.call(target, None);
                false
            }
            (false, Some(through)) => {
                self.tail_call(through);
                true
            }
            (false, None) => {
                self.out.stmts.push(Stmt::Br { target, at: None });
                true
            }
        }
    }

    /// A jump or call through a register. Returns whether it ends the
    /// block.
    fn jump_register(&mut self, step: &Step, pc: u64, link: bool) -> bool {
        let Instruction { rs, rd, .. } = step.instruction;
        let returns = !link && slot(rs) == Some(RA);
        let through = self.read(rs);
        let [through, _] = self.held([(rs, through), (0, Expr::constant(0))], step.slot.as_ref());
        if link {
            self.write(rd, Expr::constant(pc.wrapping_add(8)));
        }
        self.delay_slot(step, pc);
        if returns {
            self.out.stmts.push(Stmt::Ret {
                value: Expr::reg(vlk_arch::arch::RETURN, 32),
                at: None,
            });
            true
        } else if link {
            // What the block built in the register may make this
            // a call to a known function, when the block is built.
            self.call(None, Some(through));
            false
        } else if rs == 25 {
            // The ABI calls through t9; a table of a switch is
            // followed through another register.
            self.tail_call(through);
            true
        } else {
            self.out.stmts.push(Stmt::BrIndirect {
                target: through,
                at: None,
            });
            true
        }
    }

    fn step(&mut self, step: &Step, pc: u64) -> bool {
        self.shared_pairs = step.shared_pairs;
        let ended = match step.instruction.op {
            Op::Branch { .. } => self.branch(step, pc),
            Op::FloatBranch { .. } => {
                self.float_branch(step, pc);
                true
            }
            Op::Jump { link } => self.jump(step, pc, link),
            Op::JumpRegister { link } => self.jump_register(step, pc, link),
            Op::Break => {
                self.out.stmts.push(Stmt::Trap { at: None });
                true
            }
            _ => {
                self.plain(&step.instruction, pc, step.unaligned);
                false
            }
        };
        match step.then {
            Some(target) if !ended => {
                self.out.stmts.push(Stmt::Br {
                    target: Some(target),
                    at: None,
                });
                true
            }
            _ => ended,
        }
    }
}

impl Machine for Lifter<'_> {
    type Instruction = Step;

    fn out(&mut self) -> &mut super::Emitter {
        &mut self.out
    }

    fn branch_target(&self, step: &Step, pc: u64) -> Option<u64> {
        if let Some(target) = step.then {
            return Some(target);
        }
        match step.instruction.op {
            Op::Branch { likely: true, .. } | Op::FloatBranch { likely: true, .. } => {
                Some(pc.wrapping_add(8))
            }
            Op::Branch { link: false, .. } | Op::FloatBranch { .. } | Op::Jump { link: false } => {
                text::target(&step.instruction, pc)
            }
            _ => None,
        }
    }

    fn step(&mut self, instruction: &Step, pc: u64) -> bool {
        Lifter::step(self, instruction, pc)
    }

    fn rules(&self) -> Rules {
        // The caller of position-independent code leaves the function's
        // address in t9, and a file may give the gp its code runs with.
        let mut at_entry = Known::new();
        if let Some(t9) = slot(25) {
            at_entry.insert(t9, self.start & WORD);
        }
        if let Some(address) = self.image.global_pointer {
            at_entry.insert(GP, address);
        }
        Rules {
            at_entry,
            fixed: &[GP],
            frame: &[SP, FP],
            saved: &[16, 17, 18, 19, 20, 21, 22, 23, FP],
            folds: true,
            calls_through_registers: true,
        }
    }

    fn enter_block(&mut self) {
        self.forget();
    }
}

#[cfg(test)]
mod tests;