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
//! Optimization scheduling before and after variable splitting and type recovery.

use std::collections::HashSet;
use std::time::Instant;
use vlk_program::program::Program;
use vlk_prototypes::prototypes;

use crate::passes;
use vlk_base::deadline::passed;
use vlk_base::error::Error;
use vlk_ir::ir::{FunctionIr, Stmt};

use super::call_arguments::set_up_arguments;
use super::call_return::apply_call_return;
use super::dead_code::{drop_dead_constant_reads, drop_folded_away};
use super::indirect_result::{drop_unread_indirect_result, name_indirect_result};
use super::lifted::Lifted;
use super::stack_protector::drop_stack_protector;
use super::{Analysis, constant_spills, go_types, refs, structures, summary, typing, variadic};

pub(super) fn optimize(
    program: &Program,
    lifted: Lifted,
    deadline: Option<Instant>,
) -> Result<Analysis, Error> {
    let image = &program.image;
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    let Lifted {
        mut ir,
        has_jump_tables,
        types,
    } = lifted;
    prepare_frame(&mut ir, image, types.as_ref());
    let declared_return = types.as_ref().is_some_and(|types| types.ret.is_some())
        || go_types::runtime(image, ir.addr).is_some();
    let (uniform_32, mut simplification) =
        match simplify_registers(&mut ir, program, has_jump_tables, deadline) {
            Ok(value) => value,
            Err(error) => return Err(error),
        };
    if let Err(error) =
        split_into_variables(&mut ir, program, types.as_ref(), has_jump_tables, deadline)
    {
        return Err(error);
    }
    if let Err(error) = apply_types(&mut ir, program, types, &uniform_32, deadline) {
        return Err(error);
    }
    if let Err(error) = recover_structures(&mut ir, image, declared_return, deadline) {
        return Err(error);
    }
    let mut references = match settle_frame(&mut ir, program, deadline) {
        Ok(value) => value,
        Err(error) => return Err(error),
    };
    // A variable passed where a callee takes a pointer holds one.
    ir.pointer_values = pointer_arguments(&ir, program);
    if let Err(error) = apply_prototype_types(&mut ir, image, deadline) {
        return Err(error);
    }
    let changes = passes::deobfuscation::simplify(&mut ir);
    if changes.simplified {
        references = refs::collect(&ir, program);
    }
    simplification.add(changes);
    record_callees(&mut ir, program);
    Ok(Analysis {
        callee_parameters: Default::default(),
        callee_orders: Default::default(),
        unused_parameters: Default::default(),
        import_parameters: Default::default(),
        ir,
        references,
        simplification,
    })
}

/// Rewrites the frame accesses of the targets that pass arguments on the
/// stack against the entry frame, after recovering what a 32-bit x86
/// function needs for that.
fn prepare_frame(
    ir: &mut FunctionIr,
    image: &vlk_loader::loader::Image,
    types: Option<&vlk_loader::loader::dwarf::FunctionTypes>,
) {
    if ir.isa == vlk_base::target::Isa::I386 {
        passes::checked("analysis::com::recover_i386", ir, |ir| {
            super::com::recover_i386(ir, image, types)
        });
        passes::checked("ssa::count_variadic_arguments", ir, |ir| {
            crate::ssa::count_variadic_arguments(ir, image)
        });
        passes::frame_slots::settle_i386(ir);
    } else if ir.isa == vlk_base::target::Isa::Arm32 {
        passes::frame_slots::settle(ir);
    }
}

/// Narrows register widths, counts the arguments of variadic calls and runs
/// the first round of simplification, while the function is still written
/// in machine registers. Returns the registers only used at 32 bits and what
/// the simplification changed.
fn simplify_registers(
    ir: &mut FunctionIr,
    program: &Program,
    has_jump_tables: bool,
    deadline: Option<Instant>,
) -> Result<(HashSet<u16>, passes::deobfuscation::Simplification), Error> {
    let image = &program.image;
    let narrow_return = |target| summary::summary(program, target).narrow_return;
    let called = callees(ir, program);
    let uniform_32 =
        passes::checked_assuming("passes::widths::specialize_widths", ir, &called, |ir| {
            passes::widths::specialize_widths(ir, &narrow_return)
        });
    // Before the stack adjustments a call reads unseen, such as the push
    // of an argument, are dropped as dead.
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    if ir.isa != vlk_base::target::Isa::I386 {
        passes::checked("ssa::count_variadic_arguments", ir, |ir| {
            crate::ssa::count_variadic_arguments(ir, image)
        });
    }
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    crate::ssa::undefine_clobbered_reads(ir);
    let reached = vlk_ir::ir::cfg::reached(&*ir);
    let simplification =
        match cleanup_before_split(ir, program, has_jump_tables, &reached, deadline) {
            Ok(value) => value,
            Err(error) => return Err(error),
        };
    Ok((uniform_32, simplification))
}

