authorgravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2024-12-20 16:37:25-05:00
committergravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2024-12-20 22:51:20-05:00
log5c76e08f494b7412c1b089cac90bda14e2a45c0b
tree41d48c5a7db067bed24093179107e9cdad60ead5
parent06206479a91be3cac9d5169b61c8691744fd5135

lldb: add pretty printer for intern pool indices


13 files changed, 616 insertions(+), 220 deletions(-)

src/Compilation.zig+16-8
......@@ -2181,7 +2181,8 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
21812181 }
21822182
21832183 if (comp.zcu) |zcu| {
2184 const pt: Zcu.PerThread = .{ .zcu = zcu, .tid = .main };
2184 const pt: Zcu.PerThread = .activate(zcu, .main);
2185 defer pt.deactivate();
21852186
21862187 zcu.compile_log_text.shrinkAndFree(gpa, 0);
21872188
......@@ -2251,7 +2252,8 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
22512252 try comp.performAllTheWork(main_progress_node);
22522253
22532254 if (comp.zcu) |zcu| {
2254 const pt: Zcu.PerThread = .{ .zcu = zcu, .tid = .main };
2255 const pt: Zcu.PerThread = .activate(zcu, .main);
2256 defer pt.deactivate();
22552257
22562258 if (build_options.enable_debug_extensions and comp.verbose_intern_pool) {
22572259 std.debug.print("intern pool stats for '{s}':\n", .{
......@@ -3609,7 +3611,8 @@ fn performAllTheWorkInner(
36093611 }
36103612
36113613 if (comp.zcu) |zcu| {
3612 const pt: Zcu.PerThread = .{ .zcu = zcu, .tid = .main };
3614 const pt: Zcu.PerThread = .activate(zcu, .main);
3615 defer pt.deactivate();
36133616 if (comp.incremental) {
36143617 const update_zir_refs_node = main_progress_node.start("Update ZIR References", 0);
36153618 defer update_zir_refs_node.end();
......@@ -3683,14 +3686,16 @@ fn processOneJob(tid: usize, comp: *Compilation, job: Job, prog_node: std.Progre
36833686 const named_frame = tracy.namedFrame("analyze_func");
36843687 defer named_frame.end();
36853688
3686 const pt: Zcu.PerThread = .{ .zcu = comp.zcu.?, .tid = @enumFromInt(tid) };
3689 const pt: Zcu.PerThread = .activate(comp.zcu.?, @enumFromInt(tid));
3690 defer pt.deactivate();
36873691 pt.ensureFuncBodyAnalyzed(func) catch |err| switch (err) {
36883692 error.OutOfMemory => return error.OutOfMemory,
36893693 error.AnalysisFail => return,
36903694 };
36913695 },
36923696 .analyze_cau => |cau_index| {
3693 const pt: Zcu.PerThread = .{ .zcu = comp.zcu.?, .tid = @enumFromInt(tid) };
3697 const pt: Zcu.PerThread = .activate(comp.zcu.?, @enumFromInt(tid));
3698 defer pt.deactivate();
36943699 pt.ensureCauAnalyzed(cau_index) catch |err| switch (err) {
36953700 error.OutOfMemory => return error.OutOfMemory,
36963701 error.AnalysisFail => return,
......@@ -3719,7 +3724,8 @@ fn processOneJob(tid: usize, comp: *Compilation, job: Job, prog_node: std.Progre
37193724 const named_frame = tracy.namedFrame("resolve_type_fully");
37203725 defer named_frame.end();
37213726
3722 const pt: Zcu.PerThread = .{ .zcu = comp.zcu.?, .tid = @enumFromInt(tid) };
3727 const pt: Zcu.PerThread = .activate(comp.zcu.?, @enumFromInt(tid));
3728 defer pt.deactivate();
37233729 Type.fromInterned(ty).resolveFully(pt) catch |err| switch (err) {
37243730 error.OutOfMemory => return error.OutOfMemory,
37253731 error.AnalysisFail => return,
......@@ -3729,7 +3735,8 @@ fn processOneJob(tid: usize, comp: *Compilation, job: Job, prog_node: std.Progre
37293735 const named_frame = tracy.namedFrame("analyze_mod");
37303736 defer named_frame.end();
37313737
3732 const pt: Zcu.PerThread = .{ .zcu = comp.zcu.?, .tid = @enumFromInt(tid) };
3738 const pt: Zcu.PerThread = .activate(comp.zcu.?, @enumFromInt(tid));
3739 defer pt.deactivate();
37333740 pt.semaPkg(mod) catch |err| switch (err) {
37343741 error.OutOfMemory => return error.OutOfMemory,
37353742 error.AnalysisFail => return,
......@@ -4183,7 +4190,8 @@ fn workerAstGenFile(
41834190 const child_prog_node = prog_node.start(file.sub_file_path, 0);
41844191 defer child_prog_node.end();
41854192
4186 const pt: Zcu.PerThread = .{ .zcu = comp.zcu.?, .tid = @enumFromInt(tid) };
4193 const pt: Zcu.PerThread = .activate(comp.zcu.?, @enumFromInt(tid));
4194 defer pt.deactivate();
41874195 pt.astGenFile(file, path_digest) catch |err| switch (err) {
41884196 error.AnalysisFail => return,
41894197 else => {
src/InternPool.zig+313-119
......@@ -1580,6 +1580,8 @@ pub const String = enum(u32) {
15801580 const strings = ip.getLocalShared(unwrapped_string.tid).strings.acquire();
15811581 return strings.view().items(.@"0")[unwrapped_string.index..];
15821582 }
1583
1584 const debug_state = InternPool.debug_state;
15831585};
15841586
15851587/// An index into `strings` which might be `none`.
......@@ -1596,6 +1598,8 @@ pub const OptionalString = enum(u32) {
15961598 pub fn toSlice(string: OptionalString, len: u64, ip: *const InternPool) ?[]const u8 {
15971599 return (string.unwrap() orelse return null).toSlice(len, ip);
15981600 }
1601
1602 const debug_state = InternPool.debug_state;
15991603};
16001604
16011605/// An index into `strings`.
......@@ -1692,6 +1696,8 @@ pub const NullTerminatedString = enum(u32) {
16921696 pub fn fmt(string: NullTerminatedString, ip: *const InternPool) std.fmt.Formatter(format) {
16931697 return .{ .data = .{ .string = string, .ip = ip } };
16941698 }
1699
1700 const debug_state = InternPool.debug_state;
16951701};
16961702
16971703/// An index into `strings` which might be `none`.
......@@ -1708,6 +1714,8 @@ pub const OptionalNullTerminatedString = enum(u32) {
17081714 pub fn toSlice(string: OptionalNullTerminatedString, ip: *const InternPool) ?[:0]const u8 {
17091715 return (string.unwrap() orelse return null).toSlice(ip);
17101716 }
1717
1718 const debug_state = InternPool.debug_state;
17111719};
17121720
17131721/// A single value captured in the closure of a namespace type. This is not a plain
......@@ -4519,6 +4527,8 @@ pub const Index = enum(u32) {
45194527 .data_ptr = &slice.items(.data)[unwrapped.index],
45204528 };
45214529 }
4530
4531 const debug_state = InternPool.debug_state;
45224532 };
45234533 pub fn unwrap(index: Index, ip: *const InternPool) Unwrapped {
45244534 return if (single_threaded) .{
......@@ -4532,7 +4542,6 @@ pub const Index = enum(u32) {
45324542
45334543 /// This function is used in the debugger pretty formatters in tools/ to fetch the
45344544 /// Tag to encoding mapping to facilitate fancy debug printing for this type.
4535 /// TODO merge this with `Tag.Payload`.
45364545 fn dbHelper(self: *Index, tag_to_encoding_map: *struct {
45374546 const DataIsIndex = struct { data: Index };
45384547 const DataIsExtraIndexOfEnumExplicit = struct {
......@@ -4689,44 +4698,38 @@ pub const Index = enum(u32) {
46894698 }
46904699 }
46914700 }
4692
46934701 comptime {
46944702 if (!builtin.strip_debug_info) switch (builtin.zig_backend) {
46954703 .stage2_llvm => _ = &dbHelper,
4696 .stage2_x86_64 => {
4697 for (@typeInfo(Tag).@"enum".fields) |tag| {
4698 if (!@hasField(@TypeOf(Tag.encodings), tag.name)) {
4699 if (false) @compileLog("missing: " ++ @typeName(Tag) ++ ".encodings." ++ tag.name);
4700 continue;
4701 }
4702 const encoding = @field(Tag.encodings, tag.name);
4703 for (@typeInfo(encoding.trailing).@"struct".fields) |field| {
4704 struct {
4705 fn checkConfig(name: []const u8) void {
4706 if (!@hasField(@TypeOf(encoding.config), name)) @compileError("missing field: " ++ @typeName(Tag) ++ ".encodings." ++ tag.name ++ ".config.@\"" ++ name ++ "\"");
4707 const FieldType = @TypeOf(@field(encoding.config, name));
4708 if (@typeInfo(FieldType) != .enum_literal) @compileError("expected enum literal: " ++ @typeName(Tag) ++ ".encodings." ++ tag.name ++ ".config.@\"" ++ name ++ "\": " ++ @typeName(FieldType));
4709 }
4710 fn checkField(name: []const u8, Type: type) void {
4711 switch (@typeInfo(Type)) {
4712 .int => {},
4713 .@"enum" => {},
4714 .@"struct" => |info| assert(info.layout == .@"packed"),
4715 .optional => |info| {
4716 checkConfig(name ++ ".?");
4717 checkField(name ++ ".?", info.child);
4718 },
4719 .pointer => |info| {
4720 assert(info.size == .Slice);
4721 checkConfig(name ++ ".len");
4722 checkField(name ++ "[0]", info.child);
4723 },
4724 else => @compileError("unsupported type: " ++ @typeName(Tag) ++ ".encodings." ++ tag.name ++ "." ++ name ++ ": " ++ @typeName(Type)),
4725 }
4704 .stage2_x86_64 => for (@typeInfo(Tag).@"enum".fields) |tag| {
4705 if (!@hasField(@TypeOf(Tag.encodings), tag.name)) @compileLog("missing: " ++ @typeName(Tag) ++ ".encodings." ++ tag.name);
4706 const encoding = @field(Tag.encodings, tag.name);
4707 if (@hasField(@TypeOf(encoding), "trailing")) for (@typeInfo(encoding.trailing).@"struct".fields) |field| {
4708 struct {
4709 fn checkConfig(name: []const u8) void {
4710 if (!@hasField(@TypeOf(encoding.config), name)) @compileError("missing field: " ++ @typeName(Tag) ++ ".encodings." ++ tag.name ++ ".config.@\"" ++ name ++ "\"");
4711 const FieldType = @TypeOf(@field(encoding.config, name));
4712 if (@typeInfo(FieldType) != .enum_literal) @compileError("expected enum literal: " ++ @typeName(Tag) ++ ".encodings." ++ tag.name ++ ".config.@\"" ++ name ++ "\": " ++ @typeName(FieldType));
4713 }
4714 fn checkField(name: []const u8, Type: type) void {
4715 switch (@typeInfo(Type)) {
4716 .int => {},
4717 .@"enum" => {},
4718 .@"struct" => |info| assert(info.layout == .@"packed"),
4719 .optional => |info| {
4720 checkConfig(name ++ ".?");
4721 checkField(name ++ ".?", info.child);
4722 },
4723 .pointer => |info| {
4724 assert(info.size == .Slice);
4725 checkConfig(name ++ ".len");
4726 checkField(name ++ "[0]", info.child);
4727 },
4728 else => @compileError("unsupported type: " ++ @typeName(Tag) ++ ".encodings." ++ tag.name ++ "." ++ name ++ ": " ++ @typeName(Type)),
47264729 }
4727 }.checkField("trailing." ++ field.name, field.type);
4728 }
4729 }
4730 }
4731 }.checkField("trailing." ++ field.name, field.type);
4732 };
47304733 },
47314734 else => {},
47324735 };
......@@ -5035,7 +5038,6 @@ pub const Tag = enum(u8) {
50355038 /// data is payload index to `EnumExplicit`.
50365039 type_enum_nonexhaustive,
50375040 /// A type that can be represented with only an enum tag.
5038 /// data is SimpleType enum value.
50395041 simple_type,
50405042 /// An opaque type.
50415043 /// data is index of Tag.TypeOpaque in extra.
......@@ -5064,7 +5066,6 @@ pub const Tag = enum(u8) {
50645066 /// Untyped `undefined` is stored instead via `simple_value`.
50655067 undef,
50665068 /// A value that can be represented with only an enum tag.
5067 /// data is SimpleValue enum value.
50685069 simple_value,
50695070 /// A pointer to a `Nav`.
50705071 /// data is extra index of `PtrNav`, which contains the type and address.
......@@ -5244,95 +5245,85 @@ pub const Tag = enum(u8) {
52445245 const Union = Key.Union;
52455246 const TypePointer = Key.PtrType;
52465247
5247 fn Payload(comptime tag: Tag) type {
5248 return switch (tag) {
5249 .removed => unreachable,
5250 .type_int_signed => unreachable,
5251 .type_int_unsigned => unreachable,
5252 .type_array_big => Array,
5253 .type_array_small => Vector,
5254 .type_vector => Vector,
5255 .type_pointer => TypePointer,
5256 .type_slice => unreachable,
5257 .type_optional => unreachable,
5258 .type_anyframe => unreachable,
5259 .type_error_union => ErrorUnionType,
5260 .type_anyerror_union => unreachable,
5261 .type_error_set => ErrorSet,
5262 .type_inferred_error_set => unreachable,
5263 .type_enum_auto => EnumAuto,
5264 .type_enum_explicit => EnumExplicit,
5265 .type_enum_nonexhaustive => EnumExplicit,
5266 .simple_type => unreachable,
5267 .type_opaque => TypeOpaque,
5268 .type_struct => TypeStruct,
5269 .type_struct_packed, .type_struct_packed_inits => TypeStructPacked,
5270 .type_tuple => TypeTuple,
5271 .type_union => TypeUnion,
5272 .type_function => TypeFunction,
5273
5274 .undef => unreachable,
5275 .simple_value => unreachable,
5276 .ptr_nav => PtrNav,
5277 .ptr_comptime_alloc => PtrComptimeAlloc,
5278 .ptr_uav => PtrUav,
5279 .ptr_uav_aligned => PtrUavAligned,
5280 .ptr_comptime_field => PtrComptimeField,
5281 .ptr_int => PtrInt,
5282 .ptr_eu_payload => PtrBase,
5283 .ptr_opt_payload => PtrBase,
5284 .ptr_elem => PtrBaseIndex,
5285 .ptr_field => PtrBaseIndex,
5286 .ptr_slice => PtrSlice,
5287 .opt_payload => TypeValue,
5288 .opt_null => unreachable,
5289 .int_u8 => unreachable,
5290 .int_u16 => unreachable,
5291 .int_u32 => unreachable,
5292 .int_i32 => unreachable,
5293 .int_usize => unreachable,
5294 .int_comptime_int_u32 => unreachable,
5295 .int_comptime_int_i32 => unreachable,
5296 .int_small => IntSmall,
5297 .int_positive => unreachable,
5298 .int_negative => unreachable,
5299 .int_lazy_align => IntLazy,
5300 .int_lazy_size => IntLazy,
5301 .error_set_error => Error,
5302 .error_union_error => Error,
5303 .error_union_payload => TypeValue,
5304 .enum_literal => unreachable,
5305 .enum_tag => EnumTag,
5306 .float_f16 => unreachable,
5307 .float_f32 => unreachable,
5308 .float_f64 => unreachable,
5309 .float_f80 => unreachable,
5310 .float_f128 => unreachable,
5311 .float_c_longdouble_f80 => unreachable,
5312 .float_c_longdouble_f128 => unreachable,
5313 .float_comptime_float => unreachable,
5314 .variable => Variable,
5315 .@"extern" => Extern,
5316 .func_decl => FuncDecl,
5317 .func_instance => FuncInstance,
5318 .func_coerced => FuncCoerced,
5319 .only_possible_value => unreachable,
5320 .union_value => Union,
5321 .bytes => Bytes,
5322 .aggregate => Aggregate,
5323 .repeated => Repeated,
5324 .memoized_call => MemoizedCall,
5325 };
5326 }
5327
5248 const enum_explicit_encoding = .{
5249 .summary = .@"{.payload.name%summary#\"}",
5250 .payload = EnumExplicit,
5251 .trailing = struct {
5252 owner_union: Index,
5253 cau: ?Cau.Index,
5254 captures: ?[]CaptureValue,
5255 type_hash: ?u64,
5256 field_names: []NullTerminatedString,
5257 tag_values: []Index,
5258 },
5259 .config = .{
5260 .@"trailing.owner_union.?" = .@"payload.zir_index == .none",
5261 .@"trailing.cau.?" = .@"payload.zir_index != .none",
5262 .@"trailing.captures.?" = .@"payload.captures_len < 0xffffffff",
5263 .@"trailing.captures.?.len" = .@"payload.captures_len",
5264 .@"trailing.type_hash.?" = .@"payload.captures_len == 0xffffffff",
5265 .@"trailing.field_names.len" = .@"payload.fields_len",
5266 .@"trailing.tag_values.len" = .@"payload.fields_len",
5267 },
5268 };
53285269 const encodings = .{
5270 .removed = .{},
5271
5272 .type_int_signed = .{ .summary = .@"i{.data%value}", .data = u32 },
5273 .type_int_unsigned = .{ .summary = .@"u{.data%value}", .data = u32 },
5274 .type_array_big = .{ .summary = .@"[{.payload.len1%value} << 32 | {.payload.len0%value}:{.payload.sentinel%summary}]{.payload.child%summary}", .payload = Array },
5275 .type_array_small = .{ .summary = .@"[{.payload.len%value}]{.payload.child%summary}", .payload = Vector },
5276 .type_vector = .{ .summary = .@"@Vector({.payload.len%value}, {.payload.child%summary})", .payload = Vector },
5277 .type_pointer = .{ .summary = .@"*... {.payload.child%summary}", .payload = TypePointer },
5278 .type_slice = .{ .summary = .@"[]... {.data.unwrapped.payload.child%summary}", .data = Index },
5279 .type_optional = .{ .summary = .@"?{.data%summary}", .data = Index },
5280 .type_anyframe = .{ .summary = .@"anyframe->{.data%summary}", .data = Index },
5281 .type_error_union = .{ .summary = .@"{.payload.error_set_type%summary}!{.payload.payload_type%summary}", .payload = ErrorUnionType },
5282 .type_anyerror_union = .{ .summary = .@"anyerror!{.data%summary}", .data = Index },
5283 .type_error_set = .{ .summary = .@"error{...}", .payload = ErrorSet },
5284 .type_inferred_error_set = .{ .summary = .@"@typeInfo(@typeInfo(@TypeOf({.data%summary})).@\"fn\".return_type.?).error_union.error_set", .data = Index },
5285 .type_enum_auto = .{
5286 .summary = .@"{.payload.name%summary#\"}",
5287 .payload = EnumAuto,
5288 .trailing = struct {
5289 owner_union: ?Index,
5290 cau: ?Cau.Index,
5291 captures: ?[]CaptureValue,
5292 type_hash: ?u64,
5293 field_names: []NullTerminatedString,
5294 },
5295 .config = .{
5296 .@"trailing.owner_union.?" = .@"payload.zir_index == .none",
5297 .@"trailing.cau.?" = .@"payload.zir_index != .none",
5298 .@"trailing.captures.?" = .@"payload.captures_len < 0xffffffff",
5299 .@"trailing.captures.?.len" = .@"payload.captures_len",
5300 .@"trailing.type_hash.?" = .@"payload.captures_len == 0xffffffff",
5301 .@"trailing.field_names.len" = .@"payload.fields_len",
5302 },
5303 },
5304 .type_enum_explicit = enum_explicit_encoding,
5305 .type_enum_nonexhaustive = enum_explicit_encoding,
5306 .simple_type = .{ .summary = .@"{.index%value#.}", .index = SimpleType },
5307 .type_opaque = .{
5308 .summary = .@"{.payload.name%summary#\"}",
5309 .payload = TypeOpaque,
5310 .trailing = struct {
5311 captures: []CaptureValue,
5312 },
5313 .config = .{
5314 .@"trailing.captures.len" = .@"payload.captures_len",
5315 },
5316 },
53295317 .type_struct = .{
5318 .summary = .@"{.payload.name%summary#\"}",
53305319 .payload = TypeStruct,
53315320 .trailing = struct {
53325321 captures_len: ?u32,
53335322 captures: ?[]CaptureValue,
53345323 type_hash: ?u64,
53355324 field_types: []Index,
5325 field_names_map: OptionalMapIndex,
5326 field_names: []NullTerminatedString,
53365327 field_inits: ?[]Index,
53375328 field_aligns: ?[]Alignment,
53385329 field_is_comptime_bits: ?[]u32,
......@@ -5342,9 +5333,10 @@ pub const Tag = enum(u8) {
53425333 .config = .{
53435334 .@"trailing.captures_len.?" = .@"payload.flags.any_captures",
53445335 .@"trailing.captures.?" = .@"payload.flags.any_captures",
5345 .@"trailing.captures.?.len" = .@"trailing.captures_len",
5336 .@"trailing.captures.?.len" = .@"trailing.captures_len.?",
53465337 .@"trailing.type_hash.?" = .@"payload.flags.is_reified",
53475338 .@"trailing.field_types.len" = .@"payload.fields_len",
5339 .@"trailing.field_names.len" = .@"payload.fields_len",
53485340 .@"trailing.field_inits.?" = .@"payload.flags.any_default_inits",
53495341 .@"trailing.field_inits.?.len" = .@"payload.fields_len",
53505342 .@"trailing.field_aligns.?" = .@"payload.flags.any_aligned_fields",
......@@ -5356,7 +5348,185 @@ pub const Tag = enum(u8) {
53565348 .@"trailing.field_offset.len" = .@"payload.fields_len",
53575349 },
53585350 },
5351 .type_struct_packed = .{
5352 .summary = .@"{.payload.name%summary#\"}",
5353 .payload = TypeStructPacked,
5354 .trailing = struct {
5355 captures_len: ?u32,
5356 captures: ?[]CaptureValue,
5357 type_hash: ?u64,
5358 field_types: []Index,
5359 field_names: []NullTerminatedString,
5360 },
5361 .config = .{
5362 .@"trailing.captures_len.?" = .@"payload.flags.any_captures",
5363 .@"trailing.captures.?" = .@"payload.flags.any_captures",
5364 .@"trailing.captures.?.len" = .@"trailing.captures_len.?",
5365 .@"trailing.type_hash.?" = .@"payload.is_flags.is_reified",
5366 .@"trailing.field_types.len" = .@"payload.fields_len",
5367 .@"trailing.field_names.len" = .@"payload.fields_len",
5368 },
5369 },
5370 .type_struct_packed_inits = .{
5371 .summary = .@"{.payload.name%summary#\"}",
5372 .payload = TypeStructPacked,
5373 .trailing = struct {
5374 captures_len: ?u32,
5375 captures: ?[]CaptureValue,
5376 type_hash: ?u64,
5377 field_types: []Index,
5378 field_names: []NullTerminatedString,
5379 field_inits: []Index,
5380 },
5381 .config = .{
5382 .@"trailing.captures_len.?" = .@"payload.flags.any_captures",
5383 .@"trailing.captures.?" = .@"payload.flags.any_captures",
5384 .@"trailing.captures.?.len" = .@"trailing.captures_len.?",
5385 .@"trailing.type_hash.?" = .@"payload.is_flags.is_reified",
5386 .@"trailing.field_types.len" = .@"payload.fields_len",
5387 .@"trailing.field_names.len" = .@"payload.fields_len",
5388 .@"trailing.field_inits.len" = .@"payload.fields_len",
5389 },
5390 },
5391 .type_tuple = .{
5392 .summary = .@"struct {...}",
5393 .payload = TypeTuple,
5394 .trailing = struct {
5395 field_types: []Index,
5396 field_values: []Index,
5397 },
5398 .config = .{
5399 .@"trailing.field_types.len" = .@"payload.fields_len",
5400 .@"trailing.field_values.len" = .@"payload.fields_len",
5401 },
5402 },
5403 .type_union = .{
5404 .summary = .@"{.payload.name%summary#\"#\"}",
5405 .payload = TypeUnion,
5406 .trailing = struct {
5407 captures_len: ?u32,
5408 captures: ?[]CaptureValue,
5409 type_hash: ?u64,
5410 field_types: []Index,
5411 field_aligns: []Alignment,
5412 },
5413 .config = .{
5414 .@"trailing.captures_len.?" = .@"payload.flags.any_captures",
5415 .@"trailing.captures.?" = .@"payload.flags.any_captures",
5416 .@"trailing.captures.?.len" = .@"trailing.captures_len.?",
5417 .@"trailing.type_hash.?" = .@"payload.is_flags.is_reified",
5418 .@"trailing.field_types.len" = .@"payload.fields_len",
5419 .@"trailing.field_aligns.len" = .@"payload.fields_len",
5420 },
5421 },
5422 .type_function = .{
5423 .summary = .@"fn (...) ... {.payload.return_type%summary}",
5424 .payload = TypeFunction,
5425 .trailing = struct {
5426 param_comptime_bits: ?[]u32,
5427 param_noalias_bits: ?[]u32,
5428 param_type: []Index,
5429 },
5430 .config = .{
5431 .@"trailing.param_comptime_bits.?" = .@"payload.flags.has_comptime_bits",
5432 .@"trailing.param_comptime_bits.?.len" = .@"(payload.params_len + 31) / 32",
5433 .@"trailing.param_noalias_bits.?" = .@"payload.flags.has_noalias_bits",
5434 .@"trailing.param_noalias_bits.?.len" = .@"(payload.params_len + 31) / 32",
5435 .@"trailing.param_type.len" = .@"payload.params_len",
5436 },
5437 },
5438
5439 .undef = .{ .summary = .@"@as({.data%summary}, undefined)", .data = Index },
5440 .simple_value = .{ .summary = .@"{.index%value#.}", .index = SimpleValue },
5441 .ptr_nav = .{ .payload = PtrNav },
5442 .ptr_comptime_alloc = .{ .payload = PtrComptimeAlloc },
5443 .ptr_uav = .{ .payload = PtrUav },
5444 .ptr_uav_aligned = .{ .payload = PtrUavAligned },
5445 .ptr_comptime_field = .{ .payload = PtrComptimeField },
5446 .ptr_int = .{ .payload = PtrInt },
5447 .ptr_eu_payload = .{ .payload = PtrBase },
5448 .ptr_opt_payload = .{ .payload = PtrBase },
5449 .ptr_elem = .{ .payload = PtrBaseIndex },
5450 .ptr_field = .{ .payload = PtrBaseIndex },
5451 .ptr_slice = .{ .payload = PtrSlice },
5452 .opt_payload = .{ .summary = .@"@as({.payload.ty%summary}, {.payload.val%summary})", .payload = TypeValue },
5453 .opt_null = .{ .summary = .@"@as({.data%summary}, null)", .data = Index },
5454 .int_u8 = .{ .summary = .@"@as(u8, {.data%value})", .data = u8 },
5455 .int_u16 = .{ .summary = .@"@as(u16, {.data%value})", .data = u16 },
5456 .int_u32 = .{ .summary = .@"@as(u32, {.data%value})", .data = u32 },
5457 .int_i32 = .{ .summary = .@"@as(i32, {.data%value})", .data = i32 },
5458 .int_usize = .{ .summary = .@"@as(usize, {.data%value})", .data = u32 },
5459 .int_comptime_int_u32 = .{ .summary = .@"{.data%value}", .data = u32 },
5460 .int_comptime_int_i32 = .{ .summary = .@"{.data%value}", .data = i32 },
5461 .int_small = .{ .summary = .@"@as({.payload.ty%summary}, {.payload.value%value})", .payload = IntSmall },
5462 .int_positive = .{},
5463 .int_negative = .{},
5464 .int_lazy_align = .{ .summary = .@"@as({.payload.ty%summary}, @alignOf({.payload.lazy_ty%summary}))", .payload = IntLazy },
5465 .int_lazy_size = .{ .summary = .@"@as({.payload.ty%summary}, @sizeOf({.payload.lazy_ty%summary}))", .payload = IntLazy },
5466 .error_set_error = .{ .summary = .@"@as({.payload.ty%summary}, error.@{.payload.name%summary})", .payload = Error },
5467 .error_union_error = .{ .summary = .@"@as({.payload.ty%summary}, error.@{.payload.name%summary})", .payload = Error },
5468 .error_union_payload = .{ .summary = .@"@as({.payload.ty%summary}, {.payload.val%summary})", .payload = TypeValue },
5469 .enum_literal = .{ .summary = .@".@{.data%summary}", .data = NullTerminatedString },
5470 .enum_tag = .{ .summary = .@"@as({.payload.ty%summary}, @enumFromInt({.payload.int%summary}))", .payload = EnumTag },
5471 .float_f16 = .{ .summary = .@"@as(f16, {.data%value})", .data = f16 },
5472 .float_f32 = .{ .summary = .@"@as(f32, {.data%value})", .data = f32 },
5473 .float_f64 = .{ .summary = .@"@as(f64, {.payload%value})", .payload = f64 },
5474 .float_f80 = .{ .summary = .@"@as(f80, {.payload%value})", .payload = f80 },
5475 .float_f128 = .{ .summary = .@"@as(f128, {.payload%value})", .payload = f128 },
5476 .float_c_longdouble_f80 = .{ .summary = .@"@as(c_longdouble, {.payload%value})", .payload = f80 },
5477 .float_c_longdouble_f128 = .{ .summary = .@"@as(c_longdouble, {.payload%value})", .payload = f128 },
5478 .float_comptime_float = .{ .summary = .@"{.payload%value}", .payload = f128 },
5479 .variable = .{ .payload = Variable },
5480 .@"extern" = .{ .payload = Extern },
5481 .func_decl = .{
5482 .payload = FuncDecl,
5483 .trailing = struct {
5484 inferred_error_set: ?Index,
5485 },
5486 .config = .{
5487 .@"trailing.inferred_error_set.?" = .@"payload.analysis.inferred_error_set",
5488 },
5489 },
5490 .func_instance = .{
5491 .payload = FuncInstance,
5492 .trailing = struct {
5493 inferred_error_set: ?Index,
5494 param_values: []Index,
5495 },
5496 .config = .{
5497 .@"trailing.inferred_error_set.?" = .@"payload.analysis.inferred_error_set",
5498 .@"trailing.param_values.len" = .@"payload.ty.payload.params_len",
5499 },
5500 },
5501 .func_coerced = .{ .payload = FuncCoerced },
5502 .only_possible_value = .{ .summary = .@"@as({.data%summary}, undefined)", .data = Index },
5503 .union_value = .{ .summary = .@"@as({.payload.ty%summary}, {})", .payload = Union },
5504 .bytes = .{ .summary = .@"@as({.payload.ty%summary}, {.payload.bytes%summary}.*)", .payload = Bytes },
5505 .aggregate = .{
5506 .summary = .@"@as({.payload.ty%summary}, .{...})",
5507 .payload = Aggregate,
5508 .trailing = struct {
5509 elements: []Index,
5510 },
5511 .config = .{
5512 .@"trailing.elements.len" = .@"payload.ty.payload.fields_len",
5513 },
5514 },
5515 .repeated = .{ .summary = .@"@as({.payload.ty%summary}, @splat({.payload.elem_val%summary}))", .payload = Repeated },
5516
5517 .memoized_call = .{
5518 .payload = MemoizedCall,
5519 .trailing = struct {
5520 arg_values: []Index,
5521 },
5522 .config = .{
5523 .@"trailing.arg_values.len" = .@"payload.args_len",
5524 },
5525 },
53595526 };
5527 fn Payload(comptime tag: Tag) type {
5528 return @field(encodings, @tagName(tag)).payload;
5529 }
53605530
53615531 pub const Variable = struct {
53625532 ty: Index,
......@@ -6271,6 +6441,8 @@ pub fn init(ip: *InternPool, gpa: Allocator, available_threads: usize) !void {
62716441}
62726442
62736443pub fn deinit(ip: *InternPool, gpa: Allocator) void {
6444 if (!builtin.strip_debug_info) std.debug.assert(debug_state.intern_pool == null);
6445
62746446 ip.file_deps.deinit(gpa);
62756447 ip.src_hash_deps.deinit(gpa);
62766448 ip.nav_val_deps.deinit(gpa);
......@@ -6311,6 +6483,28 @@ pub fn deinit(ip: *InternPool, gpa: Allocator) void {
63116483 ip.* = undefined;
63126484}
63136485
6486pub fn activate(ip: *const InternPool) void {
6487 if (builtin.strip_debug_info) return;
6488 _ = Index.Unwrapped.debug_state;
6489 _ = String.debug_state;
6490 _ = OptionalString.debug_state;
6491 _ = NullTerminatedString.debug_state;
6492 _ = OptionalNullTerminatedString.debug_state;
6493 std.debug.assert(debug_state.intern_pool == null);
6494 debug_state.intern_pool = ip;
6495}
6496
6497pub fn deactivate(ip: *const InternPool) void {
6498 if (builtin.strip_debug_info) return;
6499 std.debug.assert(debug_state.intern_pool == ip);
6500 debug_state.intern_pool = null;
6501}
6502
6503/// For debugger access only.
6504const debug_state = struct {
6505 threadlocal var intern_pool: ?*const InternPool = null;
6506};
6507
63146508pub fn indexToKey(ip: *const InternPool, index: Index) Key {
63156509 assert(index != .none);
63166510 const unwrapped_index = index.unwrap(ip);
src/Type.zig+1-1
......@@ -891,7 +891,7 @@ pub const ResolveStratLazy = enum {
891891};
892892
893893/// The chosen strategy can be easily optimized away in release builds.
894/// However, in debug builds, it helps to avoid acceidentally resolving types in backends.
894/// However, in debug builds, it helps to avoid accidentally resolving types in backends.
895895pub const ResolveStrat = enum {
896896 /// Assert that all necessary resolution is completed.
897897 /// Backends should typically use this, since they must not perform type resolution.
src/Zcu.zig+67-65
......@@ -2169,90 +2169,92 @@ pub fn init(zcu: *Zcu, thread_count: usize) !void {
21692169}
21702170
21712171pub fn deinit(zcu: *Zcu) void {
2172 const pt: Zcu.PerThread = .{ .tid = .main, .zcu = zcu };
21732172 const gpa = zcu.gpa;
2173 {
2174 const pt: Zcu.PerThread = .activate(zcu, .main);
2175 defer pt.deactivate();
21742176
2175 if (zcu.llvm_object) |llvm_object| llvm_object.deinit();
2176
2177 for (zcu.import_table.keys()) |key| {
2178 gpa.free(key);
2179 }
2180 for (zcu.import_table.values()) |file_index| {
2181 pt.destroyFile(file_index);
2182 }
2183 zcu.import_table.deinit(gpa);
2177 if (zcu.llvm_object) |llvm_object| llvm_object.deinit();
21842178
2185 for (zcu.embed_table.keys(), zcu.embed_table.values()) |path, embed_file| {
2186 gpa.free(path);
2187 gpa.destroy(embed_file);
2188 }
2189 zcu.embed_table.deinit(gpa);
2179 for (zcu.import_table.keys()) |key| {
2180 gpa.free(key);
2181 }
2182 for (zcu.import_table.values()) |file_index| {
2183 pt.destroyFile(file_index);
2184 }
2185 zcu.import_table.deinit(gpa);
21902186
2191 zcu.compile_log_text.deinit(gpa);
2187 for (zcu.embed_table.keys(), zcu.embed_table.values()) |path, embed_file| {
2188 gpa.free(path);
2189 gpa.destroy(embed_file);
2190 }
2191 zcu.embed_table.deinit(gpa);
21922192
2193 zcu.local_zir_cache.handle.close();
2194 zcu.global_zir_cache.handle.close();
2193 zcu.compile_log_text.deinit(gpa);
21952194
2196 for (zcu.failed_analysis.values()) |value| {
2197 value.destroy(gpa);
2198 }
2199 for (zcu.failed_codegen.values()) |value| {
2200 value.destroy(gpa);
2201 }
2202 zcu.analysis_in_progress.deinit(gpa);
2203 zcu.failed_analysis.deinit(gpa);
2204 zcu.transitive_failed_analysis.deinit(gpa);
2205 zcu.failed_codegen.deinit(gpa);
2195 zcu.local_zir_cache.handle.close();
2196 zcu.global_zir_cache.handle.close();
22062197
2207 for (zcu.failed_files.values()) |value| {
2208 if (value) |msg| msg.destroy(gpa);
2209 }
2210 zcu.failed_files.deinit(gpa);
2198 for (zcu.failed_analysis.values()) |value| {
2199 value.destroy(gpa);
2200 }
2201 for (zcu.failed_codegen.values()) |value| {
2202 value.destroy(gpa);
2203 }
2204 zcu.analysis_in_progress.deinit(gpa);
2205 zcu.failed_analysis.deinit(gpa);
2206 zcu.transitive_failed_analysis.deinit(gpa);
2207 zcu.failed_codegen.deinit(gpa);
22112208
2212 for (zcu.failed_embed_files.values()) |msg| {
2213 msg.destroy(gpa);
2214 }
2215 zcu.failed_embed_files.deinit(gpa);
2209 for (zcu.failed_files.values()) |value| {
2210 if (value) |msg| msg.destroy(gpa);
2211 }
2212 zcu.failed_files.deinit(gpa);
22162213
2217 for (zcu.failed_exports.values()) |value| {
2218 value.destroy(gpa);
2219 }
2220 zcu.failed_exports.deinit(gpa);
2214 for (zcu.failed_embed_files.values()) |msg| {
2215 msg.destroy(gpa);
2216 }
2217 zcu.failed_embed_files.deinit(gpa);
22212218
2222 for (zcu.cimport_errors.values()) |*errs| {
2223 errs.deinit(gpa);
2224 }
2225 zcu.cimport_errors.deinit(gpa);
2219 for (zcu.failed_exports.values()) |value| {
2220 value.destroy(gpa);
2221 }
2222 zcu.failed_exports.deinit(gpa);
22262223
2227 zcu.compile_log_sources.deinit(gpa);
2224 for (zcu.cimport_errors.values()) |*errs| {
2225 errs.deinit(gpa);
2226 }
2227 zcu.cimport_errors.deinit(gpa);
22282228
2229 zcu.all_exports.deinit(gpa);
2230 zcu.free_exports.deinit(gpa);
2231 zcu.single_exports.deinit(gpa);
2232 zcu.multi_exports.deinit(gpa);
2229 zcu.compile_log_sources.deinit(gpa);
22332230
2234 zcu.potentially_outdated.deinit(gpa);
2235 zcu.outdated.deinit(gpa);
2236 zcu.outdated_ready.deinit(gpa);
2237 zcu.retryable_failures.deinit(gpa);
2231 zcu.all_exports.deinit(gpa);
2232 zcu.free_exports.deinit(gpa);
2233 zcu.single_exports.deinit(gpa);
2234 zcu.multi_exports.deinit(gpa);
22382235
2239 zcu.test_functions.deinit(gpa);
2236 zcu.potentially_outdated.deinit(gpa);
2237 zcu.outdated.deinit(gpa);
2238 zcu.outdated_ready.deinit(gpa);
2239 zcu.retryable_failures.deinit(gpa);
22402240
2241 for (zcu.global_assembly.values()) |s| {
2242 gpa.free(s);
2243 }
2244 zcu.global_assembly.deinit(gpa);
2241 zcu.test_functions.deinit(gpa);
22452242
2246 zcu.reference_table.deinit(gpa);
2247 zcu.all_references.deinit(gpa);
2248 zcu.free_references.deinit(gpa);
2243 for (zcu.global_assembly.values()) |s| {
2244 gpa.free(s);
2245 }
2246 zcu.global_assembly.deinit(gpa);
22492247
2250 zcu.type_reference_table.deinit(gpa);
2251 zcu.all_type_references.deinit(gpa);
2252 zcu.free_type_references.deinit(gpa);
2248 zcu.reference_table.deinit(gpa);
2249 zcu.all_references.deinit(gpa);
2250 zcu.free_references.deinit(gpa);
22532251
2254 if (zcu.resolved_references) |*r| r.deinit(gpa);
2252 zcu.type_reference_table.deinit(gpa);
2253 zcu.all_type_references.deinit(gpa);
2254 zcu.free_type_references.deinit(gpa);
22552255
2256 if (zcu.resolved_references) |*r| r.deinit(gpa);
2257 }
22562258 zcu.intern_pool.deinit(gpa);
22572259}
22582260
src/Zcu/PerThread.zig+9
......@@ -35,6 +35,15 @@ tid: Id,
3535pub const IdBacking = u7;
3636pub const Id = if (InternPool.single_threaded) enum { main } else enum(IdBacking) { main, _ };
3737
38pub fn activate(zcu: *Zcu, tid: Id) Zcu.PerThread {
39 zcu.intern_pool.activate();
40 return .{ .zcu = zcu, .tid = tid };
41}
42
43pub fn deactivate(pt: Zcu.PerThread) void {
44 pt.zcu.intern_pool.deactivate();
45}
46
3847fn deinitFile(pt: Zcu.PerThread, file_index: Zcu.File.Index) void {
3948 const zcu = pt.zcu;
4049 const gpa = zcu.gpa;
src/link.zig+6-3
......@@ -1537,20 +1537,23 @@ pub fn doTask(comp: *Compilation, tid: usize, task: Task) void {
15371537 };
15381538 },
15391539 .codegen_nav => |nav_index| {
1540 const pt: Zcu.PerThread = .{ .zcu = comp.zcu.?, .tid = @enumFromInt(tid) };
1540 const pt: Zcu.PerThread = .activate(comp.zcu.?, @enumFromInt(tid));
1541 defer pt.deactivate();
15411542 pt.linkerUpdateNav(nav_index) catch |err| switch (err) {
15421543 error.OutOfMemory => diags.setAllocFailure(),
15431544 };
15441545 },
15451546 .codegen_func => |func| {
1546 const pt: Zcu.PerThread = .{ .zcu = comp.zcu.?, .tid = @enumFromInt(tid) };
1547 const pt: Zcu.PerThread = .activate(comp.zcu.?, @enumFromInt(tid));
1548 defer pt.deactivate();
15471549 // This call takes ownership of `func.air`.
15481550 pt.linkerUpdateFunc(func.func, func.air) catch |err| switch (err) {
15491551 error.OutOfMemory => diags.setAllocFailure(),
15501552 };
15511553 },
15521554 .codegen_type => |ty| {
1553 const pt: Zcu.PerThread = .{ .zcu = comp.zcu.?, .tid = @enumFromInt(tid) };
1555 const pt: Zcu.PerThread = .activate(comp.zcu.?, @enumFromInt(tid));
1556 defer pt.deactivate();
15541557 pt.linkerUpdateContainerType(ty) catch |err| switch (err) {
15551558 error.OutOfMemory => diags.setAllocFailure(),
15561559 };
src/link/C.zig+2-1
......@@ -419,7 +419,8 @@ pub fn flushModule(self: *C, arena: Allocator, tid: Zcu.PerThread.Id, prog_node:
419419 const gpa = comp.gpa;
420420 const zcu = self.base.comp.zcu.?;
421421 const ip = &zcu.intern_pool;
422 const pt: Zcu.PerThread = .{ .zcu = zcu, .tid = tid };
422 const pt: Zcu.PerThread = .activate(zcu, tid);
423 defer pt.deactivate();
423424
424425 {
425426 var i: usize = 0;
src/link/Coff.zig+5-4
......@@ -2218,10 +2218,11 @@ pub fn flushModule(coff: *Coff, arena: Allocator, tid: Zcu.PerThread.Id, prog_no
22182218 const sub_prog_node = prog_node.start("COFF Flush", 0);
22192219 defer sub_prog_node.end();
22202220
2221 const pt: Zcu.PerThread = .{
2222 .zcu = comp.zcu orelse return error.LinkingWithoutZigSourceUnimplemented,
2223 .tid = tid,
2224 };
2221 const pt: Zcu.PerThread = .activate(
2222 comp.zcu orelse return error.LinkingWithoutZigSourceUnimplemented,
2223 tid,
2224 );
2225 defer pt.deactivate();
22252226
22262227 if (coff.lazy_syms.getPtr(.anyerror_type)) |metadata| {
22272228 // Most lazy symbols can be updated on first use, but
src/link/Elf/ZigObject.zig+6-3
......@@ -267,7 +267,8 @@ pub fn deinit(self: *ZigObject, allocator: Allocator) void {
267267pub fn flush(self: *ZigObject, elf_file: *Elf, tid: Zcu.PerThread.Id) !void {
268268 // Handle any lazy symbols that were emitted by incremental compilation.
269269 if (self.lazy_syms.getPtr(.anyerror_type)) |metadata| {
270 const pt: Zcu.PerThread = .{ .zcu = elf_file.base.comp.zcu.?, .tid = tid };
270 const pt: Zcu.PerThread = .activate(elf_file.base.comp.zcu.?, tid);
271 defer pt.deactivate();
271272
272273 // Most lazy symbols can be updated on first use, but
273274 // anyerror needs to wait for everything to be flushed.
......@@ -296,7 +297,8 @@ pub fn flush(self: *ZigObject, elf_file: *Elf, tid: Zcu.PerThread.Id) !void {
296297 }
297298
298299 if (build_options.enable_logging) {
299 const pt: Zcu.PerThread = .{ .zcu = elf_file.base.comp.zcu.?, .tid = tid };
300 const pt: Zcu.PerThread = .activate(elf_file.base.comp.zcu.?, tid);
301 defer pt.deactivate();
300302 for (self.navs.keys(), self.navs.values()) |nav_index, meta| {
301303 checkNavAllocated(pt, nav_index, meta);
302304 }
......@@ -306,7 +308,8 @@ pub fn flush(self: *ZigObject, elf_file: *Elf, tid: Zcu.PerThread.Id) !void {
306308 }
307309
308310 if (self.dwarf) |*dwarf| {
309 const pt: Zcu.PerThread = .{ .zcu = elf_file.base.comp.zcu.?, .tid = tid };
311 const pt: Zcu.PerThread = .activate(elf_file.base.comp.zcu.?, tid);
312 defer pt.deactivate();
310313 try dwarf.flushModule(pt);
311314
312315 const gpa = elf_file.base.comp.gpa;
src/link/MachO/ZigObject.zig+4-2
......@@ -549,7 +549,8 @@ pub fn getInputSection(self: ZigObject, atom: Atom, macho_file: *MachO) macho.se
549549pub fn flushModule(self: *ZigObject, macho_file: *MachO, tid: Zcu.PerThread.Id) !void {
550550 // Handle any lazy symbols that were emitted by incremental compilation.
551551 if (self.lazy_syms.getPtr(.anyerror_type)) |metadata| {
552 const pt: Zcu.PerThread = .{ .zcu = macho_file.base.comp.zcu.?, .tid = tid };
552 const pt: Zcu.PerThread = .activate(macho_file.base.comp.zcu.?, tid);
553 defer pt.deactivate();
553554
554555 // Most lazy symbols can be updated on first use, but
555556 // anyerror needs to wait for everything to be flushed.
......@@ -578,7 +579,8 @@ pub fn flushModule(self: *ZigObject, macho_file: *MachO, tid: Zcu.PerThread.Id)
578579 }
579580
580581 if (self.dwarf) |*dwarf| {
581 const pt: Zcu.PerThread = .{ .zcu = macho_file.base.comp.zcu.?, .tid = tid };
582 const pt: Zcu.PerThread = .activate(macho_file.base.comp.zcu.?, tid);
583 defer pt.deactivate();
582584 try dwarf.flushModule(pt);
583585
584586 self.debug_abbrev_dirty = false;
src/link/Plan9.zig+5-4
......@@ -604,10 +604,11 @@ pub fn flushModule(self: *Plan9, arena: Allocator, tid: Zcu.PerThread.Id, prog_n
604604
605605 defer assert(self.hdr.entry != 0x0);
606606
607 const pt: Zcu.PerThread = .{
608 .zcu = self.base.comp.zcu orelse return error.LinkingWithoutZigSourceUnimplemented,
609 .tid = tid,
610 };
607 const pt: Zcu.PerThread = .activate(
608 self.base.comp.zcu orelse return error.LinkingWithoutZigSourceUnimplemented,
609 tid,
610 );
611 defer pt.deactivate();
611612
612613 // finish up the lazy syms
613614 if (self.lazy_syms.getPtr(.none)) |metadata| {
src/link/Wasm/ZigObject.zig+2-1
......@@ -589,7 +589,8 @@ fn populateErrorNameTable(zig_object: *ZigObject, wasm: *Wasm, tid: Zcu.PerThrea
589589
590590 // Addend for each relocation to the table
591591 var addend: u32 = 0;
592 const pt: Zcu.PerThread = .{ .zcu = wasm.base.comp.zcu.?, .tid = tid };
592 const pt: Zcu.PerThread = .activate(wasm.base.comp.zcu.?, tid);
593 defer pt.deactivate();
593594 const slice_ty = Type.slice_const_u8_sentinel_0;
594595 const atom = wasm.getAtomPtr(atom_index);
595596 {
tools/lldb_pretty_printers.py+180-9
......@@ -13,21 +13,35 @@ page_size = 1 << 12
1313
1414def log2_int(i): return i.bit_length() - 1
1515
16def create_struct(name, struct_type, **inits):
17 struct_bytes = bytearray(struct_type.size)
18 struct_data = lldb.SBData()
16def create_struct(parent, name, struct_type, inits):
17 struct_bytes, struct_data = bytearray(struct_type.size), lldb.SBData()
1918 for field in struct_type.fields:
2019 field_size = field.type.size
21 field_bytes = inits[field.name].data.uint8[:field_size]
20 field_init = inits[field.name]
21 field_init_type = type(field_init)
22 if field_init_type == bool:
23 field_bytes = bytes([field_init])
24 elif field_init_type == int:
25 match struct_data.byte_order:
26 case lldb.eByteOrderLittle:
27 byte_order = 'little'
28 case lldb.eByteOrderBig:
29 byte_order = 'big'
30 field_bytes = field_init.to_bytes(field_size, byte_order, signed=field.type.GetTypeFlags() & lldb.eTypeIsSigned != 0)
31 elif field_init_type == lldb.SBValue:
32 field_bytes = field_init.data.uint8
33 else: return
2234 match struct_data.byte_order:
2335 case lldb.eByteOrderLittle:
36 field_bytes = field_bytes[:field_size]
2437 field_start = field.byte_offset
2538 struct_bytes[field_start:field_start + len(field_bytes)] = field_bytes
2639 case lldb.eByteOrderBig:
40 field_bytes = field_bytes[-field_size:]
2741 field_end = field.byte_offset + field_size
2842 struct_bytes[field_end - len(field_bytes):field_end] = field_bytes
2943 struct_data.SetData(lldb.SBError(), struct_bytes, struct_data.byte_order, struct_data.GetAddressByteSize())
30 return next(iter(inits.values())).CreateValueFromData(name, struct_data, struct_type)
44 return parent.CreateValueFromData(name, struct_data, struct_type)
3145
3246# Define Zig Language
3347
......@@ -292,6 +306,8 @@ class std_MultiArrayList_Slice_SynthProvider:
292306 return self.ptrs.CreateValueFromData('[%d]' % index, data, self.entry_type)
293307 except: return None
294308
309def MultiArrayList_Entry(type): return '^multi_array_list\\.MultiArrayList\\(%s\\)\\.Entry__struct_[1-9][0-9]*$' % type
310
295311class std_HashMapUnmanaged_SynthProvider:
296312 def __init__(self, value, _=None): self.value = value
297313 def update(self):
......@@ -702,7 +718,7 @@ class root_InternPool_Local_List_SynthProvider:
702718 def __init__(self, value, _=None): self.value = value
703719 def update(self):
704720 capacity = self.value.EvaluateExpression('@as(*@This().Header, @alignCast(@ptrCast(@this().bytes - @This().bytes_offset))).capacity')
705 self.view = create_struct('view', self.value.type.FindDirectNestedType('View'), bytes=self.value.GetChildMemberWithName('bytes'), len=capacity, capacity=capacity).GetNonSyntheticValue()
721 self.view = create_struct(self.value, '.view', self.value.type.FindDirectNestedType('View'), { 'bytes': self.value.GetChildMemberWithName('bytes'), 'len': capacity, 'capacity': capacity }).GetNonSyntheticValue()
706722 def has_children(self): return True
707723 def num_children(self): return 1
708724 def get_child_index(self, name):
......@@ -712,6 +728,160 @@ class root_InternPool_Local_List_SynthProvider:
712728 try: return (self.view,)[index]
713729 except: pass
714730
731expr_path_re = re.compile(r'\{([^}]+)%([^%#}]+)(?:#([^%#}]+))?\}')
732def root_InternPool_Index_SummaryProvider(value, _=None):
733 unwrapped = value.GetChildMemberWithName('unwrapped')
734 tag = unwrapped.GetChildMemberWithName('tag')
735 tag_value = tag.value
736 summary = tag.CreateValueFromType(tag.type).GetChildMemberWithName('encodings').GetChildMemberWithName(tag_value.removeprefix('.')).GetChildMemberWithName('summary')
737 if not summary: return tag_value
738 return re.sub(
739 expr_path_re,
740 lambda matchobj: getattr(unwrapped.GetValueForExpressionPath(matchobj[1]), matchobj[2]).strip(matchobj[3] or ''),
741 summary.summary.removeprefix('.').removeprefix('@"').removesuffix('"').replace(r'\"', '"'),
742 )
743
744class root_InternPool_Index_SynthProvider:
745 def __init__(self, value, _=None): self.value = value
746 def update(self):
747 self.unwrapped = None
748 wrapped = self.value.unsigned
749 if wrapped == (1 << 32) - 1: return
750 unwrapped_type = self.value.type.FindDirectNestedType('Unwrapped')
751 ip = self.value.CreateValueFromType(unwrapped_type).GetChildMemberWithName('debug_state').GetChildMemberWithName('intern_pool').GetNonSyntheticValue().GetChildMemberWithName('?')
752 tid_width, tid_shift_30 = ip.GetChildMemberWithName('tid_width').unsigned, ip.GetChildMemberWithName('tid_shift_30').unsigned
753 self.unwrapped = create_struct(self.value, '.unwrapped', unwrapped_type, { 'tid': wrapped >> tid_shift_30 & (1 << tid_width) - 1, 'index': wrapped & (1 << tid_shift_30) - 1 })
754 def has_children(self): return True
755 def num_children(self): return 0
756 def get_child_index(self, name):
757 try: return ('unwrapped',).index(name)
758 except: pass
759 def get_child_at_index(self, index):
760 try: return (self.unwrapped,)[index]
761 except: pass
762
763class root_InternPool_Index_Unwrapped_SynthProvider:
764 def __init__(self, value, _=None): self.value = value
765 def update(self):
766 self.tag, self.index, self.data, self.payload, self.trailing = None, None, None, None, None
767 index = self.value.GetChildMemberWithName('index')
768 ip = self.value.CreateValueFromType(self.value.type).GetChildMemberWithName('debug_state').GetChildMemberWithName('intern_pool').GetNonSyntheticValue().GetChildMemberWithName('?')
769 shared = ip.GetChildMemberWithName('locals').GetSyntheticValue().child[self.value.GetChildMemberWithName('tid').unsigned].GetChildMemberWithName('shared')
770 item = shared.GetChildMemberWithName('items').GetChildMemberWithName('view').child[index.unsigned]
771 self.tag, item_data = item.GetChildMemberWithName('tag'), item.GetChildMemberWithName('data')
772 encoding = self.tag.CreateValueFromType(self.tag.type).GetChildMemberWithName('encodings').GetChildMemberWithName(self.tag.value.removeprefix('.'))
773 encoding_index, encoding_data, encoding_payload, encoding_trailing, encoding_config = encoding.GetChildMemberWithName('index'), encoding.GetChildMemberWithName('data'), encoding.GetChildMemberWithName('payload'), encoding.GetChildMemberWithName('trailing'), encoding.GetChildMemberWithName('config')
774 if encoding_index:
775 index_type = encoding_index.GetValueAsType()
776 index_bytes, index_data = index.data.uint8, lldb.SBData()
777 match index_data.byte_order:
778 case lldb.eByteOrderLittle:
779 index_bytes = bytes(index_bytes[:index_type.size])
780 case lldb.eByteOrderBig:
781 index_bytes = bytes(index_bytes[-index_type.size:])
782 index_data.SetData(lldb.SBError(), index_bytes, index_data.byte_order, index_data.GetAddressByteSize())
783 self.index = self.value.CreateValueFromData('.index', index_data, index_type)
784 elif encoding_data:
785 data_type = encoding_data.GetValueAsType()
786 data_bytes, data_data = item_data.data.uint8, lldb.SBData()
787 match data_data.byte_order:
788 case lldb.eByteOrderLittle:
789 data_bytes = bytes(data_bytes[:data_type.size])
790 case lldb.eByteOrderBig:
791 data_bytes = bytes(data_bytes[-data_type.size:])
792 data_data.SetData(lldb.SBError(), data_bytes, data_data.byte_order, data_data.GetAddressByteSize())
793 self.data = self.value.CreateValueFromData('.data', data_data, data_type)
794 elif encoding_payload:
795 extra = shared.GetChildMemberWithName('extra').GetChildMemberWithName('view').GetChildMemberWithName('0')
796 extra_index = item_data.unsigned
797 payload_type = encoding_payload.GetValueAsType()
798 payload_fields = dict()
799 for payload_field in payload_type.fields:
800 payload_fields[payload_field.name] = extra.child[extra_index]
801 extra_index += 1
802 self.payload = create_struct(self.value, '.payload', payload_type, payload_fields)
803 if encoding_trailing and encoding_config:
804 trailing_type = encoding_trailing.GetValueAsType()
805 trailing_bytes, trailing_data = bytearray(trailing_type.size), lldb.SBData()
806 def eval_config(config_name):
807 expr = encoding_config.GetChildMemberWithName(config_name).summary.removeprefix('.').removeprefix('@"').removesuffix('"').replace(r'\"', '"')
808 if 'payload.' in expr:
809 return self.payload.EvaluateExpression(expr.replace('payload.', '@this().'))
810 elif expr.startswith('trailing.'):
811 field_type, field_byte_offset = trailing_type, 0
812 expr_parts = expr.split('.')
813 for expr_part in expr_parts[1:]:
814 field = next(filter(lambda field: field.name == expr_part, field_type.fields))
815 field_type = field.type
816 field_byte_offset += field.byte_offset
817 field_data = lldb.SBData()
818 field_bytes = trailing_bytes[field_byte_offset:field_byte_offset + field_type.size]
819 field_data.SetData(lldb.SBError(), field_bytes, field_data.byte_order, field_data.GetAddressByteSize())
820 return self.value.CreateValueFromData('.%s' % expr_parts[-1], field_data, field_type)
821 else:
822 return self.value.frame.EvaluateExpression(expr)
823 for trailing_field in trailing_type.fields:
824 trailing_field_type = trailing_field.type
825 trailing_field_name = 'trailing.%s' % trailing_field.name
826 trailing_field_byte_offset = trailing_field.byte_offset
827 while True:
828 match [trailing_field_type_field.name for trailing_field_type_field in trailing_field_type.fields]:
829 case ['has_value', '?']:
830 has_value_field, child_field = trailing_field_type.fields
831 trailing_field_name = '%s.%s' % (trailing_field_name, child_field.name)
832 match eval_config(trailing_field_name).value:
833 case 'true':
834 if has_value_field.type.name == 'bool':
835 trailing_bytes[trailing_field_byte_offset + has_value_field.byte_offset] = True
836 trailing_field_type = child_field.type
837 trailing_field_byte_offset += child_field.byte_offset
838 case 'false':
839 break
840 case ['ptr', 'len']:
841 ptr_field, len_field = trailing_field_type.fields
842 ptr_field_byte_offset, len_field_byte_offset = trailing_field_byte_offset + ptr_field.byte_offset, trailing_field_byte_offset + len_field.byte_offset
843 trailing_bytes[ptr_field_byte_offset:ptr_field_byte_offset + ptr_field.type.size] = extra.child[extra_index].address_of.data.uint8
844 len_field_value = eval_config('%s.len' % trailing_field_name)
845 len_field_size = len_field.type.size
846 match trailing_data.byte_order:
847 case lldb.eByteOrderLittle:
848 len_field_bytes = len_field_value.data.uint8[:len_field_size]
849 trailing_bytes[len_field_byte_offset:len_field_byte_offset + len(len_field_bytes)] = len_field_bytes
850 case lldb.eByteOrderBig:
851 len_field_bytes = len_field_value.data.uint8[-len_field_size:]
852 len_field_end = len_field_byte_offset + len_field_size
853 trailing_bytes[len_field_end - len(len_field_bytes):len_field_end] = len_field_bytes
854 extra_index += (ptr_field.type.GetPointeeType().size * len_field_value.unsigned + 3) // 4
855 break
856 case _:
857 for offset in range(0, trailing_field_type.size, 4):
858 trailing_bytes[trailing_field_byte_offset + offset:trailing_field_byte_offset + offset + 4] = extra.child[extra_index].data.uint8
859 extra_index += 1
860 break
861 trailing_data.SetData(lldb.SBError(), trailing_bytes, trailing_data.byte_order, trailing_data.GetAddressByteSize())
862 self.trailing = self.value.CreateValueFromData('.trailing', trailing_data, trailing_type)
863 def has_children(self): return True
864 def num_children(self): return 1 + ((self.index or self.data or self.payload) is not None) + (self.trailing is not None)
865 def get_child_index(self, name):
866 try: return ('tag', 'index' if self.index is not None else 'data' if self.data is not None else 'payload', 'trailing').index(name)
867 except: pass
868 def get_child_at_index(self, index):
869 try: return (self.tag, self.index or self.data or self.payload, self.trailing)[index]
870 except: pass
871
872def root_InternPool_String_SummaryProvider(value, _=None):
873 ip = value.CreateValueFromType(value.type).GetChildMemberWithName('debug_state').GetChildMemberWithName('intern_pool').GetNonSyntheticValue().GetChildMemberWithName('?')
874 tid_shift_32 = ip.GetChildMemberWithName('tid_shift_32').unsigned
875 wrapped = value.unsigned
876 locals_value = ip.GetChildMemberWithName('locals').GetSyntheticValue()
877 local_value = locals_value.child[wrapped >> tid_shift_32]
878 if local_value is None:
879 wrapped = 0
880 local_value = locals_value.child[0]
881 string = local_value.GetChildMemberWithName('shared').GetChildMemberWithName('strings').GetChildMemberWithName('view').GetChildMemberWithName('0').child[wrapped & (1 << tid_shift_32) - 1].address_of
882 string.format = lldb.eFormatCString
883 return string.value
884
715885# Initialize
716886
717887def add(debugger, *, category, regex=False, type, identifier=None, synth=False, inline_children=False, expand=False, summary=False):
......@@ -719,8 +889,6 @@ def add(debugger, *, category, regex=False, type, identifier=None, synth=False,
719889 if summary: debugger.HandleCommand('type summary add --category %s%s%s "%s"' % (category, ' --inline-children' if inline_children else ''.join((' --expand' if expand else '', ' --python-function %s_SummaryProvider' % prefix if summary == True else ' --summary-string "%s"' % summary)), ' --regex' if regex else '', type))
720890 if synth: debugger.HandleCommand('type synthetic add --category %s%s --python-class %s_SynthProvider "%s"' % (category, ' --regex' if regex else '', prefix, type))
721891
722def MultiArrayList_Entry(type): return '^multi_array_list\\.MultiArrayList\\(%s\\)\\.Entry__struct_[1-9][0-9]*$' % type
723
724892def __lldb_init_module(debugger, _=None):
725893 # Initialize Zig Categories
726894 debugger.HandleCommand('type category define --language c99 zig.lang zig.std')
......@@ -765,4 +933,7 @@ def __lldb_init_module(debugger, _=None):
765933 add(debugger, category='zig.stage2', type='arch.x86_64.CodeGen.MCValue', identifier='zig_TaggedUnion', synth=True, inline_children=True, summary=True)
766934
767935 # Initialize Zig Stage2 Compiler (compiled with the self-hosted backend)
768 add(debugger, category='zig', regex=True, type='^root\\.InternPool\\.Local\\.List\\(.*\\)$', identifier='root_InternPool_Local_List', synth=True, expand=True, summary='capacity=${var%#}')
936 add(debugger, category='zig', regex=True, type=r'^root\.InternPool\.Local\.List\(.*\)$', identifier='root_InternPool_Local_List', synth=True, expand=True, summary='capacity=${var%#}')
937 add(debugger, category='zig', type='root.InternPool.Index', synth=True, summary=True)
938 add(debugger, category='zig', type='root.InternPool.Index.Unwrapped', synth=True)
939 add(debugger, category='zig', regex=True, type=r'^root\.InternPool\.(Optional)?(NullTerminated)?String$', identifier='root_InternPool_String', summary=True)