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
//! The flags blocks pass to the blocks after them.

use std::collections::{HashMap, HashSet};

use vlk_base::target::Isa;
use vlk_ir::ir::{Block, Expr, FLAG_OPERANDS, RegRef, Stmt};

use super::{constants, flags, x86_64};

/// How a block leaves the flags: as its own code set them, if it changed
/// them, or else as they came in.
#[derive(Clone)]
pub(super) struct Exit {
    pub(super) flags: Option<flags::Flags>,
    pub(super) touched: bool,
}

/// What blocks begin with, found by lifting once: the flags each block
/// that reads them unknown should start from, with the blocks before them
/// that pass their flags on, and the constants the registers hold.
#[derive(Default)]
pub(super) struct Carried {
    pub(super) constants: HashMap<u64, constants::Facts>,
    pub(super) entry: HashMap<u64, flags::Flags>,
    pub(super) exporters: HashSet<u64>,
    pub(super) zero_exporters: HashSet<u64>,
    pub(super) condition_exporters: HashSet<u64>,
}

const ZERO_CARRIED: u16 = vlk_ir::ir::TEMP_BASE + 0x4c;
const CONDITION_BYTE: u16 = vlk_ir::ir::TEMP_BASE + 0x55;
const CONDITION_OVERFLOW: u16 = vlk_ir::ir::TEMP_BASE + 0x56;

/// The register a block's zero flag is carried in.
fn zero_carried(isa: Isa) -> u16 {
    if isa == Isa::Arm32 {
        vlk_ir::ir::TEMP_BASE + 0x54
    } else {
        ZERO_CARRIED
    }
}

/// The flags as a byte laid out as x86's `lahf` gives them, and the
/// overflow flag, where the value of each is known.
pub(super) fn condition_values(flags: &flags::Flags, isa: Isa) -> Option<(Expr, Expr)> {
    use vlk_ir::ir::{BinOp, Cond};
    let [
        (negative, _),
        (zero, _),
        (adjust, _),
        (parity, _),
        (not_carry, _),
    ] = flags.byte_tests(isa);
    let bit = |test: flags::Test| test.select(Expr::constant(1), Expr::constant(0));
    let (Some(negative), Some(zero), Some(not_carry), Some(overflow)) = (
        bit(negative),
        bit(zero),
        bit(not_carry),
        bit(flags.test(Cond::Vs, isa)),
    ) else {
        return None;
    };
    let mut byte = Expr::bin(
        BinOp::Or,
        Expr::bin(
            BinOp::Or,
            Expr::bin(BinOp::Shl, negative, Expr::constant(7)),
            Expr::bin(BinOp::Shl, zero, Expr::constant(6)),
        ),
        not_carry,
    );
    if matches!(isa, Isa::I386 | Isa::X86_64) {
        let Some(parity) = bit(parity) else {
            return None;
        };
        let Some(adjust) = bit(adjust) else {
            return None;
        };
        byte = Expr::bin(
            BinOp::Or,
            byte,
            Expr::bin(BinOp::Shl, parity, Expr::constant(2)),
        );
        byte = Expr::bin(
            BinOp::Or,
            byte,
            Expr::bin(BinOp::Shl, adjust, Expr::constant(4)),
        );
    }
    Some((byte, overflow))
}

/// What the blocks begin with after one lift: the flags of one shape that
/// the blocks before a block leave, else their values as a byte, else the
/// zero flag alone.
pub(super) fn flags(
    isa: Isa,
    blocks: &[Block],
    exits: &HashMap<u64, Exit>,
    extra_targets: &HashSet<u64>,
) -> Carried {
    let predecessors = flag_predecessors(blocks);
    let mut carried = carry_flags(blocks, exits, extra_targets, &predecessors);
    carry_conditions(
        isa,
        blocks,
        exits,
        extra_targets,
        &predecessors,
        &mut carried,
    );
    carry_zero(
        isa,
        blocks,
        exits,
        extra_targets,
        &predecessors,
        &mut carried,
    );
    carried
}