/// Sets up the arguments of the function, splits its registers into the
/// variables they hold and folds away the copies that leaves.
fn split_into_variables(
    ir: &mut FunctionIr,
    program: &Program,
    types: Option<&vlk_loader::loader::dwarf::FunctionTypes>,
    has_jump_tables: bool,
    deadline: Option<Instant>,
) -> Result<(), Error> {
    let image = &program.image;
    // Guessed register arguments do not bound a callee's stack arguments.
    // Calls that save execution state can also reach the frame implicitly.
    let promote_slots = may_promote_frame_slots(ir, image);
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked("analysis::set_up_arguments", ir, |ir| {
        set_up_arguments(ir, types)
    });
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::dce::dce(ir);
    // Every general register becomes the variables it holds, apart from the
    // stack pointer, and the frame pointer while it addresses the frame.
    // So do the vector registers, each half on its own, and the registers
    // the lifter keeps flag operands and exchanged values in.
    let general = registers_to_split(ir);
    // Bits no read looks at go first, so the variables they tied split apart;
    // a narrow return reads fewer of them.
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked(
        "analysis::typing::apply_partial_return",
        ir,
        typing::apply_partial_return,
    );
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    crate::ssa::narrow_partial_writes(ir);
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    let called = callees(ir, program);
    passes::checked_assuming("analysis::drop_unread_indirect_result", ir, &called, |ir| {
        drop_unread_indirect_result(ir, program)
    });
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    let called = callees(ir, program);
    passes::checked_assuming("ssa::split_variables", ir, &called, |ir| {
        crate::ssa::split_variables(ir, &general)
    });
    let frame_slot_promotion = if promote_slots {
        FrameSlotPromotion::Allowed
    } else {
        FrameSlotPromotion::Blocked
    };
    if let Err(error) = cleanup_after_split(ir, has_jump_tables, frame_slot_promotion, deadline) {
        return Err(error);
    }
    Ok(())
}

/// Whether no call of the function can reach its frame in a way the
/// arguments do not show.
fn may_promote_frame_slots(ir: &FunctionIr, image: &vlk_loader::loader::Image) -> bool {
    ir.blocks.iter().flat_map(|block| &block.stmts).all(|stmt| {
        let Stmt::Call {
            kind,
            target,
            through,
            args,
            ..
        } = stmt
        else {
            return true;
        };
        if *kind == vlk_types::types::CallKind::Syscall {
            return true;
        }
        if args.is_none() {
            return false;
        }
        let name = target
            .and_then(|target| image.functions.get(&target))
            .and_then(|function| function.name.as_deref())
            .or_else(|| match through {
                Some(through) => vlk_prototypes::prototypes::import_name(image, through),
                None => None,
            });
        !name.is_some_and(|name| {
            matches!(
                name.trim_start_matches('_'),
                "setjmp"
                    | "sigsetjmp"
                    | "longjmp"
                    | "siglongjmp"
                    | "longjmp_chk"
                    | "savectx"
                    | "getcontext"
                    | "swapcontext"
            )
        })
    })
}

