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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
use std::collections::HashMap;

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

/// Propagates constants within a basic block and simplifies expressions.
pub fn simplify(ir: &mut FunctionIr) {
    crate::passes::checked("passes::simplify::simplify", ir, simplify_unchecked)
}

fn simplify_unchecked(ir: &mut FunctionIr) {
    let starts: std::collections::HashSet<_> = if ir.isa == vlk_base::target::Isa::Arm32 {
        ir.blocks.iter().map(|block| block.start).collect()
    } else {
        std::collections::HashSet::new()
    };
    for block in &mut ir.blocks {
        let mut constants: HashMap<u16, u64> = HashMap::new();
        for stmt in &mut block.stmts {
            simplify_stmt(stmt, &mut constants);
            if let Stmt::BrIndirect {
                target: Expr::Const(target),
                at,
            } = stmt
                && starts.contains(&vlk_arch::arch::code_address(ir.isa, *target))
            {
                *stmt = Stmt::Br {
                    target: Some(vlk_arch::arch::code_address(ir.isa, *target)),
                    at: *at,
                };
            }
        }
    }
}

fn simplify_stmt(stmt: &mut Stmt, constants: &mut HashMap<u16, u64>) {
    match stmt {
        Stmt::Assign { dest, value, .. } => {
            let simplified = simplify_expr(value.clone(), constants);
            if let Expr::Const(value) = simplified {
                constants.insert(
                    dest.index,
                    value & vlk_ir::ir::semantics::mask(u32::from(dest.width)),
                );
            } else {
                constants.remove(&dest.index);
            }
            *value = simplified;
        }
        Stmt::Store {
            addr, value, width, ..
        } => {
            *addr = simplify_expr(addr.clone(), constants);
            *value = simplify_expr(value.clone(), constants);
            let kept = vlk_ir::ir::semantics::mask(u32::from(*width) * 8);
            // A partial register write merges the bits it keeps of the
            // register; none of them lies in the stored bytes.
            if let Expr::Bin {
                op: BinOp::Or,
                lhs,
                rhs,
            } = value
            {
                let register_bits = |part: &Expr| {
                    matches!(part,
                    Expr::Bin { op: BinOp::And, lhs, rhs }
                        if matches!(lhs.as_ref(), Expr::Reg { .. })
                            && matches!(rhs.as_ref(), Expr::Const(_)))
                };
                if let Some(low) = outside_mask(lhs, rhs, kept)
                    .filter(|_| register_bits(lhs))
                    .or_else(|| outside_mask(rhs, lhs, kept).filter(|_| register_bits(rhs)))
                    .cloned()
                {
                    *value = low;
                }
            }
            // A store keeps only its low bytes, which a mask covering them
            // does not change.
            while let Expr::Bin {
                op: vlk_ir::ir::BinOp::And,
                lhs,
                rhs,
            } = value
                && let Expr::Const(mask) = rhs.as_ref()
                && mask & kept == kept
            {
                *value = lhs.as_ref().clone();
            }
        }
        Stmt::Brif { cond, lhs, rhs, .. } => {
            let before = vlk_ir::ir::semantics::operand_width(lhs, rhs);
            let original = (lhs.clone(), rhs.clone());
            *lhs = simplify_expr(lhs.clone(), constants);
            *rhs = simplify_expr(rhs.clone(), constants);
            if let Some(width) =
                vlk_ir::ir::visit::expr_width(lhs).or_else(|| vlk_ir::ir::visit::expr_width(rhs))
            {
                cancel_round_trip(lhs, width);
                cancel_round_trip(rhs, width);
            }
            // Dropping a mask can change which bit supplies the sign.
            // Keep the comparison unless its result is unchanged or its
            // constant can be extended to match the wider operand.
            if vlk_ir::ir::semantics::operand_width(lhs, rhs) != before
                && !super::copies::comparison_preserved(*cond, before, lhs, rhs)
                && !widen_compared_constant(lhs, rhs, before)
                && !widen_compared_constant(rhs, lhs, before)
            {
                (*lhs, *rhs) = original;
            }
            // A constant compares at the operands' width.
            let bits = vlk_ir::ir::semantics::operand_width(lhs, rhs);
            if bits < 64 {
                for side in [&mut *lhs, &mut *rhs] {
                    if let Expr::Const(value) = side {
                        *value &= vlk_ir::ir::semantics::mask(bits);
                    }
                }
            }
            if matches!(cond, vlk_ir::ir::Cond::Eq | vlk_ir::ir::Cond::Ne) {
                move_offset_across(lhs, rhs);
            }
        }
        Stmt::BrIndirect { target, .. } => {
            *target = simplify_expr(target.clone(), constants);
        }
        Stmt::Switch { index, .. } => {
            *index = simplify_expr(index.clone(), constants);
        }
        Stmt::Ret { value, .. } => {
            *value = simplify_expr(value.clone(), constants);
        }
        Stmt::Call { through, args, .. } => {
            if let Some(through) = through {
                *through = simplify_expr(through.clone(), constants);
            }
            for arg in args.iter_mut().flatten() {
                *arg = simplify_expr(arg.clone(), constants);
            }
            // A call may clobber registers.
            constants.clear();
        }
        Stmt::Machine {
            inputs, outputs, ..
        } => {
            for input in inputs {
                *input = simplify_expr(input.clone(), constants);
            }
            for output in outputs {
                constants.remove(&output.index);
            }
        }
        Stmt::Unsupported { .. } => {
            // Unknown effects may clobber registers.
            constants.clear();
        }
        Stmt::Br { .. } | Stmt::BrifFlags { .. } | Stmt::Trap { .. } => {}
    }
}