/// Blocks that read flags they do not know start from a stored byte of
/// them, where every block before them ends with flags whose values are
/// known.
fn carry_conditions(
    isa: Isa,
    blocks: &[Block],
    exits: &HashMap<u64, Exit>,
    extra_targets: &HashSet<u64>,
    predecessors: &[Vec<usize>],
    carried: &mut Carried,
) {
    if !matches!(isa, Isa::Arm32 | Isa::AArch64 | Isa::I386 | Isa::X86_64) {
        return;
    }
    if !blocks.iter().any(reads_unknown_flags) {
        return;
    }
    let known = known_flag_entries(blocks, exits, extra_targets, predecessors, |index, exit| {
        !blocks[index]
            .stmts
            .iter()
            .any(|stmt| matches!(stmt, Stmt::Unsupported { .. }))
            && exit
                .flags
                .as_ref()
                .and_then(|flags| condition_values(flags, isa))
                .is_some()
    });
    for (index, block) in blocks.iter().enumerate() {
        if !known[index] || !reads_unknown_flags(block) || carried.entry.contains_key(&block.start)
        {
            continue;
        }
        carried.entry.insert(
            block.start,
            flags::Flags::stored(
                Expr::reg(CONDITION_BYTE, 64),
                Some(Expr::reg(CONDITION_OVERFLOW, 64)),
            ),
        );
        flag_exporters(
            blocks,
            exits,
            predecessors,
            index,
            &mut carried.condition_exporters,
        );
    }
}

/// Normal predecessors in block and successor order, including repeated edges.
pub(super) fn flag_predecessors(blocks: &[Block]) -> Vec<Vec<usize>> {
    let mut predecessors = vec![Vec::new(); blocks.len()];
    for index in 0..blocks.len() {
        for next in vlk_ir::ir::cfg::block_successors(blocks, index) {
            predecessors[next].push(index);
        }
    }
    predecessors
}

/// Whether a block reads flags its own code did not set: a branch on them,
/// or a select, setcc or carry left unsupported for want of them.
fn reads_unknown_flags(block: &Block) -> bool {
    block.stmts.iter().any(|stmt| match stmt {
        Stmt::BrifFlags { .. }
        | Stmt::Machine {
            instruction: vlk_ir::ir::MachineInstruction::ReadFlags,
            ..
        } => true,
        Stmt::Unsupported { text, .. } => {
            text.contains("without compare") || text.contains("not modelled")
        }
        _ => false,
    })
}

/// The flags each block starts from, by a forward pass over the blocks: a
/// block that leaves the flags alone passes on what came in, one that sets
/// them passes on its own, and a join keeps flags only of one shape from
/// every block before it. Blocks that read flags they do not know start
/// from those; the blocks that set them pass their operands on. A
/// jump-table case may be entered by a jump the blocks do not show, so it
/// never takes flags.
pub(super) fn carry_flags(
    blocks: &[Block],
    exits: &HashMap<u64, Exit>,
    extra_targets: &HashSet<u64>,
    predecessors: &[Vec<usize>],
) -> Carried {
    let mut carried = Carried::default();
    let count = blocks.len();
    let exit = |index: usize| exits.get(&blocks[index].start);
    // The shape of the flags on entry to each block: None for unknown.
    let mut entry: Vec<Option<flags::Flags>> = vec![None; count];
    let opaque = |index: usize| index == 0 || extra_targets.contains(&blocks[index].start);
    let out = |index: usize, entry: &[Option<flags::Flags>]| match exit(index) {
        Some(Exit {
            touched: true,
            flags,
        }) => flags.as_ref().map(|flags| flags.carried().0),
        Some(Exit { touched: false, .. }) => entry[index].clone(),
        None => None,
    };
    loop {
        let mut changed = false;
        for index in 0..count {
            if opaque(index) || predecessors[index].is_empty() {
                continue;
            }
            let shapes: Vec<Option<flags::Flags>> = predecessors[index]
                .iter()
                .map(|pred| out(*pred, &entry))
                .collect();
            let merged = match shapes.first() {
                Some(Some(first)) if shapes.iter().all(|shape| shape.as_ref() == Some(first)) => {
                    Some(first.clone())
                }
                _ => None,
            };
            if merged != entry[index] {
                entry[index] = merged;
                changed = true;
            }
        }
        if !changed {
            break;
        }
    }
    for (index, block) in blocks.iter().enumerate() {
        if let Some(shape) = &entry[index]
            && reads_unknown_flags(block)
        {
            carried.entry.insert(block.start, shape.clone());
            flag_exporters(blocks, exits, predecessors, index, &mut carried.exporters);
        }
    }
    carried
}

