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
use crate::passes::frame::reads_outside_frame;
use vlk_ir::ir::cfg::{live_in, live_outs, opaque};
use vlk_ir::ir::visit::assignment;
use vlk_ir::ir::visit::children;
use vlk_ir::ir::visit::count_register;
use vlk_ir::ir::visit::expr_reads;
use vlk_ir::ir::visit::expr_width;
use vlk_ir::ir::visit::reads_memory;
use vlk_ir::ir::visit::statement_reads;
use vlk_ir::ir::visit::statement_registers;
use vlk_ir::ir::{Cond, Expr, FunctionIr, Stmt, VARIABLE_BASE};

mod debug;
pub use debug::fold_stack_locals;
mod available;
pub use available::redundant_copy_renames;

/// Folds a definition read exactly once before its register is written again
/// into that reader, so `x8 = w8; if (x8 & 0x80000000) ...` keeps no temporary.
/// A definition a later block, or the next pass of a loop, may read stays.
pub fn inline_local_copies(ir: &mut FunctionIr) {
    crate::passes::checked(
        "passes::copies::inline_local_copies",
        ir,
        inline_local_copies_unchecked,
    )
}

fn inline_local_copies_unchecked(ir: &mut FunctionIr) {
    let live_in = live_in(ir);
    let live_out = live_outs(ir, &live_in);
    let params = parameter_registers(ir);
    let sp = vlk_arch::arch::stack_pointer(ir.isa);
    let private_frame = super::memory::fixed_private_frame(ir, sp);
    for (position, block) in ir.blocks.iter_mut().enumerate() {
        let mut index = 0;
        while index < block.stmts.len() {
            let Some((dest, value)) = (match &block.stmts[index] {
                Stmt::Assign { dest, value, .. } => {
                    Some((dest.index, truncated(value, dest.width)))
                }
                _ => None,
            }) else {
                index += 1;
                continue;
            };
            // The value's width must be known to check it against the read.
            if expr_width(&value).is_none() {
                index += 1;
                continue;
            }
            // The registers the value reads must not change before the use,
            // nor the memory it loads.
            let mut sources = std::collections::HashSet::new();
            vlk_ir::ir::visit::collect_reads(&value, &mut sources);
            let loads = reads_memory(&value);
            let mut reads = 0usize;
            let mut use_at = None;
            let mut clobbered = false;
            let mut redefined = false;
            for position in index + 1..block.stmts.len() {
                let stmt = &block.stmts[position];
                if use_at.is_none()
                    && super::memory::memory_ordering_barrier(stmt)
                    && !super::memory::crosses_atomic(&value, sp, private_frame)
                {
                    clobbered = true;
                    break;
                }
                if use_at.is_none()
                    && loads
                    && matches!(
                        stmt,
                        Stmt::Store { .. }
                            | Stmt::Call { .. }
                            | Stmt::Unsupported { .. }
                            | Stmt::Machine { .. }
                    )
                    && !super::memory::memory_ordering_barrier(stmt)
                    && !statement_reads(stmt).contains(&dest)
                {
                    clobbered = true;
                    break;
                }
                let used = statement_reads(stmt);
                if used.contains(&dest) {
                    // Folding into two reads would duplicate the value.
                    reads += count_register_reads(stmt, dest);
                    use_at = Some(position);
                }
                let written = statement_registers(stmt).0;
                if written.contains(&dest) {
                    redefined = true;
                    break;
                }
                if written.iter().any(|register| sources.contains(register)) {
                    clobbered = true;
                    break;
                }
            }
            // A later block may read the definition this block leaves behind.
            if !redefined && live_out[position].contains(&dest) {
                index += 1;
                continue;
            }
            let Some(use_at) = use_at else {
                index += 1;
                continue;
            };
            if reads != 1
                || clobbered
                || !further_result_moves(&block.stmts, index, use_at, &params)
            {
                index += 1;
                continue;
            }
            // Skip a reader that overwrites a register the value reads.
            if let Stmt::Assign { dest: reader, .. } = &block.stmts[use_at]
                && sources.contains(&reader.index)
            {
                index += 1;
                continue;
            }
            let mut substitution_valid = true;
            let mut folded = block.stmts[use_at].clone();
            substitute_in_statement(&mut folded, dest, &value, &mut substitution_valid);
            if !substitution_valid {
                index += 1;
                continue;
            }
            block.stmts[use_at] = folded;
            block.stmts.remove(index);
        }
    }
}