/// `other` when `kept` is `r & keep` and `keep` shares no bit with `mask`.
fn outside_mask<'e>(kept: &Expr, other: &'e Expr, mask: u64) -> Option<&'e Expr> {
    (crate::ssa::ranges::of(kept).possible() & mask == 0).then_some(other)
}

/// In a compare at `width` bits, `(a - b) + b` and `(a + b) - b` are `a`; a
/// 32-bit mask on the inner result changes nothing at 32 bits.
fn cancel_round_trip(expr: &mut Expr, width: u8) {
    use vlk_ir::ir::BinOp;
    let Expr::Bin { op, lhs, rhs } = &*expr else {
        return;
    };
    let inverse = match op {
        BinOp::Add => BinOp::Sub,
        BinOp::Sub => BinOp::Add,
        _ => return,
    };
    let mut inner = lhs.as_ref();
    if width <= 32
        && let Expr::Bin {
            op: BinOp::And,
            lhs: masked,
            rhs: mask,
        } = inner
        && matches!(mask.as_ref(), Expr::Const(0xffff_ffff))
    {
        inner = masked;
    }
    if let Expr::Bin {
        op: inner_op,
        lhs: original,
        rhs: offset,
    } = inner
        && *inner_op == inverse
        && offset == rhs
    {
        *expr = original.as_ref().clone();
    }
}

/// `x + c == k` is `x == k - c` at the width of `x`, as is `x - c == k`
/// with `k + c`.
fn move_offset_across(lhs: &mut Expr, rhs: &mut Expr) {
    let (
        Expr::Bin {
            op,
            lhs: inner,
            rhs: offset,
        },
        Expr::Const(k),
    ) = (&*lhs, &*rhs)
    else {
        return;
    };
    let Expr::Const(displacement) = offset.as_ref() else {
        return;
    };
    let moved = match op {
        vlk_ir::ir::BinOp::Add => k.wrapping_sub(*displacement),
        vlk_ir::ir::BinOp::Sub => k.wrapping_add(*displacement),
        _ => return,
    };
    let Some(width) = vlk_ir::ir::visit::expr_width(inner) else {
        return;
    };
    let mask = if width >= 64 {
        u64::MAX
    } else {
        (1u64 << width) - 1
    };
    *rhs = Expr::Const(moved & mask);
    *lhs = inner.as_ref().clone();
}

