lang: Read scalar binding subjects in place

d2eb7dbdfc304f26c2742a190f304c2b9ee940903d7e918d9b68da69c922e986
`if let x = opt`, `while let x = opt` and `let x = opt else` copied an
optional subject to a fresh stack slot unless it was an immutable
variable with stable memory. A loop such as `while let i = cur { set cur
= next[i]; }` copied `cur` on every iteration, and since
alignment-correct copies split an 8-byte `?u32` into two word copies,
linked-list traversals ran up to 28% more instructions than before that
change.

A binding pattern whose bound value is a scalar or pointer, matched by
value, now reads its subject in place, whatever the subject is. The
binding reads the value out of the subject before the body or guard
runs, so nothing refers to the subject afterwards, and writes to a
mutable binding go to the variable. Other patterns keep their rules.

prog.linkedlist runs 11.4% fewer instructions, and the prog.* fixtures
22.9% fewer (geometric mean) than before the logical condition change.

Assisted-by: Claude:opus-5.5
Alexis Sellier committed ago 1 parent b21693da
lib/std/lang/lower.rad +27 -6
1066 1066
1067 1067
/// How an aggregate match subject is held while its pattern is bound.
1068 1068
union SubjectStorage: Copy {
1069 1069
    /// Copy an aggregate to a fresh stack slot, so bindings never read the source.
1070 1070
    StackCopy,
1071 -
    /// Read an aggregate in place. Only valid when the source is an immutable
1072 -
    /// variable with stable memory and every binding is immutable, so the source
1073 -
    /// cannot change while bindings are live.
1071 +
    /// Read an aggregate in place. Only valid when the source cannot change while
1072 +
    /// bindings that refer to it are live: the source is an immutable variable with
1073 +
    /// stable memory and every binding is immutable, or the only binding is a scalar
1074 +
    /// read out before any other code runs.
1074 1075
    InPlace,
1075 1076
}
1076 1077
1077 1078
/// Classifies a match subject by how it should be compared and destructured.
1078 1079
union MatchSubjectKind: Copy {
5521 5522
        }
5522 5523
    }
5523 5524
    return true;
5524 5525
}
5525 5526
5527 +
/// Choose how the subject of an `if let`, `while let` or `let ... else` pattern is
5528 +
/// held. A binding pattern of a scalar value reads the value out of the subject
5529 +
/// before the body or guard runs, so nothing refers to the subject afterwards and
5530 +
/// it is read in place. Other patterns follow [`subjectStorage`].
5531 +
fn patternStorage(self: &mut Lowerer, pat: &ast::PatternMatch) -> SubjectStorage
5532 +
    throws (LowerError)
