Skip to content

Commit 01a2a5b

Browse files
committed
compiler: rework comptime pointer representation and access
We've got a big one here! This commit reworks how we represent pointers in the InternPool, and rewrites the logic for loading and storing from them at comptime. Firstly, the pointer representation. Previously, pointers were represented in a highly structured manner: pointers to fields, array elements, etc, were explicitly represented. This works well for simple cases, but is quite difficult to handle in the cases of unusual reinterpretations, pointer casts, offsets, etc. Therefore, pointers are now represented in a more "flat" manner. For types without well-defined layouts -- such as comptime-only types, automatic-layout aggregates, and so on -- we still use this "hierarchical" structure. However, for types with well-defined layouts, we use a byte offset associated with the pointer. This allows the comptime pointer access logic to deal with reinterpreted pointers far more gracefully, because the "base address" of a pointer -- for instance a `field` -- is a single value which pointer accesses cannot exceed since the parent has undefined layout. This strategy is also more useful to most backends -- see the updated logic in `codegen.zig` and `codegen/llvm.zig`. For backends which do prefer a chain of field and elements accesses for lowering pointer values, such as SPIR-V, there is a helpful function in `Value` which creates a strategy to derive a pointer value using ideally only field and element accesses. This is actually more correct than the previous logic, since it correctly handles pointer casts which, after the dust has settled, end up referring exactly to an aggregate field or array element. In terms of the pointer access code, it has been rewritten from the ground up. The old logic had become rather a mess of special cases being added whenever bugs were hit, and was still riddled with bugs. The new logic was written to handle the "difficult" cases correctly, the most notable of which is restructuring of a comptime-only array (for instance, converting a `[3][2]comptime_int` to a `[2][3]comptime_int`. Currently, the logic for loading and storing work somewhat differently, but a future change will likely improve the loading logic to bring it more in line with the store strategy. As far as I can tell, the rewrite has fixed all bugs exposed by ziglang#19414. As a part of this, the comptime bitcast logic has also been rewritten. Previously, bitcasts simply worked by serializing the entire value into an in-memory buffer, then deserializing it. This strategy has two key weaknesses: pointers, and undefined values. Representations of these values at comptime cannot be easily serialized/deserialized whilst preserving data, which means many bitcasts would become runtime-known if pointers were involved, or would turn `undefined` values into `0xAA`. The new logic works by "flattening" the datastructure to be cast into a sequence of bit-packed atomic values, and then "unflattening" it; using serialization when necessary, but with special handling for `undefined` values and for pointers which align in virtual memory. The resulting code is definitely slower -- more on this later -- but it is correct. The pointer access and bitcast logic required some helper functions and types which are not generally useful elsewhere, so I opted to split them into separate files `Sema/comptime_ptr_access.zig` and `Sema/bitcast.zig`, with simple re-exports in `Sema.zig` for their small public APIs. Whilst working on this branch, I caught various unrelated bugs with transitive Sema errors, and with the handling of `undefined` values. These bugs have been fixed, and corresponding behavior test added. In terms of performance, I do anticipate that this commit will regress performance somewhat, because the new pointer access and bitcast logic is necessarily more complex. I have not yet taken performance measurements, but will do shortly, and post the results in this PR. If the performance regression is severe, I will do work to to optimize the new logic before merge. Resolves: ziglang#19452 Resolves: ziglang#19460
1 parent a0914e9 commit 01a2a5b

14 files changed

+143
-24
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
//! The full test name would be:
2+
//! struct field type resolution marks transitive error from bad usingnamespace in @typeInfo call from non-initial field type
3+
//!
4+
//! This test is rather esoteric. It's ensuring that errors triggered by `@typeInfo` analyzing
5+
//! a bad `usingnamespace` correctly trigger transitive errors when analyzed by struct field type
6+
//! resolution, meaning we don't incorrectly analyze code past the uses of `S`.
7+
8+
const S = struct {
9+
ok: u32,
10+
bad: @typeInfo(T),
11+
};
12+
13+
const T = struct {
14+
pub usingnamespace @compileError("usingnamespace analyzed");
15+
};
16+
17+
comptime {
18+
const a: S = .{ .ok = 123, .bad = undefined };
19+
_ = a;
20+
@compileError("should not be reached");
21+
}
22+
23+
comptime {
24+
const b: S = .{ .ok = 123, .bad = undefined };
25+
_ = b;
26+
@compileError("should not be reached");
27+
}
28+
29+
// error
30+
//
31+
// :14:24: error: usingnamespace analyzed