fn simplify_expr(expr: Expr, constants: &HashMap<u16, u64>) -> Expr {
    match expr {
        Expr::Reg { index, width } => match constants.get(&index) {
            Some(value) if width >= 64 => Expr::constant(*value),
            Some(value) => Expr::constant(*value & ((1u64 << width) - 1)),
            None => Expr::Reg { index, width },
        },
        Expr::Const(_) => expr,
        Expr::Bin { op, lhs, rhs } => {
            let bits = vlk_ir::ir::semantics::operand_width(&lhs, &rhs);
            let original = matches!(op, BinOp::Sar | BinOp::DivS | BinOp::ModS)
                .then(|| (lhs.clone(), rhs.clone()));
            let mut simplified_lhs = simplify_expr(*lhs, constants);
            let mut simplified_rhs = simplify_expr(*rhs, constants);
            if let Some((lhs, rhs)) = original
                && vlk_ir::ir::semantics::operand_width(&simplified_lhs, &simplified_rhs) != bits
            {
                // These operations take their sign from the operands' width.
                (simplified_lhs, simplified_rhs) = (*lhs, *rhs);
            }
            fold_offsets(algebraic(Expr::bin(op, simplified_lhs, simplified_rhs)))
        }
        Expr::Load {
            addr,
            width,
            signed,
        } => Expr::Load {
            addr: Box::new(simplify_expr(*addr, constants)),
            width,
            signed,
        },
        Expr::SignExtend { value, width } => {
            let value = simplify_expr(*value, constants);
            // The extension reads only its low bytes, which the kept bits of
            // a partial register write do not reach.
            let low = vlk_ir::ir::semantics::mask(u32::from(width) * 8);
            let value = match &value {
                Expr::Bin {
                    op: vlk_ir::ir::BinOp::Or,
                    lhs: a,
                    rhs: b,
                } => outside_mask(a, b, low)
                    .or_else(|| outside_mask(b, a, low))
                    .cloned()
                    .unwrap_or(value),
                _ => value,
            };
            // In `(int8_t)(x & 0xff)` the mask repeats the extension's truncation.
            let value = match value {
                Expr::Bin {
                    op: vlk_ir::ir::BinOp::And,
                    lhs,
                    rhs,
                } => match rhs.as_ref() {
                    Expr::Const(mask)
                        if *mask == vlk_ir::ir::semantics::mask(u32::from(width) * 8) =>
                    {
                        lhs.as_ref().clone()
                    }
                    _ => Expr::Bin {
                        op: vlk_ir::ir::BinOp::And,
                        lhs,
                        rhs,
                    },
                },
                other => other,
            };
            Expr::SignExtend {
                value: Box::new(value),
                width,
            }
        }
        Expr::Select {
            cond,
            lhs,
            rhs,
            then,
            els,
        } => {
            let bits = vlk_ir::ir::semantics::operand_width(&lhs, &rhs);
            let original = (*lhs.clone(), *rhs.clone());
            let mut lhs = simplify_expr(*lhs, constants);
            let mut rhs = simplify_expr(*rhs, constants);
            let then = simplify_expr(*then, constants);
            let els = simplify_expr(*els, constants);
            let known = match (&lhs, &rhs) {
                (Expr::Const(a), Expr::Const(b)) => {
                    Some(vlk_ir::ir::semantics::holds(cond, *a, *b, bits))
                }
                _ if lhs == rhs && matches!(lhs, Expr::Reg { .. }) => {
                    Some(vlk_ir::ir::semantics::holds(cond, 0, 0, bits))
                }
                _ => None,
            };
            if known.is_none()
                && !super::copies::comparison_preserved(cond, bits, &lhs, &rhs)
                && !widen_compared_constant(&lhs, &mut rhs, bits)
                && !widen_compared_constant(&rhs, &mut lhs, bits)
            {
                (lhs, rhs) = original;
            }
            match known {
                Some(true) => then,
                Some(false) => els,
                None => Expr::Select {
                    cond,
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                    then: Box::new(then),
                    els: Box::new(els),
                },
            }
        }
        Expr::Apply { op, args } => {
            let args: Vec<Expr> = args
                .into_iter()
                .map(|arg| simplify_expr(arg, constants))
                .collect();
            // Comparing or subtracting a value's lanes with themselves, as
            // `pcmpeqd x, x` does to set every bit, reads nothing of them.
            if let (vlk_ir::ir::Operation::Lanes(lane, _), [a, b]) = (op, args.as_slice())
                && a == b
                && !vlk_ir::ir::visit::reads_memory(a)
                && !vlk_ir::ir::visit::faults(a)
            {
                use vlk_ir::ir::LaneOp;
                match lane {
                    LaneOp::Equal | LaneOp::GreaterEqualSigned | LaneOp::GreaterEqualUnsigned => {
                        return Expr::constant(u64::MAX);
                    }
                    LaneOp::Sub | LaneOp::GreaterSigned | LaneOp::GreaterUnsigned => {
                        return Expr::constant(0);
                    }
                    _ => {}
                }
            }
            let values: Option<Vec<u64>> = args
                .iter()
                .map(|arg| match arg {
                    Expr::Const(value) => Some(*value),
                    _ => None,
                })
                .collect();
            match values.and_then(|values| vlk_ir::ir::semantics::fold(op, &values)) {
                Some(value) => Expr::constant(value),
                None => {
                    let applied = Expr::Apply { op, args };
                    counted_bits(&applied).unwrap_or(applied)
                }
            }
        }
    }
}