/// A join may have a known zero flag even when its predecessors set it
/// with different operations or widths.
pub(super) fn carry_zero(
    isa: Isa,
    blocks: &[Block],
    exits: &HashMap<u64, Exit>,
    extra_targets: &HashSet<u64>,
    predecessors: &[Vec<usize>],
    carried: &mut Carried,
) {
    if !matches!(isa, Isa::X86_64 | Isa::I386 | Isa::Arm32) {
        return;
    }
    let zero = |exit: &Exit| {
        exit.flags.as_ref().and_then(|flags| {
            flags
                .test(vlk_ir::ir::Cond::Eq, isa)
                .select(Expr::constant(1), Expr::constant(0))
        })
    };
    let known = known_flag_entries(blocks, exits, extra_targets, predecessors, |_, exit| {
        zero(exit).is_some()
    });
    for (index, block) in blocks.iter().enumerate() {
        if !known[index] || !reads_unknown_flags(block) || carried.entry.contains_key(&block.start)
        {
            continue;
        }
        carried.entry.insert(
            block.start,
            flags::Flags::zero(Expr::reg(zero_carried(isa), 64)),
        );
        flag_exporters(
            blocks,
            exits,
            predecessors,
            index,
            &mut carried.zero_exporters,
        );
    }
}

/// Reachable entries whose every incoming path supplies the requested flags.
fn known_flag_entries(
    blocks: &[Block],
    exits: &HashMap<u64, Exit>,
    extra_targets: &HashSet<u64>,
    predecessors: &[Vec<usize>],
    available: impl Fn(usize, &Exit) -> bool,
) -> Vec<bool> {
    let mut reachable = vec![false; blocks.len()];
    let mut work = if blocks.is_empty() {
        Vec::new()
    } else {
        vec![0]
    };
    while let Some(index) = work.pop() {
        if reachable[index] {
            continue;
        }
        reachable[index] = true;
        work.extend(vlk_ir::ir::cfg::block_successors(blocks, index));
    }
    let mut known: Vec<_> = blocks
        .iter()
        .enumerate()
        .map(|(index, block)| {
            reachable[index]
                && index != 0
                && !extra_targets.contains(&block.start)
                && !predecessors[index].is_empty()
        })
        .collect();
    loop {
        let mut changed = false;
        for index in 1..blocks.len() {
            if !known[index] {
                continue;
            }
            if !predecessors[index]
                .iter()
                .all(|pred| match exits.get(&blocks[*pred].start) {
                    Some(exit) if exit.touched => available(*pred, exit),
                    Some(_) => known[*pred],
                    None => false,
                })
            {
                known[index] = false;
                changed = true;
            }
        }
        if !changed {
            break;
        }
    }
    known
}

/// Adds the blocks that set the flags block `index` begins with: those
/// reached backwards from it through blocks that leave the flags alone.
fn flag_exporters(
    blocks: &[Block],
    exits: &HashMap<u64, Exit>,
    predecessors: &[Vec<usize>],
    index: usize,
    exporters: &mut HashSet<u64>,
) {
    let mut work = predecessors[index].clone();
    let mut seen = HashSet::new();
    while let Some(pred) = work.pop() {
        if !seen.insert(pred) {
            continue;
        }
        match exits.get(&blocks[pred].start) {
            Some(exit) if exit.touched => {
                exporters.insert(blocks[pred].start);
            }
            _ => work.extend(predecessors[pred].iter().copied()),
        }
    }
}

