lang: Extend narrow subjects of scalar matches

cd53ae0ba7c78d11c4a31ea9a6d86b06c91e0ac9bba44d7b2dcfb65039a30060
A scalar match lowers to a switch, which compares whole registers with
the case values, but narrow values have undefined high bits. A `u32`
computed by word arithmetic is sign-extended in its register, so
`match x { case 0x80000000 => ... }` missed when `x` was 0x7fffffff + 1.
A same-size cast keeps the bits of its source, so `(b as i8)` with
`b: u8 = 255` missed `case -1`.

The subject of a scalar switch is now extended the way comparisons
extend operands: words and signed values by their sign, unsigned bytes
and halfwords with zeros. Case values are written in the same form. The
RV64 backend drops the extension when the producer of the subject
already extended it.

Assisted-by: Claude:opus-5.5
Alexis Sellier committed ago 1 parent d09d682d
lib/std/lang/lower.rad +27 -2
5225 5225
        }
5226 5226
    }
5227 5227
    return try finalizeBlocks(self);
5228 5228
}
5229 5229
5230 +
/// The constant `value` of type `typ` with its high bits set to its sign, or
5231 +
/// for `signed` false to zero.
5232 +
fn extendedConst(value: i64, typ: il::Type, signed: bool) -> i64 {
5233 +
    match typ {
5234 +
        case il::Type::W8  => return value as i8 as i64 if signed else value as u8 as i64,
5235 +
        case il::Type::W16 => return value as i16 as i64 if signed else value as u16 as i64,
5236 +
        case il::Type::W32 => return value as i32 as i64 if signed else value as u32 as i64,
5237 +
        case il::Type::W64 => return value,
5238 +
    }
5239 +
}
5240 +
5230 5241
/// Lower a scalar match as a switch instruction.
5231 5242
fn lowerMatchSwitch(
5232 5243
    self: &mut Lowerer,
5233 5244
    prongs: *[*ast::Node],
5234 5245
    subject: &MatchSubject,
5236 5247
) throws (LowerError) {
5237 5248
    let mut blocks: [BlockId; MAX_SWITCH_PRONGS] = undefined;
5238 5249
    let caseStart = self.caseList.len;
5239 5250
    let mut defaultIdx: u32 = 0;
5240 5251
    let entry = currentBlock(self);
5252 +
    // A switch compares whole registers, and a narrow subject has undefined high
5253 +
    // bits. The subject is extended as comparisons extend it: words and signed
5254 +
    // values by their sign, other values with zeros. Case values take the same form.
5255 +
    let typ = subject.ilType;
5256 +
    let signed = typ == il::Type::W32 or not isUnsignedType(&self.resolver, subject.type);
5241 5257
5242 5258
    for p, i in prongs {
5243 5259
        let case ast::NodeValue::MatchProng(prong) = p.value
5244 5260
            else throw LowerError::UnexpectedNodeValue(p);
5245 5261
5257 5273
                let cv = resolver::constValueEntry(&self.resolver, pat)
5258 5274
                    else throw LowerError::MissingConst(pat);
5259 5275
5260 5276
                try self.caseList.append(
5261 5277
                    il::SwitchCase {
5262 -
                        value: constToScalar(cv),
5278 +
                        value: extendedConst(constToScalar(cv), typ, signed),
5263 5279
                        target: *blocks[i],
5264 5280
                        args: il::ArgRange { start: 0, len: 0 },
5265 5281
                    },
5266 5282
                    &mut self.fnArena
5267 5283
                ) catch {
5269 5285
                };
5270 5286
            }
5271 5287
        }
5272 5288
        try addPredecessor(self, blocks[i], entry);
5273 5289
    }
5274 -
    let switchVal = try emitSubjectValue(self, subject);
5290 +
    let mut switchVal = try emitSubjectValue(self, subject);
5291 +
    if typ <> il::Type::W64 {
5292 +
        let dst = nextReg(self);
5293 +
        if signed {
5294 +
            try emit(self, il::Instr::Sext { typ, dst, val: switchVal });
5295 +
        } else {
5296 +
            try emit(self, il::Instr::Zext { typ, dst, val: switchVal });
5297 +
        }
5298 +
        set switchVal = il::Val::Reg(dst);
5299 +
    }
