Skip to content

Commit 4ec2990

Browse files
mluggandrewrk
authored andcommitted
Sema: allow dereferencing ill-defined pointers to zero-bit types at comptime
It doesn't matter if a pointer to a zero-bit (i.e. OPV) type is undefined or runtime-known; we still know the result of the dereference at comptime. Code may use this, for instance, when allocating zero-bit types: `@as(*void, undefined)` is entirely reasonable to use at runtime, since we know the pointer will never be accessed, thus it should be valid at comptime too.
1 parent 68c7261 commit 4ec2990

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

src/Sema.zig

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4712,6 +4712,11 @@ fn zirValidateDeref(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
47124712
.Slice => return sema.fail(block, src, "index syntax required for slice type '{}'", .{operand_ty.fmt(sema.mod)}),
47134713
}
47144714

4715+
if ((try sema.typeHasOnePossibleValue(operand_ty.childType())) != null) {
4716+
// No need to validate the actual pointer value, we don't need it!
4717+
return;
4718+
}
4719+
47154720
const elem_ty = operand_ty.elemType2();
47164721
if (try sema.resolveMaybeUndefVal(operand)) |val| {
47174722
if (val.isUndef()) {

test/behavior/comptime_memory.zig

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,3 +420,11 @@ test "mutate entire slice at comptime" {
420420
buf[1..3].* = x;
421421
}
422422
}
423+
424+
test "dereference undefined pointer to zero-bit type" {
425+
const p0: *void = undefined;
426+
try testing.expectEqual({}, p0.*);
427+
428+
const p1: *[0]u32 = undefined;
429+
try testing.expect(p1.*.len == 0);
430+
}

0 commit comments

Comments
 (0)