authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-09-28 15:58:41-07:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2024-09-28 15:58:41-07:00
log0cdec976e4eaf96e1735ff417b222ab1463727e8
tree1b47bb75eb6f29f9da11c93ac7ea924a8bfb326a
parent085cc54aadb327b9910be2c72b31ea046e7e8f52
parent2857ca1edc1c3fa83298d2e8f6d505a3776f1ae3
signaturebadge-check Signed by PGP key B5690EEEBB952194

Merge pull request #21520 from ziglang/no-formatted-panics

formalize the panic interface closes #17969 closes #20240

23 files changed, 734 insertions(+), 843 deletions(-)

lib/compiler_rt/common.zig+7-6
......@@ -75,13 +75,14 @@ pub const gnu_f16_abi = switch (builtin.cpu.arch) {
7575
7676pub const want_sparc_abi = builtin.cpu.arch.isSPARC();
7777
78// Avoid dragging in the runtime safety mechanisms into this .o file,
79// unless we're trying to test compiler-rt.
80pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace, _: ?usize) noreturn {
81 _ = error_return_trace;
78// Avoid dragging in the runtime safety mechanisms into this .o file, unless
79// we're trying to test compiler-rt.
80pub const Panic = if (builtin.is_test) std.debug.FormattedPanic else struct {};
81
82/// To be deleted after zig1.wasm is updated.
83pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace, ret_addr: ?usize) noreturn {
8284 if (builtin.is_test) {
83 @branchHint(.cold);
84 std.debug.panic("{s}", .{msg});
85 std.debug.defaultPanic(msg, error_return_trace, ret_addr orelse @returnAddress());
8586 } else {
8687 unreachable;
8788 }
lib/std/Thread.zig+77
......@@ -22,6 +22,83 @@ pub const WaitGroup = @import("Thread/WaitGroup.zig");
2222
2323pub const use_pthreads = native_os != .windows and native_os != .wasi and builtin.link_libc;
2424
25/// Spurious wakeups are possible and no precision of timing is guaranteed.
26pub fn sleep(nanoseconds: u64) void {
27 if (builtin.os.tag == .windows) {
28 const big_ms_from_ns = nanoseconds / std.time.ns_per_ms;
29 const ms = math.cast(windows.DWORD, big_ms_from_ns) orelse math.maxInt(windows.DWORD);
30 windows.kernel32.Sleep(ms);
31 return;
32 }
33
34 if (builtin.os.tag == .wasi) {
35 const w = std.os.wasi;
36 const userdata: w.userdata_t = 0x0123_45678;
37 const clock: w.subscription_clock_t = .{
38 .id = .MONOTONIC,
39 .timeout = nanoseconds,
40 .precision = 0,
41 .flags = 0,
42 };
43 const in: w.subscription_t = .{
44 .userdata = userdata,
45 .u = .{
46 .tag = .CLOCK,
47 .u = .{ .clock = clock },
48 },
49 };
50
51 var event: w.event_t = undefined;
52 var nevents: usize = undefined;
53 _ = w.poll_oneoff(&in, &event, 1, &nevents);
54 return;
55 }
56
57 if (builtin.os.tag == .uefi) {
58 const boot_services = std.os.uefi.system_table.boot_services.?;
59 const us_from_ns = nanoseconds / std.time.ns_per_us;
60 const us = math.cast(usize, us_from_ns) orelse math.maxInt(usize);
61 _ = boot_services.stall(us);
62 return;
63 }
64
65 const s = nanoseconds / std.time.ns_per_s;
66 const ns = nanoseconds % std.time.ns_per_s;
67
68 // Newer kernel ports don't have old `nanosleep()` and `clock_nanosleep()` has been around
69 // since Linux 2.6 and glibc 2.1 anyway.
70 if (builtin.os.tag == .linux) {
71 const linux = std.os.linux;
72
73 var req: linux.timespec = .{
74 .sec = std.math.cast(linux.time_t, s) orelse std.math.maxInt(linux.time_t),
75 .nsec = std.math.cast(linux.time_t, ns) orelse std.math.maxInt(linux.time_t),
76 };
77 var rem: linux.timespec = undefined;
78
79 while (true) {
80 switch (linux.E.init(linux.clock_nanosleep(.MONOTONIC, .{ .ABSTIME = false }, &req, &rem))) {
81 .SUCCESS => return,
82 .INTR => {
83 req = rem;
84 continue;
85 },
86 .FAULT,
87 .INVAL,
88 .OPNOTSUPP,
89 => unreachable,
90 else => return,
91 }
92 }
93 }
94
95 posix.nanosleep(s, ns);
96}
97
98test sleep {
99 sleep(1);
100}
101
25102const Thread = @This();
26103const Impl = if (native_os == .windows)
27104 WindowsThreadImpl
lib/std/builtin.zig+42-183
......@@ -761,195 +761,54 @@ pub const TestFn = struct {
761761 func: *const fn () anyerror!void,
762762};
763763
764/// This function type is used by the Zig language code generation and
765/// therefore must be kept in sync with the compiler implementation.
764/// Deprecated, use the `Panic` namespace instead.
765/// To be deleted after 0.14.0 is released.
766766pub const PanicFn = fn ([]const u8, ?*StackTrace, ?usize) noreturn;
767
768/// This function is used by the Zig language code generation and
769/// therefore must be kept in sync with the compiler implementation.
770pub const panic: PanicFn = if (@hasDecl(root, "panic"))
771 root.panic
772else if (@hasDecl(root, "os") and @hasDecl(root.os, "panic"))
773 root.os.panic
767/// Deprecated, use the `Panic` namespace instead.
768/// To be deleted after 0.14.0 is released.
769pub const panic: PanicFn = Panic.call;
770
771/// This namespace is used by the Zig compiler to emit various kinds of safety
772/// panics. These can be overridden by making a public `Panic` namespace in the
773/// root source file.
774pub const Panic: type = if (@hasDecl(root, "Panic"))
775 root.Panic
776else if (@hasDecl(root, "panic")) // Deprecated, use `Panic` instead.
777 DeprecatedPanic
778else if (builtin.zig_backend == .stage2_riscv64)
779 std.debug.SimplePanic // https://github.com/ziglang/zig/issues/21519
774780else
775 default_panic;
776
777/// This function is used by the Zig language code generation and
778/// therefore must be kept in sync with the compiler implementation.
779pub fn default_panic(msg: []const u8, error_return_trace: ?*StackTrace, ret_addr: ?usize) noreturn {
780 @branchHint(.cold);
781
782 // For backends that cannot handle the language features depended on by the
783 // default panic handler, we have a simpler panic handler:
784 if (builtin.zig_backend == .stage2_wasm or
785 builtin.zig_backend == .stage2_arm or
786 builtin.zig_backend == .stage2_aarch64 or
787 builtin.zig_backend == .stage2_x86 or
788 (builtin.zig_backend == .stage2_x86_64 and (builtin.target.ofmt != .elf and builtin.target.ofmt != .macho)) or
789 builtin.zig_backend == .stage2_sparc64 or
790 builtin.zig_backend == .stage2_spirv64)
791 {
792 while (true) {
793 @breakpoint();
794 }
795 }
796
797 if (builtin.zig_backend == .stage2_riscv64) {
798 std.debug.print("panic: {s}\n", .{msg});
799 @breakpoint();
800 std.posix.exit(127);
801 }
802
803 switch (builtin.os.tag) {
804 .freestanding => {
805 while (true) {
806 @breakpoint();
807 }
808 },
809 .wasi => {
810 std.debug.print("{s}", .{msg});
811 std.posix.abort();
812 },
813 .uefi => {
814 const uefi = std.os.uefi;
815
816 const Formatter = struct {
817 pub fn fmt(exit_msg: []const u8, out: []u16) ![:0]u16 {
818 var u8_buf: [256]u8 = undefined;
819 const slice = try std.fmt.bufPrint(&u8_buf, "err: {s}\r\n", .{exit_msg});
820 // We pass len - 1 because we need to add a null terminator after
821 const len = try std.unicode.utf8ToUtf16Le(out[0 .. out.len - 1], slice);
822
823 out[len] = 0;
824
825 return out[0..len :0];
826 }
827 };
828
829 const ExitData = struct {
830 pub fn create_exit_data(exit_msg: [:0]u16, exit_size: *usize) ![*:0]u16 {
831 // Need boot services for pool allocation
832 if (uefi.system_table.boot_services == null) {
833 return error.BootServicesUnavailable;
834 }
835
836 // ExitData buffer must be allocated using boot_services.allocatePool (spec: page 220)
837 const exit_data: []u16 = try uefi.raw_pool_allocator.alloc(u16, exit_msg.len + 1);
838
839 @memcpy(exit_data[0 .. exit_msg.len + 1], exit_msg[0 .. exit_msg.len + 1]);
840 exit_size.* = exit_msg.len + 1;
841
842 return @as([*:0]u16, @ptrCast(exit_data.ptr));
843 }
844 };
845
846 var buf: [256]u16 = undefined;
847 const utf16 = Formatter.fmt(msg, &buf) catch null;
848
849 var exit_size: usize = 0;
850 const exit_data = if (utf16) |u|
851 ExitData.create_exit_data(u, &exit_size) catch null
852 else
853 null;
854
855 if (utf16) |str| {
856 // Output to both std_err and con_out, as std_err is easier
857 // to read in stuff like QEMU at times, but, unlike con_out,
858 // isn't visible on actual hardware if directly booted into
859 inline for ([_]?*uefi.protocol.SimpleTextOutput{ uefi.system_table.std_err, uefi.system_table.con_out }) |o| {
860 if (o) |out| {
861 _ = out.setAttribute(uefi.protocol.SimpleTextOutput.red);
862 _ = out.outputString(str);
863 _ = out.setAttribute(uefi.protocol.SimpleTextOutput.white);
864 }
865 }
866 }
867
868 if (uefi.system_table.boot_services) |bs| {
869 _ = bs.exit(uefi.handle, .Aborted, exit_size, exit_data);
870 }
871
872 // Didn't have boot_services, just fallback to whatever.
873 std.posix.abort();
874 },
875 .cuda, .amdhsa => std.posix.abort(),
876 .plan9 => {
877 var status: [std.os.plan9.ERRMAX]u8 = undefined;
878 const len = @min(msg.len, status.len - 1);
879 @memcpy(status[0..len], msg[0..len]);
880 status[len] = 0;
881 std.os.plan9.exits(status[0..len :0]);
882 },
883 else => {
884 const first_trace_addr = ret_addr orelse @returnAddress();
885 std.debug.panicImpl(error_return_trace, first_trace_addr, msg);
886 },
887 }
888}
889
890pub fn panicSentinelMismatch(expected: anytype, actual: @TypeOf(expected)) noreturn {
891 @branchHint(.cold);
892 std.debug.panicExtra(null, @returnAddress(), "sentinel mismatch: expected {any}, found {any}", .{ expected, actual });
893}
894
895pub fn panicUnwrapError(st: ?*StackTrace, err: anyerror) noreturn {
896 @branchHint(.cold);
897 std.debug.panicExtra(st, @returnAddress(), "attempt to unwrap error: {s}", .{@errorName(err)});
898}
899
900pub fn panicOutOfBounds(index: usize, len: usize) noreturn {
901 @branchHint(.cold);
902 std.debug.panicExtra(null, @returnAddress(), "index out of bounds: index {d}, len {d}", .{ index, len });
903}
904
905pub fn panicStartGreaterThanEnd(start: usize, end: usize) noreturn {
906 @branchHint(.cold);
907 std.debug.panicExtra(null, @returnAddress(), "start index {d} is larger than end index {d}", .{ start, end });
908}
909
910pub fn panicInactiveUnionField(active: anytype, wanted: @TypeOf(active)) noreturn {
911 @branchHint(.cold);
912 std.debug.panicExtra(null, @returnAddress(), "access of union field '{s}' while field '{s}' is active", .{ @tagName(wanted), @tagName(active) });
913}
914
915pub const panic_messages = struct {
916 pub const unreach = "reached unreachable code";
917 pub const unwrap_null = "attempt to use null value";
918 pub const cast_to_null = "cast causes pointer to be null";
919 pub const incorrect_alignment = "incorrect alignment";
920 pub const invalid_error_code = "invalid error code";
921 pub const cast_truncated_data = "integer cast truncated bits";
922 pub const negative_to_unsigned = "attempt to cast negative value to unsigned integer";
923 pub const integer_overflow = "integer overflow";
924 pub const shl_overflow = "left shift overflowed bits";
925 pub const shr_overflow = "right shift overflowed bits";
926 pub const divide_by_zero = "division by zero";
927 pub const exact_division_remainder = "exact division produced remainder";
928 pub const inactive_union_field = "access of inactive union field";
929 pub const integer_part_out_of_bounds = "integer part of floating point value out of bounds";
930 pub const corrupt_switch = "switch on corrupt value";
931 pub const shift_rhs_too_big = "shift amount is greater than the type size";
932 pub const invalid_enum_value = "invalid enum value";
933 pub const sentinel_mismatch = "sentinel mismatch";
934 pub const unwrap_error = "attempt to unwrap error";
935 pub const index_out_of_bounds = "index out of bounds";
936 pub const start_index_greater_than_end = "start index is larger than end index";
937 pub const for_len_mismatch = "for loop over objects with non-equal lengths";
938 pub const memcpy_len_mismatch = "@memcpy arguments have non-equal lengths";
939 pub const memcpy_alias = "@memcpy arguments alias";
940 pub const noreturn_returned = "'noreturn' function returned";
941};
781 std.debug.FormattedPanic;
782
783/// To be deleted after 0.14.0 is released.
784const DeprecatedPanic = struct {
785 pub const call = root.panic;
786 pub const sentinelMismatch = std.debug.FormattedPanic.sentinelMismatch;
787 pub const unwrapError = std.debug.FormattedPanic.unwrapError;
788 pub const outOfBounds = std.debug.FormattedPanic.outOfBounds;
789 pub const startGreaterThanEnd = std.debug.FormattedPanic.startGreaterThanEnd;
790 pub const inactiveUnionField = std.debug.FormattedPanic.inactiveUnionField;
791 pub const messages = std.debug.FormattedPanic.messages;
792};
793
794/// To be deleted after zig1.wasm is updated.
795pub const panicSentinelMismatch = Panic.sentinelMismatch;
796/// To be deleted after zig1.wasm is updated.
797pub const panicUnwrapError = Panic.unwrapError;
798/// To be deleted after zig1.wasm is updated.
799pub const panicOutOfBounds = Panic.outOfBounds;
800/// To be deleted after zig1.wasm is updated.
801pub const panicStartGreaterThanEnd = Panic.startGreaterThanEnd;
802/// To be deleted after zig1.wasm is updated.
803pub const panicInactiveUnionField = Panic.inactiveUnionField;
804/// To be deleted after zig1.wasm is updated.
805pub const panic_messages = Panic.messages;
942806
943807pub noinline fn returnError(st: *StackTrace) void {
944 @branchHint(.cold);
808 @branchHint(.unlikely);
945809 @setRuntimeSafety(false);
946 addErrRetTraceAddr(st, @returnAddress());
947}
948
949pub inline fn addErrRetTraceAddr(st: *StackTrace, addr: usize) void {
950810 if (st.index < st.instruction_addresses.len)
951 st.instruction_addresses[st.index] = addr;
952
811 st.instruction_addresses[st.index] = @returnAddress();
953812 st.index += 1;
954813}
955814
lib/std/debug.zig+107-60
......@@ -21,6 +21,9 @@ pub const SelfInfo = @import("debug/SelfInfo.zig");
2121pub const Info = @import("debug/Info.zig");
2222pub const Coverage = @import("debug/Coverage.zig");
2323
24pub const FormattedPanic = @import("debug/FormattedPanic.zig");
25pub const SimplePanic = @import("debug/SimplePanic.zig");
26
2427/// Unresolved source locations can be represented with a single `usize` that
2528/// corresponds to a virtual memory address of the program counter. Combined
2629/// with debug information, those values can be converted into a resolved
......@@ -408,14 +411,21 @@ pub fn assertReadable(slice: []const volatile u8) void {
408411 for (slice) |*byte| _ = byte.*;
409412}
410413
414/// By including a call to this function, the caller gains an error return trace
415/// secret parameter, making `@errorReturnTrace()` more useful. This is not
416/// necessary if the function already contains a call to an errorable function
417/// elsewhere.
418pub fn errorReturnTraceHelper() anyerror!void {}
419
420/// Equivalent to `@panic` but with a formatted message.
411421pub fn panic(comptime format: []const u8, args: anytype) noreturn {
412422 @branchHint(.cold);
413
423 errorReturnTraceHelper() catch unreachable;
414424 panicExtra(@errorReturnTrace(), @returnAddress(), format, args);
415425}
416426
417/// `panicExtra` is useful when you want to print out an `@errorReturnTrace`
418/// and also print out some values.
427/// Equivalent to `@panic` but with a formatted message, and with an explicitly
428/// provided `@errorReturnTrace` and return address.
419429pub fn panicExtra(
420430 trace: ?*std.builtin.StackTrace,
421431 ret_addr: ?usize,
......@@ -436,7 +446,7 @@ pub fn panicExtra(
436446 break :blk &buf;
437447 },
438448 };
439 std.builtin.panic(msg, trace, ret_addr);
449 std.builtin.Panic.call(msg, trace, ret_addr);
440450}
441451
442452/// Non-zero whenever the program triggered a panic.
......@@ -447,11 +457,70 @@ var panicking = std.atomic.Value(u8).init(0);
447457/// This is used to catch and handle panics triggered by the panic handler.
448458threadlocal var panic_stage: usize = 0;
449459
450// `panicImpl` could be useful in implementing a custom panic handler which
451// calls the default handler (on supported platforms)
452pub fn panicImpl(trace: ?*const std.builtin.StackTrace, first_trace_addr: ?usize, msg: []const u8) noreturn {
460/// Dumps a stack trace to standard error, then aborts.
461pub fn defaultPanic(
462 msg: []const u8,
463 error_return_trace: ?*const std.builtin.StackTrace,
464 first_trace_addr: ?usize,
465) noreturn {
453466 @branchHint(.cold);
454467
468 // For backends that cannot handle the language features depended on by the
469 // default panic handler, we have a simpler panic handler:
470 if (builtin.zig_backend == .stage2_wasm or
471 builtin.zig_backend == .stage2_arm or
472 builtin.zig_backend == .stage2_aarch64 or
473 builtin.zig_backend == .stage2_x86 or
474 (builtin.zig_backend == .stage2_x86_64 and (builtin.target.ofmt != .elf and builtin.target.ofmt != .macho)) or
475 builtin.zig_backend == .stage2_sparc64 or
476 builtin.zig_backend == .stage2_spirv64)
477 {
478 @trap();
479 }
480
481 switch (builtin.os.tag) {
482 .freestanding => {
483 @trap();
484 },
485 .uefi => {
486 const uefi = std.os.uefi;
487
488 var utf16_buffer: [1000]u16 = undefined;
489 const len_minus_3 = std.unicode.utf8ToUtf16Le(&utf16_buffer, msg) catch 0;
490 utf16_buffer[len_minus_3][0..3].* = .{ '\r', '\n', 0 };
491 const len = len_minus_3 + 3;
492 const exit_msg = utf16_buffer[0 .. len - 1 :0];
493
494 // Output to both std_err and con_out, as std_err is easier
495 // to read in stuff like QEMU at times, but, unlike con_out,
496 // isn't visible on actual hardware if directly booted into
497 inline for ([_]?*uefi.protocol.SimpleTextOutput{ uefi.system_table.std_err, uefi.system_table.con_out }) |o| {
498 if (o) |out| {
499 _ = out.setAttribute(uefi.protocol.SimpleTextOutput.red);
500 _ = out.outputString(exit_msg);
501 _ = out.setAttribute(uefi.protocol.SimpleTextOutput.white);
502 }
503 }
504
505 if (uefi.system_table.boot_services) |bs| {
506 // ExitData buffer must be allocated using boot_services.allocatePool (spec: page 220)
507 const exit_data: []u16 = uefi.raw_pool_allocator.alloc(u16, exit_msg.len + 1) catch @trap();
508 @memcpy(exit_data, exit_msg[0..exit_data.len]); // Includes null terminator.
509 _ = bs.exit(uefi.handle, .Aborted, exit_msg.len + 1, exit_data);
510 }
511 @trap();
512 },
513 .cuda, .amdhsa => std.posix.abort(),
514 .plan9 => {
515 var status: [std.os.plan9.ERRMAX]u8 = undefined;
516 const len = @min(msg.len, status.len - 1);
517 @memcpy(status[0..len], msg[0..len]);
518 status[len] = 0;
519 std.os.plan9.exits(status[0..len :0]);
520 },
521 else => {},
522 }
523
455524 if (enable_segfault_handler) {
456525 // If a segfault happens while panicking, we want it to actually segfault, not trigger
457526 // the handler.
......@@ -465,7 +534,6 @@ pub fn panicImpl(trace: ?*const std.builtin.StackTrace, first_trace_addr: ?usize
465534
466535 _ = panicking.fetchAdd(1, .seq_cst);
467536
468 // Make sure to release the mutex when done
469537 {
470538 lockStdErr();
471539 defer unlockStdErr();
......@@ -478,10 +546,9 @@ pub fn panicImpl(trace: ?*const std.builtin.StackTrace, first_trace_addr: ?usize
478546 stderr.print("thread {} panic: ", .{current_thread_id}) catch posix.abort();
479547 }
480548 stderr.print("{s}\n", .{msg}) catch posix.abort();
481 if (trace) |t| {
482 dumpStackTrace(t.*);
483 }
484 dumpCurrentStackTrace(first_trace_addr);
549
550 if (error_return_trace) |t| dumpStackTrace(t.*);
551 dumpCurrentStackTrace(first_trace_addr orelse @returnAddress());
485552 }
486553
487554 waitForOtherThreadToFinishPanicking();
......@@ -489,15 +556,12 @@ pub fn panicImpl(trace: ?*const std.builtin.StackTrace, first_trace_addr: ?usize
489556 1 => {
490557 panic_stage = 2;
491558
492 // A panic happened while trying to print a previous panic message,
493 // we're still holding the mutex but that's fine as we're going to
494 // call abort()
495 const stderr = io.getStdErr().writer();
496 stderr.print("Panicked during a panic. Aborting.\n", .{}) catch posix.abort();
497 },
498 else => {
499 // Panicked while printing "Panicked during a panic."
559 // A panic happened while trying to print a previous panic message.
560 // We're still holding the mutex but that's fine as we're going to
561 // call abort().
562 io.getStdErr().writeAll("aborting due to recursive panic\n") catch {};
500563 },
564 else => {}, // Panicked while printing the recursive panic message.
501565 };
502566
503567 posix.abort();
......@@ -1157,7 +1221,7 @@ pub const default_enable_segfault_handler = runtime_safety and have_segfault_han
11571221
11581222pub fn maybeEnableSegfaultHandler() void {
11591223 if (enable_segfault_handler) {
1160 std.debug.attachSegfaultHandler();
1224 attachSegfaultHandler();
11611225 }
11621226}
11631227
......@@ -1289,46 +1353,29 @@ fn handleSegfaultWindows(info: *windows.EXCEPTION_POINTERS) callconv(windows.WIN
12891353 }
12901354}
12911355
1292fn handleSegfaultWindowsExtra(
1293 info: *windows.EXCEPTION_POINTERS,
1294 msg: u8,
1295 label: ?[]const u8,
1296) noreturn {
1297 const exception_address = @intFromPtr(info.ExceptionRecord.ExceptionAddress);
1298 if (windows.CONTEXT != void) {
1299 nosuspend switch (panic_stage) {
1300 0 => {
1301 panic_stage = 1;
1302 _ = panicking.fetchAdd(1, .seq_cst);
1303
1304 {
1305 lockStdErr();
1306 defer unlockStdErr();
1307
1308 dumpSegfaultInfoWindows(info, msg, label);
1309 }
1356fn handleSegfaultWindowsExtra(info: *windows.EXCEPTION_POINTERS, msg: u8, label: ?[]const u8) noreturn {
1357 comptime assert(windows.CONTEXT != void);
1358 nosuspend switch (panic_stage) {
1359 0 => {
1360 panic_stage = 1;
1361 _ = panicking.fetchAdd(1, .seq_cst);
1362
1363 {
1364 lockStdErr();
1365 defer unlockStdErr();
13101366
1311 waitForOtherThreadToFinishPanicking();
1312 },
1313 else => {
1314 // panic mutex already locked
13151367 dumpSegfaultInfoWindows(info, msg, label);
1316 },
1317 };
1318 posix.abort();
1319 } else {
1320 switch (msg) {
1321 0 => panicImpl(null, exception_address, "{s}", label.?),
1322 1 => {
1323 const format_item = "Segmentation fault at address 0x{x}";
1324 var buf: [format_item.len + 64]u8 = undefined; // 64 is arbitrary, but sufficiently large
1325 const to_print = std.fmt.bufPrint(buf[0..buf.len], format_item, .{info.ExceptionRecord.ExceptionInformation[1]}) catch unreachable;
1326 panicImpl(null, exception_address, to_print);
1327 },
1328 2 => panicImpl(null, exception_address, "Illegal Instruction"),
1329 else => unreachable,
1330 }
1331 }
1368 }
1369
1370 waitForOtherThreadToFinishPanicking();
1371 },
1372 1 => {
1373 panic_stage = 2;
1374 io.getStdErr().writeAll("aborting due to recursive panic\n") catch {};
1375 },
1376 else => {},
1377 };
1378 posix.abort();
13321379}
13331380
13341381fn dumpSegfaultInfoWindows(info: *windows.EXCEPTION_POINTERS, msg: u8, label: ?[]const u8) void {
......@@ -1347,7 +1394,7 @@ pub fn dumpStackPointerAddr(prefix: []const u8) void {
13471394 const sp = asm (""
13481395 : [argc] "={rsp}" (-> usize),
13491396 );
1350 std.debug.print("{s} sp = 0x{x}\n", .{ prefix, sp });
1397 print("{s} sp = 0x{x}\n", .{ prefix, sp });
13511398}
13521399
13531400test "manage resources correctly" {
lib/std/debug/FormattedPanic.zig created+45
......@@ -0,0 +1,45 @@
1//! This namespace is the default one used by the Zig compiler to emit various
2//! kinds of safety panics, due to the logic in `std.builtin.Panic`.
3//!
4//! Since Zig does not have interfaces, this file serves as an example template
5//! for users to provide their own alternative panic handling.
6//!
7//! As an alternative, see `std.debug.SimplePanic`.
8
9const std = @import("../std.zig");
10
11/// Dumps a stack trace to standard error, then aborts.
12///
13/// Explicit calls to `@panic` lower to calling this function.
14pub const call: fn ([]const u8, ?*std.builtin.StackTrace, ?usize) noreturn = std.debug.defaultPanic;
15
16pub fn sentinelMismatch(expected: anytype, found: @TypeOf(expected)) noreturn {
17 @branchHint(.cold);
18 std.debug.panicExtra(null, @returnAddress(), "sentinel mismatch: expected {any}, found {any}", .{
19 expected, found,
20 });
21}
22
23pub fn unwrapError(ert: ?*std.builtin.StackTrace, err: anyerror) noreturn {
24 @branchHint(.cold);
25 std.debug.panicExtra(ert, @returnAddress(), "attempt to unwrap error: {s}", .{@errorName(err)});
26}
27
28pub fn outOfBounds(index: usize, len: usize) noreturn {
29 @branchHint(.cold);
30 std.debug.panicExtra(null, @returnAddress(), "index out of bounds: index {d}, len {d}", .{ index, len });
31}
32
33pub fn startGreaterThanEnd(start: usize, end: usize) noreturn {
34 @branchHint(.cold);
35 std.debug.panicExtra(null, @returnAddress(), "start index {d} is larger than end index {d}", .{ start, end });
36}
37
38pub fn inactiveUnionField(active: anytype, accessed: @TypeOf(active)) noreturn {
39 @branchHint(.cold);
40 std.debug.panicExtra(null, @returnAddress(), "access of union field '{s}' while field '{s}' is active", .{
41 @tagName(accessed), @tagName(active),
42 });
43}
44
45pub const messages = std.debug.SimplePanic.messages;
lib/std/debug/SimplePanic.zig created+86
......@@ -0,0 +1,86 @@
1//! This namespace is the default one used by the Zig compiler to emit various
2//! kinds of safety panics, due to the logic in `std.builtin.Panic`.
3//!
4//! Since Zig does not have interfaces, this file serves as an example template
5//! for users to provide their own alternative panic handling.
6//!
7//! As an alternative, see `std.debug.FormattedPanic`.
8
9const std = @import("../std.zig");
10
11/// Prints the message to stderr without a newline and then traps.
12///
13/// Explicit calls to `@panic` lower to calling this function.
14pub fn call(msg: []const u8, ert: ?*std.builtin.StackTrace, ra: ?usize) noreturn {
15 @branchHint(.cold);
16 _ = ert;
17 _ = ra;
18 std.debug.lockStdErr();
19 const stderr = std.io.getStdErr();
20 stderr.writeAll(msg) catch {};
21 @trap();
22}
23
24pub fn sentinelMismatch(expected: anytype, found: @TypeOf(expected)) noreturn {
25 _ = found;
26 call("sentinel mismatch", null, null);
27}
28
29pub fn unwrapError(ert: ?*std.builtin.StackTrace, err: anyerror) noreturn {
30 _ = ert;
31 _ = &err;
32 call("attempt to unwrap error", null, null);
33}
34
35pub fn outOfBounds(index: usize, len: usize) noreturn {
36 _ = index;
37 _ = len;
38 call("index out of bounds", null, null);
39}
40
41pub fn startGreaterThanEnd(start: usize, end: usize) noreturn {
42 _ = start;
43 _ = end;
44 call("start index is larger than end index", null, null);
45}
46
47pub fn inactiveUnionField(active: anytype, accessed: @TypeOf(active)) noreturn {
48 _ = accessed;
49 call("access of inactive union field", null, null);
50}
51
52pub const messages = struct {
53 pub const reached_unreachable = "reached unreachable code";
54 pub const unwrap_null = "attempt to use null value";
55 pub const cast_to_null = "cast causes pointer to be null";
56 pub const incorrect_alignment = "incorrect alignment";
57 pub const invalid_error_code = "invalid error code";
58 pub const cast_truncated_data = "integer cast truncated bits";
59 pub const negative_to_unsigned = "attempt to cast negative value to unsigned integer";
60 pub const integer_overflow = "integer overflow";
61 pub const shl_overflow = "left shift overflowed bits";
62 pub const shr_overflow = "right shift overflowed bits";
63 pub const divide_by_zero = "division by zero";
64 pub const exact_division_remainder = "exact division produced remainder";
65 pub const integer_part_out_of_bounds = "integer part of floating point value out of bounds";
66 pub const corrupt_switch = "switch on corrupt value";
67 pub const shift_rhs_too_big = "shift amount is greater than the type size";
68 pub const invalid_enum_value = "invalid enum value";
69 pub const for_len_mismatch = "for loop over objects with non-equal lengths";
70 pub const memcpy_len_mismatch = "@memcpy arguments have non-equal lengths";
71 pub const memcpy_alias = "@memcpy arguments alias";
72 pub const noreturn_returned = "'noreturn' function returned";
73
74 /// To be deleted after zig1.wasm is updated.
75 pub const inactive_union_field = "access of inactive union field";
76 /// To be deleted after zig1.wasm is updated.
77 pub const sentinel_mismatch = "sentinel mismatch";
78 /// To be deleted after zig1.wasm is updated.
79 pub const unwrap_error = "attempt to unwrap error";
80 /// To be deleted after zig1.wasm is updated.
81 pub const index_out_of_bounds = "index out of bounds";
82 /// To be deleted after zig1.wasm is updated.
83 pub const start_index_greater_than_end = "start index is larger than end index";
84 /// To be deleted after zig1.wasm is updated.
85 pub const unreach = reached_unreachable;
86};
lib/std/fmt.zig+4-8
......@@ -1197,7 +1197,7 @@ pub fn formatInt(
11971197 if (base == 10) {
11981198 while (a >= 100) : (a = @divTrunc(a, 100)) {
11991199 index -= 2;
1200 buf[index..][0..2].* = digits2(@as(usize, @intCast(a % 100)));
1200 buf[index..][0..2].* = digits2(@intCast(a % 100));
12011201 }
12021202
12031203 if (a < 10) {
......@@ -1205,13 +1205,13 @@ pub fn formatInt(
12051205 buf[index] = '0' + @as(u8, @intCast(a));
12061206 } else {
12071207 index -= 2;
1208 buf[index..][0..2].* = digits2(@as(usize, @intCast(a)));
1208 buf[index..][0..2].* = digits2(@intCast(a));
12091209 }
12101210 } else {
12111211 while (true) {
12121212 const digit = a % base;
12131213 index -= 1;
1214 buf[index] = digitToChar(@as(u8, @intCast(digit)), case);
1214 buf[index] = digitToChar(@intCast(digit), case);
12151215 a /= base;
12161216 if (a == 0) break;
12171217 }
......@@ -1242,11 +1242,7 @@ pub fn formatIntBuf(out_buf: []u8, value: anytype, base: u8, case: Case, options
12421242
12431243// Converts values in the range [0, 100) to a string.
12441244pub fn digits2(value: usize) [2]u8 {
1245 return ("0001020304050607080910111213141516171819" ++
1246 "2021222324252627282930313233343536373839" ++
1247 "4041424344454647484950515253545556575859" ++
1248 "6061626364656667686970717273747576777879" ++
1249 "8081828384858687888990919293949596979899")[value * 2 ..][0..2].*;
1245 return "00010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"[value * 2 ..][0..2].*;
12501246}
12511247
12521248const FormatDurationData = struct {
lib/std/time.zig+4-78
......@@ -8,82 +8,8 @@ const posix = std.posix;
88
99pub const epoch = @import("time/epoch.zig");
1010
11/// Spurious wakeups are possible and no precision of timing is guaranteed.
12pub fn sleep(nanoseconds: u64) void {
13 if (builtin.os.tag == .windows) {
14 const big_ms_from_ns = nanoseconds / ns_per_ms;
15 const ms = math.cast(windows.DWORD, big_ms_from_ns) orelse math.maxInt(windows.DWORD);
16 windows.kernel32.Sleep(ms);
17 return;
18 }
19
20 if (builtin.os.tag == .wasi) {
21 const w = std.os.wasi;
22 const userdata: w.userdata_t = 0x0123_45678;
23 const clock: w.subscription_clock_t = .{
24 .id = .MONOTONIC,
25 .timeout = nanoseconds,
26 .precision = 0,
27 .flags = 0,
28 };
29 const in: w.subscription_t = .{
30 .userdata = userdata,
31 .u = .{
32 .tag = .CLOCK,
33 .u = .{ .clock = clock },
34 },
35 };
36
37 var event: w.event_t = undefined;
38 var nevents: usize = undefined;
39 _ = w.poll_oneoff(&in, &event, 1, &nevents);
40 return;
41 }
42
43 if (builtin.os.tag == .uefi) {
44 const boot_services = std.os.uefi.system_table.boot_services.?;
45 const us_from_ns = nanoseconds / ns_per_us;
46 const us = math.cast(usize, us_from_ns) orelse math.maxInt(usize);
47 _ = boot_services.stall(us);
48 return;
49 }
50
51 const s = nanoseconds / ns_per_s;
52 const ns = nanoseconds % ns_per_s;
53
54 // Newer kernel ports don't have old `nanosleep()` and `clock_nanosleep()` has been around
55 // since Linux 2.6 and glibc 2.1 anyway.
56 if (builtin.os.tag == .linux) {
57 const linux = std.os.linux;
58
59 var req: linux.timespec = .{
60 .sec = std.math.cast(linux.time_t, s) orelse std.math.maxInt(linux.time_t),
61 .nsec = std.math.cast(linux.time_t, ns) orelse std.math.maxInt(linux.time_t),
62 };
63 var rem: linux.timespec = undefined;
64
65 while (true) {
66 switch (linux.E.init(linux.clock_nanosleep(.MONOTONIC, .{ .ABSTIME = false }, &req, &rem))) {
67 .SUCCESS => return,
68 .INTR => {
69 req = rem;
70 continue;
71 },
72 .FAULT,
73 .INVAL,
74 .OPNOTSUPP,
75 => unreachable,
76 else => return,
77 }
78 }
79 }
80
81 posix.nanosleep(s, ns);
82}
83
84test sleep {
85 sleep(1);
86}
11/// Deprecated: moved to std.Thread.sleep
12pub const sleep = std.Thread.sleep;
8713
8814/// Get a calendar timestamp, in seconds, relative to UTC 1970-01-01.
8915/// Precision of timing depends on the hardware and operating system.
......@@ -155,7 +81,7 @@ test milliTimestamp {
15581 const margin = ns_per_ms * 50;
15682
15783 const time_0 = milliTimestamp();
158 sleep(ns_per_ms);
84 std.Thread.sleep(ns_per_ms);
15985 const time_1 = milliTimestamp();
16086 const interval = time_1 - time_0;
16187 try testing.expect(interval > 0);
......@@ -359,7 +285,7 @@ test Timer {
359285 const margin = ns_per_ms * 150;
360286
361287 var timer = try Timer.start();
362 sleep(10 * ns_per_ms);
288 std.Thread.sleep(10 * ns_per_ms);
363289 const time_0 = timer.read();
364290 try testing.expect(time_0 > 0);
365291 // Tests should not depend on timings: skip test if outside margin.
src/Compilation.zig-8
......@@ -195,7 +195,6 @@ job_queued_compiler_rt_obj: bool = false,
195195job_queued_fuzzer_lib: bool = false,
196196job_queued_update_builtin_zig: bool,
197197alloc_failure_occurred: bool = false,
198formatted_panics: bool = false,
199198last_update_was_cache_hit: bool = false,
200199
201200c_source_files: []const CSourceFile,
......@@ -1088,7 +1087,6 @@ pub const CreateOptions = struct {
10881087 /// executable this field is ignored.
10891088 want_compiler_rt: ?bool = null,
10901089 want_lto: ?bool = null,
1091 formatted_panics: ?bool = null,
10921090 function_sections: bool = false,
10931091 data_sections: bool = false,
10941092 no_builtin: bool = false,
......@@ -1357,9 +1355,6 @@ pub fn create(gpa: Allocator, arena: Allocator, options: CreateOptions) !*Compil
13571355 }
13581356 }
13591357
1360 // TODO: https://github.com/ziglang/zig/issues/17969
1361 const formatted_panics = options.formatted_panics orelse (options.root_mod.optimize_mode == .Debug);
1362
13631358 const error_limit = options.error_limit orelse (std.math.maxInt(u16) - 1);
13641359
13651360 // We put everything into the cache hash that *cannot be modified
......@@ -1520,7 +1515,6 @@ pub fn create(gpa: Allocator, arena: Allocator, options: CreateOptions) !*Compil
15201515 .verbose_link = options.verbose_link,
15211516 .disable_c_depfile = options.disable_c_depfile,
15221517 .reference_trace = options.reference_trace,
1523 .formatted_panics = formatted_panics,
15241518 .time_report = options.time_report,
15251519 .stack_report = options.stack_report,
15261520 .test_filters = options.test_filters,
......@@ -1638,7 +1632,6 @@ pub fn create(gpa: Allocator, arena: Allocator, options: CreateOptions) !*Compil
16381632 hash.addListOfBytes(options.test_filters);
16391633 hash.addOptionalBytes(options.test_name_prefix);
16401634 hash.add(options.skip_linker_dependencies);
1641 hash.add(formatted_panics);
16421635 hash.add(options.emit_h != null);
16431636 hash.add(error_limit);
16441637
......@@ -2564,7 +2557,6 @@ fn addNonIncrementalStuffToCacheManifest(
25642557 man.hash.addListOfBytes(comp.test_filters);
25652558 man.hash.addOptionalBytes(comp.test_name_prefix);
25662559 man.hash.add(comp.skip_linker_dependencies);
2567 man.hash.add(comp.formatted_panics);
25682560 //man.hash.add(mod.emit_h != null);
25692561 man.hash.add(mod.error_limit);
25702562 } else {
src/InternPool.zig+25-9
......@@ -7353,6 +7353,7 @@ pub fn get(ip: *InternPool, gpa: Allocator, tid: Zcu.PerThread.Id, key: Key) All
73537353 .func_type => unreachable, // use getFuncType() instead
73547354 .@"extern" => unreachable, // use getExtern() instead
73557355 .func => unreachable, // use getFuncInstance() or getFuncDecl() instead
7356 .un => unreachable, // use getUnion instead
73567357
73577358 .variable => |variable| {
73587359 const has_init = variable.init != .none;
......@@ -7968,15 +7969,6 @@ pub fn get(ip: *InternPool, gpa: Allocator, tid: Zcu.PerThread.Id, key: Key) All
79687969 if (sentinel != .none) extra.appendAssumeCapacity(.{@intFromEnum(sentinel)});
79697970 },
79707971
7971 .un => |un| {
7972 assert(un.ty != .none);
7973 assert(un.val != .none);
7974 items.appendAssumeCapacity(.{
7975 .tag = .union_value,
7976 .data = try addExtra(extra, un),
7977 });
7978 },
7979
79807972 .memoized_call => |memoized_call| {
79817973 for (memoized_call.arg_values) |arg| assert(arg != .none);
79827974 try extra.ensureUnusedCapacity(@typeInfo(MemoizedCall).@"struct".fields.len +
......@@ -7996,6 +7988,30 @@ pub fn get(ip: *InternPool, gpa: Allocator, tid: Zcu.PerThread.Id, key: Key) All
79967988 return gop.put();
79977989}
79987990
7991pub fn getUnion(
7992 ip: *InternPool,
7993 gpa: Allocator,
7994 tid: Zcu.PerThread.Id,
7995 un: Key.Union,
7996) Allocator.Error!Index {
7997 var gop = try ip.getOrPutKey(gpa, tid, .{ .un = un });
7998 defer gop.deinit();
7999 if (gop == .existing) return gop.existing;
8000 const local = ip.getLocal(tid);
8001 const items = local.getMutableItems(gpa);
8002 const extra = local.getMutableExtra(gpa);
8003 try items.ensureUnusedCapacity(1);
8004
8005 assert(un.ty != .none);
8006 assert(un.val != .none);
8007 items.appendAssumeCapacity(.{
8008 .tag = .union_value,
8009 .data = try addExtra(extra, un),
8010 });
8011
8012 return gop.put();
8013}
8014
79998015pub const UnionTypeInit = struct {
80008016 flags: packed struct {
80018017 runtime_tag: LoadedUnionType.RuntimeTag,
src/Sema.zig+235-387
......@@ -2141,7 +2141,7 @@ pub fn setupErrorReturnTrace(sema: *Sema, block: *Block, last_arg_index: usize)
21412141 const addrs_ptr = try err_trace_block.addTy(.alloc, try pt.singleMutPtrType(addr_arr_ty));
21422142
21432143 // var st: StackTrace = undefined;
2144 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
2144 const stack_trace_ty = try sema.getBuiltinType("StackTrace");
21452145 try stack_trace_ty.resolveFields(pt);
21462146 const st_ptr = try err_trace_block.addTy(.alloc, try pt.singleMutPtrType(stack_trace_ty));
21472147
......@@ -4854,11 +4854,11 @@ fn validateUnionInit(
48544854 }
48554855 block.instructions.shrinkRetainingCapacity(block_index);
48564856
4857 const union_val = try pt.intern(.{ .un = .{
4857 const union_val = try pt.internUnion(.{
48584858 .ty = union_ty.toIntern(),
48594859 .tag = tag_val.toIntern(),
48604860 .val = val.toIntern(),
4861 } });
4861 });
48624862 const union_init = Air.internedToRef(union_val);
48634863 try sema.storePtr2(block, init_src, union_ptr, init_src, union_init, init_src, .store);
48644864 return;
......@@ -5703,27 +5703,7 @@ fn addStrLit(sema: *Sema, string: InternPool.String, len: u64) CompileError!Air.
57035703}
57045704
57055705fn uavRef(sema: *Sema, val: InternPool.Index) CompileError!Air.Inst.Ref {
5706 return Air.internedToRef(try sema.refValue(val));
5707}
5708
5709fn refValue(sema: *Sema, val: InternPool.Index) CompileError!InternPool.Index {
5710 const pt = sema.pt;
5711 const ptr_ty = (try pt.ptrTypeSema(.{
5712 .child = pt.zcu.intern_pool.typeOf(val),
5713 .flags = .{
5714 .alignment = .none,
5715 .is_const = true,
5716 .address_space = .generic,
5717 },
5718 })).toIntern();
5719 return pt.intern(.{ .ptr = .{
5720 .ty = ptr_ty,
5721 .base_addr = .{ .uav = .{
5722 .val = val,
5723 .orig_ty = ptr_ty,
5724 } },
5725 .byte_offset = 0,
5726 } });
5706 return Air.internedToRef(try sema.pt.refValue(val));
57275707}
57285708
57295709fn zirInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
......@@ -6965,7 +6945,7 @@ pub fn analyzeSaveErrRetIndex(sema: *Sema, block: *Block) SemaError!Air.Inst.Ref
69656945
69666946 if (!block.ownerModule().error_tracing) return .none;
69676947
6968 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
6948 const stack_trace_ty = try sema.getBuiltinType("StackTrace");
69696949 try stack_trace_ty.resolveFields(pt);
69706950 const field_name = try zcu.intern_pool.getOrPutString(gpa, pt.tid, "index", .no_embedded_nulls);
69716951 const field_index = sema.structFieldIndex(block, stack_trace_ty, field_name, LazySrcLoc.unneeded) catch |err| switch (err) {
......@@ -7007,7 +6987,7 @@ fn popErrorReturnTrace(
70076987 // AstGen determined this result does not go to an error-handling expr (try/catch/return etc.), or
70086988 // the result is comptime-known to be a non-error. Either way, pop unconditionally.
70096989
7010 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
6990 const stack_trace_ty = try sema.getBuiltinType("StackTrace");
70116991 try stack_trace_ty.resolveFields(pt);
70126992 const ptr_stack_trace_ty = try pt.singleMutPtrType(stack_trace_ty);
70136993 const err_return_trace = try block.addTy(.err_return_trace, ptr_stack_trace_ty);
......@@ -7033,7 +7013,7 @@ fn popErrorReturnTrace(
70337013 defer then_block.instructions.deinit(gpa);
70347014
70357015 // If non-error, then pop the error return trace by restoring the index.
7036 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
7016 const stack_trace_ty = try sema.getBuiltinType("StackTrace");
70377017 try stack_trace_ty.resolveFields(pt);
70387018 const ptr_stack_trace_ty = try pt.singleMutPtrType(stack_trace_ty);
70397019 const err_return_trace = try then_block.addTy(.err_return_trace, ptr_stack_trace_ty);
......@@ -7176,7 +7156,7 @@ fn zirCall(
71767156 // If any input is an error-type, we might need to pop any trace it generated. Otherwise, we only
71777157 // need to clean-up our own trace if we were passed to a non-error-handling expression.
71787158 if (input_is_error or (pop_error_return_trace and return_ty.isError(zcu))) {
7179 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
7159 const stack_trace_ty = try sema.getBuiltinType("StackTrace");
71807160 try stack_trace_ty.resolveFields(pt);
71817161 const field_name = try zcu.intern_pool.getOrPutString(sema.gpa, pt.tid, "index", .no_embedded_nulls);
71827162 const field_index = try sema.structFieldIndex(block, stack_trace_ty, field_name, call_src);
......@@ -9327,7 +9307,7 @@ fn analyzeErrUnionPayload(
93279307 if (safety_check and block.wantSafety() and
93289308 !err_union_ty.errorUnionSet(zcu).errorSetIsEmpty(zcu))
93299309 {
9330 try sema.panicUnwrapError(block, src, operand, .unwrap_errunion_err, .is_non_err);
9310 try sema.addSafetyCheckUnwrapError(block, src, operand, .unwrap_errunion_err, .is_non_err);
93319311 }
93329312
93339313 return block.addTyOp(.unwrap_errunion_payload, payload_ty, operand);
......@@ -9411,7 +9391,7 @@ fn analyzeErrUnionPayloadPtr(
94119391 if (safety_check and block.wantSafety() and
94129392 !err_union_ty.errorUnionSet(zcu).errorSetIsEmpty(zcu))
94139393 {
9414 try sema.panicUnwrapError(block, src, operand, .unwrap_errunion_err_ptr, .is_non_err_ptr);
9394 try sema.addSafetyCheckUnwrapError(block, src, operand, .unwrap_errunion_err_ptr, .is_non_err_ptr);
94159395 }
94169396
94179397 if (initializing) {
......@@ -10231,7 +10211,7 @@ fn finishFunc(
1023110211 if (!final_is_generic and sema.wantErrorReturnTracing(return_type)) {
1023210212 // Make sure that StackTrace's fields are resolved so that the backend can
1023310213 // lower this fn type.
10234 const unresolved_stack_trace_ty = try pt.getBuiltinType("StackTrace");
10214 const unresolved_stack_trace_ty = try sema.getBuiltinType("StackTrace");
1023510215 try unresolved_stack_trace_ty.resolveFields(pt);
1023610216 }
1023710217
......@@ -14190,7 +14170,6 @@ fn maybeErrorUnwrap(
1419014170) !bool {
1419114171 const pt = sema.pt;
1419214172 const zcu = pt.zcu;
14193 if (!zcu.backendSupportsFeature(.panic_unwrap_error)) return false;
1419414173
1419514174 const tags = sema.code.instructions.items(.tag);
1419614175 for (body) |inst| {
......@@ -14223,25 +14202,17 @@ fn maybeErrorUnwrap(
1422314202 .as_node => try sema.zirAsNode(block, inst),
1422414203 .field_val => try sema.zirFieldVal(block, inst),
1422514204 .@"unreachable" => {
14226 if (!zcu.comp.formatted_panics) {
14227 try sema.safetyPanic(block, operand_src, .unwrap_error);
14228 return true;
14229 }
14230
14231 const panic_fn = try pt.getBuiltin("panicUnwrapError");
14232 const err_return_trace = try sema.getErrorReturnTrace(block);
14233 const args: [2]Air.Inst.Ref = .{ err_return_trace, operand };
14234 try sema.callBuiltin(block, operand_src, panic_fn, .auto, &args, .@"safety check");
14205 try safetyPanicUnwrapError(sema, block, operand_src, operand);
1423514206 return true;
1423614207 },
1423714208 .panic => {
1423814209 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1423914210 const msg_inst = try sema.resolveInst(inst_data.operand);
1424014211
14241 const panic_fn = try pt.getBuiltin("panic");
14212 const panic_fn = try getPanicInnerFn(sema, block, operand_src, "call");
1424214213 const err_return_trace = try sema.getErrorReturnTrace(block);
1424314214 const args: [3]Air.Inst.Ref = .{ msg_inst, err_return_trace, .null_value };
14244 try sema.callBuiltin(block, operand_src, panic_fn, .auto, &args, .@"safety check");
14215 try sema.callBuiltin(block, operand_src, Air.internedToRef(panic_fn), .auto, &args, .@"safety check");
1424514216 return true;
1424614217 },
1424714218 else => unreachable,
......@@ -18275,7 +18246,7 @@ fn zirBuiltinSrc(
1827518246 } });
1827618247 };
1827718248
18278 const src_loc_ty = try pt.getBuiltinType("SourceLocation");
18249 const src_loc_ty = try sema.getBuiltinType("SourceLocation");
1827918250 const fields = .{
1828018251 // module: [:0]const u8,
1828118252 module_name_val,
......@@ -18302,7 +18273,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1830218273 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1830318274 const src = block.nodeOffset(inst_data.src_node);
1830418275 const ty = try sema.resolveType(block, src, inst_data.operand);
18305 const type_info_ty = try pt.getBuiltinType("Type");
18276 const type_info_ty = try sema.getBuiltinType("Type");
1830618277 const type_info_tag_ty = type_info_ty.unionTagType(zcu).?;
1830718278
1830818279 if (ty.typeDeclInst(zcu)) |type_decl_inst| {
......@@ -18319,29 +18290,11 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1831918290 .undefined,
1832018291 .null,
1832118292 .enum_literal,
18322 => |type_info_tag| return Air.internedToRef((try pt.intern(.{ .un = .{
18323 .ty = type_info_ty.toIntern(),
18324 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(type_info_tag))).toIntern(),
18325 .val = .void_value,
18326 } }))),
18327 .@"fn" => {
18328 const fn_info_nav = try sema.namespaceLookup(
18329 block,
18330 src,
18331 type_info_ty.getNamespaceIndex(zcu),
18332 try ip.getOrPutString(gpa, pt.tid, "Fn", .no_embedded_nulls),
18333 ) orelse @panic("std.builtin.Type is corrupt");
18334 try sema.ensureNavResolved(src, fn_info_nav);
18335 const fn_info_ty = Type.fromInterned(ip.getNav(fn_info_nav).status.resolved.val);
18293 => |type_info_tag| return unionInitFromEnumTag(sema, block, src, type_info_ty, @intFromEnum(type_info_tag), .void_value),
1833618294
18337 const param_info_nav = try sema.namespaceLookup(
18338 block,
18339 src,
18340 fn_info_ty.getNamespaceIndex(zcu),
18341 try ip.getOrPutString(gpa, pt.tid, "Param", .no_embedded_nulls),
18342 ) orelse @panic("std.builtin.Type is corrupt");
18343 try sema.ensureNavResolved(src, param_info_nav);
18344 const param_info_ty = Type.fromInterned(ip.getNav(param_info_nav).status.resolved.val);
18295 .@"fn" => {
18296 const fn_info_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "Fn");
18297 const param_info_ty = try getBuiltinInnerType(sema, block, src, fn_info_ty, "Type.Fn", "Param");
1834518298
1834618299 const func_ty_info = zcu.typeToFunc(ty).?;
1834718300 const param_vals = try sema.arena.alloc(InternPool.Index, func_ty_info.param_types.len);
......@@ -18411,7 +18364,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1841118364 func_ty_info.return_type,
1841218365 } });
1841318366
18414 const callconv_ty = try pt.getBuiltinType("CallingConvention");
18367 const callconv_ty = try sema.getBuiltinType("CallingConvention");
1841518368
1841618369 const field_values = .{
1841718370 // calling_convention: CallingConvention,
......@@ -18425,26 +18378,18 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1842518378 // args: []const Fn.Param,
1842618379 args_val,
1842718380 };
18428 return Air.internedToRef((try pt.intern(.{ .un = .{
18381 return Air.internedToRef((try pt.internUnion(.{
1842918382 .ty = type_info_ty.toIntern(),
1843018383 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.@"fn"))).toIntern(),
1843118384 .val = try pt.intern(.{ .aggregate = .{
1843218385 .ty = fn_info_ty.toIntern(),
1843318386 .storage = .{ .elems = &field_values },
1843418387 } }),
18435 } })));
18388 })));
1843618389 },
1843718390 .int => {
18438 const int_info_nav = try sema.namespaceLookup(
18439 block,
18440 src,
18441 type_info_ty.getNamespaceIndex(zcu),
18442 try ip.getOrPutString(gpa, pt.tid, "Int", .no_embedded_nulls),
18443 ) orelse @panic("std.builtin.Type is corrupt");
18444 try sema.ensureNavResolved(src, int_info_nav);
18445 const int_info_ty = Type.fromInterned(ip.getNav(int_info_nav).status.resolved.val);
18446
18447 const signedness_ty = try pt.getBuiltinType("Signedness");
18391 const int_info_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "Int");
18392 const signedness_ty = try sema.getBuiltinType("Signedness");
1844818393 const info = ty.intInfo(zcu);
1844918394 const field_values = .{
1845018395 // signedness: Signedness,
......@@ -18452,37 +18397,30 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1845218397 // bits: u16,
1845318398 (try pt.intValue(Type.u16, info.bits)).toIntern(),
1845418399 };
18455 return Air.internedToRef((try pt.intern(.{ .un = .{
18400 return Air.internedToRef((try pt.internUnion(.{
1845618401 .ty = type_info_ty.toIntern(),
1845718402 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.int))).toIntern(),
1845818403 .val = try pt.intern(.{ .aggregate = .{
1845918404 .ty = int_info_ty.toIntern(),
1846018405 .storage = .{ .elems = &field_values },
1846118406 } }),
18462 } })));
18407 })));
1846318408 },
1846418409 .float => {
18465 const float_info_nav = try sema.namespaceLookup(
18466 block,
18467 src,
18468 type_info_ty.getNamespaceIndex(zcu),
18469 try ip.getOrPutString(gpa, pt.tid, "Float", .no_embedded_nulls),
18470 ) orelse @panic("std.builtin.Type is corrupt");
18471 try sema.ensureNavResolved(src, float_info_nav);
18472 const float_info_ty = Type.fromInterned(ip.getNav(float_info_nav).status.resolved.val);
18410 const float_info_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "Float");
1847318411
1847418412 const field_vals = .{
1847518413 // bits: u16,
1847618414 (try pt.intValue(Type.u16, ty.bitSize(zcu))).toIntern(),
1847718415 };
18478 return Air.internedToRef((try pt.intern(.{ .un = .{
18416 return Air.internedToRef((try pt.internUnion(.{
1847918417 .ty = type_info_ty.toIntern(),
1848018418 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.float))).toIntern(),
1848118419 .val = try pt.intern(.{ .aggregate = .{
1848218420 .ty = float_info_ty.toIntern(),
1848318421 .storage = .{ .elems = &field_vals },
1848418422 } }),
18485 } })));
18423 })));
1848618424 },
1848718425 .pointer => {
1848818426 const info = ty.ptrInfo(zcu);
......@@ -18491,27 +18429,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1849118429 else
1849218430 try Type.fromInterned(info.child).lazyAbiAlignment(pt);
1849318431
18494 const addrspace_ty = try pt.getBuiltinType("AddressSpace");
18495 const pointer_ty = t: {
18496 const nav = try sema.namespaceLookup(
18497 block,
18498 src,
18499 (try pt.getBuiltinType("Type")).getNamespaceIndex(zcu),
18500 try ip.getOrPutString(gpa, pt.tid, "Pointer", .no_embedded_nulls),
18501 ) orelse @panic("std.builtin.Type is corrupt");
18502 try sema.ensureNavResolved(src, nav);
18503 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
18504 };
18505 const ptr_size_ty = t: {
18506 const nav = try sema.namespaceLookup(
18507 block,
18508 src,
18509 pointer_ty.getNamespaceIndex(zcu),
18510 try ip.getOrPutString(gpa, pt.tid, "Size", .no_embedded_nulls),
18511 ) orelse @panic("std.builtin.Type is corrupt");
18512 try sema.ensureNavResolved(src, nav);
18513 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
18514 };
18432 const addrspace_ty = try sema.getBuiltinType("AddressSpace");
18433 const pointer_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "Pointer");
18434 const ptr_size_ty = try getBuiltinInnerType(sema, block, src, pointer_ty, "Type.Pointer", "Size");
1851518435
1851618436 const field_values = .{
1851718437 // size: Size,
......@@ -18534,26 +18454,17 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1853418454 else => Value.fromInterned(info.sentinel),
1853518455 })).toIntern(),
1853618456 };
18537 return Air.internedToRef((try pt.intern(.{ .un = .{
18457 return Air.internedToRef((try pt.internUnion(.{
1853818458 .ty = type_info_ty.toIntern(),
1853918459 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.pointer))).toIntern(),
1854018460 .val = try pt.intern(.{ .aggregate = .{
1854118461 .ty = pointer_ty.toIntern(),
1854218462 .storage = .{ .elems = &field_values },
1854318463 } }),
18544 } })));
18464 })));
1854518465 },
1854618466 .array => {
18547 const array_field_ty = t: {
18548 const nav = try sema.namespaceLookup(
18549 block,
18550 src,
18551 type_info_ty.getNamespaceIndex(zcu),
18552 try ip.getOrPutString(gpa, pt.tid, "Array", .no_embedded_nulls),
18553 ) orelse @panic("std.builtin.Type is corrupt");
18554 try sema.ensureNavResolved(src, nav);
18555 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
18556 };
18467 const array_field_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "Array");
1855718468
1855818469 const info = ty.arrayInfo(zcu);
1855918470 const field_values = .{
......@@ -18564,26 +18475,17 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1856418475 // sentinel: ?*const anyopaque,
1856518476 (try sema.optRefValue(info.sentinel)).toIntern(),
1856618477 };
18567 return Air.internedToRef((try pt.intern(.{ .un = .{
18478 return Air.internedToRef((try pt.internUnion(.{
1856818479 .ty = type_info_ty.toIntern(),
1856918480 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.array))).toIntern(),
1857018481 .val = try pt.intern(.{ .aggregate = .{
1857118482 .ty = array_field_ty.toIntern(),
1857218483 .storage = .{ .elems = &field_values },
1857318484 } }),
18574 } })));
18485 })));
1857518486 },
1857618487 .vector => {
18577 const vector_field_ty = t: {
18578 const nav = try sema.namespaceLookup(
18579 block,
18580 src,
18581 type_info_ty.getNamespaceIndex(zcu),
18582 try ip.getOrPutString(gpa, pt.tid, "Vector", .no_embedded_nulls),
18583 ) orelse @panic("std.builtin.Type is corrupt");
18584 try sema.ensureNavResolved(src, nav);
18585 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
18586 };
18488 const vector_field_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "Vector");
1858718489
1858818490 const info = ty.arrayInfo(zcu);
1858918491 const field_values = .{
......@@ -18592,52 +18494,34 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1859218494 // child: type,
1859318495 info.elem_type.toIntern(),
1859418496 };
18595 return Air.internedToRef((try pt.intern(.{ .un = .{
18497 return Air.internedToRef((try pt.internUnion(.{
1859618498 .ty = type_info_ty.toIntern(),
1859718499 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.vector))).toIntern(),
1859818500 .val = try pt.intern(.{ .aggregate = .{
1859918501 .ty = vector_field_ty.toIntern(),
1860018502 .storage = .{ .elems = &field_values },
1860118503 } }),
18602 } })));
18504 })));
1860318505 },
1860418506 .optional => {
18605 const optional_field_ty = t: {
18606 const nav = try sema.namespaceLookup(
18607 block,
18608 src,
18609 type_info_ty.getNamespaceIndex(zcu),
18610 try ip.getOrPutString(gpa, pt.tid, "Optional", .no_embedded_nulls),
18611 ) orelse @panic("std.builtin.Type is corrupt");
18612 try sema.ensureNavResolved(src, nav);
18613 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
18614 };
18507 const optional_field_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "Optional");
1861518508
1861618509 const field_values = .{
1861718510 // child: type,
1861818511 ty.optionalChild(zcu).toIntern(),
1861918512 };
18620 return Air.internedToRef((try pt.intern(.{ .un = .{
18513 return Air.internedToRef((try pt.internUnion(.{
1862118514 .ty = type_info_ty.toIntern(),
1862218515 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.optional))).toIntern(),
1862318516 .val = try pt.intern(.{ .aggregate = .{
1862418517 .ty = optional_field_ty.toIntern(),
1862518518 .storage = .{ .elems = &field_values },
1862618519 } }),
18627 } })));
18520 })));
1862818521 },
1862918522 .error_set => {
1863018523 // Get the Error type
18631 const error_field_ty = t: {
18632 const nav = try sema.namespaceLookup(
18633 block,
18634 src,
18635 type_info_ty.getNamespaceIndex(zcu),
18636 try ip.getOrPutString(gpa, pt.tid, "Error", .no_embedded_nulls),
18637 ) orelse @panic("std.builtin.Type is corrupt");
18638 try sema.ensureNavResolved(src, nav);
18639 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
18640 };
18524 const error_field_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "Error");
1864118525
1864218526 // Build our list of Error values
1864318527 // Optional value is only null if anyerror
......@@ -18726,23 +18610,14 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1872618610 } });
1872718611
1872818612 // Construct Type{ .error_set = errors_val }
18729 return Air.internedToRef((try pt.intern(.{ .un = .{
18613 return Air.internedToRef((try pt.internUnion(.{
1873018614 .ty = type_info_ty.toIntern(),
1873118615 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.error_set))).toIntern(),
1873218616 .val = errors_val,
18733 } })));
18617 })));
1873418618 },
1873518619 .error_union => {
18736 const error_union_field_ty = t: {
18737 const nav = try sema.namespaceLookup(
18738 block,
18739 src,
18740 type_info_ty.getNamespaceIndex(zcu),
18741 try ip.getOrPutString(gpa, pt.tid, "ErrorUnion", .no_embedded_nulls),
18742 ) orelse @panic("std.builtin.Type is corrupt");
18743 try sema.ensureNavResolved(src, nav);
18744 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
18745 };
18620 const error_union_field_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "ErrorUnion");
1874618621
1874718622 const field_values = .{
1874818623 // error_set: type,
......@@ -18750,28 +18625,19 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1875018625 // payload: type,
1875118626 ty.errorUnionPayload(zcu).toIntern(),
1875218627 };
18753 return Air.internedToRef((try pt.intern(.{ .un = .{
18628 return Air.internedToRef((try pt.internUnion(.{
1875418629 .ty = type_info_ty.toIntern(),
1875518630 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.error_union))).toIntern(),
1875618631 .val = try pt.intern(.{ .aggregate = .{
1875718632 .ty = error_union_field_ty.toIntern(),
1875818633 .storage = .{ .elems = &field_values },
1875918634 } }),
18760 } })));
18635 })));
1876118636 },
1876218637 .@"enum" => {
1876318638 const is_exhaustive = Value.makeBool(ip.loadEnumType(ty.toIntern()).tag_mode != .nonexhaustive);
1876418639
18765 const enum_field_ty = t: {
18766 const nav = try sema.namespaceLookup(
18767 block,
18768 src,
18769 type_info_ty.getNamespaceIndex(zcu),
18770 try ip.getOrPutString(gpa, pt.tid, "EnumField", .no_embedded_nulls),
18771 ) orelse @panic("std.builtin.Type is corrupt");
18772 try sema.ensureNavResolved(src, nav);
18773 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
18774 };
18640 const enum_field_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "EnumField");
1877518641
1877618642 const enum_field_vals = try sema.arena.alloc(InternPool.Index, ip.loadEnumType(ty.toIntern()).names.len);
1877718643 for (enum_field_vals, 0..) |*field_val, tag_index| {
......@@ -18858,16 +18724,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1885818724
1885918725 const decls_val = try sema.typeInfoDecls(block, src, type_info_ty, ip.loadEnumType(ty.toIntern()).namespace.toOptional());
1886018726
18861 const type_enum_ty = t: {
18862 const nav = try sema.namespaceLookup(
18863 block,
18864 src,
18865 type_info_ty.getNamespaceIndex(zcu),
18866 try ip.getOrPutString(gpa, pt.tid, "Enum", .no_embedded_nulls),
18867 ) orelse @panic("std.builtin.Type is corrupt");
18868 try sema.ensureNavResolved(src, nav);
18869 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
18870 };
18727 const type_enum_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "Enum");
1887118728
1887218729 const field_values = .{
1887318730 // tag_type: type,
......@@ -18879,37 +18736,18 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1887918736 // is_exhaustive: bool,
1888018737 is_exhaustive.toIntern(),
1888118738 };
18882 return Air.internedToRef((try pt.intern(.{ .un = .{
18739 return Air.internedToRef((try pt.internUnion(.{
1888318740 .ty = type_info_ty.toIntern(),
1888418741 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.@"enum"))).toIntern(),
1888518742 .val = try pt.intern(.{ .aggregate = .{
1888618743 .ty = type_enum_ty.toIntern(),
1888718744 .storage = .{ .elems = &field_values },
1888818745 } }),
18889 } })));
18746 })));
1889018747 },
1889118748 .@"union" => {
18892 const type_union_ty = t: {
18893 const nav = try sema.namespaceLookup(
18894 block,
18895 src,
18896 type_info_ty.getNamespaceIndex(zcu),
18897 try ip.getOrPutString(gpa, pt.tid, "Union", .no_embedded_nulls),
18898 ) orelse @panic("std.builtin.Type is corrupt");
18899 try sema.ensureNavResolved(src, nav);
18900 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
18901 };
18902
18903 const union_field_ty = t: {
18904 const nav = try sema.namespaceLookup(
18905 block,
18906 src,
18907 type_info_ty.getNamespaceIndex(zcu),
18908 try ip.getOrPutString(gpa, pt.tid, "UnionField", .no_embedded_nulls),
18909 ) orelse @panic("std.builtin.Type is corrupt");
18910 try sema.ensureNavResolved(src, nav);
18911 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
18912 };
18749 const type_union_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "Union");
18750 const union_field_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "UnionField");
1891318751
1891418752 try ty.resolveLayout(pt); // Getting alignment requires type layout
1891518753 const union_obj = zcu.typeToUnion(ty).?;
......@@ -19004,16 +18842,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1900418842 .val = if (ty.unionTagType(zcu)) |tag_ty| tag_ty.toIntern() else .none,
1900518843 } });
1900618844
19007 const container_layout_ty = t: {
19008 const nav = try sema.namespaceLookup(
19009 block,
19010 src,
19011 (try pt.getBuiltinType("Type")).getNamespaceIndex(zcu),
19012 try ip.getOrPutString(gpa, pt.tid, "ContainerLayout", .no_embedded_nulls),
19013 ) orelse @panic("std.builtin.Type is corrupt");
19014 try sema.ensureNavResolved(src, nav);
19015 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
19016 };
18845 const container_layout_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "ContainerLayout");
1901718846
1901818847 const field_values = .{
1901918848 // layout: ContainerLayout,
......@@ -19026,37 +18855,18 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1902618855 // decls: []const Declaration,
1902718856 decls_val,
1902818857 };
19029 return Air.internedToRef((try pt.intern(.{ .un = .{
18858 return Air.internedToRef((try pt.internUnion(.{
1903018859 .ty = type_info_ty.toIntern(),
1903118860 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.@"union"))).toIntern(),
1903218861 .val = try pt.intern(.{ .aggregate = .{
1903318862 .ty = type_union_ty.toIntern(),
1903418863 .storage = .{ .elems = &field_values },
1903518864 } }),
19036 } })));
18865 })));
1903718866 },
1903818867 .@"struct" => {
19039 const type_struct_ty = t: {
19040 const nav = try sema.namespaceLookup(
19041 block,
19042 src,
19043 type_info_ty.getNamespaceIndex(zcu),
19044 try ip.getOrPutString(gpa, pt.tid, "Struct", .no_embedded_nulls),
19045 ) orelse @panic("std.builtin.Type is corrupt");
19046 try sema.ensureNavResolved(src, nav);
19047 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
19048 };
19049
19050 const struct_field_ty = t: {
19051 const nav = try sema.namespaceLookup(
19052 block,
19053 src,
19054 type_info_ty.getNamespaceIndex(zcu),
19055 try ip.getOrPutString(gpa, pt.tid, "StructField", .no_embedded_nulls),
19056 ) orelse @panic("std.builtin.Type is corrupt");
19057 try sema.ensureNavResolved(src, nav);
19058 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
19059 };
18868 const type_struct_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "Struct");
18869 const struct_field_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "StructField");
1906018870
1906118871 try ty.resolveLayout(pt); // Getting alignment requires type layout
1906218872
......@@ -19233,16 +19043,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1923319043 } else .none,
1923419044 } });
1923519045
19236 const container_layout_ty = t: {
19237 const nav = try sema.namespaceLookup(
19238 block,
19239 src,
19240 (try pt.getBuiltinType("Type")).getNamespaceIndex(zcu),
19241 try ip.getOrPutString(gpa, pt.tid, "ContainerLayout", .no_embedded_nulls),
19242 ) orelse @panic("std.builtin.Type is corrupt");
19243 try sema.ensureNavResolved(src, nav);
19244 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
19245 };
19046 const container_layout_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "ContainerLayout");
1924619047
1924719048 const layout = ty.containerLayout(zcu);
1924819049
......@@ -19258,26 +19059,17 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1925819059 // is_tuple: bool,
1925919060 Value.makeBool(ty.isTuple(zcu)).toIntern(),
1926019061 };
19261 return Air.internedToRef((try pt.intern(.{ .un = .{
19062 return Air.internedToRef((try pt.internUnion(.{
1926219063 .ty = type_info_ty.toIntern(),
1926319064 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.@"struct"))).toIntern(),
1926419065 .val = try pt.intern(.{ .aggregate = .{
1926519066 .ty = type_struct_ty.toIntern(),
1926619067 .storage = .{ .elems = &field_values },
1926719068 } }),
19268 } })));
19069 })));
1926919070 },
1927019071 .@"opaque" => {
19271 const type_opaque_ty = t: {
19272 const nav = try sema.namespaceLookup(
19273 block,
19274 src,
19275 type_info_ty.getNamespaceIndex(zcu),
19276 try ip.getOrPutString(gpa, pt.tid, "Opaque", .no_embedded_nulls),
19277 ) orelse @panic("std.builtin.Type is corrupt");
19278 try sema.ensureNavResolved(src, nav);
19279 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
19280 };
19072 const type_opaque_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "Opaque");
1928119073
1928219074 try ty.resolveFields(pt);
1928319075 const decls_val = try sema.typeInfoDecls(block, src, type_info_ty, ty.getNamespace(zcu));
......@@ -19286,14 +19078,14 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1928619078 // decls: []const Declaration,
1928719079 decls_val,
1928819080 };
19289 return Air.internedToRef((try pt.intern(.{ .un = .{
19081 return Air.internedToRef((try pt.internUnion(.{
1929019082 .ty = type_info_ty.toIntern(),
1929119083 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.@"opaque"))).toIntern(),
1929219084 .val = try pt.intern(.{ .aggregate = .{
1929319085 .ty = type_opaque_ty.toIntern(),
1929419086 .storage = .{ .elems = &field_values },
1929519087 } }),
19296 } })));
19088 })));
1929719089 },
1929819090 .frame => return sema.failWithUseOfAsync(block, src),
1929919091 .@"anyframe" => return sema.failWithUseOfAsync(block, src),
......@@ -19309,19 +19101,9 @@ fn typeInfoDecls(
1930919101) CompileError!InternPool.Index {
1931019102 const pt = sema.pt;
1931119103 const zcu = pt.zcu;
19312 const ip = &zcu.intern_pool;
1931319104 const gpa = sema.gpa;
1931419105
19315 const declaration_ty = t: {
19316 const nav = try sema.namespaceLookup(
19317 block,
19318 src,
19319 type_info_ty.getNamespaceIndex(zcu),
19320 try ip.getOrPutString(gpa, pt.tid, "Declaration", .no_embedded_nulls),
19321 ) orelse @panic("std.builtin.Type is corrupt");
19322 try sema.ensureNavResolved(src, nav);
19323 break :t Type.fromInterned(ip.getNav(nav).status.resolved.val);
19324 };
19106 const declaration_ty = try getBuiltinInnerType(sema, block, src, type_info_ty, "Type", "Declaration");
1932519107
1932619108 var decl_vals = std.ArrayList(InternPool.Index).init(gpa);
1932719109 defer decl_vals.deinit();
......@@ -20265,11 +20047,11 @@ fn retWithErrTracing(
2026520047 else => true,
2026620048 };
2026720049 const gpa = sema.gpa;
20268 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
20050 const stack_trace_ty = try sema.getBuiltinType("StackTrace");
2026920051 try stack_trace_ty.resolveFields(pt);
2027020052 const ptr_stack_trace_ty = try pt.singleMutPtrType(stack_trace_ty);
2027120053 const err_return_trace = try block.addTy(.err_return_trace, ptr_stack_trace_ty);
20272 const return_err_fn = try pt.getBuiltin("returnError");
20054 const return_err_fn = try sema.getBuiltin("returnError");
2027320055 const args: [1]Air.Inst.Ref = .{err_return_trace};
2027420056
2027520057 if (!need_check) {
......@@ -20805,19 +20587,32 @@ fn unionInit(
2080520587 const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_src);
2080620588 const field_ty = Type.fromInterned(zcu.typeToUnion(union_ty).?.field_types.get(ip)[field_index]);
2080720589 const init = try sema.coerce(block, field_ty, uncasted_init, init_src);
20590 _ = union_ty_src;
20591 return unionInitFromEnumTag(sema, block, init_src, union_ty, field_index, init);
20592}
20593
20594fn unionInitFromEnumTag(
20595 sema: *Sema,
20596 block: *Block,
20597 init_src: LazySrcLoc,
20598 union_ty: Type,
20599 field_index: u32,
20600 init: Air.Inst.Ref,
20601) !Air.Inst.Ref {
20602 const pt = sema.pt;
20603 const zcu = pt.zcu;
2080820604
2080920605 if (try sema.resolveValue(init)) |init_val| {
2081020606 const tag_ty = union_ty.unionTagTypeHypothetical(zcu);
2081120607 const tag_val = try pt.enumValueFieldIndex(tag_ty, field_index);
20812 return Air.internedToRef((try pt.intern(.{ .un = .{
20608 return Air.internedToRef((try pt.internUnion(.{
2081320609 .ty = union_ty.toIntern(),
2081420610 .tag = tag_val.toIntern(),
2081520611 .val = init_val.toIntern(),
20816 } })));
20612 })));
2081720613 }
2081820614
2081920615 try sema.requireRuntimeBlock(block, init_src, null);
20820 _ = union_ty_src;
2082120616 return block.addUnionInit(union_ty, field_index, init);
2082220617}
2082320618
......@@ -20949,11 +20744,11 @@ fn zirStructInit(
2094920744 const init_inst = try sema.coerce(block, field_ty, uncoerced_init_inst, field_src);
2095020745
2095120746 if (try sema.resolveValue(init_inst)) |val| {
20952 const struct_val = Value.fromInterned(try pt.intern(.{ .un = .{
20747 const struct_val = Value.fromInterned(try pt.internUnion(.{
2095320748 .ty = resolved_ty.toIntern(),
2095420749 .tag = tag_val.toIntern(),
2095520750 .val = val.toIntern(),
20956 } }));
20751 }));
2095720752 const final_val_inst = try sema.coerce(block, result_ty, Air.internedToRef(struct_val.toIntern()), src);
2095820753 const final_val = (try sema.resolveValue(final_val_inst)).?;
2095920754 return sema.addConstantMaybeRef(final_val.toIntern(), is_ref);
......@@ -21660,7 +21455,7 @@ fn getErrorReturnTrace(sema: *Sema, block: *Block) CompileError!Air.Inst.Ref {
2166021455 const pt = sema.pt;
2166121456 const zcu = pt.zcu;
2166221457 const ip = &zcu.intern_pool;
21663 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
21458 const stack_trace_ty = try sema.getBuiltinType("StackTrace");
2166421459 try stack_trace_ty.resolveFields(pt);
2166521460 const ptr_stack_trace_ty = try pt.singleMutPtrType(stack_trace_ty);
2166621461 const opt_ptr_stack_trace_ty = try pt.optionalType(ptr_stack_trace_ty.toIntern());
......@@ -21873,7 +21668,6 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2187321668 const pt = sema.pt;
2187421669 const zcu = pt.zcu;
2187521670 const ip = &zcu.intern_pool;
21876
2187721671 try operand_ty.resolveLayout(pt);
2187821672 const enum_ty = switch (operand_ty.zigTypeTag(zcu)) {
2187921673 .enum_literal => {
......@@ -21950,7 +21744,7 @@ fn zirReify(
2195021744 },
2195121745 },
2195221746 };
21953 const type_info_ty = try pt.getBuiltinType("Type");
21747 const type_info_ty = try sema.getBuiltinType("Type");
2195421748 const uncasted_operand = try sema.resolveInst(extra.operand);
2195521749 const type_info = try sema.coerce(block, type_info_ty, uncasted_operand, operand_src);
2195621750 const val = try sema.resolveConstDefinedValue(block, operand_src, type_info, .{
......@@ -23152,7 +22946,7 @@ fn reifyStruct(
2315222946
2315322947fn resolveVaListRef(sema: *Sema, block: *Block, src: LazySrcLoc, zir_ref: Zir.Inst.Ref) CompileError!Air.Inst.Ref {
2315422948 const pt = sema.pt;
23155 const va_list_ty = try pt.getBuiltinType("VaList");
22949 const va_list_ty = try sema.getBuiltinType("VaList");
2315622950 const va_list_ptr = try pt.singleMutPtrType(va_list_ty);
2315722951
2315822952 const inst = try sema.resolveInst(zir_ref);
......@@ -23191,7 +22985,7 @@ fn zirCVaCopy(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData)
2319122985 const va_list_src = block.builtinCallArgSrc(extra.node, 0);
2319222986
2319322987 const va_list_ref = try sema.resolveVaListRef(block, va_list_src, extra.operand);
23194 const va_list_ty = try sema.pt.getBuiltinType("VaList");
22988 const va_list_ty = try sema.getBuiltinType("VaList");
2319522989
2319622990 try sema.requireRuntimeBlock(block, src, null);
2319722991 return block.addTyOp(.c_va_copy, va_list_ty, va_list_ref);
......@@ -23211,7 +23005,7 @@ fn zirCVaEnd(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) C
2321123005fn zirCVaStart(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
2321223006 const src = block.nodeOffset(@bitCast(extended.operand));
2321323007
23214 const va_list_ty = try sema.pt.getBuiltinType("VaList");
23008 const va_list_ty = try sema.getBuiltinType("VaList");
2321523009 try sema.requireRuntimeBlock(block, src, null);
2321623010 return block.addInst(.{
2321723011 .tag = .c_va_start,
......@@ -24823,7 +24617,7 @@ fn resolveExportOptions(
2482324617 const zcu = pt.zcu;
2482424618 const gpa = sema.gpa;
2482524619 const ip = &zcu.intern_pool;
24826 const export_options_ty = try pt.getBuiltinType("ExportOptions");
24620 const export_options_ty = try sema.getBuiltinType("ExportOptions");
2482724621 const air_ref = try sema.resolveInst(zir_ref);
2482824622 const options = try sema.coerce(block, export_options_ty, air_ref, src);
2482924623
......@@ -24887,7 +24681,7 @@ fn resolveBuiltinEnum(
2488724681 reason: NeededComptimeReason,
2488824682) CompileError!@field(std.builtin, name) {
2488924683 const pt = sema.pt;
24890 const ty = try pt.getBuiltinType(name);
24684 const ty = try sema.getBuiltinType(name);
2489124685 const air_ref = try sema.resolveInst(zir_ref);
2489224686 const coerced = try sema.coerce(block, ty, air_ref, src);
2489324687 const val = try sema.resolveConstDefinedValue(block, src, coerced, reason);
......@@ -25656,7 +25450,7 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2565625450 const extra = sema.code.extraData(Zir.Inst.BuiltinCall, inst_data.payload_index).data;
2565725451 const func = try sema.resolveInst(extra.callee);
2565825452
25659 const modifier_ty = try pt.getBuiltinType("CallModifier");
25453 const modifier_ty = try sema.getBuiltinType("CallModifier");
2566025454 const air_ref = try sema.resolveInst(extra.modifier);
2566125455 const modifier_ref = try sema.coerce(block, modifier_ty, air_ref, modifier_src);
2566225456 const modifier_val = try sema.resolveConstDefinedValue(block, modifier_src, modifier_ref, .{
......@@ -26782,7 +26576,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2678226576 const body = sema.code.bodySlice(extra_index, body_len);
2678326577 extra_index += body.len;
2678426578
26785 const addrspace_ty = try pt.getBuiltinType("AddressSpace");
26579 const addrspace_ty = try sema.getBuiltinType("AddressSpace");
2678626580 const val = try sema.resolveGenericBody(block, addrspace_src, body, inst, addrspace_ty, .{
2678726581 .needed_comptime_reason = "addrspace must be comptime-known",
2678826582 });
......@@ -26793,7 +26587,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2679326587 } else if (extra.data.bits.has_addrspace_ref) blk: {
2679426588 const addrspace_ref: Zir.Inst.Ref = @enumFromInt(sema.code.extra[extra_index]);
2679526589 extra_index += 1;
26796 const addrspace_ty = try pt.getBuiltinType("AddressSpace");
26590 const addrspace_ty = try sema.getBuiltinType("AddressSpace");
2679726591 const uncoerced_addrspace = sema.resolveInst(addrspace_ref) catch |err| switch (err) {
2679826592 error.GenericPoison => break :blk null,
2679926593 else => |e| return e,
......@@ -26847,7 +26641,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2684726641 const body = sema.code.bodySlice(extra_index, body_len);
2684826642 extra_index += body.len;
2684926643
26850 const cc_ty = try pt.getBuiltinType("CallingConvention");
26644 const cc_ty = try sema.getBuiltinType("CallingConvention");
2685126645 const val = try sema.resolveGenericBody(block, cc_src, body, inst, cc_ty, .{
2685226646 .needed_comptime_reason = "calling convention must be comptime-known",
2685326647 });
......@@ -26858,7 +26652,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2685826652 } else if (extra.data.bits.has_cc_ref) blk: {
2685926653 const cc_ref: Zir.Inst.Ref = @enumFromInt(sema.code.extra[extra_index]);
2686026654 extra_index += 1;
26861 const cc_ty = try pt.getBuiltinType("CallingConvention");
26655 const cc_ty = try sema.getBuiltinType("CallingConvention");
2686226656 const uncoerced_cc = sema.resolveInst(cc_ref) catch |err| switch (err) {
2686326657 error.GenericPoison => break :blk null,
2686426658 else => |e| return e,
......@@ -27075,7 +26869,7 @@ fn resolvePrefetchOptions(
2707526869 const zcu = pt.zcu;
2707626870 const gpa = sema.gpa;
2707726871 const ip = &zcu.intern_pool;
27078 const options_ty = try pt.getBuiltinType("PrefetchOptions");
26872 const options_ty = try sema.getBuiltinType("PrefetchOptions");
2707926873 const options = try sema.coerce(block, options_ty, try sema.resolveInst(zir_ref), src);
2708026874
2708126875 const rw_src = block.src(.{ .init_field_rw = src.offset.node_offset_builtin_call_arg.builtin_call_node });
......@@ -27148,7 +26942,7 @@ fn resolveExternOptions(
2714826942 const gpa = sema.gpa;
2714926943 const ip = &zcu.intern_pool;
2715026944 const options_inst = try sema.resolveInst(zir_ref);
27151 const extern_options_ty = try pt.getBuiltinType("ExternOptions");
26945 const extern_options_ty = try sema.getBuiltinType("ExternOptions");
2715226946 const options = try sema.coerce(block, extern_options_ty, options_inst, src);
2715326947
2715426948 const name_src = block.src(.{ .init_field_name = src.offset.node_offset_builtin_call_arg.builtin_call_node });
......@@ -27335,7 +27129,7 @@ fn zirBuiltinValue(sema: *Sema, extended: Zir.Inst.Extended.InstData) CompileErr
2733527129
2733627130 // Values are handled here.
2733727131 .calling_convention_c => {
27338 const callconv_ty = try pt.getBuiltinType("CallingConvention");
27132 const callconv_ty = try sema.getBuiltinType("CallingConvention");
2733927133 comptime assert(@intFromEnum(std.builtin.CallingConvention.C) == 1);
2734027134 const val = try pt.intern(.{ .enum_tag = .{
2734127135 .ty = callconv_ty.toIntern(),
......@@ -27344,7 +27138,7 @@ fn zirBuiltinValue(sema: *Sema, extended: Zir.Inst.Extended.InstData) CompileErr
2734427138 return Air.internedToRef(val);
2734527139 },
2734627140 .calling_convention_inline => {
27347 const callconv_ty = try pt.getBuiltinType("CallingConvention");
27141 const callconv_ty = try sema.getBuiltinType("CallingConvention");
2734827142 comptime assert(@intFromEnum(std.builtin.CallingConvention.Inline) == 4);
2734927143 const val = try pt.intern(.{ .enum_tag = .{
2735027144 .ty = callconv_ty.toIntern(),
......@@ -27353,7 +27147,7 @@ fn zirBuiltinValue(sema: *Sema, extended: Zir.Inst.Extended.InstData) CompileErr
2735327147 return Air.internedToRef(val);
2735427148 },
2735527149 };
27356 const ty = try pt.getBuiltinType(type_name);
27150 const ty = try sema.getBuiltinType(type_name);
2735727151 return Air.internedToRef(ty.toIntern());
2735827152}
2735927153
......@@ -27392,7 +27186,7 @@ fn zirBranchHint(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstDat
2739227186 const uncoerced_hint = try sema.resolveInst(extra.operand);
2739327187 const operand_src = block.builtinCallArgSrc(extra.node, 0);
2739427188
27395 const hint_ty = try pt.getBuiltinType("BranchHint");
27189 const hint_ty = try sema.getBuiltinType("BranchHint");
2739627190 const coerced_hint = try sema.coerce(block, hint_ty, uncoerced_hint, operand_src);
2739727191 const hint_val = try sema.resolveConstDefinedValue(block, operand_src, coerced_hint, .{
2739827192 .needed_comptime_reason = "operand to '@branchHint' must be comptime-known",
......@@ -27845,18 +27639,14 @@ fn prepareSimplePanic(sema: *Sema, block: *Block, src: LazySrcLoc) !void {
2784527639 const zcu = pt.zcu;
2784627640
2784727641 if (zcu.panic_func_index == .none) {
27848 const fn_ref = try sema.analyzeNavVal(block, src, try pt.getBuiltinNav("panic"));
27849 const fn_val = try sema.resolveConstValue(block, src, fn_ref, .{
27850 .needed_comptime_reason = "panic handler must be comptime-known",
27851 });
27852 assert(fn_val.typeOf(zcu).zigTypeTag(zcu) == .@"fn");
27853 assert(try fn_val.typeOf(zcu).fnHasRuntimeBitsSema(pt));
27854 try zcu.ensureFuncBodyAnalysisQueued(fn_val.toIntern());
27855 zcu.panic_func_index = fn_val.toIntern();
27642 zcu.panic_func_index = try sema.getPanicInnerFn(block, src, "call");
27643 // Here, function body analysis must be queued up so that backends can
27644 // make calls to this function.
27645 try zcu.ensureFuncBodyAnalysisQueued(zcu.panic_func_index);
2785627646 }
2785727647
2785827648 if (zcu.null_stack_trace == .none) {
27859 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
27649 const stack_trace_ty = try sema.getBuiltinType("StackTrace");
2786027650 try stack_trace_ty.resolveFields(pt);
2786127651 const target = zcu.getTarget();
2786227652 const ptr_stack_trace_ty = try pt.ptrTypeSema(.{
......@@ -27884,14 +27674,15 @@ fn preparePanicId(sema: *Sema, block: *Block, src: LazySrcLoc, panic_id: Zcu.Pan
2788427674
2788527675 try sema.prepareSimplePanic(block, src);
2788627676
27887 const panic_messages_ty = try pt.getBuiltinType("panic_messages");
27677 const panic_ty = try sema.getBuiltinType("Panic");
27678 const panic_messages_ty = try sema.getBuiltinInnerType(block, src, panic_ty, "Panic", "messages");
2788827679 const msg_nav_index = (sema.namespaceLookup(
2788927680 block,
2789027681 LazySrcLoc.unneeded,
2789127682 panic_messages_ty.getNamespaceIndex(zcu),
2789227683 try zcu.intern_pool.getOrPutString(gpa, pt.tid, @tagName(panic_id), .no_embedded_nulls),
2789327684 ) catch |err| switch (err) {
27894 error.AnalysisFail => @panic("std.builtin.panic_messages is corrupt"),
27685 error.AnalysisFail => return error.AnalysisFail,
2789527686 error.GenericPoison, error.ComptimeReturn, error.ComptimeBreak => unreachable,
2789627687 error.OutOfMemory => |e| return e,
2789727688 }).?;
......@@ -28015,7 +27806,7 @@ fn panicWithMsg(sema: *Sema, block: *Block, src: LazySrcLoc, msg_inst: Air.Inst.
2801527806 try sema.callBuiltin(block, src, panic_fn, .auto, &.{ msg_inst, null_stack_trace, null_ret_addr }, operation);
2801627807}
2801727808
28018fn panicUnwrapError(
27809fn addSafetyCheckUnwrapError(
2801927810 sema: *Sema,
2802027811 parent_block: *Block,
2802127812 src: LazySrcLoc,
......@@ -28023,12 +27814,8 @@ fn panicUnwrapError(
2802327814 unwrap_err_tag: Air.Inst.Tag,
2802427815 is_non_err_tag: Air.Inst.Tag,
2802527816) !void {
28026 const pt = sema.pt;
2802727817 assert(!parent_block.is_comptime);
2802827818 const ok = try parent_block.addUnOp(is_non_err_tag, operand);
28029 if (!pt.zcu.comp.formatted_panics) {
28030 return sema.addSafetyCheck(parent_block, src, ok, .unwrap_error);
28031 }
2803227819 const gpa = sema.gpa;
2803327820
2803427821 var fail_block: Block = .{
......@@ -28044,21 +27831,26 @@ fn panicUnwrapError(
2804427831
2804527832 defer fail_block.instructions.deinit(gpa);
2804627833
28047 {
28048 if (!pt.zcu.backendSupportsFeature(.panic_unwrap_error)) {
28049 _ = try fail_block.addNoOp(.trap);
28050 } else {
28051 const panic_fn = try sema.pt.getBuiltin("panicUnwrapError");
28052 const err = try fail_block.addTyOp(unwrap_err_tag, Type.anyerror, operand);
28053 const err_return_trace = try sema.getErrorReturnTrace(&fail_block);
28054 const args: [2]Air.Inst.Ref = .{ err_return_trace, err };
28055 try sema.callBuiltin(&fail_block, src, panic_fn, .auto, &args, .@"safety check");
28056 }
28057 }
27834 const err = try fail_block.addTyOp(unwrap_err_tag, Type.anyerror, operand);
27835 try safetyPanicUnwrapError(sema, &fail_block, src, err);
27836
2805827837 try sema.addSafetyCheckExtra(parent_block, ok, &fail_block);
2805927838}
2806027839
28061fn panicIndexOutOfBounds(
27840fn safetyPanicUnwrapError(sema: *Sema, block: *Block, src: LazySrcLoc, err: Air.Inst.Ref) !void {
27841 const pt = sema.pt;
27842 const zcu = pt.zcu;
27843 if (!zcu.backendSupportsFeature(.panic_fn)) {
27844 _ = try block.addNoOp(.trap);
27845 } else {
27846 const panic_fn = try getPanicInnerFn(sema, block, src, "unwrapError");
27847 const err_return_trace = try sema.getErrorReturnTrace(block);
27848 const args: [2]Air.Inst.Ref = .{ err_return_trace, err };
27849 try sema.callBuiltin(block, src, Air.internedToRef(panic_fn), .auto, &args, .@"safety check");
27850 }
27851}
27852
27853fn addSafetyCheckIndexOob(
2806227854 sema: *Sema,
2806327855 parent_block: *Block,
2806427856 src: LazySrcLoc,
......@@ -28068,13 +27860,10 @@ fn panicIndexOutOfBounds(
2806827860) !void {
2806927861 assert(!parent_block.is_comptime);
2807027862 const ok = try parent_block.addBinOp(cmp_op, index, len);
28071 if (!sema.pt.zcu.comp.formatted_panics) {
28072 return sema.addSafetyCheck(parent_block, src, ok, .index_out_of_bounds);
28073 }
28074 try sema.safetyCheckFormatted(parent_block, src, ok, "panicOutOfBounds", &.{ index, len });
27863 return addSafetyCheckCall(sema, parent_block, src, ok, "outOfBounds", &.{ index, len });
2807527864}
2807627865
28077fn panicInactiveUnionField(
27866fn addSafetyCheckInactiveUnionField(
2807827867 sema: *Sema,
2807927868 parent_block: *Block,
2808027869 src: LazySrcLoc,
......@@ -28083,13 +27872,10 @@ fn panicInactiveUnionField(
2808327872) !void {
2808427873 assert(!parent_block.is_comptime);
2808527874 const ok = try parent_block.addBinOp(.cmp_eq, active_tag, wanted_tag);
28086 if (!sema.pt.zcu.comp.formatted_panics) {
28087 return sema.addSafetyCheck(parent_block, src, ok, .inactive_union_field);
28088 }
28089 try sema.safetyCheckFormatted(parent_block, src, ok, "panicInactiveUnionField", &.{ active_tag, wanted_tag });
27875 return addSafetyCheckCall(sema, parent_block, src, ok, "inactiveUnionField", &.{ active_tag, wanted_tag });
2809027876}
2809127877
28092fn panicSentinelMismatch(
27878fn addSafetyCheckSentinelMismatch(
2809327879 sema: *Sema,
2809427880 parent_block: *Block,
2809527881 src: LazySrcLoc,
......@@ -28114,8 +27900,7 @@ fn panicSentinelMismatch(
2811427900 };
2811527901
2811627902 const ok = if (sentinel_ty.zigTypeTag(zcu) == .vector) ok: {
28117 const eql =
28118 try parent_block.addCmpVector(expected_sentinel, actual_sentinel, .eq);
27903 const eql = try parent_block.addCmpVector(expected_sentinel, actual_sentinel, .eq);
2811927904 break :ok try parent_block.addInst(.{
2812027905 .tag = .reduce,
2812127906 .data = .{ .reduce = .{
......@@ -28128,24 +27913,23 @@ fn panicSentinelMismatch(
2812827913 break :ok try parent_block.addBinOp(.cmp_eq, expected_sentinel, actual_sentinel);
2812927914 };
2813027915
28131 if (!pt.zcu.comp.formatted_panics) {
28132 return sema.addSafetyCheck(parent_block, src, ok, .sentinel_mismatch);
28133 }
28134 try sema.safetyCheckFormatted(parent_block, src, ok, "panicSentinelMismatch", &.{ expected_sentinel, actual_sentinel });
27916 return addSafetyCheckCall(sema, parent_block, src, ok, "sentinelMismatch", &.{
27917 expected_sentinel, actual_sentinel,
27918 });
2813527919}
2813627920
28137fn safetyCheckFormatted(
27921fn addSafetyCheckCall(
2813827922 sema: *Sema,
2813927923 parent_block: *Block,
2814027924 src: LazySrcLoc,
2814127925 ok: Air.Inst.Ref,
28142 func: []const u8,
27926 func_name: []const u8,
2814327927 args: []const Air.Inst.Ref,
28144) CompileError!void {
27928) !void {
27929 assert(!parent_block.is_comptime);
27930 const gpa = sema.gpa;
2814527931 const pt = sema.pt;
2814627932 const zcu = pt.zcu;
28147 assert(zcu.comp.formatted_panics);
28148 const gpa = sema.gpa;
2814927933
2815027934 var fail_block: Block = .{
2815127935 .parent = parent_block,
......@@ -28160,12 +27944,13 @@ fn safetyCheckFormatted(
2816027944
2816127945 defer fail_block.instructions.deinit(gpa);
2816227946
28163 if (!zcu.backendSupportsFeature(.safety_check_formatted)) {
27947 if (!zcu.backendSupportsFeature(.panic_fn)) {
2816427948 _ = try fail_block.addNoOp(.trap);
2816527949 } else {
28166 const panic_fn = try pt.getBuiltin(func);
28167 try sema.callBuiltin(&fail_block, src, panic_fn, .auto, args, .@"safety check");
27950 const panic_fn = try getPanicInnerFn(sema, &fail_block, src, func_name);
27951 try sema.callBuiltin(&fail_block, src, Air.internedToRef(panic_fn), .auto, args, .@"safety check");
2816827952 }
27953
2816927954 try sema.addSafetyCheckExtra(parent_block, ok, &fail_block);
2817027955}
2817127956
......@@ -29229,7 +29014,7 @@ fn unionFieldPtr(
2922929014 // TODO would it be better if get_union_tag supported pointers to unions?
2923029015 const union_val = try block.addTyOp(.load, union_ty, union_ptr);
2923129016 const active_tag = try block.addTyOp(.get_union_tag, Type.fromInterned(union_obj.enum_tag_ty), union_val);
29232 try sema.panicInactiveUnionField(block, src, active_tag, wanted_tag);
29017 try sema.addSafetyCheckInactiveUnionField(block, src, active_tag, wanted_tag);
2923329018 }
2923429019 if (field_ty.zigTypeTag(zcu) == .noreturn) {
2923529020 _ = try block.addNoOp(.unreach);
......@@ -29304,7 +29089,7 @@ fn unionFieldVal(
2930429089 const wanted_tag_val = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
2930529090 const wanted_tag = Air.internedToRef(wanted_tag_val.toIntern());
2930629091 const active_tag = try block.addTyOp(.get_union_tag, Type.fromInterned(union_obj.enum_tag_ty), union_byval);
29307 try sema.panicInactiveUnionField(block, src, active_tag, wanted_tag);
29092 try sema.addSafetyCheckInactiveUnionField(block, src, active_tag, wanted_tag);
2930829093 }
2930929094 if (field_ty.zigTypeTag(zcu) == .noreturn) {
2931029095 _ = try block.addNoOp(.unreach);
......@@ -29668,11 +29453,11 @@ fn elemValArray(
2966829453
2966929454 const runtime_src = if (maybe_undef_array_val != null) elem_index_src else array_src;
2967029455 if (oob_safety and block.wantSafety()) {
29671 // Runtime check is only needed if unable to comptime check
29456 // Runtime check is only needed if unable to comptime check.
2967229457 if (maybe_index_val == null) {
2967329458 const len_inst = try pt.intRef(Type.usize, array_len);
2967429459 const cmp_op: Air.Inst.Tag = if (array_sent != null) .cmp_lte else .cmp_lt;
29675 try sema.panicIndexOutOfBounds(block, src, elem_index, len_inst, cmp_op);
29460 try sema.addSafetyCheckIndexOob(block, src, elem_index, len_inst, cmp_op);
2967629461 }
2967729462 }
2967829463
......@@ -29740,7 +29525,7 @@ fn elemPtrArray(
2974029525 if (oob_safety and block.wantSafety() and offset == null) {
2974129526 const len_inst = try pt.intRef(Type.usize, array_len);
2974229527 const cmp_op: Air.Inst.Tag = if (array_sent) .cmp_lte else .cmp_lt;
29743 try sema.panicIndexOutOfBounds(block, src, elem_index, len_inst, cmp_op);
29528 try sema.addSafetyCheckIndexOob(block, src, elem_index, len_inst, cmp_op);
2974429529 }
2974529530
2974629531 return block.addPtrElemPtr(array_ptr, elem_index, elem_ptr_ty);
......@@ -29799,7 +29584,7 @@ fn elemValSlice(
2979929584 else
2980029585 try block.addTyOp(.slice_len, Type.usize, slice);
2980129586 const cmp_op: Air.Inst.Tag = if (slice_sent) .cmp_lte else .cmp_lt;
29802 try sema.panicIndexOutOfBounds(block, src, elem_index, len_inst, cmp_op);
29587 try sema.addSafetyCheckIndexOob(block, src, elem_index, len_inst, cmp_op);
2980329588 }
2980429589 return block.addBinOp(.slice_elem_val, slice, elem_index);
2980529590}
......@@ -29859,7 +29644,7 @@ fn elemPtrSlice(
2985929644 break :len try block.addTyOp(.slice_len, Type.usize, slice);
2986029645 };
2986129646 const cmp_op: Air.Inst.Tag = if (slice_sent) .cmp_lte else .cmp_lt;
29862 try sema.panicIndexOutOfBounds(block, src, elem_index, len_inst, cmp_op);
29647 try sema.addSafetyCheckIndexOob(block, src, elem_index, len_inst, cmp_op);
2986329648 }
2986429649 return block.addSliceElemPtr(slice, elem_index, elem_ptr_ty);
2986529650}
......@@ -32891,7 +32676,7 @@ fn optRefValue(sema: *Sema, opt_val: ?Value) !Value {
3289132676 return Value.fromInterned(try pt.intern(.{ .opt = .{
3289232677 .ty = (try pt.optionalType(ptr_anyopaque_ty.toIntern())).toIntern(),
3289332678 .val = if (opt_val) |val| (try pt.getCoerced(
32894 Value.fromInterned(try sema.refValue(val.toIntern())),
32679 Value.fromInterned(try pt.refValue(val.toIntern())),
3289532680 ptr_anyopaque_ty,
3289632681 )).toIntern() else .none,
3289732682 } }));
......@@ -33667,11 +33452,7 @@ fn analyzeSlice(
3366733452 assert(!block.is_comptime);
3366833453 try sema.requireRuntimeBlock(block, src, runtime_src.?);
3366933454 const ok = try block.addBinOp(.cmp_lte, start, end);
33670 if (!pt.zcu.comp.formatted_panics) {
33671 try sema.addSafetyCheck(block, src, ok, .start_index_greater_than_end);
33672 } else {
33673 try sema.safetyCheckFormatted(block, src, ok, "panicStartGreaterThanEnd", &.{ start, end });
33674 }
33455 try sema.addSafetyCheckCall(block, src, ok, "startGreaterThanEnd", &.{ start, end });
3367533456 }
3367633457 const new_len = if (by_length)
3367733458 try sema.coerce(block, Type.usize, uncasted_end_opt, end_src)
......@@ -33726,11 +33507,11 @@ fn analyzeSlice(
3372633507 else
3372733508 end;
3372833509
33729 try sema.panicIndexOutOfBounds(block, src, actual_end, actual_len, .cmp_lte);
33510 try sema.addSafetyCheckIndexOob(block, src, actual_end, actual_len, .cmp_lte);
3373033511 }
3373133512
3373233513 // requirement: result[new_len] == slice_sentinel
33733 try sema.panicSentinelMismatch(block, src, slice_sentinel, elem_ty, result, new_len);
33514 try sema.addSafetyCheckSentinelMismatch(block, src, slice_sentinel, elem_ty, result, new_len);
3373433515 }
3373533516 return result;
3373633517 };
......@@ -33789,11 +33570,11 @@ fn analyzeSlice(
3378933570 try sema.analyzeArithmetic(block, .add, end, .one, src, end_src, end_src, true)
3379033571 else
3379133572 end;
33792 try sema.panicIndexOutOfBounds(block, src, actual_end, len_inst, .cmp_lte);
33573 try sema.addSafetyCheckIndexOob(block, src, actual_end, len_inst, .cmp_lte);
3379333574 }
3379433575
3379533576 // requirement: start <= end
33796 try sema.panicIndexOutOfBounds(block, src, start, end, .cmp_lte);
33577 try sema.addSafetyCheckIndexOob(block, src, start, end, .cmp_lte);
3379733578 }
3379833579 const result = try block.addInst(.{
3379933580 .tag = .slice,
......@@ -33807,7 +33588,7 @@ fn analyzeSlice(
3380733588 });
3380833589 if (block.wantSafety()) {
3380933590 // requirement: result[new_len] == slice_sentinel
33810 try sema.panicSentinelMismatch(block, src, slice_sentinel, elem_ty, result, new_len);
33591 try sema.addSafetyCheckSentinelMismatch(block, src, slice_sentinel, elem_ty, result, new_len);
3381133592 }
3381233593 return result;
3381333594}
......@@ -35820,7 +35601,7 @@ pub fn resolveFnTypes(sema: *Sema, fn_ty: Type) CompileError!void {
3582035601 Type.fromInterned(fn_ty_info.return_type).isError(zcu))
3582135602 {
3582235603 // Ensure the type exists so that backends can assume that.
35823 _ = try pt.getBuiltinType("StackTrace");
35604 _ = try sema.getBuiltinType("StackTrace");
3582435605 }
3582535606
3582635607 for (0..fn_ty_info.param_types.len) |i| {
......@@ -37688,11 +37469,11 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3768837469 const only_field_ty = Type.fromInterned(union_obj.field_types.get(ip)[0]);
3768937470 const val_val = (try sema.typeHasOnePossibleValue(only_field_ty)) orelse
3769037471 return null;
37691 const only = try pt.intern(.{ .un = .{
37472 const only = try pt.internUnion(.{
3769237473 .ty = ty.toIntern(),
3769337474 .tag = tag_val.toIntern(),
3769437475 .val = val_val.toIntern(),
37695 } });
37476 });
3769637477 return Value.fromInterned(only);
3769737478 },
3769837479
......@@ -37866,7 +37647,7 @@ pub fn analyzeAsAddressSpace(
3786637647) !std.builtin.AddressSpace {
3786737648 const pt = sema.pt;
3786837649 const zcu = pt.zcu;
37869 const addrspace_ty = try pt.getBuiltinType("AddressSpace");
37650 const addrspace_ty = try sema.getBuiltinType("AddressSpace");
3787037651 const coerced = try sema.coerce(block, addrspace_ty, air_ref, src);
3787137652 const addrspace_val = try sema.resolveConstDefinedValue(block, src, coerced, .{
3787237653 .needed_comptime_reason = "address space must be comptime-known",
......@@ -38849,7 +38630,7 @@ fn analyzeUnreachable(sema: *Sema, block: *Block, src: LazySrcLoc, safety_check:
3884938630 sema.branch_hint = .cold;
3885038631 }
3885138632
38852 try sema.safetyPanic(block, src, .unreach);
38633 try sema.safetyPanic(block, src, .reached_unreachable);
3885338634 } else {
3885438635 _ = try block.addNoOp(.unreach);
3885538636 }
......@@ -39123,3 +38904,70 @@ const loadComptimePtr = @import("Sema/comptime_ptr_access.zig").loadComptimePtr;
3912338904const ComptimeLoadResult = @import("Sema/comptime_ptr_access.zig").ComptimeLoadResult;
3912438905const storeComptimePtr = @import("Sema/comptime_ptr_access.zig").storeComptimePtr;
3912538906const ComptimeStoreResult = @import("Sema/comptime_ptr_access.zig").ComptimeStoreResult;
38907
38908fn getPanicInnerFn(
38909 sema: *Sema,
38910 block: *Block,
38911 src: LazySrcLoc,
38912 inner_name: []const u8,
38913) !InternPool.Index {
38914 const gpa = sema.gpa;
38915 const pt = sema.pt;
38916 const zcu = pt.zcu;
38917 const ip = &zcu.intern_pool;
38918 const outer_ty = try sema.getBuiltinType("Panic");
38919 const inner_name_ip = try ip.getOrPutString(gpa, pt.tid, inner_name, .no_embedded_nulls);
38920 const opt_fn_ref = try namespaceLookupVal(sema, block, src, outer_ty.getNamespaceIndex(zcu), inner_name_ip);
38921 const fn_ref = opt_fn_ref orelse return sema.fail(block, src, "std.builtin.Panic missing {s}", .{inner_name});
38922 const fn_val = try sema.resolveConstValue(block, src, fn_ref, .{
38923 .needed_comptime_reason = "panic handler must be comptime-known",
38924 });
38925 if (fn_val.typeOf(zcu).zigTypeTag(zcu) != .@"fn") {
38926 return sema.fail(block, src, "std.builtin.Panic.{s} is not a function", .{inner_name});
38927 }
38928 // Better not to queue up function body analysis because the function might be generic, and
38929 // the semantic analysis for the call will already queue if necessary.
38930 return fn_val.toIntern();
38931}
38932
38933fn getBuiltinType(sema: *Sema, name: []const u8) SemaError!Type {
38934 const pt = sema.pt;
38935 const ty_inst = try sema.getBuiltin(name);
38936 const ty = Type.fromInterned(ty_inst.toInterned() orelse @panic("std.builtin is corrupt"));
38937 try ty.resolveFully(pt);
38938 return ty;
38939}
38940
38941fn getBuiltinInnerType(
38942 sema: *Sema,
38943 block: *Block,
38944 src: LazySrcLoc,
38945 outer_ty: Type,
38946 /// Relative to "std.builtin".
38947 compile_error_parent_name: []const u8,
38948 inner_name: []const u8,
38949) !Type {
38950 const pt = sema.pt;
38951 const zcu = pt.zcu;
38952 const ip = &zcu.intern_pool;
38953 const gpa = sema.gpa;
38954 const inner_name_ip = try ip.getOrPutString(gpa, pt.tid, inner_name, .no_embedded_nulls);
38955 const opt_nav = try sema.namespaceLookup(block, src, outer_ty.getNamespaceIndex(zcu), inner_name_ip);
38956 const nav = opt_nav orelse return sema.fail(block, src, "std.builtin.{s} missing {s}", .{
38957 compile_error_parent_name, inner_name,
38958 });
38959 try sema.ensureNavResolved(src, nav);
38960 const val = Value.fromInterned(ip.getNav(nav).status.resolved.val);
38961 const ty = val.toType();
38962 try ty.resolveFully(pt);
38963 return ty;
38964}
38965
38966fn getBuiltin(sema: *Sema, name: []const u8) SemaError!Air.Inst.Ref {
38967 const pt = sema.pt;
38968 const zcu = pt.zcu;
38969 const ip = &zcu.intern_pool;
38970 const nav = try pt.getBuiltinNav(name);
38971 try pt.ensureCauAnalyzed(ip.getNav(nav).analysis_owner.unwrap().?);
38972 return Air.internedToRef(ip.getNav(nav).status.resolved.val);
38973}
src/Sema/bitcast.zig+6-6
......@@ -613,11 +613,11 @@ const PackValueBits = struct {
613613 pack.bit_offset = prev_bit_offset;
614614 break :backing;
615615 }
616 return Value.fromInterned(try pt.intern(.{ .un = .{
616 return Value.fromInterned(try pt.internUnion(.{
617617 .ty = ty.toIntern(),
618618 .tag = .none,
619619 .val = backing_val.toIntern(),
620 } }));
620 }));
621621 }
622622
623623 const field_order = try pack.arena.alloc(u32, ty.unionTagTypeHypothetical(zcu).enumFieldCount(zcu));
......@@ -658,21 +658,21 @@ const PackValueBits = struct {
658658 continue;
659659 }
660660 const tag_val = try pt.enumValueFieldIndex(ty.unionTagTypeHypothetical(zcu), field_idx);
661 return Value.fromInterned(try pt.intern(.{ .un = .{
661 return Value.fromInterned(try pt.internUnion(.{
662662 .ty = ty.toIntern(),
663663 .tag = tag_val.toIntern(),
664664 .val = field_val.toIntern(),
665 } }));
665 }));
666666 }
667667
668668 // No field could represent the value. Just do whatever happens when we try to read
669669 // the backing type - either `undefined` or `error.ReinterpretDeclRef`.
670670 const backing_val = try pack.get(backing_ty);
671 return Value.fromInterned(try pt.intern(.{ .un = .{
671 return Value.fromInterned(try pt.internUnion(.{
672672 .ty = ty.toIntern(),
673673 .tag = .none,
674674 .val = backing_val.toIntern(),
675 } }));
675 }));
676676 },
677677 else => return pack.primitive(ty),
678678 }
src/Type.zig+2-2
......@@ -2677,11 +2677,11 @@ pub fn onePossibleValue(starting_type: Type, pt: Zcu.PerThread) !?Value {
26772677 const only_field_ty = union_obj.field_types.get(ip)[0];
26782678 const val_val = (try Type.fromInterned(only_field_ty).onePossibleValue(pt)) orelse
26792679 return null;
2680 const only = try pt.intern(.{ .un = .{
2680 const only = try pt.internUnion(.{
26812681 .ty = ty.toIntern(),
26822682 .tag = tag_val.toIntern(),
26832683 .val = val_val.toIntern(),
2684 } });
2684 });
26852685 return Value.fromInterned(only);
26862686 },
26872687 .opaque_type => return null,
src/Value.zig+6-6
......@@ -713,11 +713,11 @@ pub fn readFromMemory(
713713 const union_size = ty.abiSize(zcu);
714714 const array_ty = try zcu.arrayType(.{ .len = union_size, .child = .u8_type });
715715 const val = (try readFromMemory(array_ty, zcu, buffer, arena)).toIntern();
716 return Value.fromInterned(try pt.intern(.{ .un = .{
716 return Value.fromInterned(try pt.internUnion(.{
717717 .ty = ty.toIntern(),
718718 .tag = .none,
719719 .val = val,
720 } }));
720 }));
721721 },
722722 .@"packed" => {
723723 const byte_count = (@as(usize, @intCast(ty.bitSize(zcu))) + 7) / 8;
......@@ -860,11 +860,11 @@ pub fn readFromPackedMemory(
860860 .@"packed" => {
861861 const backing_ty = try ty.unionBackingType(pt);
862862 const val = (try readFromPackedMemory(backing_ty, pt, buffer, bit_offset, arena)).toIntern();
863 return Value.fromInterned(try pt.intern(.{ .un = .{
863 return Value.fromInterned(try pt.internUnion(.{
864864 .ty = ty.toIntern(),
865865 .tag = .none,
866866 .val = val,
867 } }));
867 }));
868868 },
869869 },
870870 .pointer => {
......@@ -4481,11 +4481,11 @@ pub fn resolveLazy(
44814481 return if (resolved_tag == un.tag and resolved_val == un.val)
44824482 val
44834483 else
4484 Value.fromInterned(try pt.intern(.{ .un = .{
4484 Value.fromInterned(try pt.internUnion(.{
44854485 .ty = un.ty,
44864486 .tag = resolved_tag,
44874487 .val = resolved_val,
4488 } }));
4488 }));
44894489 },
44904490 else => return val,
44914491 }
src/Zcu.zig+4-16
......@@ -220,7 +220,7 @@ generation: u32 = 0,
220220pub const PerThread = @import("Zcu/PerThread.zig");
221221
222222pub const PanicId = enum {
223 unreach,
223 reached_unreachable,
224224 unwrap_null,
225225 cast_to_null,
226226 incorrect_alignment,
......@@ -232,15 +232,10 @@ pub const PanicId = enum {
232232 shr_overflow,
233233 divide_by_zero,
234234 exact_division_remainder,
235 inactive_union_field,
236235 integer_part_out_of_bounds,
237236 corrupt_switch,
238237 shift_rhs_too_big,
239238 invalid_enum_value,
240 sentinel_mismatch,
241 unwrap_error,
242 index_out_of_bounds,
243 start_index_greater_than_end,
244239 for_len_mismatch,
245240 memcpy_len_mismatch,
246241 memcpy_alias,
......@@ -2923,17 +2918,10 @@ pub fn addGlobalAssembly(zcu: *Zcu, cau: InternPool.Cau.Index, source: []const u
29232918}
29242919
29252920pub const Feature = enum {
2926 /// When this feature is enabled, Sema will emit calls to `std.builtin.panic`
2927 /// for things like safety checks and unreachables. Otherwise traps will be emitted.
2921 /// When this feature is enabled, Sema will emit calls to
2922 /// `std.builtin.Panic` functions for things like safety checks and
2923 /// unreachables. Otherwise traps will be emitted.
29282924 panic_fn,
2929 /// When this feature is enabled, Sema will emit calls to `std.builtin.panicUnwrapError`.
2930 /// This error message requires more advanced formatting, hence it being seperate from `panic_fn`.
2931 /// Otherwise traps will be emitted.
2932 panic_unwrap_error,
2933 /// When this feature is enabled, Sema will emit calls to the more complex panic functions
2934 /// that use formatting to add detail to error messages. Similar to `panic_unwrap_error`.
2935 /// Otherwise traps will be emitted.
2936 safety_check_formatted,
29372925 /// When this feature is enabled, Sema will insert tracer functions for gathering a stack
29382926 /// trace for error returns.
29392927 error_return_trace,
src/Zcu/PerThread.zig+53-43
......@@ -1,6 +1,32 @@
11//! This type provides a wrapper around a `*Zcu` for uses which require a thread `Id`.
22//! Any operation which mutates `InternPool` state lives here rather than on `Zcu`.
33
4const Air = @import("../Air.zig");
5const Allocator = std.mem.Allocator;
6const assert = std.debug.assert;
7const Ast = std.zig.Ast;
8const AstGen = std.zig.AstGen;
9const BigIntConst = std.math.big.int.Const;
10const BigIntMutable = std.math.big.int.Mutable;
11const build_options = @import("build_options");
12const builtin = @import("builtin");
13const Cache = std.Build.Cache;
14const dev = @import("../dev.zig");
15const InternPool = @import("../InternPool.zig");
16const AnalUnit = InternPool.AnalUnit;
17const isUpDir = @import("../introspect.zig").isUpDir;
18const Liveness = @import("../Liveness.zig");
19const log = std.log.scoped(.zcu);
20const Module = @import("../Package.zig").Module;
21const Sema = @import("../Sema.zig");
22const std = @import("std");
23const target_util = @import("../target.zig");
24const trace = @import("../tracy.zig").trace;
25const Type = @import("../Type.zig");
26const Value = @import("../Value.zig");
27const Zcu = @import("../Zcu.zig");
28const Zir = std.zig.Zir;
29
430zcu: *Zcu,
531
632/// Dense, per-thread unique index.
......@@ -2697,11 +2723,16 @@ pub fn reportRetryableFileError(
26972723 gop.value_ptr.* = err_msg;
26982724}
26992725
2700///Shortcut for calling `intern_pool.get`.
2726/// Shortcut for calling `intern_pool.get`.
27012727pub fn intern(pt: Zcu.PerThread, key: InternPool.Key) Allocator.Error!InternPool.Index {
27022728 return pt.zcu.intern_pool.get(pt.zcu.gpa, pt.tid, key);
27032729}
27042730
2731/// Shortcut for calling `intern_pool.getUnion`.
2732pub fn internUnion(pt: Zcu.PerThread, un: InternPool.Key.Union) Allocator.Error!InternPool.Index {
2733 return pt.zcu.intern_pool.getUnion(pt.zcu.gpa, pt.tid, un);
2734}
2735
27052736/// Essentially a shortcut for calling `intern_pool.getCoerced`.
27062737/// However, this function also allows coercing `extern`s. The `InternPool` function can't do
27072738/// this because it requires potentially pushing to the job queue.
......@@ -2949,11 +2980,12 @@ pub fn intValue_i64(pt: Zcu.PerThread, ty: Type, x: i64) Allocator.Error!Value {
29492980}
29502981
29512982pub fn unionValue(pt: Zcu.PerThread, union_ty: Type, tag: Value, val: Value) Allocator.Error!Value {
2952 return Value.fromInterned(try pt.intern(.{ .un = .{
2983 const zcu = pt.zcu;
2984 return Value.fromInterned(try zcu.intern_pool.getUnion(zcu.gpa, pt.tid, .{
29532985 .ty = union_ty.toIntern(),
29542986 .tag = tag.toIntern(),
29552987 .val = val.toIntern(),
2956 } }));
2988 }));
29572989}
29582990
29592991/// This function casts the float representation down to the representation of the type, potentially
......@@ -3069,14 +3101,6 @@ pub fn structPackedFieldBitOffset(
30693101 unreachable; // index out of bounds
30703102}
30713103
3072pub fn getBuiltin(pt: Zcu.PerThread, name: []const u8) Allocator.Error!Air.Inst.Ref {
3073 const zcu = pt.zcu;
3074 const ip = &zcu.intern_pool;
3075 const nav = try pt.getBuiltinNav(name);
3076 pt.ensureCauAnalyzed(ip.getNav(nav).analysis_owner.unwrap().?) catch @panic("std.builtin is corrupt");
3077 return Air.internedToRef(ip.getNav(nav).status.resolved.val);
3078}
3079
30803104pub fn getBuiltinNav(pt: Zcu.PerThread, name: []const u8) Allocator.Error!InternPool.Nav.Index {
30813105 const zcu = pt.zcu;
30823106 const gpa = zcu.gpa;
......@@ -3094,13 +3118,6 @@ pub fn getBuiltinNav(pt: Zcu.PerThread, name: []const u8) Allocator.Error!Intern
30943118 return builtin_namespace.pub_decls.getKeyAdapted(name_str, Zcu.Namespace.NameAdapter{ .zcu = zcu }) orelse @panic("lib/std/builtin.zig is corrupt");
30953119}
30963120
3097pub fn getBuiltinType(pt: Zcu.PerThread, name: []const u8) Allocator.Error!Type {
3098 const ty_inst = try pt.getBuiltin(name);
3099 const ty = Type.fromInterned(ty_inst.toInterned() orelse @panic("std.builtin is corrupt"));
3100 ty.resolveFully(pt) catch @panic("std.builtin is corrupt");
3101 return ty;
3102}
3103
31043121pub fn navPtrType(pt: Zcu.PerThread, nav_index: InternPool.Nav.Index) Allocator.Error!Type {
31053122 const zcu = pt.zcu;
31063123 const ip = &zcu.intern_pool;
......@@ -3650,28 +3667,21 @@ pub fn ensureNamespaceUpToDate(pt: Zcu.PerThread, namespace_index: Zcu.Namespace
36503667 namespace.generation = zcu.generation;
36513668}
36523669
3653const Air = @import("../Air.zig");
3654const Allocator = std.mem.Allocator;
3655const assert = std.debug.assert;
3656const Ast = std.zig.Ast;
3657const AstGen = std.zig.AstGen;
3658const BigIntConst = std.math.big.int.Const;
3659const BigIntMutable = std.math.big.int.Mutable;
3660const build_options = @import("build_options");
3661const builtin = @import("builtin");
3662const Cache = std.Build.Cache;
3663const dev = @import("../dev.zig");
3664const InternPool = @import("../InternPool.zig");
3665const AnalUnit = InternPool.AnalUnit;
3666const isUpDir = @import("../introspect.zig").isUpDir;
3667const Liveness = @import("../Liveness.zig");
3668const log = std.log.scoped(.zcu);
3669const Module = @import("../Package.zig").Module;
3670const Sema = @import("../Sema.zig");
3671const std = @import("std");
3672const target_util = @import("../target.zig");
3673const trace = @import("../tracy.zig").trace;
3674const Type = @import("../Type.zig");
3675const Value = @import("../Value.zig");
3676const Zcu = @import("../Zcu.zig");
3677const Zir = std.zig.Zir;
3670pub fn refValue(pt: Zcu.PerThread, val: InternPool.Index) Zcu.SemaError!InternPool.Index {
3671 const ptr_ty = (try pt.ptrTypeSema(.{
3672 .child = pt.zcu.intern_pool.typeOf(val),
3673 .flags = .{
3674 .alignment = .none,
3675 .is_const = true,
3676 .address_space = .generic,
3677 },
3678 })).toIntern();
3679 return pt.intern(.{ .ptr = .{
3680 .ty = ptr_ty,
3681 .base_addr = .{ .uav = .{
3682 .val = val,
3683 .orig_ty = ptr_ty,
3684 } },
3685 .byte_offset = 0,
3686 } });
3687}
src/codegen/llvm.zig+7-7
......@@ -3848,13 +3848,13 @@ pub const Object = struct {
38483848
38493849 .undef => unreachable, // handled above
38503850 .simple_value => |simple_value| switch (simple_value) {
3851 .undefined,
3852 .void,
3853 .null,
3854 .empty_struct,
3855 .@"unreachable",
3856 .generic_poison,
3857 => unreachable, // non-runtime values
3851 .undefined => unreachable, // non-runtime value
3852 .void => unreachable, // non-runtime value
3853 .null => unreachable, // non-runtime value
3854 .empty_struct => unreachable, // non-runtime value
3855 .@"unreachable" => unreachable, // non-runtime value
3856 .generic_poison => unreachable, // non-runtime value
3857
38583858 .false => .false,
38593859 .true => .true,
38603860 },
src/crash_report.zig+15-6
......@@ -13,11 +13,23 @@ const Sema = @import("Sema.zig");
1313const InternPool = @import("InternPool.zig");
1414const Zir = std.zig.Zir;
1515const Decl = Zcu.Decl;
16const dev = @import("dev.zig");
1617
1718/// To use these crash report diagnostics, publish this panic in your main file
1819/// and add `pub const enable_segfault_handler = false;` to your `std_options`.
1920/// You will also need to call initialize() on startup, preferably as the very first operation in your program.
20pub const panic = if (build_options.enable_debug_extensions) compilerPanic else std.builtin.default_panic;
21pub const Panic = if (build_options.enable_debug_extensions) struct {
22 pub const call = compilerPanic;
23 pub const sentinelMismatch = std.debug.FormattedPanic.sentinelMismatch;
24 pub const unwrapError = std.debug.FormattedPanic.unwrapError;
25 pub const outOfBounds = std.debug.FormattedPanic.outOfBounds;
26 pub const startGreaterThanEnd = std.debug.FormattedPanic.startGreaterThanEnd;
27 pub const inactiveUnionField = std.debug.FormattedPanic.inactiveUnionField;
28 pub const messages = std.debug.FormattedPanic.messages;
29} else if (dev.env == .bootstrap)
30 std.debug.SimplePanic
31else
32 std.debug.FormattedPanic;
2133
2234/// Install signal handlers to identify crashes and report diagnostics.
2335pub fn initialize() void {
......@@ -317,9 +329,6 @@ const PanicSwitch = struct {
317329 /// until all panicking threads have dumped their traces.
318330 var panicking = std.atomic.Value(u8).init(0);
319331
320 // Locked to avoid interleaving panic messages from multiple threads.
321 var panic_mutex = std.Thread.Mutex{};
322
323332 /// Tracks the state of the current panic. If the code within the
324333 /// panic triggers a secondary panic, this allows us to recover.
325334 threadlocal var panic_state_raw: PanicState = .{};
......@@ -387,7 +396,7 @@ const PanicSwitch = struct {
387396
388397 state.recover_stage = .release_ref_count;
389398
390 panic_mutex.lock();
399 std.debug.lockStdErr();
391400
392401 state.recover_stage = .release_mutex;
393402
......@@ -447,7 +456,7 @@ const PanicSwitch = struct {
447456 noinline fn releaseMutex(state: *volatile PanicState) noreturn {
448457 state.recover_stage = .abort;
449458
450 panic_mutex.unlock();
459 std.debug.unlockStdErr();
451460
452461 goTo(releaseRefCount, .{state});
453462 }
src/link/MachO.zig+1-1
......@@ -3230,7 +3230,7 @@ fn initMetadata(self: *MachO, options: InitMetadataOptions) !void {
32303230 self.zig_text_seg_index = try self.addSegment("__TEXT_ZIG", .{
32313231 .fileoff = off,
32323232 .filesize = filesize,
3233 .vmaddr = base_vmaddr + 0x8000000,
3233 .vmaddr = base_vmaddr + 0x4000000,
32343234 .vmsize = filesize,
32353235 .prot = macho.PROT.READ | macho.PROT.EXEC,
32363236 });
src/main.zig+5-6
......@@ -44,8 +44,7 @@ pub const std_options = .{
4444 },
4545};
4646
47// Crash report needs to override the panic handler
48pub const panic = crash_report.panic;
47pub const Panic = crash_report.Panic;
4948
5049var wasi_preopens: fs.wasi.Preopens = undefined;
5150pub fn wasi_cwd() std.os.wasi.fd_t {
......@@ -826,7 +825,6 @@ fn buildOutputType(
826825 var version: std.SemanticVersion = .{ .major = 0, .minor = 0, .patch = 0 };
827826 var have_version = false;
828827 var compatibility_version: ?std.SemanticVersion = null;
829 var formatted_panics: ?bool = null;
830828 var function_sections = false;
831829 var data_sections = false;
832830 var no_builtin = false;
......@@ -1537,9 +1535,11 @@ fn buildOutputType(
15371535 } else if (mem.eql(u8, arg, "-gdwarf64")) {
15381536 create_module.opts.debug_format = .{ .dwarf = .@"64" };
15391537 } else if (mem.eql(u8, arg, "-fformatted-panics")) {
1540 formatted_panics = true;
1538 // Remove this after 0.15.0 is tagged.
1539 warn("-fformatted-panics is deprecated and does nothing", .{});
15411540 } else if (mem.eql(u8, arg, "-fno-formatted-panics")) {
1542 formatted_panics = false;
1541 // Remove this after 0.15.0 is tagged.
1542 warn("-fno-formatted-panics is deprecated and does nothing", .{});
15431543 } else if (mem.eql(u8, arg, "-fsingle-threaded")) {
15441544 mod_opts.single_threaded = true;
15451545 } else if (mem.eql(u8, arg, "-fno-single-threaded")) {
......@@ -3405,7 +3405,6 @@ fn buildOutputType(
34053405 .force_undefined_symbols = force_undefined_symbols,
34063406 .stack_size = stack_size,
34073407 .image_base = image_base,
3408 .formatted_panics = formatted_panics,
34093408 .function_sections = function_sections,
34103409 .data_sections = data_sections,
34113410 .no_builtin = no_builtin,
src/mutable_value.zig+2-2
......@@ -88,11 +88,11 @@ pub const MutableValue = union(enum) {
8888 .ptr = (try s.ptr.intern(pt, arena)).toIntern(),
8989 .len = (try s.len.intern(pt, arena)).toIntern(),
9090 } }),
91 .un => |u| try pt.intern(.{ .un = .{
91 .un => |u| try pt.internUnion(.{
9292 .ty = u.ty,
9393 .tag = u.tag,
9494 .val = (try u.payload.intern(pt, arena)).toIntern(),
95 } }),
95 }),
9696 });
9797 }
9898
src/target.zig-8
......@@ -586,14 +586,6 @@ pub inline fn backendSupportsFeature(backend: std.builtin.CompilerBackend, compt
586586 => true,
587587 else => false,
588588 },
589 .panic_unwrap_error => switch (backend) {
590 .stage2_c, .stage2_llvm => true,
591 else => false,
592 },
593 .safety_check_formatted => switch (backend) {
594 .stage2_c, .stage2_llvm => true,
595 else => false,
596 },
597589 .error_return_trace => switch (backend) {
598590 .stage2_llvm => true,
599591 else => false,
test/cases/exit.zig+1-1
......@@ -1,5 +1,5 @@
11pub fn main() void {}
22
33// run
4// target=x86_64-linux,x86_64-macos,x86_64-windows,x86_64-plan9
4// target=x86_64-linux,x86_64-macos,x86_64-windows
55//