authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-05-23 18:48:10-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-05-24 15:34:52-07:00
log02e9d9b43b3b1cd9a4858a1f2bff302057dc2ee2
tree211ff30043bc817e462a6845e2bf0437a7a179af
parentc97c7f9e3bade44136f2bdf8ec4015f1b1b8303f

stage2: make `?anyerror` represented the same as `anyerror`

I was able to get the backend implementation working on LLVM and the C backend, but I'm going to ask for some help on the other backends.

6 files changed, 98 insertions(+), 35 deletions(-)

src/arch/wasm/CodeGen.zig+13-10
......@@ -1386,7 +1386,7 @@ fn isByRef(ty: Type, target: std.Target) bool {
13861386 return true;
13871387 },
13881388 .Optional => {
1389 if (ty.isPtrLikeOptional()) return false;
1389 if (ty.optionalReprIsPayload()) return false;
13901390 var buf: Type.Payload.ElemType = undefined;
13911391 return ty.optionalChild(&buf).hasRuntimeBitsIgnoreComptime();
13921392 },
......@@ -1832,6 +1832,9 @@ fn store(self: *Self, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerErro
18321832 if (!pl_ty.hasRuntimeBitsIgnoreComptime()) {
18331833 return self.store(lhs, rhs, Type.u8, 0);
18341834 }
1835 if (pl_ty.zigTypeTag() == .ErrorSet) {
1836 return self.store(lhs, rhs, Type.anyerror, 0);
1837 }
18351838
18361839 const len = @intCast(u32, ty.abiSize(self.target));
18371840 return self.memcpy(lhs, rhs, .{ .imm32 = len });
......@@ -2198,7 +2201,7 @@ fn lowerParentPtr(self: *Self, ptr_val: Value, ptr_child_ty: Type) InnerError!WV
21982201 const parent_ptr = try self.lowerParentPtr(payload_ptr.container_ptr, payload_ptr.container_ty);
21992202 var buf: Type.Payload.ElemType = undefined;
22002203 const payload_ty = payload_ptr.container_ty.optionalChild(&buf);
2201 if (!payload_ty.hasRuntimeBitsIgnoreComptime() or payload_ty.isPtrLikeOptional()) {
2204 if (!payload_ty.hasRuntimeBitsIgnoreComptime() or payload_ty.optionalReprIsPayload()) {
22022205 return parent_ptr;
22032206 }
22042207
......@@ -2353,7 +2356,7 @@ fn lowerConstant(self: *Self, val: Value, ty: Type) InnerError!WValue {
23532356 const err_val = if (!is_pl) val else Value.initTag(.zero);
23542357 return self.lowerConstant(err_val, error_type);
23552358 },
2356 .Optional => if (ty.isPtrLikeOptional()) {
2359 .Optional => if (ty.optionalReprIsPayload()) {
23572360 var buf: Type.Payload.ElemType = undefined;
23582361 const pl_ty = ty.optionalChild(&buf);
23592362 if (val.castTag(.opt_payload)) |payload| {
......@@ -2392,7 +2395,7 @@ fn emitUndefined(self: *Self, ty: Type) InnerError!WValue {
23922395 .Optional => {
23932396 var buf: Type.Payload.ElemType = undefined;
23942397 const pl_ty = ty.optionalChild(&buf);
2395 if (ty.isPtrLikeOptional()) {
2398 if (ty.optionalReprIsPayload()) {
23962399 return self.emitUndefined(pl_ty);
23972400 }
23982401 return WValue{ .imm32 = 0xaaaaaaaa };
......@@ -2542,7 +2545,7 @@ fn airCmp(self: *Self, inst: Air.Inst.Index, op: std.math.CompareOperator) Inner
25422545}
25432546
25442547fn cmp(self: *Self, lhs: WValue, rhs: WValue, ty: Type, op: std.math.CompareOperator) InnerError!WValue {
2545 if (ty.zigTypeTag() == .Optional and !ty.isPtrLikeOptional()) {
2548 if (ty.zigTypeTag() == .Optional and !ty.optionalReprIsPayload()) {
25462549 var buf: Type.Payload.ElemType = undefined;
25472550 const payload_ty = ty.optionalChild(&buf);
25482551 if (payload_ty.hasRuntimeBitsIgnoreComptime()) {
......@@ -3120,7 +3123,7 @@ fn airIsNull(self: *Self, inst: Air.Inst.Index, opcode: wasm.Opcode, op_kind: en
31203123
31213124fn isNull(self: *Self, operand: WValue, optional_ty: Type, opcode: wasm.Opcode) InnerError!WValue {
31223125 try self.emitWValue(operand);
3123 if (!optional_ty.isPtrLikeOptional()) {
3126 if (!optional_ty.optionalReprIsPayload()) {
31243127 var buf: Type.Payload.ElemType = undefined;
31253128 const payload_ty = optional_ty.optionalChild(&buf);
31263129 // When payload is zero-bits, we can treat operand as a value, rather than
......@@ -3146,7 +3149,7 @@ fn airOptionalPayload(self: *Self, inst: Air.Inst.Index) InnerError!WValue {
31463149 const opt_ty = self.air.typeOf(ty_op.operand);
31473150 const payload_ty = self.air.typeOfIndex(inst);
31483151 if (!payload_ty.hasRuntimeBitsIgnoreComptime()) return WValue{ .none = {} };
3149 if (opt_ty.isPtrLikeOptional()) return operand;
3152 if (opt_ty.optionalReprIsPayload()) return operand;
31503153
31513154 const offset = opt_ty.abiSize(self.target) - payload_ty.abiSize(self.target);
31523155
......@@ -3166,7 +3169,7 @@ fn airOptionalPayloadPtr(self: *Self, inst: Air.Inst.Index) InnerError!WValue {
31663169
31673170 var buf: Type.Payload.ElemType = undefined;
31683171 const payload_ty = opt_ty.optionalChild(&buf);
3169 if (!payload_ty.hasRuntimeBitsIgnoreComptime() or opt_ty.isPtrLikeOptional()) {
3172 if (!payload_ty.hasRuntimeBitsIgnoreComptime() or opt_ty.optionalReprIsPayload()) {
31703173 return operand;
31713174 }
31723175
......@@ -3184,7 +3187,7 @@ fn airOptionalPayloadPtrSet(self: *Self, inst: Air.Inst.Index) InnerError!WValue
31843187 return self.fail("TODO: Implement OptionalPayloadPtrSet for optional with zero-sized type {}", .{payload_ty.fmtDebug()});
31853188 }
31863189
3187 if (opt_ty.isPtrLikeOptional()) {
3190 if (opt_ty.optionalReprIsPayload()) {
31883191 return operand;
31893192 }
31903193
......@@ -3215,7 +3218,7 @@ fn airWrapOptional(self: *Self, inst: Air.Inst.Index) InnerError!WValue {
32153218
32163219 const operand = try self.resolveInst(ty_op.operand);
32173220 const op_ty = self.air.typeOfIndex(inst);
3218 if (op_ty.isPtrLikeOptional()) {
3221 if (op_ty.optionalReprIsPayload()) {
32193222 return operand;
32203223 }
32213224 const offset = std.math.cast(u32, op_ty.abiSize(self.target) - payload_ty.abiSize(self.target)) catch {
src/codegen.zig+1-1
......@@ -654,7 +654,7 @@ pub fn generateSymbol(
654654 return Result{ .appended = {} };
655655 }
656656
657 if (typed_value.ty.isPtrLikeOptional()) {
657 if (typed_value.ty.optionalReprIsPayload()) {
658658 if (typed_value.val.castTag(.opt_payload)) |payload| {
659659 switch (try generateSymbol(bin_file, src_loc, .{
660660 .ty = payload_type,
src/codegen/c.zig+7-6
......@@ -712,7 +712,7 @@ pub const DeclGen = struct {
712712 .Optional => {
713713 var opt_buf: Type.Payload.ElemType = undefined;
714714 const payload_type = ty.optionalChild(&opt_buf);
715 if (ty.isPtrLikeOptional()) {
715 if (ty.optionalReprIsPayload()) {
716716 return dg.renderValue(writer, payload_type, val, location);
717717 }
718718 if (payload_type.abiSize(target) == 0) {
......@@ -1360,7 +1360,7 @@ pub const DeclGen = struct {
13601360 var opt_buf: Type.Payload.ElemType = undefined;
13611361 const child_type = t.optionalChild(&opt_buf);
13621362
1363 if (t.isPtrLikeOptional()) {
1363 if (t.optionalReprIsPayload()) {
13641364 return dg.renderType(w, child_type);
13651365 }
13661366
......@@ -3161,6 +3161,8 @@ fn airIsNull(
31613161 if (ty.isPtrLikeOptional()) {
31623162 // operand is a regular pointer, test `operand !=/== NULL`
31633163 try writer.print("){s} {s} NULL;\n", .{ deref_suffix, operator });
3164 } else if (payload_type.zigTypeTag() == .ErrorSet) {
3165 try writer.print("){s} {s} 0;\n", .{ deref_suffix, operator });
31643166 } else if (payload_type.abiSize(target) == 0) {
31653167 try writer.print("){s} {s} true;\n", .{ deref_suffix, operator });
31663168 } else {
......@@ -3183,7 +3185,7 @@ fn airOptionalPayload(f: *Function, inst: Air.Inst.Index) !CValue {
31833185 else
31843186 operand_ty;
31853187
3186 if (opt_ty.isPtrLikeOptional()) {
3188 if (opt_ty.optionalReprIsPayload()) {
31873189 // the operand is just a regular pointer, no need to do anything special.
31883190 // *?*T -> **T and ?*T -> *T are **T -> **T and *T -> *T in C
31893191 return operand;
......@@ -3209,7 +3211,7 @@ fn airOptionalPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
32093211
32103212 const opt_ty = operand_ty.elemType();
32113213
3212 if (opt_ty.isPtrLikeOptional()) {
3214 if (opt_ty.optionalReprIsPayload()) {
32133215 // The payload and the optional are the same value.
32143216 // Setting to non-null will be done when the payload is set.
32153217 return operand;
......@@ -3419,8 +3421,7 @@ fn airWrapOptional(f: *Function, inst: Air.Inst.Index) !CValue {
34193421 const operand = try f.resolveInst(ty_op.operand);
34203422
34213423 const inst_ty = f.air.typeOfIndex(inst);
3422 if (inst_ty.isPtrLikeOptional()) {
3423 // the operand is just a regular pointer, no need to do anything special.
3424 if (inst_ty.optionalReprIsPayload()) {
34243425 return operand;
34253426 }
34263427
src/codegen/llvm.zig+23-11
......@@ -1390,7 +1390,7 @@ pub const Object = struct {
13901390 gop.value_ptr.* = AnnotatedDITypePtr.initFull(di_ty);
13911391 return di_ty;
13921392 }
1393 if (ty.isPtrLikeOptional()) {
1393 if (ty.optionalReprIsPayload()) {
13941394 const ptr_di_ty = try o.lowerDebugType(child_ty, resolve);
13951395 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
13961396 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(ptr_di_ty), .{ .mod = o.module });
......@@ -1472,6 +1472,12 @@ pub const Object = struct {
14721472 .ErrorUnion => {
14731473 const err_set_ty = ty.errorUnionSet();
14741474 const payload_ty = ty.errorUnionPayload();
1475 if (err_set_ty.errorSetCardinality() == .zero) {
1476 const payload_di_ty = try o.lowerDebugType(payload_ty, .full);
1477 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1478 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(payload_di_ty), .{ .mod = o.module });
1479 return payload_di_ty;
1480 }
14751481 if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
14761482 const err_set_di_ty = try o.lowerDebugType(err_set_ty, .full);
14771483 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
......@@ -2439,7 +2445,7 @@ pub const DeclGen = struct {
24392445 return dg.context.intType(1);
24402446 }
24412447 const payload_llvm_ty = try dg.llvmType(child_ty);
2442 if (t.isPtrLikeOptional()) {
2448 if (t.optionalReprIsPayload()) {
24432449 return payload_llvm_ty;
24442450 }
24452451
......@@ -3058,7 +3064,7 @@ pub const DeclGen = struct {
30583064 if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
30593065 return non_null_bit;
30603066 }
3061 if (tv.ty.isPtrLikeOptional()) {
3067 if (tv.ty.optionalReprIsPayload()) {
30623068 if (tv.val.castTag(.opt_payload)) |payload| {
30633069 return dg.genTypedValue(.{ .ty = payload_ty, .val = payload.data });
30643070 } else if (is_pl) {
......@@ -3557,7 +3563,9 @@ pub const DeclGen = struct {
35573563 const payload_ty = opt_payload_ptr.container_ty.optionalChild(&buf);
35583564 bitcast_needed = !payload_ty.eql(ptr_child_ty, dg.module);
35593565
3560 if (!payload_ty.hasRuntimeBitsIgnoreComptime() or payload_ty.isPtrLikeOptional()) {
3566 if (!payload_ty.hasRuntimeBitsIgnoreComptime() or
3567 payload_ty.optionalReprIsPayload())
3568 {
35613569 // In this case, we represent pointer to optional the same as pointer
35623570 // to the payload.
35633571 break :blk parent_llvm_ptr;
......@@ -4461,7 +4469,9 @@ pub const FuncGen = struct {
44614469 .Int, .Bool, .Pointer, .ErrorSet => scalar_ty,
44624470 .Optional => blk: {
44634471 const payload_ty = operand_ty.optionalChild(&opt_buffer);
4464 if (!payload_ty.hasRuntimeBitsIgnoreComptime() or operand_ty.isPtrLikeOptional()) {
4472 if (!payload_ty.hasRuntimeBitsIgnoreComptime() or
4473 operand_ty.optionalReprIsPayload())
4474 {
44654475 break :blk operand_ty;
44664476 }
44674477 // We need to emit instructions to check for equality/inequality
......@@ -5414,7 +5424,7 @@ pub const FuncGen = struct {
54145424 const operand = try self.resolveInst(un_op);
54155425 const operand_ty = self.air.typeOf(un_op);
54165426 const optional_ty = if (operand_is_ptr) operand_ty.childType() else operand_ty;
5417 if (optional_ty.isPtrLikeOptional()) {
5427 if (optional_ty.optionalReprIsPayload()) {
54185428 const optional_llvm_ty = try self.dg.llvmType(optional_ty);
54195429 const loaded = if (operand_is_ptr) self.builder.buildLoad(operand, "") else operand;
54205430 return self.builder.buildICmp(pred, loaded, optional_llvm_ty.constNull(), "");
......@@ -5499,7 +5509,7 @@ pub const FuncGen = struct {
54995509 const res_ptr_ty = try self.dg.llvmType(result_ty);
55005510 return self.builder.buildBitCast(operand, res_ptr_ty, "");
55015511 }
5502 if (optional_ty.isPtrLikeOptional()) {
5512 if (optional_ty.optionalReprIsPayload()) {
55035513 // The payload and the optional are the same value.
55045514 return operand;
55055515 }
......@@ -5527,7 +5537,7 @@ pub const FuncGen = struct {
55275537 const res_ptr_ty = try self.dg.llvmType(result_ty);
55285538 return self.builder.buildBitCast(operand, res_ptr_ty, "");
55295539 }
5530 if (optional_ty.isPtrLikeOptional()) {
5540 if (optional_ty.optionalReprIsPayload()) {
55315541 // The payload and the optional are the same value.
55325542 // Setting to non-null will be done when the payload is set.
55335543 return operand;
......@@ -5561,7 +5571,7 @@ pub const FuncGen = struct {
55615571 const payload_ty = self.air.typeOfIndex(inst);
55625572 if (!payload_ty.hasRuntimeBitsIgnoreComptime()) return null;
55635573
5564 if (optional_ty.isPtrLikeOptional()) {
5574 if (optional_ty.optionalReprIsPayload()) {
55655575 // Payload value is the same as the optional value.
55665576 return operand;
55675577 }
......@@ -5702,7 +5712,9 @@ pub const FuncGen = struct {
57025712 if (!payload_ty.hasRuntimeBitsIgnoreComptime()) return non_null_bit;
57035713 const operand = try self.resolveInst(ty_op.operand);
57045714 const optional_ty = self.air.typeOfIndex(inst);
5705 if (optional_ty.isPtrLikeOptional()) return operand;
5715 if (optional_ty.optionalReprIsPayload()) {
5716 return operand;
5717 }
57065718 const llvm_optional_ty = try self.dg.llvmType(optional_ty);
57075719 if (isByRef(optional_ty)) {
57085720 const optional_ptr = self.buildAlloca(llvm_optional_ty);
......@@ -7038,7 +7050,7 @@ pub const FuncGen = struct {
70387050 }
70397051 const success_bit = self.builder.buildExtractValue(result, 1, "");
70407052
7041 if (optional_ty.isPtrLikeOptional()) {
7053 if (optional_ty.optionalReprIsPayload()) {
70427054 return self.builder.buildSelect(success_bit, payload.typeOf().constNull(), payload, "");
70437055 }
70447056
src/type.zig+53-5
......@@ -2916,8 +2916,10 @@ pub const Type = extern union {
29162916 var buf: Payload.ElemType = undefined;
29172917 const child_type = ty.optionalChild(&buf);
29182918
2919 if (child_type.zigTypeTag() == .Pointer and !child_type.isCPtr()) {
2920 return AbiAlignmentAdvanced{ .scalar = @divExact(target.cpu.arch.ptrBitWidth(), 8) };
2919 switch (child_type.zigTypeTag()) {
2920 .Pointer => return AbiAlignmentAdvanced{ .scalar = @divExact(target.cpu.arch.ptrBitWidth(), 8) },
2921 .ErrorSet => return abiAlignmentAdvanced(Type.anyerror, target, strat),
2922 else => {},
29212923 }
29222924
29232925 switch (strat) {
......@@ -3365,14 +3367,29 @@ pub const Type = extern union {
33653367 const child_type = ty.optionalChild(&buf);
33663368 if (!child_type.hasRuntimeBits()) return AbiSizeAdvanced{ .scalar = 1 };
33673369
3368 if (child_type.zigTypeTag() == .Pointer and !child_type.isCPtr() and !child_type.isSlice())
3369 return AbiSizeAdvanced{ .scalar = @divExact(target.cpu.arch.ptrBitWidth(), 8) };
3370 switch (child_type.zigTypeTag()) {
3371 .Pointer => {
3372 const ptr_info = child_type.ptrInfo().data;
3373 const has_null = switch (ptr_info.size) {
3374 .Slice, .C => true,
3375 else => ptr_info.@"allowzero",
3376 };
3377 if (!has_null) {
3378 const ptr_size_bytes = @divExact(target.cpu.arch.ptrBitWidth(), 8);
3379 return AbiSizeAdvanced{ .scalar = ptr_size_bytes };
3380 }
3381 },
3382 .ErrorSet => return abiSizeAdvanced(Type.anyerror, target, strat),
3383 else => {},
3384 }
33703385
33713386 // Optional types are represented as a struct with the child type as the first
33723387 // field and a boolean as the second. Since the child type's abi alignment is
33733388 // guaranteed to be >= that of bool's (1 byte) the added size is exactly equal
33743389 // to the child type's ABI alignment.
3375 return AbiSizeAdvanced{ .scalar = child_type.abiAlignment(target) + child_type.abiSize(target) };
3390 return AbiSizeAdvanced{
3391 .scalar = child_type.abiAlignment(target) + child_type.abiSize(target),
3392 };
33763393 },
33773394
33783395 .error_union => {
......@@ -3901,8 +3918,39 @@ pub const Type = extern union {
39013918 return ty.ptrInfo().data.@"allowzero";
39023919 }
39033920
3921 /// See also `isPtrLikeOptional`.
3922 pub fn optionalReprIsPayload(ty: Type) bool {
3923 switch (ty.tag()) {
3924 .optional_single_const_pointer,
3925 .optional_single_mut_pointer,
3926 .c_const_pointer,
3927 .c_mut_pointer,
3928 => return true,
3929
3930 .optional => {
3931 const child_ty = ty.castTag(.optional).?.data;
3932 switch (child_ty.zigTypeTag()) {
3933 .Pointer => {
3934 const info = child_ty.ptrInfo().data;
3935 switch (info.size) {
3936 .Slice, .C => return false,
3937 .Many, .One => return !info.@"allowzero",
3938 }
3939 },
3940 .ErrorSet => return true,
3941 else => return false,
3942 }
3943 },
3944
3945 .pointer => return ty.castTag(.pointer).?.data.size == .C,
3946
3947 else => return false,
3948 }
3949 }
3950
39043951 /// Returns true if the type is optional and would be lowered to a single pointer
39053952 /// address value, using 0 for null. Note that this returns true for C pointers.
3953 /// See also `hasOptionalRepr`.
39063954 pub fn isPtrLikeOptional(self: Type) bool {
39073955 switch (self.tag()) {
39083956 .optional_single_const_pointer,
test/behavior/error.zig+1-2
......@@ -433,9 +433,8 @@ test "return function call to error set from error union function" {
433433}
434434
435435test "optional error set is the same size as error set" {
436 if (builtin.zig_backend != .stage1) return error.SkipZigTest; // TODO
437
438436 comptime try expect(@sizeOf(?anyerror) == @sizeOf(anyerror));
437 comptime try expect(@alignOf(?anyerror) == @alignOf(anyerror));
439438 const S = struct {
440439 fn returnsOptErrSet() ?anyerror {
441440 return null;