5533 +
{
5534 +
    if pat.kind == ast::PatternKind::Binding {
5535 +
        let unwrapped = resolver::unwrapMatchSubject(try typeOf(self, pat.scrutinee));
5536 +
        let mut bound = unwrapped.effectiveTy;
5537 +
        if let case resolver::Type::Optional(inner) = bound {
5538 +
            set bound = *inner;
5539 +
        }
5540 +
        if unwrapped.by == resolver::MatchBy::Value and not isAggregateType(&self.resolver, bound) {
5541 +
            return SubjectStorage::InPlace;
5542 +
        }
5543 +
    }
5544 +
    return subjectStorage(self, pat.scrutinee, pat.mutable);
5545 +
}
5546 +
5526 5547
/// Choose how the subject `scrutinee` of a match is held. An immutable variable
5527 5548
/// whose memory is stable is read in place, unless the pattern binds it mutably:
5528 5549
/// nothing writes it while the bindings are live. Other subjects are copied.
5529 5550
fn subjectStorage(self: &Lowerer, scrutinee: *ast::Node, mutableBinding: bool) -> SubjectStorage {
5530 5551
    if not mutableBinding {
5539 5560
}
5540 5561
5541 5562
/// Lower an `if let` statement.
5542 5563
fn lowerIfLet(self: &mut Lowerer, cond: ast::IfLet) throws (LowerError) {
5543 5564
    let savedVarsLen = enterVarScope(self);
5544 -
    let storage = subjectStorage(self, cond.pattern.scrutinee, cond.pattern.mutable);
5565 +
    let storage = try patternStorage(self, &cond.pattern);
5545 5566
    let subject = try lowerMatchSubject(self, cond.pattern.scrutinee, storage);
5546 5567
    // An irrefutable pattern always takes the then branch. It needs no else
5547 5568
    // block, and a diverging then branch leaves nothing to merge.
5548 5569
    if try isIrrefutableRecordCase(self, &cond.pattern) {
5549 5570
        let patterns = [cond.pattern.pattern];
5638 5659
    }
5639 5660
}
5640 5661
5641 5662
/// Lower a `let-else` statement.
5642 5663
fn lowerLetElse(self: &mut Lowerer, letElse: ast::LetElse) throws (LowerError) {
5643 -
    let storage = subjectStorage(self, letElse.pattern.scrutinee, letElse.pattern.mutable);
5664 +
    let storage = try patternStorage(self, &letElse.pattern);
5644 5665
    let subject = try lowerMatchSubject(self, letElse.pattern.scrutinee, storage);
5645 5666
    // An irrefutable pattern always matches, so the else branch is unreachable.
5646 5667
    if try isIrrefutableRecordCase(self, &letElse.pattern) {
5647 5668
        let patterns = [letElse.pattern.pattern];
5648 5669
        try bindPatternVariables(self, &subject, &patterns[..], nil);
5698 5719
    let endBlock = try createBlock(self, "merge");
5699 5720
5700 5721
    // Enter loop context and jump to loop header.
5701 5722
    try enterLoop(self, endBlock, whileBlock);
5702 5723
    try switchAndJumpTo(self, whileBlock);
5703 -
    let storage = subjectStorage(self, w.pattern.scrutinee, w.pattern.mutable);
5724 +
    let storage = try patternStorage(self, &w.pattern);
5704 5725
    let subject = try lowerMatchSubject(self, w.pattern.scrutinee, storage);
5705 5726
5706 5727
    // Evaluate pattern and jump to loop body or loop end.
5707 5728
    try lowerPatternMatch(self, &subject, &w.pattern, &mut bodyBlock, "body", endBlock);
5708 5729
test/tests/coercion.implicit.ril +4 -6
3 3
fn w32 $optionalLiftLiteral() {
4 4
  @entry0
5 5
    reserve %0 $L0;
6 6
    store w8 1 %0 0;
7 7
    store w32 42 %0 4;
8 -
    reserve %1 $L0;
9 -
    blit %1 %0 $L0;
10 -
    load w8 %2 %1 0;
11 -
    br.ne w32 %2 0 @success1 @else2;
8 +
    load w8 %1 %0 0;
9 +
    br.ne w32 %1 0 @success1 @else2;
12 10
  @success1
13 -
    sload w32 %3 %1 4;
11 +
    sload w32 %2 %0 4;
14 12
    jmp @merge3;
15 13
  @else2
16 14
    ret 0;
17 15
  @merge3
18 -
    ret %3;
16 +
    ret %2;
19 17
}
20 18
21 19
fn w32 $optionalLiftVar(w32 %0) {
22 20
  @entry0
23 21
    reserve %1 $L0;
test/tests/cond.iflet.mut.ril +5 -7
1 1
layout $L0 size 8 align 4 {}
2 2
3 3
fn w32 $ifLetMut(ptr ref const $L0 %0) {
4 4
  @entry0
5 -
    reserve %1 $L0;
6 -
    blit %1 %0 $L0;
7 -
    load w8 %2 %1 0;
8 -
    br.ne w32 %2 0 @then1 @else2;
5 +
    load w8 %1 %0 0;
6 +
    br.ne w32 %1 0 @then1 @else2;
9 7
  @then1
10 -
    sload w32 %3 %1 4;
11 -
    add w32 %4 %3 1;
12 -
    ret %4;
8 +
    sload w32 %2 %0 4;
9 +
    add w32 %3 %2 1;
10 +
    ret %3;
13 11
  @else2
14 12
    ret 0;
15 13
}
test/tests/cond.letelse.mut.ril +5 -7
1 1
layout $L0 size 8 align 4 {}
2 2
3 3
fn w32 $letMutElse(ptr ref const $L0 %0) {
4 4
  @entry0
5 -
    reserve %1 $L0;
6 -
    blit %1 %0 $L0;
7 -
    load w8 %2 %1 0;
8 -
    br.ne w32 %2 0 @success1 @else2;
5 +
    load w8 %1 %0 0;
6 +
    br.ne w32 %1 0 @success1 @else2;
9 7
  @success1
10 -
    sload w32 %3 %1 4;
8 +
    sload w32 %2 %0 4;
11 9
    jmp @merge3;
12 10
  @else2
13 11
    ret 0;
14 12
  @merge3
15 -
    add w32 %4 %3 1;
16 -
    ret %4;
13 +
    add w32 %3 %2 1;
14 +
    ret %3;
17 15
}
test/tests/match.subject.inplace.eval.rad +26 -0
36 36
            return w * height;
37 37
        }
38 38
    }
39 39
}
40 40
41 +
/// Overwrite a mutable optional inside the arm that binds its scalar payload.
42 +
fn overwriteScalar(start: ?u32) -> u32 {
43 +
    let mut cur = start;
44 +
    if let value = cur {
45 +
        set cur = 7;
46 +
        if let after = cur {
47 +
            return value * 10 + after;
48 +
        }
49 +
    }
50 +
    return 0;
51 +
}
52 +
53 +
/// Overwrite a mutable optional inside the arm that binds its aggregate payload.
54 +
fn overwritePayload(start: ?Shape) -> i64 {
55 +
    let mut cur = start;
56 +
    if let shape = cur {
57 +
        set cur = Shape::Point;
58 +
        if let case Shape::Box { w, .. } = shape {
59 +
            return w;
60 +
        }
61 +
    }
62 +
    return -1;
63 +
}
64 +
41 65
@default fn main() -> i32 {
66 +
    assert overwriteScalar(3) == 37;
67 +
    assert overwritePayload(Shape::Box { w: 9, h: 1, d: 1 }) == 9;
42 68
    let mut h = Holder { shape: Shape::Box { w: 3, h: 4, d: 5 }, count: 10 };
43 69
    assert overwrite(&mut h) == 13;
44 70
    set h.shape = Shape::Box { w: 3, h: 4, d: 5 };
45 71
    assert overwriteUnion(&mut h) == 12;
46 72
    return 0;
test/tests/match.subject.inplace.rad +24 -0
32 32
            case Shape::Box { w, .. } => set total += w,
33 33
        }
34 34
    }
