authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-09-25 11:11:48-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-09-26 12:35:14-07:00
log4f8d244e7ea47a8cdb41496d51961ef4ba3ec2af
treec12d45a7aeadec432e0e40760923ac3c6ea937bc
parent04e694ad116ad2706328c13ce3643347330a861f

remove formatted panics

implements #17969

17 files changed, 634 insertions(+), 744 deletions(-)

lib/compiler_rt/common.zig+2-4
......@@ -77,11 +77,9 @@ pub const want_sparc_abi = builtin.cpu.arch.isSPARC();
7777
7878// Avoid dragging in the runtime safety mechanisms into this .o file,
7979// 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;
80pub fn panic(cause: std.builtin.PanicCause, error_return_trace: ?*std.builtin.StackTrace, ret_addr: ?usize) noreturn {
8281 if (builtin.is_test) {
83 @branchHint(.cold);
84 std.debug.panic("{s}", .{msg});
82 std.debug.defaultPanic(cause, error_return_trace, ret_addr orelse @returnAddress());
8583 } else {
8684 unreachable;
8785 }
lib/std/builtin.zig+49-164
......@@ -763,181 +763,66 @@ pub const TestFn = struct {
763763
764764/// This function type is used by the Zig language code generation and
765765/// therefore must be kept in sync with the compiler implementation.
766pub const PanicFn = fn ([]const u8, ?*StackTrace, ?usize) noreturn;
766pub const PanicFn = fn (PanicCause, ?*StackTrace, ?usize) noreturn;
767767
768/// This function is used by the Zig language code generation and
769/// therefore must be kept in sync with the compiler implementation.
768/// The entry point for auto-generated calls by the compiler.
770769pub const panic: PanicFn = if (@hasDecl(root, "panic"))
771770 root.panic
772771else if (@hasDecl(root, "os") and @hasDecl(root.os, "panic"))
773772 root.os.panic
774773else
775 default_panic;
774 std.debug.defaultPanic;
776775
777/// This function is used by the Zig language code generation and
776/// This data structure is used by the Zig language code generation and
778777/// 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}
778pub const PanicCause = union(enum) {
779 reached_unreachable,
780 unwrap_null,
781 cast_to_null,
782 incorrect_alignment,
783 invalid_error_code,
784 cast_truncated_data,
785 negative_to_unsigned,
786 integer_overflow,
787 shl_overflow,
788 shr_overflow,
789 divide_by_zero,
790 exact_division_remainder,
791 inactive_union_field: InactiveUnionField,
792 integer_part_out_of_bounds,
793 corrupt_switch,
794 shift_rhs_too_big,
795 invalid_enum_value,
796 sentinel_mismatch_usize: SentinelMismatchUsize,
797 sentinel_mismatch_other,
798 unwrap_error: anyerror,
799 index_out_of_bounds: IndexOutOfBounds,
800 start_index_greater_than_end: StartIndexGreaterThanEnd,
801 for_len_mismatch,
802 memcpy_len_mismatch,
803 memcpy_alias,
804 noreturn_returned,
805 explicit_call: []const u8,
806
807 pub const IndexOutOfBounds = struct {
808 index: usize,
809 len: usize,
810 };
904811
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}
812 pub const StartIndexGreaterThanEnd = struct {
813 start: usize,
814 end: usize,
815 };
909816
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}
817 pub const SentinelMismatchUsize = struct {
818 expected: usize,
819 found: usize,
820 };
914821
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";
822 pub const InactiveUnionField = struct {
823 active: []const u8,
824 accessed: []const u8,
825 };
941826};
942827
943828pub noinline fn returnError(st: *StackTrace) void {
lib/std/debug.zig+228-66
......@@ -408,14 +408,15 @@ pub fn assertReadable(slice: []const volatile u8) void {
408408 for (slice) |*byte| _ = byte.*;
409409}
410410
411/// Equivalent to `@panic` but with a formatted message.
411412pub fn panic(comptime format: []const u8, args: anytype) noreturn {
412413 @branchHint(.cold);
413414
414415 panicExtra(@errorReturnTrace(), @returnAddress(), format, args);
415416}
416417
417/// `panicExtra` is useful when you want to print out an `@errorReturnTrace`
418/// and also print out some values.
418/// Equivalent to `@panic` but with a formatted message, and with an explicitly
419/// provided `@errorReturnTrace` and return address.
419420pub fn panicExtra(
420421 trace: ?*std.builtin.StackTrace,
421422 ret_addr: ?usize,
......@@ -447,11 +448,104 @@ var panicking = std.atomic.Value(u8).init(0);
447448/// This is used to catch and handle panics triggered by the panic handler.
448449threadlocal var panic_stage: usize = 0;
449450
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 {
451// Dumps a stack trace to standard error, then aborts.
452//
453// This function avoids a dependency on formatted printing.
454pub fn defaultPanic(
455 cause: std.builtin.PanicCause,
456 trace: ?*const std.builtin.StackTrace,
457 first_trace_addr: ?usize,
458) noreturn {
453459 @branchHint(.cold);
454460
461 // For backends that cannot handle the language features depended on by the
462 // default panic handler, we have a simpler panic handler:
463 if (builtin.zig_backend == .stage2_wasm or
464 builtin.zig_backend == .stage2_arm or
465 builtin.zig_backend == .stage2_aarch64 or
466 builtin.zig_backend == .stage2_x86 or
467 (builtin.zig_backend == .stage2_x86_64 and (builtin.target.ofmt != .elf and builtin.target.ofmt != .macho)) or
468 builtin.zig_backend == .stage2_sparc64 or
469 builtin.zig_backend == .stage2_spirv64)
470 {
471 @trap();
472 }
473
474 if (builtin.zig_backend == .stage2_riscv64) {
475 var buffer: [1000]u8 = undefined;
476 var i: usize = 0;
477 i += fmtPanicCause(buffer[i..], cause);
478 buffer[i] = '\n';
479 i += 1;
480 const msg = buffer[0..i];
481 lockStdErr();
482 io.getStdErr().writeAll(msg) catch {};
483 @trap();
484 }
485
486 switch (builtin.os.tag) {
487 .freestanding => {
488 @trap();
489 },
490 .wasi => {
491 // TODO: before merging my branch, unify this logic with the main panic logic
492 var buffer: [1000]u8 = undefined;
493 var i: usize = 0;
494 i += fmtPanicCause(buffer[i..], cause);
495 buffer[i] = '\n';
496 i += 1;
497 const msg = buffer[0..i];
498 lockStdErr();
499 io.getStdErr().writeAll(msg) catch {};
500 @trap();
501 },
502 .uefi => {
503 const uefi = std.os.uefi;
504
505 var buffer: [1000]u8 = undefined;
506 var i: usize = 0;
507 i += fmtBuf(buffer[i..], "panic: ");
508 i += fmtPanicCause(buffer[i..], cause);
509 i += fmtBuf(buffer[i..], "\r\n\x00");
510
511 var utf16_buffer: [1000]u16 = undefined;
512 const len = std.unicode.utf8ToUtf16Le(&utf16_buffer, buffer[0..i]) catch 0;
513 const exit_msg = utf16_buffer[0 .. len - 1 :0];
514
515 // Output to both std_err and con_out, as std_err is easier
516 // to read in stuff like QEMU at times, but, unlike con_out,
517 // isn't visible on actual hardware if directly booted into
518 inline for ([_]?*uefi.protocol.SimpleTextOutput{ uefi.system_table.std_err, uefi.system_table.con_out }) |o| {
519 if (o) |out| {
520 _ = out.setAttribute(uefi.protocol.SimpleTextOutput.red);
521 _ = out.outputString(exit_msg);
522 _ = out.setAttribute(uefi.protocol.SimpleTextOutput.white);
523 }
524 }
525
526 if (uefi.system_table.boot_services) |bs| {
527 // ExitData buffer must be allocated using boot_services.allocatePool (spec: page 220)
528 const exit_data: []u16 = uefi.raw_pool_allocator.alloc(u16, exit_msg.len + 1) catch @trap();
529 @memcpy(exit_data, exit_msg[0..exit_data.len]); // Includes null terminator.
530 _ = bs.exit(uefi.handle, .Aborted, exit_msg.len + 1, exit_data);
531 }
532 @trap();
533 },
534 .cuda, .amdhsa => std.posix.abort(),
535 .plan9 => {
536 var buffer: [1000]u8 = undefined;
537 comptime assert(buffer.len > std.os.plan9.ERRMAX);
538 var i: usize = 0;
539 i += fmtPanicCause(buffer[i..], cause);
540 buffer[i] = '\n';
541 i += 1;
542 const len = @min(i, std.os.plan9.ERRMAX - 1);
543 buffer[len] = 0;
544 std.os.plan9.exits(buffer[0..len :0]);
545 },
546 else => {},
547 }
548
455549 if (enable_segfault_handler) {
456550 // If a segfault happens while panicking, we want it to actually segfault, not trigger
457551 // the handler.
......@@ -465,23 +559,29 @@ pub fn panicImpl(trace: ?*const std.builtin.StackTrace, first_trace_addr: ?usize
465559
466560 _ = panicking.fetchAdd(1, .seq_cst);
467561
468 // Make sure to release the mutex when done
469562 {
470 lockStdErr();
471 defer unlockStdErr();
472
473 const stderr = io.getStdErr().writer();
563 // This code avoids a dependency on formatted printing, the writer interface,
564 // and limits to only 1 syscall made to print the panic message to stderr.
565 var buffer: [0x1000]u8 = undefined;
566 var i: usize = 0;
474567 if (builtin.single_threaded) {
475 stderr.print("panic: ", .{}) catch posix.abort();
568 i += fmtBuf(buffer[i..], "panic: ");
476569 } else {
477 const current_thread_id = std.Thread.getCurrentId();
478 stderr.print("thread {} panic: ", .{current_thread_id}) catch posix.abort();
479 }
480 stderr.print("{s}\n", .{msg}) catch posix.abort();
481 if (trace) |t| {
482 dumpStackTrace(t.*);
570 i += fmtBuf(buffer[i..], "thread ");
571 i += fmtInt10(buffer[i..], std.Thread.getCurrentId());
572 i += fmtBuf(buffer[i..], " panic: ");
483573 }
484 dumpCurrentStackTrace(first_trace_addr);
574 i += fmtPanicCause(&buffer, cause);
575 buffer[i] = '\n';
576 i += 1;
577 const msg = buffer[0..i];
578
579 lockStdErr();
580 defer unlockStdErr();
581
582 io.getStdErr().writeAll(msg) catch posix.abort();
583 if (trace) |t| dumpStackTrace(t.*);
584 dumpCurrentStackTrace(first_trace_addr orelse @returnAddress());
485585 }
486586
487587 waitForOtherThreadToFinishPanicking();
......@@ -489,20 +589,99 @@ pub fn panicImpl(trace: ?*const std.builtin.StackTrace, first_trace_addr: ?usize
489589 1 => {
490590 panic_stage = 2;
491591
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."
592 // A panic happened while trying to print a previous panic message.
593 // We're still holding the mutex but that's fine as we're going to
594 // call abort().
595 io.getStdErr().writeAll("aborting due to recursive panic\n") catch {};
500596 },
597 else => {}, // Panicked while printing the recursive panic message.
501598 };
502599
503600 posix.abort();
504601}
505602
603pub fn fmtPanicCause(buffer: []u8, cause: std.builtin.PanicCause) usize {
604 var i: usize = 0;
605
606 switch (cause) {
607 .reached_unreachable => i += fmtBuf(buffer[i..], "reached unreachable code"),
608 .unwrap_null => i += fmtBuf(buffer[i..], "attempt to use null value"),
609 .cast_to_null => i += fmtBuf(buffer[i..], "cast causes pointer to be null"),
610 .incorrect_alignment => i += fmtBuf(buffer[i..], "incorrect alignment"),
611 .invalid_error_code => i += fmtBuf(buffer[i..], "invalid error code"),
612 .cast_truncated_data => i += fmtBuf(buffer[i..], "integer cast truncated bits"),
613 .negative_to_unsigned => i += fmtBuf(buffer[i..], "attempt to cast negative value to unsigned integer"),
614 .integer_overflow => i += fmtBuf(buffer[i..], "integer overflow"),
615 .shl_overflow => i += fmtBuf(buffer[i..], "left shift overflowed bits"),
616 .shr_overflow => i += fmtBuf(buffer[i..], "right shift overflowed bits"),
617 .divide_by_zero => i += fmtBuf(buffer[i..], "division by zero"),
618 .exact_division_remainder => i += fmtBuf(buffer[i..], "exact division produced remainder"),
619 .inactive_union_field => |info| {
620 i += fmtBuf(buffer[i..], "access of union field '");
621 i += fmtBuf(buffer[i..], info.accessed);
622 i += fmtBuf(buffer[i..], "' while field '");
623 i += fmtBuf(buffer[i..], info.active);
624 i += fmtBuf(buffer[i..], "' is active");
625 },
626 .integer_part_out_of_bounds => i += fmtBuf(buffer[i..], "integer part of floating point value out of bounds"),
627 .corrupt_switch => i += fmtBuf(buffer[i..], "switch on corrupt value"),
628 .shift_rhs_too_big => i += fmtBuf(buffer[i..], "shift amount is greater than the type size"),
629 .invalid_enum_value => i += fmtBuf(buffer[i..], "invalid enum value"),
630 .sentinel_mismatch_usize => |mm| {
631 i += fmtBuf(buffer[i..], "sentinel mismatch: expected ");
632 i += fmtInt10(buffer[i..], mm.expected);
633 i += fmtBuf(buffer[i..], ", found ");
634 i += fmtInt10(buffer[i..], mm.found);
635 },
636 .sentinel_mismatch_other => i += fmtBuf(buffer[i..], "sentinel mismatch"),
637 .unwrap_error => |err| {
638 i += fmtBuf(buffer[i..], "attempt to unwrap error: ");
639 i += fmtBuf(buffer[i..], @errorName(err));
640 },
641 .index_out_of_bounds => |oob| {
642 i += fmtBuf(buffer[i..], "index ");
643 i += fmtInt10(buffer[i..], oob.index);
644 i += fmtBuf(buffer[i..], " exceeds length ");
645 i += fmtInt10(buffer[i..], oob.len);
646 },
647 .start_index_greater_than_end => |oob| {
648 i += fmtBuf(buffer[i..], "start index ");
649 i += fmtInt10(buffer[i..], oob.start);
650 i += fmtBuf(buffer[i..], " exceeds end index ");
651 i += fmtInt10(buffer[i..], oob.end);
652 },
653 .for_len_mismatch => i += fmtBuf(buffer[i..], "for loop over objects with non-equal lengths"),
654 .memcpy_len_mismatch => i += fmtBuf(buffer[i..], "@memcpy arguments have non-equal lengths"),
655 .memcpy_alias => i += fmtBuf(buffer[i..], "@memcpy arguments alias"),
656 .noreturn_returned => i += fmtBuf(buffer[i..], "'noreturn' function returned"),
657 .explicit_call => |msg| i += fmtBuf(buffer[i..], msg),
658 }
659
660 return i;
661}
662
663fn fmtBuf(out_buf: []u8, s: []const u8) usize {
664 @memcpy(out_buf[0..s.len], s);
665 return s.len;
666}
667
668fn fmtInt10(out_buf: []u8, integer_value: usize) usize {
669 var tmp_buf: [50]u8 = undefined;
670 var i: usize = tmp_buf.len;
671 var a: usize = integer_value;
672
673 while (true) {
674 i -= 1;
675 tmp_buf[i] = '0' + (a % 10);
676 a /= 10;
677 if (a == 0) break;
678 }
679
680 const result = tmp_buf[i..];
681 @memcpy(out_buf[0..result.len], result);
682 return result.len;
683}
684
506685/// Must be called only after adding 1 to `panicking`. There are three callsites.
507686fn waitForOtherThreadToFinishPanicking() void {
508687 if (panicking.fetchSub(1, .seq_cst) != 1) {
......@@ -1157,7 +1336,7 @@ pub const default_enable_segfault_handler = runtime_safety and have_segfault_han
11571336
11581337pub fn maybeEnableSegfaultHandler() void {
11591338 if (enable_segfault_handler) {
1160 std.debug.attachSegfaultHandler();
1339 attachSegfaultHandler();
11611340 }
11621341}
11631342
......@@ -1289,46 +1468,29 @@ fn handleSegfaultWindows(info: *windows.EXCEPTION_POINTERS) callconv(windows.WIN
12891468 }
12901469}
12911470
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 }
1471fn handleSegfaultWindowsExtra(info: *windows.EXCEPTION_POINTERS, msg: u8, label: ?[]const u8) noreturn {
1472 comptime assert(windows.CONTEXT != void);
1473 nosuspend switch (panic_stage) {
1474 0 => {
1475 panic_stage = 1;
1476 _ = panicking.fetchAdd(1, .seq_cst);
1477
1478 {
1479 lockStdErr();
1480 defer unlockStdErr();
13101481
1311 waitForOtherThreadToFinishPanicking();
1312 },
1313 else => {
1314 // panic mutex already locked
13151482 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 }
1483 }
1484
1485 waitForOtherThreadToFinishPanicking();
1486 },
1487 1 => {
1488 panic_stage = 2;
1489 io.getStdErr().writeAll("aborting due to recursive panic\n") catch {};
1490 },
1491 else => {},
1492 };
1493 posix.abort();
13321494}
13331495
13341496fn dumpSegfaultInfoWindows(info: *windows.EXCEPTION_POINTERS, msg: u8, label: ?[]const u8) void {
......@@ -1347,7 +1509,7 @@ pub fn dumpStackPointerAddr(prefix: []const u8) void {
13471509 const sp = asm (""
13481510 : [argc] "={rsp}" (-> usize),
13491511 );
1350 std.debug.print("{s} sp = 0x{x}\n", .{ prefix, sp });
1512 print("{s} sp = 0x{x}\n", .{ prefix, sp });
13511513}
13521514
13531515test "manage resources correctly" {
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 {
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+267-393
......@@ -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;
......@@ -5830,8 +5830,6 @@ fn zirPanic(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
58305830 const src = block.nodeOffset(inst_data.src_node);
58315831 const msg_inst = try sema.resolveInst(inst_data.operand);
58325832
5833 // `panicWithMsg` would perform this coercion for us, but we can get a better
5834 // source location if we do it here.
58355833 const coerced_msg = try sema.coerce(block, Type.slice_const_u8, msg_inst, block.builtinCallArgSrc(inst_data.src_node, 0));
58365834
58375835 if (block.is_comptime) {
......@@ -5844,7 +5842,7 @@ fn zirPanic(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
58445842 sema.branch_hint = .cold;
58455843 }
58465844
5847 try sema.panicWithMsg(block, src, coerced_msg, .@"@panic");
5845 try callPanic(sema, block, src, .explicit_call, coerced_msg, .@"@panic");
58485846}
58495847
58505848fn zirTrap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
......@@ -7325,6 +7323,31 @@ fn callBuiltin(
73257323 );
73267324}
73277325
7326const PanicCauseTag = @typeInfo(std.builtin.PanicCause).@"union".tag_type.?;
7327
7328fn callPanic(
7329 sema: *Sema,
7330 block: *Block,
7331 call_src: LazySrcLoc,
7332 tag: PanicCauseTag,
7333 payload: Air.Inst.Ref,
7334 call_operation: CallOperation,
7335) !void {
7336 const pt = sema.pt;
7337 if (!pt.zcu.backendSupportsFeature(.panic_fn)) {
7338 _ = try block.addNoOp(.trap);
7339 return;
7340 }
7341 const panic_cause_ty = try pt.getBuiltinType("PanicCause");
7342 const panic_cause = try block.addUnionInit(panic_cause_ty, @intFromEnum(tag), payload);
7343 const panic_fn = try pt.getBuiltin("panic");
7344 const err_return_trace = try sema.getErrorReturnTrace(block);
7345 const opt_usize_ty = try pt.optionalType(.usize_type);
7346 const null_usize = try pt.nullValue(opt_usize_ty);
7347 const args: [3]Air.Inst.Ref = .{ panic_cause, err_return_trace, Air.internedToRef(null_usize) };
7348 try sema.callBuiltin(block, call_src, panic_fn, .auto, &args, call_operation);
7349}
7350
73287351const CallOperation = enum {
73297352 call,
73307353 @"@call",
......@@ -9327,7 +9350,7 @@ fn analyzeErrUnionPayload(
93279350 if (safety_check and block.wantSafety() and
93289351 !err_union_ty.errorUnionSet(zcu).errorSetIsEmpty(zcu))
93299352 {
9330 try sema.panicUnwrapError(block, src, operand, .unwrap_errunion_err, .is_non_err);
9353 try sema.addSafetyCheckUnwrapError(block, src, operand, .unwrap_errunion_err, .is_non_err);
93319354 }
93329355
93339356 return block.addTyOp(.unwrap_errunion_payload, payload_ty, operand);
......@@ -9411,7 +9434,7 @@ fn analyzeErrUnionPayloadPtr(
94119434 if (safety_check and block.wantSafety() and
94129435 !err_union_ty.errorUnionSet(zcu).errorSetIsEmpty(zcu))
94139436 {
9414 try sema.panicUnwrapError(block, src, operand, .unwrap_errunion_err_ptr, .is_non_err_ptr);
9437 try sema.addSafetyCheckUnwrapError(block, src, operand, .unwrap_errunion_err_ptr, .is_non_err_ptr);
94159438 }
94169439
94179440 if (initializing) {
......@@ -14190,7 +14213,6 @@ fn maybeErrorUnwrap(
1419014213) !bool {
1419114214 const pt = sema.pt;
1419214215 const zcu = pt.zcu;
14193 if (!zcu.backendSupportsFeature(.panic_unwrap_error)) return false;
1419414216
1419514217 const tags = sema.code.instructions.items(.tag);
1419614218 for (body) |inst| {
......@@ -14223,25 +14245,13 @@ fn maybeErrorUnwrap(
1422314245 .as_node => try sema.zirAsNode(block, inst),
1422414246 .field_val => try sema.zirFieldVal(block, inst),
1422514247 .@"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");
14248 try callPanic(sema, block, operand_src, .unwrap_error, operand, .@"safety check");
1423514249 return true;
1423614250 },
1423714251 .panic => {
1423814252 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1423914253 const msg_inst = try sema.resolveInst(inst_data.operand);
14240
14241 const panic_fn = try pt.getBuiltin("panic");
14242 const err_return_trace = try sema.getErrorReturnTrace(block);
14243 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");
14254 try callPanic(sema, block, operand_src, .explicit_call, msg_inst, .@"@panic");
1424514255 return true;
1424614256 },
1424714257 else => unreachable,
......@@ -17388,9 +17398,6 @@ fn analyzeArithmetic(
1738817398
1738917399 if (block.wantSafety() and want_safety and scalar_tag == .int) {
1739017400 if (zcu.backendSupportsFeature(.safety_checked_instructions)) {
17391 if (air_tag != air_tag_safe) {
17392 _ = try sema.preparePanicId(block, src, .integer_overflow);
17393 }
1739417401 return block.addBinOp(air_tag_safe, casted_lhs, casted_rhs);
1739517402 } else {
1739617403 const maybe_op_ov: ?Air.Inst.Tag = switch (air_tag) {
......@@ -18319,29 +18326,14 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1831918326 .undefined,
1832018327 .null,
1832118328 .enum_literal,
18322 => |type_info_tag| return Air.internedToRef((try pt.intern(.{ .un = .{
18329 => |type_info_tag| return Air.internedToRef((try pt.internUnion(.{
1832318330 .ty = type_info_ty.toIntern(),
1832418331 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(type_info_tag))).toIntern(),
1832518332 .val = .void_value,
18326 } }))),
18333 }))),
1832718334 .@"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);
18336
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);
18335 const fn_info_ty = try getInnerType(sema, block, src, type_info_ty, "Fn");
18336 const param_info_ty = try getInnerType(sema, block, src, fn_info_ty, "Param");
1834518337
1834618338 const func_ty_info = zcu.typeToFunc(ty).?;
1834718339 const param_vals = try sema.arena.alloc(InternPool.Index, func_ty_info.param_types.len);
......@@ -18425,25 +18417,17 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1842518417 // args: []const Fn.Param,
1842618418 args_val,
1842718419 };
18428 return Air.internedToRef((try pt.intern(.{ .un = .{
18420 return Air.internedToRef((try pt.internUnion(.{
1842918421 .ty = type_info_ty.toIntern(),
1843018422 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.@"fn"))).toIntern(),
1843118423 .val = try pt.intern(.{ .aggregate = .{
1843218424 .ty = fn_info_ty.toIntern(),
1843318425 .storage = .{ .elems = &field_values },
1843418426 } }),
18435 } })));
18427 })));
1843618428 },
1843718429 .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
18430 const int_info_ty = try getInnerType(sema, block, src, type_info_ty, "Int");
1844718431 const signedness_ty = try pt.getBuiltinType("Signedness");
1844818432 const info = ty.intInfo(zcu);
1844918433 const field_values = .{
......@@ -18452,37 +18436,30 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1845218436 // bits: u16,
1845318437 (try pt.intValue(Type.u16, info.bits)).toIntern(),
1845418438 };
18455 return Air.internedToRef((try pt.intern(.{ .un = .{
18439 return Air.internedToRef((try pt.internUnion(.{
1845618440 .ty = type_info_ty.toIntern(),
1845718441 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.int))).toIntern(),
1845818442 .val = try pt.intern(.{ .aggregate = .{
1845918443 .ty = int_info_ty.toIntern(),
1846018444 .storage = .{ .elems = &field_values },
1846118445 } }),
18462 } })));
18446 })));
1846318447 },
1846418448 .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);
18449 const float_info_ty = try getInnerType(sema, block, src, type_info_ty, "Float");
1847318450
1847418451 const field_vals = .{
1847518452 // bits: u16,
1847618453 (try pt.intValue(Type.u16, ty.bitSize(zcu))).toIntern(),
1847718454 };
18478 return Air.internedToRef((try pt.intern(.{ .un = .{
18455 return Air.internedToRef((try pt.internUnion(.{
1847918456 .ty = type_info_ty.toIntern(),
1848018457 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.float))).toIntern(),
1848118458 .val = try pt.intern(.{ .aggregate = .{
1848218459 .ty = float_info_ty.toIntern(),
1848318460 .storage = .{ .elems = &field_vals },
1848418461 } }),
18485 } })));
18462 })));
1848618463 },
1848718464 .pointer => {
1848818465 const info = ty.ptrInfo(zcu);
......@@ -18492,26 +18469,8 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1849218469 try Type.fromInterned(info.child).lazyAbiAlignment(pt);
1849318470
1849418471 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 };
18472 const pointer_ty = try getInnerType(sema, block, src, type_info_ty, "Pointer");
18473 const ptr_size_ty = try getInnerType(sema, block, src, pointer_ty, "Size");
1851518474
1851618475 const field_values = .{
1851718476 // size: Size,
......@@ -18534,26 +18493,17 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1853418493 else => Value.fromInterned(info.sentinel),
1853518494 })).toIntern(),
1853618495 };
18537 return Air.internedToRef((try pt.intern(.{ .un = .{
18496 return Air.internedToRef((try pt.internUnion(.{
1853818497 .ty = type_info_ty.toIntern(),
1853918498 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.pointer))).toIntern(),
1854018499 .val = try pt.intern(.{ .aggregate = .{
1854118500 .ty = pointer_ty.toIntern(),
1854218501 .storage = .{ .elems = &field_values },
1854318502 } }),
18544 } })));
18503 })));
1854518504 },
1854618505 .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 };
18506 const array_field_ty = try getInnerType(sema, block, src, type_info_ty, "Array");
1855718507
1855818508 const info = ty.arrayInfo(zcu);
1855918509 const field_values = .{
......@@ -18564,26 +18514,17 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1856418514 // sentinel: ?*const anyopaque,
1856518515 (try sema.optRefValue(info.sentinel)).toIntern(),
1856618516 };
18567 return Air.internedToRef((try pt.intern(.{ .un = .{
18517 return Air.internedToRef((try pt.internUnion(.{
1856818518 .ty = type_info_ty.toIntern(),
1856918519 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.array))).toIntern(),
1857018520 .val = try pt.intern(.{ .aggregate = .{
1857118521 .ty = array_field_ty.toIntern(),
1857218522 .storage = .{ .elems = &field_values },
1857318523 } }),
18574 } })));
18524 })));
1857518525 },
1857618526 .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 };
18527 const vector_field_ty = try getInnerType(sema, block, src, type_info_ty, "Vector");
1858718528
1858818529 const info = ty.arrayInfo(zcu);
1858918530 const field_values = .{
......@@ -18592,52 +18533,34 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1859218533 // child: type,
1859318534 info.elem_type.toIntern(),
1859418535 };
18595 return Air.internedToRef((try pt.intern(.{ .un = .{
18536 return Air.internedToRef((try pt.internUnion(.{
1859618537 .ty = type_info_ty.toIntern(),
1859718538 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.vector))).toIntern(),
1859818539 .val = try pt.intern(.{ .aggregate = .{
1859918540 .ty = vector_field_ty.toIntern(),
1860018541 .storage = .{ .elems = &field_values },
1860118542 } }),
18602 } })));
18543 })));
1860318544 },
1860418545 .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 };
18546 const optional_field_ty = try getInnerType(sema, block, src, type_info_ty, "Optional");
1861518547
1861618548 const field_values = .{
1861718549 // child: type,
1861818550 ty.optionalChild(zcu).toIntern(),
1861918551 };
18620 return Air.internedToRef((try pt.intern(.{ .un = .{
18552 return Air.internedToRef((try pt.internUnion(.{
1862118553 .ty = type_info_ty.toIntern(),
1862218554 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.optional))).toIntern(),
1862318555 .val = try pt.intern(.{ .aggregate = .{
1862418556 .ty = optional_field_ty.toIntern(),
1862518557 .storage = .{ .elems = &field_values },
1862618558 } }),
18627 } })));
18559 })));
1862818560 },
1862918561 .error_set => {
1863018562 // 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 };
18563 const error_field_ty = try getInnerType(sema, block, src, type_info_ty, "Error");
1864118564
1864218565 // Build our list of Error values
1864318566 // Optional value is only null if anyerror
......@@ -18726,23 +18649,14 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1872618649 } });
1872718650
1872818651 // Construct Type{ .error_set = errors_val }
18729 return Air.internedToRef((try pt.intern(.{ .un = .{
18652 return Air.internedToRef((try pt.internUnion(.{
1873018653 .ty = type_info_ty.toIntern(),
1873118654 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.error_set))).toIntern(),
1873218655 .val = errors_val,
18733 } })));
18656 })));
1873418657 },
1873518658 .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 };
18659 const error_union_field_ty = try getInnerType(sema, block, src, type_info_ty, "ErrorUnion");
1874618660
1874718661 const field_values = .{
1874818662 // error_set: type,
......@@ -18750,28 +18664,19 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1875018664 // payload: type,
1875118665 ty.errorUnionPayload(zcu).toIntern(),
1875218666 };
18753 return Air.internedToRef((try pt.intern(.{ .un = .{
18667 return Air.internedToRef((try pt.internUnion(.{
1875418668 .ty = type_info_ty.toIntern(),
1875518669 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.error_union))).toIntern(),
1875618670 .val = try pt.intern(.{ .aggregate = .{
1875718671 .ty = error_union_field_ty.toIntern(),
1875818672 .storage = .{ .elems = &field_values },
1875918673 } }),
18760 } })));
18674 })));
1876118675 },
1876218676 .@"enum" => {
1876318677 const is_exhaustive = Value.makeBool(ip.loadEnumType(ty.toIntern()).tag_mode != .nonexhaustive);
1876418678
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 };
18679 const enum_field_ty = try getInnerType(sema, block, src, type_info_ty, "EnumField");
1877518680
1877618681 const enum_field_vals = try sema.arena.alloc(InternPool.Index, ip.loadEnumType(ty.toIntern()).names.len);
1877718682 for (enum_field_vals, 0..) |*field_val, tag_index| {
......@@ -18858,16 +18763,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1885818763
1885918764 const decls_val = try sema.typeInfoDecls(block, src, type_info_ty, ip.loadEnumType(ty.toIntern()).namespace.toOptional());
1886018765
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 };
18766 const type_enum_ty = try getInnerType(sema, block, src, type_info_ty, "Enum");
1887118767
1887218768 const field_values = .{
1887318769 // tag_type: type,
......@@ -18879,37 +18775,18 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1887918775 // is_exhaustive: bool,
1888018776 is_exhaustive.toIntern(),
1888118777 };
18882 return Air.internedToRef((try pt.intern(.{ .un = .{
18778 return Air.internedToRef((try pt.internUnion(.{
1888318779 .ty = type_info_ty.toIntern(),
1888418780 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.@"enum"))).toIntern(),
1888518781 .val = try pt.intern(.{ .aggregate = .{
1888618782 .ty = type_enum_ty.toIntern(),
1888718783 .storage = .{ .elems = &field_values },
1888818784 } }),
18889 } })));
18785 })));
1889018786 },
1889118787 .@"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 };
18788 const type_union_ty = try getInnerType(sema, block, src, type_info_ty, "Union");
18789 const union_field_ty = try getInnerType(sema, block, src, type_info_ty, "UnionField");
1891318790
1891418791 try ty.resolveLayout(pt); // Getting alignment requires type layout
1891518792 const union_obj = zcu.typeToUnion(ty).?;
......@@ -19004,16 +18881,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1900418881 .val = if (ty.unionTagType(zcu)) |tag_ty| tag_ty.toIntern() else .none,
1900518882 } });
1900618883
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 };
18884 const container_layout_ty = try getBuiltinInnerType(sema, block, src, "Type", "ContainerLayout");
1901718885
1901818886 const field_values = .{
1901918887 // layout: ContainerLayout,
......@@ -19026,37 +18894,18 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1902618894 // decls: []const Declaration,
1902718895 decls_val,
1902818896 };
19029 return Air.internedToRef((try pt.intern(.{ .un = .{
18897 return Air.internedToRef((try pt.internUnion(.{
1903018898 .ty = type_info_ty.toIntern(),
1903118899 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.@"union"))).toIntern(),
1903218900 .val = try pt.intern(.{ .aggregate = .{
1903318901 .ty = type_union_ty.toIntern(),
1903418902 .storage = .{ .elems = &field_values },
1903518903 } }),
19036 } })));
18904 })));
1903718905 },
1903818906 .@"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 };
18907 const type_struct_ty = try getInnerType(sema, block, src, type_info_ty, "Struct");
18908 const struct_field_ty = try getInnerType(sema, block, src, type_info_ty, "StructField");
1906018909
1906118910 try ty.resolveLayout(pt); // Getting alignment requires type layout
1906218911
......@@ -19233,16 +19082,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1923319082 } else .none,
1923419083 } });
1923519084
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 };
19085 const container_layout_ty = try getInnerType(sema, block, src, type_info_ty, "ContainerLayout");
1924619086
1924719087 const layout = ty.containerLayout(zcu);
1924819088
......@@ -19258,26 +19098,17 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1925819098 // is_tuple: bool,
1925919099 Value.makeBool(ty.isTuple(zcu)).toIntern(),
1926019100 };
19261 return Air.internedToRef((try pt.intern(.{ .un = .{
19101 return Air.internedToRef((try pt.internUnion(.{
1926219102 .ty = type_info_ty.toIntern(),
1926319103 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.@"struct"))).toIntern(),
1926419104 .val = try pt.intern(.{ .aggregate = .{
1926519105 .ty = type_struct_ty.toIntern(),
1926619106 .storage = .{ .elems = &field_values },
1926719107 } }),
19268 } })));
19108 })));
1926919109 },
1927019110 .@"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 };
19111 const type_opaque_ty = try getInnerType(sema, block, src, type_info_ty, "Opaque");
1928119112
1928219113 try ty.resolveFields(pt);
1928319114 const decls_val = try sema.typeInfoDecls(block, src, type_info_ty, ty.getNamespace(zcu));
......@@ -19286,14 +19117,14 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1928619117 // decls: []const Declaration,
1928719118 decls_val,
1928819119 };
19289 return Air.internedToRef((try pt.intern(.{ .un = .{
19120 return Air.internedToRef((try pt.internUnion(.{
1929019121 .ty = type_info_ty.toIntern(),
1929119122 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.@"opaque"))).toIntern(),
1929219123 .val = try pt.intern(.{ .aggregate = .{
1929319124 .ty = type_opaque_ty.toIntern(),
1929419125 .storage = .{ .elems = &field_values },
1929519126 } }),
19296 } })));
19127 })));
1929719128 },
1929819129 .frame => return sema.failWithUseOfAsync(block, src),
1929919130 .@"anyframe" => return sema.failWithUseOfAsync(block, src),
......@@ -19309,19 +19140,9 @@ fn typeInfoDecls(
1930919140) CompileError!InternPool.Index {
1931019141 const pt = sema.pt;
1931119142 const zcu = pt.zcu;
19312 const ip = &zcu.intern_pool;
1931319143 const gpa = sema.gpa;
1931419144
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 };
19145 const declaration_ty = try getInnerType(sema, block, src, type_info_ty, "Declaration");
1932519146
1932619147 var decl_vals = std.ArrayList(InternPool.Index).init(gpa);
1932719148 defer decl_vals.deinit();
......@@ -20809,11 +20630,11 @@ fn unionInit(
2080920630 if (try sema.resolveValue(init)) |init_val| {
2081020631 const tag_ty = union_ty.unionTagTypeHypothetical(zcu);
2081120632 const tag_val = try pt.enumValueFieldIndex(tag_ty, field_index);
20812 return Air.internedToRef((try pt.intern(.{ .un = .{
20633 return Air.internedToRef((try pt.internUnion(.{
2081320634 .ty = union_ty.toIntern(),
2081420635 .tag = tag_val.toIntern(),
2081520636 .val = init_val.toIntern(),
20816 } })));
20637 })));
2081720638 }
2081820639
2081920640 try sema.requireRuntimeBlock(block, init_src, null);
......@@ -20949,11 +20770,11 @@ fn zirStructInit(
2094920770 const init_inst = try sema.coerce(block, field_ty, uncoerced_init_inst, field_src);
2095020771
2095120772 if (try sema.resolveValue(init_inst)) |val| {
20952 const struct_val = Value.fromInterned(try pt.intern(.{ .un = .{
20773 const struct_val = Value.fromInterned(try pt.internUnion(.{
2095320774 .ty = resolved_ty.toIntern(),
2095420775 .tag = tag_val.toIntern(),
2095520776 .val = val.toIntern(),
20956 } }));
20777 }));
2095720778 const final_val_inst = try sema.coerce(block, result_ty, Air.internedToRef(struct_val.toIntern()), src);
2095820779 const final_val = (try sema.resolveValue(final_val_inst)).?;
2095920780 return sema.addConstantMaybeRef(final_val.toIntern(), is_ref);
......@@ -21869,11 +21690,20 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2186921690 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
2187021691 const src = block.nodeOffset(inst_data.src_node);
2187121692 const operand = try sema.resolveInst(inst_data.operand);
21693 return analyzeTagName(sema, block, src, operand_src, operand);
21694}
21695
21696fn analyzeTagName(
21697 sema: *Sema,
21698 block: *Block,
21699 src: LazySrcLoc,
21700 operand_src: LazySrcLoc,
21701 operand: Air.Inst.Ref,
21702) CompileError!Air.Inst.Ref {
2187221703 const operand_ty = sema.typeOf(operand);
2187321704 const pt = sema.pt;
2187421705 const zcu = pt.zcu;
2187521706 const ip = &zcu.intern_pool;
21876
2187721707 try operand_ty.resolveLayout(pt);
2187821708 const enum_ty = switch (operand_ty.zigTypeTag(zcu)) {
2187921709 .enum_literal => {
......@@ -27840,7 +27670,7 @@ fn explainWhyTypeIsNotPacked(
2784027670 }
2784127671}
2784227672
27843fn prepareSimplePanic(sema: *Sema, block: *Block, src: LazySrcLoc) !void {
27673fn preparePanic(sema: *Sema, block: *Block, src: LazySrcLoc) !void {
2784427674 const pt = sema.pt;
2784527675 const zcu = pt.zcu;
2784627676
......@@ -27871,33 +27701,12 @@ fn prepareSimplePanic(sema: *Sema, block: *Block, src: LazySrcLoc) !void {
2787127701 .val = .none,
2787227702 } });
2787327703 }
27874}
27875
27876/// Backends depend on panic decls being available when lowering safety-checked
27877/// instructions. This function ensures the panic function will be available to
27878/// be called during that time.
27879fn preparePanicId(sema: *Sema, block: *Block, src: LazySrcLoc, panic_id: Zcu.PanicId) !InternPool.Nav.Index {
27880 const pt = sema.pt;
27881 const zcu = pt.zcu;
27882 const gpa = sema.gpa;
27883 if (zcu.panic_messages[@intFromEnum(panic_id)].unwrap()) |x| return x;
27884
27885 try sema.prepareSimplePanic(block, src);
2788627704
27887 const panic_messages_ty = try pt.getBuiltinType("panic_messages");
27888 const msg_nav_index = (sema.namespaceLookup(
27889 block,
27890 LazySrcLoc.unneeded,
27891 panic_messages_ty.getNamespaceIndex(zcu),
27892 try zcu.intern_pool.getOrPutString(gpa, pt.tid, @tagName(panic_id), .no_embedded_nulls),
27893 ) catch |err| switch (err) {
27894 error.AnalysisFail => @panic("std.builtin.panic_messages is corrupt"),
27895 error.GenericPoison, error.ComptimeReturn, error.ComptimeBreak => unreachable,
27896 error.OutOfMemory => |e| return e,
27897 }).?;
27898 try sema.ensureNavResolved(src, msg_nav_index);
27899 zcu.panic_messages[@intFromEnum(panic_id)] = msg_nav_index.toOptional();
27900 return msg_nav_index;
27705 if (zcu.panic_cause_type == .none) {
27706 const panic_cause_ty = try pt.getBuiltinType("PanicCause");
27707 try panic_cause_ty.resolveFields(pt);
27708 zcu.panic_cause_type = panic_cause_ty.toIntern();
27709 }
2790127710}
2790227711
2790327712fn addSafetyCheck(
......@@ -27905,7 +27714,7 @@ fn addSafetyCheck(
2790527714 parent_block: *Block,
2790627715 src: LazySrcLoc,
2790727716 ok: Air.Inst.Ref,
27908 panic_id: Zcu.PanicId,
27717 panic_cause_tag: PanicCauseTag,
2790927718) !void {
2791027719 const gpa = sema.gpa;
2791127720 assert(!parent_block.is_comptime);
......@@ -27923,7 +27732,7 @@ fn addSafetyCheck(
2792327732
2792427733 defer fail_block.instructions.deinit(gpa);
2792527734
27926 try sema.safetyPanic(&fail_block, src, panic_id);
27735 try sema.safetyPanic(&fail_block, src, panic_cause_tag);
2792727736 try sema.addSafetyCheckExtra(parent_block, ok, &fail_block);
2792827737}
2792927738
......@@ -27992,30 +27801,7 @@ fn addSafetyCheckExtra(
2799227801 parent_block.instructions.appendAssumeCapacity(block_inst);
2799327802}
2799427803
27995fn panicWithMsg(sema: *Sema, block: *Block, src: LazySrcLoc, msg_inst: Air.Inst.Ref, operation: CallOperation) !void {
27996 const pt = sema.pt;
27997 const zcu = pt.zcu;
27998
27999 if (!zcu.backendSupportsFeature(.panic_fn)) {
28000 _ = try block.addNoOp(.trap);
28001 return;
28002 }
28003
28004 try sema.prepareSimplePanic(block, src);
28005
28006 const panic_func = zcu.funcInfo(zcu.panic_func_index);
28007 const panic_fn = try sema.analyzeNavVal(block, src, panic_func.owner_nav);
28008 const null_stack_trace = Air.internedToRef(zcu.null_stack_trace);
28009
28010 const opt_usize_ty = try pt.optionalType(.usize_type);
28011 const null_ret_addr = Air.internedToRef((try pt.intern(.{ .opt = .{
28012 .ty = opt_usize_ty.toIntern(),
28013 .val = .none,
28014 } })));
28015 try sema.callBuiltin(block, src, panic_fn, .auto, &.{ msg_inst, null_stack_trace, null_ret_addr }, operation);
28016}
28017
28018fn panicUnwrapError(
27804fn addSafetyCheckUnwrapError(
2801927805 sema: *Sema,
2802027806 parent_block: *Block,
2802127807 src: LazySrcLoc,
......@@ -28023,12 +27809,8 @@ fn panicUnwrapError(
2802327809 unwrap_err_tag: Air.Inst.Tag,
2802427810 is_non_err_tag: Air.Inst.Tag,
2802527811) !void {
28026 const pt = sema.pt;
2802727812 assert(!parent_block.is_comptime);
2802827813 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 }
2803227814 const gpa = sema.gpa;
2803327815
2803427816 var fail_block: Block = .{
......@@ -28044,21 +27826,13 @@ fn panicUnwrapError(
2804427826
2804527827 defer fail_block.instructions.deinit(gpa);
2804627828
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 }
27829 const err = try fail_block.addTyOp(unwrap_err_tag, Type.anyerror, operand);
27830 try callPanic(sema, &fail_block, src, .unwrap_error, err, .@"safety check");
27831
2805827832 try sema.addSafetyCheckExtra(parent_block, ok, &fail_block);
2805927833}
2806027834
28061fn panicIndexOutOfBounds(
27835fn addSafetyCheckIndexOob(
2806227836 sema: *Sema,
2806327837 parent_block: *Block,
2806427838 src: LazySrcLoc,
......@@ -28067,14 +27841,71 @@ fn panicIndexOutOfBounds(
2806727841 cmp_op: Air.Inst.Tag,
2806827842) !void {
2806927843 assert(!parent_block.is_comptime);
27844 const gpa = sema.gpa;
2807027845 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);
27846
27847 var fail_block: Block = .{
27848 .parent = parent_block,
27849 .sema = sema,
27850 .namespace = parent_block.namespace,
27851 .instructions = .{},
27852 .inlining = parent_block.inlining,
27853 .is_comptime = false,
27854 .src_base_inst = parent_block.src_base_inst,
27855 .type_name_ctx = parent_block.type_name_ctx,
27856 };
27857
27858 defer fail_block.instructions.deinit(gpa);
27859
27860 const oob_ty = try getBuiltinInnerType(sema, &fail_block, src, "PanicCause", "IndexOutOfBounds");
27861 comptime {
27862 const fields = @typeInfo(std.builtin.PanicCause.IndexOutOfBounds).@"struct".fields;
27863 assert(std.mem.eql(u8, fields[0].name, "index"));
27864 assert(std.mem.eql(u8, fields[1].name, "len"));
27865 assert(fields.len == 2);
2807327866 }
28074 try sema.safetyCheckFormatted(parent_block, src, ok, "panicOutOfBounds", &.{ index, len });
27867 const panic_cause_payload = try fail_block.addAggregateInit(oob_ty, &.{ index, len });
27868 try callPanic(sema, &fail_block, src, .index_out_of_bounds, panic_cause_payload, .@"safety check");
27869 try sema.addSafetyCheckExtra(parent_block, ok, &fail_block);
2807527870}
2807627871
28077fn panicInactiveUnionField(
27872fn addSafetyCheckStartGreaterThanEnd(
27873 sema: *Sema,
27874 parent_block: *Block,
27875 src: LazySrcLoc,
27876 start: Air.Inst.Ref,
27877 end: Air.Inst.Ref,
27878) !void {
27879 assert(!parent_block.is_comptime);
27880 const gpa = sema.gpa;
27881 const ok = try parent_block.addBinOp(.cmp_lte, start, end);
27882
27883 var fail_block: Block = .{
27884 .parent = parent_block,
27885 .sema = sema,
27886 .namespace = parent_block.namespace,
27887 .instructions = .{},
27888 .inlining = parent_block.inlining,
27889 .is_comptime = false,
27890 .src_base_inst = parent_block.src_base_inst,
27891 .type_name_ctx = parent_block.type_name_ctx,
27892 };
27893
27894 defer fail_block.instructions.deinit(gpa);
27895
27896 const oob_ty = try getBuiltinInnerType(sema, &fail_block, src, "PanicCause", "StartIndexGreaterThanEnd");
27897 comptime {
27898 const fields = @typeInfo(std.builtin.PanicCause.StartIndexGreaterThanEnd).@"struct".fields;
27899 assert(std.mem.eql(u8, fields[0].name, "start"));
27900 assert(std.mem.eql(u8, fields[1].name, "end"));
27901 assert(fields.len == 2);
27902 }
27903 const panic_cause_payload = try fail_block.addAggregateInit(oob_ty, &.{ start, end });
27904 try callPanic(sema, &fail_block, src, .start_index_greater_than_end, panic_cause_payload, .@"safety check");
27905 try sema.addSafetyCheckExtra(parent_block, ok, &fail_block);
27906}
27907
27908fn addSafetyCheckInactiveUnionField(
2807827909 sema: *Sema,
2807927910 parent_block: *Block,
2808027911 src: LazySrcLoc,
......@@ -28082,14 +27913,39 @@ fn panicInactiveUnionField(
2808227913 wanted_tag: Air.Inst.Ref,
2808327914) !void {
2808427915 assert(!parent_block.is_comptime);
27916 const gpa = sema.gpa;
2808527917 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 });
27918
27919 var fail_block: Block = .{
27920 .parent = parent_block,
27921 .sema = sema,
27922 .namespace = parent_block.namespace,
27923 .instructions = .{},
27924 .inlining = parent_block.inlining,
27925 .is_comptime = false,
27926 .src_base_inst = parent_block.src_base_inst,
27927 .type_name_ctx = parent_block.type_name_ctx,
27928 };
27929
27930 defer fail_block.instructions.deinit(gpa);
27931
27932 const payload_ty = try getBuiltinInnerType(sema, &fail_block, src, "PanicCause", "InactiveUnionField");
27933 comptime {
27934 const fields = @typeInfo(std.builtin.PanicCause.InactiveUnionField).@"struct".fields;
27935 assert(std.mem.eql(u8, fields[0].name, "active"));
27936 assert(std.mem.eql(u8, fields[1].name, "accessed"));
27937 assert(fields.len == 2);
27938 }
27939 // TODO: before merging the branch, check how many safety checks end up being emitted
27940 // for union field accesses and avoid extraneous ones.
27941 const active_str = try analyzeTagName(sema, &fail_block, src, src, active_tag);
27942 const accessed_str = try analyzeTagName(sema, &fail_block, src, src, wanted_tag);
27943 const panic_cause_payload = try fail_block.addAggregateInit(payload_ty, &.{ active_str, accessed_str });
27944 try callPanic(sema, &fail_block, src, .inactive_union_field, panic_cause_payload, .@"safety check");
27945 try sema.addSafetyCheckExtra(parent_block, ok, &fail_block);
2809027946}
2809127947
28092fn panicSentinelMismatch(
27948fn addSafetyCheckSentinelMismatch(
2809327949 sema: *Sema,
2809427950 parent_block: *Block,
2809527951 src: LazySrcLoc,
......@@ -28099,6 +27955,7 @@ fn panicSentinelMismatch(
2809927955 sentinel_index: Air.Inst.Ref,
2810027956) !void {
2810127957 assert(!parent_block.is_comptime);
27958 const gpa = sema.gpa;
2810227959 const pt = sema.pt;
2810327960 const zcu = pt.zcu;
2810427961 const expected_sentinel_val = maybe_sentinel orelse return;
......@@ -28114,8 +27971,7 @@ fn panicSentinelMismatch(
2811427971 };
2811527972
2811627973 const ok = if (sentinel_ty.zigTypeTag(zcu) == .vector) ok: {
28117 const eql =
28118 try parent_block.addCmpVector(expected_sentinel, actual_sentinel, .eq);
27974 const eql = try parent_block.addCmpVector(expected_sentinel, actual_sentinel, .eq);
2811927975 break :ok try parent_block.addInst(.{
2812027976 .tag = .reduce,
2812127977 .data = .{ .reduce = .{
......@@ -28128,25 +27984,6 @@ fn panicSentinelMismatch(
2812827984 break :ok try parent_block.addBinOp(.cmp_eq, expected_sentinel, actual_sentinel);
2812927985 };
2813027986
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 });
28135}
28136
28137fn safetyCheckFormatted(
28138 sema: *Sema,
28139 parent_block: *Block,
28140 src: LazySrcLoc,
28141 ok: Air.Inst.Ref,
28142 func: []const u8,
28143 args: []const Air.Inst.Ref,
28144) CompileError!void {
28145 const pt = sema.pt;
28146 const zcu = pt.zcu;
28147 assert(zcu.comp.formatted_panics);
28148 const gpa = sema.gpa;
28149
2815027987 var fail_block: Block = .{
2815127988 .parent = parent_block,
2815227989 .sema = sema,
......@@ -28160,20 +27997,29 @@ fn safetyCheckFormatted(
2816027997
2816127998 defer fail_block.instructions.deinit(gpa);
2816227999
28163 if (!zcu.backendSupportsFeature(.safety_check_formatted)) {
28164 _ = try fail_block.addNoOp(.trap);
28000 // A different PanicCause tag must be used depending on what payload type it can be fit into.
28001 // If it cannot fit into any, the "other" tag can be used, which does not try to carry the
28002 // sentinel value data.
28003
28004 if (sentinel_ty.isUnsignedInt(zcu) and sentinel_ty.intInfo(zcu).bits <= Type.usize.intInfo(zcu).bits) {
28005 const mm_ty = try getBuiltinInnerType(sema, &fail_block, src, "PanicCause", "SentinelMismatchUsize");
28006 comptime {
28007 const fields = @typeInfo(std.builtin.PanicCause.SentinelMismatchUsize).@"struct".fields;
28008 assert(std.mem.eql(u8, fields[0].name, "expected"));
28009 assert(std.mem.eql(u8, fields[1].name, "found"));
28010 assert(fields.len == 2);
28011 }
28012 const panic_cause_payload = &fail_block.addAggregateInit(mm_ty, &.{ expected_sentinel, actual_sentinel });
28013 try callPanic(sema, &fail_block, src, .sentinel_mismatch_usize, panic_cause_payload, .@"safety check");
2816528014 } else {
28166 const panic_fn = try pt.getBuiltin(func);
28167 try sema.callBuiltin(&fail_block, src, panic_fn, .auto, args, .@"safety check");
28015 try callPanic(sema, &fail_block, src, .sentinel_mismatch_other, .void_value, .@"safety check");
2816828016 }
2816928017 try sema.addSafetyCheckExtra(parent_block, ok, &fail_block);
2817028018}
2817128019
2817228020/// This does not set `sema.branch_hint`.
28173fn safetyPanic(sema: *Sema, block: *Block, src: LazySrcLoc, panic_id: Zcu.PanicId) CompileError!void {
28174 const msg_nav_index = try sema.preparePanicId(block, src, panic_id);
28175 const msg_inst = try sema.analyzeNavVal(block, src, msg_nav_index);
28176 try sema.panicWithMsg(block, src, msg_inst, .@"safety check");
28021fn safetyPanic(sema: *Sema, block: *Block, src: LazySrcLoc, panic_cause_tag: PanicCauseTag) CompileError!void {
28022 try callPanic(sema, block, src, panic_cause_tag, .void_value, .@"safety check");
2817728023}
2817828024
2817928025fn emitBackwardBranch(sema: *Sema, block: *Block, src: LazySrcLoc) !void {
......@@ -29229,7 +29075,7 @@ fn unionFieldPtr(
2922929075 // TODO would it be better if get_union_tag supported pointers to unions?
2923029076 const union_val = try block.addTyOp(.load, union_ty, union_ptr);
2923129077 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);
29078 try sema.addSafetyCheckInactiveUnionField(block, src, active_tag, wanted_tag);
2923329079 }
2923429080 if (field_ty.zigTypeTag(zcu) == .noreturn) {
2923529081 _ = try block.addNoOp(.unreach);
......@@ -29304,7 +29150,7 @@ fn unionFieldVal(
2930429150 const wanted_tag_val = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
2930529151 const wanted_tag = Air.internedToRef(wanted_tag_val.toIntern());
2930629152 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);
29153 try sema.addSafetyCheckInactiveUnionField(block, src, active_tag, wanted_tag);
2930829154 }
2930929155 if (field_ty.zigTypeTag(zcu) == .noreturn) {
2931029156 _ = try block.addNoOp(.unreach);
......@@ -29668,11 +29514,11 @@ fn elemValArray(
2966829514
2966929515 const runtime_src = if (maybe_undef_array_val != null) elem_index_src else array_src;
2967029516 if (oob_safety and block.wantSafety()) {
29671 // Runtime check is only needed if unable to comptime check
29517 // Runtime check is only needed if unable to comptime check.
2967229518 if (maybe_index_val == null) {
2967329519 const len_inst = try pt.intRef(Type.usize, array_len);
2967429520 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);
29521 try sema.addSafetyCheckIndexOob(block, src, elem_index, len_inst, cmp_op);
2967629522 }
2967729523 }
2967829524
......@@ -29740,7 +29586,7 @@ fn elemPtrArray(
2974029586 if (oob_safety and block.wantSafety() and offset == null) {
2974129587 const len_inst = try pt.intRef(Type.usize, array_len);
2974229588 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);
29589 try sema.addSafetyCheckIndexOob(block, src, elem_index, len_inst, cmp_op);
2974429590 }
2974529591
2974629592 return block.addPtrElemPtr(array_ptr, elem_index, elem_ptr_ty);
......@@ -29799,7 +29645,7 @@ fn elemValSlice(
2979929645 else
2980029646 try block.addTyOp(.slice_len, Type.usize, slice);
2980129647 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);
29648 try sema.addSafetyCheckIndexOob(block, src, elem_index, len_inst, cmp_op);
2980329649 }
2980429650 return block.addBinOp(.slice_elem_val, slice, elem_index);
2980529651}
......@@ -29859,7 +29705,7 @@ fn elemPtrSlice(
2985929705 break :len try block.addTyOp(.slice_len, Type.usize, slice);
2986029706 };
2986129707 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);
29708 try sema.addSafetyCheckIndexOob(block, src, elem_index, len_inst, cmp_op);
2986329709 }
2986429710 return block.addSliceElemPtr(slice, elem_index, elem_ptr_ty);
2986529711}
......@@ -33666,12 +33512,7 @@ fn analyzeSlice(
3366633512 // requirement: start <= end
3366733513 assert(!block.is_comptime);
3366833514 try sema.requireRuntimeBlock(block, src, runtime_src.?);
33669 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 }
33515 try sema.addSafetyCheckStartGreaterThanEnd(block, src, start, end);
3367533516 }
3367633517 const new_len = if (by_length)
3367733518 try sema.coerce(block, Type.usize, uncasted_end_opt, end_src)
......@@ -33726,11 +33567,11 @@ fn analyzeSlice(
3372633567 else
3372733568 end;
3372833569
33729 try sema.panicIndexOutOfBounds(block, src, actual_end, actual_len, .cmp_lte);
33570 try sema.addSafetyCheckIndexOob(block, src, actual_end, actual_len, .cmp_lte);
3373033571 }
3373133572
3373233573 // requirement: result[new_len] == slice_sentinel
33733 try sema.panicSentinelMismatch(block, src, slice_sentinel, elem_ty, result, new_len);
33574 try sema.addSafetyCheckSentinelMismatch(block, src, slice_sentinel, elem_ty, result, new_len);
3373433575 }
3373533576 return result;
3373633577 };
......@@ -33789,11 +33630,11 @@ fn analyzeSlice(
3378933630 try sema.analyzeArithmetic(block, .add, end, .one, src, end_src, end_src, true)
3379033631 else
3379133632 end;
33792 try sema.panicIndexOutOfBounds(block, src, actual_end, len_inst, .cmp_lte);
33633 try sema.addSafetyCheckIndexOob(block, src, actual_end, len_inst, .cmp_lte);
3379333634 }
3379433635
3379533636 // requirement: start <= end
33796 try sema.panicIndexOutOfBounds(block, src, start, end, .cmp_lte);
33637 try sema.addSafetyCheckIndexOob(block, src, start, end, .cmp_lte);
3379733638 }
3379833639 const result = try block.addInst(.{
3379933640 .tag = .slice,
......@@ -33807,7 +33648,7 @@ fn analyzeSlice(
3380733648 });
3380833649 if (block.wantSafety()) {
3380933650 // requirement: result[new_len] == slice_sentinel
33810 try sema.panicSentinelMismatch(block, src, slice_sentinel, elem_ty, result, new_len);
33651 try sema.addSafetyCheckSentinelMismatch(block, src, slice_sentinel, elem_ty, result, new_len);
3381133652 }
3381233653 return result;
3381333654}
......@@ -37688,11 +37529,11 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3768837529 const only_field_ty = Type.fromInterned(union_obj.field_types.get(ip)[0]);
3768937530 const val_val = (try sema.typeHasOnePossibleValue(only_field_ty)) orelse
3769037531 return null;
37691 const only = try pt.intern(.{ .un = .{
37532 const only = try pt.internUnion(.{
3769237533 .ty = ty.toIntern(),
3769337534 .tag = tag_val.toIntern(),
3769437535 .val = val_val.toIntern(),
37695 } });
37536 });
3769637537 return Value.fromInterned(only);
3769737538 },
3769837539
......@@ -38849,7 +38690,7 @@ fn analyzeUnreachable(sema: *Sema, block: *Block, src: LazySrcLoc, safety_check:
3884938690 sema.branch_hint = .cold;
3885038691 }
3885138692
38852 try sema.safetyPanic(block, src, .unreach);
38693 try sema.safetyPanic(block, src, .reached_unreachable);
3885338694 } else {
3885438695 _ = try block.addNoOp(.unreach);
3885538696 }
......@@ -39123,3 +38964,36 @@ const loadComptimePtr = @import("Sema/comptime_ptr_access.zig").loadComptimePtr;
3912338964const ComptimeLoadResult = @import("Sema/comptime_ptr_access.zig").ComptimeLoadResult;
3912438965const storeComptimePtr = @import("Sema/comptime_ptr_access.zig").storeComptimePtr;
3912538966const ComptimeStoreResult = @import("Sema/comptime_ptr_access.zig").ComptimeStoreResult;
38967
38968/// Convenience function that looks 2 levels deep into `std.builtin`.
38969fn getBuiltinInnerType(
38970 sema: *Sema,
38971 block: *Block,
38972 src: LazySrcLoc,
38973 outer_name: []const u8,
38974 inner_name: []const u8,
38975) !Type {
38976 const outer_ty = try sema.pt.getBuiltinType(outer_name);
38977 return getInnerType(sema, block, src, outer_ty, inner_name);
38978}
38979
38980fn getInnerType(
38981 sema: *Sema,
38982 block: *Block,
38983 src: LazySrcLoc,
38984 outer_ty: Type,
38985 inner_name: []const u8,
38986) !Type {
38987 const pt = sema.pt;
38988 const zcu = pt.zcu;
38989 const ip = &zcu.intern_pool;
38990 const gpa = sema.gpa;
38991 const nav = try sema.namespaceLookup(
38992 block,
38993 src,
38994 outer_ty.getNamespaceIndex(zcu),
38995 try ip.getOrPutString(gpa, pt.tid, inner_name, .no_embedded_nulls),
38996 ) orelse return sema.fail(block, src, "std.builtin missing {s}", .{inner_name});
38997 try sema.ensureNavResolved(src, nav);
38998 return Type.fromInterned(ip.getNav(nav).status.resolved.val);
38999}
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+1-39
......@@ -210,45 +210,15 @@ all_type_references: std.ArrayListUnmanaged(TypeReference) = .empty,
210210/// Freelist of indices in `all_type_references`.
211211free_type_references: std.ArrayListUnmanaged(u32) = .empty,
212212
213panic_messages: [PanicId.len]InternPool.Nav.Index.Optional = .{.none} ** PanicId.len,
214213/// The panic function body.
215214panic_func_index: InternPool.Index = .none,
216215null_stack_trace: InternPool.Index = .none,
216panic_cause_type: InternPool.Index = .none,
217217
218218generation: u32 = 0,
219219
220220pub const PerThread = @import("Zcu/PerThread.zig");
221221
222pub const PanicId = enum {
223 unreach,
224 unwrap_null,
225 cast_to_null,
226 incorrect_alignment,
227 invalid_error_code,
228 cast_truncated_data,
229 negative_to_unsigned,
230 integer_overflow,
231 shl_overflow,
232 shr_overflow,
233 divide_by_zero,
234 exact_division_remainder,
235 inactive_union_field,
236 integer_part_out_of_bounds,
237 corrupt_switch,
238 shift_rhs_too_big,
239 invalid_enum_value,
240 sentinel_mismatch,
241 unwrap_error,
242 index_out_of_bounds,
243 start_index_greater_than_end,
244 for_len_mismatch,
245 memcpy_len_mismatch,
246 memcpy_alias,
247 noreturn_returned,
248
249 pub const len = @typeInfo(PanicId).@"enum".fields.len;
250};
251
252222pub const GlobalErrorSet = std.AutoArrayHashMapUnmanaged(InternPool.NullTerminatedString, void);
253223
254224pub const CImportError = struct {
......@@ -2926,14 +2896,6 @@ pub const Feature = enum {
29262896 /// When this feature is enabled, Sema will emit calls to `std.builtin.panic`
29272897 /// for things like safety checks and unreachables. Otherwise traps will be emitted.
29282898 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,
29372899 /// When this feature is enabled, Sema will insert tracer functions for gathering a stack
29382900 /// trace for error returns.
29392901 error_return_trace,
src/Zcu/PerThread.zig+9-3
......@@ -2697,11 +2697,16 @@ pub fn reportRetryableFileError(
26972697 gop.value_ptr.* = err_msg;
26982698}
26992699
2700///Shortcut for calling `intern_pool.get`.
2700/// Shortcut for calling `intern_pool.get`.
27012701pub fn intern(pt: Zcu.PerThread, key: InternPool.Key) Allocator.Error!InternPool.Index {
27022702 return pt.zcu.intern_pool.get(pt.zcu.gpa, pt.tid, key);
27032703}
27042704
2705/// Shortcut for calling `intern_pool.getUnion`.
2706pub fn internUnion(pt: Zcu.PerThread, un: InternPool.Key.Union) Allocator.Error!InternPool.Index {
2707 return pt.zcu.intern_pool.getUnion(pt.zcu.gpa, pt.tid, un);
2708}
2709
27052710/// Essentially a shortcut for calling `intern_pool.getCoerced`.
27062711/// However, this function also allows coercing `extern`s. The `InternPool` function can't do
27072712/// this because it requires potentially pushing to the job queue.
......@@ -2949,11 +2954,12 @@ pub fn intValue_i64(pt: Zcu.PerThread, ty: Type, x: i64) Allocator.Error!Value {
29492954}
29502955
29512956pub fn unionValue(pt: Zcu.PerThread, union_ty: Type, tag: Value, val: Value) Allocator.Error!Value {
2952 return Value.fromInterned(try pt.intern(.{ .un = .{
2957 const zcu = pt.zcu;
2958 return Value.fromInterned(try zcu.intern_pool.getUnion(zcu.gpa, pt.tid, .{
29532959 .ty = union_ty.toIntern(),
29542960 .tag = tag.toIntern(),
29552961 .val = val.toIntern(),
2956 } }));
2962 }));
29572963}
29582964
29592965/// This function casts the float representation down to the representation of the type, potentially
src/crash_report.zig+27-21
......@@ -17,7 +17,7 @@ const Decl = Zcu.Decl;
1717/// To use these crash report diagnostics, publish this panic in your main file
1818/// and add `pub const enable_segfault_handler = false;` to your `std_options`.
1919/// 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;
20pub const panic = if (build_options.enable_debug_extensions) compilerPanic else std.debug.defaultPanic;
2121
2222/// Install signal handlers to identify crashes and report diagnostics.
2323pub fn initialize() void {
......@@ -152,12 +152,16 @@ fn writeFilePath(file: *Zcu.File, writer: anytype) !void {
152152 try writer.writeAll(file.sub_file_path);
153153}
154154
155pub fn compilerPanic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace, maybe_ret_addr: ?usize) noreturn {
155pub fn compilerPanic(
156 cause: std.builtin.PanicCause,
157 error_return_trace: ?*std.builtin.StackTrace,
158 maybe_ret_addr: ?usize,
159) noreturn {
156160 @branchHint(.cold);
157161 PanicSwitch.preDispatch();
158162 const ret_addr = maybe_ret_addr orelse @returnAddress();
159163 const stack_ctx: StackContext = .{ .current = .{ .ret_addr = ret_addr } };
160 PanicSwitch.dispatch(error_return_trace, stack_ctx, msg);
164 PanicSwitch.dispatch(error_return_trace, stack_ctx, cause);
161165}
162166
163167/// Attaches a global SIGSEGV handler
......@@ -354,17 +358,17 @@ const PanicSwitch = struct {
354358 pub fn dispatch(
355359 trace: ?*const std.builtin.StackTrace,
356360 stack_ctx: StackContext,
357 msg: []const u8,
361 panic_cause: std.builtin.PanicCause,
358362 ) noreturn {
359363 var panic_state: *volatile PanicState = &panic_state_raw;
360364 debug.assert(panic_state.awaiting_dispatch);
361365 panic_state.awaiting_dispatch = false;
362366 nosuspend switch (panic_state.recover_stage) {
363 .initialize => goTo(initPanic, .{ panic_state, trace, stack_ctx, msg }),
364 .report_stack => goTo(recoverReportStack, .{ panic_state, trace, stack_ctx, msg }),
365 .release_mutex => goTo(recoverReleaseMutex, .{ panic_state, trace, stack_ctx, msg }),
366 .release_ref_count => goTo(recoverReleaseRefCount, .{ panic_state, trace, stack_ctx, msg }),
367 .abort => goTo(recoverAbort, .{ panic_state, trace, stack_ctx, msg }),
367 .initialize => goTo(initPanic, .{ panic_state, trace, stack_ctx, panic_cause }),
368 .report_stack => goTo(recoverReportStack, .{ panic_state, trace, stack_ctx, panic_cause }),
369 .release_mutex => goTo(recoverReleaseMutex, .{ panic_state, trace, stack_ctx, panic_cause }),
370 .release_ref_count => goTo(recoverReleaseRefCount, .{ panic_state, trace, stack_ctx, panic_cause }),
371 .abort => goTo(recoverAbort, .{ panic_state, trace, stack_ctx, panic_cause }),
368372 .silent_abort => goTo(abort, .{}),
369373 };
370374 }
......@@ -373,7 +377,7 @@ const PanicSwitch = struct {
373377 state: *volatile PanicState,
374378 trace: ?*const std.builtin.StackTrace,
375379 stack: StackContext,
376 msg: []const u8,
380 panic_cause: std.builtin.PanicCause,
377381 ) noreturn {
378382 // use a temporary so there's only one volatile store
379383 const new_state = PanicState{
......@@ -398,6 +402,8 @@ const PanicSwitch = struct {
398402 const current_thread_id = std.Thread.getCurrentId();
399403 stderr.print("thread {} panic: ", .{current_thread_id}) catch goTo(releaseMutex, .{state});
400404 }
405 var buffer: [1000]u8 = undefined;
406 const msg = buffer[0..std.debug.fmtPanicCause(&buffer, panic_cause)];
401407 stderr.print("{s}\n", .{msg}) catch goTo(releaseMutex, .{state});
402408
403409 state.recover_stage = .report_stack;
......@@ -413,9 +419,9 @@ const PanicSwitch = struct {
413419 state: *volatile PanicState,
414420 trace: ?*const std.builtin.StackTrace,
415421 stack: StackContext,
416 msg: []const u8,
422 panic_cause: std.builtin.PanicCause,
417423 ) noreturn {
418 recover(state, trace, stack, msg);
424 recover(state, trace, stack, panic_cause);
419425
420426 state.recover_stage = .release_mutex;
421427 const stderr = io.getStdErr().writer();
......@@ -438,9 +444,9 @@ const PanicSwitch = struct {
438444 state: *volatile PanicState,
439445 trace: ?*const std.builtin.StackTrace,
440446 stack: StackContext,
441 msg: []const u8,
447 panic_cause: std.builtin.PanicCause,
442448 ) noreturn {
443 recover(state, trace, stack, msg);
449 recover(state, trace, stack, panic_cause);
444450 goTo(releaseMutex, .{state});
445451 }
446452
......@@ -456,9 +462,9 @@ const PanicSwitch = struct {
456462 state: *volatile PanicState,
457463 trace: ?*const std.builtin.StackTrace,
458464 stack: StackContext,
459 msg: []const u8,
465 panic_cause: std.builtin.PanicCause,
460466 ) noreturn {
461 recover(state, trace, stack, msg);
467 recover(state, trace, stack, panic_cause);
462468 goTo(releaseRefCount, .{state});
463469 }
464470
......@@ -484,9 +490,9 @@ const PanicSwitch = struct {
484490 state: *volatile PanicState,
485491 trace: ?*const std.builtin.StackTrace,
486492 stack: StackContext,
487 msg: []const u8,
493 panic_cause: std.builtin.PanicCause,
488494 ) noreturn {
489 recover(state, trace, stack, msg);
495 recover(state, trace, stack, panic_cause);
490496
491497 state.recover_stage = .silent_abort;
492498 const stderr = io.getStdErr().writer();
......@@ -510,7 +516,7 @@ const PanicSwitch = struct {
510516 state: *volatile PanicState,
511517 trace: ?*const std.builtin.StackTrace,
512518 stack: StackContext,
513 msg: []const u8,
519 panic_cause: std.builtin.PanicCause,
514520 ) void {
515521 switch (state.recover_verbosity) {
516522 .message_and_stack => {
......@@ -519,7 +525,7 @@ const PanicSwitch = struct {
519525
520526 const stderr = io.getStdErr().writer();
521527 stderr.writeAll("\nPanicked during a panic: ") catch {};
522 stderr.writeAll(msg) catch {};
528 stderr.writeAll(panic_cause) catch {};
523529 stderr.writeAll("\nInner panic stack:\n") catch {};
524530 if (trace) |t| {
525531 debug.dumpStackTrace(t.*);
......@@ -533,7 +539,7 @@ const PanicSwitch = struct {
533539
534540 const stderr = io.getStdErr().writer();
535541 stderr.writeAll("\nPanicked while dumping inner panic stack: ") catch {};
536 stderr.writeAll(msg) catch {};
542 stderr.writeAll(panic_cause) catch {};
537543 stderr.writeAll("\n") catch {};
538544
539545 // If we succeed, restore all the way to dumping the stack.
src/main.zig+4-4
......@@ -826,7 +826,6 @@ fn buildOutputType(
826826 var version: std.SemanticVersion = .{ .major = 0, .minor = 0, .patch = 0 };
827827 var have_version = false;
828828 var compatibility_version: ?std.SemanticVersion = null;
829 var formatted_panics: ?bool = null;
830829 var function_sections = false;
831830 var data_sections = false;
832831 var no_builtin = false;
......@@ -1537,9 +1536,11 @@ fn buildOutputType(
15371536 } else if (mem.eql(u8, arg, "-gdwarf64")) {
15381537 create_module.opts.debug_format = .{ .dwarf = .@"64" };
15391538 } else if (mem.eql(u8, arg, "-fformatted-panics")) {
1540 formatted_panics = true;
1539 // Remove this after 0.15.0 is tagged.
1540 warn("-fformatted-panics is deprecated and does nothing", .{});
15411541 } else if (mem.eql(u8, arg, "-fno-formatted-panics")) {
1542 formatted_panics = false;
1542 // Remove this after 0.15.0 is tagged.
1543 warn("-fno-formatted-panics is deprecated and does nothing", .{});
15431544 } else if (mem.eql(u8, arg, "-fsingle-threaded")) {
15441545 mod_opts.single_threaded = true;
15451546 } else if (mem.eql(u8, arg, "-fno-single-threaded")) {
......@@ -3405,7 +3406,6 @@ fn buildOutputType(
34053406 .force_undefined_symbols = force_undefined_symbols,
34063407 .stack_size = stack_size,
34073408 .image_base = image_base,
3408 .formatted_panics = formatted_panics,
34093409 .function_sections = function_sections,
34103410 .data_sections = data_sections,
34113411 .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/safety/unreachable.zig+2-1
......@@ -1,7 +1,8 @@
11const std = @import("std");
22
3pub fn panic(message: []const u8, stack_trace: ?*std.builtin.StackTrace, _: ?usize) noreturn {
3pub fn panic(message: []const u8, stack_trace: ?*std.builtin.StackTrace, ret_addr: ?usize) noreturn {
44 _ = stack_trace;
5 _ = ret_addr;
56 if (std.mem.eql(u8, message, "reached unreachable code")) {
67 std.process.exit(0);
78 }