/// The bits of one value an Or-tree puts back where they were: each term
/// is `x & m` with contiguous `m`, or `((x >> k) & m) << k`; when the
/// terms are disjoint and cover bits 0 up to some width, the tree is `x`
/// within that width.
fn reassembled(expr: &Expr) -> Option<Expr> {
    use vlk_ir::ir::BinOp;
    let mut terms = Vec::new();
    let mut work = vec![expr];
    while let Some(term) = work.pop() {
        match term {
            Expr::Bin {
                op: BinOp::Or,
                lhs,
                rhs,
            } => work.extend([lhs.as_ref(), rhs.as_ref()]),
            other => terms.push(other),
        }
    }
    if terms.len() < 2 {
        return None;
    }
    // A contiguous run of ones: its lowest bit and how many.
    let run = |mask: u64| -> Option<(u32, u32)> {
        if mask == 0 {
            return None;
        }
        let low = mask.trailing_zeros();
        let ones = (mask >> low).trailing_ones();
        (ones == 64 || (mask >> low) >> ones == 0).then_some((low, ones))
    };
    let field = |term: &Expr| -> Option<(Expr, u32, u32)> {
        match term {
            Expr::Bin {
                op: BinOp::And,
                lhs,
                rhs,
            } => {
                let Expr::Const(mask) = rhs.as_ref() else {
                    return None;
                };
                let Some((low, ones)) = run(*mask) else {
                    return None;
                };
                Some((lhs.as_ref().clone(), low, ones))
            }
            Expr::Bin {
                op: BinOp::Shl,
                lhs,
                rhs,
            } => {
                let (
                    Expr::Const(up),
                    Expr::Bin {
                        op: BinOp::And,
                        lhs: inner,
                        rhs: mask,
                    },
                ) = (rhs.as_ref(), lhs.as_ref())
                else {
                    return None;
                };
                let (
                    Expr::Const(mask),
                    Expr::Bin {
                        op: BinOp::Shr,
                        lhs: source,
                        rhs: down,
                    },
                ) = (mask.as_ref(), inner.as_ref())
                else {
                    return None;
                };
                let Some((0, ones)) = run(*mask) else {
                    return None;
                };
                (matches!(down.as_ref(), Expr::Const(down) if down == up) && *up < 64).then(|| {
                    (
                        source.as_ref().clone(),
                        *up as u32,
                        ones.min(64 - *up as u32),
                    )
                })
            }
            _ => None,
        }
    };
    let Some(fields) = terms
        .into_iter()
        .map(field)
        .collect::<Option<Vec<(Expr, u32, u32)>>>()
    else {
        return None;
    };
    let source = fields[0].0.clone();
    if fields.iter().any(|(value, ..)| *value != source) {
        return None;
    }
    let mut ranges: Vec<(u32, u32)> = fields.iter().map(|(_, low, ones)| (*low, *ones)).collect();
    ranges.sort_unstable();
    let mut covered = 0;
    for (low, ones) in ranges {
        if low != covered {
            return None;
        }
        covered += ones;
    }
    Some(if covered >= 64 {
        source
    } else {
        Expr::bin(BinOp::And, source, Expr::constant((1 << covered) - 1))
    })
}

/// The bit count a vector sums out of per-byte counts, as `AArch64` counts
/// the bits of a general register: `uaddlv(cnt(x))` is `popcount(x)`.
fn counted_bits(expr: &Expr) -> Option<Expr> {
    use vlk_ir::ir::{LaneOp, Operation};
    let Expr::Apply {
        op: Operation::SumLanesLong {
            bits: 8,
            signed: false,
        },
        args,
    } = expr
    else {
        return None;
    };
    let mut counts = Vec::new();
    for half in args {
        match half {
            Expr::Const(0) => {}
            Expr::Apply {
                op: Operation::Lanes(LaneOp::PopCount, 8),
                args,
            } => counts.push(Expr::apply(Operation::PopCount(64), vec![args[0].clone()])),
            _ => return None,
        }
    }
    counts
        .into_iter()
        .reduce(|sum, count| Expr::bin(vlk_ir::ir::BinOp::Add, sum, count))
}

/// `x` without a mask to 32 bits it does not need: a value that already
/// fits.
fn low32(expr: &Expr) -> &Expr {
    match expr {
        Expr::Bin {
            op: BinOp::And,
            lhs,
            rhs,
        } if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff)) && fits32(lhs) => lhs,
        other => other,
    }
}

