aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorAndrew Kelley <andrew@ziglang.org>2022-06-12 17:45:57 -0400
committerGitHub <noreply@github.com>2022-06-12 17:45:57 -0400
commitffa700ee58cd29dafe2bbdfe78a4bd4f7bab0674 (patch)
treeaffe8b6dc716051f32259ad171f93d7009855c0f /src
parent6e42d45dccf4ba6fa07082db1cb820897d36924f (diff)
parent0a9d6956e7cac96c870ad062b4125b0a0a3b0143 (diff)
downloadzig-ffa700ee58cd29dafe2bbdfe78a4bd4f7bab0674.tar.gz
zig-ffa700ee58cd29dafe2bbdfe78a4bd4f7bab0674.zip
Merge pull request #11837 from Vexu/stage2
Fix (nearly) all stage2 crashes when testing stdlib
Diffstat (limited to 'src')
-rw-r--r--src/AstGen.zig7
-rw-r--r--src/Module.zig7
-rw-r--r--src/Sema.zig142
-rw-r--r--src/TypedValue.zig75
-rw-r--r--src/Zir.zig2
-rw-r--r--src/arch/aarch64/CodeGen.zig11
-rw-r--r--src/arch/arm/CodeGen.zig12
-rw-r--r--src/arch/wasm/CodeGen.zig60
-rw-r--r--src/arch/x86_64/CodeGen.zig21
-rw-r--r--src/codegen.zig9
-rw-r--r--src/codegen/c.zig76
-rw-r--r--src/codegen/llvm.zig117
-rw-r--r--src/codegen/llvm/bindings.zig3
-rw-r--r--src/print_air.zig38
-rw-r--r--src/type.zig192
-rw-r--r--src/value.zig1
16 files changed, 312 insertions, 461 deletions
diff --git a/src/AstGen.zig b/src/AstGen.zig
index 3f22146f0e..078523831c 100644
--- a/src/AstGen.zig
+++ b/src/AstGen.zig
@@ -2753,7 +2753,10 @@ fn varDecl(
const result_loc: ResultLoc = if (type_node != 0) .{
.ty = try typeExpr(gz, scope, type_node),
} else .none;
+ const prev_anon_name_strategy = gz.anon_name_strategy;
+ gz.anon_name_strategy = .dbg_var;
const init_inst = try reachableExpr(gz, scope, result_loc, var_decl.ast.init_node, node);
+ gz.anon_name_strategy = prev_anon_name_strategy;
try gz.addDbgVar(.dbg_var_val, ident_name, init_inst);
@@ -2777,6 +2780,7 @@ fn varDecl(
var init_scope = gz.makeSubBlock(scope);
// we may add more instructions to gz before stacking init_scope
init_scope.instructions_top = GenZir.unstacked_top;
+ init_scope.anon_name_strategy = .dbg_var;
defer init_scope.unstack();
var resolve_inferred_alloc: Zir.Inst.Ref = .none;
@@ -2956,7 +2960,10 @@ fn varDecl(
resolve_inferred_alloc = alloc;
break :a .{ .alloc = alloc, .result_loc = .{ .inferred_ptr = alloc } };
};
+ const prev_anon_name_strategy = gz.anon_name_strategy;
+ gz.anon_name_strategy = .dbg_var;
_ = try reachableExprComptime(gz, scope, var_data.result_loc, var_decl.ast.init_node, node, is_comptime);
+ gz.anon_name_strategy = prev_anon_name_strategy;
if (resolve_inferred_alloc != .none) {
_ = try gz.addUnNode(.resolve_inferred_alloc, resolve_inferred_alloc, node);
}
diff --git a/src/Module.zig b/src/Module.zig
index f03ba77a39..bcf6491ce6 100644
--- a/src/Module.zig
+++ b/src/Module.zig
@@ -3790,9 +3790,12 @@ pub fn ensureFuncBodyAnalyzed(mod: *Module, func: *Fn) SemaError!void {
defer liveness.deinit(gpa);
if (builtin.mode == .Debug and mod.comp.verbose_air) {
- std.debug.print("# Begin Function AIR: {s}:\n", .{decl.name});
+ const fqn = try decl.getFullyQualifiedName(mod);
+ defer mod.gpa.free(fqn);
+
+ std.debug.print("# Begin Function AIR: {s}:\n", .{fqn});
@import("print_air.zig").dump(mod, air, liveness);
- std.debug.print("# End Function AIR: {s}\n\n", .{decl.name});
+ std.debug.print("# End Function AIR: {s}\n\n", .{fqn});
}
mod.comp.bin_file.updateFunc(mod, func, air, liveness) catch |err| switch (err) {
diff --git a/src/Sema.zig b/src/Sema.zig
index bad343f941..a5e991c617 100644
--- a/src/Sema.zig
+++ b/src/Sema.zig
@@ -914,9 +914,9 @@ fn analyzeBodyInner(
// zig fmt: off
.variable => try sema.zirVarExtended( block, extended),
.struct_decl => try sema.zirStructDecl( block, extended, inst),
- .enum_decl => try sema.zirEnumDecl( block, extended),
+ .enum_decl => try sema.zirEnumDecl( block, extended, inst),
.union_decl => try sema.zirUnionDecl( block, extended, inst),
- .opaque_decl => try sema.zirOpaqueDecl( block, extended),
+ .opaque_decl => try sema.zirOpaqueDecl( block, extended, inst),
.this => try sema.zirThis( block, extended),
.ret_addr => try sema.zirRetAddr( block, extended),
.builtin_src => try sema.zirBuiltinSrc( block, extended),
@@ -2101,7 +2101,7 @@ fn zirStructDecl(
const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
.ty = Type.type,
.val = struct_val,
- }, small.name_strategy, "struct");
+ }, small.name_strategy, "struct", inst);
const new_decl = mod.declPtr(new_decl_index);
new_decl.owns_tv = true;
errdefer mod.abortAnonDecl(new_decl_index);
@@ -2133,6 +2133,7 @@ fn createAnonymousDeclTypeNamed(
typed_value: TypedValue,
name_strategy: Zir.Inst.NameStrategy,
anon_prefix: []const u8,
+ inst: ?Zir.Inst.Index,
) !Decl.Index {
const mod = sema.mod;
const namespace = block.namespace;
@@ -2152,11 +2153,13 @@ fn createAnonymousDeclTypeNamed(
const name = try std.fmt.allocPrintZ(sema.gpa, "{s}__{s}_{d}", .{
src_decl.name, anon_prefix, @enumToInt(new_decl_index),
});
+ errdefer sema.gpa.free(name);
try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, namespace, typed_value, name);
return new_decl_index;
},
.parent => {
const name = try sema.gpa.dupeZ(u8, mem.sliceTo(sema.mod.declPtr(block.src_decl).name, 0));
+ errdefer sema.gpa.free(name);
try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, namespace, typed_value, name);
return new_decl_index;
},
@@ -2188,9 +2191,31 @@ fn createAnonymousDeclTypeNamed(
try buf.appendSlice(")");
const name = try buf.toOwnedSliceSentinel(0);
+ errdefer sema.gpa.free(name);
try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, namespace, typed_value, name);
return new_decl_index;
},
+ .dbg_var => {
+ const ref = Zir.indexToRef(inst.?);
+ const zir_tags = sema.code.instructions.items(.tag);
+ const zir_data = sema.code.instructions.items(.data);
+ var i = inst.?;
+ while (i < zir_tags.len) : (i += 1) switch (zir_tags[i]) {
+ .dbg_var_ptr, .dbg_var_val => {
+ if (zir_data[i].str_op.operand != ref) continue;
+
+ const name = try std.fmt.allocPrintZ(sema.gpa, "{s}.{s}", .{
+ src_decl.name, zir_data[i].str_op.getStr(sema.code),
+ });
+ errdefer sema.gpa.free(name);
+
+ try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, namespace, typed_value, name);
+ return new_decl_index;
+ },
+ else => {},
+ };
+ return sema.createAnonymousDeclTypeNamed(block, typed_value, .anon, anon_prefix, null);
+ },
}
}
@@ -2198,6 +2223,7 @@ fn zirEnumDecl(
sema: *Sema,
block: *Block,
extended: Zir.Inst.Extended.InstData,
+ inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
const tracy = trace(@src());
defer tracy.end();
@@ -2252,7 +2278,7 @@ fn zirEnumDecl(
const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
.ty = Type.type,
.val = enum_val,
- }, small.name_strategy, "enum");
+ }, small.name_strategy, "enum", inst);
const new_decl = mod.declPtr(new_decl_index);
new_decl.owns_tv = true;
errdefer mod.abortAnonDecl(new_decl_index);
@@ -2472,7 +2498,7 @@ fn zirUnionDecl(
const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
.ty = Type.type,
.val = union_val,
- }, small.name_strategy, "union");
+ }, small.name_strategy, "union", inst);
const new_decl = mod.declPtr(new_decl_index);
new_decl.owns_tv = true;
errdefer mod.abortAnonDecl(new_decl_index);
@@ -2504,6 +2530,7 @@ fn zirOpaqueDecl(
sema: *Sema,
block: *Block,
extended: Zir.Inst.Extended.InstData,
+ inst: Zir.Inst.Index,
) CompileError!Air.Inst.Ref {
const tracy = trace(@src());
defer tracy.end();
@@ -2540,7 +2567,7 @@ fn zirOpaqueDecl(
const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
.ty = Type.type,
.val = opaque_val,
- }, small.name_strategy, "opaque");
+ }, small.name_strategy, "opaque", inst);
const new_decl = mod.declPtr(new_decl_index);
new_decl.owns_tv = true;
errdefer mod.abortAnonDecl(new_decl_index);
@@ -2589,7 +2616,7 @@ fn zirErrorSetDecl(
const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
.ty = Type.type,
.val = error_set_val,
- }, name_strategy, "error");
+ }, name_strategy, "error", inst);
const new_decl = mod.declPtr(new_decl_index);
new_decl.owns_tv = true;
errdefer mod.abortAnonDecl(new_decl_index);
@@ -4967,6 +4994,8 @@ fn lookupInNamespace(
var it = check_ns.usingnamespace_set.iterator();
while (it.next()) |entry| {
const sub_usingnamespace_decl_index = entry.key_ptr.*;
+ // Skip the decl we're currently analysing.
+ if (sub_usingnamespace_decl_index == sema.owner_decl_index) continue;
const sub_usingnamespace_decl = mod.declPtr(sub_usingnamespace_decl_index);
const sub_is_pub = entry.value_ptr.*;
if (!sub_is_pub and src_file != sub_usingnamespace_decl.getFileScope()) {
@@ -6180,6 +6209,17 @@ fn zirErrorToInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
}
}
+ const op_ty = sema.typeOf(op);
+ try sema.resolveInferredErrorSetTy(block, src, op_ty);
+ if (!op_ty.isAnyError()) {
+ const names = op_ty.errorSetNames();
+ switch (names.len) {
+ 0 => return sema.addConstant(result_ty, Value.zero),
+ 1 => return sema.addIntUnsigned(result_ty, sema.mod.global_error_set.get(names[0]).?),
+ else => {},
+ }
+ }
+
try sema.requireRuntimeBlock(block, src);
return block.addBitCast(result_ty, op_coerced);
}
@@ -6558,7 +6598,7 @@ fn analyzeErrUnionPayload(
// If the error set has no fields then no safety check is needed.
if (safety_check and block.wantSafety() and
- err_union_ty.errorUnionSet().errorSetCardinality() != .zero)
+ !err_union_ty.errorUnionSet().errorSetIsEmpty())
{
try sema.panicUnwrapError(block, src, operand, .unwrap_errunion_err, .is_non_err);
}
@@ -6644,7 +6684,7 @@ fn analyzeErrUnionPayloadPtr(
// If the error set has no fields then no safety check is needed.
if (safety_check and block.wantSafety() and
- err_union_ty.errorUnionSet().errorSetCardinality() != .zero)
+ !err_union_ty.errorUnionSet().errorSetIsEmpty())
{
try sema.panicUnwrapError(block, src, operand, .unwrap_errunion_err_ptr, .is_non_err_ptr);
}
@@ -11859,10 +11899,14 @@ fn zirBuiltinSrc(
const file_name_val = blk: {
var anon_decl = try block.startAnonDecl(src);
defer anon_decl.deinit();
- const name = try fn_owner_decl.getFileScope().fullPathZ(anon_decl.arena());
+ const relative_path = try fn_owner_decl.getFileScope().fullPath(sema.arena);
+ const absolute_path = std.fs.realpathAlloc(sema.arena, relative_path) catch |err| {
+ return sema.fail(block, src, "failed to get absolute path of file '{s}': {s}", .{ relative_path, @errorName(err) });
+ };
+ const aboslute_duped = try anon_decl.arena().dupeZ(u8, absolute_path);
const new_decl = try anon_decl.finish(
- try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), name.len),
- try Value.Tag.bytes.create(anon_decl.arena(), name[0 .. name.len + 1]),
+ try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), aboslute_duped.len),
+ try Value.Tag.bytes.create(anon_decl.arena(), aboslute_duped[0 .. aboslute_duped.len + 1]),
0, // default alignment
);
break :blk try Value.Tag.decl_ref.create(sema.arena, new_decl);
@@ -11873,6 +11917,7 @@ fn zirBuiltinSrc(
field_values[0] = file_name_val;
// fn_name: [:0]const u8,
field_values[1] = func_name_val;
+ // TODO these should be runtime only!
// line: u32
field_values[2] = try Value.Tag.int_u64.create(sema.arena, extra.line + 1);
// column: u32,
@@ -13712,10 +13757,10 @@ fn zirStructInit(
const field_type_extra = sema.code.extraData(Zir.Inst.FieldType, field_type_data.payload_index).data;
const field_name = sema.code.nullTerminatedString(field_type_extra.name_start);
const field_index = try sema.unionFieldIndex(block, resolved_ty, field_name, field_src);
+ const tag_val = try Value.Tag.enum_field_index.create(sema.arena, field_index);
const init_inst = try sema.resolveInst(item.data.init);
if (try sema.resolveMaybeUndefVal(block, field_src, init_inst)) |val| {
- const tag_val = try Value.Tag.enum_field_index.create(sema.arena, field_index);
return sema.addConstantMaybeRef(
block,
src,
@@ -13734,6 +13779,8 @@ fn zirStructInit(
const alloc = try block.addTy(.alloc, alloc_ty);
const field_ptr = try sema.unionFieldPtr(block, field_src, alloc, field_name, field_src, resolved_ty);
try sema.storePtr(block, src, field_ptr, init_inst);
+ const new_tag = try sema.addConstant(resolved_ty.unionTagTypeHypothetical(), tag_val);
+ _ = try block.addBinOp(.set_union_tag, alloc, new_tag);
return alloc;
}
@@ -14614,7 +14661,7 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
.ty = Type.type,
.val = enum_val,
- }, .anon, "enum");
+ }, .anon, "enum", null);
const new_decl = mod.declPtr(new_decl_index);
new_decl.owns_tv = true;
errdefer mod.abortAnonDecl(new_decl_index);
@@ -14704,7 +14751,7 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
.ty = Type.type,
.val = opaque_val,
- }, .anon, "opaque");
+ }, .anon, "opaque", null);
const new_decl = mod.declPtr(new_decl_index);
new_decl.owns_tv = true;
errdefer mod.abortAnonDecl(new_decl_index);
@@ -14755,7 +14802,7 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
.ty = Type.type,
.val = new_union_val,
- }, .anon, "union");
+ }, .anon, "union", null);
const new_decl = mod.declPtr(new_decl_index);
new_decl.owns_tv = true;
errdefer mod.abortAnonDecl(new_decl_index);
@@ -14923,7 +14970,7 @@ fn reifyStruct(
const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
.ty = Type.type,
.val = new_struct_val,
- }, .anon, "struct");
+ }, .anon, "struct", null);
const new_decl = mod.declPtr(new_decl_index);
new_decl.owns_tv = true;
errdefer mod.abortAnonDecl(new_decl_index);
@@ -19700,7 +19747,8 @@ fn coerce(
// pointer to tuple to slice
if (inst_ty.isSinglePointer() and
inst_ty.childType().isTuple() and
- !dest_info.mutable and dest_info.size == .Slice)
+ (!dest_info.mutable or inst_ty.ptrIsMutable() or inst_ty.childType().tupleFields().types.len == 0) and
+ dest_info.size == .Slice)
{
return sema.coerceTupleToSlicePtrs(block, dest_ty, dest_ty_src, inst, inst_src);
}
@@ -23540,7 +23588,17 @@ pub fn resolveTypeFully(
const child_ty = try sema.resolveTypeFields(block, src, ty.childType());
return resolveTypeFully(sema, block, src, child_ty);
},
- .Struct => return resolveStructFully(sema, block, src, ty),
+ .Struct => switch (ty.tag()) {
+ .@"struct" => return resolveStructFully(sema, block, src, ty),
+ .tuple, .anon_struct => {
+ const tuple = ty.tupleFields();
+
+ for (tuple.types) |field_ty| {
+ try sema.resolveTypeFully(block, src, field_ty);
+ }
+ },
+ else => {},
+ },
.Union => return resolveUnionFully(sema, block, src, ty),
.Array => return resolveTypeFully(sema, block, src, ty.childType()),
.Optional => {
@@ -23575,7 +23633,7 @@ fn resolveStructFully(
try resolveStructLayout(sema, block, src, ty);
const resolved_ty = try sema.resolveTypeFields(block, src, ty);
- const payload = resolved_ty.castTag(.@"struct") orelse return;
+ const payload = resolved_ty.castTag(.@"struct").?;
const struct_obj = payload.data;
switch (struct_obj.status) {
@@ -24425,6 +24483,10 @@ pub fn typeHasOnePossibleValue(
.bool,
.type,
.anyerror,
+ .error_set_single,
+ .error_set,
+ .error_set_merged,
+ .error_union,
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
@@ -24481,46 +24543,6 @@ pub fn typeHasOnePossibleValue(
}
},
- .error_union => {
- const error_ty = ty.errorUnionSet();
- switch (error_ty.errorSetCardinality()) {
- .zero => {
- const payload_ty = ty.errorUnionPayload();
- if (try typeHasOnePossibleValue(sema, block, src, payload_ty)) |payload_val| {
- return try Value.Tag.eu_payload.create(sema.arena, payload_val);
- } else {
- return null;
- }
- },
- .one => {
- if (ty.errorUnionPayload().isNoReturn()) {
- const error_val = (try typeHasOnePossibleValue(sema, block, src, error_ty)).?;
- return error_val;
- } else {
- return null;
- }
- },
- .many => return null,
- }
- },
-
- .error_set_single => {
- const name = ty.castTag(.error_set_single).?.data;
- return try Value.Tag.@"error".create(sema.arena, .{ .name = name });
- },
- .error_set => {
- const err_set_obj = ty.castTag(.error_set).?.data;
- const names = err_set_obj.names.keys();
- if (names.len > 1) return null;
- return try Value.Tag.@"error".create(sema.arena, .{ .name = names[0] });
- },
- .error_set_merged => {
- const name_map = ty.castTag(.error_set_merged).?.data;
- const names = name_map.keys();
- if (names.len > 1) return null;
- return try Value.Tag.@"error".create(sema.arena, .{ .name = names[0] });
- },
-
.@"struct" => {
const resolved_ty = try sema.resolveTypeFields(block, src, ty);
const s = resolved_ty.castTag(.@"struct").?.data;
diff --git a/src/TypedValue.zig b/src/TypedValue.zig
index 4b3bc23231..3c1b28e544 100644
--- a/src/TypedValue.zig
+++ b/src/TypedValue.zig
@@ -144,7 +144,41 @@ pub fn print(
return writer.writeAll(".{ ... }");
}
const vals = val.castTag(.aggregate).?.data;
- if (ty.zigTypeTag() == .Struct) {
+ if (ty.castTag(.anon_struct)) |anon_struct| {
+ const field_names = anon_struct.data.names;
+ const types = anon_struct.data.types;
+ const max_len = std.math.min(types.len, max_aggregate_items);
+
+ var i: u32 = 0;
+ while (i < max_len) : (i += 1) {
+ if (i != 0) try writer.writeAll(", ");
+ try writer.print(".{s} = ", .{field_names[i]});
+ try print(.{
+ .ty = types[i],
+ .val = vals[i],
+ }, writer, level - 1, mod);
+ }
+ if (types.len > max_aggregate_items) {
+ try writer.writeAll(", ...");
+ }
+ return writer.writeAll(" }");
+ } else if (ty.isTuple()) {
+ const fields = ty.tupleFields();
+ const max_len = std.math.min(fields.types.len, max_aggregate_items);
+
+ var i: u32 = 0;
+ while (i < max_len) : (i += 1) {
+ if (i != 0) try writer.writeAll(", ");
+ try print(.{
+ .ty = fields.types[i],
+ .val = vals[i],
+ }, writer, level - 1, mod);
+ }
+ if (fields.types.len > max_aggregate_items) {
+ try writer.writeAll(", ...");
+ }
+ return writer.writeAll(" }");
+ } else if (ty.zigTypeTag() == .Struct) {
try writer.writeAll(".{ ");
const struct_fields = ty.structFields();
const len = struct_fields.count();
@@ -194,7 +228,7 @@ pub fn print(
try writer.writeAll(".{ ");
try print(.{
- .ty = ty.unionTagType().?,
+ .ty = ty.cast(Type.Payload.Union).?.data.tag_ty,
.val = union_val.tag,
}, writer, level - 1, mod);
try writer.writeAll(" = ");
@@ -278,19 +312,27 @@ pub fn print(
.elem_ptr => {
const elem_ptr = val.castTag(.elem_ptr).?.data;
try writer.writeAll("&");
- try print(.{
- .ty = elem_ptr.elem_ty,
- .val = elem_ptr.array_ptr,
- }, writer, level - 1, mod);
+ if (level == 0) {
+ try writer.writeAll("(ptr)");
+ } else {
+ try print(.{
+ .ty = elem_ptr.elem_ty,
+ .val = elem_ptr.array_ptr,
+ }, writer, level - 1, mod);
+ }
return writer.print("[{}]", .{elem_ptr.index});
},
.field_ptr => {
const field_ptr = val.castTag(.field_ptr).?.data;
try writer.writeAll("&");
- try print(.{
- .ty = field_ptr.container_ty,
- .val = field_ptr.container_ptr,
- }, writer, level - 1, mod);
+ if (level == 0) {
+ try writer.writeAll("(ptr)");
+ } else {
+ try print(.{
+ .ty = field_ptr.container_ty,
+ .val = field_ptr.container_ptr,
+ }, writer, level - 1, mod);
+ }
if (field_ptr.container_ty.zigTypeTag() == .Struct) {
const field_name = field_ptr.container_ty.structFields().keys()[field_ptr.field_index];
@@ -344,6 +386,9 @@ pub fn print(
return writer.writeAll(" }");
},
.slice => {
+ if (level == 0) {
+ return writer.writeAll(".{ ... }");
+ }
const payload = val.castTag(.slice).?.data;
try writer.writeAll(".{ ");
const elem_ty = ty.elemType2();
@@ -372,17 +417,25 @@ pub fn print(
.@"error" => return writer.print("error.{s}", .{val.castTag(.@"error").?.data.name}),
.eu_payload => {
val = val.castTag(.eu_payload).?.data;
+ ty = ty.errorUnionPayload();
},
.opt_payload => {
val = val.castTag(.opt_payload).?.data;
+ var buf: Type.Payload.ElemType = undefined;
+ ty = ty.optionalChild(&buf);
+ return print(.{ .ty = ty, .val = val }, writer, level, mod);
},
.eu_payload_ptr => {
try writer.writeAll("&");
val = val.castTag(.eu_payload_ptr).?.data.container_ptr;
+ ty = ty.elemType2().errorUnionPayload();
},
.opt_payload_ptr => {
try writer.writeAll("&");
- val = val.castTag(.opt_payload_ptr).?.data.container_ptr;
+ val = val.castTag(.opt_payload).?.data;
+ var buf: Type.Payload.ElemType = undefined;
+ ty = ty.elemType2().optionalChild(&buf);
+ return print(.{ .ty = ty, .val = val }, writer, level, mod);
},
// TODO these should not appear in this function
diff --git a/src/Zir.zig b/src/Zir.zig
index 1ca31755f7..b43b775dfa 100644
--- a/src/Zir.zig
+++ b/src/Zir.zig
@@ -3156,6 +3156,8 @@ pub const Inst = struct {
/// Create an anonymous name for this declaration.
/// Like this: "ParentDeclName_struct_69"
anon,
+ /// Use the name specified in the next `dbg_var_{val,ptr}` instruction.
+ dbg_var,
};
/// Trailing:
diff --git a/src/arch/aarch64/CodeGen.zig b/src/arch/aarch64/CodeGen.zig
index 7a7ee31117..e74fbd44ac 100644
--- a/src/arch/aarch64/CodeGen.zig
+++ b/src/arch/aarch64/CodeGen.zig
@@ -2277,7 +2277,7 @@ fn airOptionalPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
fn errUnionErr(self: *Self, error_union_mcv: MCValue, error_union_ty: Type) !MCValue {
const err_ty = error_union_ty.errorUnionSet();
const payload_ty = error_union_ty.errorUnionPayload();
- if (err_ty.errorSetCardinality() == .zero) {
+ if (err_ty.errorSetIsEmpty()) {
return MCValue{ .immediate = 0 };
}
if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
@@ -2311,7 +2311,7 @@ fn airUnwrapErrErr(self: *Self, inst: Air.Inst.Index) !void {
fn errUnionPayload(self: *Self, error_union_mcv: MCValue, error_union_ty: Type) !MCValue {
const err_ty = error_union_ty.errorUnionSet();
const payload_ty = error_union_ty.errorUnionPayload();
- if (err_ty.errorSetCardinality() == .zero) {
+ if (err_ty.errorSetIsEmpty()) {
return error_union_mcv;
}
if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
@@ -3590,7 +3590,7 @@ fn isErr(self: *Self, ty: Type, operand: MCValue) !MCValue {
const error_type = ty.errorUnionSet();
const payload_type = ty.errorUnionPayload();
- if (error_type.errorSetCardinality() == .zero) {
+ if (error_type.errorSetIsEmpty()) {
return MCValue{ .immediate = 0 }; // always false
}
@@ -4687,11 +4687,6 @@ fn genTypedValue(self: *Self, typed_value: TypedValue) InnerError!MCValue {
const error_type = typed_value.ty.errorUnionSet();
const payload_type = typed_value.ty.errorUnionPayload();
- if (error_type.errorSetCardinality() == .zero) {
- const payload_val = typed_value.val.castTag(.eu_payload).?.data;
- return self.genTypedValue(.{ .ty = payload_type, .val = payload_val });
- }
-
const is_pl = typed_value.val.errorUnionIsPayload();
if (!payload_type.hasRuntimeBitsIgnoreComptime()) {
diff --git a/src/arch/arm/CodeGen.zig b/src/arch/arm/CodeGen.zig
index 2bf57943c3..3cc853154b 100644
--- a/src/arch/arm/CodeGen.zig
+++ b/src/arch/arm/CodeGen.zig
@@ -1773,7 +1773,7 @@ fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
fn errUnionErr(self: *Self, error_union_mcv: MCValue, error_union_ty: Type) !MCValue {
const err_ty = error_union_ty.errorUnionSet();
const payload_ty = error_union_ty.errorUnionPayload();
- if (err_ty.errorSetCardinality() == .zero) {
+ if (err_ty.errorSetIsEmpty()) {
return MCValue{ .immediate = 0 };
}
if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
@@ -1810,7 +1810,7 @@ fn airUnwrapErrErr(self: *Self, inst: Air.Inst.Index) !void {
fn errUnionPayload(self: *Self, error_union_mcv: MCValue, error_union_ty: Type) !MCValue {
const err_ty = error_union_ty.errorUnionSet();
const payload_ty = error_union_ty.errorUnionPayload();
- if (err_ty.errorSetCardinality() == .zero) {
+ if (err_ty.errorSetIsEmpty()) {
return error_union_mcv;
}
if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
@@ -3922,7 +3922,7 @@ fn isErr(self: *Self, ty: Type, operand: MCValue) !MCValue {
const error_type = ty.errorUnionSet();
const error_int_type = Type.initTag(.u16);
- if (error_type.errorSetCardinality() == .zero) {
+ if (error_type.errorSetIsEmpty()) {
return MCValue{ .immediate = 0 }; // always false
}
@@ -5368,12 +5368,6 @@ fn genTypedValue(self: *Self, typed_value: TypedValue) InnerError!MCValue {
.ErrorUnion => {
const error_type = typed_value.ty.errorUnionSet();
const payload_type = typed_value.ty.errorUnionPayload();
-
- if (error_type.errorSetCardinality() == .zero) {
- const payload_val = typed_value.val.castTag(.eu_payload).?.data;
- return self.genTypedValue(.{ .ty = payload_type, .val = payload_val });
- }
-
const is_pl = typed_value.val.errorUnionIsPayload();
if (!payload_type.hasRuntimeBitsIgnoreComptime()) {
diff --git a/src/arch/wasm/CodeGen.zig b/src/arch/wasm/CodeGen.zig
index a0bb84a9d7..c395c26437 100644
--- a/src/arch/wasm/CodeGen.zig
+++ b/src/arch/wasm/CodeGen.zig
@@ -1377,11 +1377,7 @@ fn isByRef(ty: Type, target: std.Target) bool {
.Int => return ty.intInfo(target).bits > 64,
.Float => return ty.floatBits(target) > 64,
.ErrorUnion => {
- const err_ty = ty.errorUnionSet();
const pl_ty = ty.errorUnionPayload();
- if (err_ty.errorSetCardinality() == .zero) {
- return isByRef(pl_ty, target);
- }
if (!pl_ty.hasRuntimeBitsIgnoreComptime()) {
return false;
}
@@ -1817,11 +1813,7 @@ fn airStore(self: *Self, inst: Air.Inst.Index) InnerError!WValue {
fn store(self: *Self, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerError!void {
switch (ty.zigTypeTag()) {
.ErrorUnion => {
- const err_ty = ty.errorUnionSet();
const pl_ty = ty.errorUnionPayload();
- if (err_ty.errorSetCardinality() == .zero) {
- return self.store(lhs, rhs, pl_ty, 0);
- }
if (!pl_ty.hasRuntimeBitsIgnoreComptime()) {
return self.store(lhs, rhs, Type.anyerror, 0);
}
@@ -2357,10 +2349,6 @@ fn lowerConstant(self: *Self, val: Value, ty: Type) InnerError!WValue {
},
.ErrorUnion => {
const error_type = ty.errorUnionSet();
- if (error_type.errorSetCardinality() == .zero) {
- const pl_val = if (val.castTag(.eu_payload)) |pl| pl.data else Value.initTag(.undef);
- return self.lowerConstant(pl_val, ty.errorUnionPayload());
- }
const is_pl = val.errorUnionIsPayload();
const err_val = if (!is_pl) val else Value.initTag(.zero);
return self.lowerConstant(err_val, error_type);
@@ -2929,7 +2917,7 @@ fn airIsErr(self: *Self, inst: Air.Inst.Index, opcode: wasm.Opcode) InnerError!W
const err_union_ty = self.air.typeOf(un_op);
const pl_ty = err_union_ty.errorUnionPayload();
- if (err_union_ty.errorUnionSet().errorSetCardinality() == .zero) {
+ if (err_union_ty.errorUnionSet().errorSetIsEmpty()) {
switch (opcode) {
.i32_ne => return WValue{ .imm32 = 0 },
.i32_eq => return WValue{ .imm32 = 1 },
@@ -2962,10 +2950,6 @@ fn airUnwrapErrUnionPayload(self: *Self, inst: Air.Inst.Index, op_is_ptr: bool)
const err_ty = if (op_is_ptr) op_ty.childType() else op_ty;
const payload_ty = err_ty.errorUnionPayload();
- if (err_ty.errorUnionSet().errorSetCardinality() == .zero) {
- return operand;
- }
-
if (!payload_ty.hasRuntimeBitsIgnoreComptime()) return WValue{ .none = {} };
const pl_offset = @intCast(u32, errUnionPayloadOffset(payload_ty, self.target));
@@ -2984,7 +2968,7 @@ fn airUnwrapErrUnionError(self: *Self, inst: Air.Inst.Index, op_is_ptr: bool) In
const err_ty = if (op_is_ptr) op_ty.childType() else op_ty;
const payload_ty = err_ty.errorUnionPayload();
- if (err_ty.errorUnionSet().errorSetCardinality() == .zero) {
+ if (err_ty.errorUnionSet().errorSetIsEmpty()) {
return WValue{ .imm32 = 0 };
}
@@ -3002,10 +2986,6 @@ fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) InnerError!WValue {
const operand = try self.resolveInst(ty_op.operand);
const err_ty = self.air.typeOfIndex(inst);
- if (err_ty.errorUnionSet().errorSetCardinality() == .zero) {
- return operand;
- }
-
const pl_ty = self.air.typeOf(ty_op.operand);
if (!pl_ty.hasRuntimeBitsIgnoreComptime()) {
return operand;
@@ -4633,29 +4613,27 @@ fn lowerTry(
return self.fail("TODO: lowerTry for pointers", .{});
}
- if (err_union_ty.errorUnionSet().errorSetCardinality() == .zero) {
- return err_union;
- }
-
const pl_ty = err_union_ty.errorUnionPayload();
const pl_has_bits = pl_ty.hasRuntimeBitsIgnoreComptime();
- // Block we can jump out of when error is not set
- try self.startBlock(.block, wasm.block_empty);
-
- // check if the error tag is set for the error union.
- try self.emitWValue(err_union);
- if (pl_has_bits) {
- const err_offset = @intCast(u32, errUnionErrorOffset(pl_ty, self.target));
- try self.addMemArg(.i32_load16_u, .{
- .offset = err_union.offset() + err_offset,
- .alignment = Type.anyerror.abiAlignment(self.target),
- });
+ if (!err_union_ty.errorUnionSet().errorSetIsEmpty()) {
+ // Block we can jump out of when error is not set
+ try self.startBlock(.block, wasm.block_empty);
+
+ // check if the error tag is set for the error union.
+ try self.emitWValue(err_union);
+ if (pl_has_bits) {
+ const err_offset = @intCast(u32, errUnionErrorOffset(pl_ty, self.target));
+ try self.addMemArg(.i32_load16_u, .{
+ .offset = err_union.offset() + err_offset,
+ .alignment = Type.anyerror.abiAlignment(self.target),
+ });
+ }
+ try self.addTag(.i32_eqz);
+ try self.addLabel(.br_if, 0); // jump out of block when error is '0'
+ try self.genBody(body);
+ try self.endBlock();
}
- try self.addTag(.i32_eqz);
- try self.addLabel(.br_if, 0); // jump out of block when error is '0'
- try self.genBody(body);
- try self.endBlock();
// if we reach here it means error was not set, and we want the payload
if (!pl_has_bits) {
diff --git a/src/arch/x86_64/CodeGen.zig b/src/arch/x86_64/CodeGen.zig
index 5bda84c98c..c94eaa37af 100644
--- a/src/arch/x86_64/CodeGen.zig
+++ b/src/arch/x86_64/CodeGen.zig
@@ -1806,7 +1806,7 @@ fn airUnwrapErrErr(self: *Self, inst: Air.Inst.Index) !void {
const operand = try self.resolveInst(ty_op.operand);
const result: MCValue = result: {
- if (err_ty.errorSetCardinality() == .zero) {
+ if (err_ty.errorSetIsEmpty()) {
break :result MCValue{ .immediate = 0 };
}
@@ -1857,14 +1857,8 @@ fn genUnwrapErrorUnionPayloadMir(
err_union: MCValue,
) !MCValue {
const payload_ty = err_union_ty.errorUnionPayload();
- const err_ty = err_union_ty.errorUnionSet();
const result: MCValue = result: {
- if (err_ty.errorSetCardinality() == .zero) {
- // TODO check if we can reuse
- break :result err_union;
- }
-
if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
break :result MCValue.none;
}
@@ -1991,15 +1985,10 @@ fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
}
const error_union_ty = self.air.getRefType(ty_op.ty);
- const error_ty = error_union_ty.errorUnionSet();
const payload_ty = error_union_ty.errorUnionPayload();
const operand = try self.resolveInst(ty_op.operand);
const result: MCValue = result: {
- if (error_ty.errorSetCardinality() == .zero) {
- break :result operand;
- }
-
if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
break :result operand;
}
@@ -4651,7 +4640,7 @@ fn isNonNull(self: *Self, inst: Air.Inst.Index, ty: Type, operand: MCValue) !MCV
fn isErr(self: *Self, maybe_inst: ?Air.Inst.Index, ty: Type, operand: MCValue) !MCValue {
const err_type = ty.errorUnionSet();
- if (err_type.errorSetCardinality() == .zero) {
+ if (err_type.errorSetIsEmpty()) {
return MCValue{ .immediate = 0 }; // always false
}
@@ -6909,12 +6898,6 @@ fn genTypedValue(self: *Self, typed_value: TypedValue) InnerError!MCValue {
.ErrorUnion => {
const error_type = typed_value.ty.errorUnionSet();
const payload_type = typed_value.ty.errorUnionPayload();
-
- if (error_type.errorSetCardinality() == .zero) {
- const payload_val = typed_value.val.castTag(.eu_payload).?.data;
- return self.genTypedValue(.{ .ty = payload_type, .val = payload_val });
- }
-
const is_pl = typed_value.val.errorUnionIsPayload();
if (!payload_type.hasRuntimeBitsIgnoreComptime()) {
diff --git a/src/codegen.zig b/src/codegen.zig
index 84615d86d8..025decdb4b 100644
--- a/src/codegen.zig
+++ b/src/codegen.zig
@@ -705,15 +705,6 @@ pub fn generateSymbol(
.ErrorUnion => {
const error_ty = typed_value.ty.errorUnionSet();
const payload_ty = typed_value.ty.errorUnionPayload();
-
- if (error_ty.errorSetCardinality() == .zero) {
- const payload_val = typed_value.val.castTag(.eu_payload).?.data;
- return generateSymbol(bin_file, src_loc, .{
- .ty = payload_ty,
- .val = payload_val,
- }, code, debug_output, reloc_info);
- }
-
const is_payload = typed_value.val.errorUnionIsPayload();
if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
diff --git a/src/codegen/c.zig b/src/codegen/c.zig
index 45191f3107..949e2a67f2 100644
--- a/src/codegen/c.zig
+++ b/src/codegen/c.zig
@@ -752,12 +752,6 @@ pub const DeclGen = struct {
const error_type = ty.errorUnionSet();
const payload_type = ty.errorUnionPayload();
- if (error_type.errorSetCardinality() == .zero) {
- // We use the payload directly as the type.
- const payload_val = val.castTag(.eu_payload).?.data;
- return dg.renderValue(writer, payload_type, payload_val, location);
- }
-
if (!payload_type.hasRuntimeBits()) {
// We use the error type directly as the type.
const err_val = if (val.errorUnionIsPayload()) Value.initTag(.zero) else val;
@@ -1381,13 +1375,8 @@ pub const DeclGen = struct {
return w.writeAll("uint16_t");
},
.ErrorUnion => {
- const error_ty = t.errorUnionSet();
const payload_ty = t.errorUnionPayload();
- if (error_ty.errorSetCardinality() == .zero) {
- return dg.renderType(w, payload_ty);
- }
-
if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
return dg.renderType(w, Type.anyerror);
}
@@ -2892,41 +2881,36 @@ fn lowerTry(
operand_is_ptr: bool,
result_ty: Type,
) !CValue {
- if (err_union_ty.errorUnionSet().errorSetCardinality() == .zero) {
- // If the error set has no fields, then the payload and the error
- // union are the same value.
- return err_union;
- }
-
+ const writer = f.object.writer();
const payload_ty = err_union_ty.errorUnionPayload();
const payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime();
- const writer = f.object.writer();
-
- err: {
- if (!payload_has_bits) {
- if (operand_is_ptr) {
- try writer.writeAll("if(*");
- } else {
+ if (!err_union_ty.errorUnionSet().errorSetIsEmpty()) {
+ err: {
+ if (!payload_has_bits) {
+ if (operand_is_ptr) {
+ try writer.writeAll("if(*");
+ } else {
+ try writer.writeAll("if(");
+ }
+ try f.writeCValue(writer, err_union);
+ try writer.writeAll(")");
+ break :err;
+ }
+ if (operand_is_ptr or isByRef(err_union_ty)) {
try writer.writeAll("if(");
+ try f.writeCValue(writer, err_union);
+ try writer.writeAll("->error)");
+ break :err;
}
- try f.writeCValue(writer, err_union);
- try writer.writeAll(")");
- break :err;
- }
- if (operand_is_ptr or isByRef(err_union_ty)) {
try writer.writeAll("if(");
try f.writeCValue(writer, err_union);
- try writer.writeAll("->error)");
- break :err;
+ try writer.writeAll(".error)");
}
- try writer.writeAll("if(");
- try f.writeCValue(writer, err_union);
- try writer.writeAll(".error)");
- }
- try genBody(f, body);
- try f.object.indent_writer.insertNewline();
+ try genBody(f, body);
+ try f.object.indent_writer.insertNewline();
+ }
if (!payload_has_bits) {
if (!operand_is_ptr) {
@@ -3466,7 +3450,7 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
if (operand_ty.zigTypeTag() == .Pointer) {
const err_union_ty = operand_ty.childType();
- if (err_union_ty.errorUnionSet().errorSetCardinality() == .zero) {
+ if (err_union_ty.errorUnionSet().errorSetIsEmpty()) {
return CValue{ .bytes = "0" };
}
if (!err_union_ty.errorUnionPayload().hasRuntimeBits()) {
@@ -3478,7 +3462,7 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
try writer.writeAll(";\n");
return local;
}
- if (operand_ty.errorUnionSet().errorSetCardinality() == .zero) {
+ if (operand_ty.errorUnionSet().errorSetIsEmpty()) {
return CValue{ .bytes = "0" };
}
if (!operand_ty.errorUnionPayload().hasRuntimeBits()) {
@@ -3507,10 +3491,6 @@ fn airUnwrapErrUnionPay(f: *Function, inst: Air.Inst.Index, maybe_addrof: [*:0]c
const operand_is_ptr = operand_ty.zigTypeTag() == .Pointer;
const error_union_ty = if (operand_is_ptr) operand_ty.childType() else operand_ty;
- if (error_union_ty.errorUnionSet().errorSetCardinality() == .zero) {
- return operand;
- }
-
if (!error_union_ty.errorUnionPayload().hasRuntimeBits()) {
return CValue.none;
}
@@ -3575,11 +3555,6 @@ fn airErrUnionPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
const error_ty = error_union_ty.errorUnionSet();
const payload_ty = error_union_ty.errorUnionPayload();
- if (error_ty.errorSetCardinality() == .zero) {
- // TODO: write undefined bytes through the pointer here
- return operand;
- }
-
// First, set the non-error value.
if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
try f.writeCValueDeref(writer, operand);
@@ -3623,9 +3598,6 @@ fn airWrapErrUnionPay(f: *Function, inst: Air.Inst.Index) !CValue {
const operand = try f.resolveInst(ty_op.operand);
const inst_ty = f.air.typeOfIndex(inst);
- if (inst_ty.errorUnionSet().errorSetCardinality() == .zero) {
- return operand;
- }
const local = try f.allocLocal(inst_ty, .Const);
try writer.writeAll(" = { .error = 0, .payload = ");
try f.writeCValue(writer, operand);
@@ -3652,7 +3624,7 @@ fn airIsErr(
try writer.writeAll(" = ");
- if (error_ty.errorSetCardinality() == .zero) {
+ if (error_ty.errorSetIsEmpty()) {
try writer.print("0 {s} 0;\n", .{op_str});
} else {
if (is_ptr) {
diff --git a/src/codegen/llvm.zig b/src/codegen/llvm.zig
index 19a6917be4..efe6a754b6 100644
--- a/src/codegen/llvm.zig
+++ b/src/codegen/llvm.zig
@@ -599,6 +599,13 @@ pub const Object = struct {
self.llvm_module.dump();
}
+ var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
+ defer arena_allocator.deinit();
+ const arena = arena_allocator.allocator();
+
+ const mod = comp.bin_file.options.module.?;
+ const cache_dir = mod.zig_cache_artifact_directory;
+
if (std.debug.runtime_safety) {
var error_message: [*:0]const u8 = undefined;
// verifyModule always allocs the error_message even if there is no error
@@ -606,17 +613,15 @@ pub const Object = struct {
if (self.llvm_module.verify(.ReturnStatus, &error_message).toBool()) {
std.debug.print("\n{s}\n", .{error_message});
+
+ if (try locPath(arena, comp.emit_llvm_ir, cache_dir)) |emit_llvm_ir_path| {
+ _ = self.llvm_module.printModuleToFile(emit_llvm_ir_path, &error_message);
+ }
+
@panic("LLVM module verification failed");
}
}
- var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa);
- defer arena_allocator.deinit();
- const arena = arena_allocator.allocator();
-
- const mod = comp.bin_file.options.module.?;
- const cache_dir = mod.zig_cache_artifact_directory;
-
var emit_bin_path: ?[*:0]const u8 = if (comp.bin_file.options.emit) |emit|
try emit.basenamePath(arena, try arena.dupeZ(u8, comp.bin_file.intermediary_basename.?))
else
@@ -1566,22 +1571,6 @@ pub const Object = struct {
},
.ErrorUnion => {
const payload_ty = ty.errorUnionPayload();
- switch (ty.errorUnionSet().errorSetCardinality()) {
- .zero => {
- const payload_di_ty = try o.lowerDebugType(payload_ty, .full);
- // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
- try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(payload_di_ty), .{ .mod = o.module });
- return payload_di_ty;
- },
- .one => {
- if (payload_ty.isNoReturn()) {
- const di_type = dib.createBasicType("void", 0, DW.ATE.signed);
- gop.value_ptr.* = AnnotatedDITypePtr.initFull(di_type);
- return di_type;
- }
- },
- .many => {},
- }
if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
const err_set_di_ty = try o.lowerDebugType(Type.anyerror, .full);
// The recursive call to `lowerDebugType` means we can't use `gop` anymore.
@@ -2549,15 +2538,6 @@ pub const DeclGen = struct {
},
.ErrorUnion => {
const payload_ty = t.errorUnionPayload();
- switch (t.errorUnionSet().errorSetCardinality()) {
- .zero => return dg.lowerType(payload_ty),
- .one => {
- if (payload_ty.isNoReturn()) {
- return dg.context.voidType();
- }
- },
- .many => {},
- }
if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
return try dg.lowerType(Type.anyerror);
}
@@ -3217,10 +3197,6 @@ pub const DeclGen = struct {
},
.ErrorUnion => {
const payload_type = tv.ty.errorUnionPayload();
- if (tv.ty.errorUnionSet().errorSetCardinality() == .zero) {
- const payload_val = tv.val.castTag(.eu_payload).?.data;
- return dg.lowerValue(.{ .ty = payload_type, .val = payload_val });
- }
const is_pl = tv.val.errorUnionIsPayload();
if (!payload_type.hasRuntimeBitsIgnoreComptime()) {
@@ -4790,40 +4766,37 @@ pub const FuncGen = struct {
}
fn lowerTry(fg: *FuncGen, err_union: *const llvm.Value, body: []const Air.Inst.Index, err_union_ty: Type, operand_is_ptr: bool, result_ty: Type) !?*const llvm.Value {
- if (err_union_ty.errorUnionSet().errorSetCardinality() == .zero) {
- // If the error set has no fields, then the payload and the error
- // union are the same value.
- return err_union;
- }
-
const payload_ty = err_union_ty.errorUnionPayload();
const payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime();
const target = fg.dg.module.getTarget();
- const is_err = err: {
- const err_set_ty = try fg.dg.lowerType(Type.anyerror);
- const zero = err_set_ty.constNull();
- if (!payload_has_bits) {
- const loaded = if (operand_is_ptr) fg.builder.buildLoad(err_union, "") else err_union;
- break :err fg.builder.buildICmp(.NE, loaded, zero, "");
- }
- const err_field_index = errUnionErrorOffset(payload_ty, target);
- if (operand_is_ptr or isByRef(err_union_ty)) {
- const err_field_ptr = fg.builder.buildStructGEP(err_union, err_field_index, "");
- const loaded = fg.builder.buildLoad(err_field_ptr, "");
+
+ if (!err_union_ty.errorUnionSet().errorSetIsEmpty()) {
+ const is_err = err: {
+ const err_set_ty = try fg.dg.lowerType(Type.anyerror);
+ const zero = err_set_ty.constNull();
+ if (!payload_has_bits) {
+ const loaded = if (operand_is_ptr) fg.builder.buildLoad(err_union, "") else err_union;
+ break :err fg.builder.buildICmp(.NE, loaded, zero, "");
+ }
+ const err_field_index = errUnionErrorOffset(payload_ty, target);
+ if (operand_is_ptr or isByRef(err_union_ty)) {
+ const err_field_ptr = fg.builder.buildStructGEP(err_union, err_field_index, "");
+ const loaded = fg.builder.buildLoad(err_field_ptr, "");
+ break :err fg.builder.buildICmp(.NE, loaded, zero, "");
+ }
+ const loaded = fg.builder.buildExtractValue(err_union, err_field_index, "");
break :err fg.builder.buildICmp(.NE, loaded, zero, "");
- }
- const loaded = fg.builder.buildExtractValue(err_union, err_field_index, "");
- break :err fg.builder.buildICmp(.NE, loaded, zero, "");
- };
+ };
- const return_block = fg.context.appendBasicBlock(fg.llvm_func, "TryRet");
- const continue_block = fg.context.appendBasicBlock(fg.llvm_func, "TryCont");
- _ = fg.builder.buildCondBr(is_err, return_block, continue_block);
+ const return_block = fg.context.appendBasicBlock(fg.llvm_func, "TryRet");
+ const continue_block = fg.context.appendBasicBlock(fg.llvm_func, "TryCont");
+ _ = fg.builder.buildCondBr(is_err, return_block, continue_block);
- fg.builder.positionBuilderAtEnd(return_block);
- try fg.genBody(body);
+ fg.builder.positionBuilderAtEnd(return_block);
+ try fg.genBody(body);
- fg.builder.positionBuilderAtEnd(continue_block);
+ fg.builder.positionBuilderAtEnd(continue_block);
+ }
if (!payload_has_bits) {
if (!operand_is_ptr) return null;
@@ -5660,7 +5633,7 @@ pub const FuncGen = struct {
const err_set_ty = try self.dg.lowerType(Type.initTag(.anyerror));
const zero = err_set_ty.constNull();
- if (err_union_ty.errorUnionSet().errorSetCardinality() == .zero) {
+ if (err_union_ty.errorUnionSet().errorSetIsEmpty()) {
const llvm_i1 = self.context.intType(1);
switch (op) {
.EQ => return llvm_i1.constInt(1, .False), // 0 == 0
@@ -5783,13 +5756,6 @@ pub const FuncGen = struct {
const ty_op = self.air.instructions.items(.data)[inst].ty_op;
const operand = try self.resolveInst(ty_op.operand);
- const operand_ty = self.air.typeOf(ty_op.operand);
- const error_union_ty = if (operand_is_ptr) operand_ty.childType() else operand_ty;
- if (error_union_ty.errorUnionSet().errorSetCardinality() == .zero) {
- // If the error set has no fields, then the payload and the error
- // union are the same value.
- return operand;
- }
const result_ty = self.air.typeOfIndex(inst);
const payload_ty = if (operand_is_ptr) result_ty.childType() else result_ty;
const target = self.dg.module.getTarget();
@@ -5820,7 +5786,7 @@ pub const FuncGen = struct {
const operand = try self.resolveInst(ty_op.operand);
const operand_ty = self.air.typeOf(ty_op.operand);
const err_union_ty = if (operand_is_ptr) operand_ty.childType() else operand_ty;
- if (err_union_ty.errorUnionSet().errorSetCardinality() == .zero) {
+ if (err_union_ty.errorUnionSet().errorSetIsEmpty()) {
const err_llvm_ty = try self.dg.lowerType(Type.anyerror);
if (operand_is_ptr) {
return self.builder.buildBitCast(operand, err_llvm_ty.pointerType(0), "");
@@ -5851,10 +5817,6 @@ pub const FuncGen = struct {
const operand = try self.resolveInst(ty_op.operand);
const error_union_ty = self.air.typeOf(ty_op.operand).childType();
- if (error_union_ty.errorUnionSet().errorSetCardinality() == .zero) {
- // TODO: write undefined bytes through the pointer here
- return operand;
- }
const payload_ty = error_union_ty.errorUnionPayload();
const non_error_val = try self.dg.lowerValue(.{ .ty = Type.anyerror, .val = Value.zero });
if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
@@ -5933,9 +5895,6 @@ pub const FuncGen = struct {
const ty_op = self.air.instructions.items(.data)[inst].ty_op;
const inst_ty = self.air.typeOfIndex(inst);
const operand = try self.resolveInst(ty_op.operand);
- if (inst_ty.errorUnionSet().errorSetCardinality() == .zero) {
- return operand;
- }
const payload_ty = self.air.typeOf(ty_op.operand);
if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
return operand;
diff --git a/src/codegen/llvm/bindings.zig b/src/codegen/llvm/bindings.zig
index ca748d3ce3..671014ba3b 100644
--- a/src/codegen/llvm/bindings.zig
+++ b/src/codegen/llvm/bindings.zig
@@ -390,6 +390,9 @@ pub const Module = opaque {
pub const setModuleInlineAsm2 = LLVMSetModuleInlineAsm2;
extern fn LLVMSetModuleInlineAsm2(M: *const Module, Asm: [*]const u8, Len: usize) void;
+
+ pub const printModuleToFile = LLVMPrintModuleToFile;
+ extern fn LLVMPrintModuleToFile(M: *const Module, Filename: [*:0]const u8, ErrorMessage: *[*:0]const u8) Bool;
};
pub const lookupIntrinsicID = LLVMLookupIntrinsicID;
diff --git a/src/print_air.zig b/src/print_air.zig
index af1bcb8cfb..d6db7ca75f 100644
--- a/src/print_air.zig
+++ b/src/print_air.zig
@@ -4,6 +4,7 @@ const fmtIntSizeBin = std.fmt.fmtIntSizeBin;
const Module = @import("Module.zig");
const Value = @import("value.zig").Value;
+const Type = @import("type.zig").Type;
const Air = @import("Air.zig");
const Liveness = @import("Liveness.zig");
@@ -304,14 +305,27 @@ const Writer = struct {
// no-op, no argument to write
}
+ fn writeType(w: *Writer, s: anytype, ty: Type) !void {
+ const t = ty.tag();
+ switch (t) {
+ .inferred_alloc_const => try s.writeAll("(inferred_alloc_const)"),
+ .inferred_alloc_mut => try s.writeAll("(inferred_alloc_mut)"),
+ .generic_poison => try s.writeAll("(generic_poison)"),
+ .var_args_param => try s.writeAll("(var_args_param)"),
+ .bound_fn => try s.writeAll("(bound_fn)"),
+ else => try ty.print(s, w.module),
+ }
+ }
+
fn writeTy(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
const ty = w.air.instructions.items(.data)[inst].ty;
- try s.print("{}", .{ty.fmtDebug()});
+ try w.writeType(s, ty);
}
fn writeTyOp(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
const ty_op = w.air.instructions.items(.data)[inst].ty_op;
- try s.print("{}, ", .{w.air.getRefType(ty_op.ty).fmtDebug()});
+ try w.writeType(s, w.air.getRefType(ty_op.ty));
+ try s.writeAll(", ");
try w.writeOperand(s, inst, 0, ty_op.operand);
}
@@ -320,7 +334,8 @@ const Writer = struct {
const extra = w.air.extraData(Air.Block, ty_pl.payload);
const body = w.air.extra[extra.end..][0..extra.data.body_len];
- try s.print("{}, {{\n", .{w.air.getRefType(ty_pl.ty).fmtDebug()});
+ try w.writeType(s, w.air.getRefType(ty_pl.ty));
+ try s.writeAll(", {\n");
const old_indent = w.indent;
w.indent += 2;
try w.writeBody(s, body);
@@ -335,7 +350,8 @@ const Writer = struct {
const len = @intCast(usize, vector_ty.arrayLen());
const elements = @ptrCast([]const Air.Inst.Ref, w.air.extra[ty_pl.payload..][0..len]);
- try s.print("{}, [", .{vector_ty.fmtDebug()});
+ try w.writeType(s, vector_ty);
+ try s.writeAll(", [");
for (elements) |elem, i| {
if (i != 0) try s.writeAll(", ");
try w.writeOperand(s, inst, i, elem);
@@ -408,7 +424,8 @@ const Writer = struct {
const extra = w.air.extraData(Air.Bin, pl_op.payload).data;
const elem_ty = w.air.typeOfIndex(inst).childType();
- try s.print("{}, ", .{elem_ty.fmtDebug()});
+ try w.writeType(s, elem_ty);
+ try s.writeAll(", ");
try w.writeOperand(s, inst, 0, pl_op.operand);
try s.writeAll(", ");
try w.writeOperand(s, inst, 1, extra.lhs);
@@ -511,7 +528,9 @@ const Writer = struct {
fn writeConstant(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
const ty_pl = w.air.instructions.items(.data)[inst].ty_pl;
const val = w.air.values[ty_pl.payload];
- try s.print("{}, {}", .{ w.air.getRefType(ty_pl.ty).fmtDebug(), val.fmtDebug() });
+ const ty = w.air.getRefType(ty_pl.ty);
+ try w.writeType(s, ty);
+ try s.print(", {}", .{val.fmtValue(ty, w.module)});
}
fn writeAssembly(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
@@ -523,7 +542,7 @@ const Writer = struct {
var op_index: usize = 0;
const ret_ty = w.air.typeOfIndex(inst);
- try s.print("{}", .{ret_ty.fmtDebug()});
+ try w.writeType(s, ret_ty);
if (is_volatile) {
try s.writeAll(", volatile");
@@ -647,7 +666,10 @@ const Writer = struct {
const body = w.air.extra[extra.end..][0..extra.data.body_len];
try w.writeOperand(s, inst, 0, extra.data.ptr);
- try s.print(", {}, {{\n", .{w.air.getRefType(ty_pl.ty).fmtDebug()});
+
+ try s.writeAll(", ");
+ try w.writeType(s, w.air.getRefType(ty_pl.ty));
+ try s.writeAll(", {\n");
const old_indent = w.indent;
w.indent += 2;
try w.writeBody(s, body);
diff --git a/src/type.zig b/src/type.zig
index 8556526e18..0ca7ba83c5 100644
--- a/src/type.zig
+++ b/src/type.zig
@@ -2366,6 +2366,10 @@ pub const Type = extern union {
.anyopaque,
.@"opaque",
.type_info,
+ .error_set_single,
+ .error_union,
+ .error_set,
+ .error_set_merged,
=> return true,
// These are false because they are comptime-only types.
@@ -2389,20 +2393,8 @@ pub const Type = extern union {
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
- .error_set_single,
=> return false,
- .error_set => {
- const err_set_obj = ty.castTag(.error_set).?.data;
- const names = err_set_obj.names.keys();
- return names.len > 1;
- },
- .error_set_merged => {
- const name_map = ty.castTag(.error_set_merged).?.data;
- const names = name_map.keys();
- return names.len > 1;
- },
-
// These types have more than one possible value, so the result is the same as
// asking whether they are comptime-only types.
.anyframe_T,
@@ -2443,25 +2435,6 @@ pub const Type = extern union {
}
},
- .error_union => {
- // This code needs to be kept in sync with the equivalent switch prong
- // in abiSizeAdvanced.
- const data = ty.castTag(.error_union).?.data;
- switch (data.error_set.errorSetCardinality()) {
- .zero => return hasRuntimeBitsAdvanced(data.payload, ignore_comptime_only, sema_kit),
- .one => return !data.payload.isNoReturn(),
- .many => {
- if (ignore_comptime_only) {
- return true;
- } else if (sema_kit) |sk| {
- return !(try sk.sema.typeRequiresComptime(sk.block, sk.src, ty));
- } else {
- return !comptimeOnly(ty);
- }
- },
- }
- },
-
.@"struct" => {
const struct_obj = ty.castTag(.@"struct").?.data;
if (struct_obj.status == .field_types_wip) {
@@ -2926,27 +2899,11 @@ pub const Type = extern union {
.anyerror_void_error_union,
.anyerror,
.error_set_inferred,
+ .error_set_single,
+ .error_set,
+ .error_set_merged,
=> return AbiAlignmentAdvanced{ .scalar = 2 },
- .error_set => {
- const err_set_obj = ty.castTag(.error_set).?.data;
- const names = err_set_obj.names.keys();
- if (names.len <= 1) {
- return AbiAlignmentAdvanced{ .scalar = 0 };
- } else {
- return AbiAlignmentAdvanced{ .scalar = 2 };
- }
- },
- .error_set_merged => {
- const name_map = ty.castTag(.error_set_merged).?.data;
- const names = name_map.keys();
- if (names.len <= 1) {
- return AbiAlignmentAdvanced{ .scalar = 0 };
- } else {
- return AbiAlignmentAdvanced{ .scalar = 2 };
- }
- },
-
.array, .array_sentinel => return ty.elemType().abiAlignmentAdvanced(target, strat),
// TODO audit this - is there any more complicated logic to determine
@@ -2971,12 +2928,7 @@ pub const Type = extern union {
switch (child_type.zigTypeTag()) {
.Pointer => return AbiAlignmentAdvanced{ .scalar = @divExact(target.cpu.arch.ptrBitWidth(), 8) },
- .ErrorSet => switch (child_type.errorSetCardinality()) {
- // `?error{}` is comptime-known to be null.
- .zero => return AbiAlignmentAdvanced{ .scalar = 0 },
- .one => return AbiAlignmentAdvanced{ .scalar = 1 },
- .many => return abiAlignmentAdvanced(Type.anyerror, target, strat),
- },
+ .ErrorSet => return abiAlignmentAdvanced(Type.anyerror, target, strat),
.NoReturn => return AbiAlignmentAdvanced{ .scalar = 0 },
else => {},
}
@@ -2999,15 +2951,6 @@ pub const Type = extern union {
// This code needs to be kept in sync with the equivalent switch prong
// in abiSizeAdvanced.
const data = ty.castTag(.error_union).?.data;
- switch (data.error_set.errorSetCardinality()) {
- .zero => return abiAlignmentAdvanced(data.payload, target, strat),
- .one => {
- if (data.payload.isNoReturn()) {
- return AbiAlignmentAdvanced{ .scalar = 0 };
- }
- },
- .many => {},
- }
const code_align = abiAlignment(Type.anyerror, target);
switch (strat) {
.eager, .sema_kit => {
@@ -3118,7 +3061,6 @@ pub const Type = extern union {
.@"undefined",
.enum_literal,
.type_info,
- .error_set_single,
=> return AbiAlignmentAdvanced{ .scalar = 0 },
.noreturn,
@@ -3237,7 +3179,6 @@ pub const Type = extern union {
.empty_struct_literal,
.empty_struct,
.void,
- .error_set_single,
=> return AbiSizeAdvanced{ .scalar = 0 },
.@"struct", .tuple, .anon_struct => switch (ty.containerLayout()) {
@@ -3396,27 +3337,11 @@ pub const Type = extern union {
.anyerror_void_error_union,
.anyerror,
.error_set_inferred,
+ .error_set,
+ .error_set_merged,
+ .error_set_single,
=> return AbiSizeAdvanced{ .scalar = 2 },
- .error_set => {
- const err_set_obj = ty.castTag(.error_set).?.data;
- const names = err_set_obj.names.keys();
- if (names.len <= 1) {
- return AbiSizeAdvanced{ .scalar = 0 };
- } else {
- return AbiSizeAdvanced{ .scalar = 2 };
- }
- },
- .error_set_merged => {
- const name_map = ty.castTag(.error_set_merged).?.data;
- const names = name_map.keys();
- if (names.len <= 1) {
- return AbiSizeAdvanced{ .scalar = 0 };
- } else {
- return AbiSizeAdvanced{ .scalar = 2 };
- }
- },
-
.i16, .u16 => return AbiSizeAdvanced{ .scalar = intAbiSize(16, target) },
.u29 => return AbiSizeAdvanced{ .scalar = intAbiSize(29, target) },
.i32, .u32 => return AbiSizeAdvanced{ .scalar = intAbiSize(32, target) },
@@ -3467,24 +3392,6 @@ pub const Type = extern union {
// This code needs to be kept in sync with the equivalent switch prong
// in abiAlignmentAdvanced.
const data = ty.castTag(.error_union).?.data;
- // Here we need to care whether or not the error set is *empty* or whether
- // it only has *one possible value*. In the former case, it means there
- // cannot possibly be an error, meaning the ABI size is equivalent to the
- // payload ABI size. In the latter case, we need to account for the "tag"
- // because even if both the payload type and the error set type of an
- // error union have no runtime bits, an error union still has
- // 1 bit of data which is whether or not the value is an error.
- // Zig still uses the error code encoding at runtime, even when only 1 bit
- // would suffice. This prevents coercions from needing to branch.
- switch (data.error_set.errorSetCardinality()) {
- .zero => return abiSizeAdvanced(data.payload, target, strat),
- .one => {
- if (data.payload.isNoReturn()) {
- return AbiSizeAdvanced{ .scalar = 0 };
- }
- },
- .many => {},
- }
const code_size = abiSize(Type.anyerror, target);
if (!data.payload.hasRuntimeBits()) {
// Same as anyerror.
@@ -3727,11 +3634,7 @@ pub const Type = extern union {
.error_union => {
const payload = ty.castTag(.error_union).?.data;
- if (!payload.error_set.hasRuntimeBits() and !payload.payload.hasRuntimeBits()) {
- return 0;
- } else if (!payload.error_set.hasRuntimeBits()) {
- return payload.payload.bitSizeAdvanced(target, sema_kit);
- } else if (!payload.payload.hasRuntimeBits()) {
+ if (!payload.payload.hasRuntimeBits()) {
return payload.error_set.bitSizeAdvanced(target, sema_kit);
}
@panic("TODO bitSize error union");
@@ -4351,30 +4254,25 @@ pub const Type = extern union {
};
}
- const ErrorSetCardinality = enum { zero, one, many };
-
- pub fn errorSetCardinality(ty: Type) ErrorSetCardinality {
+ /// Returns false for unresolved inferred error sets.
+ pub fn errorSetIsEmpty(ty: Type) bool {
switch (ty.tag()) {
- .anyerror => return .many,
- .error_set_inferred => return .many,
- .error_set_single => return .one,
+ .anyerror => return false,
+ .error_set_inferred => {
+ const inferred_error_set = ty.castTag(.error_set_inferred).?.data;
+ // Can't know for sure.
+ if (!inferred_error_set.is_resolved) return false;
+ if (inferred_error_set.is_anyerror) return false;
+ return inferred_error_set.errors.count() == 0;
+ },
+ .error_set_single => return false,
.error_set => {
const err_set_obj = ty.castTag(.error_set).?.data;
- const names = err_set_obj.names.keys();
- switch (names.len) {
- 0 => return .zero,
- 1 => return .one,
- else => return .many,
- }
+ return err_set_obj.names.count() == 0;
},
.error_set_merged => {
const name_map = ty.castTag(.error_set_merged).?.data;
- const names = name_map.keys();
- switch (names.len) {
- 0 => return .zero,
- 1 => return .one,
- else => return .many,
- }
+ return name_map.count() == 0;
},
else => unreachable,
}
@@ -4883,6 +4781,10 @@ pub const Type = extern union {
.bool,
.type,
.anyerror,
+ .error_union,
+ .error_set_single,
+ .error_set,
+ .error_set_merged,
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
@@ -4939,42 +4841,6 @@ pub const Type = extern union {
}
},
- .error_union => {
- const error_ty = ty.errorUnionSet();
- switch (error_ty.errorSetCardinality()) {
- .zero => {
- const payload_ty = ty.errorUnionPayload();
- if (onePossibleValue(payload_ty)) |payload_val| {
- _ = payload_val;
- return Value.initTag(.the_only_possible_value);
- } else {
- return null;
- }
- },
- .one => {
- if (ty.errorUnionPayload().isNoReturn()) {
- const error_val = onePossibleValue(error_ty).?;
- return error_val;
- } else {
- return null;
- }
- },
- .many => return null,
- }
- },
-
- .error_set_single => return Value.initTag(.the_only_possible_value),
- .error_set => {
- const err_set_obj = ty.castTag(.error_set).?.data;
- if (err_set_obj.names.count() > 1) return null;
- return Value.initTag(.the_only_possible_value);
- },
- .error_set_merged => {
- const name_map = ty.castTag(.error_set_merged).?.data;
- if (name_map.count() > 1) return null;
- return Value.initTag(.the_only_possible_value);
- },
-
.@"struct" => {
const s = ty.castTag(.@"struct").?.data;
assert(s.haveFieldTypes());
diff --git a/src/value.zig b/src/value.zig
index e1500fe4ab..996aa76bf5 100644
--- a/src/value.zig
+++ b/src/value.zig
@@ -1062,6 +1062,7 @@ pub const Value = extern union {
sema_kit: ?Module.WipAnalysis,
) Module.CompileError!BigIntConst {
switch (val.tag()) {
+ .null_value,
.zero,
.bool_false,
.the_only_possible_value, // i0, u0