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
//! How wide an integer variable needs to be. One whose readers never look
//! above its low 8, 16 or 32 bits is declared with that many, and one that
//! only ever holds values of 32 bits with 32, so that C computes on it at
//! that width and the printer needs no masks or casts to bring its value
//! back to it.

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

use vlk_ir::ir::semantics::operand_width;
use vlk_ir::ir::{BinOp, Expr, FunctionIr, Operation, Stmt};

/// How a narrow variable holds its values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Narrow {
    /// Every reader looks at no more than the low `bits`, so the variable
    /// may take either sign; `extended` when some reader extends them with
    /// zeros, as a variable of no sign does by itself.
    Read { bits: u32, extended: bool },
    /// Every value assigned fits in `bits`, and must extend with zeros
    /// when a reader looks further.
    Held { bits: u32 },
}

impl Narrow {
    pub fn bits(self) -> u32 {
        match self {
            Narrow::Read { bits, .. } => bits,
            Narrow::Held { bits } => bits,
        }
    }
}

/// The integer variables among `ints` that take fewer than 64 bits.
/// `narrow` are those the body never reads wider than 32 bits, and
/// `pointers` the registers holding addresses, a sum with which the
/// printer prints whole.
pub fn narrow_variables(
    ir: &FunctionIr,
    ints: &HashSet<u16>,
    narrow: &HashSet<u16>,
    pointers: &HashSet<u16>,
) -> HashMap<u16, Narrow> {
    let held = super::value_width::value_bits(ir);
    let saved = saved_casts(ir, &held);
    let decide = |readers: &Readers| -> HashMap<u16, Narrow> {
        ints.iter()
            .filter_map(|index| {
                // A narrow variable saves a cast or a mask where the body
                // takes or reads a narrow part of it, and costs a cast where
                // C would compute on it narrower than the reader looks.
                // One nothing reads is as wide as an `int`; one the body
                // reads at no more than 32 bits, but for a whole register
                // a callee takes at its own width, is 32 bits wide.
                let bits = match readers.bits.get(index) {
                    None => Some(32),
                    Some(read) => [8, 16, 32].into_iter().find(|bits| read <= bits),
                }
                .or(narrow.contains(index).then_some(32));
                let kind = if let Some(bits) = bits {
                    Narrow::Read {
                        bits,
                        extended: readers.extended.contains(&(*index, bits)),
                    }
                } else if let Some(bits) = held
                    .get(index)
                    .and_then(|held| [8, 16, 32].into_iter().find(|bits| held <= bits))
                {
                    Narrow::Held { bits }
                } else {
                    return None;
                };
                let widened = readers.widened.get(index).copied().unwrap_or(0);
                let saved: usize = [8, 16, 32]
                    .into_iter()
                    .filter(|bits| *bits >= kind.bits())
                    .map(|bits| saved.get(&(*index, bits)).copied().unwrap_or(0))
                    .sum();
                if widened > 0 && widened >= saved {
                    return None;
                }
                Some((*index, kind))
            })
            .collect()
    };
    // Each round reads the assignments at the widths the last one gave
    // their destinations, which only grow, until they no longer change.
    let mut decided = decide(&Readers::default());
    for _ in 0..=ints.len() + 1 {
        let next = decide(&read_bits(ir, &decided, ints, pointers, &held));
        if next == decided {
            return decided;
        }
        decided = next;
    }
    HashMap::new()
}

/// For each register, the places a 64-bit variable would go through a mask
/// or a cast to fewer bits and a narrow one would not: an assignment of a
/// value masked to them or of a register read narrower, and a narrower
/// read of the register itself.
fn saved_casts(ir: &FunctionIr, held: &HashMap<u16, u32>) -> HashMap<(u16, u32), usize> {
    fn reads(expr: &Expr, held: &HashMap<u16, u32>, counts: &mut HashMap<(u16, u32), usize>) {
        match expr {
            Expr::Reg { index, width }
                if *width < 64 && held.get(index).is_none_or(|bits| *bits > u32::from(*width)) =>
            {
                *counts.entry((*index, u32::from(*width))).or_insert(0) += 1;
            }
            Expr::SignExtend { value, width }
                if let Expr::Reg { index, width: 64 } = value.as_ref() =>
            {
                *counts.entry((*index, u32::from(*width) * 8)).or_insert(0) += 1;
            }
            _ => {
                for child in vlk_ir::ir::visit::children(expr) {
                    reads(child, held, counts);
                }
            }
        }
    }
    let mut counts = HashMap::new();
    for stmt in ir.blocks.iter().flat_map(|block| &block.stmts) {
        if let Stmt::Assign { dest, value, .. } = stmt {
            let bits = match value {
                Expr::Bin {
                    op: BinOp::And,
                    rhs,
                    ..
                } => match rhs.as_ref() {
                    Expr::Const(mask @ (0xff | 0xffff | 0xffff_ffff)) => {
                        Some(64 - mask.leading_zeros())
                    }
                    _ => None,
                },
                Expr::Reg { width, .. } if *width < 64 => Some(u32::from(*width)),
                _ => None,
            };
            if let Some(bits) = bits {
                *counts.entry((dest.index, bits)).or_insert(0) += 1;
            }
        }
        for value in stmt.operands() {
            reads(value, held, &mut counts);
        }
    }
    counts
}