/// Whether `expr` provably holds less than 2^32.
fn fits32(expr: &Expr) -> bool {
    crate::ssa::ranges::of(expr).hi <= 0xffff_ffff
}

/// The divisor a multiply-and-shift by `magic` and `shift` divides a value
/// below 2^32 by, exactly: `(x * magic) >> shift` is `x / d` for every such
/// `x` when `2^shift <= magic * d <= 2^shift + 2^(shift - 32)`.
fn magic_divisor(magic: u64, shift: u64) -> Option<u64> {
    if magic == 0 || magic > 0xffff_ffff || !(32..64).contains(&shift) {
        return None;
    }
    let power = 1u128 << shift;
    let estimate = power / u128::from(magic);
    (estimate..=estimate + 1).find_map(|divisor| {
        let product = u128::from(magic) * divisor;
        (divisor >= 2 && product >= power && product - power <= 1u128 << (shift - 32))
            .then_some(divisor as u64)
    })
}

fn scaled_register(expr: &Expr) -> Option<(&Expr, u64)> {
    match expr {
        Expr::Reg { .. } => Some((expr, 1)),
        Expr::Bin { op, lhs, rhs } => {
            let (value, factor) = match (op, lhs.as_ref(), rhs.as_ref()) {
                (BinOp::Mul, value, Expr::Const(factor))
                | (BinOp::Mul, Expr::Const(factor), value) => (value, *factor),
                (BinOp::Shl, value, Expr::Const(amount)) => (value, 1u64 << (amount & 63)),
                _ => return None,
            };
            let Some((register, scale)) = scaled_register(value) else {
                return None;
            };
            Some((register, scale.wrapping_mul(factor)))
        }
        _ => None,
    }
}