/// The value a register of `width` bits holds once it is assigned `value`:
/// a narrow destination drops the high bits a sum or product may carry.
pub(crate) fn truncated(value: &Expr, width: u8) -> Expr {
    let mask = vlk_ir::ir::semantics::mask(u32::from(width));
    if width >= 64 || crate::ssa::ranges::of(value).hi <= mask {
        return value.clone();
    }
    Expr::bin(vlk_ir::ir::BinOp::And, value.clone(), Expr::Const(mask))
}

pub(crate) fn comparison_preserved(cond: Cond, before: u32, lhs: &Expr, rhs: &Expr) -> bool {
    let after = vlk_ir::ir::semantics::operand_width(lhs, rhs);
    let mask = vlk_ir::ir::semantics::mask(before.min(after));
    before == after
        || (matches!(cond, Cond::Eq | Cond::Ne)
            && crate::ssa::ranges::of(lhs).hi <= mask
            && crate::ssa::ranges::of(rhs).hi <= mask)
}

/// Replaces every read of `dest` in one statement with the value; clears `ok`
/// when a read's width does not fit the value's.
fn substitute_in_statement(stmt: &mut Stmt, dest: u16, value: &Expr, ok: &mut bool) {
    if stmt.declared_call_reads().contains(&dest)
        || stmt
            .preserved_output_sources()
            .iter()
            .any(|(_, source)| *source == dest)
    {
        *ok = false;
        return;
    }
    let width = expr_width(value).unwrap_or(64);
    if let Stmt::Switch { index, .. } = stmt {
        substitute_register_in_expression(index, dest, width, value, ok);
    } else {
        substitute_ordinary(stmt, dest, width, value, ok);
    }
}

fn substitute_ordinary(stmt: &mut Stmt, dest: u16, width: u8, value: &Expr, ok: &mut bool) {
    match stmt {
        Stmt::Machine { inputs, .. } => {
            for input in inputs {
                substitute_register_in_expression(input, dest, width, value, ok);
            }
        }
        Stmt::Assign { value: target, .. } => {
            substitute_register_in_expression(target, dest, width, value, ok)
        }
        Stmt::Store {
            addr,
            value: stored,
            ..
        } => {
            substitute_register_in_expression(addr, dest, width, value, ok);
            substitute_register_in_expression(stored, dest, width, value, ok);
        }
        Stmt::Brif { cond, lhs, rhs, .. } => {
            let comparison = vlk_ir::ir::semantics::operand_width(lhs, rhs);
            substitute_register_in_expression(lhs, dest, width, value, ok);
            substitute_register_in_expression(rhs, dest, width, value, ok);
            *ok &= comparison_preserved(*cond, comparison, lhs, rhs);
        }
        Stmt::Ret {
            value: returned, ..
        } => substitute_register_in_expression(returned, dest, width, value, ok),
        Stmt::BrIndirect { target, .. } => {
            substitute_register_in_expression(target, dest, width, value, ok)
        }
        _ => *ok = false,
    }
}

/// Copy propagation: folds a single-use assignment (a register copy, a sign
/// extension or a small expression) into its only consumer when the widths
/// match, so no value is extended or truncated by accident.
pub fn copy_propagate(ir: &mut FunctionIr) {
    crate::passes::checked(
        "passes::copies::copy_propagate",
        ir,
        copy_propagate_unchecked,
    )
}

fn copy_propagate_unchecked(ir: &mut FunctionIr) {
    copy_propagate_with(ir, Duplication::Permit, &|_, _| true);
}

/// Copy propagation for use after CSE: does not duplicate a compound value
/// into several reads of one consumer.
pub fn copy_propagate_guarded(ir: &mut FunctionIr) {
    crate::passes::checked(
        "passes::copies::copy_propagate_guarded",
        ir,
        copy_propagate_guarded_unchecked,
    )
}

