authorgravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2023-08-10 03:25:35-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-08-11 11:01:47-07:00
log8b9161179d08a3f1dc22ea61e6165a0c638bfae3
tree9766bd828e3db022e50808c89c250c3e01b6609b
parentb835fd90cef1447904d3b009c9662ba4c0ea77d4

Sema: avoid deleting runtime side-effects in comptime initializers

Closes #16744

4 files changed, 190 insertions(+), 84 deletions(-)

src/Sema.zig+136-73
......@@ -4491,7 +4491,7 @@ fn validateUnionInit(
44914491 _ = try sema.unionFieldIndex(block, union_ty, field_name, field_src);
44924492 const air_tags = sema.air_instructions.items(.tag);
44934493 const air_datas = sema.air_instructions.items(.data);
4494 const field_ptr_air_ref = sema.inst_map.get(field_ptr).?;
4494 const field_ptr_ref = sema.inst_map.get(field_ptr).?;
44954495
44964496 // Our task here is to determine if the union is comptime-known. In such case,
44974497 // we erase the runtime AIR instructions for initializing the union, and replace
......@@ -4521,31 +4521,25 @@ fn validateUnionInit(
45214521 var make_runtime = false;
45224522 while (block_index > 0) : (block_index -= 1) {
45234523 const store_inst = block.instructions.items[block_index];
4524 if (Air.indexToRef(store_inst) == field_ptr_air_ref) break;
4524 if (Air.indexToRef(store_inst) == field_ptr_ref) break;
45254525 switch (air_tags[store_inst]) {
45264526 .store, .store_safe => {},
45274527 else => continue,
45284528 }
45294529 const bin_op = air_datas[store_inst].bin_op;
4530 var lhs = bin_op.lhs;
4531 if (Air.refToIndex(lhs)) |lhs_index| {
4532 if (air_tags[lhs_index] == .bitcast) {
4533 lhs = air_datas[lhs_index].ty_op.operand;
4534 block_index -= 1;
4535 }
4536 }
4537 if (lhs != field_ptr_air_ref) continue;
4538 while (block_index > 0) : (block_index -= 1) {
4539 const block_inst = block.instructions.items[block_index - 1];
4540 if (air_tags[block_inst] != .dbg_stmt) break;
4541 }
4542 if (block_index > 0 and
4543 field_ptr_air_ref == Air.indexToRef(block.instructions.items[block_index - 1]))
4544 {
4545 first_block_index = @min(first_block_index, block_index - 1);
4546 } else {
4547 first_block_index = @min(first_block_index, block_index);
4548 }
4530 var ptr_ref = bin_op.lhs;
4531 if (Air.refToIndex(ptr_ref)) |ptr_inst| if (air_tags[ptr_inst] == .bitcast) {
4532 ptr_ref = air_datas[ptr_inst].ty_op.operand;
4533 };
4534 if (ptr_ref != field_ptr_ref) continue;
4535 first_block_index = @min(if (Air.refToIndex(field_ptr_ref)) |field_ptr_inst|
4536 std.mem.lastIndexOfScalar(
4537 Air.Inst.Index,
4538 block.instructions.items[0..block_index],
4539 field_ptr_inst,
4540 ).?
4541 else
4542 block_index, first_block_index);
45494543 init_val = try sema.resolveMaybeUndefValAllowVariablesMaybeRuntime(bin_op.rhs, &make_runtime);
45504544 break;
45514545 }
......@@ -4557,7 +4551,29 @@ fn validateUnionInit(
45574551 if (init_val) |val| {
45584552 // Our task is to delete all the `field_ptr` and `store` instructions, and insert
45594553 // instead a single `store` to the result ptr with a comptime union value.
4560 block.instructions.shrinkRetainingCapacity(first_block_index);
4554 block_index = first_block_index;
4555 for (block.instructions.items[first_block_index..]) |cur_inst| {
4556 switch (air_tags[cur_inst]) {
4557 .struct_field_ptr,
4558 .struct_field_ptr_index_0,
4559 .struct_field_ptr_index_1,
4560 .struct_field_ptr_index_2,
4561 .struct_field_ptr_index_3,
4562 => if (Air.indexToRef(cur_inst) == field_ptr_ref) continue,
4563 .bitcast => if (air_datas[cur_inst].ty_op.operand == field_ptr_ref) continue,
4564 .store, .store_safe => {
4565 var ptr_ref = air_datas[cur_inst].bin_op.lhs;
4566 if (Air.refToIndex(ptr_ref)) |ptr_inst| if (air_tags[ptr_inst] == .bitcast) {
4567 ptr_ref = air_datas[ptr_inst].ty_op.operand;
4568 };
4569 if (ptr_ref == field_ptr_ref) continue;
4570 },
4571 else => {},
4572 }
4573 block.instructions.items[block_index] = cur_inst;
4574 block_index += 1;
4575 }
4576 block.instructions.shrinkRetainingCapacity(block_index);
45614577
45624578 var union_val = try mod.intern(.{ .un = .{
45634579 .ty = union_ty.toIntern(),
......@@ -4590,6 +4606,9 @@ fn validateStructInit(
45904606 const gpa = sema.gpa;
45914607 const ip = &mod.intern_pool;
45924608
4609 const field_indices = try gpa.alloc(u32, instrs.len);
4610 defer gpa.free(field_indices);
4611
45934612 // Maps field index to field_ptr index of where it was already initialized.
45944613 const found_fields = try gpa.alloc(Zir.Inst.Index, struct_ty.structFieldCount(mod));
45954614 defer gpa.free(found_fields);
......@@ -4597,7 +4616,7 @@ fn validateStructInit(
45974616
45984617 var struct_ptr_zir_ref: Zir.Inst.Ref = undefined;
45994618
4600 for (instrs) |field_ptr| {
4619 for (instrs, field_indices) |field_ptr, *field_index| {
46014620 const field_ptr_data = sema.code.instructions.items(.data)[field_ptr].pl_node;
46024621 const field_src: LazySrcLoc = .{ .node_offset_initializer = field_ptr_data.src_node };
46034622 const field_ptr_extra = sema.code.extraData(Zir.Inst.Field, field_ptr_data.payload_index).data;
......@@ -4606,12 +4625,12 @@ fn validateStructInit(
46064625 gpa,
46074626 sema.code.nullTerminatedString(field_ptr_extra.field_name_start),
46084627 );
4609 const field_index = if (struct_ty.isTuple(mod))
4628 field_index.* = if (struct_ty.isTuple(mod))
46104629 try sema.tupleFieldIndex(block, struct_ty, field_name, field_src)
46114630 else
46124631 try sema.structFieldIndex(block, struct_ty, field_name, field_src);
4613 if (found_fields[field_index] != 0) {
4614 const other_field_ptr = found_fields[field_index];
4632 if (found_fields[field_index.*] != 0) {
4633 const other_field_ptr = found_fields[field_index.*];
46154634 const other_field_ptr_data = sema.code.instructions.items(.data)[other_field_ptr].pl_node;
46164635 const other_field_src: LazySrcLoc = .{ .node_offset_initializer = other_field_ptr_data.src_node };
46174636 const msg = msg: {
......@@ -4622,7 +4641,7 @@ fn validateStructInit(
46224641 };
46234642 return sema.failWithOwnedErrorMsg(msg);
46244643 }
4625 found_fields[field_index] = field_ptr;
4644 found_fields[field_index.*] = field_ptr;
46264645 }
46274646
46284647 var root_msg: ?*Module.ErrorMsg = null;
......@@ -4708,7 +4727,7 @@ fn validateStructInit(
47084727 continue;
47094728 }
47104729
4711 const field_ptr_air_ref = sema.inst_map.get(field_ptr).?;
4730 const field_ptr_ref = sema.inst_map.get(field_ptr).?;
47124731
47134732 //std.debug.print("validateStructInit (field_ptr_air_inst=%{d}):\n", .{
47144733 // field_ptr_air_inst,
......@@ -4738,7 +4757,7 @@ fn validateStructInit(
47384757 var block_index = block.instructions.items.len - 1;
47394758 while (block_index > 0) : (block_index -= 1) {
47404759 const store_inst = block.instructions.items[block_index];
4741 if (Air.indexToRef(store_inst) == field_ptr_air_ref) {
4760 if (Air.indexToRef(store_inst) == field_ptr_ref) {
47424761 struct_is_comptime = false;
47434762 continue :field;
47444763 }
......@@ -4747,26 +4766,19 @@ fn validateStructInit(
47474766 else => continue,
47484767 }
47494768 const bin_op = air_datas[store_inst].bin_op;
4750 var lhs = bin_op.lhs;
4751 {
4752 const lhs_index = Air.refToIndex(lhs) orelse continue;
4753 if (air_tags[lhs_index] == .bitcast) {
4754 lhs = air_datas[lhs_index].ty_op.operand;
4755 block_index -= 1;
4756 }
4757 }
4758 if (lhs != field_ptr_air_ref) continue;
4759 while (block_index > 0) : (block_index -= 1) {
4760 const block_inst = block.instructions.items[block_index - 1];
4761 if (air_tags[block_inst] != .dbg_stmt) break;
4762 }
4763 if (block_index > 0 and
4764 field_ptr_air_ref == Air.indexToRef(block.instructions.items[block_index - 1]))
4765 {
4766 first_block_index = @min(first_block_index, block_index - 1);
4767 } else {
4768 first_block_index = @min(first_block_index, block_index);
4769 }
4769 var ptr_ref = bin_op.lhs;
4770 if (Air.refToIndex(ptr_ref)) |ptr_inst| if (air_tags[ptr_inst] == .bitcast) {
4771 ptr_ref = air_datas[ptr_inst].ty_op.operand;
4772 };
4773 if (ptr_ref != field_ptr_ref) continue;
4774 first_block_index = @min(if (Air.refToIndex(field_ptr_ref)) |field_ptr_inst|
4775 std.mem.lastIndexOfScalar(
4776 Air.Inst.Index,
4777 block.instructions.items[0..block_index],
4778 field_ptr_inst,
4779 ).?
4780 else
4781 block_index, first_block_index);
47704782 if (try sema.resolveMaybeUndefValAllowVariablesMaybeRuntime(bin_op.rhs, &make_runtime)) |val| {
47714783 field_values[i] = val.toIntern();
47724784 } else if (require_comptime) {
......@@ -4822,8 +4834,40 @@ fn validateStructInit(
48224834 if (struct_is_comptime) {
48234835 // Our task is to delete all the `field_ptr` and `store` instructions, and insert
48244836 // instead a single `store` to the struct_ptr with a comptime struct value.
4837 var init_index: usize = 0;
4838 var field_ptr_ref = Air.Inst.Ref.none;
4839 var block_index = first_block_index;
4840 for (block.instructions.items[first_block_index..]) |cur_inst| {
4841 while (field_ptr_ref == .none and init_index < instrs.len) : (init_index += 1) {
4842 const field_ty = struct_ty.structFieldType(field_indices[init_index], mod);
4843 if (try field_ty.onePossibleValue(mod)) |_| continue;
4844 field_ptr_ref = sema.inst_map.get(instrs[init_index]).?;
4845 }
4846 switch (air_tags[cur_inst]) {
4847 .struct_field_ptr,
4848 .struct_field_ptr_index_0,
4849 .struct_field_ptr_index_1,
4850 .struct_field_ptr_index_2,
4851 .struct_field_ptr_index_3,
4852 => if (Air.indexToRef(cur_inst) == field_ptr_ref) continue,
4853 .bitcast => if (air_datas[cur_inst].ty_op.operand == field_ptr_ref) continue,
4854 .store, .store_safe => {
4855 var ptr_ref = air_datas[cur_inst].bin_op.lhs;
4856 if (Air.refToIndex(ptr_ref)) |ptr_inst| if (air_tags[ptr_inst] == .bitcast) {
4857 ptr_ref = air_datas[ptr_inst].ty_op.operand;
4858 };
4859 if (ptr_ref == field_ptr_ref) {
4860 field_ptr_ref = .none;
4861 continue;
4862 }
4863 },
4864 else => {},
4865 }
4866 block.instructions.items[block_index] = cur_inst;
4867 block_index += 1;
4868 }
4869 block.instructions.shrinkRetainingCapacity(block_index);
48254870
4826 block.instructions.shrinkRetainingCapacity(first_block_index);
48274871 var struct_val = try mod.intern(.{ .aggregate = .{
48284872 .ty = struct_ty.toIntern(),
48294873 .storage = .{ .elems = field_values },
......@@ -4950,7 +4994,7 @@ fn zirValidateArrayInit(
49504994 }
49514995 }
49524996
4953 const elem_ptr_air_ref = sema.inst_map.get(elem_ptr).?;
4997 const elem_ptr_ref = sema.inst_map.get(elem_ptr).?;
49544998
49554999 // We expect to see something like this in the current block AIR:
49565000 // %a = elem_ptr(...)
......@@ -4975,7 +5019,7 @@ fn zirValidateArrayInit(
49755019 var block_index = block.instructions.items.len - 1;
49765020 while (block_index > 0) : (block_index -= 1) {
49775021 const store_inst = block.instructions.items[block_index];
4978 if (Air.indexToRef(store_inst) == elem_ptr_air_ref) {
5022 if (Air.indexToRef(store_inst) == elem_ptr_ref) {
49795023 array_is_comptime = false;
49805024 continue :outer;
49815025 }
......@@ -4984,26 +5028,19 @@ fn zirValidateArrayInit(
49845028 else => continue,
49855029 }
49865030 const bin_op = air_datas[store_inst].bin_op;
4987 var lhs = bin_op.lhs;
4988 {
4989 const lhs_index = Air.refToIndex(lhs) orelse continue;
4990 if (air_tags[lhs_index] == .bitcast) {
4991 lhs = air_datas[lhs_index].ty_op.operand;
4992 block_index -= 1;
4993 }
4994 }
4995 if (lhs != elem_ptr_air_ref) continue;
4996 while (block_index > 0) : (block_index -= 1) {
4997 const block_inst = block.instructions.items[block_index - 1];
4998 if (air_tags[block_inst] != .dbg_stmt) break;
4999 }
5000 if (block_index > 0 and
5001 elem_ptr_air_ref == Air.indexToRef(block.instructions.items[block_index - 1]))
5002 {
5003 first_block_index = @min(first_block_index, block_index - 1);
5004 } else {
5005 first_block_index = @min(first_block_index, block_index);
5006 }
5031 var ptr_ref = bin_op.lhs;
5032 if (Air.refToIndex(ptr_ref)) |ptr_inst| if (air_tags[ptr_inst] == .bitcast) {
5033 ptr_ref = air_datas[ptr_inst].ty_op.operand;
5034 };
5035 if (ptr_ref != elem_ptr_ref) continue;
5036 first_block_index = @min(if (Air.refToIndex(elem_ptr_ref)) |elem_ptr_inst|
5037 std.mem.lastIndexOfScalar(
5038 Air.Inst.Index,
5039 block.instructions.items[0..block_index],
5040 elem_ptr_inst,
5041 ).?
5042 else
5043 block_index, first_block_index);
50075044 if (try sema.resolveMaybeUndefValAllowVariablesMaybeRuntime(bin_op.rhs, &make_runtime)) |val| {
50085045 element_vals[i] = val.toIntern();
50095046 } else {
......@@ -5028,7 +5065,33 @@ fn zirValidateArrayInit(
50285065
50295066 // Our task is to delete all the `elem_ptr` and `store` instructions, and insert
50305067 // instead a single `store` to the array_ptr with a comptime struct value.
5031 block.instructions.shrinkRetainingCapacity(first_block_index);
5068 var elem_index: usize = 0;
5069 var elem_ptr_ref = Air.Inst.Ref.none;
5070 var block_index = first_block_index;
5071 for (block.instructions.items[first_block_index..]) |cur_inst| {
5072 while (elem_ptr_ref == .none and elem_index < instrs.len) : (elem_index += 1) {
5073 if (array_ty.isTuple(mod) and array_ty.structFieldIsComptime(elem_index, mod)) continue;
5074 elem_ptr_ref = sema.inst_map.get(instrs[elem_index]).?;
5075 }
5076 switch (air_tags[cur_inst]) {
5077 .ptr_elem_ptr => if (Air.indexToRef(cur_inst) == elem_ptr_ref) continue,
5078 .bitcast => if (air_datas[cur_inst].ty_op.operand == elem_ptr_ref) continue,
5079 .store, .store_safe => {
5080 var ptr_ref = air_datas[cur_inst].bin_op.lhs;
5081 if (Air.refToIndex(ptr_ref)) |ptr_inst| if (air_tags[ptr_inst] == .bitcast) {
5082 ptr_ref = air_datas[ptr_inst].ty_op.operand;
5083 };
5084 if (ptr_ref == elem_ptr_ref) {
5085 elem_ptr_ref = .none;
5086 continue;
5087 }
5088 },
5089 else => {},
5090 }
5091 block.instructions.items[block_index] = cur_inst;
5092 block_index += 1;
5093 }
5094 block.instructions.shrinkRetainingCapacity(block_index);
50325095
50335096 var array_val = try mod.intern(.{ .aggregate = .{
50345097 .ty = array_ty.toIntern(),
test/behavior/array.zig+24
......@@ -775,3 +775,27 @@ test "array init with no result pointer sets field result types" {
775775
776776 try expect(y == x);
777777}
778
779test "runtime side-effects in comptime-known array init" {
780 var side_effects: u4 = 0;
781 const init = [4]u4{
782 blk: {
783 side_effects += 1;
784 break :blk 1;
785 },
786 blk: {
787 side_effects += 2;
788 break :blk 2;
789 },
790 blk: {
791 side_effects += 4;
792 break :blk 4;
793 },
794 blk: {
795 side_effects += 8;
796 break :blk 8;
797 },
798 };
799 try expectEqual([4]u4{ 1, 2, 4, 8 }, init);
800 try expectEqual(@as(u4, std.math.maxInt(u4)), side_effects);
801}
test/behavior/struct.zig+25
......@@ -1738,3 +1738,28 @@ test "struct init with no result pointer sets field result types" {
17381738
17391739 try expect(y == x);
17401740}
1741
1742test "runtime side-effects in comptime-known struct init" {
1743 var side_effects: u4 = 0;
1744 const S = struct { a: u4, b: u4, c: u4, d: u4 };
1745 const init = S{
1746 .d = blk: {
1747 side_effects += 8;
1748 break :blk 8;
1749 },
1750 .c = blk: {
1751 side_effects += 4;
1752 break :blk 4;
1753 },
1754 .b = blk: {
1755 side_effects += 2;
1756 break :blk 2;
1757 },
1758 .a = blk: {
1759 side_effects += 1;
1760 break :blk 1;
1761 },
1762 };
1763 try expectEqual(S{ .a = 1, .b = 2, .c = 4, .d = 8 }, init);
1764 try expectEqual(@as(u4, std.math.maxInt(u4)), side_effects);
1765}
tools/lldb_pretty_printers.py+5-11
......@@ -347,15 +347,9 @@ class TagAndPayload_SynthProvider:
347347 except: return -1
348348 def get_child_at_index(self, index): return (self.tag, self.payload)[index] if index in range(2) else None
349349
350def Zir_Inst__Zir_Inst_Ref_SummaryProvider(value, _=None):
351 members = value.type.enum_members
352 # ignore .var_args_param_type and .none
353 return value if any(value.unsigned == member.unsigned for member in members) else 'instructions[%d]' % (value.unsigned + 2 - len(members))
354
355def Air_Inst__Air_Inst_Ref_SummaryProvider(value, _=None):
356 members = value.type.enum_members
357 # ignore .var_args_param_type and .none
358 return value if any(value.unsigned == member.unsigned for member in members) else 'instructions[%d]' % (value.unsigned + 2 - len(members))
350def InstRef_SummaryProvider(value, _=None):
351 return value if any(value.unsigned == member.unsigned for member in value.type.enum_members) else (
352 'InternPool.Index(%d)' % value.unsigned if value.unsigned < 0x80000000 else 'instructions[%d]' % (value.unsigned - 0x80000000))
359353
360354class Module_Decl__Module_Decl_Index_SynthProvider:
361355 def __init__(self, value, _=None): self.value = value
......@@ -700,9 +694,9 @@ def __lldb_init_module(debugger, _=None):
700694 add(debugger, category='zig.stage2', type='Zir.Inst', identifier='TagAndPayload', synth=True, inline_children=True, summary=True)
701695 add(debugger, category='zig.stage2', regex=True, type=MultiArrayList_Entry('Zir\\.Inst'), identifier='TagAndPayload', synth=True, inline_children=True, summary=True)
702696 add(debugger, category='zig.stage2', regex=True, type='^Zir\\.Inst\\.Data\\.Data__struct_[1-9][0-9]*$', inline_children=True, summary=True)
703 add(debugger, category='zig.stage2', type='Zir.Inst::Zir.Inst.Ref', summary=True)
697 add(debugger, category='zig.stage2', type='Zir.Inst::Zir.Inst.Ref', identifier='InstRef', summary=True)
704698 add(debugger, category='zig.stage2', type='Air.Inst', identifier='TagAndPayload', synth=True, inline_children=True, summary=True)
705 add(debugger, category='zig.stage2', type='Air.Inst::Air.Inst.Ref', summary=True)
699 add(debugger, category='zig.stage2', type='Air.Inst::Air.Inst.Ref', identifier='InstRef', summary=True)
706700 add(debugger, category='zig.stage2', regex=True, type=MultiArrayList_Entry('Air\\.Inst'), identifier='TagAndPayload', synth=True, inline_children=True, summary=True)
707701 add(debugger, category='zig.stage2', regex=True, type='^Air\\.Inst\\.Data\\.Data__struct_[1-9][0-9]*$', inline_children=True, summary=True)
708702 add(debugger, category='zig.stage2', type='Module.Decl::Module.Decl.Index', synth=True)