/// What the readers of each register ask of it.
#[derive(Default)]
pub(crate) struct Readers {
    /// The most low bits any reader looks at.
    pub(crate) bits: HashMap<u16, u32>,
    /// The readers that would compute on a narrow value at 64 bits, which
    /// C does only once the value is cast to a 64-bit type: a sum, a
    /// difference, a product or a left shift of it with a constant or
    /// another integer variable, its negation or its complement, whose
    /// result is read beyond 32 bits.
    pub(crate) widened: HashMap<u16, usize>,
    /// The registers some reader extends with zeros from the low bits
    /// given, reading further.
    pub(crate) extended: HashSet<(u16, u32)>,
}

/// The most low bits of each register any reader looks at, as the printer
/// asks for them, when the variables in `narrow` are as narrow as it says.
pub(crate) fn read_bits(
    ir: &FunctionIr,
    narrow: &HashMap<u16, Narrow>,
    ints: &HashSet<u16>,
    pointers: &HashSet<u16>,
    held: &HashMap<u16, u32>,
) -> Readers {
    let mut reads = Reads {
        readers: Readers::default(),
        ints,
        pointers,
        held,
        narrow_params: ir
            .params
            .iter()
            .filter(|param| param.ty.integer().is_some_and(|(bits, _)| bits <= 32))
            .map(|param| param.index)
            .collect(),
    };
    let returned = match ir.ret_type {
        vlk_types::types::CType::Void => 0,
        ref ty => ty.integer().map_or(64, |(bits, _)| bits),
    };
    for stmt in ir.blocks.iter().flat_map(|block| &block.stmts) {
        match stmt {
            Stmt::Assign { dest, value, .. } => {
                let bits = if let Some(narrow) = narrow.get(&dest.index) {
                    narrow.bits()
                } else {
                    ir.params
                        .iter()
                        .find(|param| param.index == dest.index)
                        .and_then(|param| param.ty.integer())
                        .map_or(64, |(bits, _)| bits)
                };
                reads.read_expression(value, bits);
            }
            // A choice stored in place is printed as a compare-and-exchange,
            // which reads its values whole.
            Stmt::Store {
                addr,
                value: value @ Expr::Select { .. },
                ..
            } => {
                reads.read_expression(addr, 64);
                reads.read_expression(value, 64);
            }
            Stmt::Store {
                addr, value, width, ..
            } => {
                reads.read_expression(addr, 64);
                reads.read_expression(value, u32::from(*width) * 8);
            }
            Stmt::Brif { lhs, rhs, .. } => reads.compared(lhs, rhs),
            Stmt::Switch { index, .. } => reads.compared(index, &Expr::Const(0)),
            Stmt::Ret { value, .. } => match value {
                Expr::Apply {
                    op: Operation::Results,
                    args,
                } => {
                    for (at, arg) in args.iter().enumerate() {
                        reads.read_expression(arg, if at == 0 { returned } else { 64 });
                    }
                }
                _ => reads.read_expression(value, returned),
            },
            _ => {
                for value in stmt.operands() {
                    reads.read_expression(value, 64);
                }
            }
        }
    }
    reads.readers
}

struct Reads<'a> {
    readers: Readers,
    ints: &'a HashSet<u16>,
    pointers: &'a HashSet<u16>,
    held: &'a HashMap<u16, u32>,
    /// The parameters of integer types no wider than 32 bits.
    narrow_params: HashSet<u16>,
}