fn copy_propagate_guarded_unchecked(ir: &mut FunctionIr) {
    copy_propagate_with(ir, Duplication::Avoid, &|_, _| true);
}

/// Folds computed integer temporaries without removing pointer or register bindings.
pub fn integer_expression_candidate(ir: &FunctionIr) -> Option<FunctionIr> {
    let types = crate::analysis::variables::types(ir);
    if types
        .values()
        .chain(ir.value_types.values())
        .chain(ir.params.iter().map(|param| &param.ty))
        .chain(ir.debug_locals.iter().map(|local| &local.ty))
        .chain(ir.members.iter().map(|member| &member.ty))
        .chain(std::iter::once(&ir.ret_type))
        .any(|ty| {
            ty.is_sse_float()
                || matches!(ty, vlk_types::types::CType::Named(name) if name.split_whitespace().any(|word| word == "volatile"))
        })
    {
        return None;
    }
    // Physical vector registers can hold floating values as raw integer bits.
    for block in &ir.blocks {
        for stmt in &block.stmts {
            if stmt.operands().into_iter().any(super::read_once::floats) {
                return None;
            }
            let (writes, reads) = statement_registers(stmt);
            if writes
                .into_iter()
                .chain(reads)
                .any(|index| vlk_arch::arch::vector_half(ir.isa, index).is_some())
            {
                return None;
            }
        }
    }
    let mut narrow_parameters = Vec::new();
    for param in &ir.params {
        if let Some((bits, _)) = param.ty.integer()
            && bits < 64
        {
            narrow_parameters.push((param.index, bits));
        }
    }
    if !narrow_parameters.is_empty() {
        let Some(reads) = crate::ssa::entry_demands(ir, &[]) else {
            return None;
        };
        if narrow_parameters.iter().any(|(index, bits)| {
            reads.get(index).copied().unwrap_or(0) & !vlk_ir::ir::semantics::mask(*bits) != 0
        }) {
            return None;
        }
    }
    let statements: usize = ir.blocks.iter().map(|block| block.stmts.len()).sum();
    let mut folded = ir.clone();
    if folded.debug_locals.is_empty() && fold_stack_locals(&mut folded) {
        super::read_once::fold_values_read_once(&mut folded);
    }
    let sp = vlk_arch::arch::stack_pointer(ir.isa);
    copy_propagate_with(&mut folded, Duplication::Avoid, &|index, value| {
        index >= VARIABLE_BASE
            && matches!(types.get(&index), Some(vlk_types::types::CType::Int { .. }))
            && matches!(value, Expr::Bin { .. } | Expr::SignExtend { .. })
            && !reads_outside_frame(value, sp)
            && !vlk_ir::ir::visit::faults(value)
    });
    let remaining: usize = folded.blocks.iter().map(|block| block.stmts.len()).sum();
    (remaining < statements).then_some(folded)
}

/// The registers each block reads.
fn block_reads(ir: &FunctionIr) -> Vec<std::collections::HashSet<u16>> {
    ir.blocks
        .iter()
        .map(|block| {
            block
                .stmts
                .iter()
                .flat_map(|stmt| statement_registers(stmt).1)
                .collect()
        })
        .collect()
}

/// The registers some block other than `index` reads.
fn reads_elsewhere(
    reads: &[std::collections::HashSet<u16>],
    index: usize,
) -> std::collections::HashSet<u16> {
    reads
        .iter()
        .enumerate()
        .filter(|(other, _)| *other != index)
        .flat_map(|(_, set)| set.iter().copied())
        .collect()
}

fn copy_propagate_with(
    ir: &mut FunctionIr,
    duplication: Duplication,
    eligible: &impl Fn(u16, &Expr) -> bool,
) {
    let reads = block_reads(ir);
    // A register live on leaving the block, such as one a tail call through
    // an indirect jump reads or the block itself reads again on the next
    // pass of a loop, is kept too.
    let live_in = live_in(ir);
    let live_out = live_outs(ir, &live_in);
    let params = parameter_registers(ir);
    let sp = vlk_arch::arch::stack_pointer(ir.isa);
    let private_frame = super::memory::fixed_private_frame(ir, sp);
    for (index, block) in ir.blocks.iter_mut().enumerate() {
        if opaque(block) {
            continue;
        }
        let mut outer = reads_elsewhere(&reads, index);
        outer.extend(live_out[index].iter().copied());
        copy_propagate_block(
            block,
            &outer,
            &params,
            duplication,
            sp,
            private_frame,
            eligible,
        );
    }
}

