aboutsummaryrefslogtreecommitdiff
path: root/src/arch
diff options
context:
space:
mode:
authormlugg <mlugg@mlugg.co.uk>2024-04-08 16:14:39 +0100
committermlugg <mlugg@mlugg.co.uk>2024-04-17 13:41:25 +0100
commitd0e74ffe52d0ae0d876d4e3f7ef5d32b5f5460a5 (patch)
tree001cb2b59a48e913e6036675b71f4736c55647c7 /src/arch
parent77abd3a96aa8c8c1277cdbb33d88149d4674d389 (diff)
downloadzig-d0e74ffe52d0ae0d876d4e3f7ef5d32b5f5460a5.tar.gz
zig-d0e74ffe52d0ae0d876d4e3f7ef5d32b5f5460a5.zip
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
Diffstat (limited to 'src/arch')
-rw-r--r--src/arch/wasm/CodeGen.zig123
-rw-r--r--src/arch/x86_64/CodeGen.zig8
2 files changed, 57 insertions, 74 deletions
diff --git a/src/arch/wasm/CodeGen.zig b/src/arch/wasm/CodeGen.zig
index 83159ec80e..fe94c06136 100644
--- a/src/arch/wasm/CodeGen.zig
+++ b/src/arch/wasm/CodeGen.zig
@@ -2206,7 +2206,7 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
);
break :blk extern_func.decl;
} else switch (mod.intern_pool.indexToKey(func_val.ip_index)) {
- .ptr => |ptr| switch (ptr.addr) {
+ .ptr => |ptr| if (ptr.byte_offset == 0) switch (ptr.base_addr) {
.decl => |decl| {
_ = try func.bin_file.getOrCreateAtomForDecl(decl);
break :blk decl;
@@ -3058,72 +3058,59 @@ fn wrapOperand(func: *CodeGen, operand: WValue, ty: Type) InnerError!WValue {
return WValue{ .stack = {} };
}
-fn lowerParentPtr(func: *CodeGen, ptr_val: Value, offset: u32) InnerError!WValue {
- const mod = func.bin_file.base.comp.module.?;
- const ptr = mod.intern_pool.indexToKey(ptr_val.ip_index).ptr;
- switch (ptr.addr) {
- .decl => |decl_index| {
- return func.lowerParentPtrDecl(ptr_val, decl_index, offset);
- },
- .anon_decl => |ad| return func.lowerAnonDeclRef(ad, offset),
- .eu_payload => |tag| return func.fail("TODO: Implement lowerParentPtr for {}", .{tag}),
- .int => |base| return func.lowerConstant(Value.fromInterned(base), Type.usize),
- .opt_payload => |base_ptr| return func.lowerParentPtr(Value.fromInterned(base_ptr), offset),
- .comptime_field, .comptime_alloc => unreachable,
- .elem => |elem| {
- const index = elem.index;
- const elem_type = Type.fromInterned(mod.intern_pool.typeOf(elem.base)).elemType2(mod);
- const elem_offset = index * elem_type.abiSize(mod);
- return func.lowerParentPtr(Value.fromInterned(elem.base), @as(u32, @intCast(elem_offset + offset)));
- },
+fn lowerPtr(func: *CodeGen, ptr_val: InternPool.Index, prev_offset: u64) InnerError!WValue {
+ const zcu = func.bin_file.base.comp.module.?;
+ const ptr = zcu.intern_pool.indexToKey(ptr_val).ptr;
+ const offset: u64 = prev_offset + ptr.byte_offset;
+ return switch (ptr.base_addr) {
+ .decl => |decl| return func.lowerDeclRefValue(decl, @intCast(offset)),
+ .anon_decl => |ad| return func.lowerAnonDeclRef(ad, @intCast(offset)),
+ .int => return func.lowerConstant(try zcu.intValue(Type.usize, offset), Type.usize),
+ .eu_payload => return func.fail("Wasm TODO: lower error union payload pointer", .{}),
+ .opt_payload => |opt_ptr| return func.lowerPtr(opt_ptr, offset),
.field => |field| {
- const parent_ptr_ty = Type.fromInterned(mod.intern_pool.typeOf(field.base));
- const parent_ty = parent_ptr_ty.childType(mod);
- const field_index: u32 = @intCast(field.index);
-
- const field_offset = switch (parent_ty.zigTypeTag(mod)) {
- .Struct => blk: {
- if (mod.typeToPackedStruct(parent_ty)) |struct_type| {
- if (Type.fromInterned(ptr.ty).ptrInfo(mod).packed_offset.host_size == 0)
- break :blk @divExact(mod.structPackedFieldBitOffset(struct_type, field_index) + parent_ptr_ty.ptrInfo(mod).packed_offset.bit_offset, 8)
- else
- break :blk 0;
- }
- break :blk parent_ty.structFieldOffset(field_index, mod);
+ const base_ptr = Value.fromInterned(field.base);
+ const base_ty = base_ptr.typeOf(zcu).childType(zcu);
+ const field_off: u64 = switch (base_ty.zigTypeTag(zcu)) {
+ .Pointer => off: {
+ assert(base_ty.isSlice(zcu));
+ break :off switch (field.index) {
+ Value.slice_ptr_index => 0,
+ Value.slice_len_index => @divExact(zcu.getTarget().ptrBitWidth(), 8),
+ else => unreachable,
+ };
},
- .Union => switch (parent_ty.containerLayout(mod)) {
- .@"packed" => 0,
- else => blk: {
- const layout: Module.UnionLayout = parent_ty.unionGetLayout(mod);
- if (layout.payload_size == 0) break :blk 0;
- if (layout.payload_align.compare(.gt, layout.tag_align)) break :blk 0;
-
- // tag is stored first so calculate offset from where payload starts
- break :blk layout.tag_align.forward(layout.tag_size);
- },
+ .Struct => switch (base_ty.containerLayout(zcu)) {
+ .auto => base_ty.structFieldOffset(@intCast(field.index), zcu),
+ .@"extern", .@"packed" => unreachable,
},
- .Pointer => switch (parent_ty.ptrSize(mod)) {
- .Slice => switch (field.index) {
- 0 => 0,
- 1 => func.ptrSize(),
- else => unreachable,
+ .Union => switch (base_ty.containerLayout(zcu)) {
+ .auto => off: {
+ // Keep in sync with the `un` case of `generateSymbol`.
+ const layout = base_ty.unionGetLayout(zcu);
+ if (layout.payload_size == 0) break :off 0;
+ if (layout.tag_size == 0) break :off 0;
+ if (layout.tag_align.compare(.gte, layout.payload_align)) {
+ // Tag first.
+ break :off layout.tag_size;
+ } else {
+ // Payload first.
+ break :off 0;
+ }
},
- else => unreachable,
+ .@"extern", .@"packed" => unreachable,
},
else => unreachable,
};
- return func.lowerParentPtr(Value.fromInterned(field.base), @as(u32, @intCast(offset + field_offset)));
+ return func.lowerPtr(field.base, offset + field_off);
},
- }
-}
-
-fn lowerParentPtrDecl(func: *CodeGen, ptr_val: Value, decl_index: InternPool.DeclIndex, offset: u32) InnerError!WValue {
- return func.lowerDeclRefValue(ptr_val, decl_index, offset);
+ .arr_elem, .comptime_field, .comptime_alloc => unreachable,
+ };
}
fn lowerAnonDeclRef(
func: *CodeGen,
- anon_decl: InternPool.Key.Ptr.Addr.AnonDecl,
+ anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl,
offset: u32,
) InnerError!WValue {
const mod = func.bin_file.base.comp.module.?;
@@ -3153,7 +3140,7 @@ fn lowerAnonDeclRef(
} else return WValue{ .memory_offset = .{ .pointer = target_sym_index, .offset = offset } };
}
-fn lowerDeclRefValue(func: *CodeGen, val: Value, decl_index: InternPool.DeclIndex, offset: u32) InnerError!WValue {
+fn lowerDeclRefValue(func: *CodeGen, decl_index: InternPool.DeclIndex, offset: u32) InnerError!WValue {
const mod = func.bin_file.base.comp.module.?;
const decl = mod.declPtr(decl_index);
@@ -3161,11 +3148,11 @@ fn lowerDeclRefValue(func: *CodeGen, val: Value, decl_index: InternPool.DeclInde
// want to lower the actual decl, rather than the alias itself.
if (decl.val.getFunction(mod)) |func_val| {
if (func_val.owner_decl != decl_index) {
- return func.lowerDeclRefValue(val, func_val.owner_decl, offset);
+ return func.lowerDeclRefValue(func_val.owner_decl, offset);
}
} else if (decl.val.getExternFunc(mod)) |func_val| {
if (func_val.decl != decl_index) {
- return func.lowerDeclRefValue(val, func_val.decl, offset);
+ return func.lowerDeclRefValue(func_val.decl, offset);
}
}
const decl_ty = decl.typeOf(mod);
@@ -3309,23 +3296,16 @@ fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
},
.slice => |slice| {
var ptr = ip.indexToKey(slice.ptr).ptr;
- const owner_decl = while (true) switch (ptr.addr) {
+ const owner_decl = while (true) switch (ptr.base_addr) {
.decl => |decl| break decl,
.int, .anon_decl => return func.fail("Wasm TODO: lower slice where ptr is not owned by decl", .{}),
.opt_payload, .eu_payload => |base| ptr = ip.indexToKey(base).ptr,
- .elem, .field => |base_index| ptr = ip.indexToKey(base_index.base).ptr,
- .comptime_field, .comptime_alloc => unreachable,
+ .field => |base_index| ptr = ip.indexToKey(base_index.base).ptr,
+ .arr_elem, .comptime_field, .comptime_alloc => unreachable,
};
return .{ .memory = try func.bin_file.lowerUnnamedConst(val, owner_decl) };
},
- .ptr => |ptr| switch (ptr.addr) {
- .decl => |decl| return func.lowerDeclRefValue(val, decl, 0),
- .int => |int| return func.lowerConstant(Value.fromInterned(int), Type.fromInterned(ip.typeOf(int))),
- .opt_payload, .elem, .field => return func.lowerParentPtr(val, 0),
- .anon_decl => |ad| return func.lowerAnonDeclRef(ad, 0),
- .comptime_field, .comptime_alloc => unreachable,
- else => return func.fail("Wasm TODO: lowerConstant for other const addr tag {}", .{ptr.addr}),
- },
+ .ptr => return func.lowerPtr(val.toIntern(), 0),
.opt => if (ty.optionalReprIsPayload(mod)) {
const pl_ty = ty.optionalChild(mod);
if (val.optionalValue(mod)) |payload| {
@@ -3435,7 +3415,10 @@ fn valueAsI32(func: *const CodeGen, val: Value, ty: Type) i32 {
else => return switch (mod.intern_pool.indexToKey(val.ip_index)) {
.enum_tag => |enum_tag| intIndexAsI32(&mod.intern_pool, enum_tag.int, mod),
.int => |int| intStorageAsI32(int.storage, mod),
- .ptr => |ptr| intIndexAsI32(&mod.intern_pool, ptr.addr.int, mod),
+ .ptr => |ptr| {
+ assert(ptr.base_addr == .int);
+ return @intCast(ptr.byte_offset);
+ },
.err => |err| @as(i32, @bitCast(@as(Module.ErrorInt, @intCast(mod.global_error_set.getIndex(err.name).?)))),
else => unreachable,
},
diff --git a/src/arch/x86_64/CodeGen.zig b/src/arch/x86_64/CodeGen.zig
index 9e18dbb42e..0681bc975d 100644
--- a/src/arch/x86_64/CodeGen.zig
+++ b/src/arch/x86_64/CodeGen.zig
@@ -12249,10 +12249,10 @@ fn genCall(self: *Self, info: union(enum) {
const func_key = mod.intern_pool.indexToKey(func_value.ip_index);
switch (switch (func_key) {
else => func_key,
- .ptr => |ptr| switch (ptr.addr) {
+ .ptr => |ptr| if (ptr.byte_offset == 0) switch (ptr.base_addr) {
.decl => |decl| mod.intern_pool.indexToKey(mod.declPtr(decl).val.toIntern()),
else => func_key,
- },
+ } else func_key,
}) {
.func => |func| {
if (self.bin_file.cast(link.File.Elf)) |elf_file| {
@@ -17877,8 +17877,8 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
break :result null;
}) orelse return self.fail("TODO implement airShuffle from {} and {} to {} with {}", .{
- lhs_ty.fmt(mod), rhs_ty.fmt(mod), dst_ty.fmt(mod),
- Value.fromInterned(extra.mask).fmtValue(mod),
+ lhs_ty.fmt(mod), rhs_ty.fmt(mod), dst_ty.fmt(mod),
+ Value.fromInterned(extra.mask).fmtValue(mod, null),
});
return self.finishAir(inst, result, .{ extra.a, extra.b, .none });
}