impl Reads<'_> {
    fn note(&mut self, index: u16, bits: u32) {
        let entry = self.readers.bits.entry(index).or_insert(0);
        *entry = (*entry).max(bits);
    }

    /// Counts the reader of `expr`, an operand of an operation C computes
    /// at the type of its operands, when it is a register read whole, or
    /// some of its bits that C computes at its type, and the other operand,
    /// `other`, gives C no wider type. A register read narrower is cast
    /// whatever its type.
    fn widens(&mut self, expr: &Expr, other: Option<&Expr>, bits: u32) {
        fn register(expr: &Expr) -> Option<u16> {
            match expr {
                Expr::Reg { index, width: 64 } => Some(*index),
                Expr::Bin {
                    op: BinOp::And | BinOp::Shr,
                    lhs,
                    rhs,
                } if matches!(rhs.as_ref(), Expr::Const(_)) => register(lhs),
                _ => None,
            }
        }
        let Some(index) = register(expr) else {
            return;
        };
        let narrow_other = match other {
            None | Some(Expr::Const(_)) => true,
            Some(Expr::Reg { index, .. }) => {
                self.ints.contains(index) || self.narrow_params.contains(index)
            }
            Some(_) => false,
        };
        if bits > 32 && narrow_other {
            *self.readers.widened.entry(index).or_insert(0) += 1;
        }
    }

    /// The operands of a comparison at the wider of their widths. A narrow
    /// variable compared whole with a narrow parameter, which may differ in
    /// sign, is compared through a cast.
    fn compared(&mut self, lhs: &Expr, rhs: &Expr) {
        let bits = operand_width(lhs, rhs);
        for (side, other) in [(lhs, rhs), (rhs, lhs)] {
            if matches!(other, Expr::Reg { index, .. } if self.narrow_params.contains(index)) {
                self.widens(side, Some(other), bits);
            }
        }
        self.read_expression(lhs, bits);
        self.read_expression(rhs, bits);
    }

    /// The registers `expr` reads, when its reader looks at its low `bits`.
    fn read_expression(&mut self, expr: &Expr, bits: u32) {
        let bits = bits.min(64);
        match expr {
            Expr::Reg { index, width } => self.note(*index, bits.min(u32::from(*width))),
            Expr::Const(_) => {}
            Expr::Load { addr, .. } => self.read_expression(addr, 64),
            Expr::SignExtend { value, width } => self.read_expression(value, u32::from(*width) * 8),
            Expr::Select {
                lhs,
                rhs,
                then,
                els,
                ..
            } => {
                self.compared(lhs, rhs);
                self.read_expression(then, bits);
                self.read_expression(els, bits);
            }
            Expr::Apply { op, args } => {
                let bits = match op {
                    Operation::CountLeadingZeros(bits)
                    | Operation::CountTrailingZeros(bits)
                    | Operation::PopCount(bits) => {
                        if *bits == 64 {
                            64
                        } else {
                            32
                        }
                    }
                    Operation::ReverseBits(bits) => u32::from(*bits),
                    _ => 64,
                };
                for arg in args {
                    self.read_expression(arg, bits);
                }
            }
            Expr::Bin { op, lhs, rhs } => match op {
                BinOp::And
                    if let Expr::Const(mask) = rhs.as_ref()
                        && *mask != 0 =>
                {
                    let kept = 64 - mask.leading_zeros();
                    if bits > kept
                        && let Expr::Reg { index, .. } = lhs.as_ref()
                    {
                        self.readers.extended.insert((*index, kept));
                    }
                    self.read_expression(lhs, bits.min(kept));
                }
                // A sum through a pointer or a frame address is printed as
                // an index or an offset, whole.
                BinOp::Add | BinOp::Sub if bits < 64 && self.contains_pointer_term(expr) => {
                    self.read_expression(lhs, 64);
                    self.read_expression(rhs, 64);
                }
                BinOp::Sub if matches!(lhs.as_ref(), Expr::Const(0)) => {
                    self.widens(rhs, None, bits);
                    self.read_expression(rhs, bits);
                }
                BinOp::Xor if matches!(rhs.as_ref(), Expr::Const(u64::MAX)) => {
                    self.widens(lhs, None, bits);
                    self.read_expression(lhs, bits);
                }
                BinOp::Add | BinOp::Sub | BinOp::Mul => {
                    if super::value_width::value_width_in(expr, self.held) > 31 {
                        self.widens(lhs, Some(rhs), bits);
                        self.widens(rhs, Some(lhs), bits);
                    }
                    self.read_expression(lhs, bits);
                    self.read_expression(rhs, bits);
                }
                BinOp::And | BinOp::Or | BinOp::Xor => {
                    self.read_expression(lhs, bits);
                    self.read_expression(rhs, bits);
                }
                BinOp::Shl => {
                    if super::value_width::value_width_in(expr, self.held) > 31 {
                        self.widens(lhs, None, bits);
                    }
                    let kept = match rhs.as_ref() {
                        Expr::Const(amount) if *amount < 64 => bits.saturating_sub(*amount as u32),
                        _ => bits,
                    };
                    self.read_expression(lhs, kept);
                    self.read_expression(rhs, 64);
                }
                BinOp::Shr => {
                    let needed = match rhs.as_ref() {
                        Expr::Const(amount) => bits.saturating_add((*amount).min(64) as u32),
                        _ => 64,
                    };
                    self.read_expression(lhs, needed);
                    self.read_expression(rhs, 64);
                }
                BinOp::Sar => {
                    self.read_expression(lhs, operand_width(lhs, rhs));
                    self.read_expression(rhs, 64);
                }
                BinOp::DivS | BinOp::ModS => {
                    let width = operand_width(lhs, rhs);
                    self.read_expression(lhs, width);
                    self.read_expression(rhs, width);
                }
                BinOp::DivU | BinOp::ModU | BinOp::MulHigh | BinOp::MulHighS => {
                    self.read_expression(lhs, 64);
                    self.read_expression(rhs, 64);
                }
            },
        }
    }

    /// Whether a term of the sum `expr` is a pointer, or a 64-bit value
    /// loaded from memory that may be one.
    fn contains_pointer_term(&self, expr: &Expr) -> bool {
        let mut terms = Vec::new();
        vlk_ir::ir::visit::sum_terms(expr, false, &mut terms);
        terms.iter().any(|(term, _)| match term {
            Expr::Reg { index, .. } => self.pointers.contains(index),
            Expr::Load { width: 8, .. } => true,
            _ => false,
        })
    }
}