pub fn algebraic(expr: Expr) -> Expr {
    if let Expr::Bin {
        op: BinOp::Add | BinOp::Sub,
        lhs,
        rhs,
    } = &expr
        && let (Some((left, a)), Some((right, b))) = (scaled_register(lhs), scaled_register(rhs))
        && left == right
    {
        let scale = if matches!(&expr, Expr::Bin { op: BinOp::Add, .. }) {
            a.wrapping_add(b)
        } else {
            a.wrapping_sub(b)
        };
        return Expr::bin(BinOp::Mul, left.clone(), Expr::Const(scale));
    }
    if let Expr::Bin {
        op: BinOp::Mul | BinOp::Shl,
        lhs,
        ..
    } = &expr
        && matches!(lhs.as_ref(), Expr::Bin { .. })
        && let Some((register, scale)) = scaled_register(&expr)
    {
        return Expr::bin(BinOp::Mul, register.clone(), Expr::Const(scale));
    }
    // The undefined value may be taken as any value, as zero: masked or
    // shifted it stays undefined, and bits put in beside it, as a partial
    // write of a register a call left undefined puts them, are the value.
    if let Expr::Bin { op, lhs, rhs } = &expr {
        let undefined = |expr: &Expr| {
            matches!(
                expr,
                Expr::Apply {
                    op: vlk_ir::ir::Operation::Undefined,
                    ..
                }
            )
        };
        match op {
            BinOp::And if undefined(lhs) || undefined(rhs) => {
                return Expr::apply(vlk_ir::ir::Operation::Undefined, Vec::new());
            }
            BinOp::Shl | BinOp::Shr | BinOp::Sar if undefined(lhs) => return lhs.as_ref().clone(),
            BinOp::Or if undefined(lhs) => return rhs.as_ref().clone(),
            BinOp::Or if undefined(rhs) => return lhs.as_ref().clone(),
            _ => {}
        }
    }
    // A multiply by a magic number and a shift, as compilers divide a
    // 32-bit value by a constant.
    if let Expr::Bin {
        op: BinOp::Shr,
        lhs,
        rhs,
    } = &expr
        && let (
            Expr::Bin {
                op: BinOp::Mul,
                lhs: value,
                rhs: magic,
            },
            Expr::Const(shift),
        ) = (lhs.as_ref(), rhs.as_ref())
        && let Expr::Const(magic) = magic.as_ref()
        && fits32(value)
        && let Some(divisor) = magic_divisor(*magic, *shift)
    {
        return Expr::bin(BinOp::DivU, value.as_ref().clone(), Expr::Const(divisor));
    }
    // `q + (q << k)` is `q * (2^k + 1)`, for a quotient whose remainder
    // this leads to.
    if let Expr::Bin {
        op: BinOp::Add,
        lhs,
        rhs,
    } = &expr
        && let Expr::Bin {
            op: BinOp::Shl,
            lhs: shifted,
            rhs: amount,
        } = rhs.as_ref()
        && let Expr::Const(amount @ 1..=31) = amount.as_ref()
        && low32(shifted) == low32(lhs)
        && matches!(
            low32(lhs),
            Expr::Bin {
                op: BinOp::DivU,
                ..
            }
        )
        && fits32(low32(lhs))
    {
        return Expr::bin(
            BinOp::Mul,
            low32(lhs).clone(),
            Expr::Const((1 << amount) + 1),
        );
    }
    // `x - (x / d) * d` is `x % d`.
    if let Expr::Bin {
        op: BinOp::Sub,
        lhs,
        rhs,
    } = &expr
        && let Expr::Bin {
            op: BinOp::Mul,
            lhs: quotient,
            rhs: times,
        } = low32(rhs)
        && let Expr::Bin {
            op: BinOp::DivU,
            lhs: dividend,
            rhs: divisor,
        } = low32(quotient)
        && times == divisor
        && low32(dividend) == low32(lhs)
    {
        return Expr::bin(BinOp::ModU, low32(lhs).clone(), divisor.as_ref().clone());
    }
    // So it is at the full width, signed or not: the product wraps as the
    // quotient of the least value by minus one does, and leaves zero.
    if let Expr::Bin {
        op: BinOp::Sub,
        lhs,
        rhs,
    } = &expr
        && let Expr::Bin {
            op: BinOp::Mul,
            lhs: quotient,
            rhs: times,
        } = rhs.as_ref()
        && let Expr::Bin {
            op: op @ (BinOp::DivS | BinOp::DivU),
            lhs: dividend,
            rhs: divisor,
        } = quotient.as_ref()
        && times == divisor
        && dividend == lhs
        && vlk_ir::ir::semantics::width(lhs) == 64
    {
        let remainder = if *op == BinOp::DivS {
            BinOp::ModS
        } else {
            BinOp::ModU
        };
        return Expr::bin(remainder, lhs.as_ref().clone(), divisor.as_ref().clone());
    }
    // Only where the operations around it see the same width.
    if let Some(whole) = reassembled(&expr)
        && vlk_ir::ir::semantics::width(&whole) == vlk_ir::ir::semantics::width(&expr)
    {
        return whole;
    }
    // `x | ((x >> k) & m) << k` sets only bits of `x` that `x` sets: `x`;
    // so is `(x & low) | ((x >> k) & m) << k` when the two cover every bit.
    if let Expr::Bin {
        op: BinOp::Or,
        lhs,
        rhs,
    } = &expr
        && let Expr::Bin {
            op: BinOp::Shl,
            lhs: masked,
            rhs: back,
        } = rhs.as_ref()
        && let Expr::Bin {
            op: BinOp::And,
            lhs: shifted,
            rhs: mask,
        } = masked.as_ref()
        && matches!(mask.as_ref(), Expr::Const(_))
        && let Expr::Bin {
            op: BinOp::Shr,
            lhs: value,
            rhs: out,
        } = shifted.as_ref()
        && out == back
    {
        if value == lhs {
            return lhs.as_ref().clone();
        }
        if let (
            Expr::Bin {
                op: BinOp::And,
                lhs: low_value,
                rhs: low,
            },
            Expr::Const(shift),
            Expr::Const(high),
        ) = (lhs.as_ref(), back.as_ref(), mask.as_ref())
            && let Expr::Const(low) = low.as_ref()
            && *shift > 0
            && *shift < 64
            && low_value == value
            && *low == (1u64 << shift) - 1
            && (high << shift) | low == u64::MAX
        {
            return value.as_ref().clone();
        }
    }
    let Expr::Bin { op, lhs, rhs } = &expr else {
        return expr;
    };
    let zero = |value: &Expr| matches!(value, Expr::Const(0));
    match op {
        // `0 - (0 - x)`, left behind by the absolute-value and negate shapes.
        vlk_ir::ir::BinOp::Sub if zero(lhs) => {
            if let Expr::Bin {
                op: vlk_ir::ir::BinOp::Sub,
                lhs: inner,
                rhs: inner_rhs,
            } = rhs.as_ref()
                && zero(inner)
            {
                return inner_rhs.as_ref().clone();
            }
            expr
        }
        vlk_ir::ir::BinOp::Sub if zero(rhs) => lhs.as_ref().clone(),
        vlk_ir::ir::BinOp::Add if zero(rhs) => lhs.as_ref().clone(),
        // An unsigned load is already zero above its bytes; a mask of
        // exactly those bytes keeps its width too.
        vlk_ir::ir::BinOp::And
            if let (
                Expr::Load {
                    width,
                    signed: false,
                    ..
                },
                Expr::Const(mask),
            ) = (lhs.as_ref(), rhs.as_ref())
                && *mask == vlk_ir::ir::semantics::mask(u32::from(*width) * 8) =>
        {
            lhs.as_ref().clone()
        }
        // `(x & a) & b` is `x & (a & b)`.
        vlk_ir::ir::BinOp::And
            if let (
                Expr::Const(outer),
                Expr::Bin {
                    op: vlk_ir::ir::BinOp::And,
                    lhs: inner,
                    rhs: inner_mask,
                },
            ) = (rhs.as_ref(), lhs.as_ref())
                && let Expr::Const(inner_mask) = inner_mask.as_ref() =>
        {
            Expr::bin(
                vlk_ir::ir::BinOp::And,
                inner.as_ref().clone(),
                Expr::Const(outer & inner_mask),
            )
        }
        // `((r & keep) | v) & mask` with `keep & mask == 0` is `v & mask`:
        // the kept bits of a partial register write fall outside the mask.
        vlk_ir::ir::BinOp::And
            if let Expr::Const(mask) = rhs.as_ref()
                && let Expr::Bin {
                    op: vlk_ir::ir::BinOp::Or,
                    lhs: a,
                    rhs: b,
                } = lhs.as_ref()
                && let Some(value) =
                    outside_mask(a, b, *mask).or_else(|| outside_mask(b, a, *mask)) =>
        {
            Expr::bin(vlk_ir::ir::BinOp::And, value.clone(), Expr::Const(*mask))
        }
        // The low 32 bits of a sum, difference, product or bitwise operation
        // depend only on the low 32 bits of its operands.
        vlk_ir::ir::BinOp::And if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff)) => {
            let Expr::Bin {
                op: inner,
                lhs: a,
                rhs: b,
            } = lhs.as_ref()
            else {
                return expr;
            };
            use vlk_ir::ir::BinOp;
            if !matches!(
                inner,
                BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor
            ) {
                return expr;
            }
            // A masked register stays: it reads as the 32-bit register.
            let low = |operand: &Expr| match operand {
                Expr::Bin {
                    op: BinOp::And,
                    lhs,
                    rhs,
                } if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff))
                    && !matches!(lhs.as_ref(), Expr::Reg { .. }) =>
                {
                    lhs.as_ref().clone()
                }
                other => other.clone(),
            };
            Expr::bin(
                BinOp::And,
                Expr::bin(*inner, low(a), low(b)),
                Expr::Const(0xffff_ffff),
            )
        }
        _ => expr,
    }
}

