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
//! Decoding of the MIPS32 release 2 integer and floating-point
//! instructions. Every instruction is one word; the other coprocessors'
//! instructions decode as `Other`, which the lifter does not model.

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Alu {
    Add,
    Sub,
    And,
    Or,
    Xor,
    Nor,
    Less,
    LessUnsigned,
    ShiftLeft,
    ShiftRight,
    ShiftRightArithmetic,
    Rotate,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Branch {
    Equal,
    NotEqual,
    /// The four that compare `rs` with zero.
    LessEqualZero,
    GreaterZero,
    LessZero,
    GreaterEqualZero,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Trap {
    GreaterEqual,
    GreaterEqualUnsigned,
    Less,
    LessUnsigned,
    Equal,
    NotEqual,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FloatOp {
    Add,
    Sub,
    Mul,
    Div,
    Sqrt,
    Abs,
    Move,
    Negate,
}

/// How a conversion to a word rounds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rounding {
    Nearest,
    Zero,
    Up,
    Down,
    /// As the control register says when the instruction runs.
    Current,
}

/// What a float register holds before a conversion.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FloatFormat {
    Single,
    Double,
    Word,
}

/// What decides a conditional move.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FloatTest {
    /// The general register `rt` is zero, or is not.
    Zero,
    NotZero,
    /// A condition flag is set, or is clear.
    Flag {
        set: bool,
        flag: u8,
    },
}

/// What an instruction does. Register fields are `rs`, `rt` and `rd` as
/// the encoding names them; `imm` is the immediate, already extended, or
/// the shift amount or bit position.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Op {
    /// `rd = rs op rt`; a shift by a register is `rd = rt op rs`.
    Register(Alu),
    /// `rt = rs op imm`
    Immediate(Alu),
    /// `rd = rt op imm`, a shift by a constant.
    Shift(Alu),
    /// `rt = imm << 16`
    Lui,
    /// The 64-bit product of `rs` and `rt` to HI and LO.
    Multiply {
        signed: bool,
    },
    /// The product added to, or taken from, HI and LO.
    MultiplyAdd {
        signed: bool,
        subtract: bool,
    },
    /// The quotient of `rs` by `rt` to LO and the remainder to HI.
    Divide {
        signed: bool,
    },
    /// `rd = rs * rt`, the low 32 bits.
    MultiplyLow,
    MoveFromHi,
    MoveFromLo,
    MoveToHi,
    MoveToLo,
    /// `rd = rs` when `rt` is zero, or when it is not.
    MoveIfZero,
    MoveIfNotZero,
    CountLeadingZeros,
    CountLeadingOnes,
    /// `rt` = the `size` bits of `rs` from bit `imm`; `size` is in `rd`.
    Extract,
    /// The low `size` bits of `rs` into `rt` at bit `imm`.
    Insert,
    SignExtendByte,
    SignExtendHalf,
    /// The two bytes of each half of `rt` swapped, to `rd`.
    SwapBytesInHalves,
    Load {
        bytes: u8,
        signed: bool,
    },
    Store {
        bytes: u8,
    },
    /// The unaligned word accesses: the left or right part of a word.
    LoadLeft,
    LoadRight,
    StoreLeft,
    StoreRight,
    LoadLinked,
    StoreConditional,
    /// A jump to `imm`, an address in the 256 MB region of the delay slot.
    Jump {
        link: bool,
    },
    /// A jump to the address in `rs`; a link goes to `rd`.
    JumpRegister {
        link: bool,
    },
    /// A branch by `imm` from the delay slot. `likely` skips the delay
    /// slot when the branch is not taken; `link` sets `ra`.
    Branch {
        test: Branch,
        likely: bool,
        link: bool,
    },
    Syscall,
    Break,
    /// A trap when the comparison of `rs` with `rt`, or with `imm`, holds.
    Trap {
        test: Trap,
        immediate: bool,
    },
    Sync,
    /// A hardware register read to `rt`; `rd` names it.
    ReadHardware,
    /// The float instructions name `ft` in `rt` and `fs` in `rd`; `imm` is
    /// the destination `fd` where there is one. `fd = fs op ft`.
    FloatArithmetic {
        op: FloatOp,
        double: bool,
    },
    /// `fd` = the word `fs` rounds to.
    FloatToWord {
        rounding: Rounding,
        double: bool,
    },
    /// `fd = fs`, converted to a single or a double.
    FloatConvert {
        from: FloatFormat,
        double: bool,
    },
    /// Sets a condition flag to whether `fs` and `ft` compare as the
    /// condition asks: bit 0 for unordered, bit 1 for equal, bit 2 for
    /// less. Bit 3 only asks for a signal on a quiet NaN.
    FloatCompare {
        condition: u8,
        double: bool,
        flag: u8,
    },
    /// `fd = fs` when the test holds.
    FloatSelect {
        test: FloatTest,
        double: bool,
    },
    /// `rd = rs` when a condition flag is set, or is clear.
    SelectOnFlag {
        set: bool,
        flag: u8,
    },
    /// A branch on a condition flag.
    FloatBranch {
        set: bool,
        likely: bool,
        flag: u8,
    },
    /// The low or high word of `fs` to or from the general register `rt`.
    FloatTransfer {
        to_float: bool,
        high: bool,
    },
    /// The float control register `rd` to or from `rt`.
    FloatControl {
        write: bool,
    },
    /// `ft` loaded from or stored to `imm(rs)`.
    FloatLoad {
        double: bool,
    },
    FloatStore {
        double: bool,
    },
    /// `fd` loaded from, or `fs` stored to, the sum of `rs` and `rt`.
    FloatLoadIndexed {
        double: bool,
    },
    FloatStoreIndexed {
        double: bool,
    },
    /// `fd = fs * ft + fr`, with `fr` in `rs`; the addend taken away, or
    /// the whole negated. The product is rounded before the sum.
    FloatMultiplyAdd {
        subtract: bool,
        negate: bool,
        double: bool,
    },
    /// An instruction this does not model: another coprocessor, cache
    /// control.
    Other,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Instruction {
    pub op: Op,
    pub rs: u8,
    pub rt: u8,
    pub rd: u8,
    pub imm: i64,
    /// The word itself, for the text of what is not modelled.
    pub word: u32,
}