/// Ends a block: a block whose flags carry on passes their operands, before
/// the branch that leaves it.
pub(super) fn finish_block(
    exit: Option<flags::Flags>,
    touched: bool,
    isa: Isa,
    start: u64,
    mut stmts: Vec<Stmt>,
    carried: &Carried,
    exits: &mut HashMap<u64, Exit>,
) -> Block {
    if carried.condition_exporters.contains(&start)
        && touched
        && let Some(flags) = &exit
        && let Some((byte, overflow)) = condition_values(flags, isa)
    {
        let at = stmts
            .iter()
            .position(|stmt| {
                matches!(
                    stmt,
                    Stmt::Br { .. }
                        | Stmt::Brif { .. }
                        | Stmt::BrifFlags { .. }
                        | Stmt::Switch { .. }
                        | Stmt::BrIndirect { .. }
                )
            })
            .unwrap_or(stmts.len());
        stmts.splice(
            at..at,
            [(CONDITION_BYTE, byte), (CONDITION_OVERFLOW, overflow)]
                .into_iter()
                .map(|(index, value)| Stmt::Assign {
                    dest: RegRef { index, width: 64 },
                    value,
                    at: None,
                }),
        );
    }
    if carried.exporters.contains(&start)
        && touched
        && let Some(flags) = &exit
    {
        let (_, values) = flags.carried();
        let at = match stmts.last() {
            Some(
                Stmt::Br { .. }
                | Stmt::Brif { .. }
                | Stmt::BrifFlags { .. }
                | Stmt::Switch { .. }
                | Stmt::BrIndirect { .. },
            ) => stmts.len() - 1,
            _ => stmts.len(),
        };
        let passes = vlk_ir::ir::FLAG_CARRIED
            .into_iter()
            .zip(values)
            .map(|(slot, value)| Stmt::Assign {
                dest: RegRef {
                    index: slot,
                    width: 64,
                },
                value,
                at: None,
            });
        stmts.splice(at..at, passes);
    }
    if carried.zero_exporters.contains(&start)
        && let Some(flags) = &exit
        && let Some(value) = flags
            .test(vlk_ir::ir::Cond::Eq, isa)
            .select(Expr::constant(1), Expr::constant(0))
    {
        let at = stmts
            .iter()
            .position(|stmt| {
                matches!(
                    stmt,
                    Stmt::Br { .. }
                        | Stmt::Brif { .. }
                        | Stmt::BrifFlags { .. }
                        | Stmt::Switch { .. }
                        | Stmt::BrIndirect { .. }
                )
            })
            .unwrap_or(stmts.len());
        stmts.insert(
            at,
            Stmt::Assign {
                dest: RegRef {
                    index: zero_carried(isa),
                    width: 64,
                },
                value,
                at: None,
            },
        );
    }
    exits.insert(
        start,
        Exit {
            flags: exit,
            touched: touched || stmts.iter().any(|stmt| matches!(stmt, Stmt::Call { .. })),
        },
    );
    Block { start, stmts }
}

/// Removes the copies of compare operands no branch went on to read: most
/// instructions set flags that nothing tests.
pub(super) fn drop_unread_compare_operands(blocks: &mut [Block]) {
    let mut read = HashSet::new();
    for stmt in blocks.iter().flat_map(|block| &block.stmts) {
        read.extend(
            vlk_ir::ir::visit::statement_registers(stmt)
                .1
                .into_iter()
                .filter(|register| FLAG_OPERANDS.contains(register)),
        );
    }
    for block in blocks.iter_mut() {
        block.stmts.retain(|stmt| {
            !matches!(stmt, Stmt::Assign { dest, .. }
                if FLAG_OPERANDS.contains(&dest.index) && !read.contains(&dest.index))
        });
    }
    let saved = [
        x86_64::string::STRING_FLAGS,
        x86_64::string::STRING_OVERFLOW,
    ];
    if !blocks
        .iter()
        .flat_map(|block| &block.stmts)
        .any(|stmt| matches!(stmt, Stmt::Assign { dest, .. } if saved.contains(&dest.index)))
    {
        return;
    }
    let bits = |registers: &rustc_hash::FxHashSet<u16>| {
        u8::from(registers.contains(&saved[0])) | (u8::from(registers.contains(&saved[1])) << 1)
    };
    let mut incoming = vec![0u8; blocks.len()];
    let mut outgoing = incoming.clone();
    loop {
        let mut changed = false;
        for index in (0..blocks.len()).rev() {
            let mut live = 0;
            for next in vlk_ir::ir::cfg::block_successors(blocks, index) {
                live |= incoming[next];
            }
            outgoing[index] = live;
            for stmt in blocks[index].stmts.iter().rev() {
                let (writes, reads) = vlk_ir::ir::visit::statement_registers(stmt);
                live = (live & !bits(&writes)) | bits(&reads);
            }
            changed |= incoming[index] != live;
            incoming[index] = live;
        }
        if !changed {
            break;
        }
    }
    for (block, mut live) in blocks.iter_mut().zip(outgoing) {
        let mut kept = Vec::new();
        for stmt in block.stmts.drain(..).rev() {
            if matches!(&stmt, Stmt::Assign { dest, .. } if saved.contains(&dest.index) && live & (1 << (dest.index - saved[0])) == 0)
            {
                continue;
            }
            let (writes, reads) = vlk_ir::ir::visit::statement_registers(&stmt);
            live = (live & !bits(&writes)) | bits(&reads);
            kept.push(stmt);
        }
        kept.reverse();
        block.stmts = kept;
    }
}