/// Reassociates constant offsets so an address reads as one base plus one
/// displacement (`(sp - 0x20) + 8` becomes `sp - 0x18`).
fn fold_offsets(expr: Expr) -> Expr {
    let Expr::Bin { op, lhs, rhs } = expr else {
        return expr;
    };
    let Expr::Const(delta) = rhs.as_ref() else {
        return Expr::Bin { op, lhs, rhs };
    };
    let Expr::Bin {
        op: inner_op,
        lhs: base,
        rhs: inner,
    } = lhs.as_ref()
    else {
        return Expr::Bin { op, lhs, rhs };
    };
    let Expr::Const(offset) = inner.as_ref() else {
        return Expr::Bin { op, lhs, rhs };
    };
    let outer = match op {
        vlk_ir::ir::BinOp::Add => *delta,
        vlk_ir::ir::BinOp::Sub => delta.wrapping_neg(),
        _ => return Expr::Bin { op, lhs, rhs },
    };
    let total = match inner_op {
        vlk_ir::ir::BinOp::Add => offset.wrapping_add(outer),
        vlk_ir::ir::BinOp::Sub => outer.wrapping_sub(*offset),
        _ => return Expr::Bin { op, lhs, rhs },
    };
    Expr::bin(
        vlk_ir::ir::BinOp::Add,
        base.as_ref().clone(),
        Expr::constant(total),
    )
}