impl Instruction {
    /// Whether the instruction after this one runs before control leaves.
    pub(crate) fn has_delay_slot(&self) -> bool {
        matches!(
            self.op,
            Op::Jump { .. } | Op::JumpRegister { .. } | Op::Branch { .. } | Op::FloatBranch { .. }
        )
    }
}

/// Decodes one word, stored most significant byte first when `big`.
pub fn decode(bytes: &[u8], big: bool) -> Option<Instruction> {
    let Some(&word) = bytes.first_chunk::<4>() else {
        return None;
    };
    decode_word(if big {
        u32::from_be_bytes(word)
    } else {
        u32::from_le_bytes(word)
    })
}

pub(crate) fn decode_word(word: u32) -> Option<Instruction> {
    let rs = (word >> 21 & 31) as u8;
    let rt = (word >> 16 & 31) as u8;
    let rd = (word >> 11 & 31) as u8;
    let amount = word >> 6 & 31;
    let function = word & 63;
    let signed = i64::from(word as u16 as i16);
    let unsigned = i64::from(word as u16);
    let make = |op: Op, imm: i64| Instruction {
        op,
        rs,
        rt,
        rd,
        imm,
        word,
    };
    let branch =
        |test, likely, link| make(Op::Branch { test, likely, link }, signed.wrapping_mul(4));
    let load = |bytes, signed_load| {
        make(
            Op::Load {
                bytes,
                signed: signed_load,
            },
            signed,
        )
    };
    Some(match word >> 26 {
        0 => match function {
            0 if rs == 0 => make(Op::Shift(Alu::ShiftLeft), i64::from(amount)),
            1 if amount == 0 && rt & 2 == 0 => make(
                Op::SelectOnFlag {
                    set: rt & 1 == 1,
                    flag: rt >> 2,
                },
                0,
            ),
            2 if rs == 0 => make(Op::Shift(Alu::ShiftRight), i64::from(amount)),
            2 if rs == 1 => make(Op::Shift(Alu::Rotate), i64::from(amount)),
            3 if rs == 0 => make(Op::Shift(Alu::ShiftRightArithmetic), i64::from(amount)),
            4 if amount == 0 => make(Op::Register(Alu::ShiftLeft), 0),
            6 if amount == 0 => make(Op::Register(Alu::ShiftRight), 0),
            6 if amount == 1 => make(Op::Register(Alu::Rotate), 0),
            7 if amount == 0 => make(Op::Register(Alu::ShiftRightArithmetic), 0),
            // The hint field is empty or asks for a hazard barrier.
            8 if rt == 0 && rd == 0 && matches!(amount, 0 | 16) => {
                make(Op::JumpRegister { link: false }, 0)
            }
            // A link register that is the target's own is not defined.
            9 if rt == 0 && (rd != rs || rd == 0) && matches!(amount, 0 | 16) => {
                make(Op::JumpRegister { link: rd != 0 }, 0)
            }
            10 if amount == 0 => make(Op::MoveIfZero, 0),
            11 if amount == 0 => make(Op::MoveIfNotZero, 0),
            12 => make(Op::Syscall, i64::from(word >> 6 & 0xf_ffff)),
            13 => make(Op::Break, i64::from(word >> 6 & 0xf_ffff)),
            15 => make(Op::Sync, i64::from(amount)),
            16 if rs == 0 && rt == 0 && amount == 0 => make(Op::MoveFromHi, 0),
            17 if rt == 0 && rd == 0 && amount == 0 => make(Op::MoveToHi, 0),
            18 if rs == 0 && rt == 0 && amount == 0 => make(Op::MoveFromLo, 0),
            19 if rt == 0 && rd == 0 && amount == 0 => make(Op::MoveToLo, 0),
            24 if rd == 0 && amount == 0 => make(Op::Multiply { signed: true }, 0),
            25 if rd == 0 && amount == 0 => make(Op::Multiply { signed: false }, 0),
            26 if rd == 0 && amount == 0 => make(Op::Divide { signed: true }, 0),
            27 if rd == 0 && amount == 0 => make(Op::Divide { signed: false }, 0),
            32 | 33 if amount == 0 => make(Op::Register(Alu::Add), i64::from(function & 1)),
            34 | 35 if amount == 0 => make(Op::Register(Alu::Sub), i64::from(function & 1)),
            36 if amount == 0 => make(Op::Register(Alu::And), 0),
            37 if amount == 0 => make(Op::Register(Alu::Or), 0),
            38 if amount == 0 => make(Op::Register(Alu::Xor), 0),
            39 if amount == 0 => make(Op::Register(Alu::Nor), 0),
            42 if amount == 0 => make(Op::Register(Alu::Less), 0),
            43 if amount == 0 => make(Op::Register(Alu::LessUnsigned), 0),
            48..=52 | 54 => {
                let test = match function {
                    48 => Trap::GreaterEqual,
                    49 => Trap::GreaterEqualUnsigned,
                    50 => Trap::Less,
                    51 => Trap::LessUnsigned,
                    52 => Trap::Equal,
                    _ => Trap::NotEqual,
                };
                make(
                    Op::Trap {
                        test,
                        immediate: false,
                    },
                    i64::from(word >> 6 & 0x3ff),
                )
            }
            _ => return None,
        },
        1 => match rt {
            0 => branch(Branch::LessZero, false, false),
            1 => branch(Branch::GreaterEqualZero, false, false),
            2 => branch(Branch::LessZero, true, false),
            3 => branch(Branch::GreaterEqualZero, true, false),
            16 => branch(Branch::LessZero, false, true),
            17 => branch(Branch::GreaterEqualZero, false, true),
            18 => branch(Branch::LessZero, true, true),
            19 => branch(Branch::GreaterEqualZero, true, true),
            31 => make(Op::Other, 0),
            8..=12 | 14 => {
                let test = match rt {
                    8 => Trap::GreaterEqual,
                    9 => Trap::GreaterEqualUnsigned,
                    10 => Trap::Less,
                    11 => Trap::LessUnsigned,
                    12 => Trap::Equal,
                    _ => Trap::NotEqual,
                };
                make(
                    Op::Trap {
                        test,
                        immediate: true,
                    },
                    signed,
                )
            }
            _ => return None,
        },
        2 | 3 => make(
            Op::Jump {
                link: word >> 26 == 3,
            },
            i64::from(word & 0x03ff_ffff) << 2,
        ),
        4 => branch(Branch::Equal, false, false),
        5 => branch(Branch::NotEqual, false, false),
        6 if rt == 0 => branch(Branch::LessEqualZero, false, false),
        7 if rt == 0 => branch(Branch::GreaterZero, false, false),
        20 => branch(Branch::Equal, true, false),
        21 => branch(Branch::NotEqual, true, false),
        22 if rt == 0 => branch(Branch::LessEqualZero, true, false),
        23 if rt == 0 => branch(Branch::GreaterZero, true, false),
        8 | 9 => make(Op::Immediate(Alu::Add), signed),
        10 => make(Op::Immediate(Alu::Less), signed),
        11 => make(Op::Immediate(Alu::LessUnsigned), signed),
        12 => make(Op::Immediate(Alu::And), unsigned),
        13 => make(Op::Immediate(Alu::Or), unsigned),
        14 => make(Op::Immediate(Alu::Xor), unsigned),
        15 if rs == 0 => make(Op::Lui, unsigned << 16),
        28 => match function {
            0 if rd == 0 && amount == 0 => make(
                Op::MultiplyAdd {
                    signed: true,
                    subtract: false,
                },
                0,
            ),
            1 if rd == 0 && amount == 0 => make(
                Op::MultiplyAdd {
                    signed: false,
                    subtract: false,
                },
                0,
            ),
            2 if amount == 0 => make(Op::MultiplyLow, 0),
            4 if rd == 0 && amount == 0 => make(
                Op::MultiplyAdd {
                    signed: true,
                    subtract: true,
                },
                0,
            ),
            5 if rd == 0 && amount == 0 => make(
                Op::MultiplyAdd {
                    signed: false,
                    subtract: true,
                },
                0,
            ),
            // The destination is written in both fields.
            32 if amount == 0 && rt == rd => make(Op::CountLeadingZeros, 0),
            33 if amount == 0 && rt == rd => make(Op::CountLeadingOnes, 0),
            _ => return None,
        },
        31 => match function {
            // The size less one is in `rd`; for an insertion `rd` holds the
            // highest bit, so the size is that less the position, plus one.
            0 => make(Op::Extract, i64::from(amount)),
            4 if u32::from(rd) >= amount => make(Op::Insert, i64::from(amount)),
            32 if rs == 0 && amount == 2 => make(Op::SwapBytesInHalves, 0),
            32 if rs == 0 && amount == 16 => make(Op::SignExtendByte, 0),
            32 if rs == 0 && amount == 24 => make(Op::SignExtendHalf, 0),
            // Register 29 holds the thread pointer.
            59 if rs == 0 && amount == 0 && rd == 29 => make(Op::ReadHardware, 0),
            _ => return None,
        },
        32 => load(1, true),
        33 => load(2, true),
        34 => make(Op::LoadLeft, signed),
        35 => load(4, false),
        36 => load(1, false),
        37 => load(2, false),
        38 => make(Op::LoadRight, signed),
        40 => make(Op::Store { bytes: 1 }, signed),
        41 => make(Op::Store { bytes: 2 }, signed),
        42 => make(Op::StoreLeft, signed),
        43 => make(Op::Store { bytes: 4 }, signed),
        46 => make(Op::StoreRight, signed),
        48 => make(Op::LoadLinked, signed),
        56 => make(Op::StoreConditional, signed),
        17 => return float(word, &make, signed),
        19 => {
            let double = function & 1 == 1;
            let op = match function {
                0 | 1 if rd == 0 => Op::FloatLoadIndexed { double },
                8 | 9 if amount == 0 => Op::FloatStoreIndexed { double },
                32 | 33 | 40 | 41 | 48 | 49 | 56 | 57 => Op::FloatMultiplyAdd {
                    subtract: function & 8 != 0,
                    negate: function & 16 != 0,
                    double,
                },
                _ => Op::Other,
            };
            make(op, i64::from(amount))
        }
        49 => make(Op::FloatLoad { double: false }, signed),
        53 => make(Op::FloatLoad { double: true }, signed),
        57 => make(Op::FloatStore { double: false }, signed),
        61 => make(Op::FloatStore { double: true }, signed),
        // The other coprocessors, their loads and stores, cache and
        // prefetch hints.
        16 | 18 | 47 | 50 | 51 | 54 | 55 | 58 | 59 | 62 | 63 => make(Op::Other, 0),
        _ => return None,
    })
}

