authorgravatar for luuk@degram.devLuuk de Gram <luuk@degram.dev> 2023-02-01 18:55:35+01:00
committergravatar for luuk@degram.devLuuk de Gram <luuk@degram.dev> 2023-02-01 19:10:56+01:00
log46f54b23ae604c3f99f51ca719d9085530f6b59c
tree66547a2f4b33e876afb0b29ea6799795959699fb
parent1aa0f8aa2f382fb56639ea6833a62c4b8b031247
signature Commit is signed but in an unrecognized format.

link: make Wasm atoms fully owned by the linker


10 files changed, 354 insertions(+), 327 deletions(-)

src/Module.zig+3-3
......@@ -5266,7 +5266,7 @@ pub fn clearDecl(
52665266 .macho => .{ .macho = {} },
52675267 .plan9 => .{ .plan9 = {} },
52685268 .c => .{ .c = {} },
5269 .wasm => .{ .wasm = link.File.Wasm.DeclBlock.empty },
5269 .wasm => .{ .wasm = {} },
52705270 .spirv => .{ .spirv = {} },
52715271 .nvptx => .{ .nvptx = {} },
52725272 };
......@@ -5374,7 +5374,7 @@ fn deleteDeclExports(mod: *Module, decl_index: Decl.Index) Allocator.Error!void
53745374 try macho.deleteDeclExport(decl_index, exp.options.name);
53755375 }
53765376 if (mod.comp.bin_file.cast(link.File.Wasm)) |wasm| {
5377 wasm.deleteExport(exp.link.wasm);
5377 wasm.deleteDeclExport(decl_index);
53785378 }
53795379 if (mod.comp.bin_file.cast(link.File.Coff)) |coff| {
53805380 coff.deleteDeclExport(decl_index, exp.options.name);
......@@ -5686,7 +5686,7 @@ pub fn allocateNewDecl(
56865686 .macho => .{ .macho = {} },
56875687 .plan9 => .{ .plan9 = {} },
56885688 .c => .{ .c = {} },
5689 .wasm => .{ .wasm = link.File.Wasm.DeclBlock.empty },
5689 .wasm => .{ .wasm = {} },
56905690 .spirv => .{ .spirv = {} },
56915691 .nvptx => .{ .nvptx = {} },
56925692 },
src/Sema.zig+1-1
......@@ -5570,7 +5570,7 @@ pub fn analyzeExport(
55705570 .macho => .{ .macho = {} },
55715571 .plan9 => .{ .plan9 = {} },
55725572 .c => .{ .c = {} },
5573 .wasm => .{ .wasm = .{} },
5573 .wasm => .{ .wasm = {} },
55745574 .spirv => .{ .spirv = {} },
55755575 .nvptx => .{ .nvptx = {} },
55765576 },
src/arch/wasm/CodeGen.zig+15-15
......@@ -1269,10 +1269,10 @@ fn genFunc(func: *CodeGen) InnerError!void {
12691269
12701270 var emit: Emit = .{
12711271 .mir = mir,
1272 .bin_file = &func.bin_file.base,
1272 .bin_file = func.bin_file,
12731273 .code = func.code,
12741274 .locals = func.locals.items,
1275 .decl = func.decl,
1275 .decl_index = func.decl_index,
12761276 .dbg_output = func.debug_output,
12771277 .prev_di_line = 0,
12781278 .prev_di_column = 0,
......@@ -2115,21 +2115,20 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
21152115 const fn_info = fn_ty.fnInfo();
21162116 const first_param_sret = firstParamSRet(fn_info.cc, fn_info.return_type, func.target);
21172117
2118 const callee: ?*Decl = blk: {
2118 const callee: ?Decl.Index = blk: {
21192119 const func_val = func.air.value(pl_op.operand) orelse break :blk null;
21202120 const module = func.bin_file.base.options.module.?;
21212121
21222122 if (func_val.castTag(.function)) |function| {
2123 const decl = module.declPtr(function.data.owner_decl);
2124 try decl.link.wasm.ensureInitialized(func.bin_file);
2125 break :blk decl;
2123 _ = try func.bin_file.getOrCreateAtomForDecl(function.data.owner_decl);
2124 break :blk function.data.owner_decl;
21262125 } else if (func_val.castTag(.extern_fn)) |extern_fn| {
21272126 const ext_decl = module.declPtr(extern_fn.data.owner_decl);
21282127 const ext_info = ext_decl.ty.fnInfo();
21292128 var func_type = try genFunctype(func.gpa, ext_info.cc, ext_info.param_types, ext_info.return_type, func.target);
21302129 defer func_type.deinit(func.gpa);
2131 const atom = &ext_decl.link.wasm;
2132 try atom.ensureInitialized(func.bin_file);
2130 const atom_index = try func.bin_file.getOrCreateAtomForDecl(extern_fn.data.owner_decl);
2131 const atom = func.bin_file.getAtomPtr(atom_index);
21332132 ext_decl.fn_link.wasm.type_index = try func.bin_file.putOrGetFuncType(func_type);
21342133 try func.bin_file.addOrUpdateImport(
21352134 mem.sliceTo(ext_decl.name, 0),
......@@ -2137,11 +2136,10 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
21372136 ext_decl.getExternFn().?.lib_name,
21382137 ext_decl.fn_link.wasm.type_index,
21392138 );
2140 break :blk ext_decl;
2139 break :blk extern_fn.data.owner_decl;
21412140 } else if (func_val.castTag(.decl_ref)) |decl_ref| {
2142 const decl = module.declPtr(decl_ref.data);
2143 try decl.link.wasm.ensureInitialized(func.bin_file);
2144 break :blk decl;
2141 _ = try func.bin_file.getOrCreateAtomForDecl(decl_ref.data);
2142 break :blk decl_ref.data;
21452143 }
21462144 return func.fail("Expected a function, but instead found type '{}'", .{func_val.tag()});
21472145 };
......@@ -2162,7 +2160,8 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
21622160 }
21632161
21642162 if (callee) |direct| {
2165 try func.addLabel(.call, direct.link.wasm.sym_index);
2163 const atom_index = func.bin_file.decls.get(direct).?;
2164 try func.addLabel(.call, func.bin_file.getAtom(atom_index).sym_index);
21662165 } else {
21672166 // in this case we call a function pointer
21682167 // so load its value onto the stack
......@@ -2758,9 +2757,10 @@ fn lowerDeclRefValue(func: *CodeGen, tv: TypedValue, decl_index: Module.Decl.Ind
27582757 }
27592758
27602759 module.markDeclAlive(decl);
2761 try decl.link.wasm.ensureInitialized(func.bin_file);
2760 const atom_index = try func.bin_file.getOrCreateAtomForDecl(decl_index);
2761 const atom = func.bin_file.getAtom(atom_index);
27622762
2763 const target_sym_index = decl.link.wasm.sym_index;
2763 const target_sym_index = atom.sym_index;
27642764 if (decl.ty.zigTypeTag() == .Fn) {
27652765 try func.bin_file.addTableFunction(target_sym_index);
27662766 return WValue{ .function_index = target_sym_index };
src/arch/wasm/Emit.zig+18-11
......@@ -11,8 +11,8 @@ const leb128 = std.leb;
1111
1212/// Contains our list of instructions
1313mir: Mir,
14/// Reference to the file handler
15bin_file: *link.File,
14/// Reference to the Wasm module linker
15bin_file: *link.File.Wasm,
1616/// Possible error message. When set, the value is allocated and
1717/// must be freed manually.
1818error_msg: ?*Module.ErrorMsg = null,
......@@ -21,7 +21,7 @@ code: *std.ArrayList(u8),
2121/// List of allocated locals.
2222locals: []const u8,
2323/// The declaration that code is being generated for.
24decl: *Module.Decl,
24decl_index: Module.Decl.Index,
2525
2626// Debug information
2727/// Holds the debug information for this emission
......@@ -252,8 +252,8 @@ fn offset(self: Emit) u32 {
252252fn fail(emit: *Emit, comptime format: []const u8, args: anytype) InnerError {
253253 @setCold(true);
254254 std.debug.assert(emit.error_msg == null);
255 // TODO: Determine the source location.
256 emit.error_msg = try Module.ErrorMsg.create(emit.bin_file.allocator, emit.decl.srcLoc(), format, args);
255 const mod = emit.bin_file.base.options.module.?;
256 emit.error_msg = try Module.ErrorMsg.create(emit.bin_file.base.allocator, mod.declPtr(emit.decl_index).srcLoc(), format, args);
257257 return error.EmitFail;
258258}
259259
......@@ -304,8 +304,9 @@ fn emitGlobal(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) !void {
304304 const global_offset = emit.offset();
305305 try emit.code.appendSlice(&buf);
306306
307 // globals can have index 0 as it represents the stack pointer
308 try emit.decl.link.wasm.relocs.append(emit.bin_file.allocator, .{
307 const atom_index = emit.bin_file.decls.get(emit.decl_index).?;
308 const atom = emit.bin_file.getAtomPtr(atom_index);
309 try atom.relocs.append(emit.bin_file.base.allocator, .{
309310 .index = label,
310311 .offset = global_offset,
311312 .relocation_type = .R_WASM_GLOBAL_INDEX_LEB,
......@@ -361,7 +362,9 @@ fn emitCall(emit: *Emit, inst: Mir.Inst.Index) !void {
361362 try emit.code.appendSlice(&buf);
362363
363364 if (label != 0) {
364 try emit.decl.link.wasm.relocs.append(emit.bin_file.allocator, .{
365 const atom_index = emit.bin_file.decls.get(emit.decl_index).?;
366 const atom = emit.bin_file.getAtomPtr(atom_index);
367 try atom.relocs.append(emit.bin_file.base.allocator, .{
365368 .offset = call_offset,
366369 .index = label,
367370 .relocation_type = .R_WASM_FUNCTION_INDEX_LEB,
......@@ -387,7 +390,9 @@ fn emitFunctionIndex(emit: *Emit, inst: Mir.Inst.Index) !void {
387390 try emit.code.appendSlice(&buf);
388391
389392 if (symbol_index != 0) {
390 try emit.decl.link.wasm.relocs.append(emit.bin_file.allocator, .{
393 const atom_index = emit.bin_file.decls.get(emit.decl_index).?;
394 const atom = emit.bin_file.getAtomPtr(atom_index);
395 try atom.relocs.append(emit.bin_file.base.allocator, .{
391396 .offset = index_offset,
392397 .index = symbol_index,
393398 .relocation_type = .R_WASM_TABLE_INDEX_SLEB,
......@@ -399,7 +404,7 @@ fn emitMemAddress(emit: *Emit, inst: Mir.Inst.Index) !void {
399404 const extra_index = emit.mir.instructions.items(.data)[inst].payload;
400405 const mem = emit.mir.extraData(Mir.Memory, extra_index).data;
401406 const mem_offset = emit.offset() + 1;
402 const is_wasm32 = emit.bin_file.options.target.cpu.arch == .wasm32;
407 const is_wasm32 = emit.bin_file.base.options.target.cpu.arch == .wasm32;
403408 if (is_wasm32) {
404409 try emit.code.append(std.wasm.opcode(.i32_const));
405410 var buf: [5]u8 = undefined;
......@@ -413,7 +418,9 @@ fn emitMemAddress(emit: *Emit, inst: Mir.Inst.Index) !void {
413418 }
414419
415420 if (mem.pointer != 0) {
416 try emit.decl.link.wasm.relocs.append(emit.bin_file.allocator, .{
421 const atom_index = emit.bin_file.decls.get(emit.decl_index).?;
422 const atom = emit.bin_file.getAtomPtr(atom_index);
423 try atom.relocs.append(emit.bin_file.base.allocator, .{
417424 .offset = mem_offset,
418425 .index = mem.pointer,
419426 .relocation_type = if (is_wasm32) .R_WASM_MEMORY_ADDR_LEB else .R_WASM_MEMORY_ADDR_LEB64,
src/link.zig+2-2
......@@ -267,7 +267,7 @@ pub const File = struct {
267267 macho: void,
268268 plan9: void,
269269 c: void,
270 wasm: Wasm.DeclBlock,
270 wasm: void,
271271 spirv: void,
272272 nvptx: void,
273273 };
......@@ -289,7 +289,7 @@ pub const File = struct {
289289 macho: void,
290290 plan9: void,
291291 c: void,
292 wasm: Wasm.Export,
292 wasm: void,
293293 spirv: void,
294294 nvptx: void,
295295 };
src/link/Dwarf.zig+13-12
......@@ -1099,7 +1099,7 @@ pub fn commitDeclState(
10991099 },
11001100 .wasm => {
11011101 const wasm_file = self.bin_file.cast(File.Wasm).?;
1102 const debug_line = wasm_file.debug_line_atom.?.code;
1102 const debug_line = wasm_file.getAtomPtr(wasm_file.debug_line_atom.?).code;
11031103 writeDbgLineNopsBuffered(debug_line.items, src_fn.off, 0, &.{}, src_fn.len);
11041104 },
11051105 else => unreachable,
......@@ -1177,7 +1177,7 @@ pub fn commitDeclState(
11771177
11781178 .wasm => {
11791179 const wasm_file = self.bin_file.cast(File.Wasm).?;
1180 const atom = wasm_file.debug_line_atom.?;
1180 const atom = wasm_file.getAtomPtr(wasm_file.debug_line_atom.?);
11811181 const debug_line = &atom.code;
11821182 const segment_size = debug_line.items.len;
11831183 if (needed_size != segment_size) {
......@@ -1345,7 +1345,8 @@ fn updateDeclDebugInfoAllocation(self: *Dwarf, atom_index: Atom.Index, len: u32)
13451345 },
13461346 .wasm => {
13471347 const wasm_file = self.bin_file.cast(File.Wasm).?;
1348 const debug_info = &wasm_file.debug_info_atom.?.code;
1348 const debug_info_index = wasm_file.debug_info_atom.?;
1349 const debug_info = &wasm_file.getAtomPtr(debug_info_index).code;
13491350 try writeDbgInfoNopsToArrayList(gpa, debug_info, atom.off, 0, &.{0}, atom.len, false);
13501351 },
13511352 else => unreachable,
......@@ -1441,7 +1442,7 @@ fn writeDeclDebugInfo(self: *Dwarf, atom_index: Atom.Index, dbg_info_buf: []cons
14411442 .wasm => {
14421443 const wasm_file = self.bin_file.cast(File.Wasm).?;
14431444 const info_atom = wasm_file.debug_info_atom.?;
1444 const debug_info = &info_atom.code;
1445 const debug_info = &wasm_file.getAtomPtr(info_atom).code;
14451446 const segment_size = debug_info.items.len;
14461447 if (needed_size != segment_size) {
14471448 log.debug(" needed size does not equal allocated size: {d}", .{needed_size});
......@@ -1504,8 +1505,8 @@ pub fn updateDeclLineNumber(self: *Dwarf, module: *Module, decl_index: Module.De
15041505 .wasm => {
15051506 const wasm_file = self.bin_file.cast(File.Wasm).?;
15061507 const offset = atom.off + self.getRelocDbgLineOff();
1507 const atom_ = wasm_file.debug_line_atom.?;
1508 mem.copy(u8, atom_.code.items[offset..], &data);
1508 const line_atom_index = wasm_file.debug_line_atom.?;
1509 mem.copy(u8, wasm_file.getAtomPtr(line_atom_index).code.items[offset..], &data);
15091510 },
15101511 else => unreachable,
15111512 }
......@@ -1722,7 +1723,7 @@ pub fn writeDbgAbbrev(self: *Dwarf) !void {
17221723 },
17231724 .wasm => {
17241725 const wasm_file = self.bin_file.cast(File.Wasm).?;
1725 const debug_abbrev = &wasm_file.debug_abbrev_atom.?.code;
1726 const debug_abbrev = &wasm_file.getAtomPtr(wasm_file.debug_abbrev_atom.?).code;
17261727 try debug_abbrev.resize(wasm_file.base.allocator, needed_size);
17271728 mem.copy(u8, debug_abbrev.items, &abbrev_buf);
17281729 },
......@@ -1835,7 +1836,7 @@ pub fn writeDbgInfoHeader(self: *Dwarf, module: *Module, low_pc: u64, high_pc: u
18351836 },
18361837 .wasm => {
18371838 const wasm_file = self.bin_file.cast(File.Wasm).?;
1838 const debug_info = &wasm_file.debug_info_atom.?.code;
1839 const debug_info = &wasm_file.getAtomPtr(wasm_file.debug_info_atom.?).code;
18391840 try writeDbgInfoNopsToArrayList(self.allocator, debug_info, 0, 0, di_buf.items, jmp_amt, false);
18401841 },
18411842 else => unreachable,
......@@ -2156,7 +2157,7 @@ pub fn writeDbgAranges(self: *Dwarf, addr: u64, size: u64) !void {
21562157 },
21572158 .wasm => {
21582159 const wasm_file = self.bin_file.cast(File.Wasm).?;
2159 const debug_ranges = &wasm_file.debug_ranges_atom.?.code;
2160 const debug_ranges = &wasm_file.getAtomPtr(wasm_file.debug_ranges_atom.?).code;
21602161 try debug_ranges.resize(wasm_file.base.allocator, needed_size);
21612162 mem.copy(u8, debug_ranges.items, di_buf.items);
21622163 },
......@@ -2330,7 +2331,7 @@ pub fn writeDbgLineHeader(self: *Dwarf) !void {
23302331 },
23312332 .wasm => {
23322333 const wasm_file = self.bin_file.cast(File.Wasm).?;
2333 const debug_line = &wasm_file.debug_line_atom.?.code;
2334 const debug_line = &wasm_file.getAtomPtr(wasm_file.debug_line_atom.?).code;
23342335 mem.copy(u8, buffer, debug_line.items[first_fn.off..]);
23352336 try debug_line.resize(self.allocator, debug_line.items.len + delta);
23362337 mem.copy(u8, debug_line.items[first_fn.off + delta ..], buffer);
......@@ -2381,7 +2382,7 @@ pub fn writeDbgLineHeader(self: *Dwarf) !void {
23812382 },
23822383 .wasm => {
23832384 const wasm_file = self.bin_file.cast(File.Wasm).?;
2384 const debug_line = wasm_file.debug_line_atom.?.code;
2385 const debug_line = &wasm_file.getAtomPtr(wasm_file.debug_line_atom.?).code;
23852386 writeDbgLineNopsBuffered(debug_line.items, 0, 0, di_buf.items, jmp_amt);
23862387 },
23872388 else => unreachable,
......@@ -2526,7 +2527,7 @@ pub fn flushModule(self: *Dwarf, module: *Module) !void {
25262527 },
25272528 .wasm => {
25282529 const wasm_file = self.bin_file.cast(File.Wasm).?;
2529 const debug_info = wasm_file.debug_info_atom.?.code;
2530 const debug_info = wasm_file.getAtomPtr(wasm_file.debug_info_atom.?).code;
25302531 mem.copy(u8, debug_info.items[atom.off + reloc.offset ..], &buf);
25312532 },
25322533 else => unreachable,
src/link/Wasm.zig+275-247
......@@ -9,7 +9,7 @@ const fs = std.fs;
99const leb = std.leb;
1010const log = std.log.scoped(.link);
1111
12const Atom = @import("Wasm/Atom.zig");
12pub const Atom = @import("Wasm/Atom.zig");
1313const Dwarf = @import("Dwarf.zig");
1414const Module = @import("../Module.zig");
1515const Compilation = @import("../Compilation.zig");
......@@ -31,10 +31,7 @@ const Object = @import("Wasm/Object.zig");
3131const Archive = @import("Wasm/Archive.zig");
3232const types = @import("Wasm/types.zig");
3333
34pub const base_tag = link.File.Tag.wasm;
35
36/// deprecated: Use `@import("Wasm/Atom.zig");`
37pub const DeclBlock = Atom;
34pub const base_tag: link.File.Tag = .wasm;
3835
3936base: link.File,
4037/// Output name of the file
......@@ -47,18 +44,16 @@ llvm_object: ?*LlvmObject = null,
4744/// TODO: Allow setting this through a flag?
4845host_name: []const u8 = "env",
4946/// List of all `Decl` that are currently alive.
50/// This is ment for bookkeeping so we can safely cleanup all codegen memory
51/// when calling `deinit`
52decls: std.AutoHashMapUnmanaged(Module.Decl.Index, void) = .{},
47/// Each index maps to the corresponding `Atom.Index`.
48decls: std.AutoHashMapUnmanaged(Module.Decl.Index, Atom.Index) = .{},
5349/// List of all symbols generated by Zig code.
5450symbols: std.ArrayListUnmanaged(Symbol) = .{},
5551/// List of symbol indexes which are free to be used.
5652symbols_free_list: std.ArrayListUnmanaged(u32) = .{},
5753/// Maps atoms to their segment index
58atoms: std.AutoHashMapUnmanaged(u32, *Atom) = .{},
59/// Atoms managed and created by the linker. This contains atoms
60/// from object files, and not Atoms generated by a Decl.
61managed_atoms: std.ArrayListUnmanaged(*Atom) = .{},
54atoms: std.AutoHashMapUnmanaged(u32, Atom.Index) = .{},
55/// List of all atoms.
56managed_atoms: std.ArrayListUnmanaged(Atom) = .{},
6257/// Represents the index into `segments` where the 'code' section
6358/// lives.
6459code_section_index: ?u32 = null,
......@@ -148,7 +143,7 @@ undefs: std.StringArrayHashMapUnmanaged(SymbolLoc) = .{},
148143/// Maps a symbol's location to an atom. This can be used to find meta
149144/// data of a symbol, such as its size, or its offset to perform a relocation.
150145/// Undefined (and synthetic) symbols do not have an Atom and therefore cannot be mapped.
151symbol_atom: std.AutoHashMapUnmanaged(SymbolLoc, *Atom) = .{},
146symbol_atom: std.AutoHashMapUnmanaged(SymbolLoc, Atom.Index) = .{},
152147/// Maps a symbol's location to its export name, which may differ from the decl's name
153148/// which does the exporting.
154149/// Note: The value represents the offset into the string table, rather than the actual string.
......@@ -165,14 +160,14 @@ error_table_symbol: ?u32 = null,
165160// unit contains Zig code. The lifetime of these atoms are extended
166161// until the end of the compiler's lifetime. Meaning they're not freed
167162// during `flush()` in incremental-mode.
168debug_info_atom: ?*Atom = null,
169debug_line_atom: ?*Atom = null,
170debug_loc_atom: ?*Atom = null,
171debug_ranges_atom: ?*Atom = null,
172debug_abbrev_atom: ?*Atom = null,
173debug_str_atom: ?*Atom = null,
174debug_pubnames_atom: ?*Atom = null,
175debug_pubtypes_atom: ?*Atom = null,
163debug_info_atom: ?Atom.Index = null,
164debug_line_atom: ?Atom.Index = null,
165debug_loc_atom: ?Atom.Index = null,
166debug_ranges_atom: ?Atom.Index = null,
167debug_abbrev_atom: ?Atom.Index = null,
168debug_str_atom: ?Atom.Index = null,
169debug_pubnames_atom: ?Atom.Index = null,
170debug_pubtypes_atom: ?Atom.Index = null,
176171
177172pub const Segment = struct {
178173 alignment: u32,
......@@ -430,10 +425,10 @@ pub fn openPath(allocator: Allocator, sub_path: []const u8, options: link.Option
430425 // at the end during `initializeCallCtorsFunction`.
431426 }
432427
433 if (!options.strip and options.module != null) {
434 wasm_bin.dwarf = Dwarf.init(allocator, &wasm_bin.base, options.target);
435 try wasm_bin.initDebugSections();
436 }
428 // if (!options.strip and options.module != null) {
429 // wasm_bin.dwarf = Dwarf.init(allocator, &wasm_bin.base, options.target);
430 // try wasm_bin.initDebugSections();
431 // }
437432
438433 return wasm_bin;
439434}
......@@ -474,6 +469,7 @@ fn createSyntheticSymbol(wasm: *Wasm, name: []const u8, tag: Symbol.Tag) !Symbol
474469 try wasm.globals.put(wasm.base.allocator, name_offset, loc);
475470 return loc;
476471}
472
477473/// Initializes symbols and atoms for the debug sections
478474/// Initialization is only done when compiling Zig code.
479475/// When Zig is invoked as a linker instead, the atoms
......@@ -516,6 +512,36 @@ fn parseObjectFile(wasm: *Wasm, path: []const u8) !bool {
516512 return true;
517513}
518514
515/// For a given `Module.Decl.Index` returns its corresponding `Atom.Index`.
516/// When the index was not found, a new `Atom` will be created, and its index will be returned.
517/// The newly created Atom is empty with default fields as specified by `Atom.empty`.
518pub fn getOrCreateAtomForDecl(wasm: *Wasm, decl_index: Module.Decl.Index) !Atom.Index {
519 const gop = try wasm.decls.getOrPut(wasm.base.allocator, decl_index);
520 if (!gop.found_existing) {
521 gop.value_ptr.* = try wasm.createAtom();
522 }
523 return gop.value_ptr.*;
524}
525
526/// Creates a new empty `Atom` and returns its `Atom.Index`
527fn createAtom(wasm: *Wasm) !Atom.Index {
528 const index = @intCast(Atom.Index, wasm.managed_atoms.items.len);
529 const atom = try wasm.managed_atoms.addOne(wasm.base.allocator);
530 atom.* = Atom.empty;
531 atom.sym_index = try wasm.allocateSymbol();
532 try wasm.symbol_atom.putNoClobber(wasm.base.allocator, .{ .file = null, .index = atom.sym_index }, index);
533
534 return index;
535}
536
537pub inline fn getAtom(wasm: *const Wasm, index: Atom.Index) Atom {
538 return wasm.managed_atoms.items[index];
539}
540
541pub inline fn getAtomPtr(wasm: *Wasm, index: Atom.Index) *Atom {
542 return &wasm.managed_atoms.items[index];
543}
544
519545/// Parses an archive file and will then parse each object file
520546/// that was found in the archive file.
521547/// Returns false when the file is not an archive file.
......@@ -857,15 +883,16 @@ fn resolveLazySymbols(wasm: *Wasm) !void {
857883 try wasm.discarded.putNoClobber(wasm.base.allocator, kv.value, loc);
858884 _ = wasm.resolved_symbols.swapRemove(loc); // we don't want to emit this symbol, only use it for relocations.
859885
860 const atom = try wasm.base.allocator.create(Atom);
861 errdefer wasm.base.allocator.destroy(atom);
862 try wasm.managed_atoms.append(wasm.base.allocator, atom);
886 // TODO: Can we use `createAtom` here while also re-using the symbol
887 // from `createSyntheticSymbol`.
888 const atom_index = @intCast(Atom.Index, wasm.managed_atoms.items.len);
889 const atom = try wasm.managed_atoms.addOne(wasm.base.allocator);
863890 atom.* = Atom.empty;
864891 atom.sym_index = loc.index;
865892 atom.alignment = 1;
866893
867 try wasm.parseAtom(atom, .{ .data = .synthetic });
868 try wasm.symbol_atom.putNoClobber(wasm.base.allocator, loc, atom);
894 try wasm.parseAtom(atom_index, .{ .data = .synthetic });
895 try wasm.symbol_atom.putNoClobber(wasm.base.allocator, loc, atom_index);
869896 }
870897
871898 if (wasm.undefs.fetchSwapRemove("__heap_end")) |kv| {
......@@ -873,15 +900,14 @@ fn resolveLazySymbols(wasm: *Wasm) !void {
873900 try wasm.discarded.putNoClobber(wasm.base.allocator, kv.value, loc);
874901 _ = wasm.resolved_symbols.swapRemove(loc);
875902
876 const atom = try wasm.base.allocator.create(Atom);
877 errdefer wasm.base.allocator.destroy(atom);
878 try wasm.managed_atoms.append(wasm.base.allocator, atom);
903 const atom_index = @intCast(Atom.Index, wasm.managed_atoms.items.len);
904 const atom = try wasm.managed_atoms.addOne(wasm.base.allocator);
879905 atom.* = Atom.empty;
880906 atom.sym_index = loc.index;
881907 atom.alignment = 1;
882908
883 try wasm.parseAtom(atom, .{ .data = .synthetic });
884 try wasm.symbol_atom.putNoClobber(wasm.base.allocator, loc, atom);
909 try wasm.parseAtom(atom_index, .{ .data = .synthetic });
910 try wasm.symbol_atom.putNoClobber(wasm.base.allocator, loc, atom_index);
885911 }
886912}
887913
......@@ -920,16 +946,6 @@ pub fn deinit(wasm: *Wasm) void {
920946 if (wasm.llvm_object) |llvm_object| llvm_object.destroy(gpa);
921947 }
922948
923 if (wasm.base.options.module) |mod| {
924 var decl_it = wasm.decls.keyIterator();
925 while (decl_it.next()) |decl_index_ptr| {
926 const decl = mod.declPtr(decl_index_ptr.*);
927 decl.link.wasm.deinit(gpa);
928 }
929 } else {
930 assert(wasm.decls.count() == 0);
931 }
932
933949 for (wasm.func_types.items) |*func_type| {
934950 func_type.deinit(gpa);
935951 }
......@@ -954,9 +970,8 @@ pub fn deinit(wasm: *Wasm) void {
954970 wasm.symbol_atom.deinit(gpa);
955971 wasm.export_names.deinit(gpa);
956972 wasm.atoms.deinit(gpa);
957 for (wasm.managed_atoms.items) |managed_atom| {
958 managed_atom.deinit(gpa);
959 gpa.destroy(managed_atom);
973 for (wasm.managed_atoms.items) |*managed_atom| {
974 managed_atom.deinit(wasm);
960975 }
961976 wasm.managed_atoms.deinit(gpa);
962977 wasm.segments.deinit(gpa);
......@@ -1014,18 +1029,24 @@ pub fn updateFunc(wasm: *Wasm, mod: *Module, func: *Module.Fn, air: Air, livenes
10141029
10151030 const decl_index = func.owner_decl;
10161031 const decl = mod.declPtr(decl_index);
1017 const atom = &decl.link.wasm;
1018 try atom.ensureInitialized(wasm);
1019 const gop = try wasm.decls.getOrPut(wasm.base.allocator, decl_index);
1020 if (gop.found_existing) {
1021 atom.clear();
1022 } else gop.value_ptr.* = {};
1032 const atom_index = try wasm.getOrCreateAtomForDecl(decl_index);
1033 const atom = wasm.getAtomPtr(atom_index);
1034 atom.clear();
10231035
1024 var decl_state: ?Dwarf.DeclState = if (wasm.dwarf) |*dwarf| try dwarf.initDeclState(mod, decl_index) else null;
1025 defer if (decl_state) |*ds| ds.deinit();
1036 // var decl_state: ?Dwarf.DeclState = if (wasm.dwarf) |*dwarf| try dwarf.initDeclState(mod, decl_index) else null;
1037 // defer if (decl_state) |*ds| ds.deinit();
10261038
10271039 var code_writer = std.ArrayList(u8).init(wasm.base.allocator);
10281040 defer code_writer.deinit();
1041 // const result = try codegen.generateFunction(
1042 // &wasm.base,
1043 // decl.srcLoc(),
1044 // func,
1045 // air,
1046 // liveness,
1047 // &code_writer,
1048 // if (decl_state) |*ds| .{ .dwarf = ds } else .none,
1049 // );
10291050 const result = try codegen.generateFunction(
10301051 &wasm.base,
10311052 decl.srcLoc(),
......@@ -1033,7 +1054,7 @@ pub fn updateFunc(wasm: *Wasm, mod: *Module, func: *Module.Fn, air: Air, livenes
10331054 air,
10341055 liveness,
10351056 &code_writer,
1036 if (decl_state) |*ds| .{ .dwarf = ds } else .none,
1057 .none,
10371058 );
10381059
10391060 const code = switch (result) {
......@@ -1045,19 +1066,19 @@ pub fn updateFunc(wasm: *Wasm, mod: *Module, func: *Module.Fn, air: Air, livenes
10451066 },
10461067 };
10471068
1048 if (wasm.dwarf) |*dwarf| {
1049 try dwarf.commitDeclState(
1050 mod,
1051 decl_index,
1052 // Actual value will be written after relocation.
1053 // For Wasm, this is the offset relative to the code section
1054 // which isn't known until flush().
1055 0,
1056 code.len,
1057 &decl_state.?,
1058 );
1059 }
1060 return wasm.finishUpdateDecl(decl, code);
1069 // if (wasm.dwarf) |*dwarf| {
1070 // try dwarf.commitDeclState(
1071 // mod,
1072 // decl_index,
1073 // // Actual value will be written after relocation.
1074 // // For Wasm, this is the offset relative to the code section
1075 // // which isn't known until flush().
1076 // 0,
1077 // code.len,
1078 // &decl_state.?,
1079 // );
1080 // }
1081 return wasm.finishUpdateDecl(decl_index, code);
10611082}
10621083
10631084// Generate code for the Decl, storing it in memory to be later written to
......@@ -1080,17 +1101,14 @@ pub fn updateDecl(wasm: *Wasm, mod: *Module, decl_index: Module.Decl.Index) !voi
10801101 return;
10811102 }
10821103
1083 const atom = &decl.link.wasm;
1084 try atom.ensureInitialized(wasm);
1085 const gop = try wasm.decls.getOrPut(wasm.base.allocator, decl_index);
1086 if (gop.found_existing) {
1087 atom.clear();
1088 } else gop.value_ptr.* = {};
1104 const atom_index = try wasm.getOrCreateAtomForDecl(decl_index);
1105 const atom = wasm.getAtomPtr(atom_index);
1106 atom.clear();
10891107
10901108 if (decl.isExtern()) {
10911109 const variable = decl.getVariable().?;
10921110 const name = mem.sliceTo(decl.name, 0);
1093 return wasm.addOrUpdateImport(name, decl.link.wasm.sym_index, variable.lib_name, null);
1111 return wasm.addOrUpdateImport(name, atom.sym_index, variable.lib_name, null);
10941112 }
10951113 const val = if (decl.val.castTag(.variable)) |payload| payload.data.init else decl.val;
10961114
......@@ -1103,7 +1121,7 @@ pub fn updateDecl(wasm: *Wasm, mod: *Module, decl_index: Module.Decl.Index) !voi
11031121 .{ .ty = decl.ty, .val = val },
11041122 &code_writer,
11051123 .none,
1106 .{ .parent_atom_index = decl.link.wasm.sym_index },
1124 .{ .parent_atom_index = atom.sym_index },
11071125 );
11081126
11091127 const code = switch (res) {
......@@ -1115,7 +1133,7 @@ pub fn updateDecl(wasm: *Wasm, mod: *Module, decl_index: Module.Decl.Index) !voi
11151133 },
11161134 };
11171135
1118 return wasm.finishUpdateDecl(decl, code);
1136 return wasm.finishUpdateDecl(decl_index, code);
11191137}
11201138
11211139pub fn updateDeclLineNumber(wasm: *Wasm, mod: *Module, decl_index: Module.Decl.Index) !void {
......@@ -1133,9 +1151,11 @@ pub fn updateDeclLineNumber(wasm: *Wasm, mod: *Module, decl_index: Module.Decl.I
11331151 }
11341152}
11351153
1136fn finishUpdateDecl(wasm: *Wasm, decl: *Module.Decl, code: []const u8) !void {
1154fn finishUpdateDecl(wasm: *Wasm, decl_index: Module.Decl.Index, code: []const u8) !void {
11371155 const mod = wasm.base.options.module.?;
1138 const atom: *Atom = &decl.link.wasm;
1156 const decl = mod.declPtr(decl_index);
1157 const atom_index = wasm.decls.get(decl_index).?;
1158 const atom = wasm.getAtomPtr(atom_index);
11391159 const symbol = &wasm.symbols.items[atom.sym_index];
11401160 const full_name = try decl.getFullyQualifiedName(mod);
11411161 defer wasm.base.allocator.free(full_name);
......@@ -1201,48 +1221,51 @@ pub fn lowerUnnamedConst(wasm: *Wasm, tv: TypedValue, decl_index: Module.Decl.In
12011221 const decl = mod.declPtr(decl_index);
12021222
12031223 // Create and initialize a new local symbol and atom
1204 const local_index = decl.link.wasm.locals.items.len;
1224 const atom_index = try wasm.createAtom();
1225 const parent_atom_index = try wasm.getOrCreateAtomForDecl(decl_index);
1226 const parent_atom = wasm.getAtomPtr(parent_atom_index);
1227 const local_index = parent_atom.locals.items.len;
1228 try parent_atom.locals.append(wasm.base.allocator, atom_index);
12051229 const fqdn = try decl.getFullyQualifiedName(mod);
12061230 defer wasm.base.allocator.free(fqdn);
12071231 const name = try std.fmt.allocPrintZ(wasm.base.allocator, "__unnamed_{s}_{d}", .{ fqdn, local_index });
12081232 defer wasm.base.allocator.free(name);
1209
1210 const atom = try decl.link.wasm.locals.addOne(wasm.base.allocator);
1211 atom.* = Atom.empty;
1212 try atom.ensureInitialized(wasm);
1213 atom.alignment = tv.ty.abiAlignment(wasm.base.options.target);
1214 wasm.symbols.items[atom.sym_index] = .{
1215 .name = try wasm.string_table.put(wasm.base.allocator, name),
1216 .flags = @enumToInt(Symbol.Flag.WASM_SYM_BINDING_LOCAL),
1217 .tag = .data,
1218 .index = undefined,
1219 };
1220
1221 try wasm.resolved_symbols.putNoClobber(wasm.base.allocator, atom.symbolLoc(), {});
1222
12231233 var value_bytes = std.ArrayList(u8).init(wasm.base.allocator);
12241234 defer value_bytes.deinit();
12251235
1226 const result = try codegen.generateSymbol(
1227 &wasm.base,
1228 decl.srcLoc(),
1229 tv,
1230 &value_bytes,
1231 .none,
1232 .{
1233 .parent_atom_index = atom.sym_index,
1234 .addend = null,
1235 },
1236 );
1237 const code = switch (result) {
1238 .ok => value_bytes.items,
1239 .fail => |em| {
1240 decl.analysis = .codegen_failure;
1241 try mod.failed_decls.put(mod.gpa, decl_index, em);
1242 return error.AnalysisFail;
1243 },
1236 const code = code: {
1237 const atom = wasm.getAtomPtr(atom_index);
1238 atom.alignment = tv.ty.abiAlignment(wasm.base.options.target);
1239 wasm.symbols.items[atom.sym_index] = .{
1240 .name = try wasm.string_table.put(wasm.base.allocator, name),
1241 .flags = @enumToInt(Symbol.Flag.WASM_SYM_BINDING_LOCAL),
1242 .tag = .data,
1243 .index = undefined,
1244 };
1245 try wasm.resolved_symbols.putNoClobber(wasm.base.allocator, atom.symbolLoc(), {});
1246
1247 const result = try codegen.generateSymbol(
1248 &wasm.base,
1249 decl.srcLoc(),
1250 tv,
1251 &value_bytes,
1252 .none,
1253 .{
1254 .parent_atom_index = atom.sym_index,
1255 .addend = null,
1256 },
1257 );
1258 break :code switch (result) {
1259 .ok => value_bytes.items,
1260 .fail => |em| {
1261 decl.analysis = .codegen_failure;
1262 try mod.failed_decls.put(mod.gpa, decl_index, em);
1263 return error.AnalysisFail;
1264 },
1265 };
12441266 };
12451267
1268 const atom = wasm.getAtomPtr(atom_index);
12461269 atom.size = @intCast(u32, code.len);
12471270 try atom.code.appendSlice(wasm.base.allocator, code);
12481271 return atom.sym_index;
......@@ -1290,10 +1313,13 @@ pub fn getDeclVAddr(
12901313) !u64 {
12911314 const mod = wasm.base.options.module.?;
12921315 const decl = mod.declPtr(decl_index);
1293 try decl.link.wasm.ensureInitialized(wasm);
1294 const target_symbol_index = decl.link.wasm.sym_index;
1316
1317 const target_atom_index = try wasm.getOrCreateAtomForDecl(decl_index);
1318 const target_symbol_index = wasm.getAtom(target_atom_index).sym_index;
1319
12951320 assert(reloc_info.parent_atom_index != 0);
1296 const atom = wasm.symbol_atom.get(.{ .file = null, .index = reloc_info.parent_atom_index }).?;
1321 const atom_index = wasm.symbol_atom.get(.{ .file = null, .index = reloc_info.parent_atom_index }).?;
1322 const atom = wasm.getAtomPtr(atom_index);
12971323 const is_wasm32 = wasm.base.options.target.cpu.arch == .wasm32;
12981324 if (decl.ty.zigTypeTag() == .Fn) {
12991325 assert(reloc_info.addend == 0); // addend not allowed for function relocations
......@@ -1321,9 +1347,10 @@ pub fn getDeclVAddr(
13211347 return target_symbol_index;
13221348}
13231349
1324pub fn deleteExport(wasm: *Wasm, exp: Export) void {
1350pub fn deleteDeclExport(wasm: *Wasm, decl_index: Module.Decl.Index) void {
13251351 if (wasm.llvm_object) |_| return;
1326 const sym_index = exp.sym_index orelse return;
1352 const atom_index = wasm.decls.get(decl_index) orelse return;
1353 const sym_index = wasm.getAtom(atom_index).sym_index;
13271354 const loc: SymbolLoc = .{ .file = null, .index = sym_index };
13281355 const symbol = loc.getSymbol(wasm);
13291356 const symbol_name = wasm.string_table.get(symbol.name);
......@@ -1349,7 +1376,8 @@ pub fn updateDeclExports(
13491376 }
13501377
13511378 const decl = mod.declPtr(decl_index);
1352 if (decl.link.wasm.getSymbolIndex() == null) return; // unititialized
1379 const atom_index = try wasm.getOrCreateAtomForDecl(decl_index);
1380 const atom = wasm.getAtom(atom_index);
13531381
13541382 for (exports) |exp| {
13551383 if (exp.options.section) |section| {
......@@ -1364,7 +1392,7 @@ pub fn updateDeclExports(
13641392
13651393 const export_name = try wasm.string_table.put(wasm.base.allocator, exp.options.name);
13661394 if (wasm.globals.getPtr(export_name)) |existing_loc| {
1367 if (existing_loc.index == decl.link.wasm.sym_index) continue;
1395 if (existing_loc.index == atom.sym_index) continue;
13681396 const existing_sym: Symbol = existing_loc.getSymbol(wasm).*;
13691397
13701398 const exp_is_weak = exp.options.linkage == .Internal or exp.options.linkage == .Weak;
......@@ -1385,15 +1413,16 @@ pub fn updateDeclExports(
13851413 } else if (exp_is_weak) {
13861414 continue; // to-be-exported symbol is weak, so we keep the existing symbol
13871415 } else {
1388 existing_loc.index = decl.link.wasm.sym_index;
1416 // TODO: Revisit this, why was this needed?
1417 existing_loc.index = atom.sym_index;
13891418 existing_loc.file = null;
1390 exp.link.wasm.sym_index = existing_loc.index;
1419 // exp.link.wasm.sym_index = existing_loc.index;
13911420 }
13921421 }
13931422
1394 const exported_decl = mod.declPtr(exp.exported_decl);
1395 const sym_index = exported_decl.link.wasm.sym_index;
1396 const sym_loc = exported_decl.link.wasm.symbolLoc();
1423 const exported_atom_index = try wasm.getOrCreateAtomForDecl(exp.exported_decl);
1424 const exported_atom = wasm.getAtom(exported_atom_index);
1425 const sym_loc = exported_atom.symbolLoc();
13971426 const symbol = sym_loc.getSymbol(wasm);
13981427 switch (exp.options.linkage) {
13991428 .Internal => {
......@@ -1429,7 +1458,6 @@ pub fn updateDeclExports(
14291458 // if the symbol was previously undefined, remove it as an import
14301459 _ = wasm.imports.remove(sym_loc);
14311460 _ = wasm.undefs.swapRemove(exp.options.name);
1432 exp.link.wasm.sym_index = sym_index;
14331461 }
14341462}
14351463
......@@ -1439,11 +1467,13 @@ pub fn freeDecl(wasm: *Wasm, decl_index: Module.Decl.Index) void {
14391467 }
14401468 const mod = wasm.base.options.module.?;
14411469 const decl = mod.declPtr(decl_index);
1442 const atom = &decl.link.wasm;
1470 const atom_index = wasm.decls.get(decl_index).?;
1471 const atom = wasm.getAtomPtr(atom_index);
14431472 wasm.symbols_free_list.append(wasm.base.allocator, atom.sym_index) catch {};
14441473 _ = wasm.decls.remove(decl_index);
14451474 wasm.symbols.items[atom.sym_index].tag = .dead;
1446 for (atom.locals.items) |local_atom| {
1475 for (atom.locals.items) |local_atom_index| {
1476 const local_atom = wasm.getAtom(local_atom_index);
14471477 const local_symbol = &wasm.symbols.items[local_atom.sym_index];
14481478 local_symbol.tag = .dead; // also for any local symbol
14491479 wasm.symbols_free_list.append(wasm.base.allocator, local_atom.sym_index) catch {};
......@@ -1461,7 +1491,16 @@ pub fn freeDecl(wasm: *Wasm, decl_index: Module.Decl.Index) void {
14611491 // dwarf.freeDecl(decl_index);
14621492 // }
14631493
1464 atom.deinit(wasm.base.allocator);
1494 if (atom.next) |next_atom_index| {
1495 const next_atom = wasm.getAtomPtr(next_atom_index);
1496 next_atom.prev = atom.prev;
1497 atom.next = null;
1498 }
1499 if (atom.prev) |prev_index| {
1500 const prev_atom = wasm.getAtomPtr(prev_index);
1501 prev_atom.next = atom.next;
1502 atom.prev = null;
1503 }
14651504}
14661505
14671506/// Appends a new entry to the indirect function table
......@@ -1583,7 +1622,8 @@ const Kind = union(enum) {
15831622};
15841623
15851624/// Parses an Atom and inserts its metadata into the corresponding sections.
1586fn parseAtom(wasm: *Wasm, atom: *Atom, kind: Kind) !void {
1625fn parseAtom(wasm: *Wasm, atom_index: Atom.Index, kind: Kind) !void {
1626 const atom = wasm.getAtomPtr(atom_index);
15871627 const symbol = (SymbolLoc{ .file = null, .index = atom.sym_index }).getSymbol(wasm);
15881628 const final_index: u32 = switch (kind) {
15891629 .function => |fn_data| result: {
......@@ -1658,18 +1698,20 @@ fn parseAtom(wasm: *Wasm, atom: *Atom, kind: Kind) !void {
16581698 const segment: *Segment = &wasm.segments.items[final_index];
16591699 segment.alignment = std.math.max(segment.alignment, atom.alignment);
16601700
1661 try wasm.appendAtomAtIndex(final_index, atom);
1701 try wasm.appendAtomAtIndex(final_index, atom_index);
16621702}
16631703
16641704/// From a given index, append the given `Atom` at the back of the linked list.
16651705/// Simply inserts it into the map of atoms when it doesn't exist yet.
1666pub fn appendAtomAtIndex(wasm: *Wasm, index: u32, atom: *Atom) !void {
1667 if (wasm.atoms.getPtr(index)) |last| {
1668 last.*.next = atom;
1669 atom.prev = last.*;
1670 last.* = atom;
1706pub fn appendAtomAtIndex(wasm: *Wasm, index: u32, atom_index: Atom.Index) !void {
1707 const atom = wasm.getAtomPtr(atom_index);
1708 if (wasm.atoms.getPtr(index)) |last_index_ptr| {
1709 const last = wasm.getAtomPtr(last_index_ptr.*);
1710 last.*.next = atom_index;
1711 atom.prev = last_index_ptr.*;
1712 last_index_ptr.* = atom_index;
16711713 } else {
1672 try wasm.atoms.putNoClobber(wasm.base.allocator, index, atom);
1714 try wasm.atoms.putNoClobber(wasm.base.allocator, index, atom_index);
16731715 }
16741716}
16751717
......@@ -1679,16 +1721,17 @@ fn allocateDebugAtoms(wasm: *Wasm) !void {
16791721 if (wasm.dwarf == null) return;
16801722
16811723 const allocAtom = struct {
1682 fn f(bin: *Wasm, maybe_index: *?u32, atom: *Atom) !void {
1724 fn f(bin: *Wasm, maybe_index: *?u32, atom_index: Atom.Index) !void {
16831725 const index = maybe_index.* orelse idx: {
16841726 const index = @intCast(u32, bin.segments.items.len);
16851727 try bin.appendDummySegment();
16861728 maybe_index.* = index;
16871729 break :idx index;
16881730 };
1731 const atom = bin.getAtomPtr(atom_index);
16891732 atom.size = @intCast(u32, atom.code.items.len);
16901733 bin.symbols.items[atom.sym_index].index = index;
1691 try bin.appendAtomAtIndex(index, atom);
1734 try bin.appendAtomAtIndex(index, atom_index);
16921735 }
16931736 }.f;
16941737
......@@ -1710,15 +1753,16 @@ fn allocateAtoms(wasm: *Wasm) !void {
17101753 var it = wasm.atoms.iterator();
17111754 while (it.next()) |entry| {
17121755 const segment = &wasm.segments.items[entry.key_ptr.*];
1713 var atom: *Atom = entry.value_ptr.*.getFirst();
1756 var atom_index = entry.value_ptr.*;
17141757 var offset: u32 = 0;
17151758 while (true) {
1759 const atom = wasm.getAtomPtr(atom_index);
17161760 const symbol_loc = atom.symbolLoc();
17171761 if (wasm.code_section_index) |index| {
17181762 if (index == entry.key_ptr.*) {
17191763 if (!wasm.resolved_symbols.contains(symbol_loc)) {
17201764 // only allocate resolved function body's.
1721 atom = atom.next orelse break;
1765 atom_index = atom.prev orelse break;
17221766 continue;
17231767 }
17241768 }
......@@ -1732,8 +1776,7 @@ fn allocateAtoms(wasm: *Wasm) !void {
17321776 atom.size,
17331777 });
17341778 offset += atom.size;
1735 try wasm.symbol_atom.put(wasm.base.allocator, symbol_loc, atom); // Update atom pointers
1736 atom = atom.next orelse break;
1779 atom_index = atom.prev orelse break;
17371780 }
17381781 segment.size = std.mem.alignForwardGeneric(u32, offset, segment.alignment);
17391782 }
......@@ -1867,8 +1910,8 @@ fn initializeCallCtorsFunction(wasm: *Wasm) !void {
18671910 symbol.index = func_index;
18681911
18691912 // create the atom that will be output into the final binary
1870 const atom = try wasm.base.allocator.create(Atom);
1871 errdefer wasm.base.allocator.destroy(atom);
1913 const atom_index = @intCast(Atom.Index, wasm.managed_atoms.items.len);
1914 const atom = try wasm.managed_atoms.addOne(wasm.base.allocator);
18721915 atom.* = .{
18731916 .size = @intCast(u32, function_body.items.len),
18741917 .offset = 0,
......@@ -1879,13 +1922,13 @@ fn initializeCallCtorsFunction(wasm: *Wasm) !void {
18791922 .prev = null,
18801923 .code = function_body.moveToUnmanaged(),
18811924 };
1882 try wasm.managed_atoms.append(wasm.base.allocator, atom);
1883 try wasm.appendAtomAtIndex(wasm.code_section_index.?, atom);
1884 try wasm.symbol_atom.putNoClobber(wasm.base.allocator, loc, atom);
1925 try wasm.appendAtomAtIndex(wasm.code_section_index.?, atom_index);
1926 try wasm.symbol_atom.putNoClobber(wasm.base.allocator, loc, atom_index);
18851927
18861928 // `allocateAtoms` has already been called, set the atom's offset manually.
18871929 // This is fine to do manually as we insert the atom at the very end.
1888 atom.offset = atom.prev.?.offset + atom.prev.?.size;
1930 const prev_atom = wasm.getAtom(atom.prev.?);
1931 atom.offset = prev_atom.offset + prev_atom.size;
18891932}
18901933
18911934fn setupImports(wasm: *Wasm) !void {
......@@ -2088,7 +2131,8 @@ fn setupExports(wasm: *Wasm) !void {
20882131 break :blk try wasm.string_table.put(wasm.base.allocator, sym_name);
20892132 };
20902133 const exp: types.Export = if (symbol.tag == .data) exp: {
2091 const atom = wasm.symbol_atom.get(sym_loc).?;
2134 const atom_index = wasm.symbol_atom.get(sym_loc).?;
2135 const atom = wasm.getAtom(atom_index);
20922136 const va = atom.getVA(wasm, symbol);
20932137 const global_index = @intCast(u32, wasm.imported_globals_count + wasm.wasm_globals.items.len);
20942138 try wasm.wasm_globals.append(wasm.base.allocator, .{
......@@ -2193,7 +2237,8 @@ fn setupMemory(wasm: *Wasm) !void {
21932237 const segment_index = wasm.data_segments.get(".synthetic").?;
21942238 const segment = &wasm.segments.items[segment_index];
21952239 segment.offset = 0; // for simplicity we store the entire VA into atom's offset.
2196 const atom = wasm.symbol_atom.get(loc).?;
2240 const atom_index = wasm.symbol_atom.get(loc).?;
2241 const atom = wasm.getAtomPtr(atom_index);
21972242 atom.offset = @intCast(u32, mem.alignForwardGeneric(u64, memory_ptr, heap_alignment));
21982243 }
21992244
......@@ -2226,7 +2271,8 @@ fn setupMemory(wasm: *Wasm) !void {
22262271 const segment_index = wasm.data_segments.get(".synthetic").?;
22272272 const segment = &wasm.segments.items[segment_index];
22282273 segment.offset = 0;
2229 const atom = wasm.symbol_atom.get(loc).?;
2274 const atom_index = wasm.symbol_atom.get(loc).?;
2275 const atom = wasm.getAtomPtr(atom_index);
22302276 atom.offset = @intCast(u32, memory_ptr);
22312277 }
22322278
......@@ -2352,15 +2398,14 @@ pub fn getErrorTableSymbol(wasm: *Wasm) !u32 {
23522398 // and then return said symbol's index. The final table will be populated
23532399 // during `flush` when we know all possible error names.
23542400
2355 // As sym_index '0' is reserved, we use it for our stack pointer symbol
2356 const symbol_index = wasm.symbols_free_list.popOrNull() orelse blk: {
2357 const index = @intCast(u32, wasm.symbols.items.len);
2358 _ = try wasm.symbols.addOne(wasm.base.allocator);
2359 break :blk index;
2360 };
2401 const atom_index = try wasm.createAtom();
2402 const atom = wasm.getAtomPtr(atom_index);
2403 const slice_ty = Type.initTag(.const_slice_u8_sentinel_0);
2404 atom.alignment = slice_ty.abiAlignment(wasm.base.options.target);
2405 const sym_index = atom.sym_index;
23612406
23622407 const sym_name = try wasm.string_table.put(wasm.base.allocator, "__zig_err_name_table");
2363 const symbol = &wasm.symbols.items[symbol_index];
2408 const symbol = &wasm.symbols.items[sym_index];
23642409 symbol.* = .{
23652410 .name = sym_name,
23662411 .tag = .data,
......@@ -2369,20 +2414,11 @@ pub fn getErrorTableSymbol(wasm: *Wasm) !u32 {
23692414 };
23702415 symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN);
23712416
2372 const slice_ty = Type.initTag(.const_slice_u8_sentinel_0);
2417 try wasm.resolved_symbols.put(wasm.base.allocator, atom.symbolLoc(), {});
23732418
2374 const atom = try wasm.base.allocator.create(Atom);
2375 atom.* = Atom.empty;
2376 atom.sym_index = symbol_index;
2377 atom.alignment = slice_ty.abiAlignment(wasm.base.options.target);
2378 try wasm.managed_atoms.append(wasm.base.allocator, atom);
2379 const loc = atom.symbolLoc();
2380 try wasm.resolved_symbols.put(wasm.base.allocator, loc, {});
2381 try wasm.symbol_atom.put(wasm.base.allocator, loc, atom);
2382
2383 log.debug("Error name table was created with symbol index: ({d})", .{symbol_index});
2384 wasm.error_table_symbol = symbol_index;
2385 return symbol_index;
2419 log.debug("Error name table was created with symbol index: ({d})", .{sym_index});
2420 wasm.error_table_symbol = sym_index;
2421 return sym_index;
23862422}
23872423
23882424/// Populates the error name table, when `error_table_symbol` is not null.
......@@ -2391,22 +2427,17 @@ pub fn getErrorTableSymbol(wasm: *Wasm) !u32 {
23912427/// The table is what is being pointed to within the runtime bodies that are generated.
23922428fn populateErrorNameTable(wasm: *Wasm) !void {
23932429 const symbol_index = wasm.error_table_symbol orelse return;
2394 const atom: *Atom = wasm.symbol_atom.get(.{ .file = null, .index = symbol_index }).?;
2430 const atom_index = wasm.symbol_atom.get(.{ .file = null, .index = symbol_index }).?;
2431 const atom = wasm.getAtomPtr(atom_index);
2432
23952433 // Rather than creating a symbol for each individual error name,
23962434 // we create a symbol for the entire region of error names. We then calculate
23972435 // the pointers into the list using addends which are appended to the relocation.
2398 const names_atom = try wasm.base.allocator.create(Atom);
2399 names_atom.* = Atom.empty;
2400 try wasm.managed_atoms.append(wasm.base.allocator, names_atom);
2401 const names_symbol_index = wasm.symbols_free_list.popOrNull() orelse blk: {
2402 const index = @intCast(u32, wasm.symbols.items.len);
2403 _ = try wasm.symbols.addOne(wasm.base.allocator);
2404 break :blk index;
2405 };
2406 names_atom.sym_index = names_symbol_index;
2436 const names_atom_index = try wasm.createAtom();
2437 const names_atom = wasm.getAtomPtr(names_atom_index);
24072438 names_atom.alignment = 1;
24082439 const sym_name = try wasm.string_table.put(wasm.base.allocator, "__zig_err_names");
2409 const names_symbol = &wasm.symbols.items[names_symbol_index];
2440 const names_symbol = &wasm.symbols.items[names_atom.sym_index];
24102441 names_symbol.* = .{
24112442 .name = sym_name,
24122443 .tag = .data,
......@@ -2430,7 +2461,7 @@ fn populateErrorNameTable(wasm: *Wasm) !void {
24302461 try atom.code.writer(wasm.base.allocator).writeIntLittle(u32, len - 1);
24312462 // create relocation to the error name
24322463 try atom.relocs.append(wasm.base.allocator, .{
2433 .index = names_symbol_index,
2464 .index = names_atom.sym_index,
24342465 .relocation_type = .R_WASM_MEMORY_ADDR_I32,
24352466 .offset = offset,
24362467 .addend = @intCast(i32, addend),
......@@ -2449,61 +2480,53 @@ fn populateErrorNameTable(wasm: *Wasm) !void {
24492480
24502481 const name_loc = names_atom.symbolLoc();
24512482 try wasm.resolved_symbols.put(wasm.base.allocator, name_loc, {});
2452 try wasm.symbol_atom.put(wasm.base.allocator, name_loc, names_atom);
2483 try wasm.symbol_atom.put(wasm.base.allocator, name_loc, names_atom_index);
24532484
24542485 // link the atoms with the rest of the binary so they can be allocated
24552486 // and relocations will be performed.
2456 try wasm.parseAtom(atom, .{ .data = .read_only });
2457 try wasm.parseAtom(names_atom, .{ .data = .read_only });
2487 try wasm.parseAtom(atom_index, .{ .data = .read_only });
2488 try wasm.parseAtom(names_atom_index, .{ .data = .read_only });
24582489}
24592490
24602491/// From a given index variable, creates a new debug section.
24612492/// This initializes the index, appends a new segment,
24622493/// and finally, creates a managed `Atom`.
2463pub fn createDebugSectionForIndex(wasm: *Wasm, index: *?u32, name: []const u8) !*Atom {
2494pub fn createDebugSectionForIndex(wasm: *Wasm, index: *?u32, name: []const u8) !Atom.Index {
24642495 const new_index = @intCast(u32, wasm.segments.items.len);
24652496 index.* = new_index;
24662497 try wasm.appendDummySegment();
24672498
2468 const sym_index = wasm.symbols_free_list.popOrNull() orelse idx: {
2469 const tmp_index = @intCast(u32, wasm.symbols.items.len);
2470 _ = try wasm.symbols.addOne(wasm.base.allocator);
2471 break :idx tmp_index;
2472 };
2473 wasm.symbols.items[sym_index] = .{
2499 const atom_index = try wasm.createAtom();
2500 const atom = wasm.getAtomPtr(atom_index);
2501 wasm.symbols.items[atom.sym_index] = .{
24742502 .tag = .section,
24752503 .name = try wasm.string_table.put(wasm.base.allocator, name),
24762504 .index = 0,
24772505 .flags = @enumToInt(Symbol.Flag.WASM_SYM_BINDING_LOCAL),
24782506 };
24792507
2480 const atom = try wasm.base.allocator.create(Atom);
2481 atom.* = Atom.empty;
24822508 atom.alignment = 1; // debug sections are always 1-byte-aligned
2483 atom.sym_index = sym_index;
2484 try wasm.managed_atoms.append(wasm.base.allocator, atom);
2485 try wasm.symbol_atom.put(wasm.base.allocator, atom.symbolLoc(), atom);
2486 return atom;
2509 return atom_index;
24872510}
24882511
24892512fn resetState(wasm: *Wasm) void {
24902513 for (wasm.segment_info.values()) |segment_info| {
24912514 wasm.base.allocator.free(segment_info.name);
24922515 }
2493 if (wasm.base.options.module) |mod| {
2494 var decl_it = wasm.decls.keyIterator();
2495 while (decl_it.next()) |decl_index_ptr| {
2496 const decl = mod.declPtr(decl_index_ptr.*);
2497 const atom = &decl.link.wasm;
2498 atom.next = null;
2499 atom.prev = null;
2500
2501 for (atom.locals.items) |*local_atom| {
2502 local_atom.next = null;
2503 local_atom.prev = null;
2504 }
2516
2517 var atom_it = wasm.decls.valueIterator();
2518 while (atom_it.next()) |atom_index| {
2519 const atom = wasm.getAtomPtr(atom_index.*);
2520 atom.next = null;
2521 atom.prev = null;
2522
2523 for (atom.locals.items) |local_atom_index| {
2524 const local_atom = wasm.getAtomPtr(local_atom_index);
2525 local_atom.next = null;
2526 local_atom.prev = null;
25052527 }
25062528 }
2529
25072530 wasm.functions.clearRetainingCapacity();
25082531 wasm.exports.clearRetainingCapacity();
25092532 wasm.segments.clearRetainingCapacity();
......@@ -2800,28 +2823,29 @@ pub fn flushModule(wasm: *Wasm, comp: *Compilation, prog_node: *std.Progress.Nod
28002823 try wasm.setupStart();
28012824 try wasm.setupImports();
28022825 if (wasm.base.options.module) |mod| {
2803 var decl_it = wasm.decls.keyIterator();
2804 while (decl_it.next()) |decl_index_ptr| {
2805 const decl = mod.declPtr(decl_index_ptr.*);
2826 var decl_it = wasm.decls.iterator();
2827 while (decl_it.next()) |entry| {
2828 const decl = mod.declPtr(entry.key_ptr.*);
28062829 if (decl.isExtern()) continue;
2807 const atom = &decl.*.link.wasm;
2830 const atom_index = entry.value_ptr.*;
28082831 if (decl.ty.zigTypeTag() == .Fn) {
2809 try wasm.parseAtom(atom, .{ .function = decl.fn_link.wasm });
2832 try wasm.parseAtom(atom_index, .{ .function = decl.fn_link.wasm });
28102833 } else if (decl.getVariable()) |variable| {
28112834 if (!variable.is_mutable) {
2812 try wasm.parseAtom(atom, .{ .data = .read_only });
2835 try wasm.parseAtom(atom_index, .{ .data = .read_only });
28132836 } else if (variable.init.isUndefDeep()) {
2814 try wasm.parseAtom(atom, .{ .data = .uninitialized });
2837 try wasm.parseAtom(atom_index, .{ .data = .uninitialized });
28152838 } else {
2816 try wasm.parseAtom(atom, .{ .data = .initialized });
2839 try wasm.parseAtom(atom_index, .{ .data = .initialized });
28172840 }
28182841 } else {
2819 try wasm.parseAtom(atom, .{ .data = .read_only });
2842 try wasm.parseAtom(atom_index, .{ .data = .read_only });
28202843 }
28212844
28222845 // also parse atoms for a decl's locals
2823 for (atom.locals.items) |*local_atom| {
2824 try wasm.parseAtom(local_atom, .{ .data = .read_only });
2846 const atom = wasm.getAtomPtr(atom_index);
2847 for (atom.locals.items) |local_atom_index| {
2848 try wasm.parseAtom(local_atom_index, .{ .data = .read_only });
28252849 }
28262850 }
28272851
......@@ -3066,20 +3090,22 @@ fn writeToFile(
30663090 var code_section_size: u32 = 0;
30673091 if (wasm.code_section_index) |code_index| {
30683092 const header_offset = try reserveVecSectionHeader(&binary_bytes);
3069 var atom: *Atom = wasm.atoms.get(code_index).?.getFirst();
3093 var atom_index = wasm.atoms.get(code_index).?;
30703094
30713095 // The code section must be sorted in line with the function order.
30723096 var sorted_atoms = try std.ArrayList(*Atom).initCapacity(wasm.base.allocator, wasm.functions.count());
30733097 defer sorted_atoms.deinit();
30743098
30753099 while (true) {
3100 var atom = wasm.getAtomPtr(atom_index);
30763101 if (wasm.resolved_symbols.contains(atom.symbolLoc())) {
30773102 if (!is_obj) {
30783103 atom.resolveRelocs(wasm);
30793104 }
30803105 sorted_atoms.appendAssumeCapacity(atom);
30813106 }
3082 atom = atom.next orelse break;
3107 // atom = if (atom.prev) |prev| wasm.getAtomPtr(prev) else break;
3108 atom_index = atom.prev orelse break;
30833109 }
30843110
30853111 const atom_sort_fn = struct {
......@@ -3119,11 +3145,11 @@ fn writeToFile(
31193145 // do not output 'bss' section unless we import memory and therefore
31203146 // want to guarantee the data is zero initialized
31213147 if (!import_memory and std.mem.eql(u8, entry.key_ptr.*, ".bss")) continue;
3122 const atom_index = entry.value_ptr.*;
3123 const segment = wasm.segments.items[atom_index];
3148 const segment_index = entry.value_ptr.*;
3149 const segment = wasm.segments.items[segment_index];
31243150 if (segment.size == 0) continue; // do not emit empty segments
31253151 segment_count += 1;
3126 var atom: *Atom = wasm.atoms.getPtr(atom_index).?.*.getFirst();
3152 var atom_index = wasm.atoms.get(segment_index).?;
31273153
31283154 // flag and index to memory section (currently, there can only be 1 memory section in wasm)
31293155 try leb.writeULEB128(binary_writer, @as(u32, 0));
......@@ -3134,6 +3160,7 @@ fn writeToFile(
31343160 // fill in the offset table and the data segments
31353161 var current_offset: u32 = 0;
31363162 while (true) {
3163 const atom = wasm.getAtomPtr(atom_index);
31373164 if (!is_obj) {
31383165 atom.resolveRelocs(wasm);
31393166 }
......@@ -3149,8 +3176,8 @@ fn writeToFile(
31493176 try binary_writer.writeAll(atom.code.items);
31503177
31513178 current_offset += atom.size;
3152 if (atom.next) |next| {
3153 atom = next;
3179 if (atom.prev) |prev| {
3180 atom_index = prev;
31543181 } else {
31553182 // also pad with zeroes when last atom to ensure
31563183 // segments are aligned.
......@@ -3192,15 +3219,15 @@ fn writeToFile(
31923219 }
31933220
31943221 if (!wasm.base.options.strip) {
3195 if (wasm.dwarf) |*dwarf| {
3196 const mod = wasm.base.options.module.?;
3197 try dwarf.writeDbgAbbrev();
3198 // for debug info and ranges, the address is always 0,
3199 // as locations are always offsets relative to 'code' section.
3200 try dwarf.writeDbgInfoHeader(mod, 0, code_section_size);
3201 try dwarf.writeDbgAranges(0, code_section_size);
3202 try dwarf.writeDbgLineHeader();
3203 }
3222 // if (wasm.dwarf) |*dwarf| {
3223 // const mod = wasm.base.options.module.?;
3224 // try dwarf.writeDbgAbbrev();
3225 // // for debug info and ranges, the address is always 0,
3226 // // as locations are always offsets relative to 'code' section.
3227 // try dwarf.writeDbgInfoHeader(mod, 0, code_section_size);
3228 // try dwarf.writeDbgAranges(0, code_section_size);
3229 // try dwarf.writeDbgLineHeader();
3230 // }
32043231
32053232 var debug_bytes = std.ArrayList(u8).init(wasm.base.allocator);
32063233 defer debug_bytes.deinit();
......@@ -3223,11 +3250,11 @@ fn writeToFile(
32233250
32243251 for (debug_sections) |item| {
32253252 if (item.index) |index| {
3226 var atom = wasm.atoms.get(index).?.getFirst();
3253 var atom = wasm.getAtomPtr(wasm.atoms.get(index).?);
32273254 while (true) {
32283255 atom.resolveRelocs(wasm);
32293256 try debug_bytes.appendSlice(atom.code.items);
3230 atom = atom.next orelse break;
3257 atom = if (atom.prev) |prev| wasm.getAtomPtr(prev) else break;
32313258 }
32323259 try emitDebugSection(&binary_bytes, debug_bytes.items, item.name);
32333260 debug_bytes.clearRetainingCapacity();
......@@ -3959,7 +3986,8 @@ fn emitSymbolTable(wasm: *Wasm, binary_bytes: *std.ArrayList(u8), symbol_table:
39593986
39603987 if (symbol.isDefined()) {
39613988 try leb.writeULEB128(writer, symbol.index);
3962 const atom = wasm.symbol_atom.get(sym_loc).?;
3989 const atom_index = wasm.symbol_atom.get(sym_loc).?;
3990 const atom = wasm.getAtom(atom_index);
39633991 try leb.writeULEB128(writer, @as(u32, atom.offset));
39643992 try leb.writeULEB128(writer, @as(u32, atom.size));
39653993 }
......@@ -4037,7 +4065,7 @@ fn emitCodeRelocations(
40374065 const reloc_start = binary_bytes.items.len;
40384066
40394067 var count: u32 = 0;
4040 var atom: *Atom = wasm.atoms.get(code_index).?.getFirst();
4068 var atom: *Atom = wasm.getAtomPtr(wasm.atoms.get(code_index).?);
40414069 // for each atom, we calculate the uleb size and append that
40424070 var size_offset: u32 = 5; // account for code section size leb128
40434071 while (true) {
......@@ -4055,7 +4083,7 @@ fn emitCodeRelocations(
40554083 }
40564084 log.debug("Emit relocation: {}", .{relocation});
40574085 }
4058 atom = atom.next orelse break;
4086 atom = if (atom.prev) |prev| wasm.getAtomPtr(prev) else break;
40594087 }
40604088 if (count == 0) return;
40614089 var buf: [5]u8 = undefined;
......@@ -4086,7 +4114,7 @@ fn emitDataRelocations(
40864114 // for each atom, we calculate the uleb size and append that
40874115 var size_offset: u32 = 5; // account for code section size leb128
40884116 for (wasm.data_segments.values()) |segment_index| {
4089 var atom: *Atom = wasm.atoms.get(segment_index).?.getFirst();
4117 var atom: *Atom = wasm.getAtomPtr(wasm.atoms.get(segment_index).?);
40904118 while (true) {
40914119 size_offset += getULEB128Size(atom.size);
40924120 for (atom.relocs.items) |relocation| {
......@@ -4105,7 +4133,7 @@ fn emitDataRelocations(
41054133 }
41064134 log.debug("Emit relocation: {}", .{relocation});
41074135 }
4108 atom = atom.next orelse break;
4136 atom = if (atom.prev) |prev| wasm.getAtomPtr(prev) else break;
41094137 }
41104138 }
41114139 if (count == 0) return;
src/link/Wasm/Atom.zig+20-24
......@@ -29,14 +29,17 @@ file: ?u16,
2929
3030/// Next atom in relation to this atom.
3131/// When null, this atom is the last atom
32next: ?*Atom,
32next: ?Atom.Index,
3333/// Previous atom in relation to this atom.
3434/// is null when this atom is the first in its order
35prev: ?*Atom,
35prev: ?Atom.Index,
3636
3737/// Contains atoms local to a decl, all managed by this `Atom`.
3838/// When the parent atom is being freed, it will also do so for all local atoms.
39locals: std.ArrayListUnmanaged(Atom) = .{},
39locals: std.ArrayListUnmanaged(Atom.Index) = .{},
40
41/// Alias to an unsigned 32-bit integer
42pub const Index = u32;
4043
4144/// Represents a default empty wasm `Atom`
4245pub const empty: Atom = .{
......@@ -50,14 +53,12 @@ pub const empty: Atom = .{
5053};
5154
5255/// Frees all resources owned by this `Atom`.
53pub fn deinit(atom: *Atom, gpa: Allocator) void {
56pub fn deinit(atom: *Atom, wasm: *Wasm) void {
57 const gpa = wasm.base.allocator;
5458 atom.relocs.deinit(gpa);
5559 atom.code.deinit(gpa);
56
57 for (atom.locals.items) |*local| {
58 local.deinit(gpa);
59 }
6060 atom.locals.deinit(gpa);
61 atom.* = undefined;
6162}
6263
6364/// Sets the length of relocations and code to '0',
......@@ -78,24 +79,11 @@ pub fn format(atom: Atom, comptime fmt: []const u8, options: std.fmt.FormatOptio
7879 });
7980}
8081
81/// Returns the first `Atom` from a given atom
82pub fn getFirst(atom: *Atom) *Atom {
83 var tmp = atom;
84 while (tmp.prev) |prev| tmp = prev;
85 return tmp;
86}
87
8882/// Returns the location of the symbol that represents this `Atom`
8983pub fn symbolLoc(atom: Atom) Wasm.SymbolLoc {
9084 return .{ .file = atom.file, .index = atom.sym_index };
9185}
9286
93pub fn ensureInitialized(atom: *Atom, wasm_bin: *Wasm) !void {
94 if (atom.getSymbolIndex() != null) return; // already initialized
95 atom.sym_index = try wasm_bin.allocateSymbol();
96 try wasm_bin.symbol_atom.putNoClobber(wasm_bin.base.allocator, atom.symbolLoc(), atom);
97}
98
9987pub fn getSymbolIndex(atom: Atom) ?u32 {
10088 if (atom.sym_index == 0) return null;
10189 return atom.sym_index;
......@@ -198,20 +186,28 @@ fn relocationValue(atom: Atom, relocation: types.Relocation, wasm_bin: *const Wa
198186 if (symbol.isUndefined()) {
199187 return 0;
200188 }
201 const target_atom = wasm_bin.symbol_atom.get(target_loc).?;
189 const target_atom_index = wasm_bin.symbol_atom.get(target_loc) orelse {
190 // this can only occur during incremental-compilation when a relocation
191 // still points to a freed decl. It is fine to emit the value 0 here
192 // as no actual code will point towards it.
193 return 0;
194 };
195 const target_atom = wasm_bin.getAtom(target_atom_index);
202196 const va = @intCast(i32, target_atom.getVA(wasm_bin, symbol));
203197 return @intCast(u32, va + relocation.addend);
204198 },
205199 .R_WASM_EVENT_INDEX_LEB => return symbol.index,
206200 .R_WASM_SECTION_OFFSET_I32 => {
207 const target_atom = wasm_bin.symbol_atom.get(target_loc).?;
201 const target_atom_index = wasm_bin.symbol_atom.get(target_loc).?;
202 const target_atom = wasm_bin.getAtom(target_atom_index);
208203 const rel_value = @intCast(i32, target_atom.offset) + relocation.addend;
209204 return @intCast(u32, rel_value);
210205 },
211206 .R_WASM_FUNCTION_OFFSET_I32 => {
212 const target_atom = wasm_bin.symbol_atom.get(target_loc) orelse {
207 const target_atom_index = wasm_bin.symbol_atom.get(target_loc) orelse {
213208 return @bitCast(u32, @as(i32, -1));
214209 };
210 const target_atom = wasm_bin.getAtom(target_atom_index);
215211 const offset: u32 = 11 + Wasm.getULEB128Size(target_atom.size); // Header (11 bytes fixed-size) + body size (leb-encoded)
216212 const rel_value = @intCast(i32, target_atom.offset + offset) + relocation.addend;
217213 return @intCast(u32, rel_value);
src/link/Wasm/Object.zig+5-10
......@@ -901,14 +901,9 @@ pub fn parseIntoAtoms(object: *Object, gpa: Allocator, object_index: u16, wasm_b
901901 continue; // found unknown section, so skip parsing into atom as we do not know how to handle it.
902902 };
903903
904 const atom = try gpa.create(Atom);
904 const atom_index = @intCast(Atom.Index, wasm_bin.managed_atoms.items.len);
905 const atom = try wasm_bin.managed_atoms.addOne(gpa);
905906 atom.* = Atom.empty;
906 errdefer {
907 atom.deinit(gpa);
908 gpa.destroy(atom);
909 }
910
911 try wasm_bin.managed_atoms.append(gpa, atom);
912907 atom.file = object_index;
913908 atom.size = relocatable_data.size;
914909 atom.alignment = relocatable_data.getAlignment(object);
......@@ -938,12 +933,12 @@ pub fn parseIntoAtoms(object: *Object, gpa: Allocator, object_index: u16, wasm_b
938933 .index = relocatable_data.getIndex(),
939934 })) |symbols| {
940935 atom.sym_index = symbols.pop();
941 try wasm_bin.symbol_atom.putNoClobber(gpa, atom.symbolLoc(), atom);
936 try wasm_bin.symbol_atom.putNoClobber(gpa, atom.symbolLoc(), atom_index);
942937
943938 // symbols referencing the same atom will be added as alias
944939 // or as 'parent' when they are global.
945940 while (symbols.popOrNull()) |idx| {
946 try wasm_bin.symbol_atom.putNoClobber(gpa, .{ .file = atom.file, .index = idx }, atom);
941 try wasm_bin.symbol_atom.putNoClobber(gpa, .{ .file = atom.file, .index = idx }, atom_index);
947942 const alias_symbol = object.symtable[idx];
948943 if (alias_symbol.isGlobal()) {
949944 atom.sym_index = idx;
......@@ -956,7 +951,7 @@ pub fn parseIntoAtoms(object: *Object, gpa: Allocator, object_index: u16, wasm_b
956951 segment.alignment = std.math.max(segment.alignment, atom.alignment);
957952 }
958953
959 try wasm_bin.appendAtomAtIndex(final_index, atom);
954 try wasm_bin.appendAtomAtIndex(final_index, atom_index);
960955 log.debug("Parsed into atom: '{s}' at segment index {d}", .{ object.string_table.get(object.symtable[atom.sym_index].name), final_index });
961956 }
962957}
test/link/wasm/export-data/build.zig+2-2
......@@ -23,8 +23,8 @@ pub fn build(b: *Builder) void {
2323 check_lib.checkNext("type i32");
2424 check_lib.checkNext("mutable false");
2525 check_lib.checkNext("i32.const {bar_address}");
26 check_lib.checkComputeCompare("foo_address", .{ .op = .eq, .value = .{ .literal = 0 } });
27 check_lib.checkComputeCompare("bar_address", .{ .op = .eq, .value = .{ .literal = 4 } });
26 check_lib.checkComputeCompare("foo_address", .{ .op = .eq, .value = .{ .literal = 4 } });
27 check_lib.checkComputeCompare("bar_address", .{ .op = .eq, .value = .{ .literal = 0 } });
2828
2929 check_lib.checkStart("Section export");
3030 check_lib.checkNext("entries 3");