compile_errors/bit_ptr_non_packed.zig

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
export fn entry1() void {
2+
const S = extern struct { x: u32 };
3+
_ = *align(1:2:8) S;
4+
}
5+
6+
export fn entry2() void {
7+
const S = struct { x: u32 };
8+
_ = *align(1:2:@sizeOf(S) * 2) S;
9+
}
10+
11+
export fn entry3() void {
12+
const E = enum { implicit, backing, type };
13+
_ = *align(1:2:8) E;
14+
}
15+
16+
// error
17+
//
18+
// :3:23: error: bit-pointer cannot refer to value of type 'tmp.entry1.S'
19+
// :3:23: note: only packed structs layout are allowed in packed types
20+
// :8:36: error: bit-pointer cannot refer to value of type 'tmp.entry2.S'
21+
// :8:36: note: only packed structs layout are allowed in packed types
22+
// :13:23: error: bit-pointer cannot refer to value of type 'tmp.entry3.E'

compile_errors/bitcast_undef.zig

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
export fn entry1() void {
2+
const x: i32 = undefined;
3+
const y: u32 = @bitCast(x);
4+
@compileLog(y);
5+
}
6+
7+
export fn entry2() void {
8+
const x: packed struct { x: u16, y: u16 } = .{ .x = 123, .y = undefined };
9+
const y: u32 = @bitCast(x);
10+
@compileLog(y);
11+
}
12+
13+
// error
14+
//
15+
// :4:5: error: found compile log statement
16+
// :10:5: note: also here
17+
//
18+
// Compile Log Output:
19+
// @as(u32, undefined)
20+
// @as(u32, undefined)