/// The registers that are split into the variables they hold.
fn registers_to_split(ir: &FunctionIr) -> Vec<u16> {
    let sp = vlk_arch::arch::stack_pointer(ir.isa);
    let fp = vlk_arch::arch::frame_pointer(ir.isa);
    let addresses_frame = ir
        .blocks
        .iter()
        .flat_map(|block| &block.stmts)
        .any(|stmt| match stmt {
            Stmt::Assign { dest, value, .. } if dest.index == fp => {
                let mut read = HashSet::new();
                vlk_ir::ir::visit::collect_reads(value, &mut read);
                read.contains(&sp)
            }
            _ => false,
        });
    let word_temporaries: &[u16] = if vlk_arch::arch::pointer_bytes(ir.isa) == 4 {
        &crate::lift::pairs32::TEMPORARIES
    } else {
        &[]
    };
    let general: Vec<u16> = match ir.isa {
        vlk_base::target::Isa::AArch64 | vlk_base::target::Isa::RiscV64 => {
            (0..=30).collect::<Vec<u16>>()
        }
        // The general registers, then HI and LO, and the condition flags.
        vlk_base::target::Isa::Mips32 => (0..=32)
            .chain(vlk_arch::arch::mips32::FLAG0..vlk_arch::arch::mips32::FLAG0 + 8)
            .collect(),
        _ => (0..16).collect(),
    };
    general
        .into_iter()
        .filter(|register| *register != sp && (*register != fp || !addresses_frame))
        .chain(
            vlk_arch::arch::machine_registers()
                .filter(|register| vlk_arch::arch::vector_half(ir.isa, *register).is_some()),
        )
        .chain(vlk_ir::ir::FLAG_OPERANDS)
        .chain(vlk_ir::ir::FLAG_CARRIED)
        .chain([vlk_ir::ir::EXCHANGE, vlk_ir::ir::SWITCH_INDEX])
        .chain(word_temporaries.iter().copied())
        .collect()
}

/// Types the variables from the widths they are used at, the returns, and
/// the declared or inferred signature of the function, then simplifies what
/// the types made redundant.
fn apply_types(
    ir: &mut FunctionIr,
    program: &Program,
    types: Option<vlk_loader::loader::dwarf::FunctionTypes>,
    uniform_32: &HashSet<u16>,
    deadline: Option<Instant>,
) -> Result<(), Error> {
    let image = &program.image;
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    if vlk_arch::arch::extends_words(ir.isa) {
        passes::checked("passes::widths::narrow_extended_words", ir, |ir| {
            passes::widths::narrow_extended_words(ir);
        });
    }
    passes::checked("analysis::typing::apply_width_types", ir, |ir| {
        typing::apply_width_types(ir, uniform_32)
    });
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked("analysis::typing::apply_void_return", ir, |ir| {
        typing::apply_void_return(ir)
    });
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked(
        "analysis::typing::apply_partial_return",
        ir,
        typing::apply_partial_return,
    );
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked("analysis::apply_call_return", ir, |ir| {
        apply_call_return(ir, program)
    });
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    let inferred = if types.is_none() {
        crate::lift::pairs32::definition_types(program, ir.addr)
    } else {
        None
    };
    let inferred_parameters = if types.is_none() && inferred.is_none() {
        crate::lift::pairs32::inference::parameters(program, ir.addr)
    } else {
        None
    };
    passes::checked("analysis::typing::apply_dwarf_types", ir, |ir| {
        typing::apply_dwarf_types(types, ir)
    });
    passes::checked("analysis::go_types::apply_runtime_signature", ir, |ir| {
        go_types::apply_runtime_signature(ir, image)
    });
    if let Some((params, ret)) = inferred {
        passes::checked("analysis::pairs32::place_inferred", ir, |ir| {
            super::pairs32::place_inferred(params, ret, ir)
        });
    } else if let Some(params) = inferred_parameters {
        passes::checked("analysis::pairs32::place_inferred_parameters", ir, |ir| {
            super::pairs32::place_inferred_parameters(params, ir)
        });
    }
    if let Err(error) = cleanup_after_types(ir, deadline) {
        return Err(error);
    }
    Ok(())
}

/// Names the result written through a pointer, recovers structure accesses
/// and, unless the return type is declared, types a returned pointer.
fn recover_structures(
    ir: &mut FunctionIr,
    image: &vlk_loader::loader::Image,
    declared_return: bool,
    deadline: Option<Instant>,
) -> Result<(), Error> {
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked("analysis::name_indirect_result", ir, |ir| {
        name_indirect_result(ir)
    });
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked("analysis::structures::recover", ir, |ir| {
        structures::recover(ir)
    });
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    if !declared_return {
        passes::checked("analysis::typing::apply_pointer_return_with", ir, |ir| {
            typing::apply_pointer_return_with(ir, &|stmt| prototypes::called(image, stmt))
        });
    }
    // It returns the pointer it wrote the result through.
    if !declared_return
        && ir.declared_signature.is_none()
        && let Some(result) = ir.params.iter().find(|param| param.name == "result")
    {
        ir.ret_type = result.ty.clone();
    }
    Ok(())
}