/// An instruction of the float coprocessor.
fn float(word: u32, make: &impl Fn(Op, i64) -> Instruction, signed: i64) -> Option<Instruction> {
    let format = word >> 21 & 31;
    let ft = (word >> 16 & 31) as u8;
    let fd = i64::from(word >> 6 & 31);
    let function = word & 63;
    let low = word & 0x7ff;
    let double = format == 17;
    Some(match format {
        0 | 3 | 4 | 7 if low == 0 => make(
            Op::FloatTransfer {
                to_float: format & 4 != 0,
                high: format & 3 == 3,
            },
            0,
        ),
        2 | 6 if low == 0 => make(Op::FloatControl { write: format == 6 }, 0),
        8 => make(
            Op::FloatBranch {
                set: ft & 1 == 1,
                likely: ft & 2 != 0,
                flag: ft >> 2,
            },
            signed.wrapping_mul(4),
        ),
        16 | 17 => {
            let arithmetic = |op| make(Op::FloatArithmetic { op, double }, fd);
            let to_word = |rounding| make(Op::FloatToWord { rounding, double }, fd);
            match function {
                0 => arithmetic(FloatOp::Add),
                1 => arithmetic(FloatOp::Sub),
                2 => arithmetic(FloatOp::Mul),
                3 => arithmetic(FloatOp::Div),
                4 if ft == 0 => arithmetic(FloatOp::Sqrt),
                5 if ft == 0 => arithmetic(FloatOp::Abs),
                6 if ft == 0 => arithmetic(FloatOp::Move),
                7 if ft == 0 => arithmetic(FloatOp::Negate),
                12 if ft == 0 => to_word(Rounding::Nearest),
                13 if ft == 0 => to_word(Rounding::Zero),
                14 if ft == 0 => to_word(Rounding::Up),
                15 if ft == 0 => to_word(Rounding::Down),
                36 if ft == 0 => to_word(Rounding::Current),
                17 if ft & 2 == 0 => make(
                    Op::FloatSelect {
                        test: FloatTest::Flag {
                            set: ft & 1 == 1,
                            flag: ft >> 2,
                        },
                        double,
                    },
                    fd,
                ),
                18 => make(
                    Op::FloatSelect {
                        test: FloatTest::Zero,
                        double,
                    },
                    fd,
                ),
                19 => make(
                    Op::FloatSelect {
                        test: FloatTest::NotZero,
                        double,
                    },
                    fd,
                ),
                // A conversion to the format the value has is not defined.
                32 if ft == 0 && double => make(
                    Op::FloatConvert {
                        from: FloatFormat::Double,
                        double: false,
                    },
                    fd,
                ),
                33 if ft == 0 && !double => make(
                    Op::FloatConvert {
                        from: FloatFormat::Single,
                        double: true,
                    },
                    fd,
                ),
                48..=63 if fd & 3 == 0 => make(
                    Op::FloatCompare {
                        condition: (function & 15) as u8,
                        double,
                        flag: (fd >> 2) as u8,
                    },
                    0,
                ),
                _ => return None,
            }
        }
        20 if ft == 0 && matches!(function, 32 | 33) => make(
            Op::FloatConvert {
                from: FloatFormat::Word,
                double: function == 33,
            },
            fd,
        ),
        _ => return None,
    })
}