/// Whether the last of `stmts` to write `register` is a call.
pub fn left_by_call(stmts: &[Stmt], register: u16) -> bool {
    stmts
        .iter()
        .rev()
        .find(|stmt| statement_registers(stmt).0.contains(&register))
        .is_some_and(|stmt| matches!(stmt, Stmt::Call { .. }))
}

/// Whether the copy at `index` may fold into `consumer`. One into a variable
/// of what a call before it left in a parameter's register, such as a
/// further result, only moves on into another variable: elsewhere the
/// register would read as the parameter it is named for.
fn further_result_moves(
    stmts: &[Stmt],
    index: usize,
    consumer: usize,
    params: &std::collections::HashSet<u16>,
) -> bool {
    let Stmt::Assign {
        dest,
        value: Expr::Reg { index: src, .. },
        ..
    } = &stmts[index]
    else {
        return true;
    };
    let further =
        dest.index >= VARIABLE_BASE && params.contains(src) && left_by_call(&stmts[..index], *src);
    !further
        || matches!(
            &stmts[consumer],
            Stmt::Assign {
                dest: next,
                value: Expr::Reg { index: read, width: 64 },
                ..
            } if next.index >= VARIABLE_BASE && next.width == 64 && *read == dest.index
        )
}

fn parameter_registers(ir: &FunctionIr) -> std::collections::HashSet<u16> {
    ir.params.iter().map(|param| param.index).collect()
}

#[derive(Clone, Copy)]
enum Duplication {
    Avoid,
    Permit,
}

