diff --git a/CMakeLists.txt b/CMakeLists.txt index 32f48ba2f005..8348b45cfd41 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -613,7 +613,7 @@ set(ZIG_STAGE2_SOURCES src/link/Elf/relocatable.zig src/link/Elf/relocation.zig src/link/Elf/synthetic_sections.zig - src/link/Elf/thunks.zig + src/link/Elf/Thunk.zig src/link/MachO.zig src/link/MachO/Archive.zig src/link/MachO/Atom.zig @@ -638,7 +638,7 @@ set(ZIG_STAGE2_SOURCES src/link/MachO/load_commands.zig src/link/MachO/relocatable.zig src/link/MachO/synthetic.zig - src/link/MachO/thunks.zig + src/link/MachO/Thunk.zig src/link/MachO/uuid.zig src/link/NvPtx.zig src/link/Plan9.zig diff --git a/lib/std/crypto/poly1305.zig b/lib/std/crypto/poly1305.zig index 254e19ae02ca..787f1059045f 100644 --- a/lib/std/crypto/poly1305.zig +++ b/lib/std/crypto/poly1305.zig @@ -12,7 +12,7 @@ pub const Poly1305 = struct { // accumulated hash h: [3]u64 = [_]u64{ 0, 0, 0 }, // random number added at the end (from the secret key) - pad: [2]u64, + end_pad: [2]u64, // how many bytes are waiting to be processed in a partial block leftover: usize = 0, // partial block buffer @@ -24,7 +24,7 @@ pub const Poly1305 = struct { mem.readInt(u64, key[0..8], .little) & 0x0ffffffc0fffffff, mem.readInt(u64, key[8..16], .little) & 0x0ffffffc0ffffffc, }, - .pad = [_]u64{ + .end_pad = [_]u64{ mem.readInt(u64, key[16..24], .little), mem.readInt(u64, key[24..32], .little), }, @@ -177,9 +177,9 @@ pub const Poly1305 = struct { h1 ^= mask & (h1 ^ h_p1); // Add the first half of the key, we intentionally don't use @addWithOverflow() here. - st.h[0] = h0 +% st.pad[0]; - const c = ((h0 & st.pad[0]) | ((h0 | st.pad[0]) & ~st.h[0])) >> 63; - st.h[1] = h1 +% st.pad[1] +% c; + st.h[0] = h0 +% st.end_pad[0]; + const c = ((h0 & st.end_pad[0]) | ((h0 | st.end_pad[0]) & ~st.h[0])) >> 63; + st.h[1] = h1 +% st.end_pad[1] +% c; mem.writeInt(u64, out[0..8], st.h[0], .little); mem.writeInt(u64, out[8..16], st.h[1], .little); diff --git a/lib/std/debug/Pdb.zig b/lib/std/debug/Pdb.zig index 2b2f37e7b6aa..3b1adb3c5665 100644 --- a/lib/std/debug/Pdb.zig +++ b/lib/std/debug/Pdb.zig @@ -63,18 +63,18 @@ pub fn deinit(self: *Pdb) void { } pub fn parseDbiStream(self: *Pdb) !void { - var stream = self.getStream(pdb.StreamType.Dbi) orelse + var stream = self.getStream(pdb.StreamType.dbi) orelse return error.InvalidDebugInfo; const reader = stream.reader(); const header = try reader.readStruct(std.pdb.DbiStreamHeader); - if (header.VersionHeader != 19990903) // V70, only value observed by LLVM team + if (header.version_header != 19990903) // V70, only value observed by LLVM team return error.UnknownPDBVersion; // if (header.Age != age) // return error.UnmatchingPDB; - const mod_info_size = header.ModInfoSize; - const section_contrib_size = header.SectionContributionSize; + const mod_info_size = header.mod_info_size; + const section_contrib_size = header.section_contribution_size; var modules = std.ArrayList(Module).init(self.allocator); errdefer modules.deinit(); @@ -143,7 +143,7 @@ pub fn parseDbiStream(self: *Pdb) !void { } pub fn parseInfoStream(self: *Pdb) !void { - var stream = self.getStream(pdb.StreamType.Pdb) orelse + var stream = self.getStream(pdb.StreamType.pdb) orelse return error.InvalidDebugInfo; const reader = stream.reader(); @@ -168,23 +168,23 @@ pub fn parseInfoStream(self: *Pdb) !void { try reader.readNoEof(name_bytes); const HashTableHeader = extern struct { - Size: u32, - Capacity: u32, + size: u32, + capacity: u32, fn maxLoad(cap: u32) u32 { return cap * 2 / 3 + 1; } }; const hash_tbl_hdr = try reader.readStruct(HashTableHeader); - if (hash_tbl_hdr.Capacity == 0) + if (hash_tbl_hdr.capacity == 0) return error.InvalidDebugInfo; - if (hash_tbl_hdr.Size > HashTableHeader.maxLoad(hash_tbl_hdr.Capacity)) + if (hash_tbl_hdr.size > HashTableHeader.maxLoad(hash_tbl_hdr.capacity)) return error.InvalidDebugInfo; const present = try readSparseBitVector(&reader, self.allocator); defer self.allocator.free(present); - if (present.len != hash_tbl_hdr.Size) + if (present.len != hash_tbl_hdr.size) return error.InvalidDebugInfo; const deleted = try readSparseBitVector(&reader, self.allocator); defer self.allocator.free(deleted); @@ -212,19 +212,19 @@ pub fn getSymbolName(self: *Pdb, module: *Module, address: u64) ?[]const u8 { var symbol_i: usize = 0; while (symbol_i != module.symbols.len) { - const prefix = @as(*align(1) pdb.RecordPrefix, @ptrCast(&module.symbols[symbol_i])); - if (prefix.RecordLen < 2) + const prefix: *align(1) pdb.RecordPrefix = @ptrCast(&module.symbols[symbol_i]); + if (prefix.record_len < 2) return null; - switch (prefix.RecordKind) { - .S_LPROC32, .S_GPROC32 => { - const proc_sym = @as(*align(1) pdb.ProcSym, @ptrCast(&module.symbols[symbol_i + @sizeOf(pdb.RecordPrefix)])); - if (address >= proc_sym.CodeOffset and address < proc_sym.CodeOffset + proc_sym.CodeSize) { - return std.mem.sliceTo(@as([*:0]u8, @ptrCast(&proc_sym.Name[0])), 0); + switch (prefix.record_kind) { + .lproc32, .gproc32 => { + const proc_sym: *align(1) pdb.ProcSym = @ptrCast(&module.symbols[symbol_i + @sizeOf(pdb.RecordPrefix)]); + if (address >= proc_sym.code_offset and address < proc_sym.code_offset + proc_sym.code_size) { + return std.mem.sliceTo(@as([*:0]u8, @ptrCast(&proc_sym.name[0])), 0); } }, else => {}, } - symbol_i += prefix.RecordLen + @sizeOf(u16); + symbol_i += prefix.record_len + @sizeOf(u16); } return null; @@ -238,44 +238,44 @@ pub fn getLineNumberInfo(self: *Pdb, module: *Module, address: u64) !std.debug.S var skip_len: usize = undefined; const checksum_offset = module.checksum_offset orelse return error.MissingDebugInfo; while (sect_offset != subsect_info.len) : (sect_offset += skip_len) { - const subsect_hdr = @as(*align(1) pdb.DebugSubsectionHeader, @ptrCast(&subsect_info[sect_offset])); - skip_len = subsect_hdr.Length; + const subsect_hdr: *align(1) pdb.DebugSubsectionHeader = @ptrCast(&subsect_info[sect_offset]); + skip_len = subsect_hdr.length; sect_offset += @sizeOf(pdb.DebugSubsectionHeader); - switch (subsect_hdr.Kind) { - .Lines => { + switch (subsect_hdr.kind) { + .lines => { var line_index = sect_offset; - const line_hdr = @as(*align(1) pdb.LineFragmentHeader, @ptrCast(&subsect_info[line_index])); - if (line_hdr.RelocSegment == 0) + const line_hdr: *align(1) pdb.LineFragmentHeader = @ptrCast(&subsect_info[line_index]); + if (line_hdr.reloc_segment == 0) return error.MissingDebugInfo; line_index += @sizeOf(pdb.LineFragmentHeader); - const frag_vaddr_start = line_hdr.RelocOffset; - const frag_vaddr_end = frag_vaddr_start + line_hdr.CodeSize; + const frag_vaddr_start = line_hdr.reloc_offset; + const frag_vaddr_end = frag_vaddr_start + line_hdr.code_size; if (address >= frag_vaddr_start and address < frag_vaddr_end) { // There is an unknown number of LineBlockFragmentHeaders (and their accompanying line and column records) // from now on. We will iterate through them, and eventually find a SourceLocation that we're interested in, // breaking out to :subsections. If not, we will make sure to not read anything outside of this subsection. - const subsection_end_index = sect_offset + subsect_hdr.Length; + const subsection_end_index = sect_offset + subsect_hdr.length; while (line_index < subsection_end_index) { - const block_hdr = @as(*align(1) pdb.LineBlockFragmentHeader, @ptrCast(&subsect_info[line_index])); + const block_hdr: *align(1) pdb.LineBlockFragmentHeader = @ptrCast(&subsect_info[line_index]); line_index += @sizeOf(pdb.LineBlockFragmentHeader); const start_line_index = line_index; - const has_column = line_hdr.Flags.LF_HaveColumns; + const has_column = line_hdr.flags.have_columns; // All line entries are stored inside their line block by ascending start address. // Heuristic: we want to find the last line entry // that has a vaddr_start <= address. // This is done with a simple linear search. var line_i: u32 = 0; - while (line_i < block_hdr.NumLines) : (line_i += 1) { - const line_num_entry = @as(*align(1) pdb.LineNumberEntry, @ptrCast(&subsect_info[line_index])); + while (line_i < block_hdr.num_lines) : (line_i += 1) { + const line_num_entry: *align(1) pdb.LineNumberEntry = @ptrCast(&subsect_info[line_index]); line_index += @sizeOf(pdb.LineNumberEntry); - const vaddr_start = frag_vaddr_start + line_num_entry.Offset; + const vaddr_start = frag_vaddr_start + line_num_entry.offset; if (address < vaddr_start) { break; } @@ -283,28 +283,27 @@ pub fn getLineNumberInfo(self: *Pdb, module: *Module, address: u64) !std.debug.S // line_i == 0 would mean that no matching pdb.LineNumberEntry was found. if (line_i > 0) { - const subsect_index = checksum_offset + block_hdr.NameIndex; - const chksum_hdr = @as(*align(1) pdb.FileChecksumEntryHeader, @ptrCast(&module.subsect_info[subsect_index])); - const strtab_offset = @sizeOf(pdb.StringTableHeader) + chksum_hdr.FileNameOffset; + const subsect_index = checksum_offset + block_hdr.name_index; + const chksum_hdr: *align(1) pdb.FileChecksumEntryHeader = @ptrCast(&module.subsect_info[subsect_index]); + const strtab_offset = @sizeOf(pdb.StringTableHeader) + chksum_hdr.file_name_offset; try self.string_table.?.seekTo(strtab_offset); const source_file_name = try self.string_table.?.reader().readUntilDelimiterAlloc(self.allocator, 0, 1024); const line_entry_idx = line_i - 1; const column = if (has_column) blk: { - const start_col_index = start_line_index + @sizeOf(pdb.LineNumberEntry) * block_hdr.NumLines; + const start_col_index = start_line_index + @sizeOf(pdb.LineNumberEntry) * block_hdr.num_lines; const col_index = start_col_index + @sizeOf(pdb.ColumnNumberEntry) * line_entry_idx; - const col_num_entry = @as(*align(1) pdb.ColumnNumberEntry, @ptrCast(&subsect_info[col_index])); - break :blk col_num_entry.StartColumn; + const col_num_entry: *align(1) pdb.ColumnNumberEntry = @ptrCast(&subsect_info[col_index]); + break :blk col_num_entry.start_column; } else 0; const found_line_index = start_line_index + line_entry_idx * @sizeOf(pdb.LineNumberEntry); const line_num_entry: *align(1) pdb.LineNumberEntry = @ptrCast(&subsect_info[found_line_index]); - const flags: *align(1) pdb.LineNumberEntry.Flags = @ptrCast(&line_num_entry.Flags); return .{ .file_name = source_file_name, - .line = flags.Start, + .line = line_num_entry.flags.start, .column = column, }; } @@ -335,12 +334,12 @@ pub fn getModule(self: *Pdb, index: usize) !?*Module { return mod; // At most one can be non-zero. - if (mod.mod_info.C11ByteSize != 0 and mod.mod_info.C13ByteSize != 0) + if (mod.mod_info.c11_byte_size != 0 and mod.mod_info.c13_byte_size != 0) return error.InvalidDebugInfo; - if (mod.mod_info.C13ByteSize == 0) + if (mod.mod_info.c13_byte_size == 0) return error.InvalidDebugInfo; - const stream = self.getStreamById(mod.mod_info.ModuleSymStream) orelse + const stream = self.getStreamById(mod.mod_info.module_sym_stream) orelse return error.MissingDebugInfo; const reader = stream.reader(); @@ -348,23 +347,23 @@ pub fn getModule(self: *Pdb, index: usize) !?*Module { if (signature != 4) return error.InvalidDebugInfo; - mod.symbols = try self.allocator.alloc(u8, mod.mod_info.SymByteSize - 4); + mod.symbols = try self.allocator.alloc(u8, mod.mod_info.sym_byte_size - 4); errdefer self.allocator.free(mod.symbols); try reader.readNoEof(mod.symbols); - mod.subsect_info = try self.allocator.alloc(u8, mod.mod_info.C13ByteSize); + mod.subsect_info = try self.allocator.alloc(u8, mod.mod_info.c13_byte_size); errdefer self.allocator.free(mod.subsect_info); try reader.readNoEof(mod.subsect_info); var sect_offset: usize = 0; var skip_len: usize = undefined; while (sect_offset != mod.subsect_info.len) : (sect_offset += skip_len) { - const subsect_hdr = @as(*align(1) pdb.DebugSubsectionHeader, @ptrCast(&mod.subsect_info[sect_offset])); - skip_len = subsect_hdr.Length; + const subsect_hdr: *align(1) pdb.DebugSubsectionHeader = @ptrCast(&mod.subsect_info[sect_offset]); + skip_len = subsect_hdr.length; sect_offset += @sizeOf(pdb.DebugSubsectionHeader); - switch (subsect_hdr.Kind) { - .FileChecksums => { + switch (subsect_hdr.kind) { + .file_checksums => { mod.checksum_offset = sect_offset; break; }, @@ -401,30 +400,30 @@ const Msf = struct { const superblock = try in.readStruct(pdb.SuperBlock); // Sanity checks - if (!std.mem.eql(u8, &superblock.FileMagic, pdb.SuperBlock.file_magic)) + if (!std.mem.eql(u8, &superblock.file_magic, pdb.SuperBlock.expect_magic)) return error.InvalidDebugInfo; - if (superblock.FreeBlockMapBlock != 1 and superblock.FreeBlockMapBlock != 2) + if (superblock.free_block_map_block != 1 and superblock.free_block_map_block != 2) return error.InvalidDebugInfo; const file_len = try file.getEndPos(); - if (superblock.NumBlocks * superblock.BlockSize != file_len) + if (superblock.num_blocks * superblock.block_size != file_len) return error.InvalidDebugInfo; - switch (superblock.BlockSize) { + switch (superblock.block_size) { // llvm only supports 4096 but we can handle any of these values 512, 1024, 2048, 4096 => {}, else => return error.InvalidDebugInfo, } - const dir_block_count = blockCountFromSize(superblock.NumDirectoryBytes, superblock.BlockSize); - if (dir_block_count > superblock.BlockSize / @sizeOf(u32)) + const dir_block_count = blockCountFromSize(superblock.num_directory_bytes, superblock.block_size); + if (dir_block_count > superblock.block_size / @sizeOf(u32)) return error.UnhandledBigDirectoryStream; // cf. BlockMapAddr comment. - try file.seekTo(superblock.BlockSize * superblock.BlockMapAddr); + try file.seekTo(superblock.block_size * superblock.block_map_addr); const dir_blocks = try allocator.alloc(u32, dir_block_count); for (dir_blocks) |*b| { b.* = try in.readInt(u32, .little); } var directory = MsfStream.init( - superblock.BlockSize, + superblock.block_size, file, dir_blocks, ); @@ -440,7 +439,7 @@ const Msf = struct { const Nil = 0xFFFFFFFF; for (stream_sizes) |*s| { const size = try directory.reader().readInt(u32, .little); - s.* = if (size == Nil) 0 else blockCountFromSize(size, superblock.BlockSize); + s.* = if (size == Nil) 0 else blockCountFromSize(size, superblock.block_size); } const streams = try allocator.alloc(MsfStream, stream_count); @@ -455,15 +454,15 @@ const Msf = struct { var j: u32 = 0; while (j < size) : (j += 1) { const block_id = try directory.reader().readInt(u32, .little); - const n = (block_id % superblock.BlockSize); + const n = (block_id % superblock.block_size); // 0 is for pdb.SuperBlock, 1 and 2 for FPMs. - if (block_id == 0 or n == 1 or n == 2 or block_id * superblock.BlockSize > file_len) + if (block_id == 0 or n == 1 or n == 2 or block_id * superblock.block_size > file_len) return error.InvalidBlockIndex; blocks[j] = block_id; } stream.* = MsfStream.init( - superblock.BlockSize, + superblock.block_size, file, blocks, ); @@ -471,7 +470,7 @@ const Msf = struct { } const end = directory.pos; - if (end - begin != superblock.NumDirectoryBytes) + if (end - begin != superblock.num_directory_bytes) return error.InvalidStreamDirectory; return Msf{ diff --git a/lib/std/debug/SelfInfo.zig b/lib/std/debug/SelfInfo.zig index 19adebf711f0..5e7aefef3810 100644 --- a/lib/std/debug/SelfInfo.zig +++ b/lib/std/debug/SelfInfo.zig @@ -732,14 +732,14 @@ pub const Module = switch (native_os) { fn getSymbolFromPdb(self: *@This(), relocated_address: usize) !?std.debug.Symbol { var coff_section: *align(1) const coff.SectionHeader = undefined; const mod_index = for (self.pdb.?.sect_contribs) |sect_contrib| { - if (sect_contrib.Section > self.coff_section_headers.len) continue; + if (sect_contrib.section > self.coff_section_headers.len) continue; // Remember that SectionContribEntry.Section is 1-based. - coff_section = &self.coff_section_headers[sect_contrib.Section - 1]; + coff_section = &self.coff_section_headers[sect_contrib.section - 1]; - const vaddr_start = coff_section.virtual_address + sect_contrib.Offset; - const vaddr_end = vaddr_start + sect_contrib.Size; + const vaddr_start = coff_section.virtual_address + sect_contrib.offset; + const vaddr_end = vaddr_start + sect_contrib.size; if (relocated_address >= vaddr_start and relocated_address < vaddr_end) { - break sect_contrib.ModuleIndex; + break sect_contrib.module_index; } } else { // we have no information to add to the address diff --git a/lib/std/enums.zig b/lib/std/enums.zig index a051d96112ae..aebfe2a18a7c 100644 --- a/lib/std/enums.zig +++ b/lib/std/enums.zig @@ -1501,7 +1501,7 @@ test values { X, Y, Z, - pub const X = 1; + const A = 1; }; try testing.expectEqualSlices(E, &.{ .X, .Y, .Z }, values(E)); } diff --git a/lib/std/heap/sbrk_allocator.zig b/lib/std/heap/sbrk_allocator.zig index 3ccc2dddf7f3..08933fed5257 100644 --- a/lib/std/heap/sbrk_allocator.zig +++ b/lib/std/heap/sbrk_allocator.zig @@ -7,7 +7,7 @@ const assert = std.debug.assert; pub fn SbrkAllocator(comptime sbrk: *const fn (n: usize) usize) type { return struct { - pub const vtable = Allocator.VTable{ + pub const vtable: Allocator.VTable = .{ .alloc = alloc, .resize = resize, .free = free, @@ -15,8 +15,6 @@ pub fn SbrkAllocator(comptime sbrk: *const fn (n: usize) usize) type { pub const Error = Allocator.Error; - lock: std.Thread.Mutex = .{}, - const max_usize = math.maxInt(usize); const ushift = math.Log2Int(usize); const bigpage_size = 64 * 1024; diff --git a/lib/std/meta.zig b/lib/std/meta.zig index 3d3bfca1f9ea..e7ea5b5f0efd 100644 --- a/lib/std/meta.zig +++ b/lib/std/meta.zig @@ -294,7 +294,7 @@ test declarations { pub fn a() void {} }; const U1 = union { - a: u8, + b: u8, pub fn a() void {} }; @@ -334,7 +334,7 @@ test declarationInfo { pub fn a() void {} }; const U1 = union { - a: u8, + b: u8, pub fn a() void {} }; diff --git a/lib/std/os/uefi/device_path.zig b/lib/std/os/uefi/device_path.zig index 55a3763d66c1..e02d452b096f 100644 --- a/lib/std/os/uefi/device_path.zig +++ b/lib/std/os/uefi/device_path.zig @@ -4,38 +4,38 @@ const uefi = std.os.uefi; const Guid = uefi.Guid; pub const DevicePath = union(Type) { - Hardware: Hardware, - Acpi: Acpi, - Messaging: Messaging, - Media: Media, - BiosBootSpecification: BiosBootSpecification, - End: End, + hardware: Hardware, + acpi: Acpi, + messaging: Messaging, + media: Media, + bios_boot_specification: BiosBootSpecification, + end: End, pub const Type = enum(u8) { - Hardware = 0x01, - Acpi = 0x02, - Messaging = 0x03, - Media = 0x04, - BiosBootSpecification = 0x05, - End = 0x7f, + hardware = 0x01, + acpi = 0x02, + messaging = 0x03, + media = 0x04, + bios_boot_specification = 0x05, + end = 0x7f, _, }; pub const Hardware = union(Subtype) { - Pci: *const PciDevicePath, - PcCard: *const PcCardDevicePath, - MemoryMapped: *const MemoryMappedDevicePath, - Vendor: *const VendorDevicePath, - Controller: *const ControllerDevicePath, - Bmc: *const BmcDevicePath, + pci: *const PciDevicePath, + pc_card: *const PcCardDevicePath, + memory_mapped: *const MemoryMappedDevicePath, + vendor: *const VendorDevicePath, + controller: *const ControllerDevicePath, + bmc: *const BmcDevicePath, pub const Subtype = enum(u8) { - Pci = 1, - PcCard = 2, - MemoryMapped = 3, - Vendor = 4, - Controller = 5, - Bmc = 6, + pci = 1, + pc_card = 2, + memory_mapped = 3, + vendor = 4, + controller = 5, + bmc = 6, _, }; @@ -151,14 +151,14 @@ pub const DevicePath = union(Type) { }; pub const Acpi = union(Subtype) { - Acpi: *const BaseAcpiDevicePath, - ExpandedAcpi: *const ExpandedAcpiDevicePath, - Adr: *const AdrDevicePath, + acpi: *const BaseAcpiDevicePath, + expanded_acpi: *const ExpandedAcpiDevicePath, + adr: *const AdrDevicePath, pub const Subtype = enum(u8) { - Acpi = 1, - ExpandedAcpi = 2, - Adr = 3, + acpi = 1, + expanded_acpi = 2, + adr = 3, _, }; diff --git a/lib/std/pdb.zig b/lib/std/pdb.zig index 31ad02e94564..b44f48974d2e 100644 --- a/lib/std/pdb.zig +++ b/lib/std/pdb.zig @@ -20,297 +20,297 @@ const ArrayList = std.ArrayList; /// https://llvm.org/docs/PDB/DbiStream.html#stream-header pub const DbiStreamHeader = extern struct { - VersionSignature: i32, - VersionHeader: u32, - Age: u32, - GlobalStreamIndex: u16, - BuildNumber: u16, - PublicStreamIndex: u16, - PdbDllVersion: u16, - SymRecordStream: u16, - PdbDllRbld: u16, - ModInfoSize: u32, - SectionContributionSize: u32, - SectionMapSize: u32, - SourceInfoSize: i32, - TypeServerSize: i32, - MFCTypeServerIndex: u32, - OptionalDbgHeaderSize: i32, - ECSubstreamSize: i32, - Flags: u16, - Machine: u16, - Padding: u32, + version_signature: i32, + version_header: u32, + age: u32, + global_stream_index: u16, + build_number: u16, + public_stream_index: u16, + pdb_dll_version: u16, + sym_record_stream: u16, + pdb_dll_rbld: u16, + mod_info_size: u32, + section_contribution_size: u32, + section_map_size: u32, + source_info_size: i32, + type_server_size: i32, + mfc_type_server_index: u32, + optional_dbg_header_size: i32, + ec_substream_size: i32, + flags: u16, + machine: u16, + padding: u32, }; pub const SectionContribEntry = extern struct { /// COFF Section index, 1-based - Section: u16, - Padding1: [2]u8, - Offset: u32, - Size: u32, - Characteristics: u32, - ModuleIndex: u16, - Padding2: [2]u8, - DataCrc: u32, - RelocCrc: u32, + section: u16, + padding1: [2]u8, + offset: u32, + size: u32, + characteristics: u32, + module_index: u16, + padding2: [2]u8, + data_crc: u32, + reloc_crc: u32, }; pub const ModInfo = extern struct { - Unused1: u32, - SectionContr: SectionContribEntry, - Flags: u16, - ModuleSymStream: u16, - SymByteSize: u32, - C11ByteSize: u32, - C13ByteSize: u32, - SourceFileCount: u16, - Padding: [2]u8, - Unused2: u32, - SourceFileNameIndex: u32, - PdbFilePathNameIndex: u32, + unused1: u32, + section_contr: SectionContribEntry, + flags: u16, + module_sym_stream: u16, + sym_byte_size: u32, + c11_byte_size: u32, + c13_byte_size: u32, + source_file_count: u16, + padding: [2]u8, + unused2: u32, + source_file_name_index: u32, + pdb_file_path_name_index: u32, // These fields are variable length - //ModuleName: char[], - //ObjFileName: char[], + //module_name: char[], + //obj_file_name: char[], }; pub const SectionMapHeader = extern struct { /// Number of segment descriptors - Count: u16, + count: u16, /// Number of logical segment descriptors - LogCount: u16, + log_count: u16, }; pub const SectionMapEntry = extern struct { /// See the SectionMapEntryFlags enum below. - Flags: u16, + flags: u16, /// Logical overlay number - Ovl: u16, + ovl: u16, /// Group index into descriptor array. - Group: u16, - Frame: u16, + group: u16, + frame: u16, /// Byte index of segment / group name in string table, or 0xFFFF. - SectionName: u16, + section_name: u16, /// Byte index of class in string table, or 0xFFFF. - ClassName: u16, + class_name: u16, /// Byte offset of the logical segment within physical segment. If group is set in flags, this is the offset of the group. - Offset: u32, + offset: u32, /// Byte count of the segment or group. - SectionLength: u32, + section_length: u32, }; pub const StreamType = enum(u16) { - Pdb = 1, - Tpi = 2, - Dbi = 3, - Ipi = 4, + pdb = 1, + tpi = 2, + dbi = 3, + ipi = 4, }; /// Duplicate copy of SymbolRecordKind, but using the official CV names. Useful /// for reference purposes and when dealing with unknown record types. pub const SymbolKind = enum(u16) { - S_COMPILE = 1, - S_REGISTER_16t = 2, - S_CONSTANT_16t = 3, - S_UDT_16t = 4, - S_SSEARCH = 5, - S_SKIP = 7, - S_CVRESERVE = 8, - S_OBJNAME_ST = 9, - S_ENDARG = 10, - S_COBOLUDT_16t = 11, - S_MANYREG_16t = 12, - S_RETURN = 13, - S_ENTRYTHIS = 14, - S_BPREL16 = 256, - S_LDATA16 = 257, - S_GDATA16 = 258, - S_PUB16 = 259, - S_LPROC16 = 260, - S_GPROC16 = 261, - S_THUNK16 = 262, - S_BLOCK16 = 263, - S_WITH16 = 264, - S_LABEL16 = 265, - S_CEXMODEL16 = 266, - S_VFTABLE16 = 267, - S_REGREL16 = 268, - S_BPREL32_16t = 512, - S_LDATA32_16t = 513, - S_GDATA32_16t = 514, - S_PUB32_16t = 515, - S_LPROC32_16t = 516, - S_GPROC32_16t = 517, - S_THUNK32_ST = 518, - S_BLOCK32_ST = 519, - S_WITH32_ST = 520, - S_LABEL32_ST = 521, - S_CEXMODEL32 = 522, - S_VFTABLE32_16t = 523, - S_REGREL32_16t = 524, - S_LTHREAD32_16t = 525, - S_GTHREAD32_16t = 526, - S_SLINK32 = 527, - S_LPROCMIPS_16t = 768, - S_GPROCMIPS_16t = 769, - S_PROCREF_ST = 1024, - S_DATAREF_ST = 1025, - S_ALIGN = 1026, - S_LPROCREF_ST = 1027, - S_OEM = 1028, - S_TI16_MAX = 4096, - S_REGISTER_ST = 4097, - S_CONSTANT_ST = 4098, - S_UDT_ST = 4099, - S_COBOLUDT_ST = 4100, - S_MANYREG_ST = 4101, - S_BPREL32_ST = 4102, - S_LDATA32_ST = 4103, - S_GDATA32_ST = 4104, - S_PUB32_ST = 4105, - S_LPROC32_ST = 4106, - S_GPROC32_ST = 4107, - S_VFTABLE32 = 4108, - S_REGREL32_ST = 4109, - S_LTHREAD32_ST = 4110, - S_GTHREAD32_ST = 4111, - S_LPROCMIPS_ST = 4112, - S_GPROCMIPS_ST = 4113, - S_COMPILE2_ST = 4115, - S_MANYREG2_ST = 4116, - S_LPROCIA64_ST = 4117, - S_GPROCIA64_ST = 4118, - S_LOCALSLOT_ST = 4119, - S_PARAMSLOT_ST = 4120, - S_ANNOTATION = 4121, - S_GMANPROC_ST = 4122, - S_LMANPROC_ST = 4123, - S_RESERVED1 = 4124, - S_RESERVED2 = 4125, - S_RESERVED3 = 4126, - S_RESERVED4 = 4127, - S_LMANDATA_ST = 4128, - S_GMANDATA_ST = 4129, - S_MANFRAMEREL_ST = 4130, - S_MANREGISTER_ST = 4131, - S_MANSLOT_ST = 4132, - S_MANMANYREG_ST = 4133, - S_MANREGREL_ST = 4134, - S_MANMANYREG2_ST = 4135, - S_MANTYPREF = 4136, - S_UNAMESPACE_ST = 4137, - S_ST_MAX = 4352, - S_WITH32 = 4356, - S_MANYREG = 4362, - S_LPROCMIPS = 4372, - S_GPROCMIPS = 4373, - S_MANYREG2 = 4375, - S_LPROCIA64 = 4376, - S_GPROCIA64 = 4377, - S_LOCALSLOT = 4378, - S_PARAMSLOT = 4379, - S_MANFRAMEREL = 4382, - S_MANREGISTER = 4383, - S_MANSLOT = 4384, - S_MANMANYREG = 4385, - S_MANREGREL = 4386, - S_MANMANYREG2 = 4387, - S_UNAMESPACE = 4388, - S_DATAREF = 4390, - S_ANNOTATIONREF = 4392, - S_TOKENREF = 4393, - S_GMANPROC = 4394, - S_LMANPROC = 4395, - S_ATTR_FRAMEREL = 4398, - S_ATTR_REGISTER = 4399, - S_ATTR_REGREL = 4400, - S_ATTR_MANYREG = 4401, - S_SEPCODE = 4402, - S_LOCAL_2005 = 4403, - S_DEFRANGE_2005 = 4404, - S_DEFRANGE2_2005 = 4405, - S_DISCARDED = 4411, - S_LPROCMIPS_ID = 4424, - S_GPROCMIPS_ID = 4425, - S_LPROCIA64_ID = 4426, - S_GPROCIA64_ID = 4427, - S_DEFRANGE_HLSL = 4432, - S_GDATA_HLSL = 4433, - S_LDATA_HLSL = 4434, - S_LOCAL_DPC_GROUPSHARED = 4436, - S_DEFRANGE_DPC_PTR_TAG = 4439, - S_DPC_SYM_TAG_MAP = 4440, - S_ARMSWITCHTABLE = 4441, - S_POGODATA = 4444, - S_INLINESITE2 = 4445, - S_MOD_TYPEREF = 4447, - S_REF_MINIPDB = 4448, - S_PDBMAP = 4449, - S_GDATA_HLSL32 = 4450, - S_LDATA_HLSL32 = 4451, - S_GDATA_HLSL32_EX = 4452, - S_LDATA_HLSL32_EX = 4453, - S_FASTLINK = 4455, - S_INLINEES = 4456, - S_END = 6, - S_INLINESITE_END = 4430, - S_PROC_ID_END = 4431, - S_THUNK32 = 4354, - S_TRAMPOLINE = 4396, - S_SECTION = 4406, - S_COFFGROUP = 4407, - S_EXPORT = 4408, - S_LPROC32 = 4367, - S_GPROC32 = 4368, - S_LPROC32_ID = 4422, - S_GPROC32_ID = 4423, - S_LPROC32_DPC = 4437, - S_LPROC32_DPC_ID = 4438, - S_REGISTER = 4358, - S_PUB32 = 4366, - S_PROCREF = 4389, - S_LPROCREF = 4391, - S_ENVBLOCK = 4413, - S_INLINESITE = 4429, - S_LOCAL = 4414, - S_DEFRANGE = 4415, - S_DEFRANGE_SUBFIELD = 4416, - S_DEFRANGE_REGISTER = 4417, - S_DEFRANGE_FRAMEPOINTER_REL = 4418, - S_DEFRANGE_SUBFIELD_REGISTER = 4419, - S_DEFRANGE_FRAMEPOINTER_REL_FULL_SCOPE = 4420, - S_DEFRANGE_REGISTER_REL = 4421, - S_BLOCK32 = 4355, - S_LABEL32 = 4357, - S_OBJNAME = 4353, - S_COMPILE2 = 4374, - S_COMPILE3 = 4412, - S_FRAMEPROC = 4114, - S_CALLSITEINFO = 4409, - S_FILESTATIC = 4435, - S_HEAPALLOCSITE = 4446, - S_FRAMECOOKIE = 4410, - S_CALLEES = 4442, - S_CALLERS = 4443, - S_UDT = 4360, - S_COBOLUDT = 4361, - S_BUILDINFO = 4428, - S_BPREL32 = 4363, - S_REGREL32 = 4369, - S_CONSTANT = 4359, - S_MANCONSTANT = 4397, - S_LDATA32 = 4364, - S_GDATA32 = 4365, - S_LMANDATA = 4380, - S_GMANDATA = 4381, - S_LTHREAD32 = 4370, - S_GTHREAD32 = 4371, + compile = 1, + register_16t = 2, + constant_16t = 3, + udt_16t = 4, + ssearch = 5, + skip = 7, + cvreserve = 8, + objname_st = 9, + endarg = 10, + coboludt_16t = 11, + manyreg_16t = 12, + @"return" = 13, + entrythis = 14, + bprel16 = 256, + ldata16 = 257, + gdata16 = 258, + pub16 = 259, + lproc16 = 260, + gproc16 = 261, + thunk16 = 262, + block16 = 263, + with16 = 264, + label16 = 265, + cexmodel16 = 266, + vftable16 = 267, + regrel16 = 268, + bprel32_16t = 512, + ldata32_16t = 513, + gdata32_16t = 514, + pub32_16t = 515, + lproc32_16t = 516, + gproc32_16t = 517, + thunk32_st = 518, + block32_st = 519, + with32_st = 520, + label32_st = 521, + cexmodel32 = 522, + vftable32_16t = 523, + regrel32_16t = 524, + lthread32_16t = 525, + gthread32_16t = 526, + slink32 = 527, + lprocmips_16t = 768, + gprocmips_16t = 769, + procref_st = 1024, + dataref_st = 1025, + @"align" = 1026, + lprocref_st = 1027, + oem = 1028, + ti16_max = 4096, + register_st = 4097, + constant_st = 4098, + udt_st = 4099, + coboludt_st = 4100, + manyreg_st = 4101, + bprel32_st = 4102, + ldata32_st = 4103, + gdata32_st = 4104, + pub32_st = 4105, + lproc32_st = 4106, + gproc32_st = 4107, + vftable32 = 4108, + regrel32_st = 4109, + lthread32_st = 4110, + gthread32_st = 4111, + lprocmips_st = 4112, + gprocmips_st = 4113, + compile2_st = 4115, + manyreg2_st = 4116, + lprocia64_st = 4117, + gprocia64_st = 4118, + localslot_st = 4119, + paramslot_st = 4120, + annotation = 4121, + gmanproc_st = 4122, + lmanproc_st = 4123, + reserved1 = 4124, + reserved2 = 4125, + reserved3 = 4126, + reserved4 = 4127, + lmandata_st = 4128, + gmandata_st = 4129, + manframerel_st = 4130, + manregister_st = 4131, + manslot_st = 4132, + manmanyreg_st = 4133, + manregrel_st = 4134, + manmanyreg2_st = 4135, + mantypref = 4136, + unamespace_st = 4137, + st_max = 4352, + with32 = 4356, + manyreg = 4362, + lprocmips = 4372, + gprocmips = 4373, + manyreg2 = 4375, + lprocia64 = 4376, + gprocia64 = 4377, + localslot = 4378, + paramslot = 4379, + manframerel = 4382, + manregister = 4383, + manslot = 4384, + manmanyreg = 4385, + manregrel = 4386, + manmanyreg2 = 4387, + unamespace = 4388, + dataref = 4390, + annotationref = 4392, + tokenref = 4393, + gmanproc = 4394, + lmanproc = 4395, + attr_framerel = 4398, + attr_register = 4399, + attr_regrel = 4400, + attr_manyreg = 4401, + sepcode = 4402, + local_2005 = 4403, + defrange_2005 = 4404, + defrange2_2005 = 4405, + discarded = 4411, + lprocmips_id = 4424, + gprocmips_id = 4425, + lprocia64_id = 4426, + gprocia64_id = 4427, + defrange_hlsl = 4432, + gdata_hlsl = 4433, + ldata_hlsl = 4434, + local_dpc_groupshared = 4436, + defrange_dpc_ptr_tag = 4439, + dpc_sym_tag_map = 4440, + armswitchtable = 4441, + pogodata = 4444, + inlinesite2 = 4445, + mod_typeref = 4447, + ref_minipdb = 4448, + pdbmap = 4449, + gdata_hlsl32 = 4450, + ldata_hlsl32 = 4451, + gdata_hlsl32_ex = 4452, + ldata_hlsl32_ex = 4453, + fastlink = 4455, + inlinees = 4456, + end = 6, + inlinesite_end = 4430, + proc_id_end = 4431, + thunk32 = 4354, + trampoline = 4396, + section = 4406, + coffgroup = 4407, + @"export" = 4408, + lproc32 = 4367, + gproc32 = 4368, + lproc32_id = 4422, + gproc32_id = 4423, + lproc32_dpc = 4437, + lproc32_dpc_id = 4438, + register = 4358, + pub32 = 4366, + procref = 4389, + lprocref = 4391, + envblock = 4413, + inlinesite = 4429, + local = 4414, + defrange = 4415, + defrange_subfield = 4416, + defrange_register = 4417, + defrange_framepointer_rel = 4418, + defrange_subfield_register = 4419, + defrange_framepointer_rel_full_scope = 4420, + defrange_register_rel = 4421, + block32 = 4355, + label32 = 4357, + objname = 4353, + compile2 = 4374, + compile3 = 4412, + frameproc = 4114, + callsiteinfo = 4409, + filestatic = 4435, + heapallocsite = 4446, + framecookie = 4410, + callees = 4442, + callers = 4443, + udt = 4360, + coboludt = 4361, + buildinfo = 4428, + bprel32 = 4363, + regrel32 = 4369, + constant = 4359, + manconstant = 4397, + ldata32 = 4364, + gdata32 = 4365, + lmandata = 4380, + gmandata = 4381, + lthread32 = 4370, + gthread32 = 4371, }; pub const TypeIndex = u32; @@ -320,28 +320,28 @@ pub const TypeIndex = u32; // we should define RecordPrefix as part of the ProcSym structure. // This might be important when we start generating PDB in self-hosted with our own PE linker. pub const ProcSym = extern struct { - Parent: u32, - End: u32, - Next: u32, - CodeSize: u32, - DbgStart: u32, - DbgEnd: u32, - FunctionType: TypeIndex, - CodeOffset: u32, - Segment: u16, - Flags: ProcSymFlags, - Name: [1]u8, // null-terminated + parent: u32, + end: u32, + next: u32, + code_size: u32, + dbg_start: u32, + dbg_end: u32, + function_type: TypeIndex, + code_offset: u32, + segment: u16, + flags: ProcSymFlags, + name: [1]u8, // null-terminated }; pub const ProcSymFlags = packed struct { - HasFP: bool, - HasIRET: bool, - HasFRET: bool, - IsNoReturn: bool, - IsUnreachable: bool, - HasCustomCallingConv: bool, - IsNoInline: bool, - HasOptimizedDebugInfo: bool, + has_fp: bool, + has_iret: bool, + has_fret: bool, + is_no_return: bool, + is_unreachable: bool, + has_custom_calling_conv: bool, + is_no_inline: bool, + has_optimized_debug_info: bool, }; pub const SectionContrSubstreamVersion = enum(u32) { @@ -351,11 +351,11 @@ pub const SectionContrSubstreamVersion = enum(u32) { }; pub const RecordPrefix = extern struct { - /// Record length, starting from &RecordKind. - RecordLen: u16, + /// Record length, starting from &record_kind. + record_len: u16, /// Record kind enum (SymRecordKind or TypeRecordKind) - RecordKind: SymbolKind, + record_kind: SymbolKind, }; /// The following variable length array appears immediately after the header. @@ -364,19 +364,19 @@ pub const RecordPrefix = extern struct { /// Each `LineBlockFragmentHeader` as specified below. pub const LineFragmentHeader = extern struct { /// Code offset of line contribution. - RelocOffset: u32, + reloc_offset: u32, /// Code segment of line contribution. - RelocSegment: u16, - Flags: LineFlags, + reloc_segment: u16, + flags: LineFlags, /// Code size of this line contribution. - CodeSize: u32, + code_size: u32, }; pub const LineFlags = packed struct { /// CV_LINES_HAVE_COLUMNS - LF_HaveColumns: bool, + have_columns: bool, unused: u15, }; @@ -389,110 +389,109 @@ pub const LineBlockFragmentHeader = extern struct { /// checksums buffer. The checksum entry then /// contains another offset into the string /// table of the actual name. - NameIndex: u32, - NumLines: u32, + name_index: u32, + num_lines: u32, /// code size of block, in bytes - BlockSize: u32, + block_size: u32, }; pub const LineNumberEntry = extern struct { /// Offset to start of code bytes for line number - Offset: u32, - Flags: u32, + offset: u32, + flags: Flags, - /// TODO runtime crash when I make the actual type of Flags this - pub const Flags = packed struct { + pub const Flags = packed struct(u32) { /// Start line number - Start: u24, + start: u24, /// Delta of lines to the end of the expression. Still unclear. // TODO figure out the point of this field. - End: u7, - IsStatement: bool, + end: u7, + is_statement: bool, }; }; pub const ColumnNumberEntry = extern struct { - StartColumn: u16, - EndColumn: u16, + start_column: u16, + end_column: u16, }; /// Checksum bytes follow. pub const FileChecksumEntryHeader = extern struct { /// Byte offset of filename in global string table. - FileNameOffset: u32, + file_name_offset: u32, /// Number of bytes of checksum. - ChecksumSize: u8, + checksum_size: u8, /// FileChecksumKind - ChecksumKind: u8, + checksum_kind: u8, }; pub const DebugSubsectionKind = enum(u32) { - None = 0, - Symbols = 0xf1, - Lines = 0xf2, - StringTable = 0xf3, - FileChecksums = 0xf4, - FrameData = 0xf5, - InlineeLines = 0xf6, - CrossScopeImports = 0xf7, - CrossScopeExports = 0xf8, + none = 0, + symbols = 0xf1, + lines = 0xf2, + string_table = 0xf3, + file_checksums = 0xf4, + frame_data = 0xf5, + inlinee_lines = 0xf6, + cross_scope_imports = 0xf7, + cross_scope_exports = 0xf8, // These appear to relate to .Net assembly info. - ILLines = 0xf9, - FuncMDTokenMap = 0xfa, - TypeMDTokenMap = 0xfb, - MergedAssemblyInput = 0xfc, + il_lines = 0xf9, + func_md_token_map = 0xfa, + type_md_token_map = 0xfb, + merged_assembly_input = 0xfc, - CoffSymbolRVA = 0xfd, + coff_symbol_rva = 0xfd, }; pub const DebugSubsectionHeader = extern struct { /// codeview::DebugSubsectionKind enum - Kind: DebugSubsectionKind, + kind: DebugSubsectionKind, /// number of bytes occupied by this record. - Length: u32, + length: u32, }; pub const StringTableHeader = extern struct { /// PDBStringTableSignature - Signature: u32, + signature: u32, /// 1 or 2 - HashVersion: u32, + hash_version: u32, /// Number of bytes of names buffer. - ByteSize: u32, + byte_size: u32, }; // https://llvm.org/docs/PDB/MsfFile.html#the-superblock pub const SuperBlock = extern struct { /// The LLVM docs list a space between C / C++ but empirically this is not the case. - pub const file_magic = "Microsoft C/C++ MSF 7.00\r\n\x1a\x44\x53\x00\x00\x00"; + pub const expect_magic = "Microsoft C/C++ MSF 7.00\r\n\x1a\x44\x53\x00\x00\x00"; - FileMagic: [file_magic.len]u8, + file_magic: [expect_magic.len]u8, /// The block size of the internal file system. Valid values are 512, 1024, /// 2048, and 4096 bytes. Certain aspects of the MSF file layout vary depending /// on the block sizes. For the purposes of LLVM, we handle only block sizes of /// 4KiB, and all further discussion assumes a block size of 4KiB. - BlockSize: u32, + block_size: u32, /// The index of a block within the file, at which begins a bitfield representing /// the set of all blocks within the file which are “free” (i.e. the data within /// that block is not used). See The Free Block Map for more information. Important: /// FreeBlockMapBlock can only be 1 or 2! - FreeBlockMapBlock: u32, + free_block_map_block: u32, /// The total number of blocks in the file. NumBlocks * BlockSize should equal the /// size of the file on disk. - NumBlocks: u32, + num_blocks: u32, /// The size of the stream directory, in bytes. The stream directory contains /// information about each stream’s size and the set of blocks that it occupies. /// It will be described in more detail later. - NumDirectoryBytes: u32, + num_directory_bytes: u32, - Unknown: u32, + unknown: u32, /// The index of a block within the MSF file. At this block is an array of /// ulittle32_t’s listing the blocks that the stream directory resides on. /// For large MSF files, the stream directory (which describes the block @@ -508,5 +507,5 @@ pub const SuperBlock = extern struct { // This would mean the Stream Directory is bigger than BlockSize / sizeof(u32) // blocks. We're not even close to this with a 1GB pdb file, and LLVM didn't // implement it so we're kind of safe making this assumption for now. - BlockMapAddr: u32, + block_map_addr: u32, }; diff --git a/lib/std/zig/AstGen.zig b/lib/std/zig/AstGen.zig index 309472f9ea69..9c27d1e036bb 100644 --- a/lib/std/zig/AstGen.zig +++ b/lib/std/zig/AstGen.zig @@ -4053,7 +4053,7 @@ fn fnDecl( // The source slice is added towards the *end* of this function. astgen.src_hasher.update(std.mem.asBytes(&astgen.source_column)); - // missing function name already happened in scanDecls() + // missing function name already happened in scanContainer() const fn_name_token = fn_proto.name_token orelse return error.AnalysisFail; // We insert this at the beginning so that its instruction index marks the @@ -5019,7 +5019,7 @@ fn structDeclInner( } }; - const decl_count = try astgen.scanDecls(&namespace, container_decl.ast.members); + const decl_count = try astgen.scanContainer(&namespace, container_decl.ast.members, .@"struct"); const field_count: u32 = @intCast(container_decl.ast.members.len - decl_count); const bits_per_field = 4; @@ -5088,15 +5088,6 @@ fn structDeclInner( astgen.src_hasher.update(tree.getNodeSource(backing_int_node)); } - var sfba = std.heap.stackFallback(256, astgen.arena); - const sfba_allocator = sfba.get(); - - var duplicate_names = std.AutoArrayHashMap(Zir.NullTerminatedString, std.ArrayListUnmanaged(Ast.TokenIndex)).init(sfba_allocator); - try duplicate_names.ensureTotalCapacity(field_count); - - // When there aren't errors, use this to avoid a second iteration. - var any_duplicate = false; - var known_non_opv = false; var known_comptime_only = false; var any_comptime_fields = false; @@ -5117,16 +5108,6 @@ fn structDeclInner( assert(!member.ast.tuple_like); wip_members.appendToField(@intFromEnum(field_name)); - - const gop = try duplicate_names.getOrPut(field_name); - - if (gop.found_existing) { - try gop.value_ptr.append(sfba_allocator, member.ast.main_token); - any_duplicate = true; - } else { - gop.value_ptr.* = .{}; - try gop.value_ptr.append(sfba_allocator, member.ast.main_token); - } } else if (!member.ast.tuple_like) { return astgen.failTok(member.ast.main_token, "tuple field has a name", .{}); } @@ -5211,32 +5192,6 @@ fn structDeclInner( } } - if (any_duplicate) { - var it = duplicate_names.iterator(); - - while (it.next()) |entry| { - const record = entry.value_ptr.*; - if (record.items.len > 1) { - var error_notes = std.ArrayList(u32).init(astgen.arena); - - for (record.items[1..]) |duplicate| { - try error_notes.append(try astgen.errNoteTok(duplicate, "duplicate field here", .{})); - } - - try error_notes.append(try astgen.errNoteNode(node, "struct declared here", .{})); - - try astgen.appendErrorTokNotes( - record.items[0], - "duplicate struct field name", - .{}, - error_notes.items, - ); - } - } - - return error.AnalysisFail; - } - var fields_hash: std.zig.SrcHash = undefined; astgen.src_hasher.final(&fields_hash); @@ -5317,7 +5272,7 @@ fn unionDeclInner( }; defer block_scope.unstack(); - const decl_count = try astgen.scanDecls(&namespace, members); + const decl_count = try astgen.scanContainer(&namespace, members, .@"union"); const field_count: u32 = @intCast(members.len - decl_count); if (layout != .auto and (auto_enum_tok != null or arg_node != 0)) { @@ -5348,15 +5303,6 @@ fn unionDeclInner( astgen.src_hasher.update(astgen.tree.getNodeSource(arg_node)); } - var sfba = std.heap.stackFallback(256, astgen.arena); - const sfba_allocator = sfba.get(); - - var duplicate_names = std.AutoArrayHashMap(Zir.NullTerminatedString, std.ArrayListUnmanaged(Ast.TokenIndex)).init(sfba_allocator); - try duplicate_names.ensureTotalCapacity(field_count); - - // When there aren't errors, use this to avoid a second iteration. - var any_duplicate = false; - for (members) |member_node| { var member = switch (try containerMember(&block_scope, &namespace.base, &wip_members, member_node)) { .decl => continue, @@ -5374,16 +5320,6 @@ fn unionDeclInner( const field_name = try astgen.identAsString(member.ast.main_token); wip_members.appendToField(@intFromEnum(field_name)); - const gop = try duplicate_names.getOrPut(field_name); - - if (gop.found_existing) { - try gop.value_ptr.append(sfba_allocator, member.ast.main_token); - any_duplicate = true; - } else { - gop.value_ptr.* = .{}; - try gop.value_ptr.append(sfba_allocator, member.ast.main_token); - } - const doc_comment_index = try astgen.docCommentAsString(member.firstToken()); wip_members.appendToField(@intFromEnum(doc_comment_index)); @@ -5438,32 +5374,6 @@ fn unionDeclInner( } } - if (any_duplicate) { - var it = duplicate_names.iterator(); - - while (it.next()) |entry| { - const record = entry.value_ptr.*; - if (record.items.len > 1) { - var error_notes = std.ArrayList(u32).init(astgen.arena); - - for (record.items[1..]) |duplicate| { - try error_notes.append(try astgen.errNoteTok(duplicate, "duplicate field here", .{})); - } - - try error_notes.append(try astgen.errNoteNode(node, "union declared here", .{})); - - try astgen.appendErrorTokNotes( - record.items[0], - "duplicate union field name", - .{}, - error_notes.items, - ); - } - } - - return error.AnalysisFail; - } - var fields_hash: std.zig.SrcHash = undefined; astgen.src_hasher.final(&fields_hash); @@ -5666,7 +5576,7 @@ fn containerDecl( }; defer block_scope.unstack(); - _ = try astgen.scanDecls(&namespace, container_decl.ast.members); + _ = try astgen.scanContainer(&namespace, container_decl.ast.members, .@"enum"); namespace.base.tag = .namespace; const arg_inst: Zir.Inst.Ref = if (container_decl.ast.arg != 0) @@ -5687,15 +5597,6 @@ fn containerDecl( } astgen.src_hasher.update(&.{@intFromBool(nonexhaustive)}); - var sfba = std.heap.stackFallback(256, astgen.arena); - const sfba_allocator = sfba.get(); - - var duplicate_names = std.AutoArrayHashMap(Zir.NullTerminatedString, std.ArrayListUnmanaged(Ast.TokenIndex)).init(sfba_allocator); - try duplicate_names.ensureTotalCapacity(counts.total_fields); - - // When there aren't errors, use this to avoid a second iteration. - var any_duplicate = false; - for (container_decl.ast.members) |member_node| { if (member_node == counts.nonexhaustive_node) continue; @@ -5712,16 +5613,6 @@ fn containerDecl( const field_name = try astgen.identAsString(member.ast.main_token); wip_members.appendToField(@intFromEnum(field_name)); - const gop = try duplicate_names.getOrPut(field_name); - - if (gop.found_existing) { - try gop.value_ptr.append(sfba_allocator, member.ast.main_token); - any_duplicate = true; - } else { - gop.value_ptr.* = .{}; - try gop.value_ptr.append(sfba_allocator, member.ast.main_token); - } - const doc_comment_index = try astgen.docCommentAsString(member.firstToken()); wip_members.appendToField(@intFromEnum(doc_comment_index)); @@ -5748,32 +5639,6 @@ fn containerDecl( } } - if (any_duplicate) { - var it = duplicate_names.iterator(); - - while (it.next()) |entry| { - const record = entry.value_ptr.*; - if (record.items.len > 1) { - var error_notes = std.ArrayList(u32).init(astgen.arena); - - for (record.items[1..]) |duplicate| { - try error_notes.append(try astgen.errNoteTok(duplicate, "duplicate field here", .{})); - } - - try error_notes.append(try astgen.errNoteNode(node, "enum declared here", .{})); - - try astgen.appendErrorTokNotes( - record.items[0], - "duplicate enum field name", - .{}, - error_notes.items, - ); - } - } - - return error.AnalysisFail; - } - if (!block_scope.isEmpty()) { _ = try block_scope.addBreak(.break_inline, decl_inst, .void_value); } @@ -5833,7 +5698,7 @@ fn containerDecl( }; defer block_scope.unstack(); - const decl_count = try astgen.scanDecls(&namespace, container_decl.ast.members); + const decl_count = try astgen.scanContainer(&namespace, container_decl.ast.members, .@"opaque"); var wip_members = try WipMembers.init(gpa, &astgen.scratch, decl_count, 0, 0, 0); defer wip_members.deinit(); @@ -13594,31 +13459,67 @@ fn advanceSourceCursor(astgen: *AstGen, end: usize) void { astgen.source_column = column; } -fn scanDecls(astgen: *AstGen, namespace: *Scope.Namespace, members: []const Ast.Node.Index) !u32 { +/// Detects name conflicts for decls and fields, and populates `namespace.decls` with all named declarations. +/// Returns the number of declarations in the namespace, including unnamed declarations (e.g. `comptime` decls). +fn scanContainer( + astgen: *AstGen, + namespace: *Scope.Namespace, + members: []const Ast.Node.Index, + container_kind: enum { @"struct", @"union", @"enum", @"opaque" }, +) !u32 { const gpa = astgen.gpa; const tree = astgen.tree; const node_tags = tree.nodes.items(.tag); const main_tokens = tree.nodes.items(.main_token); const token_tags = tree.tokens.items(.tag); - // We don't have shadowing for test names, so we just track those for duplicate reporting locally. - var named_tests: std.AutoHashMapUnmanaged(Zir.NullTerminatedString, Ast.Node.Index) = .{}; - var decltests: std.AutoHashMapUnmanaged(Zir.NullTerminatedString, Ast.Node.Index) = .{}; + // This type forms a linked list of source tokens declaring the same name. + const NameEntry = struct { + tok: Ast.TokenIndex, + /// Using a linked list here simplifies memory management, and is acceptable since + ///ewntries are only allocated in error situations. The entries are allocated into the + /// AstGen arena. + next: ?*@This(), + }; + + // The maps below are allocated into this SFBA to avoid using the GPA for small namespaces. + var sfba_state = std.heap.stackFallback(512, astgen.gpa); + const sfba = sfba_state.get(); + + var names: std.AutoArrayHashMapUnmanaged(Zir.NullTerminatedString, NameEntry) = .{}; + var test_names: std.AutoArrayHashMapUnmanaged(Zir.NullTerminatedString, NameEntry) = .{}; + var decltest_names: std.AutoArrayHashMapUnmanaged(Zir.NullTerminatedString, NameEntry) = .{}; defer { - named_tests.deinit(gpa); - decltests.deinit(gpa); + names.deinit(sfba); + test_names.deinit(sfba); + decltest_names.deinit(sfba); } + var any_duplicates = false; var decl_count: u32 = 0; for (members) |member_node| { - const name_token = switch (node_tags[member_node]) { + const Kind = enum { decl, field }; + const kind: Kind, const name_token = switch (node_tags[member_node]) { + .container_field_init, + .container_field_align, + .container_field, + => blk: { + var full = tree.fullContainerField(member_node).?; + switch (container_kind) { + .@"struct", .@"opaque" => {}, + .@"union", .@"enum" => full.convertToNonTupleLike(astgen.tree.nodes), + } + if (full.ast.tuple_like) continue; + break :blk .{ .field, full.ast.main_token }; + }, + .global_var_decl, .local_var_decl, .simple_var_decl, .aligned_var_decl, => blk: { decl_count += 1; - break :blk main_tokens[member_node] + 1; + break :blk .{ .decl, main_tokens[member_node] + 1 }; }, .fn_proto_simple, @@ -13630,12 +13531,10 @@ fn scanDecls(astgen: *AstGen, namespace: *Scope.Namespace, members: []const Ast. decl_count += 1; const ident = main_tokens[member_node] + 1; if (token_tags[ident] != .identifier) { - switch (astgen.failNode(member_node, "missing function name", .{})) { - error.AnalysisFail => continue, - error.OutOfMemory => return error.OutOfMemory, - } + try astgen.appendErrorNode(member_node, "missing function name", .{}); + continue; } - break :blk ident; + break :blk .{ .decl, ident }; }, .@"comptime", .@"usingnamespace" => { @@ -13648,70 +13547,87 @@ fn scanDecls(astgen: *AstGen, namespace: *Scope.Namespace, members: []const Ast. // We don't want shadowing detection here, and test names work a bit differently, so // we must do the redeclaration detection ourselves. const test_name_token = main_tokens[member_node] + 1; + const new_ent: NameEntry = .{ + .tok = test_name_token, + .next = null, + }; switch (token_tags[test_name_token]) { else => {}, // unnamed test .string_literal => { const name = try astgen.strLitAsString(test_name_token); - const gop = try named_tests.getOrPut(gpa, name.index); + const gop = try test_names.getOrPut(sfba, name.index); if (gop.found_existing) { - const name_slice = astgen.string_bytes.items[@intFromEnum(name.index)..][0..name.len]; - const name_duped = try gpa.dupe(u8, name_slice); - defer gpa.free(name_duped); - try astgen.appendErrorNodeNotes(member_node, "duplicate test name '{s}'", .{name_duped}, &.{ - try astgen.errNoteNode(gop.value_ptr.*, "other test here", .{}), - }); + var e = gop.value_ptr; + while (e.next) |n| e = n; + e.next = try astgen.arena.create(NameEntry); + e.next.?.* = new_ent; + any_duplicates = true; } else { - gop.value_ptr.* = member_node; + gop.value_ptr.* = new_ent; } }, .identifier => { const name = try astgen.identAsString(test_name_token); - const gop = try decltests.getOrPut(gpa, name); + const gop = try decltest_names.getOrPut(sfba, name); if (gop.found_existing) { - const name_slice = mem.span(astgen.nullTerminatedString(name)); - const name_duped = try gpa.dupe(u8, name_slice); - defer gpa.free(name_duped); - try astgen.appendErrorNodeNotes(member_node, "duplicate decltest '{s}'", .{name_duped}, &.{ - try astgen.errNoteNode(gop.value_ptr.*, "other decltest here", .{}), - }); + var e = gop.value_ptr; + while (e.next) |n| e = n; + e.next = try astgen.arena.create(NameEntry); + e.next.?.* = new_ent; + any_duplicates = true; } else { - gop.value_ptr.* = member_node; + gop.value_ptr.* = new_ent; } }, } continue; }, - else => continue, + else => unreachable, }; + const name_str_index = try astgen.identAsString(name_token); + + if (kind == .decl) { + // Put the name straight into `decls`, even if there are compile errors. + // This avoids incorrect "undeclared identifier" errors later on. + try namespace.decls.put(gpa, name_str_index, member_node); + } + + { + const gop = try names.getOrPut(sfba, name_str_index); + const new_ent: NameEntry = .{ + .tok = name_token, + .next = null, + }; + if (gop.found_existing) { + var e = gop.value_ptr; + while (e.next) |n| e = n; + e.next = try astgen.arena.create(NameEntry); + e.next.?.* = new_ent; + any_duplicates = true; + continue; + } else { + gop.value_ptr.* = new_ent; + } + } + + // For fields, we only needed the duplicate check! Decls have some more checks to do, though. + switch (kind) { + .decl => {}, + .field => continue, + } + const token_bytes = astgen.tree.tokenSlice(name_token); if (token_bytes[0] != '@' and isPrimitive(token_bytes)) { - switch (astgen.failTokNotes(name_token, "name shadows primitive '{s}'", .{ + try astgen.appendErrorTokNotes(name_token, "name shadows primitive '{s}'", .{ token_bytes, - }, &[_]u32{ + }, &.{ try astgen.errNoteTok(name_token, "consider using @\"{s}\" to disambiguate", .{ token_bytes, }), - })) { - error.AnalysisFail => continue, - error.OutOfMemory => return error.OutOfMemory, - } - } - - const name_str_index = try astgen.identAsString(name_token); - const gop = try namespace.decls.getOrPut(gpa, name_str_index); - if (gop.found_existing) { - const name = try gpa.dupe(u8, mem.span(astgen.nullTerminatedString(name_str_index))); - defer gpa.free(name); - switch (astgen.failNodeNotes(member_node, "redeclaration of '{s}'", .{ - name, - }, &[_]u32{ - try astgen.errNoteNode(gop.value_ptr.*, "other declaration here", .{}), - })) { - error.AnalysisFail => continue, - error.OutOfMemory => return error.OutOfMemory, - } + }); + continue; } var s = namespace.parent; @@ -13719,30 +13635,32 @@ fn scanDecls(astgen: *AstGen, namespace: *Scope.Namespace, members: []const Ast. .local_val => { const local_val = s.cast(Scope.LocalVal).?; if (local_val.name == name_str_index) { - return astgen.failTokNotes(name_token, "declaration '{s}' shadows {s} from outer scope", .{ + try astgen.appendErrorTokNotes(name_token, "declaration '{s}' shadows {s} from outer scope", .{ token_bytes, @tagName(local_val.id_cat), - }, &[_]u32{ + }, &.{ try astgen.errNoteTok( local_val.token_src, "previous declaration here", .{}, ), }); + break; } s = local_val.parent; }, .local_ptr => { const local_ptr = s.cast(Scope.LocalPtr).?; if (local_ptr.name == name_str_index) { - return astgen.failTokNotes(name_token, "declaration '{s}' shadows {s} from outer scope", .{ + try astgen.appendErrorTokNotes(name_token, "declaration '{s}' shadows {s} from outer scope", .{ token_bytes, @tagName(local_ptr.id_cat), - }, &[_]u32{ + }, &.{ try astgen.errNoteTok( local_ptr.token_src, "previous declaration here", .{}, ), }); + break; } s = local_ptr.parent; }, @@ -13751,8 +13669,46 @@ fn scanDecls(astgen: *AstGen, namespace: *Scope.Namespace, members: []const Ast. .defer_normal, .defer_error => s = s.cast(Scope.Defer).?.parent, .top => break, }; - gop.value_ptr.* = member_node; } + + if (!any_duplicates) return decl_count; + + for (names.keys(), names.values()) |name, first| { + if (first.next == null) continue; + var notes: std.ArrayListUnmanaged(u32) = .{}; + var prev: NameEntry = first; + while (prev.next) |cur| : (prev = cur.*) { + try notes.append(astgen.arena, try astgen.errNoteTok(cur.tok, "duplicate name here", .{})); + } + try notes.append(astgen.arena, try astgen.errNoteNode(namespace.node, "{s} declared here", .{@tagName(container_kind)})); + const name_duped = try astgen.arena.dupe(u8, mem.span(astgen.nullTerminatedString(name))); + try astgen.appendErrorTokNotes(first.tok, "duplicate {s} member name '{s}'", .{ @tagName(container_kind), name_duped }, notes.items); + } + + for (test_names.keys(), test_names.values()) |name, first| { + if (first.next == null) continue; + var notes: std.ArrayListUnmanaged(u32) = .{}; + var prev: NameEntry = first; + while (prev.next) |cur| : (prev = cur.*) { + try notes.append(astgen.arena, try astgen.errNoteTok(cur.tok, "duplicate test here", .{})); + } + try notes.append(astgen.arena, try astgen.errNoteNode(namespace.node, "{s} declared here", .{@tagName(container_kind)})); + const name_duped = try astgen.arena.dupe(u8, mem.span(astgen.nullTerminatedString(name))); + try astgen.appendErrorTokNotes(first.tok, "duplicate test name '{s}'", .{name_duped}, notes.items); + } + + for (decltest_names.keys(), decltest_names.values()) |name, first| { + if (first.next == null) continue; + var notes: std.ArrayListUnmanaged(u32) = .{}; + var prev: NameEntry = first; + while (prev.next) |cur| : (prev = cur.*) { + try notes.append(astgen.arena, try astgen.errNoteTok(cur.tok, "duplicate decltest here", .{})); + } + try notes.append(astgen.arena, try astgen.errNoteNode(namespace.node, "{s} declared here", .{@tagName(container_kind)})); + const name_duped = try astgen.arena.dupe(u8, mem.span(astgen.nullTerminatedString(name))); + try astgen.appendErrorTokNotes(first.tok, "duplicate decltest '{s}'", .{name_duped}, notes.items); + } + return decl_count; } diff --git a/src/arch/aarch64/bits.zig b/src/arch/aarch64/bits.zig index 01699b79292d..9c4227a712cd 100644 --- a/src/arch/aarch64/bits.zig +++ b/src/arch/aarch64/bits.zig @@ -1069,7 +1069,7 @@ pub const Instruction = union(enum) { }; } - fn bitfield( + fn initBitfield( opc: u2, n: u1, rd: Register, @@ -1579,7 +1579,7 @@ pub const Instruction = union(enum) { 64 => 0b1, else => unreachable, // unexpected register size }; - return bitfield(0b00, n, rd, rn, immr, imms); + return initBitfield(0b00, n, rd, rn, immr, imms); } pub fn bfm(rd: Register, rn: Register, immr: u6, imms: u6) Instruction { @@ -1588,7 +1588,7 @@ pub const Instruction = union(enum) { 64 => 0b1, else => unreachable, // unexpected register size }; - return bitfield(0b01, n, rd, rn, immr, imms); + return initBitfield(0b01, n, rd, rn, immr, imms); } pub fn ubfm(rd: Register, rn: Register, immr: u6, imms: u6) Instruction { @@ -1597,7 +1597,7 @@ pub const Instruction = union(enum) { 64 => 0b1, else => unreachable, // unexpected register size }; - return bitfield(0b10, n, rd, rn, immr, imms); + return initBitfield(0b10, n, rd, rn, immr, imms); } pub fn asrImmediate(rd: Register, rn: Register, shift: u6) Instruction { diff --git a/src/arch/arm/bits.zig b/src/arch/arm/bits.zig index 37386b9c629a..0388ce8c631c 100644 --- a/src/arch/arm/bits.zig +++ b/src/arch/arm/bits.zig @@ -662,7 +662,7 @@ pub const Instruction = union(enum) { }; } - fn multiply( + fn initMultiply( cond: Condition, set_cond: u1, rd: Register, @@ -864,7 +864,7 @@ pub const Instruction = union(enum) { }; } - fn branch(cond: Condition, offset: i26, link: u1) Instruction { + fn initBranch(cond: Condition, offset: i26, link: u1) Instruction { return Instruction{ .branch = .{ .cond = @intFromEnum(cond), @@ -900,7 +900,7 @@ pub const Instruction = union(enum) { }; } - fn breakpoint(imm: u16) Instruction { + fn initBreakpoint(imm: u16) Instruction { return Instruction{ .breakpoint = .{ .imm12 = @as(u12, @truncate(imm >> 4)), @@ -1087,19 +1087,19 @@ pub const Instruction = union(enum) { // Multiply pub fn mul(cond: Condition, rd: Register, rn: Register, rm: Register) Instruction { - return multiply(cond, 0, rd, rn, rm, null); + return initMultiply(cond, 0, rd, rn, rm, null); } pub fn muls(cond: Condition, rd: Register, rn: Register, rm: Register) Instruction { - return multiply(cond, 1, rd, rn, rm, null); + return initMultiply(cond, 1, rd, rn, rm, null); } pub fn mla(cond: Condition, rd: Register, rn: Register, rm: Register, ra: Register) Instruction { - return multiply(cond, 0, rd, rn, rm, ra); + return initMultiply(cond, 0, rd, rn, rm, ra); } pub fn mlas(cond: Condition, rd: Register, rn: Register, rm: Register, ra: Register) Instruction { - return multiply(cond, 1, rd, rn, rm, ra); + return initMultiply(cond, 1, rd, rn, rm, ra); } // Multiply long @@ -1261,11 +1261,11 @@ pub const Instruction = union(enum) { // Branch pub fn b(cond: Condition, offset: i26) Instruction { - return branch(cond, offset, 0); + return initBranch(cond, offset, 0); } pub fn bl(cond: Condition, offset: i26) Instruction { - return branch(cond, offset, 1); + return initBranch(cond, offset, 1); } // Branch and exchange @@ -1289,7 +1289,7 @@ pub const Instruction = union(enum) { // Breakpoint pub fn bkpt(imm: u16) Instruction { - return breakpoint(imm); + return initBreakpoint(imm); } // Aliases diff --git a/src/arch/x86_64/CodeGen.zig b/src/arch/x86_64/CodeGen.zig index adde0b461f1e..1f13c8ae7d66 100644 --- a/src/arch/x86_64/CodeGen.zig +++ b/src/arch/x86_64/CodeGen.zig @@ -15563,7 +15563,7 @@ fn genLazySymbolRef( .mov => try self.asmRegisterMemory( .{ ._, tag }, reg.to64(), - Memory.sib(.qword, .{ .base = .{ .reg = reg.to64() } }), + Memory.initSib(.qword, .{ .base = .{ .reg = reg.to64() } }), ), else => unreachable, } diff --git a/src/arch/x86_64/Disassembler.zig b/src/arch/x86_64/Disassembler.zig index d21cec28ab20..f6eeedba2c06 100644 --- a/src/arch/x86_64/Disassembler.zig +++ b/src/arch/x86_64/Disassembler.zig @@ -95,7 +95,7 @@ pub fn next(dis: *Disassembler) Error!?Instruction { if (modrm.rip()) { return inst(act_enc, .{ - .op1 = .{ .mem = Memory.rip(Memory.PtrSize.fromBitSize(act_enc.data.ops[0].memBitSize()), disp) }, + .op1 = .{ .mem = Memory.initRip(Memory.PtrSize.fromBitSize(act_enc.data.ops[0].memBitSize()), disp) }, .op2 = op2, }); } @@ -106,7 +106,7 @@ pub fn next(dis: *Disassembler) Error!?Instruction { else parseGpRegister(modrm.op2, prefixes.rex.b, prefixes.rex, 64); return inst(act_enc, .{ - .op1 = .{ .mem = Memory.sib(Memory.PtrSize.fromBitSize(act_enc.data.ops[0].memBitSize()), .{ + .op1 = .{ .mem = Memory.initSib(Memory.PtrSize.fromBitSize(act_enc.data.ops[0].memBitSize()), .{ .base = if (base) |base_reg| .{ .reg = base_reg } else .none, .scale_index = scale_index, .disp = disp, @@ -119,14 +119,14 @@ pub fn next(dis: *Disassembler) Error!?Instruction { const offset = try dis.parseOffset(); return inst(enc, .{ .op1 = .{ .reg = Register.rax.toBitSize(enc.data.ops[0].regBitSize()) }, - .op2 = .{ .mem = Memory.moffs(seg, offset) }, + .op2 = .{ .mem = Memory.initMoffs(seg, offset) }, }); }, .td => { const seg = segmentRegister(prefixes.legacy); const offset = try dis.parseOffset(); return inst(enc, .{ - .op1 = .{ .mem = Memory.moffs(seg, offset) }, + .op1 = .{ .mem = Memory.initMoffs(seg, offset) }, .op2 = .{ .reg = Register.rax.toBitSize(enc.data.ops[1].regBitSize()) }, }); }, @@ -153,7 +153,7 @@ pub fn next(dis: *Disassembler) Error!?Instruction { if (modrm.rip()) { return inst(enc, .{ - .op1 = .{ .mem = Memory.rip(Memory.PtrSize.fromBitSize(dst_bit_size), disp) }, + .op1 = .{ .mem = Memory.initRip(Memory.PtrSize.fromBitSize(dst_bit_size), disp) }, .op2 = .{ .reg = parseGpRegister(modrm.op1, prefixes.rex.r, prefixes.rex, src_bit_size) }, .op3 = op3, }); @@ -165,7 +165,7 @@ pub fn next(dis: *Disassembler) Error!?Instruction { else parseGpRegister(modrm.op2, prefixes.rex.b, prefixes.rex, 64); return inst(enc, .{ - .op1 = .{ .mem = Memory.sib(Memory.PtrSize.fromBitSize(dst_bit_size), .{ + .op1 = .{ .mem = Memory.initSib(Memory.PtrSize.fromBitSize(dst_bit_size), .{ .base = if (base) |base_reg| .{ .reg = base_reg } else .none, .scale_index = scale_index, .disp = disp, @@ -203,7 +203,7 @@ pub fn next(dis: *Disassembler) Error!?Instruction { if (modrm.rip()) { return inst(enc, .{ .op1 = .{ .reg = parseGpRegister(modrm.op1, prefixes.rex.r, prefixes.rex, dst_bit_size) }, - .op2 = .{ .mem = Memory.rip(Memory.PtrSize.fromBitSize(src_bit_size), disp) }, + .op2 = .{ .mem = Memory.initRip(Memory.PtrSize.fromBitSize(src_bit_size), disp) }, .op3 = op3, }); } @@ -215,7 +215,7 @@ pub fn next(dis: *Disassembler) Error!?Instruction { parseGpRegister(modrm.op2, prefixes.rex.b, prefixes.rex, 64); return inst(enc, .{ .op1 = .{ .reg = parseGpRegister(modrm.op1, prefixes.rex.r, prefixes.rex, dst_bit_size) }, - .op2 = .{ .mem = Memory.sib(Memory.PtrSize.fromBitSize(src_bit_size), .{ + .op2 = .{ .mem = Memory.initSib(Memory.PtrSize.fromBitSize(src_bit_size), .{ .base = if (base) |base_reg| .{ .reg = base_reg } else .none, .scale_index = scale_index, .disp = disp, diff --git a/src/arch/x86_64/Lower.zig b/src/arch/x86_64/Lower.zig index 76e068ece95b..174e9b069cbf 100644 --- a/src/arch/x86_64/Lower.zig +++ b/src/arch/x86_64/Lower.zig @@ -200,13 +200,13 @@ pub fn lowerMir(lower: *Lower, index: Mir.Inst.Index) Error!struct { }); try lower.emit(.none, .lea, &.{ .{ .reg = inst.data.ri.r1 }, - .{ .mem = Memory.sib(.qword, .{ + .{ .mem = Memory.initSib(.qword, .{ .base = .{ .reg = inst.data.ri.r1 }, .disp = -page_size, }) }, }); try lower.emit(.none, .@"test", &.{ - .{ .mem = Memory.sib(.dword, .{ + .{ .mem = Memory.initSib(.dword, .{ .base = .{ .reg = inst.data.ri.r1 }, }) }, .{ .reg = inst.data.ri.r1.to32() }, @@ -220,7 +220,7 @@ pub fn lowerMir(lower: *Lower, index: Mir.Inst.Index) Error!struct { var offset = page_size; while (offset < @as(i32, @bitCast(inst.data.ri.i))) : (offset += page_size) { try lower.emit(.none, .@"test", &.{ - .{ .mem = Memory.sib(.dword, .{ + .{ .mem = Memory.initSib(.dword, .{ .base = .{ .reg = inst.data.ri.r1 }, .disp = -offset, }) }, @@ -246,7 +246,7 @@ pub fn lowerMir(lower: *Lower, index: Mir.Inst.Index) Error!struct { }, .pseudo_probe_adjust_loop_rr => { try lower.emit(.none, .@"test", &.{ - .{ .mem = Memory.sib(.dword, .{ + .{ .mem = Memory.initSib(.dword, .{ .base = .{ .reg = inst.data.rr.r1 }, .scale_index = .{ .scale = 1, .index = inst.data.rr.r2 }, .disp = -page_size, @@ -417,7 +417,7 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand) lower.result_insts[lower.result_insts_len] = try Instruction.new(.none, .lea, &[_]Operand{ .{ .reg = .rdi }, - .{ .mem = Memory.rip(mem_op.sib.ptr_size, 0) }, + .{ .mem = Memory.initRip(mem_op.sib.ptr_size, 0) }, }); lower.result_insts_len += 1; _ = lower.reloc(.{ @@ -430,7 +430,7 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand) lower.result_insts_len += 1; _ = lower.reloc(.{ .linker_dtpoff = sym_index }, 0); emit_mnemonic = .lea; - break :op .{ .mem = Memory.sib(mem_op.sib.ptr_size, .{ + break :op .{ .mem = Memory.initSib(mem_op.sib.ptr_size, .{ .base = .{ .reg = .rax }, .disp = std.math.minInt(i32), }) }; @@ -439,12 +439,12 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand) lower.result_insts[lower.result_insts_len] = try Instruction.new(.none, .mov, &[_]Operand{ .{ .reg = .rax }, - .{ .mem = Memory.sib(.qword, .{ .base = .{ .reg = .fs } }) }, + .{ .mem = Memory.initSib(.qword, .{ .base = .{ .reg = .fs } }) }, }); lower.result_insts_len += 1; _ = lower.reloc(.{ .linker_reloc = sym_index }, 0); emit_mnemonic = .lea; - break :op .{ .mem = Memory.sib(mem_op.sib.ptr_size, .{ + break :op .{ .mem = Memory.initSib(mem_op.sib.ptr_size, .{ .base = .{ .reg = .rax }, .disp = std.math.minInt(i32), }) }; @@ -455,7 +455,7 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand) if (lower.pic) switch (mnemonic) { .lea => { if (elf_sym.flags.is_extern_ptr) emit_mnemonic = .mov; - break :op .{ .mem = Memory.rip(mem_op.sib.ptr_size, 0) }; + break :op .{ .mem = Memory.initRip(mem_op.sib.ptr_size, 0) }; }, .mov => { if (elf_sym.flags.is_extern_ptr) { @@ -463,25 +463,25 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand) lower.result_insts[lower.result_insts_len] = try Instruction.new(.none, .mov, &[_]Operand{ .{ .reg = reg.to64() }, - .{ .mem = Memory.rip(.qword, 0) }, + .{ .mem = Memory.initRip(.qword, 0) }, }); lower.result_insts_len += 1; - break :op .{ .mem = Memory.sib(mem_op.sib.ptr_size, .{ .base = .{ + break :op .{ .mem = Memory.initSib(mem_op.sib.ptr_size, .{ .base = .{ .reg = reg.to64(), } }) }; } - break :op .{ .mem = Memory.rip(mem_op.sib.ptr_size, 0) }; + break :op .{ .mem = Memory.initRip(mem_op.sib.ptr_size, 0) }; }, else => unreachable, } else switch (mnemonic) { - .call => break :op .{ .mem = Memory.sib(mem_op.sib.ptr_size, .{ + .call => break :op .{ .mem = Memory.initSib(mem_op.sib.ptr_size, .{ .base = .{ .reg = .ds }, }) }, .lea => { emit_mnemonic = .mov; break :op .{ .imm = Immediate.s(0) }; }, - .mov => break :op .{ .mem = Memory.sib(mem_op.sib.ptr_size, .{ + .mov => break :op .{ .mem = Memory.initSib(mem_op.sib.ptr_size, .{ .base = .{ .reg = .ds }, }) }, else => unreachable, @@ -495,12 +495,12 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand) lower.result_insts[lower.result_insts_len] = try Instruction.new(.none, .mov, &[_]Operand{ .{ .reg = .rdi }, - .{ .mem = Memory.rip(mem_op.sib.ptr_size, 0) }, + .{ .mem = Memory.initRip(mem_op.sib.ptr_size, 0) }, }); lower.result_insts_len += 1; lower.result_insts[lower.result_insts_len] = try Instruction.new(.none, .call, &[_]Operand{ - .{ .mem = Memory.sib(.qword, .{ .base = .{ .reg = .rdi } }) }, + .{ .mem = Memory.initSib(.qword, .{ .base = .{ .reg = .rdi } }) }, }); lower.result_insts_len += 1; emit_mnemonic = .mov; @@ -511,7 +511,7 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand) break :op switch (mnemonic) { .lea => { if (macho_sym.flags.is_extern_ptr) emit_mnemonic = .mov; - break :op .{ .mem = Memory.rip(mem_op.sib.ptr_size, 0) }; + break :op .{ .mem = Memory.initRip(mem_op.sib.ptr_size, 0) }; }, .mov => { if (macho_sym.flags.is_extern_ptr) { @@ -519,14 +519,14 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand) lower.result_insts[lower.result_insts_len] = try Instruction.new(.none, .mov, &[_]Operand{ .{ .reg = reg.to64() }, - .{ .mem = Memory.rip(.qword, 0) }, + .{ .mem = Memory.initRip(.qword, 0) }, }); lower.result_insts_len += 1; - break :op .{ .mem = Memory.sib(mem_op.sib.ptr_size, .{ .base = .{ + break :op .{ .mem = Memory.initSib(mem_op.sib.ptr_size, .{ .base = .{ .reg = reg.to64(), } }) }; } - break :op .{ .mem = Memory.rip(mem_op.sib.ptr_size, 0) }; + break :op .{ .mem = Memory.initRip(mem_op.sib.ptr_size, 0) }; }, else => unreachable, }; @@ -701,7 +701,7 @@ fn generic(lower: *Lower, inst: Mir.Inst) Error!void { }, extra.off); break :ops &.{ .{ .reg = reg }, - .{ .mem = Memory.rip(Memory.PtrSize.fromBitSize(reg.bitSize()), 0) }, + .{ .mem = Memory.initRip(Memory.PtrSize.fromBitSize(reg.bitSize()), 0) }, }; }, else => return lower.fail("TODO lower {s} {s}", .{ @tagName(inst.tag), @tagName(inst.ops) }), diff --git a/src/arch/x86_64/Mir.zig b/src/arch/x86_64/Mir.zig index 14de8ee69ce0..ff7c78e86ec0 100644 --- a/src/arch/x86_64/Mir.zig +++ b/src/arch/x86_64/Mir.zig @@ -1234,9 +1234,9 @@ pub const Memory = struct { .rm => { if (mem.info.base == .reg and @as(Register, @enumFromInt(mem.base)) == .rip) { assert(mem.info.index == .none and mem.info.scale == .@"1"); - return encoder.Instruction.Memory.rip(mem.info.size, @bitCast(mem.off)); + return encoder.Instruction.Memory.initRip(mem.info.size, @bitCast(mem.off)); } - return encoder.Instruction.Memory.sib(mem.info.size, .{ + return encoder.Instruction.Memory.initSib(mem.info.size, .{ .disp = @bitCast(mem.off), .base = switch (mem.info.base) { .none => .none, @@ -1258,7 +1258,7 @@ pub const Memory = struct { }, .off => { assert(mem.info.base == .reg); - return encoder.Instruction.Memory.moffs( + return encoder.Instruction.Memory.initMoffs( @enumFromInt(mem.base), @as(u64, mem.extra) << 32 | mem.off, ); diff --git a/src/arch/x86_64/encoder.zig b/src/arch/x86_64/encoder.zig index 0dc1dbb7c979..e3c93ce11478 100644 --- a/src/arch/x86_64/encoder.zig +++ b/src/arch/x86_64/encoder.zig @@ -110,12 +110,12 @@ pub const Instruction = struct { offset: u64, }; - pub fn moffs(reg: Register, offset: u64) Memory { + pub fn initMoffs(reg: Register, offset: u64) Memory { assert(reg.class() == .segment); return .{ .moffs = .{ .seg = reg, .offset = offset } }; } - pub fn sib(ptr_size: PtrSize, args: struct { + pub fn initSib(ptr_size: PtrSize, args: struct { disp: i32 = 0, base: Base = .none, scale_index: ?ScaleIndex = null, @@ -129,7 +129,7 @@ pub const Instruction = struct { } }; } - pub fn rip(ptr_size: PtrSize, displacement: i32) Memory { + pub fn initRip(ptr_size: PtrSize, displacement: i32) Memory { return .{ .rip = .{ .ptr_size = ptr_size, .disp = displacement } }; } @@ -1266,7 +1266,7 @@ test "lower MI encoding" { try expectEqualHexStrings("\x49\xC7\xC4\x00\x10\x00\x00", enc.code(), "mov r12, 0x1000"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.sib(.byte, .{ .base = .{ .reg = .r12 } }) }, + .{ .mem = Instruction.Memory.initSib(.byte, .{ .base = .{ .reg = .r12 } }) }, .{ .imm = Instruction.Immediate.u(0x10) }, }); try expectEqualHexStrings("\x41\xC6\x04\x24\x10", enc.code(), "mov BYTE PTR [r12], 0x10"); @@ -1290,13 +1290,13 @@ test "lower MI encoding" { try expectEqualHexStrings("\x48\xc7\xc0\x10\x00\x00\x00", enc.code(), "mov rax, 0x10"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.sib(.dword, .{ .base = .{ .reg = .r11 } }) }, + .{ .mem = Instruction.Memory.initSib(.dword, .{ .base = .{ .reg = .r11 } }) }, .{ .imm = Instruction.Immediate.u(0x10) }, }); try expectEqualHexStrings("\x41\xc7\x03\x10\x00\x00\x00", enc.code(), "mov DWORD PTR [r11], 0x10"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.rip(.qword, 0x10) }, + .{ .mem = Instruction.Memory.initRip(.qword, 0x10) }, .{ .imm = Instruction.Immediate.u(0x10) }, }); try expectEqualHexStrings( @@ -1306,25 +1306,25 @@ test "lower MI encoding" { ); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.sib(.qword, .{ .base = .{ .reg = .rbp }, .disp = -8 }) }, + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .rbp }, .disp = -8 }) }, .{ .imm = Instruction.Immediate.u(0x10) }, }); try expectEqualHexStrings("\x48\xc7\x45\xf8\x10\x00\x00\x00", enc.code(), "mov QWORD PTR [rbp - 8], 0x10"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.sib(.word, .{ .base = .{ .reg = .rbp }, .disp = -2 }) }, + .{ .mem = Instruction.Memory.initSib(.word, .{ .base = .{ .reg = .rbp }, .disp = -2 }) }, .{ .imm = Instruction.Immediate.s(-16) }, }); try expectEqualHexStrings("\x66\xC7\x45\xFE\xF0\xFF", enc.code(), "mov WORD PTR [rbp - 2], -16"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.sib(.byte, .{ .base = .{ .reg = .rbp }, .disp = -1 }) }, + .{ .mem = Instruction.Memory.initSib(.byte, .{ .base = .{ .reg = .rbp }, .disp = -1 }) }, .{ .imm = Instruction.Immediate.u(0x10) }, }); try expectEqualHexStrings("\xC6\x45\xFF\x10", enc.code(), "mov BYTE PTR [rbp - 1], 0x10"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.sib(.qword, .{ + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .ds }, .disp = 0x10000000, .scale_index = .{ .scale = 2, .index = .rcx }, @@ -1338,13 +1338,13 @@ test "lower MI encoding" { ); try enc.encode(.adc, &.{ - .{ .mem = Instruction.Memory.sib(.byte, .{ .base = .{ .reg = .rbp }, .disp = -0x10 }) }, + .{ .mem = Instruction.Memory.initSib(.byte, .{ .base = .{ .reg = .rbp }, .disp = -0x10 }) }, .{ .imm = Instruction.Immediate.u(0x10) }, }); try expectEqualHexStrings("\x80\x55\xF0\x10", enc.code(), "adc BYTE PTR [rbp - 0x10], 0x10"); try enc.encode(.adc, &.{ - .{ .mem = Instruction.Memory.rip(.qword, 0) }, + .{ .mem = Instruction.Memory.initRip(.qword, 0) }, .{ .imm = Instruction.Immediate.u(0x10) }, }); try expectEqualHexStrings("\x48\x83\x15\x00\x00\x00\x00\x10", enc.code(), "adc QWORD PTR [rip], 0x10"); @@ -1356,7 +1356,7 @@ test "lower MI encoding" { try expectEqualHexStrings("\x48\x83\xD0\x10", enc.code(), "adc rax, 0x10"); try enc.encode(.add, &.{ - .{ .mem = Instruction.Memory.sib(.dword, .{ .base = .{ .reg = .rdx }, .disp = -8 }) }, + .{ .mem = Instruction.Memory.initSib(.dword, .{ .base = .{ .reg = .rdx }, .disp = -8 }) }, .{ .imm = Instruction.Immediate.u(0x10) }, }); try expectEqualHexStrings("\x83\x42\xF8\x10", enc.code(), "add DWORD PTR [rdx - 8], 0x10"); @@ -1368,13 +1368,13 @@ test "lower MI encoding" { try expectEqualHexStrings("\x48\x83\xC0\x10", enc.code(), "add rax, 0x10"); try enc.encode(.add, &.{ - .{ .mem = Instruction.Memory.sib(.qword, .{ .base = .{ .reg = .rbp }, .disp = -0x10 }) }, + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .rbp }, .disp = -0x10 }) }, .{ .imm = Instruction.Immediate.s(-0x10) }, }); try expectEqualHexStrings("\x48\x83\x45\xF0\xF0", enc.code(), "add QWORD PTR [rbp - 0x10], -0x10"); try enc.encode(.@"and", &.{ - .{ .mem = Instruction.Memory.sib(.dword, .{ .base = .{ .reg = .ds }, .disp = 0x10000000 }) }, + .{ .mem = Instruction.Memory.initSib(.dword, .{ .base = .{ .reg = .ds }, .disp = 0x10000000 }) }, .{ .imm = Instruction.Immediate.u(0x10) }, }); try expectEqualHexStrings( @@ -1384,7 +1384,7 @@ test "lower MI encoding" { ); try enc.encode(.@"and", &.{ - .{ .mem = Instruction.Memory.sib(.dword, .{ .base = .{ .reg = .es }, .disp = 0x10000000 }) }, + .{ .mem = Instruction.Memory.initSib(.dword, .{ .base = .{ .reg = .es }, .disp = 0x10000000 }) }, .{ .imm = Instruction.Immediate.u(0x10) }, }); try expectEqualHexStrings( @@ -1394,7 +1394,7 @@ test "lower MI encoding" { ); try enc.encode(.@"and", &.{ - .{ .mem = Instruction.Memory.sib(.dword, .{ .base = .{ .reg = .r12 }, .disp = 0x10000000 }) }, + .{ .mem = Instruction.Memory.initSib(.dword, .{ .base = .{ .reg = .r12 }, .disp = 0x10000000 }) }, .{ .imm = Instruction.Immediate.u(0x10) }, }); try expectEqualHexStrings( @@ -1404,7 +1404,7 @@ test "lower MI encoding" { ); try enc.encode(.sub, &.{ - .{ .mem = Instruction.Memory.sib(.dword, .{ .base = .{ .reg = .r11 }, .disp = 0x10000000 }) }, + .{ .mem = Instruction.Memory.initSib(.dword, .{ .base = .{ .reg = .r11 }, .disp = 0x10000000 }) }, .{ .imm = Instruction.Immediate.u(0x10) }, }); try expectEqualHexStrings( @@ -1419,25 +1419,25 @@ test "lower RM encoding" { try enc.encode(.mov, &.{ .{ .reg = .rax }, - .{ .mem = Instruction.Memory.sib(.qword, .{ .base = .{ .reg = .r11 } }) }, + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .r11 } }) }, }); try expectEqualHexStrings("\x49\x8b\x03", enc.code(), "mov rax, QWORD PTR [r11]"); try enc.encode(.mov, &.{ .{ .reg = .rbx }, - .{ .mem = Instruction.Memory.sib(.qword, .{ .base = .{ .reg = .ds }, .disp = 0x10 }) }, + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .ds }, .disp = 0x10 }) }, }); try expectEqualHexStrings("\x48\x8B\x1C\x25\x10\x00\x00\x00", enc.code(), "mov rbx, QWORD PTR ds:0x10"); try enc.encode(.mov, &.{ .{ .reg = .rax }, - .{ .mem = Instruction.Memory.sib(.qword, .{ .base = .{ .reg = .rbp }, .disp = -4 }) }, + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .rbp }, .disp = -4 }) }, }); try expectEqualHexStrings("\x48\x8B\x45\xFC", enc.code(), "mov rax, QWORD PTR [rbp - 4]"); try enc.encode(.mov, &.{ .{ .reg = .rax }, - .{ .mem = Instruction.Memory.sib(.qword, .{ + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .rbp }, .scale_index = .{ .scale = 1, .index = .rcx }, .disp = -8, @@ -1447,7 +1447,7 @@ test "lower RM encoding" { try enc.encode(.mov, &.{ .{ .reg = .eax }, - .{ .mem = Instruction.Memory.sib(.dword, .{ + .{ .mem = Instruction.Memory.initSib(.dword, .{ .base = .{ .reg = .rbp }, .scale_index = .{ .scale = 4, .index = .rdx }, .disp = -4, @@ -1457,7 +1457,7 @@ test "lower RM encoding" { try enc.encode(.mov, &.{ .{ .reg = .rax }, - .{ .mem = Instruction.Memory.sib(.qword, .{ + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .rbp }, .scale_index = .{ .scale = 8, .index = .rcx }, .disp = -8, @@ -1467,7 +1467,7 @@ test "lower RM encoding" { try enc.encode(.mov, &.{ .{ .reg = .r8b }, - .{ .mem = Instruction.Memory.sib(.byte, .{ + .{ .mem = Instruction.Memory.initSib(.byte, .{ .base = .{ .reg = .rsi }, .scale_index = .{ .scale = 1, .index = .rcx }, .disp = -24, @@ -1483,7 +1483,7 @@ test "lower RM encoding" { try expectEqualHexStrings("\x48\x8C\xC8", enc.code(), "mov rax, cs"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.sib(.word, .{ .base = .{ .reg = .rbp }, .disp = -16 }) }, + .{ .mem = Instruction.Memory.initSib(.word, .{ .base = .{ .reg = .rbp }, .disp = -16 }) }, .{ .reg = .fs }, }); try expectEqualHexStrings("\x8C\x65\xF0", enc.code(), "mov WORD PTR [rbp - 16], fs"); @@ -1514,19 +1514,19 @@ test "lower RM encoding" { try enc.encode(.movsx, &.{ .{ .reg = .eax }, - .{ .mem = Instruction.Memory.sib(.word, .{ .base = .{ .reg = .rbp } }) }, + .{ .mem = Instruction.Memory.initSib(.word, .{ .base = .{ .reg = .rbp } }) }, }); try expectEqualHexStrings("\x0F\xBF\x45\x00", enc.code(), "movsx eax, BYTE PTR [rbp]"); try enc.encode(.movsx, &.{ .{ .reg = .eax }, - .{ .mem = Instruction.Memory.sib(.byte, .{ .scale_index = .{ .index = .rax, .scale = 2 } }) }, + .{ .mem = Instruction.Memory.initSib(.byte, .{ .scale_index = .{ .index = .rax, .scale = 2 } }) }, }); try expectEqualHexStrings("\x0F\xBE\x04\x45\x00\x00\x00\x00", enc.code(), "movsx eax, BYTE PTR [rax * 2]"); try enc.encode(.movsx, &.{ .{ .reg = .ax }, - .{ .mem = Instruction.Memory.rip(.byte, 0x10) }, + .{ .mem = Instruction.Memory.initRip(.byte, 0x10) }, }); try expectEqualHexStrings("\x66\x0F\xBE\x05\x10\x00\x00\x00", enc.code(), "movsx ax, BYTE PTR [rip + 0x10]"); @@ -1544,37 +1544,37 @@ test "lower RM encoding" { try enc.encode(.lea, &.{ .{ .reg = .rax }, - .{ .mem = Instruction.Memory.rip(.qword, 0x10) }, + .{ .mem = Instruction.Memory.initRip(.qword, 0x10) }, }); try expectEqualHexStrings("\x48\x8D\x05\x10\x00\x00\x00", enc.code(), "lea rax, QWORD PTR [rip + 0x10]"); try enc.encode(.lea, &.{ .{ .reg = .rax }, - .{ .mem = Instruction.Memory.rip(.dword, 0x10) }, + .{ .mem = Instruction.Memory.initRip(.dword, 0x10) }, }); try expectEqualHexStrings("\x48\x8D\x05\x10\x00\x00\x00", enc.code(), "lea rax, DWORD PTR [rip + 0x10]"); try enc.encode(.lea, &.{ .{ .reg = .eax }, - .{ .mem = Instruction.Memory.rip(.dword, 0x10) }, + .{ .mem = Instruction.Memory.initRip(.dword, 0x10) }, }); try expectEqualHexStrings("\x8D\x05\x10\x00\x00\x00", enc.code(), "lea eax, DWORD PTR [rip + 0x10]"); try enc.encode(.lea, &.{ .{ .reg = .eax }, - .{ .mem = Instruction.Memory.rip(.word, 0x10) }, + .{ .mem = Instruction.Memory.initRip(.word, 0x10) }, }); try expectEqualHexStrings("\x8D\x05\x10\x00\x00\x00", enc.code(), "lea eax, WORD PTR [rip + 0x10]"); try enc.encode(.lea, &.{ .{ .reg = .ax }, - .{ .mem = Instruction.Memory.rip(.byte, 0x10) }, + .{ .mem = Instruction.Memory.initRip(.byte, 0x10) }, }); try expectEqualHexStrings("\x66\x8D\x05\x10\x00\x00\x00", enc.code(), "lea ax, BYTE PTR [rip + 0x10]"); try enc.encode(.lea, &.{ .{ .reg = .rsi }, - .{ .mem = Instruction.Memory.sib(.qword, .{ + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .rbp }, .scale_index = .{ .scale = 1, .index = .rcx }, }) }, @@ -1583,31 +1583,31 @@ test "lower RM encoding" { try enc.encode(.add, &.{ .{ .reg = .r11 }, - .{ .mem = Instruction.Memory.sib(.qword, .{ .base = .{ .reg = .ds }, .disp = 0x10000000 }) }, + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .ds }, .disp = 0x10000000 }) }, }); try expectEqualHexStrings("\x4C\x03\x1C\x25\x00\x00\x00\x10", enc.code(), "add r11, QWORD PTR ds:0x10000000"); try enc.encode(.add, &.{ .{ .reg = .r12b }, - .{ .mem = Instruction.Memory.sib(.byte, .{ .base = .{ .reg = .ds }, .disp = 0x10000000 }) }, + .{ .mem = Instruction.Memory.initSib(.byte, .{ .base = .{ .reg = .ds }, .disp = 0x10000000 }) }, }); try expectEqualHexStrings("\x44\x02\x24\x25\x00\x00\x00\x10", enc.code(), "add r11b, BYTE PTR ds:0x10000000"); try enc.encode(.add, &.{ .{ .reg = .r12b }, - .{ .mem = Instruction.Memory.sib(.byte, .{ .base = .{ .reg = .fs }, .disp = 0x10000000 }) }, + .{ .mem = Instruction.Memory.initSib(.byte, .{ .base = .{ .reg = .fs }, .disp = 0x10000000 }) }, }); try expectEqualHexStrings("\x64\x44\x02\x24\x25\x00\x00\x00\x10", enc.code(), "add r11b, BYTE PTR fs:0x10000000"); try enc.encode(.sub, &.{ .{ .reg = .r11 }, - .{ .mem = Instruction.Memory.sib(.qword, .{ .base = .{ .reg = .r13 }, .disp = 0x10000000 }) }, + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .r13 }, .disp = 0x10000000 }) }, }); try expectEqualHexStrings("\x4D\x2B\x9D\x00\x00\x00\x10", enc.code(), "sub r11, QWORD PTR [r13 + 0x10000000]"); try enc.encode(.sub, &.{ .{ .reg = .r11 }, - .{ .mem = Instruction.Memory.sib(.qword, .{ .base = .{ .reg = .r12 }, .disp = 0x10000000 }) }, + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .r12 }, .disp = 0x10000000 }) }, }); try expectEqualHexStrings("\x4D\x2B\x9C\x24\x00\x00\x00\x10", enc.code(), "sub r11, QWORD PTR [r12 + 0x10000000]"); @@ -1630,7 +1630,7 @@ test "lower RMI encoding" { try enc.encode(.imul, &.{ .{ .reg = .r11 }, - .{ .mem = Instruction.Memory.rip(.qword, -16) }, + .{ .mem = Instruction.Memory.initRip(.qword, -16) }, .{ .imm = Instruction.Immediate.s(-1024) }, }); try expectEqualHexStrings( @@ -1641,7 +1641,7 @@ test "lower RMI encoding" { try enc.encode(.imul, &.{ .{ .reg = .bx }, - .{ .mem = Instruction.Memory.sib(.word, .{ .base = .{ .reg = .rbp }, .disp = -16 }) }, + .{ .mem = Instruction.Memory.initSib(.word, .{ .base = .{ .reg = .rbp }, .disp = -16 }) }, .{ .imm = Instruction.Immediate.s(-1024) }, }); try expectEqualHexStrings( @@ -1652,7 +1652,7 @@ test "lower RMI encoding" { try enc.encode(.imul, &.{ .{ .reg = .bx }, - .{ .mem = Instruction.Memory.sib(.word, .{ .base = .{ .reg = .rbp }, .disp = -16 }) }, + .{ .mem = Instruction.Memory.initSib(.word, .{ .base = .{ .reg = .rbp }, .disp = -16 }) }, .{ .imm = Instruction.Immediate.u(1024) }, }); try expectEqualHexStrings( @@ -1672,19 +1672,19 @@ test "lower MR encoding" { try expectEqualHexStrings("\x48\x89\xD8", enc.code(), "mov rax, rbx"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.sib(.qword, .{ .base = .{ .reg = .rbp }, .disp = -4 }) }, + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .rbp }, .disp = -4 }) }, .{ .reg = .r11 }, }); try expectEqualHexStrings("\x4c\x89\x5d\xfc", enc.code(), "mov QWORD PTR [rbp - 4], r11"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.rip(.qword, 0x10) }, + .{ .mem = Instruction.Memory.initRip(.qword, 0x10) }, .{ .reg = .r12 }, }); try expectEqualHexStrings("\x4C\x89\x25\x10\x00\x00\x00", enc.code(), "mov QWORD PTR [rip + 0x10], r12"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.sib(.qword, .{ + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .r11 }, .scale_index = .{ .scale = 2, .index = .r12 }, .disp = 0x10, @@ -1694,13 +1694,13 @@ test "lower MR encoding" { try expectEqualHexStrings("\x4F\x89\x6C\x63\x10", enc.code(), "mov QWORD PTR [r11 + 2 * r12 + 0x10], r13"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.rip(.word, -0x10) }, + .{ .mem = Instruction.Memory.initRip(.word, -0x10) }, .{ .reg = .r12w }, }); try expectEqualHexStrings("\x66\x44\x89\x25\xF0\xFF\xFF\xFF", enc.code(), "mov WORD PTR [rip - 0x10], r12w"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.sib(.byte, .{ + .{ .mem = Instruction.Memory.initSib(.byte, .{ .base = .{ .reg = .r11 }, .scale_index = .{ .scale = 2, .index = .r12 }, .disp = 0x10, @@ -1710,25 +1710,25 @@ test "lower MR encoding" { try expectEqualHexStrings("\x47\x88\x6C\x63\x10", enc.code(), "mov BYTE PTR [r11 + 2 * r12 + 0x10], r13b"); try enc.encode(.add, &.{ - .{ .mem = Instruction.Memory.sib(.byte, .{ .base = .{ .reg = .ds }, .disp = 0x10000000 }) }, + .{ .mem = Instruction.Memory.initSib(.byte, .{ .base = .{ .reg = .ds }, .disp = 0x10000000 }) }, .{ .reg = .r12b }, }); try expectEqualHexStrings("\x44\x00\x24\x25\x00\x00\x00\x10", enc.code(), "add BYTE PTR ds:0x10000000, r12b"); try enc.encode(.add, &.{ - .{ .mem = Instruction.Memory.sib(.dword, .{ .base = .{ .reg = .ds }, .disp = 0x10000000 }) }, + .{ .mem = Instruction.Memory.initSib(.dword, .{ .base = .{ .reg = .ds }, .disp = 0x10000000 }) }, .{ .reg = .r12d }, }); try expectEqualHexStrings("\x44\x01\x24\x25\x00\x00\x00\x10", enc.code(), "add DWORD PTR [ds:0x10000000], r12d"); try enc.encode(.add, &.{ - .{ .mem = Instruction.Memory.sib(.dword, .{ .base = .{ .reg = .gs }, .disp = 0x10000000 }) }, + .{ .mem = Instruction.Memory.initSib(.dword, .{ .base = .{ .reg = .gs }, .disp = 0x10000000 }) }, .{ .reg = .r12d }, }); try expectEqualHexStrings("\x65\x44\x01\x24\x25\x00\x00\x00\x10", enc.code(), "add DWORD PTR [gs:0x10000000], r12d"); try enc.encode(.sub, &.{ - .{ .mem = Instruction.Memory.sib(.qword, .{ .base = .{ .reg = .r11 }, .disp = 0x10000000 }) }, + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .r11 }, .disp = 0x10000000 }) }, .{ .reg = .r12 }, }); try expectEqualHexStrings("\x4D\x29\xA3\x00\x00\x00\x10", enc.code(), "sub QWORD PTR [r11 + 0x10000000], r12"); @@ -1743,12 +1743,12 @@ test "lower M encoding" { try expectEqualHexStrings("\x41\xFF\xD4", enc.code(), "call r12"); try enc.encode(.call, &.{ - .{ .mem = Instruction.Memory.sib(.qword, .{ .base = .{ .reg = .r12 } }) }, + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .r12 } }) }, }); try expectEqualHexStrings("\x41\xFF\x14\x24", enc.code(), "call QWORD PTR [r12]"); try enc.encode(.call, &.{ - .{ .mem = Instruction.Memory.sib(.qword, .{ + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .none, .scale_index = .{ .index = .r11, .scale = 2 }, }) }, @@ -1756,7 +1756,7 @@ test "lower M encoding" { try expectEqualHexStrings("\x42\xFF\x14\x5D\x00\x00\x00\x00", enc.code(), "call QWORD PTR [r11 * 2]"); try enc.encode(.call, &.{ - .{ .mem = Instruction.Memory.sib(.qword, .{ + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .none, .scale_index = .{ .index = .r12, .scale = 2 }, }) }, @@ -1764,7 +1764,7 @@ test "lower M encoding" { try expectEqualHexStrings("\x42\xFF\x14\x65\x00\x00\x00\x00", enc.code(), "call QWORD PTR [r12 * 2]"); try enc.encode(.call, &.{ - .{ .mem = Instruction.Memory.sib(.qword, .{ .base = .{ .reg = .gs } }) }, + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .gs } }) }, }); try expectEqualHexStrings("\x65\xFF\x14\x25\x00\x00\x00\x00", enc.code(), "call gs:0x0"); @@ -1774,22 +1774,22 @@ test "lower M encoding" { try expectEqualHexStrings("\xE8\x00\x00\x00\x00", enc.code(), "call 0x0"); try enc.encode(.push, &.{ - .{ .mem = Instruction.Memory.sib(.qword, .{ .base = .{ .reg = .rbp } }) }, + .{ .mem = Instruction.Memory.initSib(.qword, .{ .base = .{ .reg = .rbp } }) }, }); try expectEqualHexStrings("\xFF\x75\x00", enc.code(), "push QWORD PTR [rbp]"); try enc.encode(.push, &.{ - .{ .mem = Instruction.Memory.sib(.word, .{ .base = .{ .reg = .rbp } }) }, + .{ .mem = Instruction.Memory.initSib(.word, .{ .base = .{ .reg = .rbp } }) }, }); try expectEqualHexStrings("\x66\xFF\x75\x00", enc.code(), "push QWORD PTR [rbp]"); try enc.encode(.pop, &.{ - .{ .mem = Instruction.Memory.rip(.qword, 0) }, + .{ .mem = Instruction.Memory.initRip(.qword, 0) }, }); try expectEqualHexStrings("\x8F\x05\x00\x00\x00\x00", enc.code(), "pop QWORD PTR [rip]"); try enc.encode(.pop, &.{ - .{ .mem = Instruction.Memory.rip(.word, 0) }, + .{ .mem = Instruction.Memory.initRip(.word, 0) }, }); try expectEqualHexStrings("\x66\x8F\x05\x00\x00\x00\x00", enc.code(), "pop WORD PTR [rbp]"); @@ -1870,48 +1870,48 @@ test "lower FD/TD encoding" { try enc.encode(.mov, &.{ .{ .reg = .rax }, - .{ .mem = Instruction.Memory.moffs(.cs, 0x10) }, + .{ .mem = Instruction.Memory.initMoffs(.cs, 0x10) }, }); try expectEqualHexStrings("\x2E\x48\xA1\x10\x00\x00\x00\x00\x00\x00\x00", enc.code(), "movabs rax, cs:0x10"); try enc.encode(.mov, &.{ .{ .reg = .eax }, - .{ .mem = Instruction.Memory.moffs(.fs, 0x10) }, + .{ .mem = Instruction.Memory.initMoffs(.fs, 0x10) }, }); try expectEqualHexStrings("\x64\xA1\x10\x00\x00\x00\x00\x00\x00\x00", enc.code(), "movabs eax, fs:0x10"); try enc.encode(.mov, &.{ .{ .reg = .ax }, - .{ .mem = Instruction.Memory.moffs(.gs, 0x10) }, + .{ .mem = Instruction.Memory.initMoffs(.gs, 0x10) }, }); try expectEqualHexStrings("\x65\x66\xA1\x10\x00\x00\x00\x00\x00\x00\x00", enc.code(), "movabs ax, gs:0x10"); try enc.encode(.mov, &.{ .{ .reg = .al }, - .{ .mem = Instruction.Memory.moffs(.ds, 0x10) }, + .{ .mem = Instruction.Memory.initMoffs(.ds, 0x10) }, }); try expectEqualHexStrings("\xA0\x10\x00\x00\x00\x00\x00\x00\x00", enc.code(), "movabs al, ds:0x10"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.moffs(.cs, 0x10) }, + .{ .mem = Instruction.Memory.initMoffs(.cs, 0x10) }, .{ .reg = .rax }, }); try expectEqualHexStrings("\x2E\x48\xA3\x10\x00\x00\x00\x00\x00\x00\x00", enc.code(), "movabs cs:0x10, rax"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.moffs(.fs, 0x10) }, + .{ .mem = Instruction.Memory.initMoffs(.fs, 0x10) }, .{ .reg = .eax }, }); try expectEqualHexStrings("\x64\xA3\x10\x00\x00\x00\x00\x00\x00\x00", enc.code(), "movabs fs:0x10, eax"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.moffs(.gs, 0x10) }, + .{ .mem = Instruction.Memory.initMoffs(.gs, 0x10) }, .{ .reg = .ax }, }); try expectEqualHexStrings("\x65\x66\xA3\x10\x00\x00\x00\x00\x00\x00\x00", enc.code(), "movabs gs:0x10, ax"); try enc.encode(.mov, &.{ - .{ .mem = Instruction.Memory.moffs(.ds, 0x10) }, + .{ .mem = Instruction.Memory.initMoffs(.ds, 0x10) }, .{ .reg = .al }, }); try expectEqualHexStrings("\xA2\x10\x00\x00\x00\x00\x00\x00\x00", enc.code(), "movabs ds:0x10, al"); @@ -1949,16 +1949,16 @@ test "invalid instruction" { .{ .reg = .al }, }); try invalidInstruction(.call, &.{ - .{ .mem = Instruction.Memory.rip(.dword, 0) }, + .{ .mem = Instruction.Memory.initRip(.dword, 0) }, }); try invalidInstruction(.call, &.{ - .{ .mem = Instruction.Memory.rip(.word, 0) }, + .{ .mem = Instruction.Memory.initRip(.word, 0) }, }); try invalidInstruction(.call, &.{ - .{ .mem = Instruction.Memory.rip(.byte, 0) }, + .{ .mem = Instruction.Memory.initRip(.byte, 0) }, }); try invalidInstruction(.mov, &.{ - .{ .mem = Instruction.Memory.rip(.word, 0x10) }, + .{ .mem = Instruction.Memory.initRip(.word, 0x10) }, .{ .reg = .r12 }, }); try invalidInstruction(.lea, &.{ @@ -1967,7 +1967,7 @@ test "invalid instruction" { }); try invalidInstruction(.lea, &.{ .{ .reg = .al }, - .{ .mem = Instruction.Memory.rip(.byte, 0) }, + .{ .mem = Instruction.Memory.initRip(.byte, 0) }, }); try invalidInstruction(.pop, &.{ .{ .reg = .r12b }, @@ -1992,7 +1992,7 @@ fn cannotEncode(mnemonic: Instruction.Mnemonic, ops: []const Instruction.Operand test "cannot encode" { try cannotEncode(.@"test", &.{ - .{ .mem = Instruction.Memory.sib(.byte, .{ .base = .{ .reg = .r12 } }) }, + .{ .mem = Instruction.Memory.initSib(.byte, .{ .base = .{ .reg = .r12 } }) }, .{ .reg = .ah }, }); try cannotEncode(.@"test", &.{ @@ -2369,7 +2369,7 @@ const Assembler = struct { if (res.rip) { if (res.base != null or res.scale_index != null or res.offset != null) return error.InvalidMemoryOperand; - return Instruction.Memory.rip(ptr_size orelse .qword, res.disp orelse 0); + return Instruction.Memory.initRip(ptr_size orelse .qword, res.disp orelse 0); } if (res.base) |base| { if (res.rip) @@ -2377,9 +2377,9 @@ const Assembler = struct { if (res.offset) |offset| { if (res.scale_index != null or res.disp != null) return error.InvalidMemoryOperand; - return Instruction.Memory.moffs(base, offset); + return Instruction.Memory.initMoffs(base, offset); } - return Instruction.Memory.sib(ptr_size orelse .qword, .{ + return Instruction.Memory.initSib(ptr_size orelse .qword, .{ .base = .{ .reg = base }, .scale_index = res.scale_index, .disp = res.disp orelse 0, diff --git a/src/codegen.zig b/src/codegen.zig index 67217c37e87c..adc77c78edb8 100644 --- a/src/codegen.zig +++ b/src/codegen.zig @@ -836,16 +836,6 @@ pub const GenResult = union(enum) { /// Traditionally, this corresponds to emitting a relocation in a relocatable object file. lea_symbol: u32, }; - - fn fail( - gpa: Allocator, - src_loc: Zcu.LazySrcLoc, - comptime format: []const u8, - args: anytype, - ) Allocator.Error!GenResult { - const msg = try ErrorMsg.create(gpa, src_loc, format, args); - return .{ .fail = msg }; - } }; fn genNavRef( @@ -935,7 +925,8 @@ fn genNavRef( const atom = p9.getAtom(atom_index); return .{ .mcv = .{ .memory = atom.getOffsetTableAddress(p9) } }; } else { - return GenResult.fail(gpa, src_loc, "TODO genNavRef for target {}", .{target}); + const msg = try ErrorMsg.create(gpa, src_loc, "TODO genNavRef for target {}", .{target}); + return .{ .fail = msg }; } } diff --git a/src/codegen/llvm/BitcodeReader.zig b/src/codegen/llvm/BitcodeReader.zig index 940b96534001..8a9af1562921 100644 --- a/src/codegen/llvm/BitcodeReader.zig +++ b/src/codegen/llvm/BitcodeReader.zig @@ -33,9 +33,9 @@ pub const Block = struct { .abbrevs = .{ .abbrevs = .{} }, }; - const set_bid: u32 = 1; - const block_name: u32 = 2; - const set_record_name: u32 = 3; + const set_bid_id: u32 = 1; + const block_name_id: u32 = 2; + const set_record_name_id: u32 = 3; fn deinit(info: *Info, allocator: std.mem.Allocator) void { allocator.free(info.block_name); @@ -61,7 +61,7 @@ pub const Record = struct { assert(record.id == Abbrev.Builtin.define_abbrev.toRecordId()); var i: usize = 0; while (i < record.operands.len) switch (record.operands[i]) { - Abbrev.Operand.literal => { + Abbrev.Operand.literal_id => { try operands.append(.{ .literal = record.operands[i + 1] }); i += 2; }, @@ -211,7 +211,7 @@ fn nextRecord(bc: *BitcodeReader) !?Record { .align_32_bits, .block_len => return error.UnsupportedArrayElement, .abbrev_op => switch (try bc.readFixed(u1, 1)) { 1 => try operands.appendSlice(&.{ - Abbrev.Operand.literal, + Abbrev.Operand.literal_id, try bc.readVbr(u64, 8), }), 0 => { @@ -334,9 +334,9 @@ fn parseBlockInfoBlock(bc: *BitcodeReader) !void { try record.toOwnedAbbrev(bc.allocator), ); }, - Block.Info.set_bid => block_id = std.math.cast(u32, record.operands[0]) orelse + Block.Info.set_bid_id => block_id = std.math.cast(u32, record.operands[0]) orelse return error.Overflow, - Block.Info.block_name => if (bc.keep_names) { + Block.Info.block_name_id => if (bc.keep_names) { const gop = try bc.block_info.getOrPut(bc.allocator, block_id orelse return error.UnspecifiedBlockId); if (!gop.found_existing) gop.value_ptr.* = Block.Info.default; @@ -346,7 +346,7 @@ fn parseBlockInfoBlock(bc: *BitcodeReader) !void { byte.* = std.math.cast(u8, operand) orelse return error.InvalidName; gop.value_ptr.block_name = name; }, - Block.Info.set_record_name => if (bc.keep_names) { + Block.Info.set_record_name_id => if (bc.keep_names) { const gop = try bc.block_info.getOrPut(bc.allocator, block_id orelse return error.UnspecifiedBlockId); if (!gop.found_existing) gop.value_ptr.* = Block.Info.default; @@ -467,7 +467,7 @@ const Abbrev = struct { block_len, abbrev_op, - const literal = std.math.maxInt(u64); + const literal_id = std.math.maxInt(u64); const Encoding = enum(u3) { fixed = 1, vbr = 2, diff --git a/src/link/Elf.zig b/src/link/Elf.zig index 3dca7eace3ca..e577b8d45aa7 100644 --- a/src/link/Elf.zig +++ b/src/link/Elf.zig @@ -3467,7 +3467,7 @@ fn updateSectionSizes(self: *Elf) !void { if (atom_list.items.len == 0) continue; // Create jump/branch range extenders if needed. - try thunks.createThunks(shdr, @intCast(shndx), self); + try self.createThunks(shdr, @intCast(shndx)); } } @@ -5576,6 +5576,88 @@ fn defaultEntrySymbolName(cpu_arch: std.Target.Cpu.Arch) []const u8 { }; } +fn createThunks(elf_file: *Elf, shdr: *elf.Elf64_Shdr, shndx: u32) !void { + const gpa = elf_file.base.comp.gpa; + const cpu_arch = elf_file.getTarget().cpu.arch; + // A branch will need an extender if its target is larger than + // `2^(jump_bits - 1) - margin` where margin is some arbitrary number. + const max_distance = switch (cpu_arch) { + .aarch64 => 0x500_000, + .x86_64, .riscv64 => unreachable, + else => @panic("unhandled arch"), + }; + const atoms = elf_file.sections.items(.atom_list)[shndx].items; + assert(atoms.len > 0); + + for (atoms) |ref| { + elf_file.atom(ref).?.value = -1; + } + + var i: usize = 0; + while (i < atoms.len) { + const start = i; + const start_atom = elf_file.atom(atoms[start]).?; + assert(start_atom.alive); + start_atom.value = try advanceSection(shdr, start_atom.size, start_atom.alignment); + i += 1; + + while (i < atoms.len) : (i += 1) { + const atom_ptr = elf_file.atom(atoms[i]).?; + assert(atom_ptr.alive); + if (@as(i64, @intCast(atom_ptr.alignment.forward(shdr.sh_size))) - start_atom.value >= max_distance) + break; + atom_ptr.value = try advanceSection(shdr, atom_ptr.size, atom_ptr.alignment); + } + + // Insert a thunk at the group end + const thunk_index = try elf_file.addThunk(); + const thunk_ptr = elf_file.thunk(thunk_index); + thunk_ptr.output_section_index = shndx; + + // Scan relocs in the group and create trampolines for any unreachable callsite + for (atoms[start..i]) |ref| { + const atom_ptr = elf_file.atom(ref).?; + const file_ptr = atom_ptr.file(elf_file).?; + log.debug("atom({}) {s}", .{ ref, atom_ptr.name(elf_file) }); + for (atom_ptr.relocs(elf_file)) |rel| { + const is_reachable = switch (cpu_arch) { + .aarch64 => r: { + const r_type: elf.R_AARCH64 = @enumFromInt(rel.r_type()); + if (r_type != .CALL26 and r_type != .JUMP26) break :r true; + const target_ref = file_ptr.resolveSymbol(rel.r_sym(), elf_file); + const target = elf_file.symbol(target_ref).?; + if (target.flags.has_plt) break :r false; + if (atom_ptr.output_section_index != target.output_section_index) break :r false; + const target_atom = target.atom(elf_file).?; + if (target_atom.value == -1) break :r false; + const saddr = atom_ptr.address(elf_file) + @as(i64, @intCast(rel.r_offset)); + const taddr = target.address(.{}, elf_file); + _ = math.cast(i28, taddr + rel.r_addend - saddr) orelse break :r false; + break :r true; + }, + .x86_64, .riscv64 => unreachable, + else => @panic("unsupported arch"), + }; + if (is_reachable) continue; + const target = file_ptr.resolveSymbol(rel.r_sym(), elf_file); + try thunk_ptr.symbols.put(gpa, target, {}); + } + atom_ptr.addExtra(.{ .thunk = thunk_index }, elf_file); + } + + thunk_ptr.value = try advanceSection(shdr, thunk_ptr.size(elf_file), Atom.Alignment.fromNonzeroByteUnits(2)); + + log.debug("thunk({d}) : {}", .{ thunk_index, thunk_ptr.fmt(elf_file) }); + } +} +fn advanceSection(shdr: *elf.Elf64_Shdr, adv_size: u64, alignment: Atom.Alignment) !i64 { + const offset = alignment.forward(shdr.sh_size); + const padding = offset - shdr.sh_size; + shdr.sh_size += padding + adv_size; + shdr.sh_addralign = @max(shdr.sh_addralign, alignment.toByteUnits() orelse 1); + return @intCast(offset); +} + const std = @import("std"); const build_options = @import("build_options"); const builtin = @import("builtin"); @@ -5598,7 +5680,6 @@ const musl = @import("../musl.zig"); const relocatable = @import("Elf/relocatable.zig"); const relocation = @import("Elf/relocation.zig"); const target_util = @import("../target.zig"); -const thunks = @import("Elf/thunks.zig"); const trace = @import("../tracy.zig").trace; const synthetic_sections = @import("Elf/synthetic_sections.zig"); @@ -5636,7 +5717,7 @@ const PltGotSection = synthetic_sections.PltGotSection; const SharedObject = @import("Elf/SharedObject.zig"); const Symbol = @import("Elf/Symbol.zig"); const StringTable = @import("StringTable.zig"); -const Thunk = thunks.Thunk; +const Thunk = @import("Elf/Thunk.zig"); const Value = @import("../Value.zig"); const VerneedSection = synthetic_sections.VerneedSection; const ZigObject = @import("Elf/ZigObject.zig"); diff --git a/src/link/Elf/Atom.zig b/src/link/Elf/Atom.zig index 10a7aa2b798e..ef2301f1cd74 100644 --- a/src/link/Elf/Atom.zig +++ b/src/link/Elf/Atom.zig @@ -2251,6 +2251,6 @@ const Fde = eh_frame.Fde; const File = @import("file.zig").File; const Object = @import("Object.zig"); const Symbol = @import("Symbol.zig"); -const Thunk = @import("thunks.zig").Thunk; +const Thunk = @import("Thunk.zig"); const ZigObject = @import("ZigObject.zig"); const dev = @import("../../dev.zig"); diff --git a/src/link/Elf/Thunk.zig b/src/link/Elf/Thunk.zig new file mode 100644 index 000000000000..389ba7ffed4c --- /dev/null +++ b/src/link/Elf/Thunk.zig @@ -0,0 +1,144 @@ +value: i64 = 0, +output_section_index: u32 = 0, +symbols: std.AutoArrayHashMapUnmanaged(Elf.Ref, void) = .{}, +output_symtab_ctx: Elf.SymtabCtx = .{}, + +pub fn deinit(thunk: *Thunk, allocator: Allocator) void { + thunk.symbols.deinit(allocator); +} + +pub fn size(thunk: Thunk, elf_file: *Elf) usize { + const cpu_arch = elf_file.getTarget().cpu.arch; + return thunk.symbols.keys().len * trampolineSize(cpu_arch); +} + +pub fn address(thunk: Thunk, elf_file: *Elf) i64 { + const shdr = elf_file.sections.items(.shdr)[thunk.output_section_index]; + return @as(i64, @intCast(shdr.sh_addr)) + thunk.value; +} + +pub fn targetAddress(thunk: Thunk, ref: Elf.Ref, elf_file: *Elf) i64 { + const cpu_arch = elf_file.getTarget().cpu.arch; + return thunk.address(elf_file) + @as(i64, @intCast(thunk.symbols.getIndex(ref).? * trampolineSize(cpu_arch))); +} + +pub fn write(thunk: Thunk, elf_file: *Elf, writer: anytype) !void { + switch (elf_file.getTarget().cpu.arch) { + .aarch64 => try aarch64.write(thunk, elf_file, writer), + .x86_64, .riscv64 => unreachable, + else => @panic("unhandled arch"), + } +} + +pub fn calcSymtabSize(thunk: *Thunk, elf_file: *Elf) void { + thunk.output_symtab_ctx.nlocals = @as(u32, @intCast(thunk.symbols.keys().len)); + for (thunk.symbols.keys()) |ref| { + const sym = elf_file.symbol(ref).?; + thunk.output_symtab_ctx.strsize += @as(u32, @intCast(sym.name(elf_file).len + "$thunk".len + 1)); + } +} + +pub fn writeSymtab(thunk: Thunk, elf_file: *Elf) void { + const cpu_arch = elf_file.getTarget().cpu.arch; + for (thunk.symbols.keys(), thunk.output_symtab_ctx.ilocal..) |ref, ilocal| { + const sym = elf_file.symbol(ref).?; + const st_name = @as(u32, @intCast(elf_file.strtab.items.len)); + elf_file.strtab.appendSliceAssumeCapacity(sym.name(elf_file)); + elf_file.strtab.appendSliceAssumeCapacity("$thunk"); + elf_file.strtab.appendAssumeCapacity(0); + elf_file.symtab.items[ilocal] = .{ + .st_name = st_name, + .st_info = elf.STT_FUNC, + .st_other = 0, + .st_shndx = @intCast(thunk.output_section_index), + .st_value = @intCast(thunk.targetAddress(ref, elf_file)), + .st_size = trampolineSize(cpu_arch), + }; + } +} + +fn trampolineSize(cpu_arch: std.Target.Cpu.Arch) usize { + return switch (cpu_arch) { + .aarch64 => aarch64.trampoline_size, + .x86_64, .riscv64 => unreachable, + else => @panic("unhandled arch"), + }; +} + +pub fn format( + thunk: Thunk, + comptime unused_fmt_string: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, +) !void { + _ = thunk; + _ = unused_fmt_string; + _ = options; + _ = writer; + @compileError("do not format Thunk directly"); +} + +pub fn fmt(thunk: Thunk, elf_file: *Elf) std.fmt.Formatter(format2) { + return .{ .data = .{ + .thunk = thunk, + .elf_file = elf_file, + } }; +} + +const FormatContext = struct { + thunk: Thunk, + elf_file: *Elf, +}; + +fn format2( + ctx: FormatContext, + comptime unused_fmt_string: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, +) !void { + _ = options; + _ = unused_fmt_string; + const thunk = ctx.thunk; + const elf_file = ctx.elf_file; + try writer.print("@{x} : size({x})\n", .{ thunk.value, thunk.size(elf_file) }); + for (thunk.symbols.keys()) |ref| { + const sym = elf_file.symbol(ref).?; + try writer.print(" {} : {s} : @{x}\n", .{ ref, sym.name(elf_file), sym.value }); + } +} + +pub const Index = u32; + +const aarch64 = struct { + fn write(thunk: Thunk, elf_file: *Elf, writer: anytype) !void { + for (thunk.symbols.keys(), 0..) |ref, i| { + const sym = elf_file.symbol(ref).?; + const saddr = thunk.address(elf_file) + @as(i64, @intCast(i * trampoline_size)); + const taddr = sym.address(.{}, elf_file); + const pages = try util.calcNumberOfPages(saddr, taddr); + try writer.writeInt(u32, Instruction.adrp(.x16, pages).toU32(), .little); + const off: u12 = @truncate(@as(u64, @bitCast(taddr))); + try writer.writeInt(u32, Instruction.add(.x16, .x16, off, false).toU32(), .little); + try writer.writeInt(u32, Instruction.br(.x16).toU32(), .little); + } + } + + const trampoline_size = 3 * @sizeOf(u32); + + const util = @import("../aarch64.zig"); + const Instruction = util.Instruction; +}; + +const assert = std.debug.assert; +const elf = std.elf; +const log = std.log.scoped(.link); +const math = std.math; +const mem = std.mem; +const std = @import("std"); + +const Allocator = mem.Allocator; +const Atom = @import("Atom.zig"); +const Elf = @import("../Elf.zig"); +const Symbol = @import("Symbol.zig"); + +const Thunk = @This(); diff --git a/src/link/Elf/thunks.zig b/src/link/Elf/thunks.zig deleted file mode 100644 index bc534639da32..000000000000 --- a/src/link/Elf/thunks.zig +++ /dev/null @@ -1,234 +0,0 @@ -pub fn createThunks(shdr: *elf.Elf64_Shdr, shndx: u32, elf_file: *Elf) !void { - const gpa = elf_file.base.comp.gpa; - const cpu_arch = elf_file.getTarget().cpu.arch; - const max_distance = maxAllowedDistance(cpu_arch); - const atoms = elf_file.sections.items(.atom_list)[shndx].items; - assert(atoms.len > 0); - - for (atoms) |ref| { - elf_file.atom(ref).?.value = -1; - } - - var i: usize = 0; - while (i < atoms.len) { - const start = i; - const start_atom = elf_file.atom(atoms[start]).?; - assert(start_atom.alive); - start_atom.value = try advance(shdr, start_atom.size, start_atom.alignment); - i += 1; - - while (i < atoms.len) : (i += 1) { - const atom = elf_file.atom(atoms[i]).?; - assert(atom.alive); - if (@as(i64, @intCast(atom.alignment.forward(shdr.sh_size))) - start_atom.value >= max_distance) - break; - atom.value = try advance(shdr, atom.size, atom.alignment); - } - - // Insert a thunk at the group end - const thunk_index = try elf_file.addThunk(); - const thunk = elf_file.thunk(thunk_index); - thunk.output_section_index = shndx; - - // Scan relocs in the group and create trampolines for any unreachable callsite - for (atoms[start..i]) |ref| { - const atom = elf_file.atom(ref).?; - const file = atom.file(elf_file).?; - log.debug("atom({}) {s}", .{ ref, atom.name(elf_file) }); - for (atom.relocs(elf_file)) |rel| { - const is_reachable = switch (cpu_arch) { - .aarch64 => aarch64.isReachable(atom, rel, elf_file), - .x86_64, .riscv64 => unreachable, - else => @panic("unsupported arch"), - }; - if (is_reachable) continue; - const target = file.resolveSymbol(rel.r_sym(), elf_file); - try thunk.symbols.put(gpa, target, {}); - } - atom.addExtra(.{ .thunk = thunk_index }, elf_file); - } - - thunk.value = try advance(shdr, thunk.size(elf_file), Atom.Alignment.fromNonzeroByteUnits(2)); - - log.debug("thunk({d}) : {}", .{ thunk_index, thunk.fmt(elf_file) }); - } -} - -fn advance(shdr: *elf.Elf64_Shdr, size: u64, alignment: Atom.Alignment) !i64 { - const offset = alignment.forward(shdr.sh_size); - const padding = offset - shdr.sh_size; - shdr.sh_size += padding + size; - shdr.sh_addralign = @max(shdr.sh_addralign, alignment.toByteUnits() orelse 1); - return @intCast(offset); -} - -/// A branch will need an extender if its target is larger than -/// `2^(jump_bits - 1) - margin` where margin is some arbitrary number. -fn maxAllowedDistance(cpu_arch: std.Target.Cpu.Arch) u32 { - return switch (cpu_arch) { - .aarch64 => 0x500_000, - .x86_64, .riscv64 => unreachable, - else => @panic("unhandled arch"), - }; -} - -pub const Thunk = struct { - value: i64 = 0, - output_section_index: u32 = 0, - symbols: std.AutoArrayHashMapUnmanaged(Elf.Ref, void) = .{}, - output_symtab_ctx: Elf.SymtabCtx = .{}, - - pub fn deinit(thunk: *Thunk, allocator: Allocator) void { - thunk.symbols.deinit(allocator); - } - - pub fn size(thunk: Thunk, elf_file: *Elf) usize { - const cpu_arch = elf_file.getTarget().cpu.arch; - return thunk.symbols.keys().len * trampolineSize(cpu_arch); - } - - pub fn address(thunk: Thunk, elf_file: *Elf) i64 { - const shdr = elf_file.sections.items(.shdr)[thunk.output_section_index]; - return @as(i64, @intCast(shdr.sh_addr)) + thunk.value; - } - - pub fn targetAddress(thunk: Thunk, ref: Elf.Ref, elf_file: *Elf) i64 { - const cpu_arch = elf_file.getTarget().cpu.arch; - return thunk.address(elf_file) + @as(i64, @intCast(thunk.symbols.getIndex(ref).? * trampolineSize(cpu_arch))); - } - - pub fn write(thunk: Thunk, elf_file: *Elf, writer: anytype) !void { - switch (elf_file.getTarget().cpu.arch) { - .aarch64 => try aarch64.write(thunk, elf_file, writer), - .x86_64, .riscv64 => unreachable, - else => @panic("unhandled arch"), - } - } - - pub fn calcSymtabSize(thunk: *Thunk, elf_file: *Elf) void { - thunk.output_symtab_ctx.nlocals = @as(u32, @intCast(thunk.symbols.keys().len)); - for (thunk.symbols.keys()) |ref| { - const sym = elf_file.symbol(ref).?; - thunk.output_symtab_ctx.strsize += @as(u32, @intCast(sym.name(elf_file).len + "$thunk".len + 1)); - } - } - - pub fn writeSymtab(thunk: Thunk, elf_file: *Elf) void { - const cpu_arch = elf_file.getTarget().cpu.arch; - for (thunk.symbols.keys(), thunk.output_symtab_ctx.ilocal..) |ref, ilocal| { - const sym = elf_file.symbol(ref).?; - const st_name = @as(u32, @intCast(elf_file.strtab.items.len)); - elf_file.strtab.appendSliceAssumeCapacity(sym.name(elf_file)); - elf_file.strtab.appendSliceAssumeCapacity("$thunk"); - elf_file.strtab.appendAssumeCapacity(0); - elf_file.symtab.items[ilocal] = .{ - .st_name = st_name, - .st_info = elf.STT_FUNC, - .st_other = 0, - .st_shndx = @intCast(thunk.output_section_index), - .st_value = @intCast(thunk.targetAddress(ref, elf_file)), - .st_size = trampolineSize(cpu_arch), - }; - } - } - - fn trampolineSize(cpu_arch: std.Target.Cpu.Arch) usize { - return switch (cpu_arch) { - .aarch64 => aarch64.trampoline_size, - .x86_64, .riscv64 => unreachable, - else => @panic("unhandled arch"), - }; - } - - pub fn format( - thunk: Thunk, - comptime unused_fmt_string: []const u8, - options: std.fmt.FormatOptions, - writer: anytype, - ) !void { - _ = thunk; - _ = unused_fmt_string; - _ = options; - _ = writer; - @compileError("do not format Thunk directly"); - } - - pub fn fmt(thunk: Thunk, elf_file: *Elf) std.fmt.Formatter(format2) { - return .{ .data = .{ - .thunk = thunk, - .elf_file = elf_file, - } }; - } - - const FormatContext = struct { - thunk: Thunk, - elf_file: *Elf, - }; - - fn format2( - ctx: FormatContext, - comptime unused_fmt_string: []const u8, - options: std.fmt.FormatOptions, - writer: anytype, - ) !void { - _ = options; - _ = unused_fmt_string; - const thunk = ctx.thunk; - const elf_file = ctx.elf_file; - try writer.print("@{x} : size({x})\n", .{ thunk.value, thunk.size(elf_file) }); - for (thunk.symbols.keys()) |ref| { - const sym = elf_file.symbol(ref).?; - try writer.print(" {} : {s} : @{x}\n", .{ ref, sym.name(elf_file), sym.value }); - } - } - - pub const Index = u32; -}; - -const aarch64 = struct { - fn isReachable(atom: *const Atom, rel: elf.Elf64_Rela, elf_file: *Elf) bool { - const r_type: elf.R_AARCH64 = @enumFromInt(rel.r_type()); - if (r_type != .CALL26 and r_type != .JUMP26) return true; - const file = atom.file(elf_file).?; - const target_ref = file.resolveSymbol(rel.r_sym(), elf_file); - const target = elf_file.symbol(target_ref).?; - if (target.flags.has_plt) return false; - if (atom.output_section_index != target.output_section_index) return false; - const target_atom = target.atom(elf_file).?; - if (target_atom.value == -1) return false; - const saddr = atom.address(elf_file) + @as(i64, @intCast(rel.r_offset)); - const taddr = target.address(.{}, elf_file); - _ = math.cast(i28, taddr + rel.r_addend - saddr) orelse return false; - return true; - } - - fn write(thunk: Thunk, elf_file: *Elf, writer: anytype) !void { - for (thunk.symbols.keys(), 0..) |ref, i| { - const sym = elf_file.symbol(ref).?; - const saddr = thunk.address(elf_file) + @as(i64, @intCast(i * trampoline_size)); - const taddr = sym.address(.{}, elf_file); - const pages = try util.calcNumberOfPages(saddr, taddr); - try writer.writeInt(u32, Instruction.adrp(.x16, pages).toU32(), .little); - const off: u12 = @truncate(@as(u64, @bitCast(taddr))); - try writer.writeInt(u32, Instruction.add(.x16, .x16, off, false).toU32(), .little); - try writer.writeInt(u32, Instruction.br(.x16).toU32(), .little); - } - } - - const trampoline_size = 3 * @sizeOf(u32); - - const util = @import("../aarch64.zig"); - const Instruction = util.Instruction; -}; - -const assert = std.debug.assert; -const elf = std.elf; -const log = std.log.scoped(.link); -const math = std.math; -const mem = std.mem; -const std = @import("std"); - -const Allocator = mem.Allocator; -const Atom = @import("Atom.zig"); -const Elf = @import("../Elf.zig"); -const Symbol = @import("Symbol.zig"); diff --git a/src/link/MachO.zig b/src/link/MachO.zig index fd77201739b0..27bfc9392ea6 100644 --- a/src/link/MachO.zig +++ b/src/link/MachO.zig @@ -64,10 +64,10 @@ stubs_helper: StubsHelperSection = .{}, objc_stubs: ObjcStubsSection = .{}, la_symbol_ptr: LaSymbolPtrSection = .{}, tlv_ptr: TlvPtrSection = .{}, -rebase: Rebase = .{}, -bind: Bind = .{}, -weak_bind: WeakBind = .{}, -lazy_bind: LazyBind = .{}, +rebase_section: Rebase = .{}, +bind_section: Bind = .{}, +weak_bind_section: WeakBind = .{}, +lazy_bind_section: LazyBind = .{}, export_trie: ExportTrie = .{}, unwind_info: UnwindInfo = .{}, data_in_code: DataInCode = .{}, @@ -324,10 +324,10 @@ pub fn deinit(self: *MachO) void { self.stubs.deinit(gpa); self.objc_stubs.deinit(gpa); self.tlv_ptr.deinit(gpa); - self.rebase.deinit(gpa); - self.bind.deinit(gpa); - self.weak_bind.deinit(gpa); - self.lazy_bind.deinit(gpa); + self.rebase_section.deinit(gpa); + self.bind_section.deinit(gpa); + self.weak_bind_section.deinit(gpa); + self.lazy_bind_section.deinit(gpa); self.export_trie.deinit(gpa); self.unwind_info.deinit(gpa); self.data_in_code.deinit(gpa); @@ -2005,7 +2005,7 @@ fn calcSectionSizeWorker(self: *MachO, sect_id: u8) void { fn createThunksWorker(self: *MachO, sect_id: u8) void { const tracy = trace(@src()); defer tracy.end(); - thunks.createThunks(sect_id, self) catch |err| { + self.createThunks(sect_id) catch |err| { const header = self.sections.items(.header)[sect_id]; self.reportUnexpectedError("failed to create thunks and calculate size of section '{s},{s}': {s}", .{ header.segName(), @@ -2562,7 +2562,7 @@ fn updateLazyBindSizeWorker(self: *MachO) void { defer tracy.end(); const doWork = struct { fn doWork(macho_file: *MachO) !void { - try macho_file.lazy_bind.updateSize(macho_file); + try macho_file.lazy_bind_section.updateSize(macho_file); const sect_id = macho_file.stubs_helper_sect_index.?; const out = &macho_file.sections.items(.out)[sect_id]; var stream = std.io.fixedBufferStream(out.items); @@ -2585,9 +2585,9 @@ pub fn updateLinkeditSizeWorker(self: *MachO, tag: enum { data_in_code, }) void { const res = switch (tag) { - .rebase => self.rebase.updateSize(self), - .bind => self.bind.updateSize(self), - .weak_bind => self.weak_bind.updateSize(self), + .rebase => self.rebase_section.updateSize(self), + .bind => self.bind_section.updateSize(self), + .weak_bind => self.weak_bind_section.updateSize(self), .export_trie => self.export_trie.updateSize(self), .data_in_code => self.data_in_code.updateSize(self), }; @@ -2640,13 +2640,13 @@ fn writeDyldInfo(self: *MachO) !void { var stream = std.io.fixedBufferStream(buffer); const writer = stream.writer(); - try self.rebase.write(writer); + try self.rebase_section.write(writer); try stream.seekTo(cmd.bind_off - base_off); - try self.bind.write(writer); + try self.bind_section.write(writer); try stream.seekTo(cmd.weak_bind_off - base_off); - try self.weak_bind.write(writer); + try self.weak_bind_section.write(writer); try stream.seekTo(cmd.lazy_bind_off - base_off); - try self.lazy_bind.write(writer); + try self.lazy_bind_section.write(writer); try stream.seekTo(cmd.export_off - base_off); try self.export_trie.write(writer); try self.base.file.?.pwriteAll(buffer, cmd.rebase_off); @@ -4602,7 +4602,6 @@ const load_commands = @import("MachO/load_commands.zig"); const relocatable = @import("MachO/relocatable.zig"); const tapi = @import("tapi.zig"); const target_util = @import("../target.zig"); -const thunks = @import("MachO/thunks.zig"); const trace = @import("../tracy.zig").trace; const synthetic = @import("MachO/synthetic.zig"); @@ -4641,7 +4640,7 @@ const StringTable = @import("StringTable.zig"); const StubsSection = synthetic.StubsSection; const StubsHelperSection = synthetic.StubsHelperSection; const Symbol = @import("MachO/Symbol.zig"); -const Thunk = thunks.Thunk; +const Thunk = @import("MachO/Thunk.zig"); const TlvPtrSection = synthetic.TlvPtrSection; const Value = @import("../Value.zig"); const UnwindInfo = @import("MachO/UnwindInfo.zig"); @@ -5292,3 +5291,96 @@ pub const KernE = enum(u32) { NOT_FOUND = 56, _, }; + +fn createThunks(macho_file: *MachO, sect_id: u8) !void { + const tracy = trace(@src()); + defer tracy.end(); + + const gpa = macho_file.base.comp.gpa; + const slice = macho_file.sections.slice(); + const header = &slice.items(.header)[sect_id]; + const thnks = &slice.items(.thunks)[sect_id]; + const atoms = slice.items(.atoms)[sect_id].items; + assert(atoms.len > 0); + + for (atoms) |ref| { + ref.getAtom(macho_file).?.value = @bitCast(@as(i64, -1)); + } + + var i: usize = 0; + while (i < atoms.len) { + const start = i; + const start_atom = atoms[start].getAtom(macho_file).?; + assert(start_atom.isAlive()); + start_atom.value = advanceSection(header, start_atom.size, start_atom.alignment); + i += 1; + + while (i < atoms.len and + header.size - start_atom.value < max_allowed_distance) : (i += 1) + { + const atom = atoms[i].getAtom(macho_file).?; + assert(atom.isAlive()); + atom.value = advanceSection(header, atom.size, atom.alignment); + } + + // Insert a thunk at the group end + const thunk_index = try macho_file.addThunk(); + const thunk = macho_file.getThunk(thunk_index); + thunk.out_n_sect = sect_id; + try thnks.append(gpa, thunk_index); + + // Scan relocs in the group and create trampolines for any unreachable callsite + try scanThunkRelocs(thunk_index, gpa, atoms[start..i], macho_file); + thunk.value = advanceSection(header, thunk.size(), .@"4"); + + log.debug("thunk({d}) : {}", .{ thunk_index, thunk.fmt(macho_file) }); + } +} + +fn advanceSection(sect: *macho.section_64, adv_size: u64, alignment: Atom.Alignment) u64 { + const offset = alignment.forward(sect.size); + const padding = offset - sect.size; + sect.size += padding + adv_size; + sect.@"align" = @max(sect.@"align", alignment.toLog2Units()); + return offset; +} + +fn scanThunkRelocs(thunk_index: Thunk.Index, gpa: Allocator, atoms: []const MachO.Ref, macho_file: *MachO) !void { + const tracy = trace(@src()); + defer tracy.end(); + + const thunk = macho_file.getThunk(thunk_index); + + for (atoms) |ref| { + const atom = ref.getAtom(macho_file).?; + log.debug("atom({d}) {s}", .{ atom.atom_index, atom.getName(macho_file) }); + for (atom.getRelocs(macho_file)) |rel| { + if (rel.type != .branch) continue; + if (isReachable(atom, rel, macho_file)) continue; + try thunk.symbols.put(gpa, rel.getTargetSymbolRef(atom.*, macho_file), {}); + } + atom.addExtra(.{ .thunk = thunk_index }, macho_file); + } +} + +fn isReachable(atom: *const Atom, rel: Relocation, macho_file: *MachO) bool { + const target = rel.getTargetSymbol(atom.*, macho_file); + if (target.getSectionFlags().stubs or target.getSectionFlags().objc_stubs) return false; + if (atom.out_n_sect != target.getOutputSectionIndex(macho_file)) return false; + const target_atom = target.getAtom(macho_file).?; + if (target_atom.value == @as(u64, @bitCast(@as(i64, -1)))) return false; + const saddr = @as(i64, @intCast(atom.getAddress(macho_file))) + @as(i64, @intCast(rel.offset - atom.off)); + const taddr: i64 = @intCast(rel.getTargetAddress(atom.*, macho_file)); + _ = math.cast(i28, taddr + rel.addend - saddr) orelse return false; + return true; +} + +/// Branch instruction has 26 bits immediate but is 4 byte aligned. +const jump_bits = @bitSizeOf(i28); +const max_distance = (1 << (jump_bits - 1)); + +/// A branch will need an extender if its target is larger than +/// `2^(jump_bits - 1) - margin` where margin is some arbitrary number. +/// mold uses 5MiB margin, while ld64 uses 4MiB margin. We will follow mold +/// and assume margin to be 5MiB. +const max_allowed_distance = max_distance - 0x500_000; diff --git a/src/link/MachO/Atom.zig b/src/link/MachO/Atom.zig index a0193c20be7b..d2a6a134974d 100644 --- a/src/link/MachO/Atom.zig +++ b/src/link/MachO/Atom.zig @@ -1220,6 +1220,6 @@ const MachO = @import("../MachO.zig"); const Object = @import("Object.zig"); const Relocation = @import("Relocation.zig"); const Symbol = @import("Symbol.zig"); -const Thunk = @import("thunks.zig").Thunk; +const Thunk = @import("Thunk.zig"); const UnwindInfo = @import("UnwindInfo.zig"); const dev = @import("../../dev.zig"); diff --git a/src/link/MachO/Thunk.zig b/src/link/MachO/Thunk.zig new file mode 100644 index 000000000000..4a76a408edec --- /dev/null +++ b/src/link/MachO/Thunk.zig @@ -0,0 +1,125 @@ +value: u64 = 0, +out_n_sect: u8 = 0, +symbols: std.AutoArrayHashMapUnmanaged(MachO.Ref, void) = .{}, +output_symtab_ctx: MachO.SymtabCtx = .{}, + +pub fn deinit(thunk: *Thunk, allocator: Allocator) void { + thunk.symbols.deinit(allocator); +} + +pub fn size(thunk: Thunk) usize { + return thunk.symbols.keys().len * trampoline_size; +} + +pub fn getAddress(thunk: Thunk, macho_file: *MachO) u64 { + const header = macho_file.sections.items(.header)[thunk.out_n_sect]; + return header.addr + thunk.value; +} + +pub fn getTargetAddress(thunk: Thunk, ref: MachO.Ref, macho_file: *MachO) u64 { + return thunk.getAddress(macho_file) + thunk.symbols.getIndex(ref).? * trampoline_size; +} + +pub fn write(thunk: Thunk, macho_file: *MachO, writer: anytype) !void { + for (thunk.symbols.keys(), 0..) |ref, i| { + const sym = ref.getSymbol(macho_file).?; + const saddr = thunk.getAddress(macho_file) + i * trampoline_size; + const taddr = sym.getAddress(.{}, macho_file); + const pages = try aarch64.calcNumberOfPages(@intCast(saddr), @intCast(taddr)); + try writer.writeInt(u32, aarch64.Instruction.adrp(.x16, pages).toU32(), .little); + const off: u12 = @truncate(taddr); + try writer.writeInt(u32, aarch64.Instruction.add(.x16, .x16, off, false).toU32(), .little); + try writer.writeInt(u32, aarch64.Instruction.br(.x16).toU32(), .little); + } +} + +pub fn calcSymtabSize(thunk: *Thunk, macho_file: *MachO) void { + thunk.output_symtab_ctx.nlocals = @as(u32, @intCast(thunk.symbols.keys().len)); + for (thunk.symbols.keys()) |ref| { + const sym = ref.getSymbol(macho_file).?; + thunk.output_symtab_ctx.strsize += @as(u32, @intCast(sym.getName(macho_file).len + "__thunk".len + 1)); + } +} + +pub fn writeSymtab(thunk: Thunk, macho_file: *MachO, ctx: anytype) void { + var n_strx = thunk.output_symtab_ctx.stroff; + for (thunk.symbols.keys(), thunk.output_symtab_ctx.ilocal..) |ref, ilocal| { + const sym = ref.getSymbol(macho_file).?; + const name = sym.getName(macho_file); + const out_sym = &ctx.symtab.items[ilocal]; + out_sym.n_strx = n_strx; + @memcpy(ctx.strtab.items[n_strx..][0..name.len], name); + n_strx += @intCast(name.len); + @memcpy(ctx.strtab.items[n_strx..][0.."__thunk".len], "__thunk"); + n_strx += @intCast("__thunk".len); + ctx.strtab.items[n_strx] = 0; + n_strx += 1; + out_sym.n_type = macho.N_SECT; + out_sym.n_sect = @intCast(thunk.out_n_sect + 1); + out_sym.n_value = @intCast(thunk.getTargetAddress(ref, macho_file)); + out_sym.n_desc = 0; + } +} + +pub fn format( + thunk: Thunk, + comptime unused_fmt_string: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, +) !void { + _ = thunk; + _ = unused_fmt_string; + _ = options; + _ = writer; + @compileError("do not format Thunk directly"); +} + +pub fn fmt(thunk: Thunk, macho_file: *MachO) std.fmt.Formatter(format2) { + return .{ .data = .{ + .thunk = thunk, + .macho_file = macho_file, + } }; +} + +const FormatContext = struct { + thunk: Thunk, + macho_file: *MachO, +}; + +fn format2( + ctx: FormatContext, + comptime unused_fmt_string: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, +) !void { + _ = options; + _ = unused_fmt_string; + const thunk = ctx.thunk; + const macho_file = ctx.macho_file; + try writer.print("@{x} : size({x})\n", .{ thunk.value, thunk.size() }); + for (thunk.symbols.keys()) |ref| { + const sym = ref.getSymbol(macho_file).?; + try writer.print(" {} : {s} : @{x}\n", .{ ref, sym.getName(macho_file), sym.value }); + } +} + +const trampoline_size = 3 * @sizeOf(u32); + +pub const Index = u32; + +const aarch64 = @import("../aarch64.zig"); +const assert = std.debug.assert; +const log = std.log.scoped(.link); +const macho = std.macho; +const math = std.math; +const mem = std.mem; +const std = @import("std"); +const trace = @import("../../tracy.zig").trace; + +const Allocator = mem.Allocator; +const Atom = @import("Atom.zig"); +const MachO = @import("../MachO.zig"); +const Relocation = @import("Relocation.zig"); +const Symbol = @import("Symbol.zig"); + +const Thunk = @This(); diff --git a/src/link/MachO/synthetic.zig b/src/link/MachO/synthetic.zig index 35f9d4553607..5c7ede387d08 100644 --- a/src/link/MachO/synthetic.zig +++ b/src/link/MachO/synthetic.zig @@ -204,7 +204,7 @@ pub const StubsHelperSection = struct { for (macho_file.stubs.symbols.items) |ref| { const sym = ref.getSymbol(macho_file).?; if (sym.flags.weak) continue; - const offset = macho_file.lazy_bind.offsets.items[idx]; + const offset = macho_file.lazy_bind_section.offsets.items[idx]; const source: i64 = @intCast(sect.addr + preamble_size + entry_size * idx); const target: i64 = @intCast(sect.addr); switch (cpu_arch) { diff --git a/src/link/MachO/thunks.zig b/src/link/MachO/thunks.zig deleted file mode 100644 index 4248785c54c6..000000000000 --- a/src/link/MachO/thunks.zig +++ /dev/null @@ -1,218 +0,0 @@ -pub fn createThunks(sect_id: u8, macho_file: *MachO) !void { - const tracy = trace(@src()); - defer tracy.end(); - - const gpa = macho_file.base.comp.gpa; - const slice = macho_file.sections.slice(); - const header = &slice.items(.header)[sect_id]; - const thnks = &slice.items(.thunks)[sect_id]; - const atoms = slice.items(.atoms)[sect_id].items; - assert(atoms.len > 0); - - for (atoms) |ref| { - ref.getAtom(macho_file).?.value = @bitCast(@as(i64, -1)); - } - - var i: usize = 0; - while (i < atoms.len) { - const start = i; - const start_atom = atoms[start].getAtom(macho_file).?; - assert(start_atom.isAlive()); - start_atom.value = advance(header, start_atom.size, start_atom.alignment); - i += 1; - - while (i < atoms.len and - header.size - start_atom.value < max_allowed_distance) : (i += 1) - { - const atom = atoms[i].getAtom(macho_file).?; - assert(atom.isAlive()); - atom.value = advance(header, atom.size, atom.alignment); - } - - // Insert a thunk at the group end - const thunk_index = try macho_file.addThunk(); - const thunk = macho_file.getThunk(thunk_index); - thunk.out_n_sect = sect_id; - try thnks.append(gpa, thunk_index); - - // Scan relocs in the group and create trampolines for any unreachable callsite - try scanRelocs(thunk_index, gpa, atoms[start..i], macho_file); - thunk.value = advance(header, thunk.size(), .@"4"); - - log.debug("thunk({d}) : {}", .{ thunk_index, thunk.fmt(macho_file) }); - } -} - -fn advance(sect: *macho.section_64, size: u64, alignment: Atom.Alignment) u64 { - const offset = alignment.forward(sect.size); - const padding = offset - sect.size; - sect.size += padding + size; - sect.@"align" = @max(sect.@"align", alignment.toLog2Units()); - return offset; -} - -fn scanRelocs(thunk_index: Thunk.Index, gpa: Allocator, atoms: []const MachO.Ref, macho_file: *MachO) !void { - const tracy = trace(@src()); - defer tracy.end(); - - const thunk = macho_file.getThunk(thunk_index); - - for (atoms) |ref| { - const atom = ref.getAtom(macho_file).?; - log.debug("atom({d}) {s}", .{ atom.atom_index, atom.getName(macho_file) }); - for (atom.getRelocs(macho_file)) |rel| { - if (rel.type != .branch) continue; - if (isReachable(atom, rel, macho_file)) continue; - try thunk.symbols.put(gpa, rel.getTargetSymbolRef(atom.*, macho_file), {}); - } - atom.addExtra(.{ .thunk = thunk_index }, macho_file); - } -} - -fn isReachable(atom: *const Atom, rel: Relocation, macho_file: *MachO) bool { - const target = rel.getTargetSymbol(atom.*, macho_file); - if (target.getSectionFlags().stubs or target.getSectionFlags().objc_stubs) return false; - if (atom.out_n_sect != target.getOutputSectionIndex(macho_file)) return false; - const target_atom = target.getAtom(macho_file).?; - if (target_atom.value == @as(u64, @bitCast(@as(i64, -1)))) return false; - const saddr = @as(i64, @intCast(atom.getAddress(macho_file))) + @as(i64, @intCast(rel.offset - atom.off)); - const taddr: i64 = @intCast(rel.getTargetAddress(atom.*, macho_file)); - _ = math.cast(i28, taddr + rel.addend - saddr) orelse return false; - return true; -} - -pub const Thunk = struct { - value: u64 = 0, - out_n_sect: u8 = 0, - symbols: std.AutoArrayHashMapUnmanaged(MachO.Ref, void) = .{}, - output_symtab_ctx: MachO.SymtabCtx = .{}, - - pub fn deinit(thunk: *Thunk, allocator: Allocator) void { - thunk.symbols.deinit(allocator); - } - - pub fn size(thunk: Thunk) usize { - return thunk.symbols.keys().len * trampoline_size; - } - - pub fn getAddress(thunk: Thunk, macho_file: *MachO) u64 { - const header = macho_file.sections.items(.header)[thunk.out_n_sect]; - return header.addr + thunk.value; - } - - pub fn getTargetAddress(thunk: Thunk, ref: MachO.Ref, macho_file: *MachO) u64 { - return thunk.getAddress(macho_file) + thunk.symbols.getIndex(ref).? * trampoline_size; - } - - pub fn write(thunk: Thunk, macho_file: *MachO, writer: anytype) !void { - for (thunk.symbols.keys(), 0..) |ref, i| { - const sym = ref.getSymbol(macho_file).?; - const saddr = thunk.getAddress(macho_file) + i * trampoline_size; - const taddr = sym.getAddress(.{}, macho_file); - const pages = try aarch64.calcNumberOfPages(@intCast(saddr), @intCast(taddr)); - try writer.writeInt(u32, aarch64.Instruction.adrp(.x16, pages).toU32(), .little); - const off: u12 = @truncate(taddr); - try writer.writeInt(u32, aarch64.Instruction.add(.x16, .x16, off, false).toU32(), .little); - try writer.writeInt(u32, aarch64.Instruction.br(.x16).toU32(), .little); - } - } - - pub fn calcSymtabSize(thunk: *Thunk, macho_file: *MachO) void { - thunk.output_symtab_ctx.nlocals = @as(u32, @intCast(thunk.symbols.keys().len)); - for (thunk.symbols.keys()) |ref| { - const sym = ref.getSymbol(macho_file).?; - thunk.output_symtab_ctx.strsize += @as(u32, @intCast(sym.getName(macho_file).len + "__thunk".len + 1)); - } - } - - pub fn writeSymtab(thunk: Thunk, macho_file: *MachO, ctx: anytype) void { - var n_strx = thunk.output_symtab_ctx.stroff; - for (thunk.symbols.keys(), thunk.output_symtab_ctx.ilocal..) |ref, ilocal| { - const sym = ref.getSymbol(macho_file).?; - const name = sym.getName(macho_file); - const out_sym = &ctx.symtab.items[ilocal]; - out_sym.n_strx = n_strx; - @memcpy(ctx.strtab.items[n_strx..][0..name.len], name); - n_strx += @intCast(name.len); - @memcpy(ctx.strtab.items[n_strx..][0.."__thunk".len], "__thunk"); - n_strx += @intCast("__thunk".len); - ctx.strtab.items[n_strx] = 0; - n_strx += 1; - out_sym.n_type = macho.N_SECT; - out_sym.n_sect = @intCast(thunk.out_n_sect + 1); - out_sym.n_value = @intCast(thunk.getTargetAddress(ref, macho_file)); - out_sym.n_desc = 0; - } - } - - pub fn format( - thunk: Thunk, - comptime unused_fmt_string: []const u8, - options: std.fmt.FormatOptions, - writer: anytype, - ) !void { - _ = thunk; - _ = unused_fmt_string; - _ = options; - _ = writer; - @compileError("do not format Thunk directly"); - } - - pub fn fmt(thunk: Thunk, macho_file: *MachO) std.fmt.Formatter(format2) { - return .{ .data = .{ - .thunk = thunk, - .macho_file = macho_file, - } }; - } - - const FormatContext = struct { - thunk: Thunk, - macho_file: *MachO, - }; - - fn format2( - ctx: FormatContext, - comptime unused_fmt_string: []const u8, - options: std.fmt.FormatOptions, - writer: anytype, - ) !void { - _ = options; - _ = unused_fmt_string; - const thunk = ctx.thunk; - const macho_file = ctx.macho_file; - try writer.print("@{x} : size({x})\n", .{ thunk.value, thunk.size() }); - for (thunk.symbols.keys()) |ref| { - const sym = ref.getSymbol(macho_file).?; - try writer.print(" {} : {s} : @{x}\n", .{ ref, sym.getName(macho_file), sym.value }); - } - } - - const trampoline_size = 3 * @sizeOf(u32); - - pub const Index = u32; -}; - -/// Branch instruction has 26 bits immediate but is 4 byte aligned. -const jump_bits = @bitSizeOf(i28); -const max_distance = (1 << (jump_bits - 1)); - -/// A branch will need an extender if its target is larger than -/// `2^(jump_bits - 1) - margin` where margin is some arbitrary number. -/// mold uses 5MiB margin, while ld64 uses 4MiB margin. We will follow mold -/// and assume margin to be 5MiB. -const max_allowed_distance = max_distance - 0x500_000; - -const aarch64 = @import("../aarch64.zig"); -const assert = std.debug.assert; -const log = std.log.scoped(.link); -const macho = std.macho; -const math = std.math; -const mem = std.mem; -const std = @import("std"); -const trace = @import("../../tracy.zig").trace; - -const Allocator = mem.Allocator; -const Atom = @import("Atom.zig"); -const MachO = @import("../MachO.zig"); -const Relocation = @import("Relocation.zig"); -const Symbol = @import("Symbol.zig"); diff --git a/test/behavior/call.zig b/test/behavior/call.zig index 3995a24faee9..5b94a4b07d23 100644 --- a/test/behavior/call.zig +++ b/test/behavior/call.zig @@ -549,7 +549,7 @@ test "call function pointer in comptime field" { auto: [max_len]u8 = undefined, offset: u64 = 0, - comptime capacity: *const fn () u64 = capacity, + comptime capacityFn: *const fn () u64 = capacity, const max_len: u64 = 32; @@ -558,9 +558,9 @@ test "call function pointer in comptime field" { } }; - const a: Auto = .{ .offset = 16, .capacity = Auto.capacity }; - try std.testing.expect(a.capacity() == 32); - try std.testing.expect((a.capacity)() == 32); + const a: Auto = .{ .offset = 16, .capacityFn = Auto.capacity }; + try std.testing.expect(a.capacityFn() == 32); + try std.testing.expect((a.capacityFn)() == 32); } test "generic function pointer can be called" { diff --git a/test/behavior/packed-union.zig b/test/behavior/packed-union.zig index aa4f98b783b5..701c0484a41e 100644 --- a/test/behavior/packed-union.zig +++ b/test/behavior/packed-union.zig @@ -149,12 +149,12 @@ test "packed union initialized with a runtime value" { value: u63, fields: Fields, - fn value() i64 { + fn getValue() i64 { return 1341; } }; - const timestamp: i64 = ID.value(); + const timestamp: i64 = ID.getValue(); const id = ID{ .fields = Fields{ .timestamp = @as(u50, @intCast(timestamp)), .random_bits = 420, diff --git a/test/behavior/struct.zig b/test/behavior/struct.zig index ff70c1450563..44f035f46f00 100644 --- a/test/behavior/struct.zig +++ b/test/behavior/struct.zig @@ -1529,15 +1529,15 @@ test "function pointer in struct returns the struct" { const A = struct { const A = @This(); - f: *const fn () A, + ptr: *const fn () A, fn f() A { - return .{ .f = f }; + return .{ .ptr = f }; } }; var a = A.f(); _ = &a; - try expect(a.f == A.f); + try expect(a.ptr == A.f); } test "no dependency loop on optional field wrapped in generic function" { diff --git a/test/behavior/union.zig b/test/behavior/union.zig index 13d8862dea9a..a952e9b9d31a 100644 --- a/test/behavior/union.zig +++ b/test/behavior/union.zig @@ -155,18 +155,6 @@ test "unions embedded in aggregate types" { } } -test "access a member of tagged union with conflicting enum tag name" { - const Bar = union(enum) { - A: A, - B: B, - - const A = u8; - const B = void; - }; - - comptime assert(Bar.A == u8); -} - test "constant tagged union with payload" { if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; @@ -1417,10 +1405,10 @@ test "union field ptr - zero sized payload" { const U = union { foo: void, bar: void, - fn bar(_: *void) void {} + fn qux(_: *void) void {} }; var u: U = .{ .foo = {} }; - U.bar(&u.foo); + U.qux(&u.foo); } test "union field ptr - zero sized field" { @@ -1431,10 +1419,10 @@ test "union field ptr - zero sized field" { const U = union { foo: void, bar: u32, - fn bar(_: *void) void {} + fn qux(_: *void) void {} }; var u: U = .{ .foo = {} }; - U.bar(&u.foo); + U.qux(&u.foo); } test "packed union in packed struct" { diff --git a/test/cases/compile_errors/colliding_invalid_top_level_functions.zig b/test/cases/compile_errors/colliding_invalid_top_level_functions.zig index 8a2adb2f0778..e63810c986ff 100644 --- a/test/cases/compile_errors/colliding_invalid_top_level_functions.zig +++ b/test/cases/compile_errors/colliding_invalid_top_level_functions.zig @@ -5,10 +5,9 @@ export fn entry() usize { } // error -// backend=stage2 -// target=native // -// :2:1: error: redeclaration of 'func' -// :1:1: note: other declaration here +// :1:4: error: duplicate struct member name 'func' +// :2:4: note: duplicate name here +// :1:1: note: struct declared here // :1:11: error: use of undeclared identifier 'bogus' // :2:11: error: use of undeclared identifier 'bogus' diff --git a/test/cases/compile_errors/decl_shadows_local.zig b/test/cases/compile_errors/decl_shadows_local.zig index 44066ab659be..eeb69a495455 100644 --- a/test/cases/compile_errors/decl_shadows_local.zig +++ b/test/cases/compile_errors/decl_shadows_local.zig @@ -2,6 +2,7 @@ fn foo(a: usize) void { struct { const a = 1; }; + _ = a; } fn bar(a: usize) void { struct { @@ -18,5 +19,5 @@ fn bar(a: usize) void { // // :3:15: error: declaration 'a' shadows function parameter from outer scope // :1:8: note: previous declaration here -// :9:19: error: declaration 'a' shadows function parameter from outer scope -// :6:8: note: previous declaration here +// :10:19: error: declaration 'a' shadows function parameter from outer scope +// :7:8: note: previous declaration here diff --git a/test/cases/compile_errors/duplicate_enum_field.zig b/test/cases/compile_errors/duplicate_enum_field.zig index 02738f1b3743..b3a4f4495b40 100644 --- a/test/cases/compile_errors/duplicate_enum_field.zig +++ b/test/cases/compile_errors/duplicate_enum_field.zig @@ -12,6 +12,6 @@ export fn entry() void { // backend=stage2 // target=native // -// :2:5: error: duplicate enum field name -// :3:5: note: duplicate field here +// :2:5: error: duplicate enum member name 'Bar' +// :3:5: note: duplicate name here // :1:13: note: enum declared here diff --git a/test/cases/compile_errors/duplicate_struct_field.zig b/test/cases/compile_errors/duplicate_struct_field.zig index 954ed24e920f..bb1ba2644573 100644 --- a/test/cases/compile_errors/duplicate_struct_field.zig +++ b/test/cases/compile_errors/duplicate_struct_field.zig @@ -24,10 +24,10 @@ export fn b() void { // backend=stage2 // target=native // -// :2:5: error: duplicate struct field name -// :3:5: note: duplicate field here +// :2:5: error: duplicate struct member name 'Bar' +// :3:5: note: duplicate name here // :1:13: note: struct declared here -// :7:5: error: duplicate struct field name -// :9:5: note: duplicate field here -// :10:5: note: duplicate field here +// :7:5: error: duplicate struct member name 'a' +// :9:5: note: duplicate name here +// :10:5: note: duplicate name here // :6:11: note: struct declared here diff --git a/test/cases/compile_errors/duplicate_union_field.zig b/test/cases/compile_errors/duplicate_union_field.zig index b57842c1f798..912296ec2e7d 100644 --- a/test/cases/compile_errors/duplicate_union_field.zig +++ b/test/cases/compile_errors/duplicate_union_field.zig @@ -8,9 +8,7 @@ export fn entry() void { } // error -// backend=stage2 -// target=native // -// :2:5: error: duplicate union field name -// :3:5: note: duplicate field here +// :2:5: error: duplicate union member name 'Bar' +// :3:5: note: duplicate name here // :1:13: note: union declared here diff --git a/test/cases/compile_errors/error_in_struct_initializer_doesnt_crash_the_compiler.zig b/test/cases/compile_errors/error_in_struct_initializer_doesnt_crash_the_compiler.zig index ea799c561aaf..b880dd5992e5 100644 --- a/test/cases/compile_errors/error_in_struct_initializer_doesnt_crash_the_compiler.zig +++ b/test/cases/compile_errors/error_in_struct_initializer_doesnt_crash_the_compiler.zig @@ -8,9 +8,7 @@ pub export fn entry() void { } // error -// backend=stage2 -// target=native // -// :3:9: error: duplicate struct field name -// :4:9: note: duplicate field here +// :3:9: error: duplicate struct member name 'e' +// :4:9: note: duplicate name here // :2:22: note: struct declared here diff --git a/test/cases/compile_errors/field_decl_name_conflict.zig b/test/cases/compile_errors/field_decl_name_conflict.zig new file mode 100644 index 000000000000..b71eb5b11904 --- /dev/null +++ b/test/cases/compile_errors/field_decl_name_conflict.zig @@ -0,0 +1,18 @@ +foo: u32, +bar: u32, +qux: u32, + +const foo = 123; + +var bar: u8 = undefined; +fn bar() void {} + +// error +// +// :1:1: error: duplicate struct member name 'foo' +// :5:7: note: duplicate name here +// :1:1: note: struct declared here +// :2:1: error: duplicate struct member name 'bar' +// :7:5: note: duplicate name here +// :8:4: note: duplicate name here +// :1:1: note: struct declared here diff --git a/test/cases/compile_errors/invalid_duplicate_test_decl_name.zig b/test/cases/compile_errors/invalid_duplicate_test_decl_name.zig index 2dd330912aa0..0e59795993f6 100644 --- a/test/cases/compile_errors/invalid_duplicate_test_decl_name.zig +++ b/test/cases/compile_errors/invalid_duplicate_test_decl_name.zig @@ -6,5 +6,6 @@ test "thingy" {} // target=native // is_test=true // -// :2:1: error: duplicate test name 'thingy' -// :1:1: note: other test here +// :1:6: error: duplicate test name 'thingy' +// :2:6: note: duplicate test here +// :1:1: note: struct declared here diff --git a/test/cases/compile_errors/invalid_store_to_comptime_field.zig b/test/cases/compile_errors/invalid_store_to_comptime_field.zig index f3082b06a96b..86ec05bf688a 100644 --- a/test/cases/compile_errors/invalid_store_to_comptime_field.zig +++ b/test/cases/compile_errors/invalid_store_to_comptime_field.zig @@ -25,21 +25,21 @@ pub export fn entry3() void { const U = struct { comptime foo: u32 = 1, bar: u32, - fn foo(x: @This()) void { + fn qux(x: @This()) void { _ = x; } }; - _ = U.foo(U{ .foo = 2, .bar = 2 }); + _ = U.qux(U{ .foo = 2, .bar = 2 }); } pub export fn entry4() void { const U = struct { comptime foo: u32 = 1, bar: u32, - fn foo(x: @This()) void { + fn qux(x: @This()) void { _ = x; } }; - _ = U.foo(.{ .foo = 2, .bar = 2 }); + _ = U.qux(.{ .foo = 2, .bar = 2 }); } pub export fn entry5() void { comptime var y = .{ 1, 2 }; diff --git a/test/cases/compile_errors/multiple_function_definitions.zig b/test/cases/compile_errors/multiple_function_definitions.zig index 134daaeaa4f6..63522ca40d9c 100644 --- a/test/cases/compile_errors/multiple_function_definitions.zig +++ b/test/cases/compile_errors/multiple_function_definitions.zig @@ -5,8 +5,7 @@ export fn entry() void { } // error -// backend=stage2 -// target=native // -// :2:1: error: redeclaration of 'a' -// :1:1: note: other declaration here +// :1:4: error: duplicate struct member name 'a' +// :2:4: note: duplicate name here +// :1:1: note: struct declared here diff --git a/test/cases/compile_errors/redefinition_of_enums.zig b/test/cases/compile_errors/redefinition_of_enums.zig index 34d5efe8df86..0ccc7ec8ddd4 100644 --- a/test/cases/compile_errors/redefinition_of_enums.zig +++ b/test/cases/compile_errors/redefinition_of_enums.zig @@ -5,5 +5,6 @@ const A = enum { x }; // backend=stage2 // target=native // -// :2:1: error: redeclaration of 'A' -// :1:1: note: other declaration here +// :1:7: error: duplicate struct member name 'A' +// :2:7: note: duplicate name here +// :1:1: note: struct declared here diff --git a/test/cases/compile_errors/redefinition_of_global_variables.zig b/test/cases/compile_errors/redefinition_of_global_variables.zig index 6f4ed225f791..9c224a30a91c 100644 --- a/test/cases/compile_errors/redefinition_of_global_variables.zig +++ b/test/cases/compile_errors/redefinition_of_global_variables.zig @@ -5,5 +5,6 @@ var a: i32 = 2; // backend=stage2 // target=native // -// :2:1: error: redeclaration of 'a' -// :1:1: note: other declaration here +// :1:5: error: duplicate struct member name 'a' +// :2:5: note: duplicate name here +// :1:1: note: struct declared here diff --git a/test/cases/compile_errors/redefinition_of_struct.zig b/test/cases/compile_errors/redefinition_of_struct.zig index 22852966dbc2..da7b2fa4dd07 100644 --- a/test/cases/compile_errors/redefinition_of_struct.zig +++ b/test/cases/compile_errors/redefinition_of_struct.zig @@ -5,5 +5,6 @@ const A = struct { y: i32 }; // backend=stage2 // target=native // -// :2:1: error: redeclaration of 'A' -// :1:1: note: other declaration here +// :1:7: error: duplicate struct member name 'A' +// :2:7: note: duplicate name here +// :1:1: note: struct declared here diff --git a/test/cases/compile_errors/struct_duplicate_field_name.zig b/test/cases/compile_errors/struct_duplicate_field_name.zig index 057083c3cb57..207b40daf394 100644 --- a/test/cases/compile_errors/struct_duplicate_field_name.zig +++ b/test/cases/compile_errors/struct_duplicate_field_name.zig @@ -11,6 +11,6 @@ export fn entry() void { // error // target=native // -// :2:5: error: duplicate struct field name -// :3:5: note: duplicate field here +// :2:5: error: duplicate struct member name 'foo' +// :3:5: note: duplicate name here // :1:11: note: struct declared here diff --git a/test/cases/compile_errors/union_duplicate_enum_field.zig b/test/cases/compile_errors/union_duplicate_enum_field.zig index 21c307755be0..3a350f923f9f 100644 --- a/test/cases/compile_errors/union_duplicate_enum_field.zig +++ b/test/cases/compile_errors/union_duplicate_enum_field.zig @@ -12,6 +12,6 @@ export fn foo() void { // error // target=native // -// :3:5: error: duplicate union field name -// :4:5: note: duplicate field here +// :3:5: error: duplicate union member name 'a' +// :4:5: note: duplicate name here // :2:11: note: union declared here diff --git a/test/cases/compile_errors/union_duplicate_field_definition.zig b/test/cases/compile_errors/union_duplicate_field_definition.zig index e0866964eb36..4fca2a7b362b 100644 --- a/test/cases/compile_errors/union_duplicate_field_definition.zig +++ b/test/cases/compile_errors/union_duplicate_field_definition.zig @@ -11,6 +11,6 @@ export fn entry() void { // error // target=native // -// :2:5: error: duplicate union field name -// :3:5: note: duplicate field here +// :2:5: error: duplicate union member name 'foo' +// :3:5: note: duplicate name here // :1:11: note: union declared here diff --git a/test/cases/function_redeclaration.zig b/test/cases/function_redeclaration.zig index b6cbf664a9fd..2b8dc4c15dd5 100644 --- a/test/cases/function_redeclaration.zig +++ b/test/cases/function_redeclaration.zig @@ -8,7 +8,8 @@ fn foo() void { // error // -// :3:1: error: redeclaration of 'entry' -// :2:1: note: other declaration here +// :2:4: error: duplicate struct member name 'entry' +// :3:4: note: duplicate name here +// :2:1: note: struct declared here // :6:9: error: local variable shadows declaration of 'foo' // :5:1: note: declared here diff --git a/test/cases/global_variable_redeclaration.zig b/test/cases/global_variable_redeclaration.zig index 9a0d5939fbff..3970294b0d63 100644 --- a/test/cases/global_variable_redeclaration.zig +++ b/test/cases/global_variable_redeclaration.zig @@ -4,5 +4,6 @@ var foo = true; // error // -// :3:1: error: redeclaration of 'foo' -// :2:1: note: other declaration here +// :2:5: error: duplicate struct member name 'foo' +// :3:5: note: duplicate name here +// :2:1: note: struct declared here diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 07ad178859db..447984d2779a 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -92,7 +92,7 @@ pub fn addCases(ctx: *Cases, b: *std.Build) !void { \\const a = @import("a.zig"); \\ \\export fn entry() void { - \\ _ = a.S.foo(a.S{ .foo = 2, .bar = 2 }); + \\ _ = a.S.qux(a.S{ .foo = 2, .bar = 2 }); \\} , &[_][]const u8{ ":4:23: error: value stored in comptime field does not match the default value of the field", @@ -102,7 +102,7 @@ pub fn addCases(ctx: *Cases, b: *std.Build) !void { \\pub const S = struct { \\ comptime foo: u32 = 1, \\ bar: u32, - \\ pub fn foo(x: @This()) void { + \\ pub fn qux(x: @This()) void { \\ _ = x; \\ } \\};