/// Folds literals, collects the references of the function and settles its
/// frame, dropping the reads and stores that leaves unused. Returns the
/// references.
fn settle_frame(
    ir: &mut FunctionIr,
    program: &Program,
    deadline: Option<Instant>,
) -> Result<Vec<refs::Reference>, Error> {
    let image = &program.image;
    let sp = vlk_arch::arch::stack_pointer(ir.isa);
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked("lift::fold_literals", ir, |ir| {
        crate::lift::fold_literals(ir, image)
    });
    if ir.isa == vlk_base::target::Isa::Mips32 {
        passes::checked("lift::mips32::fold_fixed_entries", ir, |ir| {
            crate::lift::mips32::fold_fixed_entries(ir, image)
        });
    }
    let references = refs::collect(&*ir, program);
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::frame_slots::settle(ir);
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked("analysis::drop_stack_protector", ir, |ir| {
        drop_stack_protector(ir, image)
    });
    // Settling simplifies again, which can leave a table read unused.
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked("analysis::drop_dead_constant_reads", ir, |ir| {
        drop_dead_constant_reads(ir, image)
    });
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    crate::ssa::take_results_directly(ir);
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::read_once::fold_values_read_once(ir);
    // Folding the last frame loads can leave their stores unused.
    let plain_frame_stores = ir.blocks.iter().flat_map(|block| &block.stmts).all(|stmt| {
        let Stmt::Store {
            addr, value, width, ..
        } = stmt
        else {
            return true;
        };
        matches!(
            value,
            vlk_ir::ir::Expr::Reg { .. } | vlk_ir::ir::Expr::Const(_)
        ) && matches!(width, 1 | 2 | 4 | 8)
            && passes::memory::private_address(addr, *width, sp)
            && passes::frame_slots::frame_slot(addr, 0, sp)
                .is_some_and(|slot| slot >= ir.frame_bottom)
    });
    if passes::memory::fixed_private_frame(&*ir, sp)
        && !ir.blocks.iter().any(vlk_ir::ir::cfg::opaque)
        && plain_frame_stores
    {
        passes::frame::drop_dead_frame_stores(ir);
    }
    Ok(references)
}

/// The variables passed where a callee takes a pointer.
fn pointer_arguments(ir: &FunctionIr, program: &Program) -> Vec<u16> {
    let mut pointer_values = Vec::new();
    for stmt in ir.blocks.iter().flat_map(|block| &block.stmts) {
        if stmt.has_declared_call() {
            continue;
        }
        if let Stmt::Call {
            target: Some(target),
            args: Some(args),
            ..
        } = stmt
        {
            let pointers = summary::summary(program, *target).pointers;
            let first_arguments = args.iter().enumerate().take(32);
            for (position, arg) in first_arguments {
                if pointers & 1 << position != 0
                    && let vlk_ir::ir::Expr::Reg { index, width: 64 } = arg
                    && *index >= vlk_ir::ir::VARIABLE_BASE
                {
                    pointer_values.push(*index);
                }
            }
        }
    }
    pointer_values
}

/// Types the function from the prototypes and records of what it calls,
/// marks variadic use and applies the types of Go functions.
fn apply_prototype_types(
    ir: &mut FunctionIr,
    image: &vlk_loader::loader::Image,
    deadline: Option<Instant>,
) -> Result<(), Error> {
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked("analysis::typing::apply_prototypes", ir, |ir| {
        typing::apply_prototypes(ir, image)
    });
    passes::checked("analysis::pairs32::type_temporaries", ir, |ir| {
        super::pairs32::type_temporaries(ir)
    });
    passes::checked("prototypes::apply_records", ir, |ir| {
        prototypes::apply_records(ir, image)
    });
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked("analysis::variadic::mark_variadic", ir, |ir| {
        variadic::mark_variadic(ir)
    });
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked("passes::coalesce::reuse_pointers", ir, |ir| {
        passes::coalesce::reuse_pointers(ir)
    });
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked("analysis::go_types::apply", ir, |ir| {
        go_types::apply(ir, image)
    });
    Ok(())
}

