Skip to content

Commit

Permalink
compiler: rework comptime pointer representation and access
Browse files Browse the repository at this point in the history
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
  • Loading branch information
mlugg committed Apr 12, 2024
1 parent 6dcbad7 commit 0b9f711
Show file tree
Hide file tree
Showing 33 changed files with 4,230 additions and 2,384 deletions.
410 changes: 271 additions & 139 deletions src/InternPool.zig

Large diffs are not rendered by default.

60 changes: 38 additions & 22 deletions src/Module.zig
Original file line number Diff line number Diff line change
Expand Up @@ -528,21 +528,6 @@ pub const Decl = struct {
return zcu.namespacePtrUnwrap(decl.getInnerNamespaceIndex(zcu));
}

pub fn dump(decl: *Decl) void {
const loc = std.zig.findLineColumn(decl.scope.source.bytes, decl.src);
std.debug.print("{s}:{d}:{d} name={d} status={s}", .{
decl.scope.sub_file_path,
loc.line + 1,
loc.column + 1,
@intFromEnum(decl.name),
@tagName(decl.analysis),
});
if (decl.has_tv) {
std.debug.print(" val={}", .{decl.val});
}
std.debug.print("\n", .{});
}

pub fn getFileScope(decl: Decl, zcu: *Zcu) *File {
return zcu.namespacePtr(decl.src_namespace).file_scope;
}
Expand Down Expand Up @@ -660,6 +645,22 @@ pub const Decl = struct {
},
};
}

pub fn declPtrType(decl: Decl, zcu: *Zcu) !Type {
assert(decl.has_tv);
const decl_ty = decl.typeOf(zcu);
return zcu.ptrType(.{
.child = decl_ty.toIntern(),
.flags = .{
.alignment = if (decl.alignment == decl_ty.abiAlignment(zcu))
.none
else
decl.alignment,
.address_space = decl.@"addrspace",
.is_const = true,
},
});
}
};

/// This state is attached to every Decl when Module emit_h is non-null.
Expand Down Expand Up @@ -3537,6 +3538,10 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
}

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

const old_has_tv = decl.has_tv;
// The following values are ignored if `!old_has_tv`
Expand Down Expand Up @@ -4114,10 +4119,11 @@ fn newEmbedFile(

const ptr_val = try ip.get(gpa, .{ .ptr = .{
.ty = ptr_ty,
.addr = .{ .anon_decl = .{
.base_addr = .{ .anon_decl = .{
.val = array_val,
.orig_ty = ptr_ty,
} },
.byte_offset = 0,
} });

result.* = new_file;
Expand Down Expand Up @@ -4476,6 +4482,11 @@ pub fn analyzeFnBody(mod: *Module, func_index: InternPool.Index, arena: Allocato
const decl_index = func.owner_decl;
const decl = mod.declPtr(decl_index);

log.debug("func name '{}'", .{(try decl.fullyQualifiedName(mod)).fmt(ip)});
defer blk: {
log.debug("finish func name '{}'", .{(decl.fullyQualifiedName(mod) catch break :blk).fmt(ip)});
}

mod.intern_pool.removeDependenciesForDepender(gpa, InternPool.Depender.wrap(.{ .func = func_index }));

var comptime_err_ret_trace = std.ArrayList(SrcLoc).init(gpa);
Expand Down Expand Up @@ -5319,7 +5330,7 @@ pub fn populateTestFunctions(
const decl = mod.declPtr(decl_index);
const test_fn_ty = decl.typeOf(mod).slicePtrFieldType(mod).childType(mod);

const array_anon_decl: InternPool.Key.Ptr.Addr.AnonDecl = array: {
const array_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = array: {
// Add mod.test_functions to an array decl then make the test_functions
// decl reference it as a slice.
const test_fn_vals = try gpa.alloc(InternPool.Index, mod.test_functions.count());
Expand All @@ -5329,7 +5340,7 @@ pub fn populateTestFunctions(
const test_decl = mod.declPtr(test_decl_index);
const test_decl_name = try gpa.dupe(u8, ip.stringToSlice(try test_decl.fullyQualifiedName(mod)));
defer gpa.free(test_decl_name);
const test_name_anon_decl: InternPool.Key.Ptr.Addr.AnonDecl = n: {
const test_name_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = n: {
const test_name_ty = try mod.arrayType(.{
.len = test_decl_name.len,
.child = .u8_type,
Expand All @@ -5350,7 +5361,8 @@ pub fn populateTestFunctions(
.ty = .slice_const_u8_type,
.ptr = try mod.intern(.{ .ptr = .{
.ty = .manyptr_const_u8_type,
.addr = .{ .anon_decl = test_name_anon_decl },
.base_addr = .{ .anon_decl = test_name_anon_decl },
.byte_offset = 0,
} }),
.len = try mod.intern(.{ .int = .{
.ty = .usize_type,
Expand All @@ -5365,7 +5377,8 @@ pub fn populateTestFunctions(
.is_const = true,
},
} }),
.addr = .{ .decl = test_decl_index },
.base_addr = .{ .decl = test_decl_index },
.byte_offset = 0,
} }),
};
test_fn_val.* = try mod.intern(.{ .aggregate = .{
Expand Down Expand Up @@ -5402,7 +5415,8 @@ pub fn populateTestFunctions(
.ty = new_ty.toIntern(),
.ptr = try mod.intern(.{ .ptr = .{
.ty = new_ty.slicePtrFieldType(mod).toIntern(),
.addr = .{ .anon_decl = array_anon_decl },
.base_addr = .{ .anon_decl = array_anon_decl },
.byte_offset = 0,
} }),
.len = (try mod.intValue(Type.usize, mod.test_functions.count())).toIntern(),
} });
Expand Down Expand Up @@ -5667,9 +5681,11 @@ pub fn errorSetFromUnsortedNames(
/// Supports only pointers, not pointer-like optionals.
pub fn ptrIntValue(mod: *Module, ty: Type, x: u64) Allocator.Error!Value {
assert(ty.zigTypeTag(mod) == .Pointer and !ty.isSlice(mod));
assert(x != 0 or ty.isAllowzeroPtr(mod));
const i = try intern(mod, .{ .ptr = .{
.ty = ty.toIntern(),
.addr = .{ .int = (try mod.intValue_u64(Type.usize, x)).toIntern() },
.base_addr = .int,
.byte_offset = x,
} });
return Value.fromInterned(i);
}
Expand Down
Loading

0 comments on commit 0b9f711

Please sign in to comment.