fn copy_propagate_block(
    block: &mut vlk_ir::ir::Block,
    outer_reads: &std::collections::HashSet<u16>,
    params: &std::collections::HashSet<u16>,
    duplication: Duplication,
    sp: u16,
    private_frame: bool,
    eligible: &impl Fn(u16, &Expr) -> bool,
) {
    let duplication = matches!(duplication, Duplication::Avoid);
    let mut index = 0;
    while index < block.stmts.len() {
        let copy = match &block.stmts[index] {
            Stmt::Assign { dest, value, .. } if eligible(dest.index, value) => {
                // A value of unknown width, such as a sign extension, takes
                // the destination's width.
                let fold_width = expr_width(value).unwrap_or(dest.width);
                let foldable = match value {
                    Expr::Reg { index: src, .. } => *src != dest.index,
                    Expr::SignExtend { .. } => true,
                    // A read outside the frame may be volatile, and a large
                    // expression hurts readability once inlined.
                    _ => !reads_outside_frame(value, sp) && expr_size(value) <= 8,
                };
                foldable.then(|| (dest.index, fold_width, truncated(value, dest.width)))
            }
            _ => None,
        };
        let Some((dest, width, template)) = copy else {
            index += 1;
            continue;
        };
        // A read in another block keeps the temporary alive, unless this block
        // redefines it later so other blocks see that value instead.
        let redefined = block
            .stmts
            .iter()
            .skip(index + 1)
            .any(|stmt| statement_registers(stmt).0.contains(&dest));
        if outer_reads.contains(&dest) && !redefined {
            index += 1;
            continue;
        }
        // A value that reads its own destination cannot move.
        let mut sources: std::collections::HashSet<u16> = std::collections::HashSet::new();
        expr_reads(&template, &mut sources);
        if sources.contains(&dest) {
            index += 1;
            continue;
        }
        // Exactly one consumer, and no redefinition of the sources before it.
        let mut consumer = None;
        let mut foldable = true;
        let loads = reads_memory(&template);
        for later in index + 1..block.stmts.len() {
            if super::memory::memory_ordering_barrier(&block.stmts[later])
                && !super::memory::crosses_atomic(&template, sp, private_frame)
            {
                foldable = false;
                break;
            }
            let (writes, reads) = statement_registers(&block.stmts[later]);
            let reads_dest = reads.contains(&dest);
            if consumer.is_none()
                && loads
                && !reads_dest
                && match &block.stmts[later] {
                    Stmt::Store { addr, width, .. } => {
                        !super::memory::loads_avoid(&template, addr, *width)
                    }
                    Stmt::Call { .. } | Stmt::Unsupported { .. } | Stmt::Machine { .. } => true,
                    _ => false,
                }
                && !super::memory::memory_ordering_barrier(&block.stmts[later])
            {
                foldable = false;
                break;
            }
            // The consumer may rewrite a source: it reads before it writes.
            if writes.iter().any(|written| sources.contains(written)) && !reads_dest {
                foldable = false;
                break;
            }
            if reads_dest {
                if consumer.is_some() {
                    foldable = false;
                    break;
                }
                consumer = Some(later);
            }
            if writes.contains(&dest) {
                break;
            }
        }
        let Some(consumer) = consumer else {
            index += 1;
            continue;
        };
        if !foldable || !further_result_moves(&block.stmts, index, consumer, params) {
            index += 1;
            continue;
        }
        // Removing the copy is safe when the consumer redefines the register
        // or nothing else reads it before its next definition.
        let rewrites_dest = match assignment(&block.stmts[consumer]) {
            Some((dest_ref, _)) => dest_ref.index == dest,
            None => false,
        };
        let mut other_reads = block.stmts.iter().enumerate().any(|(position, stmt)| {
            position != consumer && position != index && statement_registers(stmt).1.contains(&dest)
        });
        if other_reads && !rewrites_dest {
            let mut escapes = false;
            for later in consumer + 1..block.stmts.len() {
                let (writes, reads) = statement_registers(&block.stmts[later]);
                if writes.contains(&dest) {
                    break;
                }
                if reads.contains(&dest) {
                    escapes = true;
                    break;
                }
            }
            other_reads = escapes;
        }
        if !rewrites_dest && other_reads {
            index += 1;
            continue;
        }
        // Inlining a compound value into two reads would undo CSE, and a
        // choice repeated reads as two.
        let reads_in_consumer = count_register_reads(&block.stmts[consumer], dest);
        if reads_in_consumer > 1
            && ((duplication && expr_size(&template) > 1) || contains_select(&template))
        {
            index += 1;
            continue;
        }
        if !substitute_statement(&mut block.stmts[consumer], dest, width, &template) {
            index += 1;
            continue;
        }
        block.stmts.remove(index);
        // `index` now names the statement after the removed copy.
    }
}

fn contains_select(expr: &Expr) -> bool {
    matches!(expr, Expr::Select { .. })
        || vlk_ir::ir::visit::children(expr)
            .into_iter()
            .any(contains_select)
}

/// How many times a statement reads one register.
fn count_register_reads(stmt: &Stmt, reg: u16) -> usize {
    let mut total = stmt
        .preserved_output_sources()
        .iter()
        .filter(|(_, source)| *source == reg)
        .count();
    total += usize::from(stmt.declared_call_reads().contains(&reg));
    match stmt {
        Stmt::Machine { inputs, .. } => {
            total += inputs
                .iter()
                .map(|input| count_register(input, reg))
                .sum::<usize>()
        }
        Stmt::Assign { value, .. } => total += count_register(value, reg),
        Stmt::Store { addr, value, .. } => {
            total += count_register(addr, reg) + count_register(value, reg);
        }
        Stmt::Brif { lhs, rhs, .. } => total += count_register(lhs, reg) + count_register(rhs, reg),
        Stmt::Ret { value, .. } => total += count_register(value, reg),
        Stmt::BrIndirect { target, .. } => total += count_register(target, reg),
        Stmt::Call {
            convention,
            through,
            args,
            floats_named,
            ..
        } => {
            total += through
                .iter()
                .map(|expr| count_register(expr, reg))
                .sum::<usize>();
            total += match args {
                Some(args) => args
                    .iter()
                    .map(|arg| count_register(arg, reg))
                    .sum::<usize>(),
                None => {
                    let mut addressing = rustc_hash::FxHashSet::default();
                    if let Some(through) = through {
                        vlk_ir::ir::visit::collect_reads(through, &mut addressing);
                    }
                    usize::from(
                        convention
                            .call_reads_through(&addressing, *floats_named)
                            .contains(&reg),
                    )
                }
            };
        }
        _ => {}
    }
    total
}