/// Sign-extends the constant `constant` compares `value` with from `bits`
/// to 64 bits, when `value` is a value of fewer bits read with its sign
/// extended, which compares the same at either width; false otherwise.
fn widen_compared_constant(value: &Expr, constant: &mut Expr, bits: u32) -> bool {
    let narrow = match value {
        Expr::Load {
            width,
            signed: true,
            ..
        }
        | Expr::SignExtend { width, .. } => u32::from(*width) * 8,
        _ => return false,
    };
    let Expr::Const(constant_value) = constant else {
        return false;
    };
    if narrow >= bits || *constant_value & vlk_ir::ir::semantics::mask(bits) != *constant_value {
        return false;
    }
    *constant_value = vlk_ir::ir::semantics::sign_extend(*constant_value, bits) as u64;
    true
}

#[cfg(test)]
mod tests;

#[cfg(test)]
mod magic_tests {
    use super::magic_divisor;

    #[test]
    fn magic_multiply_divides_selected_32_bit_values() {
        // The magic numbers compilers use for unsigned 32-bit division.
        for (magic, shift, divisor) in [
            (0xaaaa_aaab, 33, 3),
            (0xcccc_cccd, 34, 5),
            (0xcccc_cccd, 35, 10),
        ] {
            assert_eq!(magic_divisor(magic, shift), Some(divisor));
            for x in [
                0u64,
                1,
                2,
                divisor - 1,
                divisor,
                0x7fff_ffff,
                0xffff_fffe,
                0xffff_ffff,
            ] {
                assert_eq!((x * magic) >> shift, x / divisor, "{x} / {divisor}");
            }
        }
    }

    /// The condition `magic_divisor` accepts makes the multiply and shift an
    /// exact division for every magic number, divisor and value below 2^32,
    /// at every shift it allows.
    #[test]
    fn smt_accepted_magic_numbers_divide_every_32_bit_value() {
        use vlk_smt::smt::Proofs;
        if !Proofs::available() {
            return;
        }
        let mut proofs = Proofs::default();
        for shift in 32..64u32 {
            let power = 1u128 << shift;
            let slack = 1u128 << (shift - 32);
            let accepted = format!(
                "(and (>= d 2) (>= m 1) (<= m 4294967295) (<= {power} (* m d)) (<= (* m d) (+ {power} {slack})))"
            );
            let x = "(+ (* q d) r)";
            let domain = format!("(and (>= q 0) (>= r 0) (< r d) (< {x} 4294967296))");
            let exact =
                format!("(and (<= (* q {power}) (* {x} m)) (< (* {x} m) (* (+ q 1) {power})))");
            proofs.predicate(
                format!("magic divisor at shift {shift}"),
                "true",
                &format!("(forall ((m Int) (d Int)) (=> (and {accepted} {domain}) {exact}))"),
            );
        }
        // Without the upper bound on the product the shift may round up.
        proofs.counterexample(
            "magic divisor without the error bound",
            "true",
            "(forall ((m Int) (d Int)) (=> (and (>= d 2) (>= m 1) (<= m 4294967295) (<= 8589934592 (* m d)) (>= q 0) (>= r 0) (< r d) (< (+ (* q d) r) 4294967296)) (and (<= (* q 8589934592) (* (+ (* q d) r) m)) (< (* (+ (* q d) r) m) (* (+ q 1) 8589934592)))))",
        );
        proofs.check();
    }
}

#[cfg(test)]
mod select_tests {
    use super::*;
    use vlk_ir::ir::Cond;

    #[test]
    fn selects_fold_constant_and_identical_comparisons_at_the_original_width() {
        for cond in [
            Cond::Eq,
            Cond::Ne,
            Cond::Cs,
            Cond::Cc,
            Cond::Hi,
            Cond::Ls,
            Cond::Ge,
            Cond::Lt,
            Cond::Gt,
            Cond::Le,
            Cond::Mi,
            Cond::Pl,
            Cond::Vs,
            Cond::Vc,
        ] {
            for (lhs, rhs, constants, a, b, bits) in [
                (Expr::Const(1), Expr::Const(2), HashMap::new(), 1, 2, 64),
                (
                    Expr::reg(0, 8),
                    Expr::Const(255),
                    HashMap::from([(0, 127)]),
                    127,
                    255,
                    8,
                ),
                (Expr::reg(0, 32), Expr::reg(0, 32), HashMap::new(), 0, 0, 32),
            ] {
                let value = Expr::Select {
                    cond,
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                    then: Box::new(Expr::Const(11)),
                    els: Box::new(Expr::Const(22)),
                };
                let expected = if vlk_ir::ir::semantics::holds(cond, a, b, bits) {
                    11
                } else {
                    22
                };
                assert_eq!(simplify_expr(value, &constants), Expr::Const(expected));
            }
        }
    }
}