Skip to content

Commit 83e8d6d

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 #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: #19452 Resolves: #19460
1 parent 05d9755 commit 83e8d6d

34 files changed

+4297
-2436
lines changed

src/InternPool.zig

Lines changed: 272 additions & 140 deletions
Large diffs are not rendered by default.

src/Module.zig

Lines changed: 38 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -528,21 +528,6 @@ pub const Decl = struct {
528528
return zcu.namespacePtrUnwrap(decl.getInnerNamespaceIndex(zcu));
529529
}
530530

531-
pub fn dump(decl: *Decl) void {
532-
const loc = std.zig.findLineColumn(decl.scope.source.bytes, decl.src);
533-
std.debug.print("{s}:{d}:{d} name={d} status={s}", .{
534-
decl.scope.sub_file_path,
535-
loc.line + 1,
536-
loc.column + 1,
537-
@intFromEnum(decl.name),
538-
@tagName(decl.analysis),
539-
});
540-
if (decl.has_tv) {
541-
std.debug.print(" val={}", .{decl.val});
542-
}
543-
std.debug.print("\n", .{});
544-
}
545-
546531
pub fn getFileScope(decl: Decl, zcu: *Zcu) *File {
547532
return zcu.namespacePtr(decl.src_namespace).file_scope;
548533
}
@@ -660,6 +645,22 @@ pub const Decl = struct {
660645
},
661646
};
662647
}
648+
649+
pub fn declPtrType(decl: Decl, zcu: *Zcu) !Type {
650+
assert(decl.has_tv);
651+
const decl_ty = decl.typeOf(zcu);
652+
return zcu.ptrType(.{
653+
.child = decl_ty.toIntern(),
654+
.flags = .{
655+
.alignment = if (decl.alignment == decl_ty.abiAlignment(zcu))
656+
.none
657+
else
658+
decl.alignment,
659+
.address_space = decl.@"addrspace",
660+
.is_const = decl.getOwnedVariable(zcu) == null,
661+
},
662+
});
663+
}
663664
};
664665

665666
/// This state is attached to every Decl when Module emit_h is non-null.
@@ -3535,6 +3536,10 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
35353536
}
35363537

35373538
log.debug("semaDecl '{d}'", .{@intFromEnum(decl_index)});
3539+
log.debug("decl name '{}'", .{(try decl.fullyQualifiedName(mod)).fmt(ip)});
3540+
defer blk: {
3541+
log.debug("finish decl name '{}'", .{(decl.fullyQualifiedName(mod) catch break :blk).fmt(ip)});
3542+
}
35383543

35393544
const old_has_tv = decl.has_tv;
35403545
// The following values are ignored if `!old_has_tv`
@@ -4122,10 +4127,11 @@ fn newEmbedFile(
41224127
})).toIntern();
41234128
const ptr_val = try ip.get(gpa, .{ .ptr = .{
41244129
.ty = ptr_ty,
4125-
.addr = .{ .anon_decl = .{
4130+
.base_addr = .{ .anon_decl = .{
41264131
.val = array_val,
41274132
.orig_ty = ptr_ty,
41284133
} },
4134+
.byte_offset = 0,
41294135
} });
41304136

41314137
result.* = new_file;
@@ -4489,6 +4495,11 @@ pub fn analyzeFnBody(mod: *Module, func_index: InternPool.Index, arena: Allocato
44894495
const decl_index = func.owner_decl;
44904496
const decl = mod.declPtr(decl_index);
44914497

4498+
log.debug("func name '{}'", .{(try decl.fullyQualifiedName(mod)).fmt(ip)});
4499+
defer blk: {
4500+
log.debug("finish func name '{}'", .{(decl.fullyQualifiedName(mod) catch break :blk).fmt(ip)});
4501+
}
4502+
44924503
mod.intern_pool.removeDependenciesForDepender(gpa, InternPool.Depender.wrap(.{ .func = func_index }));
44934504

44944505
var comptime_err_ret_trace = std.ArrayList(SrcLoc).init(gpa);
@@ -5332,7 +5343,7 @@ pub fn populateTestFunctions(
53325343
const decl = mod.declPtr(decl_index);
53335344
const test_fn_ty = decl.typeOf(mod).slicePtrFieldType(mod).childType(mod);
53345345

5335-
const array_anon_decl: InternPool.Key.Ptr.Addr.AnonDecl = array: {
5346+
const array_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = array: {
53365347
// Add mod.test_functions to an array decl then make the test_functions
53375348
// decl reference it as a slice.
53385349
const test_fn_vals = try gpa.alloc(InternPool.Index, mod.test_functions.count());
@@ -5342,7 +5353,7 @@ pub fn populateTestFunctions(
53425353
const test_decl = mod.declPtr(test_decl_index);
53435354
const test_decl_name = try test_decl.fullyQualifiedName(mod);
53445355
const test_decl_name_len = test_decl_name.length(ip);
5345-
const test_name_anon_decl: InternPool.Key.Ptr.Addr.AnonDecl = n: {
5356+
const test_name_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = n: {
53465357
const test_name_ty = try mod.arrayType(.{
53475358
.len = test_decl_name_len,
53485359
.child = .u8_type,
@@ -5363,7 +5374,8 @@ pub fn populateTestFunctions(
53635374
.ty = .slice_const_u8_type,
53645375
.ptr = try mod.intern(.{ .ptr = .{
53655376
.ty = .manyptr_const_u8_type,
5366-
.addr = .{ .anon_decl = test_name_anon_decl },
5377+
.base_addr = .{ .anon_decl = test_name_anon_decl },
5378+
.byte_offset = 0,
53675379
} }),
53685380
.len = try mod.intern(.{ .int = .{
53695381
.ty = .usize_type,
@@ -5378,7 +5390,8 @@ pub fn populateTestFunctions(
53785390
.is_const = true,
53795391
},
53805392
} }),
5381-
.addr = .{ .decl = test_decl_index },
5393+
.base_addr = .{ .decl = test_decl_index },
5394+
.byte_offset = 0,
53825395
} }),
53835396
};
53845397
test_fn_val.* = try mod.intern(.{ .aggregate = .{
@@ -5415,7 +5428,8 @@ pub fn populateTestFunctions(
54155428
.ty = new_ty.toIntern(),
54165429
.ptr = try mod.intern(.{ .ptr = .{
54175430
.ty = new_ty.slicePtrFieldType(mod).toIntern(),
5418-
.addr = .{ .anon_decl = array_anon_decl },
5431+
.base_addr = .{ .anon_decl = array_anon_decl },
5432+
.byte_offset = 0,
54195433
} }),
54205434
.len = (try mod.intValue(Type.usize, mod.test_functions.count())).toIntern(),
54215435
} });
@@ -5680,9 +5694,11 @@ pub fn errorSetFromUnsortedNames(
56805694
/// Supports only pointers, not pointer-like optionals.
56815695
pub fn ptrIntValue(mod: *Module, ty: Type, x: u64) Allocator.Error!Value {
56825696
assert(ty.zigTypeTag(mod) == .Pointer and !ty.isSlice(mod));
5697+
assert(x != 0 or ty.isAllowzeroPtr(mod));
56835698
const i = try intern(mod, .{ .ptr = .{
56845699
.ty = ty.toIntern(),
5685-
.addr = .{ .int = (try mod.intValue_u64(Type.usize, x)).toIntern() },
5700+
.base_addr = .int,
5701+
.byte_offset = x,
56865702
} });
56875703
return Value.fromInterned(i);
56885704
}

0 commit comments

Comments
 (0)