/// Registers never read wider than 32 bits, so their zero extension can be
/// left out.
pub fn narrow_registers(ir: &FunctionIr) -> std::collections::HashSet<u16> {
    let mut wide: std::collections::HashSet<u16> = std::collections::HashSet::new();
    let mut seen: std::collections::HashSet<u16> = std::collections::HashSet::new();
    for block in &ir.blocks {
        for stmt in &block.stmts {
            match stmt {
                Stmt::Machine { inputs, .. } => {
                    for input in inputs {
                        collect_register_read_widths(input, &mut seen, &mut wide);
                    }
                }
                Stmt::Assign { value, .. } => {
                    collect_register_read_widths(value, &mut seen, &mut wide)
                }
                Stmt::Store { addr, value, .. } => {
                    collect_register_read_widths(addr, &mut seen, &mut wide);
                    collect_register_read_widths(value, &mut seen, &mut wide);
                }
                Stmt::Brif { lhs, rhs, .. } => {
                    collect_register_read_widths(lhs, &mut seen, &mut wide);
                    collect_register_read_widths(rhs, &mut seen, &mut wide);
                }
                Stmt::Ret { value, .. } => {
                    collect_register_read_widths(value, &mut seen, &mut wide)
                }
                Stmt::BrIndirect { target, .. } => {
                    collect_register_read_widths(target, &mut seen, &mut wide)
                }
                Stmt::Switch { index, .. } => {
                    collect_register_read_widths(index, &mut seen, &mut wide)
                }
                Stmt::Call { .. } => {
                    for value in stmt.operands() {
                        collect_register_read_widths(value, &mut seen, &mut wide);
                    }
                }
                _ => {}
            }
        }
    }
    // The x86 segment bases and xmm halves have no 32-bit names to take.
    let named = |index: &u16| {
        ir.isa != vlk_base::target::Isa::X86_64 || !(16..vlk_ir::ir::TEMP_BASE).contains(index)
    };
    seen.into_iter()
        .filter(|index| !wide.contains(index) && named(index))
        .collect()
}

pub(crate) fn collect_register_read_widths(
    expr: &Expr,
    seen: &mut std::collections::HashSet<u16>,
    wide: &mut std::collections::HashSet<u16>,
) {
    match expr {
        Expr::Reg { index, width } => {
            seen.insert(*index);
            if u32::from(*width) > 32 {
                wide.insert(*index);
            }
        }
        Expr::Const(_) => {}
        Expr::Bin { op, lhs, rhs } => {
            // A read masked to 32 bits or fewer observes only the low 32 bits.
            if matches!(op, BinOp::And)
                && matches!(rhs.as_ref(), Expr::Const(mask) if *mask <= 0xffff_ffff)
                && let Expr::Reg { index, .. } = lhs.as_ref()
            {
                seen.insert(*index);
                collect_register_read_widths(rhs, seen, wide);
                return;
            }
            collect_register_read_widths(lhs, seen, wide);
            collect_register_read_widths(rhs, seen, wide);
        }
        Expr::Load { addr, .. } => collect_register_read_widths(addr, seen, wide),
        Expr::SignExtend { value, .. } => collect_register_read_widths(value, seen, wide),
        Expr::Select {
            lhs,
            rhs,
            then,
            els,
            ..
        } => {
            collect_register_read_widths(lhs, seen, wide);
            collect_register_read_widths(rhs, seen, wide);
            collect_register_read_widths(then, seen, wide);
            collect_register_read_widths(els, seen, wide);
        }
        Expr::Apply { args, .. } => {
            for arg in args {
                collect_register_read_widths(arg, seen, wide);
            }
        }
    }
}

#[cfg(test)]
mod tests;