/// Records what the renderer needs to know of the callees: their
/// signatures, results and, in a Go program, their register arguments.
fn record_callees(ir: &mut FunctionIr, program: &Program) {
    let image = &program.image;
    ir.callee_signatures = crate::analysis::calls::printable_signatures(program, &*ir);
    ir.callee_results = crate::analysis::results::callee_results(program, &*ir);
    ir.callee_float_returns = crate::analysis::results::callee_float_returns(program, &*ir);
    ir.callee_named_arguments = ir
        .blocks
        .iter()
        .flat_map(|block| &block.stmts)
        .filter_map(|stmt| match stmt {
            vlk_ir::ir::Stmt::Call {
                target: Some(target),
                convention: vlk_types::types::Convention::O32,
                ..
            } => Some(*target),
            _ => None,
        })
        .filter_map(|target| {
            let named = crate::analysis::summary::summary(program, target).further_from;
            (named != 0).then_some((target, named))
        })
        .collect();
    if image.go {
        ir.listed_callees = ir
            .blocks
            .iter()
            .flat_map(|block| &block.stmts)
            .filter_map(|stmt| match stmt {
                vlk_ir::ir::Stmt::Call {
                    target: Some(target),
                    through: None,
                    ..
                } => Some(*target),
                _ => None,
            })
            .filter(|target| vlk_loader::loader::go::argument_registers(image, *target).is_some())
            .collect();
        ir.callee_floats = ir
            .blocks
            .iter()
            .flat_map(|block| &block.stmts)
            .filter_map(|stmt| match stmt {
                vlk_ir::ir::Stmt::Call {
                    target: Some(target),
                    through: None,
                    floats_named: true,
                    convention,
                    ..
                } if convention.go_registers() => Some(*target),
                _ => None,
            })
            .filter_map(|target| {
                crate::analysis::summary::summary(program, target)
                    .floats
                    .filter(|floats| *floats > 0)
                    .map(|floats| (target, floats))
            })
            .collect();
    }
}

fn cleanup_before_split(
    ir: &mut FunctionIr,
    program: &Program,
    has_jump_tables: bool,
    reached: &HashSet<u64>,
    deadline: Option<Instant>,
) -> Result<passes::deobfuscation::Simplification, Error> {
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    let changes = passes::optimize(ir, has_jump_tables);
    passes::checked("analysis::constant_spills::forward", ir, |ir| {
        constant_spills::forward(ir, program)
    });
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::checked("analysis::drop_folded_away", ir, |ir| {
        drop_folded_away(ir, reached)
    });
    Ok(changes)
}

enum FrameSlotPromotion {
    Allowed,
    Blocked,
}

fn cleanup_after_split(
    ir: &mut FunctionIr,
    has_jump_tables: bool,
    frame_slot_promotion: FrameSlotPromotion,
    deadline: Option<Instant>,
) -> Result<(), Error> {
    // The new variables leave copies between them to fold away, and values
    // spilled across calls that now survive them in their variables.
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::copies::copy_propagate_guarded(ir);
    if !has_jump_tables {
        if let Err(error) = passed(deadline) {
            return Err(error);
        }
        passes::memory::forward_stored_values(ir);
        if let Err(error) = passed(deadline) {
            return Err(error);
        }
        passes::memory::forward_spilled_variables(ir);
        if matches!(frame_slot_promotion, FrameSlotPromotion::Allowed) {
            passes::memory::promote_frame_slots(ir);
        }
    }
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::dce::dce(ir);
    Ok(())
}

fn cleanup_after_types(ir: &mut FunctionIr, deadline: Option<Instant>) -> Result<(), Error> {
    // A narrower return reads fewer bits, which may leave more of a
    // partial write unread.
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    crate::ssa::narrow_partial_writes(ir);
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::copies::copy_propagate_guarded(ir);
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::simplify::simplify(ir);
    // With the variables split, what they hold narrows again.
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    crate::ssa::ranges::simplify(ir);
    // Simplifying can fold a variable's value into its readers.
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::dce::dce(ir);
    if let Err(error) = passed(deadline) {
        return Err(error);
    }
    passes::coalesce::coalesce_copies(ir);
    Ok(())
}

/// What the summaries say of the callees `ir` calls directly, for the
/// rewrite validation of a pass that relies on them.
fn callees(ir: &FunctionIr, program: &Program) -> passes::Callees {
    let mut callees = passes::Callees::default();
    if !cfg!(feature = "validate") {
        return callees;
    }
    for stmt in ir.blocks.iter().flat_map(|block| &block.stmts) {
        if let Stmt::Call {
            target: Some(target),
            ..
        } = stmt
        {
            let summary = summary::summary(program, *target);
            if summary.narrow_return {
                callees.narrow_results.push(*target);
            }
            if !summary.indirect_result {
                callees.without_result_address.push(*target);
            }
        }
    }
    callees
}