compile_errors/compile_log_a_pointer_to_an_opaque_value.zig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,4 @@ export fn entry() void {
99
// :2:5: error: found compile log statement
1010
//
1111
// Compile Log Output:
12-
// @as(*const anyopaque, &tmp.entry)
12+
// @as(*const anyopaque, @as(*const anyopaque, @ptrCast(tmp.entry)))

compile_errors/comptime_dereference_slice_of_struct.zig

Lines changed: 0 additions & 13 deletions
This file was deleted.

compile_errors/dereferencing_invalid_payload_ptr_at_comptime.zig

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ comptime {
66

77
const payload_ptr = &opt_ptr.?;
88
opt_ptr = null;
9-
_ = payload_ptr.*.*;
9+
_ = payload_ptr.*.*; // TODO: this case was regressed by #19630
1010
}
1111
comptime {
1212
var opt: ?u8 = 15;
@@ -28,6 +28,5 @@ comptime {
2828
// backend=stage2
2929
// target=native
3030
//
31-
// :9:20: error: attempt to use null value
3231
// :16:20: error: attempt to use null value
3332
// :24:20: error: attempt to unwrap error: Foo

compile_errors/function_call_assigned_to_incorrect_type.zig

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@ fn concat() [16]f32 {
1111
// target=native
1212
//
1313
// :3:17: error: expected type '[4]f32', found '[16]f32'
14-
// :3:17: note: array of length 16 cannot cast into an array of length 4
14+
// :3:17: note: destination has length 4
15+
// :3:17: note: source has length 16

compile_errors/issue_7810-comptime_slice-len_increment_beyond_bounds.zig

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,5 @@ export fn foo_slice_len_increment_beyond_bounds() void {
88
}
99

1010
// error
11-
// backend=stage2
12-
// target=native
1311
//
14-
// :6:16: error: comptime store of index 8 out of bounds of array length 8
12+
// :6:16: error: dereference of '*u8' exceeds bounds of containing decl of type '[8]u8'
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
comptime {
2+
const a: @Vector(3, u8) = .{ 1, 200, undefined };
3+
@compileLog(@addWithOverflow(a, a));
4+
}
5+
6+
comptime {
7+
const a: @Vector(3, u8) = .{ 1, 2, undefined };
8+
const b: @Vector(3, u8) = .{ 0, 3, 10 };
9+
@compileLog(@subWithOverflow(a, b));
10+
}
11+
12+
comptime {
13+
const a: @Vector(3, u8) = .{ 1, 200, undefined };
14+
@compileLog(@mulWithOverflow(a, a));
15+
}
16+
17+
// error
18+
//
19+
// :3:5: error: found compile log statement
20+
// :9:5: note: also here
21+
// :14:5: note: also here
22+
//
23+
// Compile Log Output:
24+
// @as(struct{@Vector(3, u8), @Vector(3, u1)}, .{ .{ 2, 144, undefined }, .{ 0, 1, undefined } })
25+
// @as(struct{@Vector(3, u8), @Vector(3, u1)}, .{ .{ 1, 255, undefined }, .{ 0, 1, undefined } })
26+
// @as(struct{@Vector(3, u8), @Vector(3, u1)}, .{ .{ 1, 64, undefined }, .{ 0, 1, undefined } })

compile_errors/packed_struct_with_fields_of_not_allowed_types.zig

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ export fn entry6() void {
3030
}
3131
export fn entry7() void {
3232
_ = @sizeOf(packed struct {
33-
x: enum { A, B },
33+
x: enum(u1) { A, B },
3434
});
3535
}
3636
export fn entry8() void {
@@ -70,6 +70,12 @@ export fn entry13() void {
7070
x: *type,
7171
});
7272
}
73+
export fn entry14() void {
74+
const E = enum { implicit, backing, type };
75+
_ = @sizeOf(packed struct {
76+
x: E,
77+
});
78+
}
7379

7480
// error
7581
// backend=llvm
@@ -97,3 +103,5 @@ export fn entry13() void {
97103
// :70:12: error: packed structs cannot contain fields of type '*type'
98104
// :70:12: note: comptime-only pointer has no guaranteed in-memory representation
99105
// :70:12: note: types are not available at runtime
106+
// :76:12: error: packed structs cannot contain fields of type 'tmp.entry14.E'
107+
// :74:15: note: enum declared here
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
export fn entry1() void {
2+
const x: u32 = 123;
3+
const ptr: [*]const u32 = @ptrCast(&x);
4+
_ = ptr - 1;
5+
}
6+
7+
export fn entry2() void {
8+
const S = extern struct { x: u32, y: u32 };
9+
const y: u32 = 123;
10+
const parent_ptr: *const S = @fieldParentPtr("y", &y);
11+
_ = parent_ptr;
12+
}
13+
14+
// error
15+
//
16+
// :4:13: error: pointer computation here causes undefined behavior
17+
// :4:13: note: resulting pointer exceeds bounds of containing value which may trigger overflow
18+
// :10:55: error: pointer computation here causes undefined behavior
19+
// :10:55: note: resulting pointer exceeds bounds of containing value which may trigger overflow

compile_errors/reading_past_end_of_pointer_casted_array.zig

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,17 @@ comptime {
55
const deref = int_ptr.*;
66
_ = deref;
77
}
8+
comptime {
9+
const array: [4]u8 = "aoeu".*;
10+
const sub_array = array[1..];
11+
const int_ptr: *const u32 = @ptrCast(@alignCast(sub_array));
12+
const deref = int_ptr.*;
13+
_ = deref;
14+
}
815

916
// error
1017
// backend=stage2
1118
// target=native
1219
//
1320
// :5:26: error: dereference of '*const u24' exceeds bounds of containing decl of type '[4]u8'
21+
// :12:26: error: dereference of '*const u32' exceeds bounds of containing decl of type '[4]u8'

compile_errors/slice_cannot_have_its_bytes_reinterpreted.zig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,4 @@ export fn foo() void {
77
// backend=stage2
88
// target=native
99
//
10-
// :3:49: error: comptime dereference requires '[]const u8' to have a well-defined layout, but it does not.
10+
// :3:49: error: comptime dereference requires '[]const u8' to have a well-defined layout

comptime_aggregate_print.zig

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,5 +31,5 @@ pub fn main() !void {}
3131
// :20:5: error: found compile log statement
3232
//
3333
// Compile Log Output:
34-
// @as([]i32, &(comptime alloc).buf[0..2])
35-
// @as([]i32, &(comptime alloc).buf[0..2])
34+
// @as([]i32, @as([*]i32, @ptrCast(@as(tmp.UnionContainer, .{ .buf = .{ 1, 2 } }).buf[0]))[0..2])
35+
// @as([]i32, @as([*]i32, @ptrCast(@as(tmp.StructContainer, .{ .buf = .{ 3, 4 } }).buf[0]))[0..2])

0 commit comments

Comments
 (0)