/// Number of expression nodes, used to keep inlining from exploding.
pub fn expr_size(expr: &Expr) -> usize {
    1 + children(expr).into_iter().map(expr_size).sum::<usize>()
}

fn substitute_statement(stmt: &mut Stmt, dest: u16, width: u8, template: &Expr) -> bool {
    if stmt.declared_call_reads().contains(&dest)
        || stmt
            .preserved_output_sources()
            .iter()
            .any(|(_, source)| *source == dest)
    {
        return false;
    }
    let mut folded = stmt.clone();
    let mut ok = true;
    match &mut folded {
        // A call naming its arguments reads nothing else of them.
        Stmt::Call {
            through,
            args: Some(args),
            convention,
            floats_named,
            ..
        } if !convention.unnamed_reads(*floats_named).contains(&dest) => {
            for expr in through.iter_mut().chain(args.iter_mut()) {
                substitute_register_in_expression(expr, dest, width, template, &mut ok);
            }
        }
        _ => substitute_ordinary(&mut folded, dest, width, template, &mut ok),
    }
    if ok {
        *stmt = folded;
    }
    ok
}

pub(crate) fn substitute_register_in_expression(
    expr: &mut Expr,
    dest: u16,
    width: u8,
    template: &Expr,
    ok: &mut bool,
) {
    if !*ok {
        return;
    }
    if let Expr::Reg { index, width: read } = expr {
        if *index == dest {
            let narrow_expression = matches!(expr_width(template), Some(32));
            if *read != width && !(narrow_expression && *read > 32 && width <= 32) {
                *ok = false;
                return;
            }
            *expr = truncated(template, *read);
        }
        return;
    }
    // A low-bit mask permits different expression widths, but the register
    // read still truncates before that mask.
    if let Expr::Bin {
        op: vlk_ir::ir::BinOp::And,
        lhs,
        rhs,
    } = expr
    {
        let mask = match rhs.as_ref() {
            Expr::Const(mask) => Some(*mask),
            _ => None,
        };
        if let Some(mask) = mask
            && mask <= 0xffff_ffff
            && let Expr::Reg { index, width: read } = lhs.as_ref()
            && *index == dest
            && matches!(expr_width(template), Some(32))
        {
            let kept_mask = mask;
            *expr = Expr::bin(
                vlk_ir::ir::BinOp::And,
                truncated(template, *read),
                Expr::constant(kept_mask),
            );
            return;
        }
    }
    match expr {
        Expr::Bin { op, lhs, rhs } => {
            // The operands' width decides the sign of these operations.
            let sensitive = matches!(
                op,
                vlk_ir::ir::BinOp::Sar | vlk_ir::ir::BinOp::DivS | vlk_ir::ir::BinOp::ModS
            );
            let before = vlk_ir::ir::semantics::operand_width(lhs, rhs);
            substitute_register_in_expression(lhs, dest, width, template, ok);
            substitute_register_in_expression(rhs, dest, width, template, ok);
            if sensitive && before != vlk_ir::ir::semantics::operand_width(lhs, rhs) {
                *ok = false;
            }
        }
        Expr::Select {
            cond,
            lhs,
            rhs,
            then,
            els,
        } => {
            let comparison = vlk_ir::ir::semantics::operand_width(lhs, rhs);
            substitute_register_in_expression(lhs, dest, width, template, ok);
            substitute_register_in_expression(rhs, dest, width, template, ok);
            substitute_register_in_expression(then, dest, width, template, ok);
            substitute_register_in_expression(els, dest, width, template, ok);
            *ok &= comparison_preserved(*cond, comparison, lhs, rhs);
        }
        Expr::Load { addr, .. } => {
            substitute_register_in_expression(addr, dest, width, template, ok)
        }
        Expr::SignExtend { value, .. } => {
            substitute_register_in_expression(value, dest, width, template, ok)
        }
        Expr::Apply { args, .. } => {
            for arg in args {
                substitute_register_in_expression(arg, dest, width, template, ok);
            }
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests;