vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
use std::collections::HashMap;
use vlk_arch::arch::{stack_pointer, x86};

use vlk_ir::ir::visit::statement_registers;
use vlk_ir::ir::{Expr, FunctionIr, Stmt};

/// Removes stores to frame slots that nothing reads. Does nothing when any
/// frame address escapes.
pub fn drop_dead_frame_stores(ir: &mut FunctionIr) {
    crate::passes::checked(
        "passes::frame::drop_dead_frame_stores",
        ir,
        drop_dead_frame_stores_unchecked,
    )
}

fn drop_dead_frame_stores_unchecked(ir: &mut FunctionIr) {
    let sp = stack_pointer(ir.isa);
    let spills = if ir
        .blocks
        .iter()
        .flat_map(|block| &block.stmts)
        .any(|stmt| statement_registers(stmt).0.contains(&sp))
    {
        None
    } else {
        crate::passes::memory::spill_range(ir)
    };
    // Every frame-slot range the body reads, and whether a frame address escapes.
    let mut read: Vec<(u64, u8)> = Vec::new();
    let mut escaped = false;
    let mut stores: Vec<(usize, usize, u64, u8)> = Vec::new();
    for (position, block) in ir.blocks.iter().enumerate() {
        for (index, stmt) in block.stmts.iter().enumerate() {
            // A declared call may read any frame slot through memory.
            if stmt.has_deferred_call_memory() {
                return;
            }
            match stmt {
                Stmt::Store {
                    addr, value, width, ..
                } => {
                    if let Some(slot) = frame_slot_of(addr, sp) {
                        if crate::passes::frame_slots::checked_frame_slot(addr, 0, sp).is_some_and(
                            |offset| crate::passes::memory::private_slot(offset, *width, spills),
                        ) {
                            stores.push((position, index, slot, *width));
                        }
                    } else {
                        // The address may be computed from slots it loads.
                        collect_frame_reads(addr, sp, &mut read);
                        if address_uses_frame(addr, sp) {
                            escaped = true;
                        }
                    }
                    collect_frame_reads(value, sp, &mut read);
                    if address_uses_frame(value, sp) {
                        escaped = true;
                    }
                }
                Stmt::Assign { dest, value, .. } => {
                    // Adjusting the stack pointer does not make a frame address escape.
                    if dest.index == sp {
                        continue;
                    }
                    collect_frame_reads(value, sp, &mut read);
                    if let Expr::Load { addr, .. } = value {
                        if frame_slot_of(addr, sp).is_none() && address_uses_frame(addr, sp) {
                            escaped = true;
                        }
                    } else if address_uses_frame(value, sp) {
                        escaped = true;
                    }
                }
                Stmt::Ret {
                    value: read_value, ..
                }
                | Stmt::Switch {
                    index: read_value, ..
                }
                | Stmt::BrIndirect {
                    target: read_value, ..
                } => {
                    collect_frame_reads(read_value, sp, &mut read);
                    if address_uses_frame(read_value, sp) {
                        escaped = true;
                    }
                }
                Stmt::Brif { lhs, rhs, .. } => {
                    collect_frame_reads(lhs, sp, &mut read);
                    collect_frame_reads(rhs, sp, &mut read);
                    if address_uses_frame(lhs, sp) || address_uses_frame(rhs, sp) {
                        escaped = true;
                    }
                }
                // A callee whose arguments are known reads its stack ones
                // through the loads among them; any other may read the
                // frame anywhere.
                Stmt::Call {
                    through,
                    args: Some(args),
                    ..
                } => {
                    for value in through.iter().chain(args) {
                        collect_frame_reads(value, sp, &mut read);
                        if address_uses_frame(value, sp) {
                            escaped = true;
                        }
                    }
                }
                Stmt::Machine { inputs, .. } => {
                    for value in inputs {
                        collect_frame_reads(value, sp, &mut read);
                        if address_uses_frame(value, sp) {
                            escaped = true;
                        }
                    }
                }
                Stmt::Call { .. } => escaped = true,
                _ => {}
            }
        }
    }
    // An escaped frame address may be read through elsewhere, e.g. by a callee.
    if escaped {
        return;
    }
    let overlaps = |slot: u64, width: u8| {
        let (start, end) = (slot as i64, slot as i64 + i64::from(width));
        read.iter().any(|(other, other_width)| {
            let (other_start, other_end) = (*other as i64, *other as i64 + i64::from(*other_width));
            start < other_end && other_start < end
        })
    };
    let dead: std::collections::HashSet<(usize, usize)> = stores
        .into_iter()
        .filter(|(position, index, slot, width)| {
            !overlaps(*slot, *width)
                || overwritten(&ir.blocks[*position].stmts, *index, *slot, *width, sp)
        })
        .map(|(position, index, _, _)| (position, index))
        .collect();
    if dead.is_empty() {
        return;
    }
    for (position, block) in ir.blocks.iter_mut().enumerate() {
        let mut index = 0;
        block.stmts.retain(|_| {
            let keep = !dead.contains(&(position, index));
            index += 1;
            keep
        });
    }
}

/// True when later stores in the block cover every byte of the store at
/// `index` before anything reads them.
fn overwritten(stmts: &[Stmt], index: usize, slot: u64, width: u8, sp: u16) -> bool {
    let start = slot as i64;
    let end = start + i64::from(width);
    let mut covered = vec![false; usize::from(width)];
    for stmt in &stmts[index + 1..] {
        let mut read = Vec::new();
        match stmt {
            Stmt::Store {
                addr, value, width, ..
            } => {
                collect_frame_reads(addr, sp, &mut read);
                collect_frame_reads(value, sp, &mut read);
                if read.iter().any(|(other, other_width)| {
                    let other = *other as i64;
                    other < end && start < other + i64::from(*other_width)
                }) {
                    return false;
                }
                if let Some(other) = frame_slot_of(addr, sp) {
                    let other = other as i64;
                    for byte in other.max(start)..(other + i64::from(*width)).min(end) {
                        covered[(byte - start) as usize] = true;
                    }
                    if covered.iter().all(|byte| *byte) {
                        return true;
                    }
                }
            }
            Stmt::Assign { dest, value, .. } => {
                if dest.index == sp {
                    return false;
                }
                collect_frame_reads(value, sp, &mut read);
                if read.iter().any(|(other, other_width)| {
                    let other = *other as i64;
                    other < end && start < other + i64::from(*other_width)
                }) {
                    return false;
                }
            }
            _ => return false,
        }
    }
    false
}

/// The offset `k` of an address that is exactly `sp + k`.
fn frame_slot_of(addr: &Expr, sp: u16) -> Option<u64> {
    match addr {
        Expr::Reg { index, .. } if *index == sp => Some(0),
        Expr::Bin {
            op: vlk_ir::ir::BinOp::Add,
            lhs,
            rhs,
        } => match (lhs.as_ref(), rhs.as_ref()) {
            (Expr::Reg { index, .. }, Expr::Const(delta)) if *index == sp => Some(*delta),
            (Expr::Const(delta), Expr::Reg { index, .. }) if *index == sp => Some(*delta),
            _ => None,
        },
        Expr::Bin {
            op: vlk_ir::ir::BinOp::Sub,
            lhs,
            rhs,
        } => match (lhs.as_ref(), rhs.as_ref()) {
            (Expr::Reg { index, .. }, Expr::Const(delta)) if *index == sp => {
                Some(delta.wrapping_neg())
            }
            _ => None,
        },
        _ => None,
    }
}

fn collect_frame_reads(expr: &Expr, sp: u16, read: &mut Vec<(u64, u8)>) {
    match expr {
        Expr::Load { addr, width, .. } => match frame_slot_of(addr, sp) {
            Some(slot) => read.push((slot, *width)),
            None => collect_frame_reads(addr, sp, read),
        },
        Expr::Bin { lhs, rhs, .. } => {
            collect_frame_reads(lhs, sp, read);
            collect_frame_reads(rhs, sp, read);
        }
        Expr::SignExtend { value, .. } => collect_frame_reads(value, sp, read),
        Expr::Select {
            lhs,
            rhs,
            then,
            els,
            ..
        } => {
            collect_frame_reads(lhs, sp, read);
            collect_frame_reads(rhs, sp, read);
            collect_frame_reads(then, sp, read);
            collect_frame_reads(els, sp, read);
        }
        Expr::Apply { args, .. } => {
            for arg in args {
                collect_frame_reads(arg, sp, read);
            }
        }
        Expr::Reg { .. } | Expr::Const(_) => {}
    }
}

/// True when the expression computes a stack address other than a plain slot
/// access; such a value may reach a callee.
fn address_uses_frame(expr: &Expr, sp: u16) -> bool {
    match expr {
        Expr::Reg { index, .. } => *index == sp,
        // A load through a slot is a local read; any other load still carries
        // the address it computed.
        Expr::Load { addr, .. } => {
            frame_slot_of(addr, sp).is_none() && address_uses_frame(addr, sp)
        }
        Expr::Bin { lhs, rhs, .. } => address_uses_frame(lhs, sp) || address_uses_frame(rhs, sp),
        Expr::SignExtend { value, .. } => address_uses_frame(value, sp),
        Expr::Select {
            lhs,
            rhs,
            then,
            els,
            ..
        } => {
            address_uses_frame(lhs, sp)
                || address_uses_frame(rhs, sp)
                || address_uses_frame(then, sp)
                || address_uses_frame(els, sp)
        }
        Expr::Apply { args, .. } => args.iter().any(|arg| address_uses_frame(arg, sp)),
        Expr::Const(_) => false,
    }
}

/// Removes callee-saved register spills (a register stored to a slot and
/// reloaded from it, untouched in between), plus the stack adjustments when
/// the stack has no other use.
///
/// The frame displacement on entry to each block follows the control flow,
/// so the save and the restores resolve to the same slot across blocks and
/// stack adjustments.
pub fn elide_callee_saves(ir: &mut FunctionIr) {
    crate::passes::checked(
        "passes::frame::elide_callee_saves",
        ir,
        elide_callee_saves_unchecked,
    )
}

fn elide_callee_saves_unchecked(ir: &mut FunctionIr) {
    if ir
        .blocks
        .iter()
        .flat_map(|block| &block.stmts)
        .any(Stmt::has_deferred_call_memory)
    {
        return;
    }
    let sp = stack_pointer(ir.isa);
    let mut accesses: Vec<Access> = Vec::new();
    let frames = crate::passes::frame_slots::block_entry_frame_offsets(ir, sp);
    for (block_index, block) in ir.blocks.iter().enumerate() {
        // A block whose frame the paths into it disagree on names no slot.
        let Some(mut frame) = frames[block_index] else {
            continue;
        };
        for (position, stmt) in block.stmts.iter().enumerate() {
            match stmt {
                Stmt::Store { addr, value, .. } => {
                    let slot = stack_slot(addr, frame, sp);
                    if let (Some(slot), Expr::Reg { index, .. }) = (slot, value) {
                        accesses.push(Access {
                            block: block_index,
                            position,
                            slot,
                            store: true,
                            register: *index,
                        });
                    }
                }
                Stmt::Assign { dest, value, .. } => {
                    if let Expr::Load { addr, .. } = value
                        && let Some(slot) = stack_slot(addr, frame, sp)
                    {
                        accesses.push(Access {
                            block: block_index,
                            position,
                            slot,
                            store: false,
                            register: dest.index,
                        });
                    }
                    if dest.index == sp
                        && let Some(delta) = stack_delta(value, sp)
                    {
                        frame = frame.wrapping_add(delta);
                    }
                }
                _ => {}
            }
        }
    }
    // Each slot must be written once and only read back into the same
    // register, once per return path, with that register untouched between
    // the save and each restore.
    let mut by_slot: HashMap<i64, Vec<usize>> = HashMap::new();
    for (index, access) in accesses.iter().enumerate() {
        by_slot.entry(access.slot).or_default().push(index);
    }
    let mut drop: std::collections::HashSet<(usize, usize)> = std::collections::HashSet::new();
    let mut saved: Vec<i64> = Vec::new();
    for list in by_slot.values() {
        let [save, restores @ ..] = list.as_slice() else {
            continue;
        };
        let first = &accesses[*save];
        if restores.is_empty()
            || !first.store
            || first.register == sp
            || restores.iter().any(|index| {
                let restore = &accesses[*index];
                restore.store || restore.register != first.register
            })
        {
            continue;
        }
        // Nothing else in the function may touch the register, whatever the
        // path: the save and its restores are the register's only uses, apart
        // from a frame pointer setup that nothing reads through.
        let round_trip: Vec<(usize, usize)> = list
            .iter()
            .map(|index| (accesses[*index].block, accesses[*index].position))
            .collect();
        let mut register_used_elsewhere = false;
        let mut frame_setup: Option<(usize, usize)> = None;
        'scan: for (block_index, block) in ir.blocks.iter().enumerate() {
            for (position, stmt) in block.stmts.iter().enumerate() {
                if round_trip.contains(&(block_index, position)) {
                    continue;
                }
                let (writes, reads) = statement_registers(stmt);
                if reads.contains(&first.register) {
                    register_used_elsewhere = true;
                    break 'scan;
                }
                if writes.contains(&first.register) {
                    if frame_setup.is_none() && is_frame_setup(stmt, sp) {
                        frame_setup = Some((block_index, position));
                        continue;
                    }
                    register_used_elsewhere = true;
                    break 'scan;
                }
            }
        }
        if register_used_elsewhere {
            // A callee-saved register the body uses is still only preserved
            // for the caller when the entry saves it and each return restores
            // it: the round trip says nothing about the function itself,
            // unless the body reads the saved value through the frame pointer.
            if callee_saved(ir, first.register, sp)
                && !reads_through_stack_pointer_copy(ir, sp)
                && saves_entry_value(ir, first)
                && restores
                    .iter()
                    .all(|index| restores_on_return(ir, &accesses[*index]))
            {
                drop.insert((first.block, first.position));
                saved.push(first.slot);
                for restore in restores.iter().map(|index| &accesses[*index]) {
                    drop.insert((restore.block, restore.position));
                }
            }
            continue;
        }
        drop.insert((first.block, first.position));
        saved.push(first.slot);
        for restore in restores.iter().map(|index| &accesses[*index]) {
            drop.insert((restore.block, restore.position));
        }
        if let Some(position) = frame_setup {
            drop.insert(position);
        }
    }
    for slot in saved {
        if !ir.saved_slots.contains(&slot) {
            ir.saved_slots.push(slot);
        }
    }
    if drop.is_empty() {
        return;
    }
    // A frame that only held the spills can go too.
    let stack_still_used = ir.blocks.iter().enumerate().any(|(block_index, block)| {
        block.stmts.iter().enumerate().any(|(position, stmt)| {
            if drop.contains(&(block_index, position)) {
                return false;
            }
            let (writes, reads) = statement_registers(stmt);
            let touched = reads.contains(&sp) || writes.contains(&sp);
            if !touched {
                return false;
            }
            !matches!(
                stmt,
                Stmt::Assign { dest, value, .. } if dest.index == sp && stack_delta(value, sp).is_some()
            )
        })
    });
    if !stack_still_used {
        for (block_index, block) in ir.blocks.iter().enumerate() {
            for (position, stmt) in block.stmts.iter().enumerate() {
                if let Stmt::Assign { dest, value, .. } = stmt
                    && dest.index == sp
                    && stack_delta(value, sp).is_some()
                {
                    drop.insert((block_index, position));
                }
            }
        }
    }
    for (block_index, block) in ir.blocks.iter_mut().enumerate() {
        let mut position = 0;
        block.stmts.retain(|_| {
            let keep = !drop.contains(&(block_index, position));
            position += 1;
            keep
        });
    }
}

struct Access {
    block: usize,
    position: usize,
    slot: i64,
    store: bool,
    register: u16,
}

/// Drops the pushes of a scratch register the entry block makes before
/// writing it, as `push rax` does to align the stack: the register holds no
/// argument there, and no load reads the slot.
pub fn drop_alignment_pushes(ir: &mut FunctionIr) {
    crate::passes::checked(
        "passes::frame::drop_alignment_pushes",
        ir,
        drop_alignment_pushes_unchecked,
    )
}

fn drop_alignment_pushes_unchecked(ir: &mut FunctionIr) {
    use vlk_types::types::Convention;
    if ir
        .blocks
        .iter()
        .flat_map(|block| &block.stmts)
        .any(Stmt::has_deferred_call_memory)
    {
        return;
    }
    if !matches!(ir.convention, Convention::SysV | Convention::Win64) {
        return;
    }
    let sp = stack_pointer(ir.isa);
    let arguments = ir.convention.arguments();
    let loads_from_frame = ir.blocks.iter().flat_map(|block| &block.stmts).any(|stmt| {
        let mut read = Vec::new();
        for operand in stmt.operands() {
            collect_frame_reads(operand, sp, &mut read);
        }
        !read.is_empty()
    });
    if loads_from_frame {
        return;
    }
    let Some(entry) = ir.blocks.first_mut() else {
        return;
    };
    let mut written = std::collections::HashSet::new();
    let mut keep = Vec::with_capacity(entry.stmts.len());
    for stmt in entry.stmts.drain(..) {
        let pushed = matches!(&stmt, Stmt::Store {
                addr,
                value: Expr::Reg { index, width: 64 },
                width: 8,
                ..
            } if frame_slot_of(addr, sp).is_some()
                && *index != sp
                && !arguments.contains(index)
                && ir.convention.clobbered().contains(index)
                && !written.contains(index));
        written.extend(vlk_ir::ir::visit::statement_registers(&stmt).0);
        if !pushed {
            keep.push(stmt);
        }
    }
    entry.stmts = keep;
}

fn callee_saved(ir: &FunctionIr, reg: u16, sp: u16) -> bool {
    // A function returns through the link register it was entered with
    // under any convention, Go's included, which keeps no other register.
    let link = vlk_arch::arch::link_register(ir.isa) == Some(reg);
    reg != sp && reg < 32 && (link || !ir.convention.clobbered().contains(&reg))
}

/// The save stores the register's value on entry: nothing writes it before
/// the save in its block, nor in any block a path from the entry passes
/// on the way there, as when the prologue waits past an early return.
fn saves_entry_value(ir: &FunctionIr, save: &Access) -> bool {
    let writes = |stmts: &[Stmt]| {
        stmts
            .iter()
            .any(|stmt| statement_registers(stmt).0.contains(&save.register))
    };
    if writes(&ir.blocks[save.block].stmts[..save.position]) {
        return false;
    }
    if save.block == 0 {
        return true;
    }
    // The blocks from which the save's block can be reached.
    let successors: Vec<Vec<usize>> = (0..ir.blocks.len())
        .map(|index| vlk_ir::ir::cfg::block_successors(&ir.blocks, index))
        .collect();
    let mut before = std::collections::HashSet::new();
    let mut work = vec![save.block];
    while let Some(block) = work.pop() {
        for (from, next) in successors.iter().enumerate() {
            if next.contains(&block) && before.insert(from) {
                work.push(from);
            }
        }
    }
    !before.contains(&save.block)
        && before.contains(&0)
        && before.iter().all(|block| !writes(&ir.blocks[*block].stmts))
}

/// The restore is the register's last use on the way out of a return.
fn restores_on_return(ir: &FunctionIr, restore: &Access) -> bool {
    let stmts = &ir.blocks[restore.block].stmts;
    matches!(stmts.last(), Some(Stmt::Ret { .. }))
        && stmts[restore.position + 1..].iter().all(|stmt| {
            let (writes, reads) = statement_registers(stmt);
            !writes.contains(&restore.register) && !reads.contains(&restore.register)
        })
}

/// `fp = sp` or `fp = sp + k`: the frame pointer setup in a frame-pointer
/// prologue.
fn is_frame_setup(stmt: &Stmt, sp: u16) -> bool {
    let Stmt::Assign { value, .. } = stmt else {
        return false;
    };
    match value {
        Expr::Reg { index, .. } => *index == sp,
        _ => stack_slot(value, 0, sp).is_some(),
    }
}

/// Removes an x86 `push rbp; mov rbp, rsp` prologue and `pop rbp` epilogue
/// in the same block when nothing between them reads the frame pointer or
/// the stack pointer.
pub fn elide_frame_pointer(ir: &mut FunctionIr) {
    crate::passes::checked(
        "passes::frame::elide_frame_pointer",
        ir,
        elide_frame_pointer_unchecked,
    )
}

fn elide_frame_pointer_unchecked(ir: &mut FunctionIr) {
    for block in &mut ir.blocks {
        elide_frame_pointer_block(block);
    }
}

fn elide_frame_pointer_block(block: &mut vlk_ir::ir::Block) {
    let Some((prologue, frame)) = frame_prologue(&block.stmts) else {
        return;
    };
    let Some(epilogue) = frame_epilogue(&block.stmts, frame) else {
        return;
    };
    for position in prologue.end..epilogue.start {
        let (writes, reads) = statement_registers(&block.stmts[position]);
        let _ = writes;
        if reads.contains(&frame) || reads.contains(&x86::RSP) {
            return;
        }
    }
    // Remove the epilogue first so the prologue's indices stay valid.
    block.stmts.drain(epilogue.start..epilogue.end);
    block.stmts.drain(prologue.start..prologue.end);
}

/// The slot of an exact `sp + k` or `sp - k` address, offset by the current
/// frame displacement.
fn stack_slot(expr: &Expr, frame: i64, sp: u16) -> Option<i64> {
    let add = |offset: i64| Some(frame.wrapping_add(offset));
    match expr {
        Expr::Reg { index, .. } if *index == sp => Some(frame),
        Expr::Bin {
            op: vlk_ir::ir::BinOp::Add,
            lhs,
            rhs,
        } => match (lhs.as_ref(), rhs.as_ref()) {
            (Expr::Reg { index, .. }, Expr::Const(delta)) if *index == sp => add(*delta as i64),
            (Expr::Const(delta), Expr::Reg { index, .. }) if *index == sp => add(*delta as i64),
            _ => None,
        },
        Expr::Bin {
            op: vlk_ir::ir::BinOp::Sub,
            lhs,
            rhs,
        } => match (lhs.as_ref(), rhs.as_ref()) {
            (Expr::Reg { index, .. }, Expr::Const(delta)) if *index == sp => add(-(*delta as i64)),
            _ => None,
        },
        _ => None,
    }
}

/// Reads `sp + k` / `sp - k` as a signed stack delta.
fn stack_delta(value: &Expr, sp: u16) -> Option<i64> {
    let Expr::Bin { op, lhs, rhs } = value else {
        return None;
    };
    if !matches!(lhs.as_ref(), Expr::Reg { index, .. } if *index == sp) {
        return None;
    }
    let Expr::Const(delta) = rhs.as_ref() else {
        return None;
    };
    let delta = *delta as i64;
    match op {
        vlk_ir::ir::BinOp::Add => Some(delta),
        vlk_ir::ir::BinOp::Sub => Some(-delta),
        _ => None,
    }
}

/// Matches `rsp -= 8; *(u64 *)rsp = rbp; rbp = rsp` at the block's head and
/// returns its range and the frame pointer register.
fn frame_prologue(stmts: &[Stmt]) -> Option<(std::ops::Range<usize>, u16)> {
    let Some(first) = stmts.first() else {
        return None;
    };
    let Stmt::Assign {
        dest: sp, value, ..
    } = first
    else {
        return None;
    };
    if sp.index != x86::RSP {
        return None;
    }
    let Some(delta) = stack_delta(value, x86::RSP) else {
        return None;
    };
    if delta != -(8i64) {
        return None;
    }
    let Some(second) = stmts.get(1) else {
        return None;
    };
    let Stmt::Store {
        addr, value: saved, ..
    } = second
    else {
        return None;
    };
    if !matches!(addr, Expr::Reg { index, .. } if *index == x86::RSP) {
        return None;
    }
    let Expr::Reg { index: frame, .. } = saved else {
        return None;
    };
    let Some(third) = stmts.get(2) else {
        return None;
    };
    let Stmt::Assign {
        dest: next,
        value: source,
        ..
    } = third
    else {
        return None;
    };
    if next.index != *frame || !matches!(source, Expr::Reg { index, .. } if *index == x86::RSP) {
        return None;
    }
    Some((0..3, *frame))
}

/// Matches `rbp = *(u64 *)rsp; rsp += 8` at the block's tail, restoring the
/// same frame pointer register, and returns its range.
fn frame_epilogue(stmts: &[Stmt], frame: u16) -> Option<std::ops::Range<usize>> {
    // The pair may sit just before a trailing `Ret`.
    let mut len = stmts.len();
    if matches!(stmts.get(len.saturating_sub(1)), Some(Stmt::Ret { .. })) {
        len -= 1;
    }
    if len < 2 {
        return None;
    }
    let Stmt::Assign {
        dest: sp, value, ..
    } = &stmts[len - 1]
    else {
        return None;
    };
    if sp.index != x86::RSP {
        return None;
    }
    let Some(delta) = stack_delta(value, x86::RSP) else {
        return None;
    };
    if delta != 8 {
        return None;
    }
    let Stmt::Assign {
        dest: restored,
        value,
        ..
    } = &stmts[len - 2]
    else {
        return None;
    };
    if restored.index != frame {
        return None;
    }
    let Expr::Load { addr, .. } = value else {
        return None;
    };
    if !matches!(addr.as_ref(), Expr::Reg { index, .. } if *index == x86::RSP) {
        return None;
    }
    Some(len - 2..len)
}

/// True when the expression loads through an address that does not use the
/// stack pointer `sp`, which may be volatile; stack accesses are ordinary
/// locals.
pub(crate) fn reads_outside_frame(expr: &Expr, sp: u16) -> bool {
    let reads_outside_frame = |expr| reads_outside_frame(expr, sp);
    match expr {
        Expr::Load { addr, .. } => !address_uses_stack(addr, sp) || reads_outside_frame(addr),
        Expr::Bin { lhs, rhs, .. } => reads_outside_frame(lhs) || reads_outside_frame(rhs),
        Expr::SignExtend { value, .. } => reads_outside_frame(value),
        Expr::Select {
            lhs,
            rhs,
            then,
            els,
            ..
        } => {
            reads_outside_frame(lhs)
                || reads_outside_frame(rhs)
                || reads_outside_frame(then)
                || reads_outside_frame(els)
        }
        Expr::Apply { args, .. } => args.iter().any(reads_outside_frame),
        _ => false,
    }
}

fn address_uses_stack(expr: &Expr, sp: u16) -> bool {
    match expr {
        Expr::Reg { index, .. } => *index == sp,
        Expr::Bin { lhs, rhs, .. } => address_uses_stack(lhs, sp) || address_uses_stack(rhs, sp),
        Expr::SignExtend { value, .. } => address_uses_stack(value, sp),
        _ => false,
    }
}

/// Whether a register set to the stack pointer is read through as an
/// address: right after a push it addresses the value pushed.
fn reads_through_stack_pointer_copy(ir: &FunctionIr, sp: u16) -> bool {
    let pointers: std::collections::HashSet<u16> = ir
        .blocks
        .iter()
        .flat_map(|block| &block.stmts)
        .filter_map(|stmt| match stmt {
            Stmt::Assign { dest, value, .. } if dest.index != sp && *value == Expr::reg(sp, 64) => {
                Some(dest.index)
            }
            _ => None,
        })
        .collect();
    fn loads_at(expr: &Expr, pointers: &std::collections::HashSet<u16>) -> bool {
        match expr {
            Expr::Load { addr, .. } if matches!(addr.as_ref(), Expr::Reg { index, .. } if pointers.contains(index)) => {
                true
            }
            _ => vlk_ir::ir::visit::children(expr)
                .into_iter()
                .any(|child| loads_at(child, pointers)),
        }
    }
    ir.blocks
        .iter()
        .flat_map(|block| &block.stmts)
        .any(|stmt| match stmt {
            Stmt::Assign { value, .. } | Stmt::Ret { value, .. } => loads_at(value, &pointers),
            Stmt::Store { addr, value, .. } => {
                loads_at(addr, &pointers) || loads_at(value, &pointers)
            }
            Stmt::Brif { lhs, rhs, .. } => loads_at(lhs, &pointers) || loads_at(rhs, &pointers),
            _ => false,
        })
}

#[cfg(test)]
mod tests;