35 35
    return total;
36 36
}
37 +
38 +
/// Follow links through a mutable optional, which is read in place because its
39 +
/// binding is a scalar read before the body writes the optional.
40 +
fn follow(links: &[?u32], start: ?u32) -> u32 {
41 +
    let mut count: u32 = 0;
42 +
    let mut cur = start;
43 +
    while let i = cur {
44 +
        set count += 1;
45 +
        set cur = links[i];
46 +
    }
47 +
    return count;
48 +
}
49 +
50 +
/// Bind an aggregate payload of a mutable optional, which is copied.
51 +
fn payload(shapes: &[?Shape]) -> i64 {
52 +
    let mut cur = shapes[0];
53 +
    if let s = cur {
54 +
        set cur = nil;
55 +
        if let case Shape::Box { w, .. } = s {
56 +
            return w;
57 +
        }
58 +
    }
59 +
    return 0;
60 +
}
test/tests/match.subject.inplace.ril +58 -0
1 1
layout $L0 size 32 align 8 {}
2 2
layout $L1 size 16 align 8 {
3 3
    slot 0 slice ref const $L0;
4 4
}
5 +
layout $L2 size 16 align 8 {
6 +
    slot 0 slice ref const $L3;
7 +
}
8 +
layout $L3 size 8 align 4 {}
9 +
layout $L4 size 16 align 8 {
10 +
    slot 0 slice ref const $L5;
11 +
}
12 +
layout $L5 size 40 align 8 {}
5 13
6 14
fn w64 $param(ptr ref const $L0 %0) {
7 15
  @entry0
8 16
    jmp @arm1;
9 17
  @arm1
69 77
    add w64 %9 %8 %7;
70 78
    jmp @merge7(%9);
71 79
  @arm9
72 80
    unreachable;
73 81
}
82 +
83 +
fn w32 $follow(ptr ref const $L2 %0, ptr ref const $L3 %1) {
84 +
  @entry0
85 +
    reserve %2 $L3;
86 +
    blit %2 %1 $L3;
87 +
    jmp @while1(%2, 0, %0);
88 +
  @while1(ptr ref mut $L3 %3, w32 %6, ptr ref const $L2 %8)
89 +
    load w8 %4 %3 0;
90 +
    br.ne w32 %4 0 @body2 @merge3;
91 +
  @body2
92 +
    load w32 %5 %3 4;
93 +
    add w32 %7 %6 1;
94 +
    slice.elem %9 %8 %5 $L3;
95 +
    blit %3 %9 $L3;
96 +
    jmp @while1(%3, %7, %8);
97 +
  @merge3
98 +
    ret %6;
99 +
}
100 +
101 +
fn w64 $payload(ptr ref const $L4 %0) {
102 +
  @entry0
103 +
    slice.elem %1 %0 0 $L5;
104 +
    reserve %2 $L5;
105 +
    blit %2 %1 $L5;
106 +
    reserve %3 $L5;
107 +
    blit %3 %2 $L5;
108 +
    load w8 %4 %3 0;
109 +
    br.ne w32 %4 0 @then1 @else2;
110 +
  @then1
111 +
    field %5 %3 8;
112 +
    reserve %6 $L5;
113 +
    store w8 0 %6 0;
114 +
    blit %2 %6 $L5;
115 +
    reserve %7 $L0;
116 +
    blit %7 %5 $L0;
117 +
    load w8 %8 %7 0;
118 +
    br.eq w8 %8 1 @then3 @else4;
119 +
  @else2
120 +
    jmp @merge6;
121 +
  @then3
122 +
    field %9 %7 8;
123 +
    sload w64 %10 %9 0;
124 +
    ret %10;
125 +
  @else4
126 +
    jmp @merge5;
127 +
  @merge5
128 +
    jmp @merge6;
129 +
  @merge6
130 +
    ret 0;
131 +
}