5275 5300
    try emit(self, il::Instr::Switch {
5276 5301
        val: switchVal,
5277 5302
        defaultTarget: *blocks[defaultIdx],
5278 5303
        defaultArgs: il::ArgRange { start: 0, len: 0 },
5279 5304
        cases: il::CaseRange { start: caseStart, len: self.caseList.len - caseStart },
test/tests/match.more.ril +4 -3
43 43
    unreachable;
44 44
}
45 45
46 46
fn w32 $matchNoElse(w32 %0) {
47 47
  @entry0
48 -
    switch %0 (1 @case1) @default2;
48 +
    sext w32 %1 %0;
49 +
    switch %1 (1 @case1) @default2;
49 50
  @case1
50 51
    jmp @merge3(1);
51 52
  @default2
52 53
    jmp @merge3(0);
53 -
  @merge3(w32 %1)
54 -
    ret %1;
54 +
  @merge3(w32 %2)
55 +
    ret %2;
55 56
}
test/tests/match.scalar.extension.rad added +61 -0
1 +
//! returns: 0
2 +
//! Scalar matches compare the value of narrow subjects, whatever high bits the
3 +
//! instruction that produced the subject left in its register.
4 +
5 +
/// Classify a word.
6 +
fn word(x: u32) -> u32 {
7 +
    match x {
8 +
        case 0x80000000 => return 1,
9 +
        case 0xffffffff => return 2,
10 +
        case 7 => return 3,
11 +
        else => return 0,
12 +
    }
13 +
}
14 +
15 +
/// Classify a signed word.
16 +
fn signedWord(x: i32) -> u32 {
17 +
    match x {
18 +
        case -1 => return 1,
19 +
        case -2147483648 => return 2,
20 +
        else => return 0,
21 +
    }
22 +
}
23 +
24 +
/// Classify a signed byte.
25 +
fn signedByte(x: i8) -> u32 {
26 +
    match x {
27 +
        case -1 => return 1,
28 +
        case 127 => return 2,
29 +
        else => return 0,
30 +
    }
31 +
}
32 +
33 +
/// Classify an unsigned halfword.
34 +
fn half(x: u16) -> u32 {
35 +
    match x {
36 +
        case 0 => return 1,
37 +
        case 0xffff => return 2,
38 +
        else => return 0,
39 +
    }
40 +
}
41 +
42 +
@default fn main() -> i32 {
43 +
    let words: [u32; 3] = [0x7fffffff, 0x80000000, 0xffffffff];
44 +
    // Computed and loaded words.
45 +
    assert word(words[0] + 1) == 1;
46 +
    assert word(words[1]) == 1;
47 +
    assert word(words[2]) == 2;
48 +
    assert word(words[0] * 2 + 1) == 2;
49 +
    assert word(words[2] + 8) == 3;
50 +
    // Same-size casts keep the bits of the source.
51 +
    assert signedWord(words[2] as i32) == 1;
52 +
    assert signedWord(words[1] as i32) == 2;
53 +
    assert signedWord(words[0] as i32) == 0;
54 +
    let bytes: [u8; 2] = [255, 127];
55 +
    assert signedByte(bytes[0] as i8) == 1;
56 +
    assert signedByte(bytes[1] as i8) == 2;
57 +
    let halves: [u16; 1] = [0xffff];
58 +
    assert half(halves[0]) == 2;
59 +
    assert half(halves[0] + 1) == 1;
60 +
    return 0;
61 +
}
test/tests/match.simple.ril +2 -1
1 1
fn w32 $matchSimple(w32 %0) {
2 2
  @entry0
3 -
    switch %0 (0 @case1) (1 @case2) @default3;
3 +
    sext w32 %1 %0;
4 +
    switch %1 (0 @case1) (1 @case2) @default3;
4 5
  @case1
5 6
    ret 0;
6 7
  @case2
7 8
    ret 1;
8 9
  @default3
test/tests/match.switch.ril +2 -1
1 1
fn w32 $matchSwitch(w32 %0) {
2 2
  @entry0
3 -
    switch %0 (0 @case1) (1 @case2) (2 @case3) @default4;
3 +
    sext w32 %1 %0;
4 +
    switch %1 (0 @case1) (1 @case2) (2 @case3) @default4;
4 5
  @case1
5 6
    ret 10;
6 7
  @case2
7 8
    ret 20;
8 9
  @case3
test/tests/match.wildcard.switch.ril +4 -2
1 1
fn w32 $literalThenWildcard(w32 %0) {
2 2
  @entry0
3 -
    switch %0 (2 @case1) @default2;
3 +
    sext w32 %1 %0;
4 +
    switch %1 (2 @case1) @default2;
4 5
  @case1
5 6
    ret 20;
6 7
  @default2
7 8
    ret 99;
8 9
}
9 10
10 11
fn w32 $multiWildcard(w32 %0) {
11 12
  @entry0
12 -
    switch %0 (2 @case1) @default2;
13 +
    sext w32 %1 %0;
14 +
    switch %1 (2 @case1) @default2;
13 15
  @case1
14 16
    ret 20;
15 17
  @default2
16 18
    ret 99;
17 19
}